UpdateOperations.cs 12 KB

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