Murad Shirinov 1 year ago
parent
commit
a441108a5e

+ 1 - 0
BankOperationsUpdate.WorkerService/Data/Models/BankOperationDTO.cs

@@ -26,5 +26,6 @@ public class BankOperationDTO
26 26
 	public Guid? CustomHouseItemsCollectionId { get; set; }
27 27
 	public decimal? AdvanceAmount { get; set; }
28 28
 	public decimal? BalanceAmount { get; set; }
29
+	public long OrderId { get; set; }
29 30
 }
30 31
 

+ 1 - 0
BankOperationsUpdate.WorkerService/Data/Models/TransactionsDTO.cs

@@ -10,5 +10,6 @@ public class TransactionsDTO
10 10
 	public decimal? OutcomeAmount { get; set; }
11 11
 	public decimal BalanceAmount { get; set; }
12 12
 	public bool IsChanged { get; set; }
13
+	public long OperationOrderId { get; set; }
13 14
 }
14 15
 

+ 83 - 37
BankOperationsUpdate.WorkerService/OperationsUpdate/UpdateOperations.cs

@@ -1,5 +1,7 @@
1 1
 
2 2
 
3
+using System.Security;
4
+
3 5
 namespace BankOperationsUpdate.WorkerService.OperationsUpdate;
4 6
 
5 7
 public  class UpdateOperations
@@ -55,12 +57,12 @@ public  class UpdateOperations
55 57
 	void SetTransactionsInitial()
56 58
 	{
57 59
 		var bankBalances = GetAllBankBalances().ToList();
58
-		decimal? currentBalance;
59 60
 
60 61
 		for(int i = 0; i < bankBalances.Count; i++) {
61
-			currentBalance = bankBalances[i].Amount;
62
+
62 63
 			_logger.LogDebug("Process for account {0}", bankBalances[i].Id);
63
-			SetTransactionsForAccount(currentBalance, bankBalances[i].BankAccountId.Value, bankBalances[i].BusinessId.Value);
64
+
65
+			SetTransactionsForAccount(bankBalances[i]!.BankAccountId.Value, bankBalances[i]!.BusinessId.Value);
64 66
 
65 67
 		}
66 68
 	}
@@ -69,38 +71,51 @@ public  class UpdateOperations
69 71
 
70 72
 	void AddConfirmedOperations()
71 73
 	{
72
-		var operations = GetAllConfirmedOperations().OrderBy(x => x.DocDate).ThenBy(x => x.CreatedDate).ToList();
73
-		var newOperations = GetAllNewOperations().OrderBy(x => x.DocDate).ThenBy(x => x.CreatedDate).ToList();
74
+        //get all operations with Confirmed status 
75
+        var operations = GetAllConfirmedOperations().OrderBy(x => x.DocDate).ThenBy(x => x.OrderId).ToList();
76
+		//get all operations with New status 
77
+		var newOperations = GetAllNewOperations().OrderBy(x => x.DocDate).ThenBy(x => x.OrderId).ToList();
78
+		//get all bankOperationIds that added to transactions
74 79
 		var transactiondHashSet = GetAllTransactions().Select(x => x.BankOperationId).ToHashSet();
80
+
75 81
 		BankAccountBalance accountBalance;
76 82
 		Transaction transaction;
77 83
 
78 84
 		foreach (var item in operations) {
79 85
 
86
+			//if transaction with opertion id doesn't exist then add new transatcion and change balance 
80 87
 			if (!transactiondHashSet.Contains(item.Id)) {
81
-				accountBalance = GetAccountBalanceByBusinessId(item.BankAccountId.Value, item.BusinessId.Value);
82
-				accountBalance.Amount = accountBalance.Amount!.Value + item.IncomeAmount!.Value - item.OutcomeAmount!.Value;
83
-
84
-				transaction = new Transaction {
85
-					Id = Guid.NewGuid(),
86
-					BankOperationId = item.Id,
87
-					IncomeAmount = item.IncomeAmount,
88
-					OutcomeAmount = item.OutcomeAmount,
89
-					BalanceAmount = item.IncomeAmount!.Value - item.OutcomeAmount!.Value,
90
-					ModifiedDate = item.DocDate,
91
-					BusinessId = item.BusinessId.Value,
92
-					BankAccountId = item.BankAccountId.Value,
93
-					CreateDate = DateTime.Now,
94
-					OperationCreateDate = item.CreatedDate!.Value,
95
-					IsChanged = true,
96
-				};
97
-
98
-				_logger.LogInformation(Environment.NewLine + "Created new Transaction {0}", transaction.Id);
99
-				_repositoryWrapper.Transaction.Create(transaction);
100
-				_repositoryWrapper.BankAccountBalance.Update(accountBalance);
101
-				_repositoryWrapper.Save();
102
-				_repositoryWrapper.Transaction.Detach(transaction);
103
-				_repositoryWrapper.BankAccountBalance.Detach(accountBalance);
88
+				try {
89
+					accountBalance = GetAccountBalanceByBusinessId(item.BankAccountId!.Value, item.BusinessId!.Value);
90
+					//change balance on certain amount
91
+					accountBalance.Amount = accountBalance.Amount!.Value + item.IncomeAmount!.Value - item.OutcomeAmount!.Value;
92
+
93
+					//create new transaction
94
+					transaction = new Transaction {
95
+						Id = Guid.NewGuid(),
96
+						BankOperationId = item.Id,
97
+						IncomeAmount = item.IncomeAmount,
98
+						OutcomeAmount = item.OutcomeAmount,
99
+						BalanceAmount = item.IncomeAmount!.Value - item.OutcomeAmount!.Value,
100
+						ModifiedDate = item.DocDate,
101
+						BusinessId = item.BusinessId.Value,
102
+						BankAccountId = item.BankAccountId.Value,
103
+						CreateDate = DateTime.Now,
104
+						OperationCreateDate = item.CreatedDate ?? item.DocDate!.Value,
105
+						IsChanged = true,
106
+						OperationOrderId = item.OrderId,
107
+					};
108
+
109
+					_logger.LogInformation(Environment.NewLine + "Created new Transaction {0}", transaction.Id);
110
+					_repositoryWrapper.Transaction.Create(transaction);
111
+					_repositoryWrapper.BankAccountBalance.Update(accountBalance);
112
+					_repositoryWrapper.Save();
113
+					_repositoryWrapper.Transaction.Detach(transaction);
114
+					_repositoryWrapper.BankAccountBalance.Detach(accountBalance);
115
+				}
116
+				catch(Exception ex) {
117
+					_logger.LogError(ex.Message);
118
+				}
104 119
 			
105 120
 			}
106 121
 			else if(transactiondHashSet.Contains(item.Id) && item.IsChanged == true) {
@@ -125,13 +140,16 @@ public  class UpdateOperations
125 140
 		var accountBalance = GetAccountBalanceByBusinessId(operation.BankAccountId.Value, operation.BusinessId.Value);
126 141
 		decimal incomeDifference, outcomeDifference;
127 142
 
143
+		//if it is bankOperation with new status that already was in transatctions
128 144
 		if (!IsChanged) {
129
-
145
+			 //get the income or outcome sum of rollBackcked transaction
130 146
 			incomeDifference = -1 * transaction.IncomeAmount.Value;
131 147
 			outcomeDifference = -1 * transaction.OutcomeAmount.Value;
132 148
 			_repositoryWrapper.Transaction.Delete(transaction);
133 149
 		}
150
+		//else if it is confirmed transaction that has already in transactions
134 151
 		else {
152
+			 //get the income or outcome difference that opertion was changed
135 153
 			incomeDifference = operation.IncomeAmount.Value - transaction.IncomeAmount.Value;
136 154
 			outcomeDifference = operation.OutcomeAmount.Value - transaction.OutcomeAmount.Value;
137 155
 
@@ -149,8 +167,16 @@ public  class UpdateOperations
149 167
 		_repositoryWrapper.BankAccountBalance.Update(accountBalance);
150 168
 		_repositoryWrapper.Save();
151 169
 		_repositoryWrapper.Transaction.Detach(transaction);
170
+        _repositoryWrapper.BankAccountBalance.Detach(accountBalance);
171
+
152 172
 
153
-		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();
173
+        //get the transactions that come after modified transaction and change their balanceAmount on cahnged certain amount
174
+        var transactionsList = GetTransactionsByAccountId(operation.BankAccountId.Value, operation.BusinessId.Value)
175
+			.Where(x => x.BusinessId == operation.BusinessId && 
176
+				x.BankAccountId == operation.BankAccountId && 
177
+				DateTime.Compare(x.ModifiedDate.Value, transaction.ModifiedDate.Value) >= 0)
178
+			.OrderBy(x => x.ModifiedDate)
179
+			.ThenBy(x => x.OperationOrderId).ToList();	 
154 180
 
155 181
 		foreach(var item  in transactionsList) {
156 182
 			item.BalanceAmount = item.BalanceAmount + incomeDifference - outcomeDifference;
@@ -162,6 +188,8 @@ public  class UpdateOperations
162 188
 
163 189
 	}
164 190
 
191
+
192
+	//update all new added transactions for updating balance amount of items that comes after updated  item
165 193
 	void UpdateConfirmedTransactions()
166 194
 	{
167 195
 		var bankAccounts = GetAllBankBalances().ToList();
@@ -169,12 +197,12 @@ public  class UpdateOperations
169 197
 		decimal newValue = 0M;
170 198
 
171 199
 		foreach (var account in bankAccounts) {
172
-			transactions = GetTransactionsByAccountId(account.BankAccountId.Value, account.BusinessId.Value).OrderBy(x => x.ModifiedDate).ThenBy(x => x.OperationCreateDate).ToList();
200
+			transactions = GetTransactionsByAccountId(account.BankAccountId!.Value, account.BusinessId!.Value).OrderBy(x => x.ModifiedDate).ThenBy(x => x.OperationOrderId).ToList();
173 201
 
174 202
 			for (int i = 1; i < transactions.Count; i++) {
175 203
 				if (transactions[i].IsChanged == true) {
176 204
 					transactions[i].BalanceAmount += transactions[i - 1].BalanceAmount;
177
-					newValue += transactions[i].IncomeAmount.Value - transactions[i].OutcomeAmount.Value;
205
+					newValue += transactions[i].IncomeAmount!.Value - transactions[i].OutcomeAmount!.Value;
178 206
 					transactions[i].IsChanged = false;
179 207
 				}
180 208
 				else {
@@ -187,17 +215,31 @@ public  class UpdateOperations
187 215
 		}
188 216
 	}
189 217
 
190
-	void SetTransactionsForAccount(decimal? balance, Guid accountId, Guid businessId)
218
+
219
+	/// <summary>
220
+	/// Create transatction for each bank operation	 if they don't exist
221
+	/// </summary>
222
+	/// <param name="accountId"></param>
223
+	/// <param name="businessId"></param>
224
+	void SetTransactionsForAccount(Guid accountId, Guid businessId)
191 225
 	{
192
-		var operations =  GetAllConfirmedOperations(accountId, businessId).OrderBy(x => x.DocDate).ToList();
226
+		//get all confirmed operations by accountId and businessId and order them by DocDate
227
+		var operations =  GetAllConfirmedOperations(accountId, businessId).OrderBy(x => x.DocDate).ThenBy(x => x.OrderId).ToList();
228
+		
229
+		// get Unitque bankOpertionsIds from transatctions 
193 230
 		var transactionsHashSet = GetTransactionsByAccountId(accountId, businessId).Select(x => x.BankOperationId).ToHashSet();
194 231
 		Transaction transaction = new Transaction();
232
+
233
+		//get current balance by summarizing all Incomes and outcomes from transacitons
195 234
 		var currentBalance = GetTransactionsByAccountId(accountId, businessId).Sum(x => (x.IncomeAmount - x.OutcomeAmount));
196 235
 											   
197 236
 
198
-		for (int i = 0; i < operations.Count; i++) {
237
+		for (int i = 0; i < operations.Count && transactionsHashSet.Count == 0; i++) {
238
+
239
+			//if BankOperationsIds doesn't contain confirmed operations then..
240
+			if (!transactionsHashSet.Contains(operations[i].Id) ) {
199 241
 
200
-			if (!transactionsHashSet.Contains(operations[i].Id)) {
242
+				//change balance on certain income or outcome amount
201 243
 				currentBalance = currentBalance + operations[i].IncomeAmount!.Value - operations[i].OutcomeAmount!.Value;
202 244
 
203 245
 				transaction.Id = Guid.NewGuid();
@@ -208,8 +250,12 @@ public  class UpdateOperations
208 250
 				transaction.ModifiedDate = operations[i].DocDate;
209 251
 				transaction.BusinessId = businessId;
210 252
 				transaction.BankAccountId = accountId;
211
-				transaction.BalanceAmount = currentBalance??0;
253
+				transaction.CreateDate = DateTime.Now;
254
+                transaction.OperationCreateDate = operations[i].CreatedDate ?? transaction.ModifiedDate!.Value;
255
+                transaction.BalanceAmount = currentBalance ?? 0;
256
+				transaction.OperationOrderId = operations[i].OrderId;
212 257
 
258
+				//create transaction
213 259
 				_repositoryWrapper.Transaction.Create(transaction);
214 260
 				_repositoryWrapper.Save();
215 261
 			}

+ 4 - 1
BankOperationsUpdate.WorkerService/Worker.cs

@@ -12,15 +12,18 @@ public class Worker : BackgroundService
12 12
 		_updateOperations = updateOperations;
13 13
 		refreshInterval = Int32.TryParse(config.GetSection("RefreshInterval").Value, out int minutes) ? TimeSpan.FromMinutes(5) : TimeSpan.FromMinutes(minutes);
14 14
 	}
15
+	
15 16
 
16 17
 	protected override async Task ExecuteAsync(CancellationToken stoppingToken)
17 18
 	{
19
+		_updateOperations.WhenStart();
20
+
18 21
 		while (!stoppingToken.IsCancellationRequested) {
19 22
 			try {
20 23
 				_updateOperations.Execute();
21 24
 			}
22 25
 			catch (Exception ex) {
23
-				_logger.LogError(ex.Message);
26
+				_logger.LogError("Message: {message} \n Source : {source} \n StackTrace: {stackTrace}", ex.Message, ex.Source, ex.StackTrace);
24 27
 				
25 28
 			}
26 29
 			

+ 1 - 0
Entities/Models/BankOperation.cs

@@ -35,6 +35,7 @@ namespace Entities.Models
35 35
         public decimal? AdvanceAmount { get; set; }
36 36
         public decimal? BalanceAmount { get; set; }
37 37
         public bool? IsChanged { get; set; }
38
+        public long OrderId { get; set; }
38 39
 
39 40
         public virtual ICollection<Transaction> SkTransactions { get; set; }
40 41
     }

+ 1 - 0
Entities/Models/Transaction.cs

@@ -12,6 +12,7 @@ namespace Entities.Models
12 12
         public decimal? IncomeAmount { get; set; }
13 13
         public decimal? OutcomeAmount { get; set; }
14 14
         public decimal BalanceAmount { get; set; }
15
+        public long OperationOrderId { get; set; }
15 16
         public bool IsChanged { get; set; }
16 17
         public DateTime? ModifiedDate { get; set; }
17 18
         public Guid BankAccountId { get; set; }

+ 7 - 2
Entities/RepositoryContext.cs

@@ -73,7 +73,10 @@ namespace Entities
73 73
 
74 74
 				entity.Property(e => e.IsChanged).HasDefaultValue(false);
75 75
 
76
-			});
76
+                entity.Property(e => e.OrderId);
77
+
78
+
79
+            });
77 80
 
78 81
 			modelBuilder.Entity<Transaction>(entity => {
79 82
 				entity.ToTable("SK_Transactions", "SEPTEM");
@@ -98,7 +101,9 @@ namespace Entities
98 101
 
99 102
 				entity.HasIndex(e => e.BusinessId);
100 103
 
101
-				entity.HasOne(d => d.BankOperation)
104
+				entity.Property(e => e.OperationOrderId);
105
+
106
+                entity.HasOne(d => d.BankOperation)
102 107
 					.WithMany(p => p.SkTransactions)
103 108
 					.HasForeignKey(d => d.BankOperationId)
104 109
 					.HasForeignKey(d => d.BankAccountId);