1877 lines
81 KiB
C#
1877 lines
81 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.Diagnostics;
|
||
using System.Linq;
|
||
using System.Net.Http;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
using _0_Framework.Application;
|
||
using _0_Framework.Application.Enums;
|
||
using _0_Framework.Application.PaymentGateway;
|
||
using _0_Framework.Application.Sms;
|
||
using _0_Framework.Application.UID;
|
||
using _0_Framework.Exceptions;
|
||
using AccountManagement.Application.Contracts.Account;
|
||
using Company.Domain.ContarctingPartyAgg;
|
||
using Company.Domain.EmployeeAgg;
|
||
using Company.Domain.empolyerAgg;
|
||
using Company.Domain.FinancialInvoiceAgg;
|
||
using Company.Domain.FinancialStatmentAgg;
|
||
using Company.Domain.FinancialTransactionAgg;
|
||
using Company.Domain.InstitutionContractAgg;
|
||
using Company.Domain.LeftWorkAgg;
|
||
using Company.Domain.PaymentTransactionAgg;
|
||
using Company.Domain.RepresentativeAgg;
|
||
using Company.Domain.RollCallServiceAgg;
|
||
using Company.Domain.TemporaryClientRegistrationAgg;
|
||
using Company.Domain.WorkshopAgg;
|
||
using CompanyManagment.App.Contracts.FinancialInvoice;
|
||
using CompanyManagment.App.Contracts.FinancialStatment;
|
||
using CompanyManagment.App.Contracts.InstitutionContract;
|
||
using CompanyManagment.App.Contracts.InstitutionContractContactinfo;
|
||
using CompanyManagment.App.Contracts.PaymentTransaction;
|
||
using CompanyManagment.App.Contracts.PersonalContractingParty;
|
||
using CompanyManagment.App.Contracts.Workshop;
|
||
using CompanyManagment.EFCore.Migrations;
|
||
using Microsoft.AspNetCore.Mvc;
|
||
using OfficeOpenXml.Packaging.Ionic.Zip;
|
||
using PersianTools.Core;
|
||
using ConnectedPersonnelViewModel = CompanyManagment.App.Contracts.Workshop.ConnectedPersonnelViewModel;
|
||
using FinancialStatment = Company.Domain.FinancialStatmentAgg.FinancialStatment;
|
||
|
||
namespace CompanyManagment.Application;
|
||
|
||
public class InstitutionContractApplication : IInstitutionContractApplication
|
||
{
|
||
private readonly IInstitutionContractRepository _institutionContractRepository;
|
||
private readonly IPersonalContractingPartyRepository _contractingPartyRepository;
|
||
private readonly IRepresentativeRepository _representativeRepository;
|
||
private readonly IFinancialStatmentApplication _financialStatmentApplication;
|
||
private readonly IEmployerRepository _employerRepository;
|
||
private readonly IWorkshopRepository _workshopRepository;
|
||
private readonly ILeftWorkRepository _leftWorkRepository;
|
||
private readonly IWorkshopApplication _workshopApplication;
|
||
private readonly IContractingPartyTempRepository _contractingPartyTempRepository;
|
||
private readonly IFinancialStatmentRepository _financialStatmentRepository;
|
||
private readonly IContactInfoApplication _contactInfoApplication;
|
||
private readonly IAccountApplication _accountApplication;
|
||
private readonly ISmsService _smsService;
|
||
private readonly IUidService _uidService;
|
||
private readonly IFinancialInvoiceRepository _financialInvoiceRepository;
|
||
private readonly IPaymentGateway _paymentGateway;
|
||
private readonly IPaymentTransactionRepository _paymentTransactionRepository;
|
||
private readonly IRollCallServiceRepository _rollCallServiceRepository;
|
||
|
||
|
||
public InstitutionContractApplication(IInstitutionContractRepository institutionContractRepository,
|
||
IPersonalContractingPartyRepository contractingPartyRepository,
|
||
IRepresentativeRepository representativeRepository, IEmployerRepository employerRepository,
|
||
IWorkshopRepository workshopRepository, ILeftWorkRepository leftWorkRepository,
|
||
IFinancialStatmentApplication financialStatmentApplication, IWorkshopApplication workshopApplication,
|
||
IContractingPartyTempRepository contractingPartyTempRepository,
|
||
IFinancialStatmentRepository financialStatmentRepository, IContactInfoApplication contactInfoApplication,
|
||
IAccountApplication accountApplication, ISmsService smsService, IUidService uidService,
|
||
IFinancialInvoiceRepository financialInvoiceRepository, IHttpClientFactory httpClientFactory,
|
||
IPaymentTransactionRepository paymentTransactionRepository, IRollCallServiceRepository rollCallServiceRepository)
|
||
{
|
||
_institutionContractRepository = institutionContractRepository;
|
||
_contractingPartyRepository = contractingPartyRepository;
|
||
_representativeRepository = representativeRepository;
|
||
_employerRepository = employerRepository;
|
||
_workshopRepository = workshopRepository;
|
||
_leftWorkRepository = leftWorkRepository;
|
||
_financialStatmentApplication = financialStatmentApplication;
|
||
_workshopApplication = workshopApplication;
|
||
_contractingPartyTempRepository = contractingPartyTempRepository;
|
||
_financialStatmentRepository = financialStatmentRepository;
|
||
_contactInfoApplication = contactInfoApplication;
|
||
_accountApplication = accountApplication;
|
||
_smsService = smsService;
|
||
_uidService = uidService;
|
||
_financialInvoiceRepository = financialInvoiceRepository;
|
||
_paymentTransactionRepository = paymentTransactionRepository;
|
||
_rollCallServiceRepository = rollCallServiceRepository;
|
||
_paymentGateway = new SepehrPaymentGateway(httpClientFactory);
|
||
}
|
||
|
||
public OperationResult Create(CreateInstitutionContract command)
|
||
{
|
||
string contractingPartyName = String.Empty;
|
||
bool dateMessages = false;
|
||
string dateMaessageResult = String.Empty;
|
||
var opration = new OperationResult();
|
||
if (_institutionContractRepository.Exists(x =>
|
||
x.ContractingPartyId == command.ContractingPartyId && x.RepresentativeId == command.RepresentativeId &&
|
||
x.TypeOfContract == command.TypeOfContract))
|
||
return opration.Failed(
|
||
"برای این معرف و طرف حساب قبلا قرارداد ایجاد شده است، شما میتوانید از تمدید استفاده کنید");
|
||
|
||
if (string.IsNullOrWhiteSpace(command.ContractDateFa))
|
||
{
|
||
dateMaessageResult = "تاریخ قراراداد اجباری است. ";
|
||
dateMessages = true;
|
||
}
|
||
|
||
if (string.IsNullOrWhiteSpace(command.ContractStartFa))
|
||
{
|
||
dateMaessageResult += "تاریخ شروع قراراداد اجباری است. ";
|
||
dateMessages = true;
|
||
}
|
||
|
||
if (string.IsNullOrWhiteSpace(command.ContractEndFa))
|
||
{
|
||
dateMaessageResult += "تاریخ پایان قراراداد اجباری است. ";
|
||
dateMessages = true;
|
||
}
|
||
|
||
if (dateMessages)
|
||
return opration.Failed(dateMaessageResult);
|
||
|
||
if (command.RepresentativeId < 1 && command.ContractingPartyId > 1)
|
||
{
|
||
return opration.Failed("معرف را انتخاب کنید");
|
||
}
|
||
else if (command.ContractingPartyId < 1 && command.RepresentativeId > 1)
|
||
{
|
||
return opration.Failed("طرف حساب را انتخاب کنید");
|
||
}
|
||
else if (command.ContractingPartyId < 1 && command.RepresentativeId < 1)
|
||
{
|
||
return opration.Failed("معرف و طرف حساب را انتخاب کنید");
|
||
}
|
||
|
||
var syear = command.ContractStartFa.Substring(0, 4);
|
||
var smonth = command.ContractStartFa.Substring(5, 2);
|
||
var sday = command.ContractStartFa.Substring(8, 2);
|
||
var contractingParty = _contractingPartyRepository.GetDetails(command.ContractingPartyId);
|
||
//شماره قرارداد
|
||
var contractNo = $"{syear}{smonth}{sday}/{contractingParty.ArchiveCode}/0";
|
||
|
||
///////////////////////
|
||
if (command.ContactInformationList.Count == 0)
|
||
return opration.Failed("ورود شماره تماس برای ارسال پیامک الزامیست");
|
||
var accountContact = command.ContactInformationList.Where(x =>
|
||
x.SendSmsString == "true" && x.Position == "طرف قرارداد" && x.PhoneType == "شماره همراه" &&
|
||
!string.IsNullOrWhiteSpace(x.PhoneNumber)).ToList();
|
||
if (accountContact.Count == 0)
|
||
return opration.Failed("ورود شماره همراه با سمت طرف قرارداد برای ساخت حساب کاربری الزامیست");
|
||
var accountContactCount = command.ContactInformationList
|
||
.Where(x => x.PhoneType == "شماره همراه" && x.Position == "طرف قرارداد").ToList();
|
||
if (accountContactCount.Count > 1)
|
||
return opration.Failed("فقط یکی از شماره تلفن ها میتواند سمت طرف قرارداد داشته باشد");
|
||
|
||
contractingPartyName = contractingParty.LName;
|
||
//نام معرف
|
||
var representative = _representativeRepository.GetDetails(command.RepresentativeId).FullName;
|
||
|
||
var contractStartGr = command.ContractStartFa.ToGeorgianDateTime();
|
||
var contractEndGr = command.ContractEndFa.ToGeorgianDateTime();
|
||
|
||
var contractDateGr = command.ContractDateFa.ToGeorgianDateTime();
|
||
|
||
if (command.Address != null && command.State == null)
|
||
{
|
||
return opration.Failed("لطفا استان و شهر را انتخاب کنید");
|
||
}
|
||
|
||
if ((command.Address != null && command.State != null) && command.City == "شهرستان")
|
||
{
|
||
return opration.Failed("لطفا شهر را انتخاب کنید");
|
||
}
|
||
|
||
if (command.Address == null && command.State != null)
|
||
{
|
||
return opration.Failed("لطفا آدرس را وارد کنید");
|
||
}
|
||
|
||
if (string.IsNullOrWhiteSpace(command.OfficialCompany))
|
||
return opration.Failed("رسمی یا غیر رسمی بودن پرداخت را مشخص کنید");
|
||
if (command.OfficialCompany == "Official" && string.IsNullOrWhiteSpace(command.HasValueAddedTax))
|
||
return opration.Failed("وضعیت ارزش افزوده را مشخص کنید");
|
||
if (string.IsNullOrWhiteSpace(command.TypeOfContract))
|
||
return opration.Failed("عنوان قرارداد را انتخاب کنید");
|
||
|
||
if (string.IsNullOrWhiteSpace(command.ContractAmountString))
|
||
command.ContractAmountString = "0";
|
||
if (string.IsNullOrWhiteSpace(command.DailyCompenseationString))
|
||
command.DailyCompenseationString = "0";
|
||
if (string.IsNullOrWhiteSpace(command.ObligationString))
|
||
command.ObligationString = "0";
|
||
if (string.IsNullOrWhiteSpace(command.TotalAmountString))
|
||
command.TotalAmountString = "0";
|
||
command.ValueAddedTax = string.IsNullOrWhiteSpace(command.ValueAddedTaxStr)
|
||
? 0
|
||
: command.ValueAddedTaxStr.MoneyToDouble();
|
||
var contractAmount = command.ContractAmountString.ToDoubleMoney();
|
||
command.ContractAmount = Convert.ToDouble(contractAmount);
|
||
var DailyCompenseation = command.DailyCompenseationString.ToDoubleMoney();
|
||
command.DailyCompenseation = Convert.ToDouble(DailyCompenseation);
|
||
var Obligation = command.ObligationString.ToDoubleMoney();
|
||
command.Obligation = Convert.ToDouble(Obligation);
|
||
var TotalAmount = command.TotalAmountString.ToDoubleMoney();
|
||
command.TotalAmount = Convert.ToDouble(TotalAmount);
|
||
//var hasValueAddedTax = "false";
|
||
//double valueAddedTax = 0;
|
||
//if (command.HasValueAddedTax == "true")
|
||
//{
|
||
// hasValueAddedTax = "true";
|
||
// valueAddedTax = command.ContractAmount * 0.1;
|
||
// command.ContractAmount += valueAddedTax;
|
||
//}
|
||
|
||
var createContract = new InstitutionContract(contractNo, command.RepresentativeId, representative,
|
||
command.ContractingPartyId,
|
||
contractingPartyName, contractDateGr, command.ContractDateFa, command.State, command.City,
|
||
command.Address, contractStartGr,
|
||
command.ContractStartFa, contractEndGr, command.ContractEndFa, command.ContractAmount,
|
||
command.DailyCompenseation, command.Obligation,
|
||
command.TotalAmount, 0, command.WorkshopManualCount, command.EmployeeManualCount, command.Description,
|
||
command.OfficialCompany, command.TypeOfContract, command.HasValueAddedTax, command.ValueAddedTax, [], command.LawId,0,0);
|
||
|
||
_institutionContractRepository.Create(createContract);
|
||
_institutionContractRepository.SaveChanges();
|
||
return opration.Succcedded(createContract.id);
|
||
}
|
||
|
||
public OperationResult Extension(CreateInstitutionContract command)
|
||
{
|
||
bool dateMessages = false;
|
||
string dateMaessageResult = String.Empty;
|
||
var opration = new OperationResult();
|
||
|
||
command.ExtensionNo += 1;
|
||
if (_institutionContractRepository.Exists(x =>
|
||
x.ExtensionNo == command.ExtensionNo && x.ContractingPartyId == command.ContractingPartyId &&
|
||
x.TypeOfContract == command.TypeOfContract))
|
||
return opration.Failed("برای این قرارداد قبلا تمدید ایجاد شده است");
|
||
|
||
|
||
if (string.IsNullOrWhiteSpace(command.ContractDateFa))
|
||
{
|
||
dateMaessageResult = "تاریخ قراراداد اجباری است. ";
|
||
dateMessages = true;
|
||
}
|
||
|
||
if (string.IsNullOrWhiteSpace(command.ContractStartFa))
|
||
{
|
||
dateMaessageResult += "تاریخ شروع قراراداد اجباری است. ";
|
||
dateMessages = true;
|
||
}
|
||
|
||
if (string.IsNullOrWhiteSpace(command.ContractEndFa))
|
||
{
|
||
dateMaessageResult += "تاریخ پایان قراراداد اجباری است. ";
|
||
dateMessages = true;
|
||
}
|
||
|
||
if (dateMessages)
|
||
return opration.Failed(dateMaessageResult);
|
||
|
||
var firstContract =
|
||
_institutionContractRepository.GetFirstContract(command.ContractingPartyId, command.TypeOfContract);
|
||
|
||
var syear = firstContract.ContractStartFa.Substring(0, 4);
|
||
var smonth = firstContract.ContractStartFa.Substring(5, 2);
|
||
var sday = firstContract.ContractStartFa.Substring(8, 2);
|
||
var contractingParty = _contractingPartyRepository.GetDetails(command.ContractingPartyId);
|
||
//شماره قرارداد
|
||
var contractNo = $"{syear}{smonth}{sday}/{contractingParty.ArchiveCode}/{command.ExtensionNo}";
|
||
|
||
|
||
var contractStartGr = command.ContractStartFa.ToGeorgianDateTime();
|
||
var contractEndGr = command.ContractEndFa.ToGeorgianDateTime();
|
||
|
||
var contractDateGr = command.ContractDateFa.ToGeorgianDateTime();
|
||
if (_institutionContractRepository.Exists(x =>
|
||
((contractStartGr >= x.ContractStartGr && contractStartGr <= x.ContractEndGr) ||
|
||
(contractEndGr >= x.ContractStartGr && contractEndGr <= x.ContractEndGr)) &&
|
||
x.TypeOfContract == command.TypeOfContract && x.ContractingPartyId == command.ContractingPartyId))
|
||
return opration.Failed("تاریخ شروع و پایان وارد شده با قرارداد دیگری تداخل دارد");
|
||
if (command.Address != null && command.State == null)
|
||
{
|
||
return opration.Failed("لطفا استان و شهر را انتخاب کنید");
|
||
}
|
||
|
||
if ((command.Address != null && command.State != null) && command.City == "شهرستان")
|
||
{
|
||
return opration.Failed("لطفا شهر را انتخاب کنید");
|
||
}
|
||
|
||
if (command.Address == null && command.State != null)
|
||
{
|
||
return opration.Failed("لطفا آدرس را وارد کنید");
|
||
}
|
||
|
||
if (string.IsNullOrWhiteSpace(command.OfficialCompany))
|
||
return opration.Failed("رسمی یا غیر رسمی بودن پرداخت را مشخص کنید");
|
||
if (command.OfficialCompany == "Official" && string.IsNullOrWhiteSpace(command.HasValueAddedTax))
|
||
return opration.Failed("وضعیت ارزش افزوده را مشخص کنید");
|
||
if (string.IsNullOrWhiteSpace(command.TypeOfContract))
|
||
return opration.Failed("عنوان قرارداد را انتخاب کنید");
|
||
if (string.IsNullOrWhiteSpace(command.ContractAmountString))
|
||
command.ContractAmountString = "0";
|
||
if (string.IsNullOrWhiteSpace(command.DailyCompenseationString))
|
||
command.DailyCompenseationString = "0";
|
||
if (string.IsNullOrWhiteSpace(command.ObligationString))
|
||
command.ObligationString = "0";
|
||
if (string.IsNullOrWhiteSpace(command.TotalAmountString))
|
||
command.TotalAmountString = "0";
|
||
command.ValueAddedTax = string.IsNullOrWhiteSpace(command.ValueAddedTaxStr)
|
||
? 0
|
||
: command.ValueAddedTaxStr.MoneyToDouble();
|
||
var contractAmount = command.ContractAmountString.ToDoubleMoney();
|
||
command.ContractAmount = Convert.ToDouble(contractAmount);
|
||
var DailyCompenseation = command.DailyCompenseationString.ToDoubleMoney();
|
||
command.DailyCompenseation = Convert.ToDouble(DailyCompenseation);
|
||
var Obligation = command.ObligationString.ToDoubleMoney();
|
||
command.Obligation = Convert.ToDouble(Obligation);
|
||
var TotalAmount = command.TotalAmountString.ToDoubleMoney();
|
||
command.TotalAmount = Convert.ToDouble(TotalAmount);
|
||
var createContract = new InstitutionContract(contractNo, command.RepresentativeId, command.RepresentativeName,
|
||
command.ContractingPartyId,
|
||
command.ContractingPartyName, contractDateGr, command.ContractDateFa, command.State, command.City,
|
||
command.Address, contractStartGr,
|
||
command.ContractStartFa, contractEndGr, command.ContractEndFa, command.ContractAmount,
|
||
command.DailyCompenseation, command.Obligation,
|
||
command.TotalAmount, command.ExtensionNo, command.WorkshopManualCount, command.EmployeeManualCount,
|
||
command.Description, command.OfficialCompany, command.TypeOfContract, command.HasValueAddedTax,
|
||
command.ValueAddedTax, [], command.LawId,0,0);
|
||
|
||
_institutionContractRepository.Create(createContract);
|
||
_institutionContractRepository.SaveChanges();
|
||
|
||
|
||
return opration.Succcedded(createContract.id);
|
||
}
|
||
|
||
public OperationResult Edit(EditInstitutionContract command)
|
||
{
|
||
bool dateMessages = false;
|
||
string dateMaessageResult = String.Empty;
|
||
var opration = new OperationResult();
|
||
var ContractEdit = _institutionContractRepository.Get(command.Id);
|
||
if (ContractEdit == null)
|
||
opration.Failed("رکورد مورد نظر وجود ندارد");
|
||
|
||
var contractStartGr = command.ContractStartFa.ToGeorgianDateTime();
|
||
var contractEndGr = command.ContractEndFa.ToGeorgianDateTime();
|
||
|
||
var contractDateGr = command.ContractDateFa.ToGeorgianDateTime();
|
||
|
||
if (_institutionContractRepository.Exists(x =>
|
||
x.ContractingPartyId == ContractEdit.ContractingPartyId &&
|
||
((contractStartGr >= x.ContractStartGr && contractStartGr <= x.ContractEndGr) ||
|
||
(contractEndGr >= x.ContractStartGr && contractEndGr <= x.ContractEndGr)) && x.id != command.Id &&
|
||
x.TypeOfContract == command.TypeOfContract))
|
||
return opration.Failed("در بازه تاریخ وارد شده قرارداد دیگری وجود دارد");
|
||
//if (_institutionContractRepository.Exists(x =>
|
||
// x.ContractingPartyId == ContractEdit.ContractingPartyId && (x.ContractStartGr <= contractDateGr || x.ContractDateGr <= contractDateGr) && x.id != command.Id))
|
||
// return opration.Failed("تاریخ عقد قرارداد با قرارداد دیگری تداخل دارد");
|
||
if (string.IsNullOrWhiteSpace(command.ContractDateFa))
|
||
{
|
||
dateMaessageResult = "تاریخ قراراداد اجباری است. ";
|
||
dateMessages = true;
|
||
}
|
||
|
||
if (string.IsNullOrWhiteSpace(command.ContractStartFa))
|
||
{
|
||
dateMaessageResult += "تاریخ شروع قراراداد اجباری است. ";
|
||
dateMessages = true;
|
||
}
|
||
|
||
if (string.IsNullOrWhiteSpace(command.ContractEndFa))
|
||
{
|
||
dateMaessageResult += "تاریخ پایان قراراداد اجباری است. ";
|
||
dateMessages = true;
|
||
}
|
||
|
||
if (dateMessages)
|
||
return opration.Failed(dateMaessageResult);
|
||
if (command.Address != null && command.State == null)
|
||
{
|
||
return opration.Failed("لطفا استان و شهر را انتخاب کنید");
|
||
}
|
||
|
||
if ((command.Address != null && command.State != null) && command.City == "شهرستان")
|
||
{
|
||
return opration.Failed("لطفا شهر را انتخاب کنید");
|
||
}
|
||
|
||
if (command.Address == null && command.State != null)
|
||
{
|
||
return opration.Failed("لطفا آدرس را وارد کنید");
|
||
}
|
||
|
||
if (string.IsNullOrWhiteSpace(command.OfficialCompany))
|
||
return opration.Failed("رسمی یا غیر رسمی بودن پرداخت را مشخص کنید");
|
||
if (command.OfficialCompany == "Official" && string.IsNullOrWhiteSpace(command.HasValueAddedTax))
|
||
return opration.Failed("وضعیت ارزش افزوده را مشخص کنید");
|
||
if (string.IsNullOrWhiteSpace(command.TypeOfContract))
|
||
return opration.Failed("عنوان قرارداد را انتخاب کنید");
|
||
|
||
if (string.IsNullOrWhiteSpace(command.ContractAmountString))
|
||
command.ContractAmountString = "0";
|
||
if (string.IsNullOrWhiteSpace(command.DailyCompenseationString))
|
||
command.DailyCompenseationString = "0";
|
||
if (string.IsNullOrWhiteSpace(command.ObligationString))
|
||
command.ObligationString = "0";
|
||
if (string.IsNullOrWhiteSpace(command.TotalAmountString))
|
||
command.TotalAmountString = "0";
|
||
|
||
command.ValueAddedTax = command.ValueAddedTaxStr.MoneyToDouble();
|
||
var contractAmount = command.ContractAmountString.ToDoubleMoney();
|
||
command.ContractAmount = Convert.ToDouble(contractAmount);
|
||
var DailyCompenseation = command.DailyCompenseationString.ToDoubleMoney();
|
||
command.DailyCompenseation = Convert.ToDouble(DailyCompenseation);
|
||
var Obligation = command.ObligationString.ToDoubleMoney();
|
||
command.Obligation = Convert.ToDouble(Obligation);
|
||
var TotalAmount = command.TotalAmountString.ToDoubleMoney();
|
||
command.TotalAmount = Convert.ToDouble(TotalAmount);
|
||
|
||
ContractEdit.Edit(contractDateGr, command.ContractDateFa, command.State, command.City, command.Address,
|
||
contractStartGr,
|
||
command.ContractStartFa, contractEndGr, command.ContractEndFa, command.ContractAmount,
|
||
command.DailyCompenseation,
|
||
command.Obligation, command.TotalAmount, command.WorkshopManualCount, command.EmployeeManualCount,
|
||
command.Description, command.OfficialCompany, command.TypeOfContract, command.ValueAddedTax,
|
||
command.HasValueAddedTax);
|
||
_institutionContractRepository.SaveChanges();
|
||
return opration.Succcedded(command.Id);
|
||
}
|
||
|
||
public EditInstitutionContract GetDetails(long id)
|
||
{
|
||
return _institutionContractRepository.GetDetails(id);
|
||
}
|
||
|
||
public List<InstitutionContractViewModel> Search(InstitutionContractSearchModel searchModel)
|
||
{
|
||
var query = _institutionContractRepository.Search(searchModel);
|
||
var join = new List<InstitutionContractViewModel>();
|
||
|
||
var now = DateTime.Now;
|
||
var nowFa = now.ToFarsi();
|
||
|
||
var endFa = nowFa.FindeEndOfMonth();
|
||
var endThisMontGr = endFa.ToGeorgianDateTime();
|
||
//var watch = System.Diagnostics.Stopwatch.StartNew();
|
||
|
||
|
||
var newResult = query.Select(x => new InstitutionContractViewModel
|
||
{
|
||
Id = x.Id,
|
||
ContractNo = x.ContractNo,
|
||
ContractStartGr = x.ContractStartGr,
|
||
ContractStartFa = x.ContractStartFa,
|
||
ContractEndGr = x.ContractEndGr,
|
||
ContractEndFa = x.ContractEndFa,
|
||
//RepresentativeId = x.RepresentativeId,
|
||
RepresentativeName = x.RepresentativeName,
|
||
//ContractingPartyName = _contractingPartyRepository.GetDetails(x.ContractingPartyId).LName,
|
||
//IsContractingPartyBlock = _contractingPartyRepository.GetDetails(x.ContractingPartyId).IsBlock,
|
||
//BlockTimes = _contractingPartyRepository.GetDetails(x.ContractingPartyId).BlockTimes,
|
||
ContractingPartyId = x.ContractingPartyId,
|
||
EmployerViewModels = _employerRepository.GetEmployerByContracrtingPartyID(x.ContractingPartyId),
|
||
EmployerNo = _employerRepository.GetEmployerByContracrtingPartyID(x.ContractingPartyId)
|
||
.FirstOrDefault(xn => xn.ContractingPartyID == x.ContractingPartyId)?.EmployerNo,
|
||
EmployerName = _employerRepository.GetEmployerByContracrtingPartyID(x.ContractingPartyId)
|
||
.FirstOrDefault(xn => xn.ContractingPartyID == x.ContractingPartyId)?.FullName,
|
||
//EmployerId = _employerRepository.GetEmployerByContracrtingPartyID(x.ContractingPartyId).FirstOrDefault(xn => xn.ContractingPartyID == x.ContractingPartyId)?.Id == null ? 0 :
|
||
// _employerRepository.GetEmployerByContracrtingPartyID(x.ContractingPartyId).FirstOrDefault(xn => xn.ContractingPartyID == x.ContractingPartyId)!.Id,
|
||
ContractAmount = x.ContractAmount,
|
||
TotalAmount = x.TotalAmount,
|
||
SearchAmount = x.SearchAmount,
|
||
IsActiveString = x.IsActiveString,
|
||
OfficialCompany = x.OfficialCompany,
|
||
Signature = x.Signature,
|
||
ExpireColor = ExpCheckColor(now, x.ContractEndGr, endThisMontGr, x.ContractAmount, x.IsActiveString),
|
||
BalanceDouble = TotalBalance(x.ContractingPartyId).TotalBalanceDbl,
|
||
BalanceStr = TotalBalance(x.ContractingPartyId).TotalBalanceStr,
|
||
//WorkshopViewModels = WorkShopDetailsAndEmployeeCount(x.ContractingPartyId).WorkshopViewModels,
|
||
//WorkshopCount = WorkShopDetailsAndEmployeeCount(x.ContractingPartyId).WorkshopCount,
|
||
//EmployeeCount = WorkShopDetailsAndEmployeeCount(x.ContractingPartyId).EmployeeCount,
|
||
//ArchiveCode = WorkShopDetailsAndEmployeeCount(x.ContractingPartyId).ArchiveCode,
|
||
TypeOfContract = x.TypeOfContract
|
||
}).ToList();
|
||
//Console.WriteLine("efTime : " + watch.Elapsed);
|
||
|
||
//var watchw = System.Diagnostics.Stopwatch.StartNew();
|
||
foreach (var item in newResult)
|
||
{
|
||
//string totalBalanceStr = "0";
|
||
//double totalBalance = 0;
|
||
//var firstGetStatement = _financialStatmentApplication.GetDetailsByContractingPartyId(item.ContractingPartyId);
|
||
//var allTransactions = firstGetStatement.FinancialTransactionViewModels;
|
||
//if (allTransactions != null)
|
||
//{
|
||
// allTransactions = allTransactions.OrderBy(x => x.TdateGr).ToList();
|
||
// var debt = allTransactions.Sum(x => x.Deptor);
|
||
// var credit = allTransactions.Sum(x => x.Creditor);
|
||
// totalBalance = debt - credit;
|
||
// totalBalanceStr = totalBalance.ToMoney();
|
||
//}
|
||
var contractingParty = _contractingPartyRepository.GetDetails(item.ContractingPartyId);
|
||
if (contractingParty != null)
|
||
{
|
||
item.ContractingPartyName = contractingParty.LName;
|
||
item.IsContractingPartyBlock = contractingParty.IsBlock;
|
||
item.BlockTimes = contractingParty.BlockTimes;
|
||
}
|
||
|
||
|
||
var employer = _employerRepository.GetEmployerByContracrtingPartyID(item.ContractingPartyId);
|
||
item.EmployerViewModels = employer;
|
||
item.EmployerName = employer.FirstOrDefault(x => x.ContractingPartyID == item.ContractingPartyId)?.FullName;
|
||
var id = employer.FirstOrDefault(x => x.ContractingPartyID == item.ContractingPartyId)?.Id;
|
||
item.EmployerNo = employer.FirstOrDefault(x => x.ContractingPartyID == item.ContractingPartyId)?.EmployerNo;
|
||
if (id != null) item.EmployerId = (long)id;
|
||
|
||
var emplId = item.EmployerViewModels.Select(x => x.Id).ToList();
|
||
|
||
item.WorkshopViewModels = _workshopRepository.GetWorkshopsByEmployerId(emplId);
|
||
var workshopIds = item.WorkshopViewModels.Select(x => x.Id).ToList();
|
||
var left = 0;
|
||
item.WorkshopCount = Convert.ToString(item.WorkshopViewModels.Count);
|
||
//var joinPersonelList = new List<ConnectedPersonnelViewModel>();
|
||
int pCount = 0;
|
||
foreach (var workshopId in workshopIds)
|
||
{
|
||
//var reslt = _workshopApplication.GetConnectedPersonnels(workshopId);
|
||
//var noBlock = reslt.Where(x => x.Black == false).ToList();
|
||
//joinPersonelList.AddRange(noBlock);
|
||
var p = _workshopApplication.PersonnelCount(workshopId);
|
||
pCount += p;
|
||
}
|
||
//var joinlistWithoutDuplicat = joinPersonelList.GroupBy(x => x.PersonName).Select(x => x.First()).ToList();
|
||
//left = joinlistWithoutDuplicat.Count();
|
||
// var left= _leftWorkRepository.GetLeftPersonelByWorkshopId(workshopIds).Count();
|
||
|
||
item.EmployeeCount = Convert.ToString(pCount);
|
||
//if (item.ContractEndGr < now)
|
||
// item.ExpireColor = "black";
|
||
//if (item.ContractEndGr >= now && item.ContractEndGr <= endThisMontGr)
|
||
// item.ExpireColor = "red";
|
||
//if (item.ContractAmount == "0")
|
||
// item.ExpireColor = "purple";
|
||
int archiveCode = 0;
|
||
if (item.WorkshopViewModels.Count > 0)
|
||
{
|
||
var workshop = item.WorkshopViewModels.OrderBy(x => x.Id)?.ToList();
|
||
|
||
var arc = workshop.Select(x => new ArchiveCodConvertoint
|
||
{
|
||
ArchiveCodeInt = x.ArchiveCode.Substring(0, 1) == "b" ? 10000000 : x.ArchiveCode.ConvertToInt(),
|
||
}).OrderBy(x => x.ArchiveCodeInt).ToList();
|
||
var minArchiveCode = arc.Min(x => x.ArchiveCodeInt);
|
||
archiveCode = minArchiveCode == 10000000 ? 0 : minArchiveCode;
|
||
}
|
||
|
||
var result = new InstitutionContractViewModel()
|
||
{
|
||
Id = item.Id,
|
||
ContractNo = item.ContractNo,
|
||
ContractStartGr = item.ContractStartGr,
|
||
ContractStartFa = item.ContractStartFa,
|
||
ContractEndGr = item.ContractEndGr,
|
||
ContractEndFa = item.ContractEndFa,
|
||
RepresentativeName = item.RepresentativeName,
|
||
ContractingPartyName = item.ContractingPartyName,
|
||
ContractingPartyId = item.ContractingPartyId,
|
||
EmployerNo = item.EmployerNo,
|
||
ContractAmount = item.ContractAmount,
|
||
EmployerName = item.EmployerName,
|
||
EmployerViewModels = item.EmployerViewModels,
|
||
IsActiveString = item.IsActiveString,
|
||
WorkshopCount = item.WorkshopCount,
|
||
WorkshopViewModels = item.WorkshopViewModels,
|
||
EmployeeCount = item.EmployeeCount,
|
||
ExpireColor = item.ExpireColor,
|
||
SearchAmount = item.SearchAmount,
|
||
BalanceDouble = item.BalanceDouble,
|
||
BalanceStr = item.BalanceStr,
|
||
Signature = item.Signature,
|
||
ArchiveCode = archiveCode,
|
||
TypeOfContract = item.TypeOfContract,
|
||
IsContractingPartyBlock = item.IsContractingPartyBlock,
|
||
BlockTimes = item.BlockTimes,
|
||
};
|
||
join.Add(result);
|
||
}
|
||
|
||
//Console.WriteLine("forEchTime : " + watchw.Elapsed);
|
||
var findeByFilter = new List<InstitutionContractViewModel>();
|
||
if (searchModel.WorkshopId != 0)
|
||
{
|
||
foreach (var item in join)
|
||
{
|
||
var check = item.WorkshopViewModels.Where(x => x.Id == searchModel.WorkshopId).ToList();
|
||
if (check.Count > 0)
|
||
findeByFilter.Add(item);
|
||
}
|
||
|
||
join = findeByFilter;
|
||
}
|
||
|
||
var findeByFilter2 = new List<InstitutionContractViewModel>();
|
||
if (searchModel.EmployerId != 0)
|
||
{
|
||
foreach (var item in join)
|
||
{
|
||
var check = item.EmployerViewModels.Where(x => x.Id == searchModel.EmployerId).ToList();
|
||
if (check.Count > 0)
|
||
findeByFilter2.Add(item);
|
||
}
|
||
|
||
join = findeByFilter2;
|
||
}
|
||
|
||
|
||
join = join.OrderBy(x => x.WorkshopCount != "0" && string.IsNullOrWhiteSpace(x.ExpireColor))
|
||
.ThenBy(x => x.WorkshopCount == "0" && string.IsNullOrWhiteSpace(x.ExpireColor))
|
||
.ThenBy(x => x.ExpireColor == "red")
|
||
.ThenBy(x => x.ExpireColor == "purple")
|
||
.ThenBy(x => x.ExpireColor == "black").ToList();
|
||
|
||
return join;
|
||
}
|
||
|
||
public List<InstitutionContractViewModel> NewSearch(InstitutionContractSearchModel searchModel)
|
||
{
|
||
return _institutionContractRepository.NewSearch(searchModel);
|
||
}
|
||
|
||
|
||
public List<InstitutionContractViewModel> GetInstitutionContractToSetServicesExcelImport()
|
||
{
|
||
var result = _institutionContractRepository.NewSearch(new InstitutionContractSearchModel());
|
||
|
||
return result.Where(x =>
|
||
x.IsActiveString == "true" && x.IsContractingPartyBlock != "true" && x.WorkshopCount != "0" &&
|
||
x.ContractStartGr <= DateTime.Now && x.ContractEndGr >= DateTime.Now).ToList();
|
||
}
|
||
|
||
public string ExpCheckColor(DateTime now, DateTime ContractEndGr, DateTime endThisMontGr, string ContractAmount,
|
||
string isActiveString)
|
||
{
|
||
string result = "";
|
||
|
||
if (ContractEndGr < now)
|
||
result = "black";
|
||
if (ContractEndGr >= now && ContractEndGr <= endThisMontGr)
|
||
result = "red";
|
||
if (ContractAmount == "0")
|
||
result = "purple";
|
||
if (isActiveString == "blue")
|
||
result = "blue";
|
||
return result;
|
||
}
|
||
|
||
public TotalbalancViewModel TotalBalance(long contractingPartyId)
|
||
{
|
||
var result = new TotalbalancViewModel();
|
||
|
||
var firstGetStatement = _financialStatmentApplication.GetDetailsByContractingPartyId(contractingPartyId);
|
||
var allTransactions = firstGetStatement.FinancialTransactionViewModels;
|
||
if (allTransactions != null)
|
||
{
|
||
allTransactions = allTransactions.OrderBy(x => x.TdateGr).ToList();
|
||
var debt = allTransactions.Sum(x => x.Deptor);
|
||
var credit = allTransactions.Sum(x => x.Creditor);
|
||
result.TotalBalanceDbl = debt - credit;
|
||
result.TotalBalanceStr = result.TotalBalanceDbl.ToMoney();
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
public WorkshopsAndEmployeeViewModel WorkShopDetailsAndEmployeeCount(long contractingPartyId)
|
||
{
|
||
var result = new WorkshopsAndEmployeeViewModel();
|
||
|
||
var emplId = _employerRepository.GetEmployerByContracrtingPartyID(contractingPartyId).Select(x => x.Id)
|
||
.ToList();
|
||
;
|
||
result.WorkshopViewModels = _workshopRepository.GetWorkshopsByEmployerId(emplId);
|
||
var workshopIds = result.WorkshopViewModels.Select(x => x.Id).ToList();
|
||
var left = 0;
|
||
result.WorkshopCount = Convert.ToString(workshopIds.Count);
|
||
var joinPersonelList = new List<ConnectedPersonnelViewModel>();
|
||
foreach (var workshopId in workshopIds)
|
||
{
|
||
//var reslt = _workshopApplication.GetConnectedPersonnels(workshopId);
|
||
//var noBlock = reslt.Where(x => x.Black == false).ToList();
|
||
//joinPersonelList.AddRange(noBlock);
|
||
var pCount = _workshopApplication.PersonnelCount(workshopId);
|
||
result.EmployeeCount = Convert.ToString(pCount);
|
||
}
|
||
//var joinlistWithoutDuplicat = joinPersonelList.GroupBy(x => x.PersonName).Select(x => x.First()).ToList();
|
||
//left = joinlistWithoutDuplicat.Count();
|
||
//result.EmployeeCount = Convert.ToString(left);
|
||
|
||
|
||
result.ArchiveCode = 0;
|
||
if (workshopIds.Count > 0)
|
||
{
|
||
var workshop = result.WorkshopViewModels.OrderBy(x => x.Id)?.ToList();
|
||
|
||
var arc = workshop.Select(x => new ArchiveCodConvertoint
|
||
{
|
||
ArchiveCodeInt = x.ArchiveCode.Substring(0, 1) == "b" ? 10000000 : x.ArchiveCode.ConvertToInt(),
|
||
}).OrderBy(x => x.ArchiveCodeInt).ToList();
|
||
var minArchiveCode = arc.Min(x => x.ArchiveCodeInt);
|
||
result.ArchiveCode = minArchiveCode == 10000000 ? 0 : minArchiveCode;
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
public List<InstitutionContractViewModel> PrintAll(List<long> id)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
public InstitutionContractViewModel PrintOne(long id)
|
||
{
|
||
var get = _institutionContractRepository.GetDetails(id);
|
||
var employer = _employerRepository.GetEmployerByContracrtingPartyID(get.ContractingPartyId);
|
||
var employerViewModels = employer;
|
||
var emplId = employerViewModels.Select(x => x.Id).ToList();
|
||
var workshops = _workshopRepository.GetWorkshopsByEmployerId(emplId);
|
||
var res = new InstitutionContractViewModel()
|
||
{
|
||
Id = get.Id,
|
||
ContractNo = get.ContractNo,
|
||
|
||
ContractStartFa = get.ContractStartFa,
|
||
|
||
ContractEndFa = get.ContractEndFa,
|
||
|
||
ContractingPartyName = get.ContractingPartyName,
|
||
|
||
ContractingPartyId = get.ContractingPartyId,
|
||
ContractDateFa = get.ContractDateFa,
|
||
State = get.State,
|
||
City = get.City,
|
||
Address = get.Address,
|
||
Description = get.Description,
|
||
HasValueAddedTax = get.HasValueAddedTax,
|
||
ValueAddedTax = get.ValueAddedTax,
|
||
ContractAmount = get.ContractAmountString,
|
||
DailyCompenseation = get.DailyCompenseationString,
|
||
Obligation = get.ObligationString,
|
||
TotalAmount = get.TotalAmountString,
|
||
WorkshopViewModels = workshops
|
||
};
|
||
return res;
|
||
}
|
||
|
||
|
||
public OperationResult Active(long id)
|
||
{
|
||
var opration = new OperationResult();
|
||
var contract = _institutionContractRepository.Get(id);
|
||
if (contract == null)
|
||
return opration.Failed("رکورد مورد نظر یافت نشد");
|
||
|
||
contract.Active();
|
||
|
||
_institutionContractRepository.SaveChanges();
|
||
return opration.Succcedded();
|
||
}
|
||
|
||
public OperationResult DeActive(long id)
|
||
{
|
||
var opration = new OperationResult();
|
||
var contract = _institutionContractRepository.Get(id);
|
||
if (contract == null)
|
||
return opration.Failed("رکورد مورد نظر یافت نشد");
|
||
|
||
contract.DeActive();
|
||
|
||
|
||
_institutionContractRepository.SaveChanges();
|
||
return opration.Succcedded();
|
||
}
|
||
|
||
public OperationResult DeActiveBlue(long id)
|
||
{
|
||
var opration = new OperationResult();
|
||
var institutionContract = _institutionContractRepository.Get(id);
|
||
if (institutionContract == null)
|
||
return opration.Failed("رکورد مورد نظر یافت نشد");
|
||
|
||
institutionContract.DeActiveBlue();
|
||
_institutionContractRepository.SaveChanges();
|
||
|
||
return opration.Succcedded();
|
||
}
|
||
|
||
public OperationResult DeActiveAllConnections(long id)
|
||
{
|
||
var opration = new OperationResult();
|
||
var institutionContract = _institutionContractRepository.Get(id);
|
||
if (institutionContract == null)
|
||
return opration.Failed("رکورد مورد نظر یافت نشد");
|
||
|
||
|
||
var contractingParty = _contractingPartyRepository.Get(institutionContract.ContractingPartyId);
|
||
if (contractingParty != null)
|
||
{
|
||
contractingParty.DeActive();
|
||
_contractingPartyRepository.SaveChanges();
|
||
var employers =
|
||
_employerRepository.GetEmployerByContracrtingPartyID(institutionContract.ContractingPartyId);
|
||
//var employersIdList = employers.Select(x => x.Id).ToList();
|
||
//var workshops = _workshopApplication.GetWorkshopsByEmployerId(employersIdList);
|
||
//foreach (var workshop in workshops)
|
||
//{
|
||
// var res = _workshopApplication.DeActive(workshop.Id);
|
||
//}
|
||
foreach (var employer in employers)
|
||
{
|
||
var res = _employerRepository.DeActiveAll(employer.Id);
|
||
}
|
||
}
|
||
|
||
return opration.Succcedded();
|
||
}
|
||
|
||
public OperationResult ReActiveAllConnections(long id)
|
||
{
|
||
var opration = new OperationResult();
|
||
var institutionContract = _institutionContractRepository.Get(id);
|
||
if (institutionContract == null)
|
||
return opration.Failed("رکورد مورد نظر یافت نشد");
|
||
|
||
|
||
var contractingParty = _contractingPartyRepository.Get(institutionContract.ContractingPartyId);
|
||
if (contractingParty != null)
|
||
{
|
||
contractingParty.Active();
|
||
_contractingPartyRepository.SaveChanges();
|
||
var employers =
|
||
_employerRepository.GetEmployerByContracrtingPartyID(institutionContract.ContractingPartyId);
|
||
//var employersIdList = employers.Select(x => x.Id).ToList();
|
||
//var workshops = _workshopApplication.GetWorkshopsByEmployerId(employersIdList);
|
||
//foreach (var workshop in workshops)
|
||
//{
|
||
// var res = _workshopApplication.DeActive(workshop.Id);
|
||
//}
|
||
foreach (var employer in employers)
|
||
{
|
||
var res = _employerRepository.ActiveAll(employer.Id);
|
||
}
|
||
}
|
||
|
||
return opration.Succcedded();
|
||
}
|
||
|
||
public void ReActiveAllAfterCreateNew(long contractingPartyId)
|
||
{
|
||
var contractingParty = _contractingPartyRepository.Get(contractingPartyId);
|
||
if (contractingParty != null)
|
||
{
|
||
if (contractingParty.IsActiveString == "false")
|
||
{
|
||
contractingParty.Active();
|
||
_contractingPartyRepository.SaveChanges();
|
||
}
|
||
|
||
var employers =
|
||
_employerRepository.GetEmployerByContracrtingPartyID(contractingPartyId);
|
||
|
||
foreach (var employer in employers)
|
||
{
|
||
var res = _employerRepository.ActiveAll(employer.Id);
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
public void RemoveContract(long id)
|
||
{
|
||
_institutionContractRepository.RemoveContract(id);
|
||
|
||
}
|
||
|
||
|
||
public OperationResult Sign(long id)
|
||
{
|
||
var opration = new OperationResult();
|
||
var contract = _institutionContractRepository.Get(id);
|
||
if (contract == null)
|
||
return opration.Failed("رکورد مورد نظر یافت نشد");
|
||
|
||
contract.Sign();
|
||
|
||
|
||
_institutionContractRepository.SaveChanges();
|
||
opration.IsSuccedded = true;
|
||
return opration.Succcedded();
|
||
}
|
||
|
||
public OperationResult UnSign(long id)
|
||
{
|
||
var opration = new OperationResult();
|
||
var contract = _institutionContractRepository.Get(id);
|
||
if (contract == null)
|
||
return opration.Failed("رکورد مورد نظر یافت نشد");
|
||
|
||
contract.UnSign();
|
||
|
||
|
||
_institutionContractRepository.SaveChanges();
|
||
opration.IsSuccedded = true;
|
||
return opration.Succcedded();
|
||
}
|
||
|
||
public void CreateContractingPartyAccount(long contractingPartyid, long accountId)
|
||
{
|
||
_institutionContractRepository.CreateContractingPartyAccount(contractingPartyid, accountId);
|
||
}
|
||
|
||
public double GetcontractAmount(int countPerson)
|
||
{
|
||
return _institutionContractRepository.GetcontractAmount(countPerson);
|
||
}
|
||
|
||
public async Task<PagedResult<GetInstitutionContractListItemsViewModel>> GetList(
|
||
InstitutionContractListSearchModel searchModel)
|
||
{
|
||
return await _institutionContractRepository.GetList(searchModel);
|
||
}
|
||
|
||
public Task<GetInstitutionContractListStatsViewModel> GetListStats(InstitutionContractListSearchModel searchModel)
|
||
{
|
||
return _institutionContractRepository.GetListStats(searchModel);
|
||
}
|
||
|
||
public async Task<OperationResult> CreateAsync(CreateInstitutionContractRequest command)
|
||
{
|
||
var opration = new OperationResult();
|
||
var syear = command.ContractStartFa.Substring(0, 4);
|
||
var smonth = command.ContractStartFa.Substring(5, 2);
|
||
var sday = command.ContractStartFa.Substring(8, 2);
|
||
|
||
var transaction = await _contractingPartyRepository.BeginTransactionAsync();
|
||
|
||
if (command.ContractStartFa.TryToGeorgianDateTime(out var contractStartGr) == false)
|
||
return opration.Failed("تاریخ شروع قرارداد معتبر نیست");
|
||
|
||
contractStartGr.AddMonthsFa((int)command.Duration, out var contractEndGr);
|
||
|
||
contractEndGr = contractEndGr.ToFarsi().FindeEndOfMonth().ToGeorgianDateTime();
|
||
|
||
PersonalContractingParty existingContractingParty = null;
|
||
if (command.ContractingPartyLegalType == LegalType.Legal)
|
||
{
|
||
existingContractingParty =
|
||
await _contractingPartyRepository.GetByNationalId(command.LegalParty.NationalId);
|
||
if (_contractingPartyRepository.Exists(x =>
|
||
x.LName == command.LegalParty.CompanyName && x.RegisterId == command.LegalParty.RegisterId))
|
||
{
|
||
if (_institutionContractRepository.Exists(x => x.ContractStartGr < contractEndGr
|
||
&& contractStartGr < x.ContractEndGr
|
||
&& x.ContractingPartyId == existingContractingParty.id
|
||
&& x.IsActiveString == "true"))
|
||
{
|
||
throw new BadRequestException("امکان ایجاد قرارداد تکراری وجود ندارد");
|
||
}
|
||
}
|
||
|
||
if (!command.LegalParty.IsAuth && existingContractingParty != null)
|
||
{
|
||
var legalCommand = command.LegalParty;
|
||
existingContractingParty.UnAuthenticateLegalEdit(legalCommand.FName,legalCommand.LName,legalCommand.FatherName,legalCommand.IdNumber,existingContractingParty.IdNumberSeri,existingContractingParty.IdNumberSerial,
|
||
legalCommand.BirthDateFa,legalCommand.Gender,legalCommand.PhoneNumber);
|
||
}
|
||
|
||
if (existingContractingParty != null)
|
||
{
|
||
existingContractingParty.EditLegalPartyFromInstitution(command.LegalParty.Position,command.LegalParty.CompanyName,
|
||
command.LegalParty.RegisterId,command.LegalParty.NationalId);
|
||
}
|
||
}
|
||
else if (command.ContractingPartyLegalType == LegalType.Real)
|
||
{
|
||
existingContractingParty =
|
||
await _contractingPartyRepository.GetByNationalCode(command.RealParty.NationalCode);
|
||
if (_contractingPartyRepository.Exists(x =>
|
||
x.LName == command.RealParty.LName && x.Nationalcode == command.RealParty.NationalCode))
|
||
{
|
||
if (_institutionContractRepository.Exists(x => x.ContractStartGr < contractEndGr
|
||
&& contractStartGr < x.ContractEndGr
|
||
&& x.ContractingPartyId == existingContractingParty.id
|
||
&& x.IsActiveString == "true"))
|
||
{
|
||
throw new BadRequestException("امکان ایجاد قرارداد تکراری وجود ندارد");
|
||
}
|
||
}
|
||
if (!command.RealParty.IsAuth && existingContractingParty != null)
|
||
{
|
||
var realCommand = command.RealParty;
|
||
existingContractingParty.UnAuthenticateRealEdit(realCommand.FName,realCommand.LName,realCommand.FatherName,realCommand.IdNumber,existingContractingParty.IdNumberSeri,existingContractingParty.IdNumberSerial,
|
||
realCommand.BirthDateFa,realCommand.Gender,realCommand.PhoneNumber);
|
||
}
|
||
}
|
||
|
||
await _institutionContractRepository.SaveChangesAsync();
|
||
PersonalContractingParty contractingParty;
|
||
if (existingContractingParty != null)
|
||
{
|
||
contractingParty = existingContractingParty;
|
||
}
|
||
else
|
||
{
|
||
OperationResult<PersonalContractingParty> contractingPartyResult = command.ContractingPartyLegalType switch
|
||
{
|
||
LegalType.Legal => await CreateLegalContractingPartyEntity(command.LegalParty, command.RepresentativeId,
|
||
command.Address,
|
||
command.City, command.Province),
|
||
LegalType.Real => await CreateRealContractingPartyEntity(command.RealParty, command.RepresentativeId,
|
||
command.Address,
|
||
command.City, command.Province),
|
||
_ => throw new BadRequestException("نوع طرف قرارداد مشخص نشده است")
|
||
};
|
||
|
||
if (!contractingPartyResult.IsSuccedded)
|
||
return opration.Failed(contractingPartyResult.Message);
|
||
|
||
contractingParty = contractingPartyResult.Data;
|
||
}
|
||
|
||
|
||
|
||
if (_institutionContractRepository.Exists(x =>
|
||
x.ContractingPartyId == contractingParty.id && x.RepresentativeId == command.RepresentativeId &&
|
||
x.TypeOfContract == "JobRelation"))
|
||
return opration.Failed(
|
||
"برای این معرف و طرف حساب قبلا قرارداد ایجاد شده است، شما میتوانید از تمدید استفاده کنید");
|
||
|
||
var contractNo = $"{syear}{smonth}{sday}/{contractingParty.ArchiveCode}/0";
|
||
|
||
var representative = _representativeRepository.Get(command.RepresentativeId);
|
||
if (representative == null)
|
||
return opration.Failed("معرف مورد نظر یافت نشد");
|
||
|
||
if (command.IsInstallment &&
|
||
!command.Workshops.Any(x => x.HasContractPlanInPerson || x.HasInsurancePlanInPerson))
|
||
{
|
||
return opration.Failed("برای قراردادهای اقساطی حداقل یک کارگاه باید دارای طرح حضوری باشد");
|
||
}
|
||
|
||
|
||
var today = DateTime.Today;
|
||
|
||
var contractDateGr = today;
|
||
var contractDateFa = contractDateGr.ToFarsi();
|
||
|
||
|
||
var hasValueAddedTax = command.TaxAmount > 0 ? "true" : "false";
|
||
|
||
var contractingPartyFullName = "";
|
||
if (contractingParty.IsLegal == "حقیقی")
|
||
{
|
||
contractingPartyFullName = contractingParty.FName + " " + contractingParty.LName;
|
||
}
|
||
else
|
||
{
|
||
contractingPartyFullName = contractingParty.CeoFName + " " + contractingParty.CeoLName;
|
||
}
|
||
|
||
var workshopDetails = command.Workshops.Select(x =>
|
||
new InstitutionContractWorkshopInitial(x.WorkshopName, x.HasRollCallPlan, false, x.HasCustomizeCheckoutPlan,
|
||
x.HasContractPlan, x.HasContractPlanInPerson, x.HasInsurancePlan, x.HasInsurancePlanInPerson,
|
||
x.PersonnelCount, x.Price)).ToList();
|
||
|
||
|
||
var entity = new InstitutionContract(contractNo, command.RepresentativeId, representative.FullName,
|
||
contractingParty.id,
|
||
contractingPartyFullName, contractDateGr, contractDateFa, command.Province, command.City, command.Address,
|
||
contractStartGr,
|
||
contractStartGr.ToFarsi(), contractEndGr, contractEndGr.ToFarsi(), command.OneMonthAmount,
|
||
command.DailyCompensation,
|
||
command.Obligation, command.PaymentAmount, 0,
|
||
command.Workshops.Count.ToString(),
|
||
command.Workshops.Sum(x => x.PersonnelCount).ToString(), command.Description,
|
||
"NotOfficial", "JobRelation", hasValueAddedTax,
|
||
command.TaxAmount, workshopDetails, command.LawId,command.DiscountPercentage,command.DiscountAmount );
|
||
|
||
|
||
FinancialStatment financialStatement;
|
||
if (_financialStatmentRepository.Exists(x => x.ContractingPartyId == contractingParty.id))
|
||
{
|
||
financialStatement = await _financialStatmentRepository.GetByContractingPartyId(contractingParty.id);
|
||
}
|
||
else
|
||
{
|
||
financialStatement = new FinancialStatment(contractingParty.id, contractingPartyFullName);
|
||
await _financialStatmentRepository.CreateAsync(financialStatement);
|
||
}
|
||
await _institutionContractRepository.CreateAsync(entity);
|
||
await _institutionContractRepository.SaveChangesAsync();
|
||
|
||
if (command.IsInstallment)
|
||
{
|
||
var installments =
|
||
CalculateInstallment(command.PaymentAmount, (int)command.Duration, command.ContractStartFa, true);
|
||
|
||
|
||
// دریافت مبلغ اولین قسط
|
||
//این کار برای این هست که اولین قسط باید با تاریخ امروز باشد و باید به وضعیت مالی بدهی ایجاد شود که یوزر اولین بدهی را وارد کند
|
||
var firstInstallmentAmount = installments.First().Amount;
|
||
|
||
// حذف اولین قسط
|
||
installments.RemoveAt(0);
|
||
|
||
// ایجاد قسط جدید با تاریخ امروز
|
||
var todayInstallment = new InstitutionContractInstallment(DateTime.Today, firstInstallmentAmount, "");
|
||
|
||
|
||
// اضافه کردن قسط جدید به ابتدای لیست
|
||
installments.Insert(0, todayInstallment);
|
||
|
||
entity.SetInstallments(installments);
|
||
|
||
await _institutionContractRepository.SaveChangesAsync();
|
||
|
||
}
|
||
|
||
var mainContactInfo = new CreateContactInfo
|
||
{
|
||
InstitutionContractId = entity.id,
|
||
PhoneType = "شماره همراه",
|
||
Position = "طرف قرارداد",
|
||
PhoneNumber = contractingParty.Phone,
|
||
FnameLname = contractingPartyFullName,
|
||
SendSms = true
|
||
};
|
||
_contactInfoApplication.Create(mainContactInfo);
|
||
|
||
foreach (var contactInfo in command.ContactInfos)
|
||
{
|
||
if (contactInfo.PhoneNumber != null)
|
||
{
|
||
var contactinfo = new CreateContactInfo
|
||
{
|
||
InstitutionContractId = entity.id,
|
||
PhoneType = contactInfo.PhoneType,
|
||
Position = contactInfo.Position,
|
||
PhoneNumber = contactInfo.PhoneNumber,
|
||
FnameLname = contactInfo.FnameLname,
|
||
SendSms = contactInfo.SendSmsString == "true" ? true : false
|
||
};
|
||
_contactInfoApplication.Create(contactinfo);
|
||
}
|
||
}
|
||
|
||
var userPass = contractingParty.IsLegal == "حقیقی"
|
||
? contractingParty.Nationalcode
|
||
: contractingParty.NationalId;
|
||
var createAcc = new RegisterAccount
|
||
{
|
||
Fullname = contractingParty.LName,
|
||
Username = userPass,
|
||
Password = userPass,
|
||
Mobile = contractingParty.Phone,
|
||
NationalCode = userPass
|
||
};
|
||
var res = _accountApplication.RegisterClient(createAcc);
|
||
if (res.IsSuccedded)
|
||
CreateContractingPartyAccount(contractingParty.id, res.SendId);
|
||
|
||
|
||
await _smsService.SendInstitutionCreationVerificationLink(contractingParty.Phone, contractingPartyFullName,
|
||
entity.PublicId, contractingParty.id, entity.id);
|
||
|
||
await _institutionContractRepository.SaveChangesAsync();
|
||
|
||
await transaction.CommitAsync();
|
||
return opration.Succcedded();
|
||
}
|
||
|
||
public async Task<OperationResult> EditAsync(EditInstitutionContractRequest command)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
|
||
public Task<List<RegistrationWorkflowMainListViewModel>> RegistrationWorkflowMainList()
|
||
{
|
||
return _institutionContractRepository.RegistrationWorkflowMainList();
|
||
}
|
||
|
||
public Task<List<RegistrationWorkflowItemsViewModel>> RegistrationWorkflowItems(long institutionContractId)
|
||
{
|
||
return _institutionContractRepository.RegistrationWorkflowItems(institutionContractId);
|
||
}
|
||
|
||
public async Task<GetInstitutionVerificationDetailsViewModel> GetVerificationDetails(Guid id)
|
||
{
|
||
return await _institutionContractRepository.GetVerificationDetails(id);
|
||
}
|
||
|
||
|
||
public async Task<OperationResult<OtpResultViewModel>> SendVerifyOtp(Guid id)
|
||
{
|
||
var institutionContract = await _institutionContractRepository.GetByPublicIdAsync(id);
|
||
if (institutionContract == null)
|
||
{
|
||
throw new NotFoundException("رکورد مورد نظر یافت نشد");
|
||
}
|
||
|
||
if (institutionContract.VerificationStatus == InstitutionContractVerificationStatus.Verified)
|
||
throw new BadRequestException("این قرارداد مالی قبلا تایید شده است");
|
||
|
||
if (institutionContract.VerificationStatus == InstitutionContractVerificationStatus.PendingForVerify &&
|
||
institutionContract.VerifyCodeCreation != DateTime.MinValue)
|
||
{
|
||
if (!institutionContract.CanResendVerifyCode)
|
||
{
|
||
throw new BadRequestException("کد تایید قبلی هنوز منقضی نشده است",
|
||
new Dictionary<string, object>
|
||
{
|
||
{
|
||
"expireTime", (int)institutionContract.ReSendTime.TotalSeconds -
|
||
(int)(DateTime.Now - institutionContract.VerifyCodeCreation).TotalSeconds
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
var contractingParty = _contractingPartyRepository.Get(institutionContract.ContractingPartyId);
|
||
if (contractingParty == null)
|
||
throw new NotFoundException("طرف قرارداد یافت نشد");
|
||
|
||
var code = new Random().Next(1000, 9999).ToString();
|
||
|
||
var contractingPartyFullName = contractingParty.IsLegal == "حقیقی"
|
||
? contractingParty.FName + " " + contractingParty.LName
|
||
: contractingParty.CeoFName + " " + contractingParty.CeoLName;
|
||
|
||
institutionContract.SetVerifyCode(code, contractingPartyFullName, contractingParty.Phone);
|
||
|
||
var transaction = await _institutionContractRepository.BeginTransactionAsync();
|
||
try
|
||
{
|
||
await _institutionContractRepository.SaveChangesAsync();
|
||
await _smsService.SendInstitutionVerificationCode(contractingParty.Phone, code,contractingPartyFullName,
|
||
contractingParty.id, institutionContract.id);
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
transaction.Rollback();
|
||
Console.WriteLine(e);
|
||
throw;
|
||
}
|
||
|
||
await transaction.CommitAsync();
|
||
var result = new OtpResultViewModel
|
||
{
|
||
ExpireTimeSec = (int)institutionContract.ExpireTime.TotalSeconds,
|
||
ReSendTimeSec = (int)institutionContract.ReSendTime.TotalSeconds
|
||
};
|
||
return new OperationResult<OtpResultViewModel>().Succcedded(result);
|
||
}
|
||
|
||
public async Task<OperationResult<string>> VerifyOtpAndMakeGateway(Guid publicId, string code, string callbackUrl)
|
||
{
|
||
var op = new OperationResult<string>();
|
||
var institutionContract = await _institutionContractRepository.GetByPublicIdAsync(publicId);
|
||
if (institutionContract == null)
|
||
{
|
||
throw new NotFoundException("رکورد مورد نظر یافت نشد");
|
||
}
|
||
|
||
if (institutionContract.VerificationStatus == InstitutionContractVerificationStatus.Verified)
|
||
throw new BadRequestException("این قرارداد مالی قبلا تایید شده است");
|
||
|
||
if (institutionContract.VerificationStatus == InstitutionContractVerificationStatus.PendingForVerify &&
|
||
institutionContract.VerifyCodeExpired)
|
||
throw new BadRequestException("کد تایید منقضی شده است");
|
||
|
||
var contractingParty = _contractingPartyRepository.Get(institutionContract.ContractingPartyId);
|
||
if (contractingParty == null)
|
||
throw new NotFoundException("طرف قرارداد یافت نشد");
|
||
|
||
if (institutionContract.VerifyCode != code)
|
||
return op.Failed("کد وارد شده صحیح نمی باشد");
|
||
|
||
var financialStatement =await _financialStatmentRepository.GetByContractingPartyId(contractingParty.id);
|
||
|
||
var dbTransaction = await _institutionContractRepository.BeginTransactionAsync();
|
||
FinancialInvoice financialInvoice;
|
||
FinancialInvoiceItem financialInvoiceItem;
|
||
var today = DateTime.Today;
|
||
double invoiceAmount = 0;
|
||
string invoiceItemDescription = string.Empty;
|
||
FinancialInvoiceItemType invoiceItemType = FinancialInvoiceItemType.BuyInstitutionContract;
|
||
long invoiceItemEntityId = 0;
|
||
|
||
if (institutionContract.IsInstallment)
|
||
{
|
||
var firstInstallment = institutionContract.Installments.First();
|
||
var firstInstallmentAmount = firstInstallment.Amount;
|
||
|
||
financialInvoice = await _financialInvoiceRepository.GetUnPaidByEntityId(firstInstallment.Id, FinancialInvoiceItemType.BuyInstitutionContractInstallment);
|
||
if (financialInvoice == null)
|
||
{
|
||
var financialTransaction = new FinancialTransaction(0, today, today.ToFarsi(),
|
||
"قسط اول سرویس", "debt", "بابت خدمات", firstInstallmentAmount, 0, 0);
|
||
financialStatement.AddFinancialTransaction(financialTransaction);
|
||
invoiceAmount = firstInstallmentAmount;
|
||
invoiceItemDescription = $"پرداخت قسط اول قرارداد شماره {institutionContract.ContractNo}";
|
||
invoiceItemType = FinancialInvoiceItemType.BuyInstitutionContractInstallment;
|
||
invoiceItemEntityId = firstInstallment.Id;
|
||
}
|
||
else
|
||
{
|
||
invoiceAmount = financialInvoice.Amount;
|
||
invoiceItemDescription = financialInvoice.Items.First().Description;
|
||
invoiceItemType = financialInvoice.Items.First().Type;
|
||
invoiceItemEntityId = financialInvoice.Items.First().EntityId;
|
||
}
|
||
}
|
||
else
|
||
{
|
||
financialInvoice = await _financialInvoiceRepository.GetUnPaidByEntityId(institutionContract.id, FinancialInvoiceItemType.BuyInstitutionContract);
|
||
if (financialInvoice == null)
|
||
{
|
||
var financialTransaction = new FinancialTransaction(0, today, today.ToFarsi(),
|
||
"پرداخت کل سرویس", "debt", "بابت خدمات", institutionContract.TotalAmount, 0, 0);
|
||
financialStatement.AddFinancialTransaction(financialTransaction);
|
||
invoiceAmount = institutionContract.TotalAmount;
|
||
invoiceItemDescription = $"پرداخت کل قرارداد شماره {institutionContract.ContractNo}";
|
||
invoiceItemType = FinancialInvoiceItemType.BuyInstitutionContract;
|
||
invoiceItemEntityId = institutionContract.id;
|
||
}
|
||
else
|
||
{
|
||
invoiceAmount = financialInvoice.Amount;
|
||
invoiceItemDescription = financialInvoice.Items.First().Description;
|
||
invoiceItemType = financialInvoice.Items.First().Type;
|
||
invoiceItemEntityId = financialInvoice.Items.First().EntityId;
|
||
}
|
||
}
|
||
|
||
if (financialInvoice == null)
|
||
{
|
||
financialInvoice = new FinancialInvoice(invoiceAmount, contractingParty.id, $"خرید قرارداد مالی شماره {institutionContract.ContractNo}");
|
||
financialInvoiceItem = new FinancialInvoiceItem(invoiceItemDescription, invoiceAmount, 0, invoiceItemType, invoiceItemEntityId);
|
||
financialInvoice.AddItem(financialInvoiceItem);
|
||
await _financialInvoiceRepository.CreateAsync(financialInvoice);
|
||
}
|
||
|
||
await _financialInvoiceRepository.SaveChangesAsync();
|
||
|
||
var transaction = new PaymentTransaction(institutionContract.ContractingPartyId, invoiceAmount,
|
||
institutionContract.ContractingPartyName, "https://client.gozareshgir.ir",
|
||
PaymentTransactionGateWay.SepehrPay);
|
||
await _paymentTransactionRepository.CreateAsync(transaction);
|
||
await _financialInvoiceRepository.SaveChangesAsync();
|
||
|
||
var createPayment = new CreatePaymentGatewayRequest()
|
||
{
|
||
Amount = invoiceAmount,
|
||
TransactionId = transaction.id.ToString(),
|
||
CallBackUrl = callbackUrl,
|
||
FinancialInvoiceId = financialInvoice.id,
|
||
};
|
||
var gatewayResponse = await _paymentGateway.Create(createPayment);
|
||
if (!gatewayResponse.IsSuccess)
|
||
return op.Failed("خطا در ایجاد درگاه پرداخت: " + gatewayResponse.Message + gatewayResponse.ErrorCode);
|
||
|
||
|
||
// institutionContract.SetPendingWorkflow();
|
||
//
|
||
// var phone = institutionContract.ContactInfoList.FirstOrDefault(x =>
|
||
// x.SendSms && x.Position == "طرف قرارداد" && x.PhoneType == "شماره همراه");
|
||
// if (phone !=null)
|
||
// {
|
||
// var userPass = contractingParty.IsLegal == "حقیقی"
|
||
// ? contractingParty.Nationalcode
|
||
// : contractingParty.NationalId;
|
||
// var createAcc = new RegisterAccount
|
||
// {
|
||
// Fullname = contractingParty.LName,
|
||
// Username = userPass,
|
||
// Password = userPass,
|
||
// Mobile = phone.PhoneNumber,
|
||
// NationalCode = userPass
|
||
// };
|
||
// var res = _accountApplication.RegisterClient(createAcc);
|
||
// if (res.IsSuccedded)
|
||
// CreateContractingPartyAccount(contractingParty.id, res.SendId);
|
||
// }
|
||
|
||
await dbTransaction.CommitAsync();
|
||
await _institutionContractRepository.SaveChangesAsync();
|
||
return op.Succcedded(gatewayResponse.Token);
|
||
}
|
||
|
||
public async Task<InstitutionContractWorkshopDetailViewModel> GetWorkshopInitialDetails(long workshopDetailsId)
|
||
{
|
||
var details = await _institutionContractRepository.GetInstitutionWorkshopInitialDetails(workshopDetailsId);
|
||
var services = details.Services;
|
||
var newArchiveCode = _workshopRepository.GetLastArchiveCode() + 1;
|
||
|
||
var res = new InstitutionContractWorkshopDetailViewModel()
|
||
{
|
||
ServicesViewModel = new WorkshopServicesViewModel()
|
||
{
|
||
Contract = services.Contract,
|
||
ContractInPerson = services.ContractInPerson,
|
||
CustomizeCheckout = services.CustomizeCheckout,
|
||
Insurance = services.Insurance,
|
||
InsuranceInPerson = services.InsuranceInPerson,
|
||
RollCall = services.RollCall,
|
||
RollCallInPerson = services.RollCallInPerson
|
||
},
|
||
WorkshopName = details.WorkshopName,
|
||
ArchiveCode = newArchiveCode
|
||
};
|
||
return res;
|
||
}
|
||
|
||
public InstitutionContractDiscountResponse CalculateDiscount(InstitutionContractSetDiscountRequest request)
|
||
{
|
||
return _institutionContractRepository.CalculateDiscount(request);
|
||
}
|
||
|
||
public InstitutionContractDiscountResponse ResetDiscountCreate(
|
||
InstitutionContractResetDiscountForCreateRequest request)
|
||
{
|
||
return _institutionContractRepository.ResetDiscountCreate(request);
|
||
}
|
||
|
||
public async Task<InstitutionContractExtensionInquiryResult> GetExtensionInquiry(long previousContractId)
|
||
{
|
||
return await _institutionContractRepository.GetExtensionInquiry(previousContractId);
|
||
}
|
||
|
||
public async Task<InstitutionContractExtensionWorkshopsResponse> GetExtensionWorkshops(
|
||
InstitutionContractExtensionWorkshopsRequest request)
|
||
{
|
||
return await _institutionContractRepository.GetExtensionWorkshops(request);
|
||
}
|
||
|
||
public async Task<InstitutionContractExtensionPlanResponse> GetExtensionInstitutionPlan(
|
||
InstitutionContractExtensionPlanRequest request)
|
||
{
|
||
return await _institutionContractRepository.GetExtensionInstitutionPlan(request);
|
||
}
|
||
|
||
public async Task<InstitutionContractExtensionPaymentResponse> GetExtensionPaymentMethod(
|
||
InstitutionContractExtensionPaymentRequest request)
|
||
{
|
||
return await _institutionContractRepository.GetExtensionPaymentMethod(request);
|
||
}
|
||
|
||
public async Task<InstitutionContractDiscountResponse> SetDiscountForExtension(
|
||
InstitutionContractSetDiscountForExtensionRequest request)
|
||
{
|
||
return await _institutionContractRepository.SetDiscountForExtension(request);
|
||
}
|
||
|
||
public async Task<InstitutionContractDiscountResponse> ResetDiscountForExtension(
|
||
InstitutionContractResetDiscountForExtensionRequest request)
|
||
{
|
||
return await _institutionContractRepository.ResetDiscountForExtension(request);
|
||
}
|
||
|
||
public async Task<OperationResult> ExtensionComplete(InstitutionContractExtensionCompleteRequest request)
|
||
{
|
||
return await _institutionContractRepository.ExtensionComplete(request);
|
||
}
|
||
|
||
public async Task<List<InstitutionContractSelectListViewModel>> GetInstitutionContractSelectList(string search,
|
||
string selected)
|
||
{
|
||
return await _institutionContractRepository.GetInstitutionContractSelectList(search, selected);
|
||
}
|
||
|
||
public async Task<InstitutionContractAmendmentWorkshopsResponse> GetAmendmentWorkshops(long institutionContractId)
|
||
{
|
||
return await _institutionContractRepository.GetAmendmentWorkshops(institutionContractId);
|
||
}
|
||
|
||
public async Task<InsertAmendmentTempWorkshopResponse> InsertAmendmentTempWorkshops(
|
||
InstitutionContractAmendmentTempWorkshopViewModel request)
|
||
{
|
||
return await _institutionContractRepository.InsertAmendmentTempWorkshops(request);
|
||
}
|
||
|
||
public Task RemoveAmendmentWorkshops(Guid workshopTempId)
|
||
{
|
||
return _institutionContractRepository.RemoveAmendmentWorkshops(workshopTempId);
|
||
}
|
||
|
||
public Task<InsitutionContractAmendmentPaymentResponse> GetAmendmentPaymentDetails(
|
||
InsitutionContractAmendmentPaymentRequest request)
|
||
{
|
||
return _institutionContractRepository.GetAmendmentPaymentDetails(request);
|
||
}
|
||
|
||
public async Task<OperationResult> ResendVerifyLink(long institutionContractId)
|
||
{
|
||
var institutionContract = _institutionContractRepository.Get(institutionContractId);
|
||
|
||
if (institutionContract == null)
|
||
{
|
||
throw new NotFoundException("رکورد مورد نظر یافت نشد");
|
||
}
|
||
|
||
if (institutionContract.VerificationStatus != InstitutionContractVerificationStatus.PendingForVerify)
|
||
{
|
||
throw new BadRequestException("این قرارداد مالی در وضعیت مناسبی برای ارسال مجدد لینک تایید نمی باشد");
|
||
}
|
||
|
||
var contractingParty = _contractingPartyRepository.Get(institutionContract.ContractingPartyId);
|
||
if (contractingParty == null)
|
||
throw new NotFoundException("طرف قرارداد یافت نشد");
|
||
var contractingPartyFullName = contractingParty.FName + " " + contractingParty.LName;
|
||
await _smsService.SendInstitutionCreationVerificationLink(contractingParty.Phone, contractingPartyFullName,
|
||
institutionContract.PublicId, contractingParty.id, institutionContract.id);
|
||
return new OperationResult().Succcedded();
|
||
}
|
||
|
||
public async Task<InstitutionContractPrintViewModel> PrintOneAsync(long id)
|
||
{
|
||
return (await _institutionContractRepository.PrintAllAsync([id])).FirstOrDefault();
|
||
}
|
||
|
||
|
||
public async Task<OperationResult> SetPendingWorkflow(long entityId,InstitutionContractSigningType signingType)
|
||
{
|
||
var op = new OperationResult();
|
||
var institutionContract = await _institutionContractRepository.GetIncludeWorkshopDetailsAsync(entityId);
|
||
if (institutionContract == null)
|
||
{
|
||
return op.Failed("قرارداد مالی یافت نشد");
|
||
}
|
||
|
||
if (institutionContract.VerificationStatus != InstitutionContractVerificationStatus.PendingForVerify)
|
||
{
|
||
return op.Failed("وضعیت قرارداد مالی برای این عملیات مناسب نمی باشد");
|
||
}
|
||
|
||
var initialCreatedWorkshops = institutionContract.WorkshopGroup.InitialWorkshops
|
||
.Where(x => x.WorkshopCreated && x.WorkshopId is > 0).ToList();
|
||
|
||
var currentWorkshops = institutionContract.WorkshopGroup.CurrentWorkshops.ToList();
|
||
var accountId = _contractingPartyRepository
|
||
.GetAccountByPersonalContractingParty(institutionContract.ContractingPartyId).Id;
|
||
foreach (var createdWorkshop in initialCreatedWorkshops)
|
||
{
|
||
if (currentWorkshops.Any(x => x.WorkshopId == createdWorkshop.WorkshopId))
|
||
{
|
||
//rollcall serviecs
|
||
if (createdWorkshop.Services.RollCall)
|
||
{
|
||
var ActiveService = _rollCallServiceRepository.GetActiveServiceByWorkshopId(createdWorkshop.WorkshopId!.Value);
|
||
var startTime = institutionContract.ContractStartGr;
|
||
var endTime = institutionContract.ContractEndGr;
|
||
if (ActiveService != null)
|
||
{
|
||
if (ActiveService.EndService> startTime)
|
||
{
|
||
startTime = ActiveService.EndService;
|
||
}
|
||
|
||
}
|
||
var rollCallService = new RollCallService("BasedOnIC",
|
||
startTime, endTime, createdWorkshop.WorkshopId.Value,accountId,createdWorkshop.PersonnelCount,
|
||
0,"12");
|
||
await _rollCallServiceRepository.CreateAsync(rollCallService);
|
||
}
|
||
}
|
||
else
|
||
{
|
||
var currentWorkshop = new InstitutionContractWorkshopCurrent(createdWorkshop.WorkshopName,
|
||
createdWorkshop.Services.RollCall, createdWorkshop.Services.RollCallInPerson,
|
||
createdWorkshop.Services.CustomizeCheckout, createdWorkshop.Services.Contract,
|
||
createdWorkshop.Services.ContractInPerson, createdWorkshop.Services.Insurance,
|
||
createdWorkshop.Services.InsuranceInPerson,createdWorkshop.PersonnelCount, createdWorkshop.Price,
|
||
createdWorkshop.InstitutionContractWorkshopGroupId,createdWorkshop.WorkshopGroup,
|
||
createdWorkshop.WorkshopId!.Value, false,createdWorkshop.id);
|
||
institutionContract.WorkshopGroup.AddCurrentWorkshop(currentWorkshop);
|
||
}
|
||
}
|
||
|
||
if (institutionContract.WorkshopGroup.InitialWorkshops.All(x => x.WorkshopCreated && x.WorkshopId is > 0))
|
||
{
|
||
|
||
institutionContract.Verified();
|
||
}
|
||
else
|
||
{
|
||
institutionContract.SetPendingWorkflow();
|
||
}
|
||
|
||
institutionContract.SetSigningType(signingType);
|
||
|
||
await _institutionContractRepository.SaveChangesAsync();
|
||
return op.Succcedded();
|
||
}
|
||
|
||
public async Task<long> GetIdByInstallmentId(long installmentId)
|
||
{
|
||
return await _institutionContractRepository.GetIdByInstallmentId(installmentId);
|
||
}
|
||
public Task<GetInstitutionContractWorkshopsDetails> GetContractWorkshopsDetails(long id)
|
||
{
|
||
return _institutionContractRepository.GetContractWorkshopsDetails(id);
|
||
}
|
||
|
||
public async Task<GetInstitutionAmendmentVerificationDetailsViewModel> GetAmendmentVerificationDetails(Guid id, long amendmentId)
|
||
{
|
||
return await _institutionContractRepository.GetAmendmentVerificationDetails(id,amendmentId);
|
||
}
|
||
|
||
public async Task AmendmentComplete(InstitutionContractAmendmentCompleteRequest request)
|
||
{
|
||
await _institutionContractRepository.AmendmentComplete(request);
|
||
}
|
||
|
||
|
||
public async Task<OperationResult> VerifyInstitutionContractManually(long institutionContractId)
|
||
{
|
||
var op = new OperationResult();
|
||
|
||
var institutionContract =await _institutionContractRepository
|
||
.GetIncludeWorkshopDetailsAsync(institutionContractId);
|
||
|
||
if (institutionContract == null)
|
||
return op.Failed("قرارداد مالی یافت نشد");
|
||
|
||
if (institutionContract.VerificationStatus == InstitutionContractVerificationStatus.Verified)
|
||
return op.Failed("قرارداد مالی قبلا تایید شده است");
|
||
|
||
var transaction = await _institutionContractRepository.BeginTransactionAsync();
|
||
await SetPendingWorkflow(institutionContractId,InstitutionContractSigningType.Physical);
|
||
|
||
var financialStatement = await _financialStatmentRepository
|
||
.GetByContractingPartyId(institutionContract.ContractingPartyId);
|
||
|
||
DateTime today = DateTime.Today;
|
||
var description = institutionContract.IsInstallment
|
||
? "قسط اول سرویس"
|
||
: "پرداخت کل سرویس";
|
||
var debtorAmount = institutionContract.IsInstallment
|
||
? institutionContract.Installments.First().Amount
|
||
: institutionContract.TotalAmount;
|
||
|
||
var financialTransaction = new FinancialTransaction(0, today, today.ToFarsi(),
|
||
description, "debt", "بابت خدمات", debtorAmount, 0, 0);
|
||
financialStatement.AddFinancialTransaction(financialTransaction);
|
||
|
||
await _institutionContractRepository.SaveChangesAsync();
|
||
await transaction.CommitAsync();
|
||
return op.Succcedded();
|
||
}
|
||
|
||
private async Task<OperationResult<PersonalContractingParty>> CreateLegalContractingPartyEntity(
|
||
CreateInstitutionContractLegalPartyRequest request, long representativeId, string address, string city,
|
||
string state)
|
||
{
|
||
var opration = new OperationResult<PersonalContractingParty>();
|
||
|
||
|
||
if (representativeId < 1)
|
||
return opration.Failed("لطفا معرف را انتخاب کنید");
|
||
|
||
if (_contractingPartyRepository.Exists(x =>
|
||
x.LName == request.CompanyName && x.NationalId == request.NationalId))
|
||
return opration.Failed("نام شرکت وارد شده تکراری است");
|
||
|
||
|
||
//if (_contractingPartyRepository.Exists(x =>
|
||
// x.RegisterId == request.RegisterId && x.LName != request.CompanyName))
|
||
// return opration.Failed("شماره ثبت وارد شده تکراری است");
|
||
|
||
|
||
if (_contractingPartyRepository.Exists(x =>
|
||
x.NationalId == request.NationalId && x.LName != request.CompanyName))
|
||
{
|
||
return opration.Failed("شناسه ملی وارد شده تکراری است");
|
||
}
|
||
|
||
var archiveCode = _contractingPartyRepository.GetLastNewArchiveCode();
|
||
|
||
|
||
var representative = _representativeRepository.GetDetails(representativeId);
|
||
var legalContractingParty = new PersonalContractingParty("*", request.CompanyName,
|
||
"*", "*", request.RegisterId, request.NationalId,
|
||
"حقوقی",
|
||
request.PhoneNumber, request.PhoneNumber, address, representativeId, representative.FullName,
|
||
archiveCode, state, city, null, null,
|
||
request.FName, request.LName, request.Position);
|
||
|
||
if (request.IsAuth)
|
||
{
|
||
legalContractingParty.LegalAuthentication(request.FName, request.LName, request.FatherName,
|
||
request.IdNumber, null, null, request.BirthDateFa, request.Gender, request.PhoneNumber);
|
||
}
|
||
|
||
await _contractingPartyRepository.CreateAsync(legalContractingParty);
|
||
await _contractingPartyRepository.SaveChangesAsync();
|
||
|
||
return opration.Succcedded(legalContractingParty);
|
||
}
|
||
|
||
private async Task<OperationResult<PersonalContractingParty>> CreateRealContractingPartyEntity(
|
||
CreateInstitutionContractRealPartyRequest request, long representativeId, string address,
|
||
string city, string province)
|
||
{
|
||
var operation = new OperationResult<PersonalContractingParty>();
|
||
|
||
|
||
if (representativeId < 1)
|
||
return operation.Failed("لطفا معرف را انتخاب کنید");
|
||
|
||
if (_contractingPartyRepository.Exists(x => x.Nationalcode == request.NationalCode))
|
||
{
|
||
return operation.Failed("کد ملی وارد شده تکراری است");
|
||
}
|
||
|
||
var archiveCode = _contractingPartyRepository.GetLastNewArchiveCode();
|
||
|
||
if (request.NationalCode.NationalCodeValid() != "valid")
|
||
{
|
||
return operation.Failed("کد ملی وارد شده نا معتبر است");
|
||
}
|
||
|
||
var representative = _representativeRepository.GetDetails(representativeId);
|
||
|
||
if (representative == null)
|
||
return operation.Failed("معرف مورد نظر یافت نشد");
|
||
|
||
var personalContractingParty = new PersonalContractingParty(request.FName, request.LName,
|
||
request.NationalCode, request.IdNumber, "*", "*",
|
||
"حقیقی",
|
||
request.PhoneNumber, request.PhoneNumber, address, representativeId, representative.FullName, archiveCode,
|
||
province, city, null, null, null, null);
|
||
|
||
if (request.IsAuth)
|
||
{
|
||
personalContractingParty.Authentication(request.FName, request.LName, request.FatherName,
|
||
request.IdNumber, null, null, request.BirthDateFa, request.Gender, request.PhoneNumber);
|
||
}
|
||
|
||
await _contractingPartyRepository.CreateAsync(personalContractingParty);
|
||
await _contractingPartyRepository.SaveChangesAsync();
|
||
|
||
return operation.Succcedded(personalContractingParty);
|
||
}
|
||
|
||
public static List<InstitutionContractInstallment> CalculateInstallment(double amount, int installmentCount,
|
||
string loanStartDate, bool getRounded)
|
||
{
|
||
int day = Convert.ToInt32(loanStartDate.Substring(8, 2));
|
||
int month = Convert.ToInt32(loanStartDate.Substring(5, 2));
|
||
int year = Convert.ToInt32(loanStartDate.Substring(0, 4));
|
||
|
||
var installments = new List<InstitutionContractInstallment>();
|
||
|
||
|
||
bool endOfMonth = day == 31;
|
||
|
||
|
||
var dividedAmount = amount / installmentCount;
|
||
|
||
double moneyPerMonth = 0;
|
||
|
||
if (getRounded)
|
||
moneyPerMonth = Math.Floor(dividedAmount / 1000) * 1000;
|
||
else
|
||
moneyPerMonth = Math.Floor(dividedAmount);
|
||
|
||
double lastLoan = amount - (moneyPerMonth * (installmentCount - 1));
|
||
|
||
if (endOfMonth)
|
||
{
|
||
for (int i = 1; i < installmentCount; i++)
|
||
{
|
||
var installment =
|
||
new InstitutionContractInstallment(loanStartDate.ToGeorgianDateTime(), moneyPerMonth, "");
|
||
|
||
installments.Add(installment);
|
||
|
||
if (month == 12)
|
||
{
|
||
year++;
|
||
month = 1;
|
||
}
|
||
else
|
||
{
|
||
month++;
|
||
}
|
||
|
||
loanStartDate = $"{year:0000}/{month:00}/01".FindeEndOfMonth();
|
||
}
|
||
|
||
var lastInstallment = new InstitutionContractInstallment(loanStartDate.ToGeorgianDateTime(), lastLoan, "");
|
||
|
||
installments.Add(lastInstallment);
|
||
return installments;
|
||
}
|
||
else
|
||
{
|
||
for (int i = 1; i < installmentCount; i++)
|
||
{
|
||
var installment =
|
||
new InstitutionContractInstallment(loanStartDate.ToGeorgianDateTime(), moneyPerMonth, "");
|
||
|
||
installments.Add(installment);
|
||
var endDay = 0;
|
||
|
||
if (month == 12)
|
||
{
|
||
year++;
|
||
month = 1;
|
||
}
|
||
else
|
||
{
|
||
month++;
|
||
}
|
||
|
||
if (day == 30)
|
||
{
|
||
if (month == 12)
|
||
{
|
||
var lastYearDay =
|
||
Convert.ToInt32($"{year:0000}/{month:00}/1".FindeEndOfMonth().Substring(8, 2));
|
||
endDay = lastYearDay == 30 ? lastYearDay : 29;
|
||
}
|
||
}
|
||
|
||
loanStartDate =
|
||
endDay == 0 ? $"{year:0000}/{month:00}/{day:00}" : $"{year:0000}/{month:00}/{endDay:00}";
|
||
}
|
||
|
||
var lastInstallment = new InstitutionContractInstallment(loanStartDate.ToGeorgianDateTime(), lastLoan, "");
|
||
installments.Add(lastInstallment);
|
||
return installments;
|
||
}
|
||
}
|
||
}
|
||
|
||
#region CustomViewModels
|
||
|
||
public class TotalbalancViewModel
|
||
{
|
||
public string TotalBalanceStr { get; set; } = "0";
|
||
public double TotalBalanceDbl { get; set; } = 0;
|
||
}
|
||
|
||
public class WorkshopsAndEmployeeViewModel
|
||
{
|
||
public List<WorkshopViewModel> WorkshopViewModels { get; set; }
|
||
public string WorkshopCount { get; set; }
|
||
public string EmployeeCount { get; set; }
|
||
public int ArchiveCode { get; set; }
|
||
}
|
||
|
||
#endregion
|
||
|