2228 lines
105 KiB
C#
2228 lines
105 KiB
C#
using _0_Framework.Application;
|
||
using _0_Framework.Application.Enums;
|
||
using _0_Framework.Application.Sms;
|
||
using _0_Framework.InfraStructure;
|
||
using Company.Domain.ContarctingPartyAgg;
|
||
using Company.Domain.InstitutionContractAgg;
|
||
using Company.Domain.SmsResultAgg;
|
||
using CompanyManagment.App.Contracts.Hubs;
|
||
using CompanyManagment.App.Contracts.InstitutionContract;
|
||
using CompanyManagment.App.Contracts.InstitutionContractContactinfo;
|
||
using CompanyManagment.EFCore.Migrations;
|
||
using Microsoft.AspNetCore.SignalR;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using Microsoft.Extensions.Logging;
|
||
using PersianTools.Core;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Diagnostics;
|
||
using System.Linq;
|
||
using System.Text;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace CompanyManagment.EFCore.Repository;
|
||
|
||
public class InstitutionContractSmsServiceRepository : RepositoryBase<long, InstitutionContract>, IInstitutionContractSmsServiceRepository
|
||
{
|
||
private readonly CompanyContext _context;
|
||
private readonly ILogger<InstitutionContractSmsServiceRepository> _logger;
|
||
private readonly ISmsService _smsService;
|
||
private readonly ISmsResultRepository _smsResultRepository;
|
||
private readonly IHubContext<SendSmsHub> _hubContext;
|
||
private readonly IPersonalContractingPartyRepository _personalContractingPartyRepository;
|
||
private readonly IAuthHelper _authHelper;
|
||
|
||
public InstitutionContractSmsServiceRepository(CompanyContext context, ISmsService smsService, ILogger<InstitutionContractSmsServiceRepository> logger, ISmsResultRepository smsResultRepository, IHubContext<SendSmsHub> hubContext, IPersonalContractingPartyRepository personalContractingPartyRepository, IAuthHelper authHelper) : base(context)
|
||
{
|
||
_context = context;
|
||
_smsService = smsService;
|
||
_logger = logger;
|
||
_smsResultRepository = smsResultRepository;
|
||
_hubContext = hubContext;
|
||
_personalContractingPartyRepository = personalContractingPartyRepository;
|
||
_authHelper = authHelper;
|
||
}
|
||
|
||
//هشدار - اقدام قضائی
|
||
#region WarninSmsAndLegalActionSms
|
||
|
||
public async Task SendWarningOrLegalActionSmsTask(TypeOfSmsSetting typeOfSmsSetting)
|
||
{
|
||
var now = DateTime.Now;
|
||
|
||
|
||
// تبدیل تاریخ میلادی به شمسی
|
||
var persianNow = now.ToFarsi();
|
||
var persianEndOfMonth = int.Parse(persianNow.FindeEndOfMonth().Substring(8, 2));
|
||
var dayOfMonth = int.Parse(persianNow.Substring(8, 2));
|
||
var hour = now.Hour;
|
||
var minute = now.Minute;
|
||
var checkAnyToExecute = false;
|
||
|
||
//اگر آخرین روز ماه باشد
|
||
//اگر روز مثلا عدد روز 31 بود ولی آخرین روز ماه 30 بود
|
||
if (dayOfMonth == persianEndOfMonth)
|
||
{
|
||
checkAnyToExecute = await _context.SmsSettings
|
||
.AnyAsync(x =>
|
||
x.DayOfMonth >= dayOfMonth &&
|
||
x.TimeOfDay.Hours == hour &&
|
||
x.TimeOfDay.Minutes == minute &&
|
||
x.TypeOfSmsSetting == typeOfSmsSetting &&
|
||
x.IsActive
|
||
);
|
||
}
|
||
else
|
||
{
|
||
checkAnyToExecute = await _context.SmsSettings
|
||
.AnyAsync(x =>
|
||
x.DayOfMonth == dayOfMonth &&
|
||
x.TimeOfDay.Hours == hour &&
|
||
x.TimeOfDay.Minutes == minute &&
|
||
x.TypeOfSmsSetting == typeOfSmsSetting &&
|
||
x.IsActive
|
||
);
|
||
}
|
||
|
||
|
||
if (checkAnyToExecute)
|
||
{
|
||
|
||
var getSmsData = await GetWarningOrLegalActionSmsListData(typeOfSmsSetting);
|
||
await SendWarningOrLegalActionSms(getSmsData, typeOfSmsSetting);
|
||
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
///دریافت لیست پیامک قراداد های آبی بدهکار
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public async Task<List<SmsListData>> GetWarningOrLegalActionSmsListData(TypeOfSmsSetting typeOfSmsSetting)
|
||
{
|
||
var smsList = new List<SmsListData>();
|
||
var institutionContracts = await _context.InstitutionContractSet.AsQueryable().Select(x => new InstitutionContractViewModel
|
||
{
|
||
Id = x.id,
|
||
ContractingPartyId = x.ContractingPartyId,
|
||
ContractingPartyName = x.ContractingPartyName,
|
||
ContractStartGr = x.ContractStartGr,
|
||
ContractStartFa = x.ContractStartFa,
|
||
ContractEndGr = x.ContractEndGr,
|
||
ContractEndFa = x.ContractEndFa,
|
||
IsActiveString = x.IsActiveString,
|
||
ContractAmountDouble = x.ContractAmount,
|
||
OfficialCompany = x.OfficialCompany,
|
||
IsInstallment = x.IsInstallment,
|
||
VerificationStatus = x.VerificationStatus,
|
||
SigningType = x.SigningType,
|
||
}).Where(x => x.IsActiveString == "blue" &&
|
||
x.ContractAmountDouble > 0).GroupBy(x => x.ContractingPartyId).Select(x => x.First()).ToListAsync();
|
||
|
||
|
||
// قرارداد هایی که بطور یکجا پرداخت شده اند
|
||
var paidInFull = institutionContracts.Where(x =>
|
||
x.SigningType != InstitutionContractSigningType.Legacy && x.IsInstallment == false && x.SigningType != null).ToList();
|
||
|
||
//حذف قراداد هایی که یکجا پرداخت شده اند از لیست ایجاد سند ماهانه
|
||
institutionContracts = institutionContracts.Except(paidInFull).ToList();
|
||
|
||
var contractingPartyList = await _context.PersonalContractingParties
|
||
.Where(x => institutionContracts.Select(ins => ins.ContractingPartyId).Contains(x.id)).ToListAsync();
|
||
|
||
var financialStatmentList = await _context.FinancialStatments.AsSplitQuery()
|
||
.Where(x => institutionContracts.Select(ins => ins.ContractingPartyId).Contains(x.ContractingPartyId))
|
||
.Include(x => x.FinancialTransactionList).Where(x => x.FinancialTransactionList.Count > 0).ToListAsync();
|
||
|
||
var phoneNumberList = await _context.InstitutionContractContactInfos
|
||
.Where(x => institutionContracts.Select(ins => ins.Id).Contains(x.InstitutionContractId))
|
||
.Where(x => x.SendSms && x.PhoneType == "شماره همراه" && !string.IsNullOrWhiteSpace(x.PhoneNumber) &&
|
||
x.PhoneNumber.Length == 11).ToListAsync();
|
||
var legalActionSentSms = await _context.SmsResults
|
||
.Where(x => x.TypeOfSms == "اقدام قضایی").AsNoTracking().ToListAsync();
|
||
|
||
|
||
var oldInstitutionContract = institutionContracts.Where(x => x.IsInstallment == false).ToList();
|
||
var electronicInstitutionContract = institutionContracts.Where(x => x.IsInstallment == true).ToList();
|
||
|
||
foreach (var item in oldInstitutionContract)
|
||
{
|
||
try
|
||
{
|
||
var contractingParty = contractingPartyList.FirstOrDefault(x => x.id == item.ContractingPartyId);
|
||
bool hasLegalActionSentSms = legalActionSentSms.Any(x => x.InstitutionContractId == item.Id);
|
||
int year = Convert.ToInt32(item.ContractEndFa.Substring(0, 4));
|
||
int month = Convert.ToInt32(item.ContractEndFa.Substring(5, 2));
|
||
var endOfContractNextMonthStart = new PersianDateTime(year, month, 1).AddMonths(1);
|
||
var endOfContractNextMonthEnd = (($"{endOfContractNextMonthStart}").FindeEndOfMonth()).ToGeorgianDateTime();
|
||
var now = DateTime.Now;
|
||
bool executeCondition = false;
|
||
|
||
switch (typeOfSmsSetting)
|
||
{
|
||
case TypeOfSmsSetting.Warning:
|
||
executeCondition = !hasLegalActionSentSms && now.Date <= endOfContractNextMonthEnd.Date;
|
||
|
||
break;
|
||
case TypeOfSmsSetting.LegalAction:
|
||
executeCondition = !hasLegalActionSentSms && now.Date > endOfContractNextMonthEnd.Date;
|
||
break;
|
||
}
|
||
|
||
if (!string.IsNullOrWhiteSpace(contractingParty.LName) && executeCondition)
|
||
{
|
||
//Thread.Sleep(500);x.IsLegal == "حقیقی" ? $"{x.FName.Trim()} {x.LName.Trim()}" : $"{x.LName.Trim()}"
|
||
var partyName = contractingParty.IsLegal == "حقیقی"
|
||
? $"{contractingParty.FName} {contractingParty.LName}"
|
||
: $"{contractingParty.LName}";
|
||
if (!string.IsNullOrWhiteSpace(contractingParty.SureName))
|
||
partyName = $"{partyName} ({contractingParty.SureName})";
|
||
|
||
if (partyName.Length > 25) partyName = $"{partyName.Substring(0, 25)}";
|
||
|
||
var isLegal = contractingParty.IsLegal == "حقوقی" ? true : false;
|
||
//var isBlock = contractingParty.IsBlock == "true" ? true : false;
|
||
//var isActive = contractingParty.IsActiveString == "true" ? true : false;
|
||
|
||
|
||
var hasFinancialStatement =
|
||
financialStatmentList.Any(x => x.ContractingPartyId == item.ContractingPartyId);
|
||
|
||
var hasPhonNumber = phoneNumberList.Any(x => x.InstitutionContractId == item.Id);
|
||
|
||
if (hasFinancialStatement && hasPhonNumber)
|
||
{
|
||
var phoneNumbers = phoneNumberList.Where(x => x.InstitutionContractId == item.Id)
|
||
.Select(x => new CreateContactInfo
|
||
{
|
||
PhoneType = x.PhoneType,
|
||
PhoneNumber = x.PhoneNumber,
|
||
|
||
InstitutionContractId = x.InstitutionContractId,
|
||
SendSms = x.SendSms
|
||
}).Where(x => x.PhoneNumber.Length == 11).ToList();
|
||
|
||
var transactions = financialStatmentList.FirstOrDefault(x =>
|
||
x.ContractingPartyId == item.ContractingPartyId);
|
||
|
||
|
||
var debtor = transactions.FinancialTransactionList.Sum(x => x.Deptor);
|
||
var creditor = transactions.FinancialTransactionList.Sum(x => x.Creditor);
|
||
|
||
|
||
//var id = $"{item.ContractingPartyId}";
|
||
var aprove = $"{transactions.id}";
|
||
var balance = debtor - creditor;
|
||
|
||
if (balance > 0) // اگر بدهکار بود
|
||
{
|
||
|
||
if (isLegal)
|
||
{
|
||
if (item.OfficialCompany == "Official") // حقوقی بدهکار رسمی
|
||
{
|
||
var balanceToMoney = balance.ToMoney();
|
||
|
||
foreach (var number in phoneNumbers)
|
||
{
|
||
|
||
|
||
|
||
if (!string.IsNullOrWhiteSpace(number.PhoneNumber) &&
|
||
number.PhoneNumber.Length == 11)
|
||
{
|
||
|
||
//var smsResult = _smsService.MonthlyBill(number.PhoneNumber, 608443,
|
||
// partyName,
|
||
// balanceToMoney, id, aprove);
|
||
//Thread.Sleep(1000);
|
||
//if (smsResult.IsSuccedded)
|
||
//{
|
||
// var createSmsResult = new SmsResult(smsResult.MessageId,
|
||
// smsResult.Message, typeOfSms, partyName, number.PhoneNumber,
|
||
// item.ContractingPartyId, item.Id);
|
||
// _smsResultRepository.Create(createSmsResult);
|
||
// _smsResultRepository.SaveChanges();
|
||
// Thread.Sleep(1000);
|
||
//}
|
||
|
||
|
||
smsList.Add(new SmsListData()
|
||
{
|
||
PhoneNumber = number.PhoneNumber,
|
||
TemplateId = typeOfSmsSetting == TypeOfSmsSetting.Warning ? 608443 : 313520,
|
||
PartyName = partyName,
|
||
Amount = balanceToMoney,
|
||
ContractingPartyId = contractingParty.id,
|
||
AproveId = aprove,
|
||
TypeOfSmsMethod = "MonthlyBill",
|
||
Code1 = "",
|
||
Code2 = "",
|
||
InstitutionContractId = item.Id
|
||
});
|
||
}
|
||
}
|
||
|
||
|
||
|
||
}
|
||
else if (item.OfficialCompany == "NotOfficial") // حقوقی بدهکار غیر رسمی
|
||
{
|
||
var balanceToMoney = balance.ToMoney();
|
||
foreach (var number in phoneNumbers)
|
||
{
|
||
|
||
if (!string.IsNullOrWhiteSpace(number.PhoneNumber) &&
|
||
number.PhoneNumber.Length == 11)
|
||
{
|
||
|
||
//var smsResult = _smsService.MonthlyBill(number.PhoneNumber, 351691,
|
||
// partyName,
|
||
// balanceToMoney, id, aprove);
|
||
//Thread.Sleep(1000);
|
||
//if (smsResult.IsSuccedded)
|
||
//{
|
||
// var createSmsResult = new SmsResult(smsResult.MessageId,
|
||
// smsResult.Message, typeOfSms, partyName, number.PhoneNumber,
|
||
// item.ContractingPartyId, item.Id);
|
||
// _smsResultRepository.Create(createSmsResult);
|
||
// _smsResultRepository.SaveChanges();
|
||
// Thread.Sleep(1000);
|
||
//}
|
||
|
||
smsList.Add(new SmsListData()
|
||
{
|
||
PhoneNumber = number.PhoneNumber,
|
||
TemplateId = typeOfSmsSetting == TypeOfSmsSetting.Warning ? 351691 : 181540,
|
||
PartyName = partyName,
|
||
Amount = balanceToMoney,
|
||
ContractingPartyId = contractingParty.id,
|
||
AproveId = aprove,
|
||
TypeOfSmsMethod = "MonthlyBill",
|
||
Code1 = "",
|
||
Code2 = "",
|
||
InstitutionContractId = item.Id
|
||
});
|
||
|
||
}
|
||
}
|
||
|
||
|
||
}
|
||
}
|
||
else
|
||
{
|
||
if (item.OfficialCompany == "Official") // حقیقی بدهکار رسمی
|
||
{
|
||
var balanceToMoney = balance.ToMoney();
|
||
|
||
foreach (var number in phoneNumbers)
|
||
{
|
||
|
||
if (!string.IsNullOrWhiteSpace(number.PhoneNumber) &&
|
||
number.PhoneNumber.Length == 11)
|
||
{
|
||
|
||
//var smsResult = _smsService.MonthlyBill(number.PhoneNumber, 190430,
|
||
// partyName,
|
||
// balanceToMoney, id, aprove);
|
||
//Thread.Sleep(1000);
|
||
//if (smsResult.IsSuccedded)
|
||
//{
|
||
// var createSmsResult = new SmsResult(smsResult.MessageId,
|
||
// smsResult.Message, typeOfSms, partyName, number.PhoneNumber,
|
||
// item.ContractingPartyId, item.Id);
|
||
// _smsResultRepository.Create(createSmsResult);
|
||
// _smsResultRepository.SaveChanges();
|
||
// Thread.Sleep(1000);
|
||
//}
|
||
|
||
smsList.Add(new SmsListData()
|
||
{
|
||
PhoneNumber = number.PhoneNumber,
|
||
TemplateId = typeOfSmsSetting == TypeOfSmsSetting.Warning ? 190430 : 478695,
|
||
PartyName = partyName,
|
||
Amount = balanceToMoney,
|
||
ContractingPartyId = contractingParty.id,
|
||
AproveId = aprove,
|
||
TypeOfSmsMethod = "MonthlyBill",
|
||
Code1 = "",
|
||
Code2 = "",
|
||
InstitutionContractId = item.Id
|
||
});
|
||
}
|
||
|
||
|
||
}
|
||
|
||
|
||
}
|
||
else if (item.OfficialCompany == "NotOfficial") // حقیقی بدهکار غیر رسمی
|
||
{
|
||
var balanceToMoney = balance.ToMoney();
|
||
|
||
foreach (var number in phoneNumbers)
|
||
{
|
||
|
||
if (!string.IsNullOrWhiteSpace(number.PhoneNumber) &&
|
||
number.PhoneNumber.Length == 11)
|
||
{
|
||
//var smsResult = _smsService.MonthlyBill(number.PhoneNumber, 412829,
|
||
// partyName,
|
||
// balanceToMoney, id, aprove);
|
||
//Thread.Sleep(1000);
|
||
//if (smsResult.IsSuccedded)
|
||
//{
|
||
// var createSmsResult = new SmsResult(smsResult.MessageId,
|
||
// smsResult.Message, typeOfSms, partyName, number.PhoneNumber,
|
||
// item.ContractingPartyId, item.Id);
|
||
// _smsResultRepository.Create(createSmsResult);
|
||
// _smsResultRepository.SaveChanges();
|
||
// Thread.Sleep(1000);
|
||
//}
|
||
|
||
smsList.Add(new SmsListData()
|
||
{
|
||
PhoneNumber = number.PhoneNumber,
|
||
TemplateId = typeOfSmsSetting == TypeOfSmsSetting.Warning ? 412829 : 147971,
|
||
PartyName = partyName,
|
||
Amount = balanceToMoney,
|
||
ContractingPartyId = contractingParty.id,
|
||
AproveId = aprove,
|
||
TypeOfSmsMethod = "MonthlyBill",
|
||
Code1 = "",
|
||
Code2 = "",
|
||
InstitutionContractId = item.Id
|
||
});
|
||
}
|
||
}
|
||
|
||
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
|
||
|
||
string name = item.ContractingPartyName.Length > 18 ? item.ContractingPartyName.Substring(0, 18) : item.ContractingPartyName;
|
||
string errMess = $"{name}-خطا";
|
||
_smsService.Alarm("09114221321", errMess);
|
||
_logger.LogError(e, "BlueWarningSms");
|
||
}
|
||
}
|
||
|
||
|
||
foreach (var item in electronicInstitutionContract)
|
||
{
|
||
try
|
||
{
|
||
var contractingParty = contractingPartyList.FirstOrDefault(x => x.id == item.ContractingPartyId);
|
||
bool hasLegalActionSentSms = legalActionSentSms.Any(x => x.InstitutionContractId == item.Id);
|
||
int year = Convert.ToInt32(item.ContractEndFa.Substring(0, 4));
|
||
int month = Convert.ToInt32(item.ContractEndFa.Substring(5, 2));
|
||
var endOfContractNextMonthStart = new PersianDateTime(year, month, 1).AddMonths(1);
|
||
var endOfContractNextMonthEnd = (($"{endOfContractNextMonthStart}").FindeEndOfMonth()).ToGeorgianDateTime();
|
||
var now = DateTime.Now;
|
||
|
||
bool executeCondition = false;
|
||
|
||
switch (typeOfSmsSetting)
|
||
{
|
||
case TypeOfSmsSetting.Warning:
|
||
executeCondition = !hasLegalActionSentSms && now.Date <= endOfContractNextMonthEnd.Date;
|
||
|
||
break;
|
||
case TypeOfSmsSetting.LegalAction:
|
||
executeCondition = !hasLegalActionSentSms && now.Date > endOfContractNextMonthEnd.Date;
|
||
break;
|
||
}
|
||
if (!string.IsNullOrWhiteSpace(contractingParty.LName) && executeCondition)
|
||
{
|
||
var partyName = contractingParty.IsLegal == "حقیقی"
|
||
? $"{contractingParty.FName} {contractingParty.LName}"
|
||
: $"{contractingParty.LName}";
|
||
if (!string.IsNullOrWhiteSpace(contractingParty.SureName))
|
||
partyName = $"{partyName} ({contractingParty.SureName})";
|
||
|
||
if (partyName.Length > 25) partyName = $"{partyName.Substring(0, 25)}";
|
||
|
||
//var isLegal = contractingParty.IsLegal == "حقوقی" ? true : false;
|
||
//var isBlock = contractingParty.IsBlock == "true" ? true : false;
|
||
//var isActive = contractingParty.IsActiveString == "true" ? true : false;
|
||
|
||
|
||
var hasFinancialStatement =
|
||
financialStatmentList.Any(x => x.ContractingPartyId == item.ContractingPartyId);
|
||
|
||
|
||
var hasPhonNumber = phoneNumberList.Any(x => x.InstitutionContractId == item.Id);
|
||
|
||
if (hasFinancialStatement && hasPhonNumber)
|
||
{
|
||
var phoneNumbers = phoneNumberList.Where(x => x.InstitutionContractId == item.Id)
|
||
.Select(x => new CreateContactInfo
|
||
{
|
||
PhoneType = x.PhoneType,
|
||
PhoneNumber = x.PhoneNumber,
|
||
|
||
InstitutionContractId = x.InstitutionContractId,
|
||
SendSms = x.SendSms
|
||
}).Where(x => x.PhoneNumber.Length == 11).ToList();
|
||
|
||
var transactions = financialStatmentList.FirstOrDefault(x =>
|
||
x.ContractingPartyId == item.ContractingPartyId);
|
||
|
||
var debtor = transactions.FinancialTransactionList.Sum(x => x.Deptor);
|
||
var creditor = transactions.FinancialTransactionList.Sum(x => x.Creditor);
|
||
|
||
|
||
//var id = $"{item.ContractingPartyId}";
|
||
var aprove = $"{transactions.id}";
|
||
var balance = debtor - creditor;
|
||
int templateId = 0;
|
||
//انتخاب قالب پیامک بر اساس حقیق/حقوقی
|
||
|
||
|
||
if (balance > 0) // اگر بدهکار بود
|
||
{
|
||
var balanceToMoney = balance.ToMoney();
|
||
|
||
foreach (var number in phoneNumbers)
|
||
{
|
||
string publicId = transactions.PublicIdStr;
|
||
string code1 = publicId.Substring(0, 25);
|
||
string code2 = publicId.Substring(25);
|
||
|
||
|
||
smsList.Add(new SmsListData()
|
||
{
|
||
PhoneNumber = number.PhoneNumber,
|
||
TemplateId = typeOfSmsSetting == TypeOfSmsSetting.Warning ? 530657 : 665145,
|
||
PartyName = partyName,
|
||
Amount = balanceToMoney,
|
||
ContractingPartyId = contractingParty.id,
|
||
AproveId = aprove,
|
||
TypeOfSmsMethod = "MonthlyBillNew",
|
||
Code1 = code1,
|
||
Code2 = code2,
|
||
InstitutionContractId = item.Id
|
||
});
|
||
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
_logger.LogError($"ContractingPartyId : {item.ContractingPartyId} - ContractingPartyName : {item.ContractingPartyName} - InstitutionContractId : {item.Id} خطای دریافت لیست بدهکاران ");
|
||
throw;
|
||
}
|
||
}
|
||
return smsList;
|
||
}
|
||
|
||
|
||
public async Task SendWarningOrLegalActionSms(List<SmsListData> smsListData, TypeOfSmsSetting typeOfSmsSetting)
|
||
{
|
||
//ارسال پیامک با اساس لیست
|
||
|
||
var typeOfSms = "";
|
||
|
||
switch (typeOfSmsSetting)
|
||
{
|
||
case TypeOfSmsSetting.Warning:
|
||
typeOfSms = "هشدار";
|
||
break;
|
||
case TypeOfSmsSetting.LegalAction:
|
||
typeOfSms = "اقدام قضایی";
|
||
break;
|
||
}
|
||
#region SendSMSFromList
|
||
|
||
if (smsListData.Any() && !string.IsNullOrWhiteSpace(typeOfSms))
|
||
{
|
||
|
||
|
||
// int successProcess = 1;
|
||
//int countList = smsListData.Count;
|
||
|
||
|
||
foreach (var item in smsListData)
|
||
{
|
||
try
|
||
{
|
||
if (item.TypeOfSmsMethod == "MonthlyBill")
|
||
{
|
||
var res = await _smsService.MonthlyBill(item.PhoneNumber, item.TemplateId, item.PartyName,
|
||
item.Amount,
|
||
$"{item.ContractingPartyId}", item.AproveId);
|
||
|
||
if (res.isSucceded)
|
||
{
|
||
var createSmsResult = new Company.Domain.SmsResultAgg.SmsResult(res.messaeId,
|
||
res.message, typeOfSms, item.PartyName, item.PhoneNumber,
|
||
item.ContractingPartyId, item.InstitutionContractId);
|
||
|
||
await _smsResultRepository.CreateAsync(createSmsResult);
|
||
await _smsResultRepository.SaveChangesAsync();
|
||
}
|
||
}
|
||
else
|
||
{
|
||
var res = await _smsService.MonthlyBillNew(item.PhoneNumber, item.TemplateId, item.PartyName,
|
||
item.Amount, item.Code1, item.Code2);
|
||
if (res.isSucceded)
|
||
{
|
||
var createSmsResult = new Company.Domain.SmsResultAgg.SmsResult(res.messaeId,
|
||
res.message, typeOfSms, item.PartyName, item.PhoneNumber,
|
||
item.ContractingPartyId, item.InstitutionContractId);
|
||
|
||
await _smsResultRepository.CreateAsync(createSmsResult);
|
||
await _smsResultRepository.SaveChangesAsync();
|
||
}
|
||
}
|
||
|
||
Thread.Sleep(600);
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
string name = item.PartyName.Length > 18 ? item.PartyName.Substring(0, 18) : item.PartyName;
|
||
string errMess = $"{name}-خطا";
|
||
_logger.LogError(errMess);
|
||
await _smsService.Alarm("09114221321", errMess);
|
||
}
|
||
|
||
//var percent = (successProcess / (double)countList) * 100;
|
||
//await _hubContext.Clients.Group(SendSmsHub.GetGroupName(7))
|
||
//.SendAsync("showStatus", (int)percent);
|
||
|
||
// successProcess += 1;
|
||
}
|
||
|
||
|
||
|
||
}
|
||
|
||
#endregion
|
||
}
|
||
|
||
#endregion
|
||
|
||
//بلاک - آنبلاک - پیامک بلاک
|
||
#region Block
|
||
|
||
/// <summary>
|
||
/// پیامک بلاک
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public async Task SendBlockSmsForBackgroundTask()
|
||
{
|
||
var now = DateTime.Now;
|
||
|
||
|
||
// تبدیل تاریخ میلادی به شمسی
|
||
var persianNow = now.ToFarsi();
|
||
var persianEndOfMonth = int.Parse(persianNow.FindeEndOfMonth().Substring(8, 2));
|
||
var dayOfMonth = int.Parse(persianNow.Substring(8, 2));
|
||
var hour = now.Hour;
|
||
var minute = now.Minute;
|
||
var checkAnyToExecute = false;
|
||
|
||
//اگر آخرین روز ماه باشد
|
||
//اگر روز مثلا عدد روز 31 بود ولی آخرین روز ماه 30 بود
|
||
if (dayOfMonth == persianEndOfMonth)
|
||
{
|
||
checkAnyToExecute = await _context.SmsSettings
|
||
.AnyAsync(x =>
|
||
x.DayOfMonth >= dayOfMonth &&
|
||
x.TimeOfDay.Hours == hour &&
|
||
x.TimeOfDay.Minutes == minute &&
|
||
x.TypeOfSmsSetting == TypeOfSmsSetting.BlockContractingParty &&
|
||
x.IsActive
|
||
);
|
||
}
|
||
else
|
||
{
|
||
checkAnyToExecute = await _context.SmsSettings
|
||
.AnyAsync(x =>
|
||
x.DayOfMonth == dayOfMonth &&
|
||
x.TimeOfDay.Hours == hour &&
|
||
x.TimeOfDay.Minutes == minute &&
|
||
x.TypeOfSmsSetting == TypeOfSmsSetting.BlockContractingParty &&
|
||
x.IsActive
|
||
);
|
||
}
|
||
|
||
|
||
if (checkAnyToExecute)
|
||
{
|
||
//اجرای تسک
|
||
|
||
//دریافت لیست بدهکاران
|
||
var smsListData = await GetBlockListData(now);
|
||
string typeOfSms = "اعلام مسدودی طرف حساب";
|
||
string sendMessStart = "شروع پیامک مسدودی";
|
||
string sendMessEnd = "پایان پیامک مسدودی";
|
||
//ارسال پیامک
|
||
|
||
await SendBlockSmsToContractingParties(smsListData, typeOfSms, sendMessStart, sendMessEnd);
|
||
|
||
Console.WriteLine("executed at : " + persianNow + " - " + hour + ":" + minute);
|
||
}
|
||
}
|
||
|
||
|
||
public async Task<List<BlockSmsListData>> GetBlockListData(DateTime checkDate)
|
||
{
|
||
var smsList = new List<BlockSmsListData>();
|
||
|
||
var institutionContracts = await _context.InstitutionContractSet
|
||
.Include(x => x.Installments)
|
||
.Select(x => new InstitutionContractViewModel
|
||
{
|
||
Id = x.id,
|
||
ContractingPartyId = x.ContractingPartyId,
|
||
ContractingPartyName = x.ContractingPartyName,
|
||
ContractStartGr = x.ContractStartGr,
|
||
ContractStartFa = x.ContractStartFa,
|
||
ContractEndGr = x.ContractEndGr,
|
||
ContractEndFa = x.ContractEndFa,
|
||
IsActiveString = x.IsActiveString,
|
||
ContractAmountDouble = x.ContractAmount,
|
||
OfficialCompany = x.OfficialCompany,
|
||
IsInstallment = x.IsInstallment,
|
||
VerificationStatus = x.VerificationStatus,
|
||
SigningType = x.SigningType,
|
||
InstallmentList = x.Installments
|
||
.Select(ins => new InstitutionContractInstallmentViewModel
|
||
{ AmountDouble = ins.Amount, InstallmentDateGr = ins.InstallmentDateGr })
|
||
.OrderBy(ins => ins.InstallmentDateGr).Skip(1).ToList(),
|
||
}).Where(x => x.ContractStartGr < checkDate && x.ContractEndGr >= checkDate &&
|
||
x.ContractAmountDouble > 0 && x.VerificationStatus != InstitutionContractVerificationStatus.PendingForVerify).GroupBy(x => x.ContractingPartyId).Select(x => x.First())
|
||
.ToListAsync();
|
||
|
||
// قرارداد هایی که بطور یکجا پرداخت شده اند
|
||
var paidInFull = institutionContracts.Where(x =>
|
||
x.SigningType != InstitutionContractSigningType.Legacy && x.IsInstallment == false && x.SigningType != null).ToList();
|
||
|
||
//حذف قراداد هایی که یکجا پرداخت شده اند از لیست ایجاد سند ماهانه
|
||
institutionContracts = institutionContracts.Except(paidInFull).ToList();
|
||
|
||
var contractingPartyList = await _context.PersonalContractingParties
|
||
.Where(x => institutionContracts.Select(ins => ins.ContractingPartyId).Contains(x.id)).ToListAsync();
|
||
|
||
var financialStatmentList = await _context.FinancialStatments.AsSplitQuery()
|
||
.Where(x => institutionContracts.Select(ins => ins.ContractingPartyId).Contains(x.ContractingPartyId))
|
||
.Include(x => x.FinancialTransactionList).Where(x => x.FinancialTransactionList.Count > 0).ToListAsync();
|
||
|
||
var phoneNumberList = await _context.InstitutionContractContactInfos
|
||
.Where(x => institutionContracts.Select(ins => ins.Id).Contains(x.InstitutionContractId))
|
||
.Where(x => x.SendSms && x.PhoneType == "شماره همراه" && !string.IsNullOrWhiteSpace(x.PhoneNumber) &&
|
||
x.PhoneNumber.Length == 11).ToListAsync();
|
||
var oldInstitutionContract = institutionContracts.Where(x => x.IsInstallment == false).ToList();
|
||
var electronicInstitutionContract = institutionContracts.Where(x => x.IsInstallment == true).ToList();
|
||
foreach (var item in oldInstitutionContract)
|
||
{
|
||
try
|
||
{
|
||
var contractingParty = contractingPartyList.FirstOrDefault(x => x.id == item.ContractingPartyId);
|
||
if (contractingParty != null && contractingParty.IsBlock == "true")
|
||
{
|
||
var partyName = contractingParty.IsLegal == "حقیقی"
|
||
? $"{contractingParty.FName} {contractingParty.LName}"
|
||
: $"{contractingParty.LName}";
|
||
if (!string.IsNullOrWhiteSpace(contractingParty.SureName))
|
||
partyName = $"{partyName} ({contractingParty.SureName})";
|
||
|
||
if (partyName.Length > 25) partyName = $"{partyName.Substring(0, 25)}";
|
||
|
||
var isLegal = contractingParty.IsLegal == "حقوقی" ? true : false;
|
||
|
||
var hasFinancialStatment =
|
||
financialStatmentList.Any(x =>
|
||
x.ContractingPartyId == item.ContractingPartyId & x.FinancialTransactionList.Count > 0);
|
||
|
||
|
||
var hasPhonNumber = phoneNumberList.Any(x => x.InstitutionContractId == item.Id);
|
||
|
||
|
||
if (hasFinancialStatment && hasPhonNumber)
|
||
{
|
||
var transactions =
|
||
financialStatmentList.FirstOrDefault(x => x.ContractingPartyId == item.ContractingPartyId);
|
||
|
||
var debtor = transactions.FinancialTransactionList.Sum(x => x.Deptor);
|
||
var creditor = transactions.FinancialTransactionList.Sum(x => x.Creditor);
|
||
|
||
|
||
var id = $"{item.ContractingPartyId}";
|
||
var aprove = $"{transactions.id}";
|
||
var balance = debtor - creditor;
|
||
if (balance > 0)
|
||
{
|
||
var jobRelation = "بابت قرارداد مابین (روابط کار)";
|
||
var taxAndFinancial = "بابت قرارداد مابین (حسابداری و مالیات)";
|
||
|
||
|
||
var jobRelationContract = transactions.FinancialTransactionList
|
||
.OrderByDescending(x => x.TdateGr).FirstOrDefault(x =>
|
||
x.TypeOfTransaction == "debt" && x.DescriptionOption == jobRelation);
|
||
var taxAndFinancialContract = transactions.FinancialTransactionList
|
||
.OrderByDescending(x => x.TdateGr).FirstOrDefault(x =>
|
||
x.TypeOfTransaction == "debt" && x.DescriptionOption == taxAndFinancial);
|
||
|
||
var jobRelationContractAmounts =
|
||
jobRelationContract != null ? jobRelationContract.Deptor : 0;
|
||
var taxAndFinancialContractAmounts =
|
||
taxAndFinancialContract != null ? taxAndFinancialContract.Deptor : 0;
|
||
|
||
var sumOfAmounts = jobRelationContractAmounts * 2 + taxAndFinancialContractAmounts * 2;
|
||
if (balance >= sumOfAmounts)
|
||
{
|
||
var phoneNumbers = new List<CreateContactInfo>();
|
||
phoneNumbers = phoneNumberList.Where(x => x.InstitutionContractId == item.Id)
|
||
.Select(x => new CreateContactInfo
|
||
{
|
||
PhoneType = x.PhoneType,
|
||
PhoneNumber = x.PhoneNumber,
|
||
|
||
InstitutionContractId = x.InstitutionContractId,
|
||
SendSms = x.SendSms
|
||
}).Where(x => x.PhoneNumber.Length == 11).ToList();
|
||
|
||
|
||
var accountType = item.OfficialCompany == "Official" ? "ol" : "nol";
|
||
|
||
var balanceToMoney = balance.ToMoney();
|
||
var amount = balanceToMoney + " " + "ریال" + " ";
|
||
foreach (var number in phoneNumbers)
|
||
{
|
||
smsList.Add(new BlockSmsListData()
|
||
{
|
||
PhoneNumber = number.PhoneNumber,
|
||
PartyName = partyName,
|
||
AccountType = accountType,
|
||
Amount = amount,
|
||
ContractingPartyId = contractingParty.id,
|
||
InstitutionContractId = item.Id,
|
||
AproveId = aprove,
|
||
IsElectronicContract = false,
|
||
Code1 = "",
|
||
Code2 = "",
|
||
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
string name = item.ContractingPartyName.Length > 18
|
||
? item.ContractingPartyName.Substring(0, 18)
|
||
: item.ContractingPartyName;
|
||
string errMess = $"{name}-خطا";
|
||
await _smsService.Alarm("09114221321", errMess);
|
||
}
|
||
}
|
||
|
||
foreach (var item in electronicInstitutionContract)
|
||
{
|
||
try
|
||
{
|
||
var contractingParty = contractingPartyList.FirstOrDefault(x => x.id == item.ContractingPartyId);
|
||
if (contractingParty != null && contractingParty.IsBlock == "true")
|
||
{
|
||
var partyName = contractingParty.IsLegal == "حقیقی"
|
||
? $"{contractingParty.FName} {contractingParty.LName}"
|
||
: $"{contractingParty.LName}";
|
||
if (!string.IsNullOrWhiteSpace(contractingParty.SureName))
|
||
partyName = $"{partyName} ({contractingParty.SureName})";
|
||
|
||
if (partyName.Length > 25) partyName = $"{partyName.Substring(0, 25)}";
|
||
|
||
var isLegal = contractingParty.IsLegal == "حقوقی" ? true : false;
|
||
|
||
var hasFinancialStatment =
|
||
financialStatmentList.Any(x =>
|
||
x.ContractingPartyId == item.ContractingPartyId & x.FinancialTransactionList.Count > 0);
|
||
|
||
|
||
var hasPhonNumber = phoneNumberList.Any(x => x.InstitutionContractId == item.Id);
|
||
|
||
|
||
if (hasFinancialStatment && hasPhonNumber)
|
||
{
|
||
var transactions =
|
||
financialStatmentList.FirstOrDefault(x => x.ContractingPartyId == item.ContractingPartyId);
|
||
|
||
var debtor = transactions.FinancialTransactionList.Sum(x => x.Deptor);
|
||
var creditor = transactions.FinancialTransactionList.Sum(x => x.Creditor);
|
||
|
||
|
||
var id = $"{item.ContractingPartyId}";
|
||
var aprove = $"{transactions.id}";
|
||
var balance = debtor - creditor;
|
||
if (balance > 0)
|
||
{
|
||
|
||
var instalment = item.InstallmentList
|
||
.FirstOrDefault().AmountDouble;
|
||
|
||
var sumOfAmounts = instalment * 2;
|
||
if (balance >= sumOfAmounts)
|
||
{
|
||
var phoneNumbers = new List<CreateContactInfo>();
|
||
phoneNumbers = phoneNumberList.Where(x => x.InstitutionContractId == item.Id)
|
||
.Select(x => new CreateContactInfo
|
||
{
|
||
PhoneType = x.PhoneType,
|
||
PhoneNumber = x.PhoneNumber,
|
||
|
||
InstitutionContractId = x.InstitutionContractId,
|
||
SendSms = x.SendSms
|
||
}).Where(x => x.PhoneNumber.Length == 11).ToList();
|
||
|
||
|
||
var accountType = item.OfficialCompany == "Official" ? "ol" : "nol";
|
||
|
||
var balanceToMoney = balance.ToMoney();
|
||
var amount = balanceToMoney + " " + "ریال" + " ";
|
||
string publicId = transactions.PublicIdStr;
|
||
string code1 = publicId.Substring(0, 25);
|
||
string code2 = publicId.Substring(25);
|
||
foreach (var number in phoneNumbers)
|
||
{
|
||
|
||
smsList.Add(new BlockSmsListData()
|
||
{
|
||
PhoneNumber = number.PhoneNumber,
|
||
PartyName = partyName,
|
||
AccountType = accountType,
|
||
Amount = amount,
|
||
ContractingPartyId = contractingParty.id,
|
||
InstitutionContractId = item.Id,
|
||
AproveId = aprove,
|
||
IsElectronicContract = true,
|
||
Code1 = code1,
|
||
Code2 = code2
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
string name = item.ContractingPartyName.Length > 18
|
||
? item.ContractingPartyName.Substring(0, 18)
|
||
: item.ContractingPartyName;
|
||
string errMess = $"{name}-خطا";
|
||
await _smsService.Alarm("09114221321", errMess);
|
||
}
|
||
}
|
||
return smsList;
|
||
}
|
||
|
||
public async Task SendBlockSmsToContractingParties(List<BlockSmsListData> smsListData, string typeOfSms,
|
||
string sendMessStart, string sendMessEnd)
|
||
{
|
||
var currentAccountId = _authHelper.CurrentAccountId();
|
||
var signalR = _hubContext.Clients.Group(SendSmsHub.GetGroupName(currentAccountId));
|
||
if (smsListData.Any())
|
||
{
|
||
try
|
||
{
|
||
var sendingStart = await _smsService.Alarm("09114221321", sendMessStart);
|
||
Thread.Sleep(1000);
|
||
|
||
if (!sendingStart)
|
||
{
|
||
await signalR.SendAsync("sendToApi", "failed");
|
||
return;
|
||
}
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
await signalR.SendAsync("sendToApi", "failed");
|
||
return;
|
||
}
|
||
int successProcess = 1;
|
||
int countList = smsListData.Count;
|
||
|
||
foreach (var item in smsListData)
|
||
{
|
||
try
|
||
{
|
||
if (item.IsElectronicContract)
|
||
{
|
||
var smsResult = await _smsService.BlockMessageForElectronicContract(item.PhoneNumber, item.PartyName,
|
||
item.Amount, item.Code1, $"{item.Code2}");
|
||
Thread.Sleep(1000);
|
||
var createSmsResult = new Company.Domain.SmsResultAgg.SmsResult(smsResult.messaeId,
|
||
smsResult.message, typeOfSms,
|
||
item.PartyName, item.PhoneNumber, item.ContractingPartyId, item.InstitutionContractId);
|
||
await _smsResultRepository.CreateAsync(createSmsResult);
|
||
await _smsResultRepository.SaveChangesAsync();
|
||
await signalR.SendAsync("sendStatus", true, item.PhoneNumber);
|
||
}
|
||
else
|
||
{
|
||
var smsResult = await _smsService.BlockMessage(item.PhoneNumber, item.PartyName,
|
||
item.Amount, item.AccountType, $"{item.ContractingPartyId}", item.AproveId);
|
||
Thread.Sleep(1000);
|
||
var createSmsResult = new Company.Domain.SmsResultAgg.SmsResult(smsResult.messaeId,
|
||
smsResult.message, typeOfSms,
|
||
item.PartyName, item.PhoneNumber, item.ContractingPartyId, item.InstitutionContractId);
|
||
await _smsResultRepository.CreateAsync(createSmsResult);
|
||
await _smsResultRepository.SaveChangesAsync();
|
||
await signalR.SendAsync("sendStatus", true, item.PhoneNumber);
|
||
}
|
||
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
string name = item.PartyName.Length > 18 ? item.PartyName.Substring(0, 18) : item.PartyName;
|
||
string errMess = $"{name}-خطا";
|
||
await signalR.SendAsync("sendStatus", false, item.PhoneNumber);
|
||
await _smsService.Alarm("09114221321", errMess);
|
||
}
|
||
|
||
Thread.Sleep(600);
|
||
var percent = (successProcess / (double)countList) * 100;
|
||
await signalR.SendAsync("showStatus", (int)percent);
|
||
|
||
successProcess += 1;
|
||
}
|
||
|
||
|
||
await _smsService.Alarm("09114221321", sendMessEnd);
|
||
Thread.Sleep(1000);
|
||
await _smsService.Alarm("09111485044", sendMessEnd);
|
||
}
|
||
}
|
||
|
||
|
||
public async Task<List<long>> GetToBeBlockList(DateTime checkDate)
|
||
{
|
||
var contractingPartyIdList = new List<long>();
|
||
|
||
var institutionContracts = await _context.InstitutionContractSet.Where(x => x.IsActiveString == "true")
|
||
.Include(x => x.Installments)
|
||
.Select(x => new InstitutionContractViewModel
|
||
{
|
||
Id = x.id,
|
||
ContractingPartyId = x.ContractingPartyId,
|
||
ContractingPartyName = x.ContractingPartyName,
|
||
ContractStartGr = x.ContractStartGr,
|
||
ContractStartFa = x.ContractStartFa,
|
||
ContractEndGr = x.ContractEndGr,
|
||
ContractEndFa = x.ContractEndFa,
|
||
IsActiveString = x.IsActiveString,
|
||
ContractAmountDouble = x.ContractAmount,
|
||
OfficialCompany = x.OfficialCompany,
|
||
IsInstallment = x.IsInstallment,
|
||
VerificationStatus = x.VerificationStatus,
|
||
SigningType = x.SigningType,
|
||
InstallmentList = x.Installments
|
||
.Select(ins => new InstitutionContractInstallmentViewModel
|
||
{ AmountDouble = ins.Amount, InstallmentDateGr = ins.InstallmentDateGr })
|
||
.OrderBy(ins => ins.InstallmentDateGr).Skip(1).ToList(),
|
||
}).Where(x => x.ContractStartGr < checkDate && x.ContractEndGr >= checkDate &&
|
||
x.ContractAmountDouble > 0 && x.VerificationStatus != InstitutionContractVerificationStatus.PendingForVerify).GroupBy(x => x.ContractingPartyId).Select(x => x.First())
|
||
.ToListAsync();
|
||
|
||
// قرارداد هایی که بطور یکجا پرداخت شده اند
|
||
var paidInFull = institutionContracts.Where(x =>
|
||
x.SigningType != InstitutionContractSigningType.Legacy && x.IsInstallment == false && x.SigningType != null).ToList();
|
||
|
||
//حذف قراداد هایی که یکجا پرداخت شده اند از لیست ایجاد سند ماهانه
|
||
institutionContracts = institutionContracts.Except(paidInFull).ToList();
|
||
|
||
var contractingPartyList = await _context.PersonalContractingParties
|
||
.Where(x => institutionContracts.Select(ins => ins.ContractingPartyId).Contains(x.id)).ToListAsync();
|
||
|
||
var financialStatmentList = await _context.FinancialStatments.AsSplitQuery()
|
||
.Where(x => institutionContracts.Select(ins => ins.ContractingPartyId).Contains(x.ContractingPartyId))
|
||
.Include(x => x.FinancialTransactionList).Where(x => x.FinancialTransactionList.Count > 0).ToListAsync();
|
||
|
||
|
||
var oldInstitutionContract = institutionContracts.Where(x => x.IsInstallment == false).ToList();
|
||
var electronicInstitutionContract = institutionContracts.Where(x => x.IsInstallment == true).ToList();
|
||
foreach (var item in oldInstitutionContract)
|
||
{
|
||
try
|
||
{
|
||
var contractingParty = contractingPartyList.FirstOrDefault(x => x.id == item.ContractingPartyId);
|
||
if (contractingParty != null && contractingParty.IsBlock == "false" &&
|
||
contractingParty.IsActiveString == "true")
|
||
{
|
||
var transactions =
|
||
financialStatmentList.FirstOrDefault(x => x.ContractingPartyId == item.ContractingPartyId);
|
||
|
||
if (transactions != null)
|
||
{
|
||
var debtor = transactions.FinancialTransactionList.Sum(x => x.Deptor);
|
||
var creditor = transactions.FinancialTransactionList.Sum(x => x.Creditor);
|
||
|
||
|
||
|
||
var balance = debtor - creditor;
|
||
if (balance > 0)
|
||
{
|
||
var jobRelation = "بابت قرارداد مابین (روابط کار)";
|
||
var taxAndFinancial = "بابت قرارداد مابین (حسابداری و مالیات)";
|
||
|
||
|
||
var jobRelationContract = transactions.FinancialTransactionList
|
||
.OrderByDescending(x => x.TdateGr).FirstOrDefault(x =>
|
||
x.TypeOfTransaction == "debt" && x.DescriptionOption == jobRelation);
|
||
var taxAndFinancialContract = transactions.FinancialTransactionList
|
||
.OrderByDescending(x => x.TdateGr).FirstOrDefault(x =>
|
||
x.TypeOfTransaction == "debt" && x.DescriptionOption == taxAndFinancial);
|
||
|
||
var jobRelationContractAmounts =
|
||
jobRelationContract != null ? jobRelationContract.Deptor : 0;
|
||
var taxAndFinancialContractAmounts =
|
||
taxAndFinancialContract != null ? taxAndFinancialContract.Deptor : 0;
|
||
|
||
var sumOfAmounts = jobRelationContractAmounts * 2 + taxAndFinancialContractAmounts * 2;
|
||
if (balance >= sumOfAmounts)
|
||
{
|
||
contractingPartyIdList.Add(contractingParty.id);
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
}
|
||
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
string name = item.ContractingPartyName.Length > 18
|
||
? item.ContractingPartyName.Substring(0, 18)
|
||
: item.ContractingPartyName;
|
||
string errMess = $"{name}-خطا";
|
||
await _smsService.Alarm("09114221321", errMess);
|
||
}
|
||
}
|
||
|
||
foreach (var item in electronicInstitutionContract)
|
||
{
|
||
try
|
||
{
|
||
var contractingParty = contractingPartyList.FirstOrDefault(x => x.id == item.ContractingPartyId);
|
||
if (contractingParty != null && contractingParty.IsBlock == "false" &&
|
||
contractingParty.IsActiveString == "true")
|
||
{
|
||
|
||
var transactions =
|
||
financialStatmentList.FirstOrDefault(x => x.ContractingPartyId == item.ContractingPartyId);
|
||
if (transactions != null)
|
||
{
|
||
var debtor = transactions.FinancialTransactionList.Sum(x => x.Deptor);
|
||
var creditor = transactions.FinancialTransactionList.Sum(x => x.Creditor);
|
||
|
||
var balance = debtor - creditor;
|
||
if (balance > 0)
|
||
{
|
||
|
||
var instalment = item.InstallmentList
|
||
.FirstOrDefault()!.AmountDouble;
|
||
|
||
var sumOfAmounts = instalment * 2;
|
||
if (balance >= sumOfAmounts)
|
||
{
|
||
|
||
contractingPartyIdList.Add(contractingParty.id);
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
string name = item.ContractingPartyName.Length > 18
|
||
? item.ContractingPartyName.Substring(0, 18)
|
||
: item.ContractingPartyName;
|
||
string errMess = $"{name}-خطا";
|
||
await _smsService.Alarm("09114221321", errMess);
|
||
}
|
||
}
|
||
return contractingPartyIdList;
|
||
}
|
||
|
||
/// <summary>
|
||
/// بلاک سازی
|
||
/// </summary>
|
||
/// <param name="checkDate"></param>
|
||
/// <returns></returns>
|
||
public async Task Block(DateTime checkDate)
|
||
{
|
||
var toBeblockList = await GetToBeBlockList(checkDate);
|
||
|
||
foreach (var item in toBeblockList)
|
||
{
|
||
var res = _personalContractingPartyRepository.Get(item);
|
||
if (res != null)
|
||
{
|
||
res.Block();
|
||
|
||
}
|
||
}
|
||
if (toBeblockList.Any())
|
||
await _context.SaveChangesAsync();
|
||
}
|
||
|
||
/// <summary>
|
||
/// آنبلاک
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public async Task UnBlock()
|
||
{
|
||
var getBlockedParties = await _context.PersonalContractingParties
|
||
.Where(x => x.IsBlock == "true" && x.IsActiveString == "true").Select(x => x.id).ToArrayAsync();
|
||
var checkDate = DateTime.Now;
|
||
if (getBlockedParties.Any())
|
||
{
|
||
var institutionContracts = await _context.InstitutionContractSet.Where(x => getBlockedParties.Contains(x.ContractingPartyId))
|
||
.Include(x => x.Installments)
|
||
.Select(x => new InstitutionContractViewModel
|
||
{
|
||
Id = x.id,
|
||
ContractingPartyId = x.ContractingPartyId,
|
||
ContractingPartyName = x.ContractingPartyName,
|
||
ContractStartGr = x.ContractStartGr,
|
||
ContractStartFa = x.ContractStartFa,
|
||
ContractEndGr = x.ContractEndGr,
|
||
ContractEndFa = x.ContractEndFa,
|
||
IsActiveString = x.IsActiveString,
|
||
ContractAmountDouble = x.ContractAmount,
|
||
OfficialCompany = x.OfficialCompany,
|
||
IsInstallment = x.IsInstallment,
|
||
VerificationStatus = x.VerificationStatus,
|
||
SigningType = x.SigningType,
|
||
InstallmentList = x.Installments
|
||
.Select(ins => new InstitutionContractInstallmentViewModel
|
||
{ AmountDouble = ins.Amount, InstallmentDateGr = ins.InstallmentDateGr })
|
||
.OrderBy(ins => ins.InstallmentDateGr).Skip(1).ToList(),
|
||
}).Where(x => x.ContractStartGr < checkDate && x.ContractEndGr >= checkDate &&
|
||
x.ContractAmountDouble > 0 && x.VerificationStatus != InstitutionContractVerificationStatus.PendingForVerify).GroupBy(x => x.ContractingPartyId).Select(x => x.First())
|
||
.ToListAsync();
|
||
|
||
// قرارداد هایی که بطور یکجا پرداخت شده اند
|
||
var paidInFull = institutionContracts.Where(x =>
|
||
x.SigningType != InstitutionContractSigningType.Legacy && x.IsInstallment == false && x.SigningType != null).ToList();
|
||
|
||
//حذف قراداد هایی که یکجا پرداخت شده اند از لیست ایجاد سند ماهانه
|
||
institutionContracts = institutionContracts.Except(paidInFull).ToList();
|
||
|
||
var financialStatmentList = await _context.FinancialStatments.AsSplitQuery()
|
||
.Where(x => getBlockedParties.Contains(x.ContractingPartyId))
|
||
.Include(x => x.FinancialTransactionList).Where(x => x.FinancialTransactionList.Count > 0).ToListAsync();
|
||
|
||
var oldInstitutionContract = institutionContracts.Where(x => x.IsInstallment == false).ToList();
|
||
var electronicInstitutionContract = institutionContracts.Where(x => x.IsInstallment == true).ToList();
|
||
|
||
foreach (var item in oldInstitutionContract)
|
||
{
|
||
try
|
||
{
|
||
|
||
var transactions =
|
||
financialStatmentList.FirstOrDefault(x => x.ContractingPartyId == item.ContractingPartyId);
|
||
|
||
if (transactions != null)
|
||
{
|
||
var debtor = transactions.FinancialTransactionList.Sum(x => x.Deptor);
|
||
var creditor = transactions.FinancialTransactionList.Sum(x => x.Creditor);
|
||
|
||
|
||
|
||
var balance = debtor - creditor;
|
||
|
||
var jobRelation = "بابت قرارداد مابین (روابط کار)";
|
||
var taxAndFinancial = "بابت قرارداد مابین (حسابداری و مالیات)";
|
||
|
||
|
||
var jobRelationContract = transactions.FinancialTransactionList
|
||
.OrderByDescending(x => x.TdateGr).FirstOrDefault(x =>
|
||
x.TypeOfTransaction == "debt" && x.DescriptionOption == jobRelation);
|
||
var taxAndFinancialContract = transactions.FinancialTransactionList
|
||
.OrderByDescending(x => x.TdateGr).FirstOrDefault(x =>
|
||
x.TypeOfTransaction == "debt" && x.DescriptionOption == taxAndFinancial);
|
||
|
||
var jobRelationContractAmounts =
|
||
jobRelationContract != null ? jobRelationContract.Deptor : 0;
|
||
var taxAndFinancialContractAmounts =
|
||
taxAndFinancialContract != null ? taxAndFinancialContract.Deptor : 0;
|
||
|
||
var sumOfAmounts = jobRelationContractAmounts * 2 + taxAndFinancialContractAmounts * 2;
|
||
if (balance < sumOfAmounts)
|
||
{
|
||
var res = _personalContractingPartyRepository.Get(item.ContractingPartyId);
|
||
var blockTime = res.BlockTimes + 1;
|
||
res.DisableBlock(blockTime);
|
||
|
||
}
|
||
|
||
}
|
||
|
||
|
||
|
||
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
string name = item.ContractingPartyName.Length > 18
|
||
? item.ContractingPartyName.Substring(0, 18)
|
||
: item.ContractingPartyName;
|
||
string errMess = $"{name}-خطا";
|
||
await _smsService.Alarm("09114221321", errMess);
|
||
}
|
||
}
|
||
|
||
foreach (var item in electronicInstitutionContract)
|
||
{
|
||
try
|
||
{
|
||
|
||
|
||
var transactions =
|
||
financialStatmentList.FirstOrDefault(x => x.ContractingPartyId == item.ContractingPartyId);
|
||
if (transactions != null)
|
||
{
|
||
var debtor = transactions.FinancialTransactionList.Sum(x => x.Deptor);
|
||
var creditor = transactions.FinancialTransactionList.Sum(x => x.Creditor);
|
||
|
||
var balance = debtor - creditor;
|
||
|
||
|
||
var instalment = item.InstallmentList
|
||
.FirstOrDefault()!.AmountDouble;
|
||
|
||
var sumOfAmounts = instalment * 2;
|
||
if (balance < sumOfAmounts)
|
||
{
|
||
var res = _personalContractingPartyRepository.Get(item.ContractingPartyId);
|
||
var blockTime = res.BlockTimes + 1;
|
||
res.DisableBlock(blockTime);
|
||
|
||
|
||
}
|
||
|
||
}
|
||
|
||
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
string name = item.ContractingPartyName.Length > 18
|
||
? item.ContractingPartyName.Substring(0, 18)
|
||
: item.ContractingPartyName;
|
||
string errMess = $"{name}-خطا";
|
||
await _smsService.Alarm("09114221321", errMess);
|
||
}
|
||
}
|
||
|
||
|
||
await _context.SaveChangesAsync();
|
||
}
|
||
|
||
}
|
||
|
||
|
||
public async Task DeActiveInstitutionEndOfContract(DateTime checkDate)
|
||
{
|
||
var institutionContracts = await _context.InstitutionContractSet
|
||
.Where(x => (x.IsActiveString == "true" || x.IsActiveString == "blue") && (x.ContractEndGr.Date < checkDate.Date && x.VerificationStatus != InstitutionContractVerificationStatus.PendingForVerify))
|
||
.Include(x => x.Installments)
|
||
.Select(x => new InstitutionContractViewModel
|
||
{
|
||
Id = x.id,
|
||
ContractingPartyId = x.ContractingPartyId,
|
||
ContractingPartyName = x.ContractingPartyName,
|
||
ContractStartGr = x.ContractStartGr,
|
||
ContractStartFa = x.ContractStartFa,
|
||
ContractEndGr = x.ContractEndGr,
|
||
ContractEndFa = x.ContractEndFa,
|
||
IsActiveString = x.IsActiveString,
|
||
ContractAmountDouble = x.ContractAmount,
|
||
OfficialCompany = x.OfficialCompany,
|
||
IsInstallment = x.IsInstallment,
|
||
VerificationStatus = x.VerificationStatus,
|
||
SigningType = x.SigningType,
|
||
InstallmentList = x.Installments
|
||
.Select(ins => new InstitutionContractInstallmentViewModel
|
||
{ AmountDouble = ins.Amount, InstallmentDateGr = ins.InstallmentDateGr })
|
||
.OrderBy(ins => ins.InstallmentDateGr).Skip(1).ToList(),
|
||
}).ToListAsync();
|
||
|
||
// قرارداد هایی که بطور یکجا پرداخت شده اند
|
||
var paidInFull = institutionContracts.Where(x =>
|
||
x.SigningType != InstitutionContractSigningType.Legacy && x.IsInstallment == false && x.SigningType != null).ToList();
|
||
|
||
//حذف قراداد هایی که یکجا پرداخت شده اند از لیست ایجاد سند ماهانه
|
||
institutionContracts = institutionContracts.Except(paidInFull).ToList();
|
||
|
||
|
||
|
||
var financialStatmentList = await _context.FinancialStatments.AsSplitQuery()
|
||
.Where(x => institutionContracts.Select(ins => ins.ContractingPartyId).Contains(x.ContractingPartyId))
|
||
.Include(x => x.FinancialTransactionList).Where(x => x.FinancialTransactionList.Count > 0).ToListAsync();
|
||
//قرارداد های جاری فعال
|
||
var currentActiveContracts = await _context.InstitutionContractSet.Where(x =>
|
||
x.ContractEndGr.Date > checkDate.Date && x.IsActiveString == "true" &&
|
||
x.VerificationStatus != InstitutionContractVerificationStatus.PendingForVerify).ToListAsync();
|
||
|
||
|
||
|
||
var institutionContractIds = institutionContracts.Select(x => x.Id).ToList();
|
||
var queryableContracts =await _context.InstitutionContractSet.Where(x => institutionContractIds.Contains(x.id)).ToListAsync();
|
||
foreach (var item in institutionContracts)
|
||
{
|
||
try
|
||
{
|
||
var existContractAfterThis = currentActiveContracts.Any(x =>
|
||
x.ContractingPartyId == item.ContractingPartyId);
|
||
var transactions =
|
||
financialStatmentList.FirstOrDefault(x => x.ContractingPartyId == item.ContractingPartyId);
|
||
var contract = queryableContracts.FirstOrDefault(x => x.id == item.Id);
|
||
if (transactions != null && contract != null)
|
||
{
|
||
var debtor = transactions.FinancialTransactionList.Sum(x => x.Deptor);
|
||
var creditor = transactions.FinancialTransactionList.Sum(x => x.Creditor);
|
||
|
||
|
||
|
||
var balance = debtor - creditor;
|
||
|
||
|
||
if (balance > 0)
|
||
{
|
||
if (existContractAfterThis) // اگر بعد از این قراداد مالی قراردادی داشت حتی اگر بدهکار بود فقط غیرفعالش کن
|
||
contract.DeActive();
|
||
else // اگر نداشت غیر فعال آبیش کن
|
||
contract.DeActiveBlue();
|
||
|
||
}
|
||
else // اگر بدهکار نبود چه بعدش قرارداد مالی داشت چه نداشت غیرفعال کن
|
||
{
|
||
contract.DeActive();
|
||
|
||
}
|
||
|
||
await _context.SaveChangesAsync();
|
||
if (!existContractAfterThis) // اگر بعد از این قراداد مالی قرادادی نداشت همه وابستگی ها را غیر فعال کن
|
||
{
|
||
await _personalContractingPartyRepository.DeActiveAllAsync(item.ContractingPartyId);
|
||
Thread.Sleep(500);
|
||
}
|
||
}
|
||
|
||
|
||
|
||
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
string name = item.ContractingPartyName.Length > 18
|
||
? item.ContractingPartyName.Substring(0, 18)
|
||
: item.ContractingPartyName;
|
||
string errMess = $"{name}-خطا";
|
||
await _smsService.Alarm("09114221321", errMess);
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
public async Task BlueDeActiveAfterZeroDebt()
|
||
{
|
||
var institutionContracts =await _context.InstitutionContractSet
|
||
.Where(x => x.IsActiveString == "blue").ToListAsync();
|
||
|
||
var financialStatmentList = await _context.FinancialStatments.AsSplitQuery()
|
||
.Where(x => institutionContracts.Select(ins => ins.ContractingPartyId).Contains(x.ContractingPartyId))
|
||
.Include(x => x.FinancialTransactionList).Where(x => x.FinancialTransactionList.Count > 0)
|
||
.ToListAsync();
|
||
|
||
foreach (var item in institutionContracts)
|
||
{
|
||
try
|
||
{
|
||
|
||
|
||
var transactions =
|
||
financialStatmentList.FirstOrDefault(x => x.ContractingPartyId == item.ContractingPartyId);
|
||
|
||
if (transactions != null)
|
||
{
|
||
var debtor = transactions.FinancialTransactionList.Sum(x => x.Deptor);
|
||
var creditor = transactions.FinancialTransactionList.Sum(x => x.Creditor);
|
||
|
||
|
||
|
||
var balance = debtor - creditor;
|
||
|
||
|
||
if (balance <= 0)
|
||
{
|
||
|
||
item.DeActive();
|
||
await _context.SaveChangesAsync();
|
||
|
||
}
|
||
|
||
|
||
}
|
||
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
string name = item.ContractingPartyName.Length > 18
|
||
? item.ContractingPartyName.Substring(0, 18)
|
||
: item.ContractingPartyName;
|
||
string errMess = $"{name}-خطا";
|
||
await _smsService.Alarm("09114221321", errMess);
|
||
}
|
||
}
|
||
}
|
||
#endregion
|
||
|
||
//ارسال پیامک یادآور تایید قرارداد مالی
|
||
#region InstitutionContractConfirm
|
||
|
||
/// <summary>
|
||
/// ارسال پیامک یادآور تایید قراداد مالی
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public async Task SendInstitutionContractConfirmSmsTask()
|
||
{
|
||
var now = DateTime.Now;
|
||
|
||
|
||
// تبدیل تاریخ میلادی به شمسی
|
||
var persianNow = now.ToFarsi();
|
||
var persianEndOfMonth = int.Parse(persianNow.FindeEndOfMonth().Substring(8, 2));
|
||
var dayOfMonth = int.Parse(persianNow.Substring(8, 2));
|
||
var hour = now.Hour;
|
||
var minute = now.Minute;
|
||
var checkAnyToExecute = false;
|
||
|
||
//اگر آخرین روز ماه باشد
|
||
//اگر روز مثلا عدد روز 31 بود ولی آخرین روز ماه 30 بود
|
||
if (dayOfMonth == persianEndOfMonth)
|
||
{
|
||
checkAnyToExecute = await _context.SmsSettings
|
||
.AnyAsync(x =>
|
||
x.DayOfMonth >= dayOfMonth && /// اگر بزرگتر یا مساوی رو جاری بود
|
||
x.TimeOfDay.Hours == hour &&
|
||
x.TimeOfDay.Minutes == minute &&
|
||
x.TypeOfSmsSetting == TypeOfSmsSetting.InstitutionContractConfirm &&
|
||
x.IsActive
|
||
);
|
||
}
|
||
else
|
||
{
|
||
checkAnyToExecute = await _context.SmsSettings
|
||
.AnyAsync(x =>
|
||
x.DayOfMonth == dayOfMonth &&
|
||
x.TimeOfDay.Hours == hour &&
|
||
x.TimeOfDay.Minutes == minute &&
|
||
x.TypeOfSmsSetting == TypeOfSmsSetting.InstitutionContractConfirm &&
|
||
x.IsActive
|
||
);
|
||
}
|
||
|
||
|
||
if (checkAnyToExecute)
|
||
{
|
||
//اجرای تسک
|
||
_logger.LogInformation("اجرای تسک ارسال یاد آور تایید قراداد مالی SendInstitutionContractConfirmSms" +
|
||
persianNow + " - " + hour + ":" + minute);
|
||
//دریافت لیست قراداد های تایید نشده
|
||
var fromAmonthAgo = now.AddDays(-30);
|
||
var pendingContracts = await _context.InstitutionContractSet
|
||
.Where(x => x.CreationDate >= fromAmonthAgo && x.CreationDate.Date != now.Date &&
|
||
x.VerificationStatus == InstitutionContractVerificationStatus.PendingForVerify)
|
||
.Join(_context.PersonalContractingParties,
|
||
contract => contract.ContractingPartyId,
|
||
contractingParty => contractingParty.id,
|
||
(contract, contractingParty) => new { contract, contractingParty }).Select(x =>
|
||
new InstitutionCreationVerificationSmsDto
|
||
{
|
||
Number = x.contractingParty.Phone,
|
||
FullName = x.contractingParty.IsLegal == "حقیقی"
|
||
? $"{x.contractingParty.FName} {x.contractingParty.LName}"
|
||
: $"{x.contractingParty.LName}",
|
||
ContractingPartyId = x.contract.ContractingPartyId,
|
||
InstitutionContractId = x.contract.id,
|
||
InstitutionId = x.contract.PublicId,
|
||
}).ToListAsync();
|
||
|
||
string typeOfSms = "یادآور تایید قرارداد مالی";
|
||
foreach (var item in pendingContracts)
|
||
{
|
||
var sendResult = await _smsService.SendInstitutionCreationVerificationLink(item.Number, item.FullName,
|
||
item.InstitutionId, item.ContractingPartyId, item.InstitutionContractId, typeOfSms);
|
||
Thread.Sleep(1000);
|
||
}
|
||
|
||
Console.WriteLine("executed at : " + persianNow + " - " + hour + ":" + minute);
|
||
}
|
||
}
|
||
|
||
#endregion
|
||
|
||
#region ReminderSMS
|
||
/// <summary>
|
||
/// دریافت لیست - ارسال پیامک
|
||
/// فراخوانی از سمت بک گراند سرویس
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public async Task<bool> SendReminderSmsForBackgroundTask()
|
||
{
|
||
var now = DateTime.Now;
|
||
|
||
|
||
// تبدیل تاریخ میلادی به شمسی
|
||
var persianNow = now.ToFarsi();
|
||
var persianEndOfMonth = int.Parse(persianNow.FindeEndOfMonth().Substring(8, 2));
|
||
var dayOfMonth = int.Parse(persianNow.Substring(8, 2));
|
||
var hour = now.Hour;
|
||
var minute = now.Minute;
|
||
var checkAnyToExecute = false;
|
||
|
||
//اگر آخرین روز ماه باشد
|
||
//اگر روز مثلا عدد روز 31 بود ولی آخرین روز ماه 30 بود
|
||
if (dayOfMonth == persianEndOfMonth)
|
||
{
|
||
checkAnyToExecute = await _context.SmsSettings
|
||
.AnyAsync(x =>
|
||
x.DayOfMonth >= dayOfMonth &&
|
||
x.TimeOfDay.Hours == hour &&
|
||
x.TimeOfDay.Minutes == minute &&
|
||
x.TypeOfSmsSetting == TypeOfSmsSetting.InstitutionContractDebtReminder &&
|
||
x.IsActive
|
||
);
|
||
}
|
||
else
|
||
{
|
||
checkAnyToExecute = await _context.SmsSettings
|
||
.AnyAsync(x =>
|
||
x.DayOfMonth == dayOfMonth &&
|
||
x.TimeOfDay.Hours == hour &&
|
||
x.TimeOfDay.Minutes == minute &&
|
||
x.TypeOfSmsSetting == TypeOfSmsSetting.InstitutionContractDebtReminder &&
|
||
x.IsActive
|
||
);
|
||
}
|
||
|
||
|
||
if (checkAnyToExecute)
|
||
{
|
||
//اجرای تسک
|
||
_logger.LogInformation("اجرای تسک پیامک های یاد آور SendReminderSmsForBackgroundTask" + persianNow + " - " +
|
||
hour + ":" + minute);
|
||
//دریافت لیست بدهکاران
|
||
var smsListData = await GetSmsListData(now, TypeOfSmsSetting.InstitutionContractDebtReminder);
|
||
string typeOfSms = "یادآور بدهی ماهانه";
|
||
string sendMessStart = "شروع پیامک یادآور";
|
||
string sendMessEnd = "پایان پیامک یادآور";
|
||
//ارسال پیامک
|
||
await SendReminderSmsToContractingParties(smsListData, typeOfSms, sendMessStart, sendMessEnd);
|
||
|
||
|
||
Console.WriteLine("executed at : " + persianNow + " - " + hour + ":" + minute);
|
||
return true;
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
/// <summary>
|
||
/// ارسال پیامک صورت حساب ماهانه
|
||
/// </summary>
|
||
/// <param name="now"></param>
|
||
/// <returns></returns>
|
||
public async Task SendMonthlySms(DateTime now)
|
||
{
|
||
//دریافت لیست بدهکاران
|
||
var smsListData = await GetSmsListData(now, TypeOfSmsSetting.MonthlyInstitutionContract);
|
||
|
||
string typeOfSms = "صورت حساب ماهانه";
|
||
string sendMessStart = "شروع پیامک ماهانه";
|
||
string sendMessEnd = "پایان پیامک ماهانه";
|
||
//ارسال پیامک
|
||
await SendReminderSmsToContractingParties(smsListData, typeOfSms, sendMessStart, sendMessEnd);
|
||
}
|
||
|
||
/// <summary>
|
||
///دریافت لیست بدهکارن
|
||
/// جهت ارسال پیامک
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public async Task<List<SmsListData>> GetSmsListData(DateTime checkDate, TypeOfSmsSetting typeOfSmsSetting)
|
||
{
|
||
var watch = new Stopwatch();
|
||
var smsList = new List<SmsListData>();
|
||
var currentMonthStart = ($"{(checkDate.ToFarsi()).Substring(0, 8)}01").ToGeorgianDateTime();
|
||
var previusMonthEnd = currentMonthStart.AddDays(-1);
|
||
var previusMonthStart = ($"{(previusMonthEnd.ToFarsi()).Substring(0, 8)}01").ToGeorgianDateTime();
|
||
|
||
watch.Start();
|
||
//دریافت اطلاعات بدهکارن و ساخت لیست پیامک
|
||
|
||
#region GetSmsListData
|
||
|
||
//var rollcallServiceList = _context.RollCallServices.Where(x => x.StartService.Date <= previusMonthStart.Date && x.EndService.Date >= previusMonthEnd.Date).ToList();
|
||
var institutionContracts = await _context.InstitutionContractSet.AsSplitQuery()
|
||
.Include(x => x.Installments)
|
||
.Select(x =>
|
||
new InstitutionContractViewModel
|
||
{
|
||
Id = x.id,
|
||
ContractingPartyId = x.ContractingPartyId,
|
||
ContractingPartyName = x.ContractingPartyName,
|
||
ContractStartGr = x.ContractStartGr,
|
||
ContractStartFa = x.ContractStartFa,
|
||
ContractEndGr = x.ContractEndGr,
|
||
ContractEndFa = x.ContractEndFa,
|
||
IsActiveString = x.IsActiveString,
|
||
ContractAmountDouble = x.ContractAmount,
|
||
OfficialCompany = x.OfficialCompany,
|
||
IsInstallment = x.IsInstallment,
|
||
VerificationStatus = x.VerificationStatus,
|
||
SigningType = x.SigningType,
|
||
InstallmentList = x.Installments
|
||
.Select(ins => new InstitutionContractInstallmentViewModel
|
||
{ AmountDouble = ins.Amount, InstallmentDateGr = ins.InstallmentDateGr })
|
||
.OrderBy(ins => ins.InstallmentDateGr).Skip(1).ToList(),
|
||
}).Where(x => x.ContractStartGr < checkDate && x.ContractEndGr >= checkDate &&
|
||
x.ContractAmountDouble > 0 && x.VerificationStatus != InstitutionContractVerificationStatus.PendingForVerify)
|
||
.GroupBy(x => x.ContractingPartyId).Select(x => x.First())
|
||
.ToListAsync();
|
||
// قرارداد هایی که بطور یکجا پرداخت شده اند
|
||
var paidInFull = institutionContracts.Where(x =>
|
||
x.SigningType != InstitutionContractSigningType.Legacy && x.IsInstallment == false && x.SigningType != null).ToList();
|
||
|
||
//حذف قراداد هایی که یکجا پرداخت شده اند از لیست ایجاد سند ماهانه
|
||
institutionContracts = institutionContracts.Except(paidInFull).ToList();
|
||
|
||
var contractingPartyList = await _context.PersonalContractingParties
|
||
.Where(x => institutionContracts.Select(ins => ins.ContractingPartyId).Contains(x.id)).ToListAsync();
|
||
|
||
var financialStatmentList = await _context.FinancialStatments.AsSplitQuery()
|
||
.Where(x => institutionContracts.Select(ins => ins.ContractingPartyId).Contains(x.ContractingPartyId))
|
||
.Include(x => x.FinancialTransactionList).Where(x => x.FinancialTransactionList.Count > 0).ToListAsync();
|
||
|
||
var phoneNumberList = await _context.InstitutionContractContactInfos
|
||
.Where(x => institutionContracts.Select(ins => ins.Id).Contains(x.InstitutionContractId))
|
||
.Where(x => x.SendSms && x.PhoneType == "شماره همراه" && !string.IsNullOrWhiteSpace(x.PhoneNumber) &&
|
||
x.PhoneNumber.Length == 11).ToListAsync();
|
||
|
||
Console.WriteLine("database query: " + watch.Elapsed);
|
||
watch.Stop();
|
||
watch.Start();
|
||
|
||
//var a = new FinancialInvoice(balance, item.ContractingPartyId, "");
|
||
//var b = new FinancialInvoiceItem("", balance, a.id, FinancialInvoiceItemType.PreviousDebt,
|
||
// 0);
|
||
//a.AddItem(b);
|
||
//_context.Add(a);
|
||
var oldInstitutionContract = institutionContracts.Where(x => x.IsInstallment == false).ToList();
|
||
var electronicInstitutionContract = institutionContracts.Where(x => x.IsInstallment == true).ToList();
|
||
foreach (var item in oldInstitutionContract)
|
||
{
|
||
try
|
||
{
|
||
var contractingParty = contractingPartyList.FirstOrDefault(x => x.id == item.ContractingPartyId);
|
||
//var isSend = sendedSms.Any(x => x.ContractingPatyId == contractingParty.Id);
|
||
if (!string.IsNullOrWhiteSpace(contractingParty.LName))
|
||
{
|
||
//Thread.Sleep(500);
|
||
var partyName = contractingParty.IsLegal == "حقیقی"
|
||
? $"{contractingParty.FName} {contractingParty.LName}"
|
||
: $"{contractingParty.LName}";
|
||
if (!string.IsNullOrWhiteSpace(contractingParty.SureName))
|
||
partyName = $"{partyName} ({contractingParty.SureName})";
|
||
|
||
if (partyName.Length > 25) partyName = $"{partyName.Substring(0, 25)}";
|
||
|
||
var isLegal = contractingParty.IsLegal == "حقوقی" ? true : false;
|
||
var isBlock = contractingParty.IsBlock == "true" ? true : false;
|
||
var isActive = contractingParty.IsActiveString == "true" ? true : false;
|
||
if (!string.IsNullOrWhiteSpace(contractingParty.IsActiveString) && isActive)
|
||
{
|
||
var hasFinancialStatement =
|
||
financialStatmentList.Any(x => x.ContractingPartyId == item.ContractingPartyId);
|
||
|
||
|
||
var hasPhonNumber = phoneNumberList.Any(x => x.InstitutionContractId == item.Id);
|
||
|
||
|
||
if (hasFinancialStatement && hasPhonNumber)
|
||
{
|
||
var phoneNumbers = phoneNumberList.Where(x => x.InstitutionContractId == item.Id)
|
||
.Select(x => new CreateContactInfo
|
||
{
|
||
PhoneType = x.PhoneType,
|
||
PhoneNumber = x.PhoneNumber,
|
||
|
||
InstitutionContractId = x.InstitutionContractId,
|
||
SendSms = x.SendSms
|
||
}).Where(x => x.PhoneNumber.Length == 11).ToList();
|
||
|
||
var transactions = financialStatmentList.FirstOrDefault(x =>
|
||
x.ContractingPartyId == item.ContractingPartyId);
|
||
|
||
var debtor = transactions.FinancialTransactionList.Sum(x => x.Deptor);
|
||
var creditor = transactions.FinancialTransactionList.Sum(x => x.Creditor);
|
||
|
||
|
||
var id = $"{item.ContractingPartyId}";
|
||
var aprove = $"{transactions.id}";
|
||
var balance = debtor - creditor;
|
||
|
||
|
||
|
||
if (balance > 0) // اگر بدهکار بود
|
||
{
|
||
//var employers = _context.Employers.Where(x => x.ContractingPartyId == item.ContractingPartyId)
|
||
// .Select(x => x.id);
|
||
//var workshops = _context.WorkshopEmployers.Where(x => employers.Contains(x.EmployerId))
|
||
// .Select(x => x.WorkshopId).Distinct().ToList();
|
||
|
||
|
||
//var services =
|
||
// rollcallServiceList.Where(x => workshops.Contains(x.WorkshopId)).ToList();
|
||
|
||
//var hasRollCallService = services.Count > 0;
|
||
|
||
//موقت
|
||
var hasRollCallService = false;
|
||
|
||
//if (hasRollCallService)
|
||
//{
|
||
// var employees =
|
||
// _context.RollCallEmployees.Where(x => workshops.Contains(x.WorkshopId))
|
||
// .Select(x => x.id);
|
||
|
||
// var employeeCount = _context.RollCallEmployeesStatus
|
||
// .Where(x => employees.Contains(x.RollCallEmployeeId))
|
||
// .Count(x => x.EndDate.Date == activeStatusDate.Date);
|
||
|
||
// if (employeeCount == 0)
|
||
// hasRollCallService = false;
|
||
//}
|
||
|
||
if (isLegal)
|
||
{
|
||
if (item.OfficialCompany == "Official") // حقوقی بدهکار رسمی
|
||
{
|
||
var balanceToMoney = balance.ToMoney();
|
||
|
||
foreach (var number in phoneNumbers)
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(number.PhoneNumber) &&
|
||
number.PhoneNumber.Length == 11)
|
||
{
|
||
|
||
var templateId = 161233;
|
||
if (typeOfSmsSetting ==
|
||
TypeOfSmsSetting.MonthlyInstitutionContract)
|
||
{
|
||
templateId = 394006;
|
||
}
|
||
|
||
smsList.Add(new SmsListData()
|
||
{
|
||
PhoneNumber = number.PhoneNumber,
|
||
TemplateId = templateId,
|
||
PartyName = partyName,
|
||
Amount = balanceToMoney,
|
||
ContractingPartyId = contractingParty.id,
|
||
AproveId = aprove,
|
||
TypeOfSmsMethod = "MonthlyBill",
|
||
Code1 = "",
|
||
Code2 = "",
|
||
InstitutionContractId = item.Id
|
||
});
|
||
|
||
}
|
||
}
|
||
}
|
||
else if (item.OfficialCompany == "NotOfficial") // حقوقی بدهکار غیر رسمی
|
||
{
|
||
var balanceToMoney = balance.ToMoney();
|
||
foreach (var number in phoneNumbers)
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(number.PhoneNumber) &&
|
||
number.PhoneNumber.Length == 11)
|
||
{
|
||
|
||
var templateId = 347415;
|
||
if (typeOfSmsSetting ==
|
||
TypeOfSmsSetting.MonthlyInstitutionContract)
|
||
{
|
||
templateId = 679068;
|
||
}
|
||
|
||
smsList.Add(new SmsListData()
|
||
{
|
||
PhoneNumber = number.PhoneNumber,
|
||
TemplateId = templateId,
|
||
PartyName = partyName,
|
||
Amount = balanceToMoney,
|
||
ContractingPartyId = contractingParty.id,
|
||
AproveId = aprove,
|
||
TypeOfSmsMethod = "MonthlyBill",
|
||
Code1 = "",
|
||
Code2 = "",
|
||
InstitutionContractId = item.Id
|
||
});
|
||
|
||
}
|
||
}
|
||
}
|
||
}
|
||
else
|
||
{
|
||
if (item.OfficialCompany == "Official") // حقیقی بدهکار رسمی
|
||
{
|
||
var balanceToMoney = balance.ToMoney();
|
||
|
||
foreach (var number in phoneNumbers)
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(number.PhoneNumber) &&
|
||
number.PhoneNumber.Length == 11)
|
||
{
|
||
|
||
var templateId = 998180;
|
||
if (typeOfSmsSetting ==
|
||
TypeOfSmsSetting.MonthlyInstitutionContract)
|
||
{
|
||
templateId = 646040;
|
||
}
|
||
|
||
smsList.Add(new SmsListData()
|
||
{
|
||
PhoneNumber = number.PhoneNumber,
|
||
TemplateId = templateId,
|
||
PartyName = partyName,
|
||
Amount = balanceToMoney,
|
||
ContractingPartyId = contractingParty.id,
|
||
AproveId = aprove,
|
||
TypeOfSmsMethod = "MonthlyBill",
|
||
Code1 = "",
|
||
Code2 = "",
|
||
InstitutionContractId = item.Id
|
||
});
|
||
|
||
}
|
||
}
|
||
}
|
||
else if (item.OfficialCompany == "NotOfficial") // حقیقی بدهکار غیر رسمی
|
||
{
|
||
var balanceToMoney = balance.ToMoney();
|
||
|
||
foreach (var number in phoneNumbers)
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(number.PhoneNumber) &&
|
||
number.PhoneNumber.Length == 11)
|
||
{
|
||
|
||
|
||
var templateId = 810539;
|
||
if (typeOfSmsSetting ==
|
||
TypeOfSmsSetting.MonthlyInstitutionContract)
|
||
{
|
||
templateId = 566537;
|
||
}
|
||
|
||
smsList.Add(new SmsListData()
|
||
{
|
||
PhoneNumber = number.PhoneNumber,
|
||
TemplateId = templateId,
|
||
PartyName = partyName,
|
||
Amount = balanceToMoney,
|
||
ContractingPartyId = contractingParty.id,
|
||
AproveId = aprove,
|
||
TypeOfSmsMethod = "MonthlyBill",
|
||
Code1 = "",
|
||
Code2 = "",
|
||
InstitutionContractId = item.Id
|
||
});
|
||
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
phoneNumbers = new List<CreateContactInfo>();
|
||
}
|
||
}
|
||
}
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
string name = item.ContractingPartyName.Length > 18
|
||
? item.ContractingPartyName.Substring(0, 18)
|
||
: item.ContractingPartyName;
|
||
string errMess = $"{name}-خطا";
|
||
// _smsService.Alarm("09114221321", errMess);
|
||
}
|
||
}
|
||
|
||
foreach (var item in electronicInstitutionContract)
|
||
{
|
||
try
|
||
{
|
||
var contractingParty = contractingPartyList.FirstOrDefault(x => x.id == item.ContractingPartyId);
|
||
if (!string.IsNullOrWhiteSpace(contractingParty.LName))
|
||
{
|
||
var partyName = contractingParty.IsLegal == "حقیقی"
|
||
? $"{contractingParty.FName} {contractingParty.LName}"
|
||
: $"{contractingParty.LName}";
|
||
if (!string.IsNullOrWhiteSpace(contractingParty.SureName))
|
||
partyName = $"{partyName} ({contractingParty.SureName})";
|
||
|
||
if (partyName.Length > 25) partyName = $"{partyName.Substring(0, 25)}";
|
||
|
||
var isLegal = contractingParty.IsLegal == "حقوقی" ? true : false;
|
||
var isBlock = contractingParty.IsBlock == "true" ? true : false;
|
||
var isActive = contractingParty.IsActiveString == "true" ? true : false;
|
||
|
||
if (!string.IsNullOrWhiteSpace(contractingParty.IsActiveString) && isActive)
|
||
{
|
||
var hasFinancialStatement =
|
||
financialStatmentList.Any(x => x.ContractingPartyId == item.ContractingPartyId);
|
||
|
||
|
||
var hasPhonNumber = phoneNumberList.Any(x => x.InstitutionContractId == item.Id);
|
||
|
||
if (hasFinancialStatement && hasPhonNumber)
|
||
{
|
||
var phoneNumbers = phoneNumberList.Where(x => x.InstitutionContractId == item.Id)
|
||
.Select(x => new CreateContactInfo
|
||
{
|
||
PhoneType = x.PhoneType,
|
||
PhoneNumber = x.PhoneNumber,
|
||
|
||
InstitutionContractId = x.InstitutionContractId,
|
||
SendSms = x.SendSms
|
||
}).Where(x => x.PhoneNumber.Length == 11).ToList();
|
||
|
||
var transactions = financialStatmentList.FirstOrDefault(x =>
|
||
x.ContractingPartyId == item.ContractingPartyId);
|
||
|
||
var debtor = transactions.FinancialTransactionList.Sum(x => x.Deptor);
|
||
var creditor = transactions.FinancialTransactionList.Sum(x => x.Creditor);
|
||
|
||
|
||
var id = $"{item.ContractingPartyId}";
|
||
var aprove = $"{transactions.id}";
|
||
var balance = debtor - creditor;
|
||
int templateId = 0;
|
||
//انتخاب قالب پیامک بر اساس حقیق/حقوقی
|
||
if (isLegal)
|
||
{
|
||
templateId = 789638;
|
||
if (typeOfSmsSetting ==
|
||
TypeOfSmsSetting.MonthlyInstitutionContract)
|
||
{
|
||
templateId = 983035;
|
||
}
|
||
}
|
||
else
|
||
{
|
||
templateId = 768277;
|
||
if (typeOfSmsSetting ==
|
||
TypeOfSmsSetting.MonthlyInstitutionContract)
|
||
{
|
||
templateId = 479624;
|
||
}
|
||
}
|
||
|
||
if (balance > 0) // اگر بدهکار بود
|
||
{
|
||
var balanceToMoney = balance.ToMoney();
|
||
|
||
foreach (var number in phoneNumbers)
|
||
{
|
||
string publicId = transactions.PublicIdStr;
|
||
string code1 = publicId.Substring(0, 25);
|
||
string code2 = publicId.Substring(25);
|
||
|
||
|
||
smsList.Add(new SmsListData()
|
||
{
|
||
PhoneNumber = number.PhoneNumber,
|
||
TemplateId = templateId,
|
||
PartyName = partyName,
|
||
Amount = balanceToMoney,
|
||
ContractingPartyId = contractingParty.id,
|
||
AproveId = aprove,
|
||
TypeOfSmsMethod = "MonthlyBillNew",
|
||
Code1 = code1,
|
||
Code2 = code2,
|
||
InstitutionContractId = item.Id
|
||
});
|
||
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
_logger.LogError($"ContractingPartyId : {item.ContractingPartyId} - ContractingPartyName : {item.ContractingPartyName} - InstitutionContractId : {item.Id} خطای دریافت لیست بدهکاران ");
|
||
throw;
|
||
}
|
||
}
|
||
|
||
|
||
#endregion
|
||
|
||
Console.WriteLine("SmsListData: " + watch.Elapsed);
|
||
return smsList;
|
||
}
|
||
|
||
/// <summary>
|
||
/// ارسال پیامک های یاد آور بدهی
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public async Task SendReminderSmsToContractingParties(List<SmsListData> smsListData, string typeOfSms,
|
||
string sendMessStart, string sendMessEnd)
|
||
{
|
||
//ارسال پیامک با اساس لیست
|
||
|
||
#region SendSMSFromList
|
||
|
||
var currentAccountId = _authHelper.CurrentAccountId();
|
||
var signalR = _hubContext.Clients.Group(SendSmsHub.GetGroupName(currentAccountId));
|
||
if (smsListData.Any())
|
||
{
|
||
try
|
||
{
|
||
var sendingStart = await _smsService.Alarm("09114221321", sendMessStart);
|
||
Thread.Sleep(1000);
|
||
|
||
if (!sendingStart)
|
||
{
|
||
await signalR.SendAsync("sendToApi", "failed");
|
||
return;
|
||
}
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
await signalR.SendAsync("sendToApi", "failed");
|
||
return;
|
||
}
|
||
|
||
int successProcess = 1;
|
||
int countList = smsListData.Count;
|
||
|
||
#region Test
|
||
|
||
|
||
//for (int i = 0; i < 100; i++)
|
||
//{
|
||
// var percent = (successProcess / (double)countList) * 100;
|
||
// await _hubContext.Clients.Group(SendSmsHub.GetGroupName(7))
|
||
// .SendAsync("showStatus", (int)percent);
|
||
// Thread.Sleep(1000);
|
||
// successProcess += 1;
|
||
//}
|
||
#endregion
|
||
|
||
foreach (var item in smsListData)
|
||
{
|
||
try
|
||
{
|
||
|
||
if (item.TypeOfSmsMethod == "MonthlyBill")
|
||
{
|
||
var res = await _smsService.MonthlyBill(item.PhoneNumber, item.TemplateId, item.PartyName,
|
||
item.Amount,
|
||
$"{item.ContractingPartyId}", item.AproveId);
|
||
|
||
if (res.isSucceded)
|
||
{
|
||
|
||
var createSmsResult = new Company.Domain.SmsResultAgg.SmsResult(res.messaeId,
|
||
res.message, typeOfSms, item.PartyName, item.PhoneNumber,
|
||
item.ContractingPartyId, item.InstitutionContractId);
|
||
|
||
await _smsResultRepository.CreateAsync(createSmsResult);
|
||
await _smsResultRepository.SaveChangesAsync();
|
||
await signalR.SendAsync("sendStatus", true, item.PhoneNumber);
|
||
}
|
||
}
|
||
else
|
||
{
|
||
var res = await _smsService.MonthlyBillNew(item.PhoneNumber, item.TemplateId, item.PartyName,
|
||
item.Amount, item.Code1, item.Code2);
|
||
if (res.isSucceded)
|
||
{
|
||
|
||
var createSmsResult = new Company.Domain.SmsResultAgg.SmsResult(res.messaeId,
|
||
res.message, typeOfSms, item.PartyName, item.PhoneNumber,
|
||
item.ContractingPartyId, item.InstitutionContractId);
|
||
|
||
await _smsResultRepository.CreateAsync(createSmsResult);
|
||
await _smsResultRepository.SaveChangesAsync();
|
||
await signalR.SendAsync("sendStatus", true, item.PhoneNumber);
|
||
}
|
||
}
|
||
|
||
Thread.Sleep(600);
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
string name = item.PartyName.Length > 18 ? item.PartyName.Substring(0, 18) : item.PartyName;
|
||
string errMess = $"{name}-خطا";
|
||
await signalR.SendAsync("sendStatus", false, item.PhoneNumber);
|
||
_logger.LogError(errMess);
|
||
await _smsService.Alarm("09114221321", errMess);
|
||
}
|
||
|
||
var percent = (successProcess / (double)countList) * 100;
|
||
await signalR.SendAsync("showStatus", (int)percent);
|
||
|
||
successProcess += 1;
|
||
}
|
||
|
||
|
||
//await _smsService.Alarm("09114221321", sendMessEnd);
|
||
//Thread.Sleep(1000);
|
||
//await _smsService.Alarm("09111485044", sendMessEnd);
|
||
}
|
||
|
||
#endregion
|
||
}
|
||
|
||
#endregion
|
||
|
||
}
|
||
|
||
|