gemcap-be-common 1.2.140 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (303) hide show
  1. package/classes/bank-transaction-item.d.ts +17 -0
  2. package/classes/bank-transaction-item.js +64 -0
  3. package/classes/bank-transaction-item.ts +66 -0
  4. package/classes/bank-uploaded-transaction.d.ts +17 -0
  5. package/classes/bank-uploaded-transaction.js +35 -0
  6. package/classes/bank-uploaded-transaction.ts +35 -0
  7. package/classes/inventory-item.d.ts +41 -0
  8. package/classes/inventory-item.js +44 -0
  9. package/classes/inventory-item.ts +63 -0
  10. package/classes/payable-account-item.d.ts +22 -0
  11. package/classes/payable-account-item.js +27 -0
  12. package/classes/payable-account-item.ts +35 -0
  13. package/classes/quickbook-item.d.ts +37 -0
  14. package/classes/quickbook-item.js +51 -0
  15. package/classes/quickbook-item.ts +59 -0
  16. package/classes/receivable-item.d.ts +26 -0
  17. package/classes/receivable-item.js +28 -0
  18. package/classes/receivable-item.ts +38 -0
  19. package/constants/date-formats.contsants.d.ts +1 -0
  20. package/constants/date-formats.contsants.js +4 -0
  21. package/constants/date-formats.contsants.ts +1 -0
  22. package/db/brokers.db.d.ts +185 -0
  23. package/db/brokers.db.js +35 -2
  24. package/db/brokers.db.ts +34 -1
  25. package/db/collateral-adjustments.db.d.ts +34 -0
  26. package/db/collateral-adjustments.db.js +52 -0
  27. package/db/collateral-adjustments.db.ts +54 -0
  28. package/db/collaterals.db.d.ts +1 -1
  29. package/db/equipment.db.d.ts +40 -0
  30. package/db/equipment.db.js +55 -0
  31. package/db/equipment.db.ts +56 -0
  32. package/db/financial-spreading.db.ts +2 -1
  33. package/db/groups.d.ts +5 -0
  34. package/db/groups.js +57 -0
  35. package/db/groups.ts +52 -0
  36. package/db/inventories.d.ts +91 -0
  37. package/db/inventories.js +449 -0
  38. package/db/inventories.ts +481 -0
  39. package/db/inventory-availability.d.ts +3 -0
  40. package/db/inventory-availability.js +103 -0
  41. package/db/inventory-availability.ts +113 -0
  42. package/db/new-summary.d.ts +31 -0
  43. package/db/new-summary.js +1295 -0
  44. package/db/new-summary.ts +1509 -0
  45. package/db/payable-accounts.d.ts +30 -0
  46. package/db/payable-accounts.js +55 -0
  47. package/db/payable-accounts.ts +50 -0
  48. package/db/reserve.db.d.ts +34 -0
  49. package/db/reserve.db.js +52 -0
  50. package/db/reserve.db.ts +48 -0
  51. package/db/uploads.db.d.ts +2 -0
  52. package/db/uploads.db.js +29 -0
  53. package/db/uploads.db.ts +24 -0
  54. package/helpers/main.helper.d.ts +31 -0
  55. package/helpers/main.helper.js +63 -0
  56. package/helpers/main.helper.ts +63 -0
  57. package/models/AccountPayableItem.model.d.ts +6 -6
  58. package/models/AllocatedBankTransaction.model.d.ts +54 -0
  59. package/models/AllocatedBankTransaction.model.js +70 -0
  60. package/models/AllocatedBankTransaction.model.ts +94 -0
  61. package/models/AllocatedData.model.d.ts +33 -0
  62. package/models/AllocatedData.model.js +19 -0
  63. package/models/AllocatedData.model.ts +24 -0
  64. package/models/BBCDate.model.d.ts +3 -3
  65. package/models/BBCSheet.model.d.ts +3 -3
  66. package/models/Banks.model.d.ts +3 -3
  67. package/models/Borrower.model.d.ts +3 -3
  68. package/models/BorrowerData.model.d.ts +3 -3
  69. package/models/BorrowerDataInsurance.model.d.ts +3 -3
  70. package/models/BorrowerDataTerm.model.d.ts +3 -3
  71. package/models/BorrowerSummary.model.js +1 -1
  72. package/models/BorrowerSummary.model.ts +1 -1
  73. package/models/CalandarDay.model.d.ts +40 -0
  74. package/models/CalandarDay.model.js +47 -0
  75. package/models/CalandarDay.model.ts +61 -0
  76. package/models/CashAllocationProduct.model.d.ts +119 -0
  77. package/models/CashAllocationProduct.model.js +102 -0
  78. package/models/CashAllocationProduct.model.ts +112 -0
  79. package/models/CashAllocationReference.model.d.ts +37 -0
  80. package/models/CashAllocationReference.model.js +27 -0
  81. package/models/CashAllocationReference.model.ts +40 -0
  82. package/models/CollateralAdjustment.model.d.ts +51 -0
  83. package/models/CollateralAdjustment.model.js +61 -0
  84. package/models/CollateralAdjustment.model.ts +98 -0
  85. package/models/Company.model.d.ts +35 -0
  86. package/models/Company.model.js +18 -0
  87. package/models/Company.model.ts +29 -0
  88. package/models/CustomerAPGroup.model.d.ts +32 -0
  89. package/models/CustomerAPGroup.model.js +24 -0
  90. package/models/CustomerAPGroup.model.ts +31 -0
  91. package/models/Equipment.model.d.ts +53 -0
  92. package/models/Equipment.model.js +140 -0
  93. package/models/Equipment.model.ts +172 -0
  94. package/models/FinancialCompliance.model.d.ts +39 -0
  95. package/models/FinancialCompliance.model.js +64 -0
  96. package/models/FinancialCompliance.model.ts +78 -0
  97. package/models/FinancialComplianceBorrower.model.d.ts +58 -0
  98. package/models/FinancialComplianceBorrower.model.js +82 -0
  99. package/models/FinancialComplianceBorrower.model.ts +118 -0
  100. package/models/FinancialIndexes.model.d.ts +36 -0
  101. package/models/FinancialIndexes.model.js +27 -0
  102. package/models/FinancialIndexes.model.ts +37 -0
  103. package/models/Inventory.model.d.ts +18 -18
  104. package/models/InventoryAvailability.model.d.ts +21 -21
  105. package/models/InventoryAvailabilityItem.model.d.ts +6 -6
  106. package/models/InventoryItem.model.d.ts +24 -24
  107. package/models/InventoryManualEntry.model.d.ts +9 -9
  108. package/models/InventorySeasonalRates.model.d.ts +3 -3
  109. package/models/LoanBroker.model.d.ts +3 -3
  110. package/models/LoanCharges.model.d.ts +12 -12
  111. package/models/LoanProducts.model.d.ts +9 -9
  112. package/models/LoanStatementStatus.model.d.ts +35 -0
  113. package/models/LoanStatementStatus.model.js +34 -0
  114. package/models/LoanStatementStatus.model.ts +45 -0
  115. package/models/LoanStatementTransaction.model.d.ts +9 -9
  116. package/models/LoanTransactionFile.model.d.ts +41 -0
  117. package/models/LoanTransactionFile.model.js +44 -0
  118. package/models/LoanTransactionFile.model.ts +61 -0
  119. package/models/MappedGroup.model.d.ts +37 -0
  120. package/models/MappedGroup.model.js +33 -0
  121. package/models/MappedGroup.model.ts +46 -0
  122. package/models/MonthEndData.Model.d.ts +41 -0
  123. package/models/MonthEndData.Model.js +42 -0
  124. package/models/MonthEndData.Model.ts +53 -0
  125. package/models/OrganizationEmails.model.d.ts +44 -0
  126. package/models/OrganizationEmails.model.js +40 -0
  127. package/models/OrganizationEmails.model.ts +54 -0
  128. package/models/ProductBroker.model.d.ts +9 -9
  129. package/models/QuickbooksAccount.model.d.ts +39 -0
  130. package/models/QuickbooksAccount.model.js +43 -0
  131. package/models/QuickbooksAccount.model.ts +57 -0
  132. package/models/Receivable.model.d.ts +12 -12
  133. package/models/ReceivableAvailability.model.d.ts +54 -54
  134. package/models/ReceivableAvailabilityItem.model.d.ts +57 -57
  135. package/models/ReceivableItem.model.d.ts +6 -6
  136. package/models/Reserve.model.d.ts +51 -0
  137. package/models/Reserve.model.js +96 -0
  138. package/models/Reserve.model.ts +125 -0
  139. package/models/TermLoan.model.d.ts +3 -3
  140. package/models/TermLoanCalculated.model.d.ts +6 -6
  141. package/models/TransactionAttachedFile.Model.d.ts +35 -0
  142. package/models/TransactionAttachedFile.Model.js +37 -0
  143. package/models/TransactionAttachedFile.Model.ts +48 -0
  144. package/models/UploadedBankTransaction.model.d.ts +56 -0
  145. package/models/UploadedBankTransaction.model.js +78 -0
  146. package/models/UploadedBankTransaction.model.ts +110 -0
  147. package/models/UploadedData.model.d.ts +36 -0
  148. package/models/UploadedData.model.js +23 -0
  149. package/models/UploadedData.model.ts +35 -0
  150. package/models/UploadedFile.model.d.ts +40 -0
  151. package/models/UploadedFile.model.js +41 -0
  152. package/models/UploadedFile.model.ts +57 -0
  153. package/models/UploadedSheet.model.d.ts +46 -0
  154. package/models/UploadedSheet.model.js +27 -0
  155. package/models/UploadedSheet.model.ts +51 -0
  156. package/package.json +10 -1
  157. package/repositories/globals.repository.d.ts +8 -0
  158. package/repositories/globals.repository.js +24 -0
  159. package/repositories/globals.repository.ts +21 -0
  160. package/services/attached-files.service.d.ts +57 -0
  161. package/services/attached-files.service.js +103 -0
  162. package/services/attached-files.service.ts +123 -0
  163. package/services/availability.service.d.ts +77 -0
  164. package/services/availability.service.js +897 -0
  165. package/services/availability.service.ts +1034 -0
  166. package/services/bank-uploaded-transactions.service.d.ts +33 -0
  167. package/services/bank-uploaded-transactions.service.js +430 -0
  168. package/services/bank-uploaded-transactions.service.ts +475 -0
  169. package/services/banks.service.d.ts +36 -0
  170. package/services/banks.service.js +91 -0
  171. package/services/banks.service.ts +95 -0
  172. package/services/borrower-summary.service.d.ts +35 -0
  173. package/services/borrower-summary.service.js +310 -0
  174. package/services/borrower-summary.service.ts +334 -0
  175. package/services/borrowers.service.d.ts +103 -0
  176. package/services/borrowers.service.js +268 -0
  177. package/services/borrowers.service.ts +302 -0
  178. package/services/brokers.service.d.ts +212 -0
  179. package/services/brokers.service.js +160 -0
  180. package/services/brokers.service.ts +200 -0
  181. package/services/calendar.service.d.ts +53 -0
  182. package/services/calendar.service.js +108 -0
  183. package/services/calendar.service.ts +128 -0
  184. package/services/cash-allocation.service.d.ts +40 -0
  185. package/services/cash-allocation.service.js +92 -0
  186. package/services/cash-allocation.service.ts +105 -0
  187. package/services/collateral-adjustments.service.d.ts +38 -0
  188. package/services/collateral-adjustments.service.js +82 -0
  189. package/services/collateral-adjustments.service.ts +95 -0
  190. package/services/collaterals.service.d.ts +69 -0
  191. package/services/collaterals.service.js +279 -0
  192. package/services/collaterals.service.ts +319 -0
  193. package/services/companies.service.d.ts +5 -0
  194. package/services/companies.service.js +21 -0
  195. package/services/companies.service.ts +23 -0
  196. package/services/compliance-borrowers.service.d.ts +152 -0
  197. package/services/compliance-borrowers.service.js +569 -0
  198. package/services/compliance-borrowers.service.ts +617 -0
  199. package/services/equipment.service.d.ts +42 -0
  200. package/services/equipment.service.js +120 -0
  201. package/services/equipment.service.ts +149 -0
  202. package/services/file-manager.service.d.ts +44 -0
  203. package/services/file-manager.service.js +120 -0
  204. package/services/file-manager.service.ts +146 -0
  205. package/services/financial-compliance.service.d.ts +58 -0
  206. package/services/financial-compliance.service.js +281 -0
  207. package/services/financial-compliance.service.ts +309 -0
  208. package/services/financial-indexes.service.d.ts +20 -0
  209. package/services/financial-indexes.service.js +241 -0
  210. package/services/financial-indexes.service.ts +257 -0
  211. package/services/financial-spreading.service.d.ts +74 -0
  212. package/services/financial-spreading.service.js +450 -0
  213. package/services/financial-spreading.service.ts +517 -0
  214. package/services/globals.service.d.ts +5 -0
  215. package/services/globals.service.js +11 -0
  216. package/services/globals.service.ts +8 -0
  217. package/services/groups.service.d.ts +39 -0
  218. package/services/groups.service.js +65 -0
  219. package/services/groups.service.ts +64 -0
  220. package/services/inventory-availability.service.d.ts +13 -0
  221. package/services/inventory-availability.service.js +170 -0
  222. package/services/inventory-availability.service.ts +187 -0
  223. package/services/inventory.service.d.ts +118 -0
  224. package/services/inventory.service.js +239 -0
  225. package/services/inventory.service.ts +276 -0
  226. package/services/loan-charges.service.d.ts +83 -0
  227. package/services/loan-charges.service.js +343 -0
  228. package/services/loan-charges.service.ts +396 -0
  229. package/services/loan-payments.service.d.ts +94 -0
  230. package/services/loan-payments.service.js +485 -0
  231. package/services/loan-payments.service.ts +541 -0
  232. package/services/loan-products.service.d.ts +12 -0
  233. package/services/loan-products.service.js +55 -0
  234. package/services/loan-products.service.ts +58 -0
  235. package/services/loan-statement-balance.service.d.ts +16 -0
  236. package/services/loan-statement-balance.service.js +106 -0
  237. package/services/loan-statement-balance.service.ts +113 -0
  238. package/services/loan-statement-effects.service.d.ts +8 -0
  239. package/services/loan-statement-effects.service.js +42 -0
  240. package/services/loan-statement-effects.service.ts +41 -0
  241. package/services/loan-statement-status.service.d.ts +208 -0
  242. package/services/loan-statement-status.service.js +159 -0
  243. package/services/loan-statement-status.service.ts +177 -0
  244. package/services/loan-statement.service.d.ts +186 -0
  245. package/services/loan-statement.service.js +935 -0
  246. package/services/loan-statement.service.ts +1040 -0
  247. package/services/loan-transactions.service.d.ts +169 -0
  248. package/services/loan-transactions.service.js +941 -0
  249. package/services/loan-transactions.service.ts +1042 -0
  250. package/services/lock.service.d.ts +6 -0
  251. package/services/lock.service.js +45 -0
  252. package/services/lock.service.ts +45 -0
  253. package/services/manual-entry.service.d.ts +20 -0
  254. package/services/manual-entry.service.js +186 -0
  255. package/services/manual-entry.service.ts +201 -0
  256. package/services/month-end-data.service.d.ts +34 -0
  257. package/services/month-end-data.service.js +30 -0
  258. package/services/month-end-data.service.ts +35 -0
  259. package/services/nodemailer.service.d.ts +96 -0
  260. package/services/nodemailer.service.js +689 -0
  261. package/services/nodemailer.service.ts +774 -0
  262. package/services/organization-emails.service.d.ts +31 -0
  263. package/services/organization-emails.service.js +10 -0
  264. package/services/organization-emails.service.ts +7 -0
  265. package/services/organizations.service.d.ts +34 -0
  266. package/services/organizations.service.js +74 -0
  267. package/services/organizations.service.ts +84 -0
  268. package/services/pdf.service.d.ts +61 -0
  269. package/services/pdf.service.js +547 -0
  270. package/services/pdf.service.ts +642 -0
  271. package/services/quickbooks.service.d.ts +99 -0
  272. package/services/quickbooks.service.js +640 -0
  273. package/services/quickbooks.service.ts +734 -0
  274. package/services/reports/investor-summary.service.d.ts +28 -0
  275. package/services/reports/investor-summary.service.js +136 -0
  276. package/services/reports/investor-summary.service.ts +159 -0
  277. package/services/reports.service.d.ts +126 -0
  278. package/services/reports.service.js +584 -0
  279. package/services/reports.service.ts +702 -0
  280. package/services/reserve.service.d.ts +37 -0
  281. package/services/reserve.service.js +76 -0
  282. package/services/reserve.service.ts +79 -0
  283. package/services/sentry.service.d.ts +11 -0
  284. package/services/sentry.service.js +49 -0
  285. package/services/sentry.service.ts +33 -0
  286. package/services/signs.service.d.ts +69 -0
  287. package/services/signs.service.js +230 -0
  288. package/services/signs.service.ts +260 -0
  289. package/services/term-loan.service.d.ts +30 -0
  290. package/services/term-loan.service.js +614 -0
  291. package/services/term-loan.service.ts +696 -0
  292. package/services/uploads.service.d.ts +134 -0
  293. package/services/uploads.service.js +587 -0
  294. package/services/uploads.service.ts +643 -0
  295. package/services/user-logs.service.d.ts +23 -0
  296. package/services/user-logs.service.js +160 -0
  297. package/services/user-logs.service.ts +177 -0
  298. package/services/users.service.d.ts +4 -4
  299. package/services/yield.service.d.ts +46 -0
  300. package/services/yield.service.js +42 -12
  301. package/services/yield.service.ts +38 -8
  302. package/tsconfig.json +5 -5
  303. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,33 @@
1
+ import { ISplitTransaction, IUploadedBankTransaction, IUploadedBankTransactionWithInfo } from '../models/UploadedBankTransaction.model';
2
+ import { IAllocatedBankTransaction, PreSplitUploadedBankTransactionWithInfo } from '../models/AllocatedBankTransaction.model';
3
+ import { LoanTransactionsService } from './loan-transactions.service';
4
+ import { CashAllocationService } from './cash-allocation.service';
5
+ import { LoanStatementStatusService } from './loan-statement-status.service';
6
+ export declare class BankUploadedTransactionsService {
7
+ private readonly cashAllocationService;
8
+ private readonly loanStatementStatusService;
9
+ private readonly getLoanTransactionsService;
10
+ constructor(cashAllocationService: CashAllocationService, loanStatementStatusService: LoanStatementStatusService, getLoanTransactionsService: () => LoanTransactionsService);
11
+ uploadTransactions(transactions: IUploadedBankTransaction[]): Promise<string>;
12
+ getAllocatedBankTransactions(startDate: Date, endDate: Date): Promise<IAllocatedBankTransaction[]>;
13
+ deleteAllocatedBankTransaction(transactionIds: string[]): Promise<void>;
14
+ getMappedUploadedBankTransactions(startDate: Date, endDate: Date): Promise<IUploadedBankTransactionWithInfo[]>;
15
+ getUploadedBankTransactions(startDate: Date, endDate: Date): Promise<IUploadedBankTransaction[]>;
16
+ getAllocatedTransactions(date: Date): Promise<IAllocatedBankTransaction[]>;
17
+ getPreAllocatedTransactions(date: Date): Promise<{
18
+ allocatedBankTransactions: IAllocatedBankTransaction[];
19
+ uploadedBankTransactions: PreSplitUploadedBankTransactionWithInfo[];
20
+ }>;
21
+ resetAllocatedBankTransactions(date: Date): Promise<void>;
22
+ createAllocatedBankTransactions(date: Date): Promise<void>;
23
+ convertBankTransactions(startDate: Date, userId: string): Promise<void>;
24
+ recalculateProducts(productIds: string[]): void;
25
+ preSplitBankTransactions(transactionId: string, splitTransaction: ISplitTransaction[]): Promise<void>;
26
+ deleteBankTransaction(transactionIds: string[]): Promise<void>;
27
+ revertAllBankTransactions(startDate: Date, endDate: Date, userId: string): Promise<void>;
28
+ revertBankTransactions(transactionIds: string[], userId: string): Promise<void>;
29
+ getUniqueDates(): Promise<any[]>;
30
+ saveAllocatedBankTransactions(date: Date, transactions: IAllocatedBankTransaction[]): Promise<void>;
31
+ createAllocatedBankTransaction(transaction: IAllocatedBankTransaction): Promise<void>;
32
+ updateLockStatus(date: Date, isLocked: boolean): Promise<void>;
33
+ }
@@ -0,0 +1,430 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.BankUploadedTransactionsService = void 0;
7
+ const mongoose_1 = __importDefault(require("mongoose"));
8
+ const decimal_js_1 = require("decimal.js");
9
+ const lodash_1 = __importDefault(require("lodash"));
10
+ const dayjs_1 = __importDefault(require("dayjs"));
11
+ const LoanTransaction_model_1 = require("../models/LoanTransaction.model");
12
+ const Banks_model_1 = require("../models/Banks.model");
13
+ const UploadedBankTransaction_model_1 = require("../models/UploadedBankTransaction.model");
14
+ const main_helper_1 = require("../helpers/main.helper");
15
+ const CashAllocationReference_model_1 = require("../models/CashAllocationReference.model");
16
+ const CashAllocationProduct_model_1 = require("../models/CashAllocationProduct.model");
17
+ const AllocatedBankTransaction_model_1 = require("../models/AllocatedBankTransaction.model");
18
+ const AllocatedData_model_1 = require("../models/AllocatedData.model");
19
+ const date_formats_contsants_1 = require("../constants/date-formats.contsants");
20
+ const useExternalUploader = false; // TODO keep only external upload
21
+ const createCashAllocationReferencesOnUpload = false;
22
+ class BankUploadedTransactionsService {
23
+ cashAllocationService;
24
+ loanStatementStatusService;
25
+ getLoanTransactionsService;
26
+ constructor(cashAllocationService, loanStatementStatusService, getLoanTransactionsService) {
27
+ this.cashAllocationService = cashAllocationService;
28
+ this.loanStatementStatusService = loanStatementStatusService;
29
+ this.getLoanTransactionsService = getLoanTransactionsService;
30
+ }
31
+ async uploadTransactions(transactions) {
32
+ if (useExternalUploader) {
33
+ const taskId = (0, main_helper_1.getUUID)();
34
+ // await this.queueService.sendTaskToQueue({
35
+ // data: { transactions, taskId },
36
+ // pattern: 'bank_uploaded_transactions#CREATE',
37
+ // }, 'goat_upload');
38
+ return taskId;
39
+ }
40
+ else {
41
+ const mappedTransactions = transactions.reduce((acc, transaction) => {
42
+ const normalizedTransaction = {
43
+ ...transaction,
44
+ reference: transaction.reference.trim(),
45
+ isConverted: false,
46
+ };
47
+ return [...acc, normalizedTransaction];
48
+ }, []);
49
+ await Promise.all(mappedTransactions.map(async (transaction) => {
50
+ const newTransactions = new UploadedBankTransaction_model_1.UploadedBankTransaction(transaction);
51
+ await newTransactions.save();
52
+ }));
53
+ if (createCashAllocationReferencesOnUpload) {
54
+ await this.cashAllocationService.createCashAllocation(mappedTransactions);
55
+ }
56
+ return null;
57
+ }
58
+ }
59
+ async getAllocatedBankTransactions(startDate, endDate) {
60
+ return AllocatedBankTransaction_model_1.AllocatedBankTransaction.aggregate([
61
+ {
62
+ $match: {
63
+ $and: [
64
+ { 'date': { $gte: startDate } },
65
+ { 'date': { $lte: endDate } },
66
+ ],
67
+ },
68
+ },
69
+ {
70
+ $sort: { order: 1, date: 1 },
71
+ },
72
+ ]);
73
+ }
74
+ async deleteAllocatedBankTransaction(transactionIds) {
75
+ await AllocatedBankTransaction_model_1.AllocatedBankTransaction.deleteMany({ uploadedBankTransactionId: { $in: transactionIds.map((id) => new mongoose_1.default.Types.ObjectId(id)) } });
76
+ }
77
+ async getMappedUploadedBankTransactions(startDate, endDate) {
78
+ const bankTransactions = await this.getUploadedBankTransactions(startDate, endDate);
79
+ const cashAllocationReferences = await CashAllocationReference_model_1.CashAllocationReference.find().lean();
80
+ const cashAllocationProducts = await CashAllocationProduct_model_1.CashAllocationProduct.find().lean();
81
+ const cashAllocationProductsMap = new Map();
82
+ cashAllocationProducts.forEach((product) => {
83
+ cashAllocationProductsMap.set(product._id.toString(), product);
84
+ });
85
+ const transactionHasMatch = (bankTransaction) => {
86
+ if (bankTransaction.splitTransactions.length > 0) {
87
+ const totalSplit = bankTransaction.splitTransactions.reduce((acc, split) => new decimal_js_1.Decimal(split.amount).add(acc).toNumber(), 0);
88
+ if (totalSplit === bankTransaction.amount) {
89
+ return true;
90
+ }
91
+ }
92
+ const foundCashAllocationReference = cashAllocationReferences.find((cashAllocationReference) => bankTransaction.reference.toLowerCase().includes(cashAllocationReference.reference.toLowerCase()));
93
+ if (!foundCashAllocationReference || !foundCashAllocationReference.cashAllocationProductId) {
94
+ return false;
95
+ }
96
+ return !!cashAllocationProductsMap.get(foundCashAllocationReference.cashAllocationProductId.toString());
97
+ };
98
+ const transactionCanSplit = (bankTransaction) => {
99
+ const foundCashAllocationReference = cashAllocationReferences.find((cashAllocationReference) => bankTransaction.reference.toLowerCase().includes(cashAllocationReference.reference.toLowerCase()));
100
+ if (!foundCashAllocationReference || !foundCashAllocationReference.cashAllocationProductId) {
101
+ return false;
102
+ }
103
+ const foundProduct = cashAllocationProductsMap.get(foundCashAllocationReference.cashAllocationProductId.toString());
104
+ return foundProduct.isCommonSplit;
105
+ };
106
+ return bankTransactions.map((bankTransaction) => {
107
+ return {
108
+ ...bankTransaction,
109
+ hasMatch: transactionHasMatch(bankTransaction),
110
+ canSplit: transactionCanSplit(bankTransaction),
111
+ };
112
+ });
113
+ }
114
+ async getUploadedBankTransactions(startDate, endDate) {
115
+ return UploadedBankTransaction_model_1.UploadedBankTransaction.aggregate([
116
+ {
117
+ $match: {
118
+ $and: [
119
+ { 'date': { $gte: startDate } },
120
+ { 'date': { $lte: endDate } },
121
+ ],
122
+ },
123
+ },
124
+ {
125
+ $sort: { date: 1 },
126
+ },
127
+ ]);
128
+ }
129
+ async getAllocatedTransactions(date) {
130
+ const startDate = (0, dayjs_1.default)(date).utcOffset(0).startOf('day');
131
+ const endDate = startDate.endOf('day');
132
+ return AllocatedBankTransaction_model_1.AllocatedBankTransaction.aggregate([
133
+ {
134
+ $match: {
135
+ $and: [
136
+ { 'date': { $gte: startDate.toDate() } },
137
+ { 'date': { $lte: endDate.toDate() } },
138
+ ],
139
+ },
140
+ },
141
+ {
142
+ $sort: { date: 1, order: 1 },
143
+ },
144
+ ]);
145
+ }
146
+ async getPreAllocatedTransactions(date) {
147
+ const startDate = (0, dayjs_1.default)(date).utcOffset(0).startOf('day');
148
+ const endDate = startDate.endOf('day');
149
+ const pureUploadedBankTransactions = await this.getMappedUploadedBankTransactions(startDate.toDate(), endDate.toDate());
150
+ const { references, products } = await this.cashAllocationService.getAllCashAllocations();
151
+ const populateAllocatedBankTransaction = (allocatedBankTransaction, cashAllocation) => {
152
+ const updatedAllocatedBankTransaction = lodash_1.default.cloneDeep(allocatedBankTransaction);
153
+ if (cashAllocation) {
154
+ const keysToUpdate = ['class', 'location', 'DRMemo', 'CRMemo'];
155
+ keysToUpdate.forEach((key) => {
156
+ updatedAllocatedBankTransaction[key] = cashAllocation[key];
157
+ });
158
+ updatedAllocatedBankTransaction.cashAllocationProductId = cashAllocation._id;
159
+ }
160
+ return updatedAllocatedBankTransaction;
161
+ };
162
+ let order = 0;
163
+ const uploadedBankTransactions = pureUploadedBankTransactions
164
+ .reduce((acc, tr) => {
165
+ if (tr.splitTransactions.length > 0) {
166
+ const restTransaction = {
167
+ ...tr,
168
+ order,
169
+ splitTransactionId: null,
170
+ splitMemo: '',
171
+ };
172
+ order = order + 1;
173
+ const splitTransactions = tr.splitTransactions.map((splitTr) => {
174
+ const foundRef = references.find((i) => i._id.toString() === splitTr.referenceId.toString());
175
+ const transaction = {
176
+ _id: tr._id,
177
+ order,
178
+ accountNumber: tr.accountNumber,
179
+ amount: splitTr.amount,
180
+ date: tr.date,
181
+ detail1: '',
182
+ detail2: '',
183
+ detail3: '',
184
+ hasMatch: true,
185
+ canSplit: false,
186
+ isConverted: tr.isConverted,
187
+ reference: foundRef ? foundRef.reference : tr.reference,
188
+ splitTransactions: [],
189
+ transactionType: tr.transactionType,
190
+ splitTransactionId: splitTr._id,
191
+ splitMemo: splitTr.memo,
192
+ };
193
+ restTransaction.amount = new decimal_js_1.Decimal(restTransaction.amount).sub(transaction.amount).toNumber();
194
+ return transaction;
195
+ });
196
+ if (restTransaction.amount !== 0) {
197
+ return [...acc, ...splitTransactions, restTransaction];
198
+ }
199
+ return [...acc, ...splitTransactions];
200
+ }
201
+ order = order + 1;
202
+ return [...acc, { ...tr, splitTransactionId: null, splitMemo: '', order }];
203
+ }, []);
204
+ const allocatedBankTransactions = uploadedBankTransactions
205
+ .reduce((acc, tr) => {
206
+ const allocatedBankTransaction = {
207
+ order: tr.order,
208
+ uploadedBankTransactionId: tr._id,
209
+ accountNumber: tr.accountNumber,
210
+ amount: tr.amount,
211
+ date: tr.date,
212
+ reference: tr.reference,
213
+ cashAllocationReferenceId: null,
214
+ cashAllocationProductId: null,
215
+ accounts: null,
216
+ class: '',
217
+ location: '',
218
+ memo: tr.splitMemo,
219
+ splitTransactionId: tr.splitTransactionId,
220
+ };
221
+ const foundCashAllocationReferences = references
222
+ .filter((reference) => tr.reference.toLowerCase().includes(reference.reference.toLowerCase()));
223
+ if (!foundCashAllocationReferences.length) {
224
+ return acc;
225
+ }
226
+ const useOnlyOneReference = true;
227
+ const reducedFoundCashAllocationReferences = useOnlyOneReference ? foundCashAllocationReferences.slice(0, 1) : foundCashAllocationReferences;
228
+ return [
229
+ ...acc,
230
+ ...reducedFoundCashAllocationReferences.map((foundCashAllocationReference) => {
231
+ const foundCashAllocationProduct = products
232
+ .find((product) => product._id.toString() === foundCashAllocationReference.cashAllocationProductId.toString());
233
+ if (!foundCashAllocationProduct) {
234
+ return null;
235
+ }
236
+ return foundCashAllocationProduct
237
+ ? populateAllocatedBankTransaction({
238
+ ...allocatedBankTransaction,
239
+ cashAllocationReferenceId: foundCashAllocationReference._id,
240
+ accounts: foundCashAllocationProduct.accounts,
241
+ memo: (tr.splitMemo && tr.splitMemo.trim() !== '')
242
+ ? tr.splitMemo
243
+ : (tr.amount > 0 ? foundCashAllocationProduct.DRMemo : foundCashAllocationProduct.CRMemo),
244
+ }, foundCashAllocationProduct)
245
+ : allocatedBankTransaction;
246
+ })
247
+ ];
248
+ }, [])
249
+ .filter((tr) => !!tr);
250
+ return { allocatedBankTransactions, uploadedBankTransactions };
251
+ }
252
+ async resetAllocatedBankTransactions(date) {
253
+ const { allocatedBankTransactions } = await this.getPreAllocatedTransactions(date);
254
+ const uniqueTransactionsIds = new Set(allocatedBankTransactions.map((tr) => tr.uploadedBankTransactionId.toString()));
255
+ await this.deleteAllocatedBankTransaction(Array.from(uniqueTransactionsIds));
256
+ await Promise.all(allocatedBankTransactions.map(async (transaction) => {
257
+ const newTransaction = new AllocatedBankTransaction_model_1.AllocatedBankTransaction(transaction);
258
+ await newTransaction.save();
259
+ }));
260
+ await this.updateLockStatus(date, false);
261
+ }
262
+ async createAllocatedBankTransactions(date) {
263
+ const cashAllocations = await this.getAllocatedTransactions(date);
264
+ const allocatedData = await AllocatedData_model_1.AllocatedData.findOne({ date: (0, dayjs_1.default)(date).format(date_formats_contsants_1.MAIN_DATE_FORMAT) });
265
+ if (cashAllocations.length > 0 && (allocatedData && allocatedData.isLocked)) {
266
+ return;
267
+ }
268
+ await this.resetAllocatedBankTransactions(date);
269
+ }
270
+ async convertBankTransactions(startDate, userId) {
271
+ const allocatedTransactions = await this.getAllocatedTransactions(startDate);
272
+ const transactionIds = allocatedTransactions.map((transaction) => transaction.uploadedBankTransactionId.toString());
273
+ const transactions = await UploadedBankTransaction_model_1.UploadedBankTransaction.find({ _id: { $in: transactionIds } });
274
+ const cashAllocations = await this.cashAllocationService.getAllCashAllocations();
275
+ const banks = await Banks_model_1.Bank.find().lean();
276
+ const loanTransactionsMap = transactions.reduce((acc, transaction) => {
277
+ return {
278
+ ...acc,
279
+ [transaction._id.toString()]: [],
280
+ };
281
+ }, {});
282
+ const productIds = new Set();
283
+ await Promise.all(allocatedTransactions.map(async (transactionToConvert) => {
284
+ const transaction = transactions.find((tr) => tr._id.toString() === transactionToConvert.uploadedBankTransactionId.toString());
285
+ if (transaction.isConverted) {
286
+ return;
287
+ }
288
+ const splitTransaction = transactionToConvert.splitTransactionId
289
+ ? transaction.splitTransactions.find((tr) => tr._id.toString() === transactionToConvert.splitTransactionId.toString())
290
+ : null;
291
+ const foundCashAllocationProduct = cashAllocations.products.find((c) => c._id.toString() === transactionToConvert.cashAllocationProductId.toString());
292
+ if (!foundCashAllocationProduct || !foundCashAllocationProduct.productId) {
293
+ return;
294
+ }
295
+ const foundBank = banks.find((b) => b.bankAccountNumber === transaction.accountNumber);
296
+ const getLoanTransaction = () => ({
297
+ amount: transactionToConvert.amount,
298
+ bankId: foundBank ? new mongoose_1.default.Types.ObjectId(String(foundBank._id)) : null,
299
+ customerId: null,
300
+ date: new Date(transaction.date),
301
+ description: '',
302
+ effectiveDate: null,
303
+ productId: foundCashAllocationProduct.productId,
304
+ reference: splitTransaction ? splitTransaction.memo : transactionToConvert.reference,
305
+ transactionType: transaction.amount > 0 ? LoanTransaction_model_1.ELoanTransactionTypes.COLLECTION : LoanTransaction_model_1.ELoanTransactionTypes.DISBURSEMENT,
306
+ balance: 0,
307
+ floatedBalance: 0,
308
+ });
309
+ const loanTransactionsService = this.getLoanTransactionsService();
310
+ const normalizedTransaction = await loanTransactionsService.normalizeLoanTransaction(getLoanTransaction(), userId);
311
+ const createdLoanTransaction = await loanTransactionsService.createLoanTransaction(normalizedTransaction);
312
+ loanTransactionsMap[String(transaction._id)] = [...loanTransactionsMap[String(transaction._id)], new mongoose_1.default.Types.ObjectId(String(createdLoanTransaction._id))];
313
+ productIds.add(String(foundCashAllocationProduct.productId));
314
+ }));
315
+ await Promise.all(transactions.map(async (transaction) => {
316
+ await transaction.updateOne({
317
+ isConverted: true,
318
+ loanTransactionIds: loanTransactionsMap[String(transaction._id)],
319
+ });
320
+ }));
321
+ this.recalculateProducts(Array.from(productIds));
322
+ }
323
+ recalculateProducts(productIds) {
324
+ // TODO rework in something better
325
+ setTimeout(async () => {
326
+ await Promise.all(productIds.map(async (productId) => {
327
+ console.log({ productId });
328
+ const loanTransactionsService = this.getLoanTransactionsService();
329
+ await loanTransactionsService.recalculateProduct(productId);
330
+ }));
331
+ }, 2000);
332
+ }
333
+ async preSplitBankTransactions(transactionId, splitTransaction) {
334
+ const mappedSplitTransactions = splitTransaction.map((transaction) => {
335
+ const { _id, ...transactionRest } = transaction;
336
+ return _id.toString().includes('new_') ? transactionRest : transaction;
337
+ });
338
+ await UploadedBankTransaction_model_1.UploadedBankTransaction.updateOne({ _id: new mongoose_1.default.Types.ObjectId(transactionId) }, { splitTransactions: mappedSplitTransactions });
339
+ }
340
+ async deleteBankTransaction(transactionIds) {
341
+ await UploadedBankTransaction_model_1.UploadedBankTransaction.deleteMany({ _id: { $in: transactionIds }, isConverted: false });
342
+ }
343
+ async revertAllBankTransactions(startDate, endDate, userId) {
344
+ const transactions = await this.getUploadedBankTransactions(startDate, endDate);
345
+ const transactionIds = transactions.map((t) => t._id.toString());
346
+ await this.revertBankTransactions(transactionIds, userId);
347
+ }
348
+ async revertBankTransactions(transactionIds, userId) {
349
+ const foundTransaction = await UploadedBankTransaction_model_1.UploadedBankTransaction.find({ _id: { $in: transactionIds }, isConverted: true });
350
+ const productIds = new Set();
351
+ await Promise.all(foundTransaction.map(async (transaction) => {
352
+ try {
353
+ await Promise.all(transaction.loanTransactionIds.map(async (loanTransactionId) => {
354
+ const loanTransaction = await LoanTransaction_model_1.LoanTransaction.findById(loanTransactionId);
355
+ const loanTransactionsService = this.getLoanTransactionsService();
356
+ const isLocked = await loanTransactionsService.checkLockStatus(loanTransaction);
357
+ if (isLocked) {
358
+ throw new Error('period is locked');
359
+ }
360
+ const validationError = await this.loanStatementStatusService.validateDate(loanTransaction.productId.toString(), new Date(transaction.date));
361
+ if (validationError) {
362
+ throw new Error('validation error');
363
+ }
364
+ await loanTransactionsService.deleteLoanTransaction(loanTransactionId.toString(), false, userId);
365
+ productIds.add(loanTransaction.productId.toString());
366
+ }));
367
+ transaction.loanTransactionIds = [];
368
+ transaction.isConverted = false;
369
+ await transaction.save();
370
+ this.recalculateProducts(Array.from(productIds));
371
+ }
372
+ catch (error) {
373
+ console.log(error);
374
+ }
375
+ }));
376
+ }
377
+ async getUniqueDates() {
378
+ const uniqueDates = await UploadedBankTransaction_model_1.UploadedBankTransaction.aggregate([
379
+ {
380
+ $group: {
381
+ _id: { $dateToString: { format: '%Y-%m-%d', date: '$date' } },
382
+ },
383
+ },
384
+ {
385
+ $sort: { _id: 1 },
386
+ },
387
+ ]);
388
+ return uniqueDates.map(d => d._id);
389
+ }
390
+ async saveAllocatedBankTransactions(date, transactions) {
391
+ const startDate = (0, dayjs_1.default)(date).utcOffset(0).startOf('day');
392
+ const endDate = startDate.endOf('day');
393
+ const existingAllocatedTransactions = await this.getAllocatedBankTransactions(startDate.toDate(), endDate.toDate());
394
+ const existingTransactionIds = existingAllocatedTransactions.map((t) => t._id.toString());
395
+ const transactionIds = transactions.map((t) => t._id.toString());
396
+ const transactionIdsToDelete = existingTransactionIds.reduce((acc, id) => {
397
+ if (transactionIds.includes(id)) {
398
+ return acc;
399
+ }
400
+ return [...acc, id];
401
+ }, []);
402
+ await Promise.all(transactions.map(async (transaction, order) => {
403
+ const { _id, ...rest } = transaction;
404
+ if (_id.toString().includes('new_')) {
405
+ const newTransaction = new AllocatedBankTransaction_model_1.AllocatedBankTransaction({ ...rest, order });
406
+ await newTransaction.save();
407
+ }
408
+ else {
409
+ await AllocatedBankTransaction_model_1.AllocatedBankTransaction.updateOne({ _id }, { ...rest, order });
410
+ }
411
+ }));
412
+ await AllocatedBankTransaction_model_1.AllocatedBankTransaction.deleteMany({ _id: { $in: transactionIdsToDelete } });
413
+ await this.updateLockStatus(date, true);
414
+ }
415
+ async createAllocatedBankTransaction(transaction) {
416
+ const { _id, ...rest } = transaction;
417
+ const startDate = (0, dayjs_1.default)(transaction.date).utcOffset(0).startOf('day');
418
+ const endDate = startDate.endOf('day');
419
+ const existingAllocatedTransactions = await this.getAllocatedBankTransactions(startDate.toDate(), endDate.toDate());
420
+ const order = existingAllocatedTransactions.length > 0 ? existingAllocatedTransactions[existingAllocatedTransactions.length - 1].order + 1 : 0;
421
+ const newTransaction = new AllocatedBankTransaction_model_1.AllocatedBankTransaction({ ...rest, order });
422
+ await newTransaction.save();
423
+ await this.updateLockStatus(transaction.date, true);
424
+ }
425
+ async updateLockStatus(date, isLocked) {
426
+ const normalizedDate = (0, dayjs_1.default)(date).utcOffset(0).startOf('day');
427
+ await AllocatedData_model_1.AllocatedData.updateOne({ date: normalizedDate.format(date_formats_contsants_1.MAIN_DATE_FORMAT) }, { isLocked }, { upsert: true });
428
+ }
429
+ }
430
+ exports.BankUploadedTransactionsService = BankUploadedTransactionsService;