UpdateOperations.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. 
  2. namespace BankOperationsUpdate.WorkerService.OperationsUpdate;
  3. public class UpdateOperations
  4. {
  5. private IRepositoryWrapper _repositoryWrapper;
  6. private readonly ILogger<UpdateOperations> _logger;
  7. private readonly IServiceProvider _provider;
  8. public UpdateOperations(ILogger<UpdateOperations> logger, IServiceProvider provider)
  9. {
  10. _logger = logger;
  11. _provider = provider;
  12. }
  13. public void WhenStart()
  14. {
  15. using (var scope = _provider.CreateScope()) {
  16. _repositoryWrapper = scope.ServiceProvider.GetRequiredService<IRepositoryWrapper>();
  17. SetTransactionsInitial();
  18. }
  19. }
  20. public void Execute()
  21. {
  22. using (var scope = _provider.CreateScope()) {
  23. _repositoryWrapper = scope.ServiceProvider.GetRequiredService<IRepositoryWrapper>();
  24. AddConfirmedOperations();
  25. }
  26. using (var scope = _provider.CreateScope()) {
  27. _repositoryWrapper = scope.ServiceProvider.GetRequiredService<IRepositoryWrapper>();
  28. UpdateConfirmedTransactions();
  29. }
  30. }
  31. #region Different Get methods
  32. public IQueryable<BankOperation> GetAllOperations() => _repositoryWrapper.BankOperation.GetAll();
  33. public IQueryable<BankOperation> GetAllConfirmedOperations() => _repositoryWrapper.BankOperation.GetAllConfirmed(Guid.Empty, Guid.Empty);
  34. public IQueryable<BankOperation> GetAllConfirmedOperations(Guid accountId, Guid businessId) => _repositoryWrapper.BankOperation.GetAllConfirmed(accountId, businessId);
  35. public IQueryable<BankOperation> GetAllNewOperations() => _repositoryWrapper.BankOperation.GetAllNew(Guid.Empty, Guid.Empty);
  36. public IQueryable<BankOperation> GetAllNewOperations(Guid accountId, Guid businessId) => _repositoryWrapper.BankOperation.GetAllNew(accountId, businessId);
  37. public IQueryable<BankAccountBalance> GetAllBankBalances() => _repositoryWrapper.BankAccountBalance.FindAll();
  38. public BankAccountBalance GetAccountBalanceByBusinessId(Guid accountId, Guid businessId) =>
  39. _repositoryWrapper.BankAccountBalance.GetByBankAccountId(accountId, businessId).FirstOrDefault();
  40. public IQueryable<Transaction> GetTransactionsByAccountId(Guid accountId, Guid businessId) => _repositoryWrapper.Transaction.GetByAccountId(accountId, businessId);
  41. public IQueryable<Transaction> GetAllTransactions() => _repositoryWrapper.Transaction.FindAll();
  42. public Transaction GetTransactionByOperationId(Guid operationId) => _repositoryWrapper.Transaction.GetByOperationId(operationId);
  43. #endregion
  44. void SetTransactionsInitial()
  45. {
  46. var bankBalances = GetAllBankBalances().ToList();
  47. decimal? currentBalance;
  48. for(int i = 0; i < bankBalances.Count; i++) {
  49. currentBalance = bankBalances[i].Amount;
  50. _logger.LogDebug("Process for account {0}", bankBalances[i].Id);
  51. SetTransactionsForAccount(currentBalance, bankBalances[i].BankAccountId.Value, bankBalances[i].BusinessId.Value);
  52. }
  53. }
  54. void AddConfirmedOperations()
  55. {
  56. var operations = GetAllConfirmedOperations().OrderBy(x => x.DocDate).ThenBy(x => x.CreatedDate).ToList();
  57. var newOperations = GetAllNewOperations().OrderBy(x => x.DocDate).ThenBy(x => x.CreatedDate).ToList();
  58. var transactiondHashSet = GetAllTransactions().Select(x => x.BankOperationId).ToHashSet();
  59. BankAccountBalance accountBalance;
  60. Transaction transaction;
  61. foreach (var item in operations) {
  62. if (!transactiondHashSet.Contains(item.Id)) {
  63. accountBalance = GetAccountBalanceByBusinessId(item.BankAccountId.Value, item.BusinessId.Value);
  64. accountBalance.Amount = accountBalance.Amount!.Value + item.IncomeAmount!.Value - item.OutcomeAmount!.Value;
  65. transaction = new Transaction {
  66. Id = Guid.NewGuid(),
  67. BankOperationId = item.Id,
  68. IncomeAmount = item.IncomeAmount,
  69. OutcomeAmount = item.OutcomeAmount,
  70. BalanceAmount = item.IncomeAmount!.Value - item.OutcomeAmount!.Value,
  71. ModifiedDate = item.DocDate,
  72. BusinessId = item.BusinessId.Value,
  73. BankAccountId = item.BankAccountId.Value,
  74. CreateDate = DateTime.Now,
  75. OperationCreateDate = item.CreatedDate!.Value,
  76. IsChanged = true,
  77. };
  78. _logger.LogInformation(Environment.NewLine + "Created new Transaction {0}", transaction.Id);
  79. _repositoryWrapper.Transaction.Create(transaction);
  80. _repositoryWrapper.BankAccountBalance.Update(accountBalance);
  81. _repositoryWrapper.Save();
  82. _repositoryWrapper.Transaction.Detach(transaction);
  83. _repositoryWrapper.BankAccountBalance.Detach(accountBalance);
  84. }
  85. else if(transactiondHashSet.Contains(item.Id) && item.IsChanged == true) {
  86. UpdateChangedOperations(item, true);
  87. }
  88. }
  89. foreach (var item in newOperations) {
  90. if (transactiondHashSet.Contains(item.Id)) {
  91. UpdateChangedOperations(item, false);
  92. }
  93. }
  94. }
  95. void UpdateChangedOperations(BankOperation operation, bool IsChanged)
  96. {
  97. Transaction transaction = GetTransactionByOperationId(operation.Id);
  98. var accountBalance = GetAccountBalanceByBusinessId(operation.BankAccountId.Value, operation.BusinessId.Value);
  99. decimal incomeDifference, outcomeDifference;
  100. if (!IsChanged) {
  101. incomeDifference = -1 * transaction.IncomeAmount.Value;
  102. outcomeDifference = -1 * transaction.OutcomeAmount.Value;
  103. _repositoryWrapper.Transaction.Delete(transaction);
  104. }
  105. else {
  106. incomeDifference = operation.IncomeAmount.Value - transaction.IncomeAmount.Value;
  107. outcomeDifference = operation.OutcomeAmount.Value - transaction.OutcomeAmount.Value;
  108. transaction.IncomeAmount += incomeDifference;
  109. transaction.OutcomeAmount += outcomeDifference;
  110. operation.IsChanged = false;
  111. _logger.LogInformation("Updated transaction with id: {0}", transaction.Id);
  112. _repositoryWrapper.Transaction.Update(transaction);
  113. _repositoryWrapper.BankOperation.Update(operation);
  114. }
  115. accountBalance.Amount = accountBalance.Amount + incomeDifference - outcomeDifference;
  116. _repositoryWrapper.BankAccountBalance.Update(accountBalance);
  117. _repositoryWrapper.Save();
  118. _repositoryWrapper.Transaction.Detach(transaction);
  119. var transactionsList = GetTransactionsByAccountId(operation.BankAccountId.Value, operation.BusinessId.Value).Where(x => x.BusinessId == operation.BusinessId && x.BankAccountId == operation.BankAccountId && DateTime.Compare(x.ModifiedDate.Value, transaction.ModifiedDate.Value) >= 0).OrderBy(x => x.ModifiedDate).ThenBy(x => x.OperationCreateDate).ToList();
  120. foreach(var item in transactionsList) {
  121. item.BalanceAmount = item.BalanceAmount + incomeDifference - outcomeDifference;
  122. _logger.LogInformation("Updated transaction with id: {0}", transaction.Id);
  123. _repositoryWrapper.Transaction.Update(item);
  124. _repositoryWrapper.Save();
  125. _repositoryWrapper.Transaction.Detach(item);
  126. }
  127. }
  128. void UpdateConfirmedTransactions()
  129. {
  130. var bankAccounts = GetAllBankBalances().ToList();
  131. List<Transaction> transactions;
  132. decimal newValue = 0M;
  133. foreach (var account in bankAccounts) {
  134. transactions = GetTransactionsByAccountId(account.BankAccountId.Value, account.BusinessId.Value).OrderBy(x => x.ModifiedDate).ThenBy(x => x.OperationCreateDate).ToList();
  135. for (int i = 1; i < transactions.Count; i++) {
  136. if (transactions[i].IsChanged == true) {
  137. transactions[i].BalanceAmount += transactions[i - 1].BalanceAmount;
  138. newValue += transactions[i].IncomeAmount.Value - transactions[i].OutcomeAmount.Value;
  139. transactions[i].IsChanged = false;
  140. }
  141. else {
  142. transactions[i].BalanceAmount += newValue;
  143. }
  144. _repositoryWrapper.Transaction.Update(transactions[i]);
  145. _repositoryWrapper.Save();
  146. }
  147. }
  148. }
  149. void SetTransactionsForAccount(decimal? balance, Guid accountId, Guid businessId)
  150. {
  151. var operations = GetAllConfirmedOperations(accountId, businessId).OrderBy(x => x.DocDate).ToList();
  152. var transactionsHashSet = GetTransactionsByAccountId(accountId, businessId).Select(x => x.BankOperationId).ToHashSet();
  153. Transaction transaction = new Transaction();
  154. var currentBalance = GetTransactionsByAccountId(accountId, businessId).Sum(x => (x.IncomeAmount - x.OutcomeAmount));
  155. for (int i = 0; i < operations.Count; i++) {
  156. if (!transactionsHashSet.Contains(operations[i].Id)) {
  157. currentBalance = currentBalance + operations[i].IncomeAmount!.Value - operations[i].OutcomeAmount!.Value;
  158. transaction.Id = Guid.NewGuid();
  159. transaction.IncomeAmount = operations[i].IncomeAmount;
  160. transaction.OutcomeAmount = operations[i].OutcomeAmount;
  161. transaction.BankOperationId = operations[i].Id;
  162. transaction.IsChanged = false;
  163. transaction.ModifiedDate = operations[i].DocDate;
  164. transaction.BusinessId = businessId;
  165. transaction.BankAccountId = accountId;
  166. transaction.BalanceAmount = currentBalance??0;
  167. _repositoryWrapper.Transaction.Create(transaction);
  168. _repositoryWrapper.Save();
  169. }
  170. }
  171. _logger.LogInformation($"{operations.Count} count records was written");
  172. }
  173. }