using System.Transactions;
using _0_Framework.Application;
using _0_Framework.Application.Enums;
using AccountManagement.Application.Contracts.Account;
using CompanyManagement.Infrastructure.Excel.InstitutionContract;
using CompanyManagment.App.Contracts.Employer;
using CompanyManagment.App.Contracts.InstitutionContract;
using CompanyManagment.App.Contracts.InstitutionContractContactinfo;
using CompanyManagment.App.Contracts.InstitutionPlan;
using CompanyManagment.App.Contracts.PersonalContractingParty;
using CompanyManagment.App.Contracts.Representative;
using CompanyManagment.App.Contracts.TemporaryClientRegistration;
using CompanyManagment.App.Contracts.Workshop;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
using ServiceHost.Areas.Client.Pages.Company.PaymentToEmployee;
using ServiceHost.BaseControllers;
namespace ServiceHost.Areas.Admin.Controllers;
///
/// کنترلر قرارداد های مالی موسسه
///
public class institutionContractController : AdminBaseController
{
private readonly IInstitutionContractApplication _institutionContractApplication;
private readonly IPersonalContractingPartyApp _contractingPartyApplication;
private readonly IContactInfoApplication _contactInfoApplication;
private readonly IAccountApplication _accountApplication;
private readonly IEmployerApplication _employerApplication;
private readonly IWorkshopApplication _workshopApplication;
private readonly ITemporaryClientRegistrationApplication _temporaryClientRegistration;
public institutionContractController(IInstitutionContractApplication institutionContractApplication,
IPersonalContractingPartyApp contractingPartyApplication, IContactInfoApplication contactInfoApplication,
IAccountApplication accountApplication, IEmployerApplication employerApplication,
IWorkshopApplication workshopApplication, ITemporaryClientRegistrationApplication temporaryClientRegistration)
{
_institutionContractApplication = institutionContractApplication;
_contractingPartyApplication = contractingPartyApplication;
_contactInfoApplication = contactInfoApplication;
_accountApplication = accountApplication;
_employerApplication = employerApplication;
_workshopApplication = workshopApplication;
_temporaryClientRegistration = temporaryClientRegistration;
}
///
/// لیست قرارداد های مالی
///
///
[HttpGet]
public async Task>> GetList(
InstitutionContractListSearchModel searchModel)
{
return await _institutionContractApplication.GetList(searchModel);
}
///
/// وضعیت تب ها
///
///
///
[HttpGet("stats")]
public async Task> GetListStats(
InstitutionContractListSearchModel searchModel)
{
return await _institutionContractApplication.GetListStats(searchModel);
}
///
/// ویرایش
///
///
[HttpPut]
public async Task> Edit([FromBody] EditInstitutionContractRequest command)
{
var op = new OperationResult();
var phoneNumber = command.ContactInfos.FirstOrDefault(x =>
x.SendSmsString == "true" && x.Position == "طرف قرارداد" && x.PhoneType == "شماره همراه");
var conractingParty = _contractingPartyApplication.GetDetails(command.ContractingPartyId);
if (conractingParty.IsLegal == "حقیقی" && string.IsNullOrWhiteSpace(conractingParty.Nationalcode))
return new JsonResult(op.Failed("کد ملی طرف حساب وجود ندارد"));
if (conractingParty.IsLegal == "حقوقی" && string.IsNullOrWhiteSpace(conractingParty.NationalId))
return new JsonResult(op.Failed("شناسه ملی طرف حساب وجود ندارد"));
if (phoneNumber == null)
return new JsonResult(op.Failed("تعیین شماره همراه با سمت طرف قرارداد اجباریست"));
//if (string.IsNullOrWhiteSpace(command.HasValueAddedTax))
// command.HasValueAddedTax = "false";
var result = await _institutionContractApplication.EditAsync(command);
var contractingPartyId = _institutionContractApplication.GetDetails(result.SendId);
var counter = command.ContactInfos.Count;
var getOldContarct = _institutionContractApplication.NewSearch(new InstitutionContractSearchModel()
{ ContractingPartyId = contractingPartyId.ContractingPartyId, IsActiveString = "both" })
.Where(x => x.IsActiveString == "false" || x.IsActiveString == "blue").ToList();
if (result.IsSuccedded && counter > 0)
{
if (getOldContarct.Count > 0)
{
foreach (var item in getOldContarct)
{
_contactInfoApplication.RemoveContactInfo(item.Id);
foreach (var phone in command.ContactInfos)
{
if (phone.PhoneNumber != null)
{
var contactinfo = new CreateContactInfo
{
InstitutionContractId = item.Id,
PhoneType = phone.PhoneType,
Position = phone.Position,
PhoneNumber = phone.PhoneNumber,
FnameLname = phone.FnameLname,
SendSms = phone.SendSmsString == "true" ? true : false
};
_contactInfoApplication.Create(contactinfo);
}
Thread.Sleep(500);
}
}
}
_contactInfoApplication.RemoveContactInfo(command.Id);
foreach (var item in command.ContactInfos)
{
if (item.PhoneNumber != null)
{
var contactinfo = new CreateContactInfo
{
InstitutionContractId = result.SendId,
PhoneType = item.PhoneType,
Position = item.Position,
PhoneNumber = item.PhoneNumber,
FnameLname = item.FnameLname,
SendSms = item.SendSmsString == "true" ? true : false
};
_contactInfoApplication.Create(contactinfo);
}
Thread.Sleep(500);
}
//ساخت اکانت کلاینت
var userPass = conractingParty.IsLegal == "حقیقی"
? conractingParty.Nationalcode
: conractingParty.NationalId;
var checkExistAccount = _accountApplication.CheckExistClientAccount(userPass);
if (!checkExistAccount)
{
var createAcc = new RegisterAccount
{
Fullname = conractingParty.LName,
Username = userPass,
Password = userPass,
Mobile = phoneNumber.PhoneNumber,
NationalCode = userPass
};
var res = _accountApplication.RegisterClient(createAcc);
if (res.IsSuccedded)
_institutionContractApplication.CreateContractingPartyAccount(command.ContractingPartyId,
res.SendId);
}
}
//Thread.Sleep(500);
//for (int i = 0; i <= counter - 1; i++)
//{
// if (command.ContactInformationList[i].PhoneNumber != null)
// {
// var contactinfo = new CreateContactInfo()
// {
// InstitutionContractId = result.SendId,
// PhoneType = command.ContactInformationList[i].PhoneType,
// Position = command.ContactInformationList[i].Position,
// PhoneNumber = command.ContactInformationList[i].PhoneNumber,
// FnameLname = command.ContactInformationList[i].FnameLname,
// SendSms = command.ContactInformationList[i].SendSmsString == "true" ? true : false
// };
// _contactInfoApplication.Create(contactinfo);
// }
// Thread.Sleep(500);
//}
return new JsonResult(result);
}
[HttpPost("deActive/{id}")]
public ActionResult DeActive(long id, string balance)
{
var result = new OperationResult();
if (balance == "0")
{
result = _institutionContractApplication.DeActive(id);
if (result.IsSuccedded) result = _institutionContractApplication.DeActiveAllConnections(id);
}
else
{
result = _institutionContractApplication.DeActiveBlue(id);
if (result.IsSuccedded)
result = _institutionContractApplication.DeActiveAllConnections(id);
}
return result;
}
///
/// غیر فعال
///
///
///
[HttpPost("active/{id}")]
public ActionResult IsActive(long id)
{
var result = _institutionContractApplication.Active(id);
if (result.IsSuccedded)
{
result = _institutionContractApplication.ReActiveAllConnections(id);
}
return result;
}
[HttpPost("sign/{id}")]
public ActionResult Sign(long Id)
{
var result = _institutionContractApplication.Sign(Id);
if (result.IsSuccedded)
return new JsonResult(new
{
isSuccedded = true
});
return new JsonResult(new
{
isSuccedded = false
});
}
[HttpPost("unsign/{id}")]
public ActionResult UnSign(long Id)
{
var id = Convert.ToInt64(Id);
var result = _institutionContractApplication.UnSign(Id);
if (result.IsSuccedded)
return new JsonResult(new
{
isSuccedded = true
});
return new JsonResult(new
{
isSuccedded = false
});
}
///
/// بلاک طرف حساب
///
///
///
[HttpPost("block-contracting-party/{id}")]
public IActionResult OnPostBlockContractingParty(long id)
{
var result = _contractingPartyApplication.Block(id);
var afterActtion = _contractingPartyApplication.GetDetails(id);
return new JsonResult(new
{
isSuccedded = result.IsSuccedded,
isBlock = afterActtion.IsBlock,
blockTimes = afterActtion.BlockTimes
});
}
///
/// آنبلاک طرف حساب
///
///
///
[HttpPost("unblock-contracting-party/{id}")]
public IActionResult OnPostUnBlockContractingParty(long id)
{
var result = _contractingPartyApplication.DisableBlock(id);
var afterActtion = _contractingPartyApplication.GetDetails(id);
return new JsonResult(new
{
isSuccedded = result.IsSuccedded,
isBlock = afterActtion.IsBlock,
blockTimes = afterActtion.BlockTimes
});
}
[HttpGet("extension/{id}")]
public ActionResult OnGetExtension(long id)
{
var todayGr = DateTime.Now;
var todayFa = todayGr.ToFarsi();
var previusContract = _institutionContractApplication.GetDetails(id);
var previusContractEnd = previusContract.ContractEndGr.AddDays(1);
var startFa = previusContractEnd.ToFarsi();
var endFa = startFa.FindeEndOfYear();
var representativList = new List();
var contractingPartyList = new List();
var res = _institutionContractApplication.GetDetails(id);
var representative = new RepresentativeViewModel
{
Id = res.RepresentativeId,
FullName = res.RepresentativeName
};
representativList.Add(representative);
var contractingParty = new PersonalContractingPartyViewModel
{
id = res.ContractingPartyId,
FullName = _contractingPartyApplication.GetFullName(res.ContractingPartyId)
};
contractingPartyList.Add(contractingParty);
res.RepresentativeSelectList =
new SelectList(representativList, "Id", "FullName");
res.ContractingPartiesSelectList =
new SelectList(contractingPartyList, "id", "FullName");
var employer = _employerApplication.GetEmployerByContracrtingPartyID(res.ContractingPartyId);
var emplId = employer.Select(x => x.Id).ToList();
var w = _workshopApplication.GetWorkshopsByEmployerId(emplId);
var workshopIds = w.Select(x => x.Id).ToList();
var workshopCount = Convert.ToString(w.Count);
var pCount = 0;
if (workshopIds.Count > 0)
{
foreach (var workshopId in workshopIds)
{
var p = _workshopApplication.PersonnelCount(workshopId);
pCount += p;
}
res.EmployeeCount = Convert.ToString(pCount);
}
else
{
res.EmployeeCount = "0";
}
//var left = _leftWorkApplication.GetLeftPersonelByWorkshopId(workshopIds);
res.WorkshopCount = workshopCount;
res.WorkshopManualCount = workshopCount;
res.EmployeeManualCount = res.EmployeeCount;
res.ContractDateFa = todayFa;
res.ContractStartFa = startFa;
res.ContractEndFa = endFa;
res.ContractAmountString = "0";
res.DailyCompenseationString = "0";
res.ObligationString = "0";
res.TotalAmountString = "0";
res.PrviousContractId = id;
if (!string.IsNullOrWhiteSpace(res.EmployeeManualCount))
{
var countPerson = Convert.ToInt32(res.EmployeeCount);
var finalAmount = _institutionContractApplication.GetcontractAmount(countPerson);
var syear = Convert.ToInt32(startFa.Substring(0, 4));
var smonth = Convert.ToInt32(startFa.Substring(5, 2));
var sday = Convert.ToInt32(startFa.Substring(8, 2));
var eyear = Convert.ToInt32(endFa.Substring(0, 4));
var emonth = Convert.ToInt32(endFa.Substring(5, 2));
var eday = Convert.ToInt32(endFa.Substring(8, 2));
emonth += 1;
var def = (eyear - syear) * 12 + emonth - smonth;
//رند ماهیانه
//int rightMDigits = (int)(finalAmount % 1000000);
//if (rightMDigits < 500000)
//{
// finalAmount = (int)(finalAmount / 100000) * 100000;
//}
//else
//{
// finalAmount = (int)(finalAmount / 100000 + 1) * 100000;
//}
finalAmount = (int)(finalAmount / 1000000) * 1000000;
double compute = 0;
double tenPercent = 0;
if (res.HasValueAddedTax == "true")
{
tenPercent = finalAmount * 10 / 100;
res.ContractAmountOAlone = finalAmount.ToMoney();
//افزودن 10 درصد
finalAmount += tenPercent;
res.ContractAmountString = finalAmount.ToMoney();
res.ValueAddedTaxStr = tenPercent.ToMoney();
compute = finalAmount * def;
res.ObligationString = compute.ToMoney();
res.TotalAmountString = res.ObligationString;
}
else
{
res.ContractAmountOAlone = finalAmount.ToMoney();
res.ContractAmountString = res.ContractAmountOAlone;
res.ValueAddedTaxStr = "0";
compute = finalAmount * def;
res.ObligationString = compute.ToMoney();
res.TotalAmountString = res.ObligationString;
}
//رند سالانه
//int rightYDigits = (int)(compute % 10000000);
//if (rightYDigits < 5000000)
//compute = (int)(compute / 1000000) * 1000000;
}
var contactInfo = _contactInfoApplication.GetContactInfolist(id);
if (contactInfo.Count > 0)
{
res.ContactInfoCounter = contactInfo.Count;
res.ContactInformationList = contactInfo;
}
else
{
res.ContactInfoCounter = 0;
}
return res;
}
[HttpPost("extension")]
public async Task> OnPostExtension(
[FromBody] ExtenstionInstitutionContractRequest command)
{
var op = new OperationResult();
var phoneNumber = command.ContactInfos.FirstOrDefault(x =>
x.SendSmsString == "true" && x.Position == "طرف قرارداد" && x.PhoneType == "شماره همراه");
var conractingParty = _contractingPartyApplication.GetDetails(command.ContractingPartyId);
if (conractingParty.IsLegal == "حقیقی" && string.IsNullOrWhiteSpace(conractingParty.Nationalcode))
return new JsonResult(op.Failed("کد ملی طرف حساب وجود ندارد"));
if (conractingParty.IsLegal == "حقوقی" && string.IsNullOrWhiteSpace(conractingParty.NationalId))
return new JsonResult(op.Failed("شناسه ملی طرف حساب وجود ندارد"));
if (phoneNumber == null)
return new JsonResult(op.Failed("تعیین شماره همراه با سمت طرف قرارداد اجباریست"));
var counter = command.ContactInfos.Count;
var result = await _institutionContractApplication.ExtensionَAsync(command);
if (result.IsSuccedded && counter > 0)
{
for (var i = 0; i <= counter - 1; i++)
{
if (command.ContactInfos[i].PhoneNumber != null)
{
var contactinfo = new CreateContactInfo
{
InstitutionContractId = result.SendId,
PhoneType = command.ContactInfos[i].PhoneType,
Position = command.ContactInfos[i].Position,
PhoneNumber = command.ContactInfos[i].PhoneNumber,
FnameLname = command.ContactInfos[i].FnameLname,
SendSms = command.ContactInfos[i].SendSmsString == "true" ? true : false
};
_contactInfoApplication.Create(contactinfo);
}
Thread.Sleep(500);
}
}
if (result.IsSuccedded)
{
_institutionContractApplication.DeActive(command.PreviousContractId);
_institutionContractApplication.ReActiveAllAfterCreateNew(command.ContractingPartyId);
}
var contractingPartyId = _institutionContractApplication.GetDetails(result.SendId);
var getOldContarct = _institutionContractApplication.NewSearch(new InstitutionContractSearchModel()
{ ContractingPartyId = contractingPartyId.ContractingPartyId, IsActiveString = "both" })
.Where(x => x.IsActiveString == "false" || x.IsActiveString == "blue").ToList();
if (result.IsSuccedded && counter > 0)
{
if (getOldContarct.Count > 0)
{
foreach (var item in getOldContarct)
{
_contactInfoApplication.RemoveContactInfo(item.Id);
foreach (var phone in command.ContactInfos)
{
if (phone.PhoneNumber != null)
{
var contactinfo = new CreateContactInfo
{
InstitutionContractId = item.Id,
PhoneType = phone.PhoneType,
Position = phone.Position,
PhoneNumber = phone.PhoneNumber,
FnameLname = phone.FnameLname,
SendSms = phone.SendSmsString == "true" ? true : false
};
_contactInfoApplication.Create(contactinfo);
}
Thread.Sleep(500);
}
}
//ساخت اکانت کلاینت
var userPass = conractingParty.IsLegal == "حقیقی"
? conractingParty.Nationalcode
: conractingParty.NationalId;
var checkExistAccount = _accountApplication.CheckExistClientAccount(userPass);
if (!checkExistAccount)
{
var createAcc = new RegisterAccount
{
Fullname = conractingParty.LName,
Username = userPass,
Password = userPass,
Mobile = phoneNumber.PhoneNumber,
NationalCode = userPass
};
var res = _accountApplication.RegisterClient(createAcc);
if (res.IsSuccedded)
_institutionContractApplication.CreateContractingPartyAccount(command.ContractingPartyId,
res.SendId);
}
}
}
return result;
}
///
/// دانلود اکسل
///
///
[HttpGet("excel")]
public IActionResult OnGetDownloadExcel()
{
var institutionContractViewModels =
_institutionContractApplication.NewSearch(new() { IsActiveString = "both", TypeOfContract = "both" });
var bytes = InstitutionContractExcelGenerator.GenerateExcel(institutionContractViewModels);
return File(bytes,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
$"قرارداد های مالی.xlsx");
}
[HttpPost("create/inquiry")]
public async Task>> CreateInquiry(
[FromBody] CreateInquiryRequest request)
{
var res = await _temporaryClientRegistration.CreateContractingPartyTemp(request.NationalCode,
request.DateOfBirth,
request.Mobile);
return res;
}
[HttpPost("create/workshop-service-calculator")]
public ActionResult WorkshopServiceCalculator([FromBody]CreateWorkshopTemp command)
{
var workshopTemp = new WorkshopTempViewModel
{
WorkshopName = command.WorkshopName,
CountPerson = command.CountPerson,
ContractAndCheckout = command.ContractAndCheckout,
Insurance = command.Insurance,
RollCall = command.RollCall,
CustomizeCheckout = command.CustomizeCheckout,
ContractAndCheckoutInPerson = command.ContractAndCheckoutInPerson,
InsuranceInPerson = command.InsuranceInPerson
};
var response = _temporaryClientRegistration.GetInstitutionPlanForWorkshop(workshopTemp);
var result = new WorkshopServiceCalculatorResponse
{
TotalAmount = response.OnlineAndInPersonSumAmountStr
};
return result;
}
[HttpPost("create/institution-plan-calculator")]
public async Task> InstitutionPlanCalculator(
[FromBody] InstitutionPlanCalculatorRequest request)
{
var res = await _temporaryClientRegistration.GetTotalPaymentAndWorkshopList(request.TotalAmountMonth,duration: request.Duration,request.HasInPersonContract);
var result = new InstitutionPlanCalculatorResponse()
{
TotalAmountWithTax = res.OneTimeTotalPaymentStr,
OneTimeTotalAmountWithoutTax = res.OneTimeWithoutTaxPaymentStr,
TotalTax = res.ValueAddedTaxStr,
Installments = res.MonthlyInstallments,
OneTimeTotalAmount = res.OneTimeTotalPaymentStr,
MonthlyTotalAmount = res.MonthlyTotalPaymentStr,
MonthlyTotalAmountWithoutTax = res.MonthlyWithoutTaxPaymentStr,
ContractStart = res.ContractStartFa,
ContractEnd = res.ContractEndFa,
Discount = res.Discount,
ValueAddedTax = res.ValueAddedTaxStr,
DailyCompensation = "0",
Obligation = res.OneTimeTotalPaymentStr,
PaymentForOneMonth = res.SumOfWorkshopsPayment,
DiscountedAmountForOneMonth = res.DiscountedAmountForOneMonth
};
return res;
}
///
/// ایجاد
///
///
///
[HttpPost]
public async Task> Create([FromBody]CreateInstitutionContractRequest command)
{
var res =await _institutionContractApplication.CreateAsync(command);
return res;
}
///
/// ارسال لینک تایید قوانین و مقررات به طرف حساب
///
///
///
[HttpPost("create/send-link/{contractingPartyTempId}")]
public async Task> SendAgreementLink(long contractingPartyTempId)
{
return await _temporaryClientRegistration.SendAgreementLink(contractingPartyTempId);
}
[HttpPost("create/verify-code")]
public async Task> CheckVerifyCode(VerifyCodeRequest request)
{
using var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
var operationResult =
await _temporaryClientRegistration.CheckVerifyCodeIsTrue(request.ContractingPartyId, request.verifyCode);
if (!operationResult.IsSuccedded)
return operationResult;
operationResult = await _temporaryClientRegistration.PayOffCompleted(request.ContractingPartyId);
if (operationResult.IsSuccedded)
transaction.Complete();
return operationResult;
}
}
public class InstitutionPlanCalculatorResponse
{
public string TotalAmountWithTax { get; set; }
public string OneTimeTotalAmountWithoutTax { get; set; }
public string OneTimeTotalAmount { get; set; }
public string TotalTax { get; set; }
public string MonthlyTotalAmount { get; set; }
public string MonthlyTotalAmountWithoutTax { get; set; }
public string ContractStart { get; set; }
public string ContractEnd { get; set; }
public string ValueAddedTax { get; set; }
public string DailyCompensation { get; set; }
public string Obligation { get; set; }
public string PaymentForOneMonth { get; set; }
public string DiscountedAmountForOneMonth { get; set; }
public string Discount { get; set; }
public List Installments { get; set; }
}
public class WorkshopServiceCalculatorResponse
{
public string TotalAmount { get; set; }
}
public record InstitutionPlanCalculatorRequest(double TotalAmountMonth,bool HasInPersonContract,
InstitutionContractDuration Duration = InstitutionContractDuration.TwelveMonths);
public class CreateInquiryRequest
{
public string NationalCode { get; set; }
public string DateOfBirth { get; set; }
public string Mobile { get; set; }
}
public class VerifyCodeRequest
{
public long ContractingPartyId { get; set; }
public string verifyCode { get; set; }
}