UpdateOperations.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. 
  2. using System.Security;
  3. namespace BankOperationsUpdate.WorkerService.OperationsUpdate;
  4. public class UpdateOperations
  5. {
  6. private IRepositoryWrapper _repositoryWrapper;
  7. private readonly ILogger<UpdateOperations> _logger;
  8. private readonly IServiceProvider _provider;
  9. public UpdateOperations(ILogger<UpdateOperations> logger, IServiceProvider provider)
  10. {
  11. _logger = logger;
  12. _provider = provider;
  13. }
  14. public void WhenStart()
  15. {
  16. using (var scope = _provider.CreateScope()) {
  17. _repositoryWrapper = scope.ServiceProvider.GetRequiredService<IRepositoryWrapper>();
  18. SetTransactionsInitial();
  19. }
  20. }
  21. public void Execute()
  22. {
  23. using (var scope = _provider.CreateScope()) {
  24. _repositoryWrapper = scope.ServiceProvider.GetRequiredService<IRepositoryWrapper>();
  25. AddConfirmedOperations();
  26. }
  27. using (var scope = _provider.CreateScope()) {
  28. _repositoryWrapper = scope.ServiceProvider.GetRequiredService<IRepositoryWrapper>();
  29. UpdateConfirmedTransactions();
  30. }
  31. }
  32. #region Different Get methods
  33. public IQueryable<BankOperation> GetAllOperations() => _repositoryWrapper.BankOperation.GetAll();
  34. public IQueryable<BankOperation> GetAllConfirmedOperations() => _repositoryWrapper.BankOperation.GetAllConfirmed(Guid.Empty, Guid.Empty);
  35. public IQueryable<BankOperation> GetAllConfirmedOperations(Guid accountId, Guid businessId) => _repositoryWrapper.BankOperation.GetAllConfirmed(accountId, businessId);
  36. public IQueryable<BankOperation> GetAllNewOperations() => _repositoryWrapper.BankOperation.GetAllNew(Guid.Empty, Guid.Empty);
  37. public IQueryable<BankOperation> GetAllNewOperations(Guid accountId, Guid businessId) => _repositoryWrapper.BankOperation.GetAllNew(accountId, businessId);
  38. public IQueryable<BankAccountBalance> GetAllBankBalances() => _repositoryWrapper.BankAccountBalance.FindAll();
  39. public BankAccountBalance GetAccountBalanceByBusinessId(Guid accountId, Guid businessId) =>
  40. _repositoryWrapper.BankAccountBalance.GetByBankAccountId(accountId, businessId).FirstOrDefault();
  41. public IQueryable<Transaction> GetTransactionsByAccountId(Guid accountId, Guid businessId) => _repositoryWrapper.Transaction.GetByAccountId(accountId, businessId);
  42. public IQueryable<Transaction> GetAllTransactions() => _repositoryWrapper.Transaction.FindAll();
  43. public Transaction GetTransactionByOperationId(Guid operationId) => _repositoryWrapper.Transaction.GetByOperationId(operationId);
  44. #endregion
  45. void SetTransactionsInitial()
  46. {
  47. var bankBalances = GetAllBankBalances().ToList();
  48. for(int i = 0; i < bankBalances.Count; i++) {
  49. _logger.LogDebug("Process for account {0}", bankBalances[i].Id);
  50. SetTransactionsForAccount(bankBalances[i]!.BankAccountId.Value, bankBalances[i]!.BusinessId.Value);
  51. }
  52. }
  53. void AddConfirmedOperations()
  54. {
  55. //get all operations with Confirmed status
  56. var operations = GetAllConfirmedOperations().OrderBy(x => x.DocDate).ThenBy(x => x.OrderId).ToList();
  57. //get all operations with New status
  58. var newOperations = GetAllNewOperations().OrderBy(x => x.DocDate).ThenBy(x => x.OrderId).ToList();
  59. //get all bankOperationIds that added to transactions
  60. var transactiondHashSet = GetAllTransactions().Select(x => x.BankOperationId).ToHashSet();
  61. BankAccountBalance accountBalance;
  62. Transaction transaction;
  63. foreach (var item in operations) {
  64. //if transaction with opertion id doesn't exist then add new transatcion and change balance
  65. if (!transactiondHashSet.Contains(item.Id)) {
  66. try {
  67. accountBalance = GetAccountBalanceByBusinessId(item.BankAccountId!.Value, item.BusinessId!.Value);
  68. //change balance on certain amount
  69. accountBalance.Amount = accountBalance.Amount!.Value + item.IncomeAmount!.Value - item.OutcomeAmount!.Value;
  70. //create new transaction
  71. transaction = new Transaction {
  72. Id = Guid.NewGuid(),
  73. BankOperationId = item.Id,
  74. IncomeAmount = item.IncomeAmount,
  75. OutcomeAmount = item.OutcomeAmount,
  76. BalanceAmount = item.IncomeAmount!.Value - item.OutcomeAmount!.Value,
  77. ModifiedDate = item.DocDate,
  78. BusinessId = item.BusinessId.Value,
  79. BankAccountId = item.BankAccountId.Value,
  80. CreateDate = DateTime.Now,
  81. OperationCreateDate = item.CreatedDate ?? item.DocDate!.Value,
  82. IsChanged = true,
  83. OperationOrderId = item.OrderId,
  84. };
  85. _logger.LogInformation(Environment.NewLine + "Created new Transaction {0}", transaction.Id);
  86. _repositoryWrapper.Transaction.Create(transaction);
  87. _repositoryWrapper.BankAccountBalance.Update(accountBalance);
  88. _repositoryWrapper.Save();
  89. _repositoryWrapper.Transaction.Detach(transaction);
  90. _repositoryWrapper.BankAccountBalance.Detach(accountBalance);
  91. }
  92. catch(Exception ex) {
  93. _logger.LogError(ex.Message);
  94. }
  95. }
  96. else if(transactiondHashSet.Contains(item.Id) && item.IsChanged == true) {
  97. UpdateChangedOperations(item, true);
  98. }
  99. }
  100. foreach (var item in newOperations) {
  101. if (transactiondHashSet.Contains(item.Id)) {
  102. UpdateChangedOperations(item, false);
  103. }
  104. }
  105. }
  106. void UpdateChangedOperations(BankOperation operation, bool IsChanged)
  107. {
  108. Transaction transaction = GetTransactionByOperationId(operation.Id);
  109. var accountBalance = GetAccountBalanceByBusinessId(operation.BankAccountId.Value, operation.BusinessId.Value);
  110. decimal incomeDifference, outcomeDifference;
  111. //if it is bankOperation with new status that already was in transatctions
  112. if (!IsChanged) {
  113. //get the income or outcome sum of rollBackcked transaction
  114. incomeDifference = -1 * transaction.IncomeAmount.Value;
  115. outcomeDifference = -1 * transaction.OutcomeAmount.Value;
  116. _repositoryWrapper.Transaction.Delete(transaction);
  117. }
  118. //else if it is confirmed transaction that has already in transactions
  119. else {
  120. //get the income or outcome difference that opertion was changed
  121. incomeDifference = operation.IncomeAmount.Value - transaction.IncomeAmount.Value;
  122. outcomeDifference = operation.OutcomeAmount.Value - transaction.OutcomeAmount.Value;
  123. transaction.IncomeAmount += incomeDifference;
  124. transaction.OutcomeAmount += outcomeDifference;
  125. operation.IsChanged = false;
  126. _logger.LogInformation("Updated transaction with id: {0}", transaction.Id);
  127. _repositoryWrapper.Transaction.Update(transaction);
  128. _repositoryWrapper.BankOperation.Update(operation);
  129. }
  130. accountBalance.Amount = accountBalance.Amount + incomeDifference - outcomeDifference;
  131. _repositoryWrapper.BankAccountBalance.Update(accountBalance);
  132. _repositoryWrapper.Save();
  133. _repositoryWrapper.Transaction.Detach(transaction);
  134. _repositoryWrapper.BankAccountBalance.Detach(accountBalance);
  135. //get the transactions that come after modified transaction and change their balanceAmount on cahnged certain amount
  136. var transactionsList = GetTransactionsByAccountId(operation.BankAccountId.Value, operation.BusinessId.Value)
  137. .Where(x => x.BusinessId == operation.BusinessId &&
  138. x.BankAccountId == operation.BankAccountId &&
  139. DateTime.Compare(x.ModifiedDate.Value, transaction.ModifiedDate.Value) >= 0)
  140. .OrderBy(x => x.ModifiedDate)
  141. .ThenBy(x => x.OperationOrderId).ToList();
  142. foreach(var item in transactionsList) {
  143. item.BalanceAmount = item.BalanceAmount + incomeDifference - outcomeDifference;
  144. _logger.LogInformation("Updated transaction with id: {0}", transaction.Id);
  145. _repositoryWrapper.Transaction.Update(item);
  146. _repositoryWrapper.Save();
  147. _repositoryWrapper.Transaction.Detach(item);
  148. }
  149. }
  150. //update all new added transactions for updating balance amount of items that comes after updated item
  151. void UpdateConfirmedTransactions()
  152. {
  153. var bankAccounts = GetAllBankBalances().ToList();
  154. List<Transaction> transactions;
  155. decimal newValue = 0M;
  156. foreach (var account in bankAccounts) {
  157. transactions = GetTransactionsByAccountId(account.BankAccountId!.Value, account.BusinessId!.Value).OrderBy(x => x.ModifiedDate).ThenBy(x => x.OperationOrderId).ToList();
  158. for (int i = 1; i < transactions.Count; i++) {
  159. if (transactions[i].IsChanged == true) {
  160. transactions[i].BalanceAmount += transactions[i - 1].BalanceAmount;
  161. newValue += transactions[i].IncomeAmount!.Value - transactions[i].OutcomeAmount!.Value;
  162. transactions[i].IsChanged = false;
  163. }
  164. else {
  165. transactions[i].BalanceAmount += newValue;
  166. }
  167. _repositoryWrapper.Transaction.Update(transactions[i]);
  168. _repositoryWrapper.Save();
  169. }
  170. }
  171. }
  172. /// <summary>
  173. /// Create transatction for each bank operation if they don't exist
  174. /// </summary>
  175. /// <param name="accountId"></param>
  176. /// <param name="businessId"></param>
  177. void SetTransactionsForAccount(Guid accountId, Guid businessId)
  178. {
  179. //get all confirmed operations by accountId and businessId and order them by DocDate
  180. var operations = GetAllConfirmedOperations(accountId, businessId).OrderBy(x => x.DocDate).ThenBy(x => x.OrderId).ToList();
  181. // get Unitque bankOpertionsIds from transatctions
  182. var transactionsHashSet = GetTransactionsByAccountId(accountId, businessId).Select(x => x.BankOperationId).ToHashSet();
  183. Transaction transaction = new Transaction();
  184. //get current balance by summarizing all Incomes and outcomes from transacitons
  185. var currentBalance = GetTransactionsByAccountId(accountId, businessId).Sum(x => (x.IncomeAmount - x.OutcomeAmount));
  186. for (int i = 0; i < operations.Count && transactionsHashSet.Count == 0; i++) {
  187. //if BankOperationsIds doesn't contain confirmed operations then..
  188. if (!transactionsHashSet.Contains(operations[i].Id) ) {
  189. //change balance on certain income or outcome amount
  190. currentBalance = currentBalance + operations[i].IncomeAmount!.Value - operations[i].OutcomeAmount!.Value;
  191. transaction.Id = Guid.NewGuid();
  192. transaction.IncomeAmount = operations[i].IncomeAmount;
  193. transaction.OutcomeAmount = operations[i].OutcomeAmount;
  194. transaction.BankOperationId = operations[i].Id;
  195. transaction.IsChanged = false;
  196. transaction.ModifiedDate = operations[i].DocDate;
  197. transaction.BusinessId = businessId;
  198. transaction.BankAccountId = accountId;
  199. transaction.CreateDate = DateTime.Now;
  200. transaction.OperationCreateDate = operations[i].CreatedDate ?? transaction.ModifiedDate!.Value;
  201. transaction.BalanceAmount = currentBalance ?? 0;
  202. transaction.OperationOrderId = operations[i].OrderId;
  203. //create transaction
  204. _repositoryWrapper.Transaction.Create(transaction);
  205. _repositoryWrapper.Save();
  206. }
  207. }
  208. _logger.LogInformation($"{operations.Count} count records was written");
  209. }
  210. }