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,106 @@
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.LoanStatementBalanceService = void 0;
7
+ const decimal_js_1 = __importDefault(require("decimal.js"));
8
+ const dayjs_1 = __importDefault(require("dayjs"));
9
+ const LoanPayment_model_1 = require("../models/LoanPayment.model");
10
+ const LoanStatementTransaction_model_1 = require("../models/LoanStatementTransaction.model");
11
+ const loan_charge_type_enum_1 = require("../enums/loan-charge-type.enum");
12
+ class LoanStatementBalanceService {
13
+ loanChargesService;
14
+ getLoanStatementService;
15
+ loanTransactionsService;
16
+ constructor(loanChargesService, getLoanStatementService, loanTransactionsService) {
17
+ this.loanChargesService = loanChargesService;
18
+ this.getLoanStatementService = getLoanStatementService;
19
+ this.loanTransactionsService = loanTransactionsService;
20
+ }
21
+ async cleanDecreasePayment(payment, userId) {
22
+ if (!!payment.paid) {
23
+ let firstPaidStatement = null;
24
+ await Promise.all(payment.paid.map(async (paid) => {
25
+ const foundPayment = await LoanStatementTransaction_model_1.LoanStatementTransactionModel.findById(paid.statementId);
26
+ if (!foundPayment) {
27
+ return;
28
+ }
29
+ if (!firstPaidStatement ||
30
+ (foundPayment.date.getTime() < firstPaidStatement.date.getTime()) ||
31
+ (firstPaidStatement.date.getTime() === foundPayment.date.getTime() && firstPaidStatement.order > foundPayment.order)) {
32
+ firstPaidStatement = foundPayment;
33
+ }
34
+ await LoanStatementTransaction_model_1.LoanStatementTransactionModel.findByIdAndUpdate(paid.statementId, {
35
+ amountPaid: new decimal_js_1.default(foundPayment.amountPaid).sub(paid.amount).toNumber(),
36
+ settlementCode: null,
37
+ });
38
+ }));
39
+ if (firstPaidStatement) {
40
+ await this.calculateProductBalance(payment.productId.toString(), firstPaidStatement.date);
41
+ }
42
+ }
43
+ if (!!payment.loanTransactions) {
44
+ await Promise.all(payment.loanTransactions.map(async (t) => {
45
+ await this.loanTransactionsService.deleteLoanTransaction(t.transactionId.toString(), false, userId);
46
+ }));
47
+ }
48
+ await LoanPayment_model_1.LoanPaymentModel.findByIdAndUpdate(payment._id, { paid: [] });
49
+ }
50
+ async calculateProductBalance(productId, startDate) {
51
+ const loanStatementService = this.getLoanStatementService();
52
+ const statements = await loanStatementService.getTransactionsFromDate(productId, startDate);
53
+ for (const statement of statements) {
54
+ await this.updateBalance(statement);
55
+ }
56
+ }
57
+ async updateBalance(loanStatementTransaction) {
58
+ const loanStatementService = this.getLoanStatementService();
59
+ const previousTransaction = await loanStatementService.getPreviousTransaction(loanStatementTransaction);
60
+ const previousBalance = !previousTransaction ? 0 : previousTransaction.balance;
61
+ const newBalance = new decimal_js_1.default(previousBalance).add(loanStatementTransaction.amount).sub(loanStatementTransaction.amountPaid).toNumber();
62
+ await LoanStatementTransaction_model_1.LoanStatementTransactionModel.findByIdAndUpdate(loanStatementTransaction._id, { balance: newBalance });
63
+ }
64
+ async getLastStatementTransactionForDate(productId, startDate) {
65
+ const charges = await this.loanChargesService.getLoanChargeForProduct(productId);
66
+ const lastStatements = await LoanStatementTransaction_model_1.LoanStatementTransactionModel.aggregate([
67
+ {
68
+ $match: {
69
+ 'chargeId': { $in: charges.map((charge) => charge._id) },
70
+ 'date': { $lt: startDate },
71
+ },
72
+ }, {
73
+ $sort: {
74
+ 'date': -1,
75
+ 'order': -1,
76
+ },
77
+ }, {
78
+ $limit: 1,
79
+ },
80
+ ]);
81
+ if (lastStatements.length === 0) {
82
+ return null;
83
+ }
84
+ return lastStatements[0];
85
+ }
86
+ async getNextAdminTransactionForDate(productId, date) {
87
+ const charges = await this.loanChargesService.getLoanChargeForProduct(productId);
88
+ const adminCharge = charges.find((c) => c.chargeType === loan_charge_type_enum_1.ELoanChargeType.ADMIN_FEE);
89
+ if (adminCharge) {
90
+ const nextAdminFee = await LoanStatementTransaction_model_1.LoanStatementTransactionModel
91
+ .findOne({
92
+ chargeId: adminCharge._id,
93
+ date: { $gte: (0, dayjs_1.default)(date).startOf('month').toDate() },
94
+ })
95
+ .sort({ date: 1 })
96
+ .lean();
97
+ if (nextAdminFee) {
98
+ const totalDays = (0, dayjs_1.default)(date).daysInMonth();
99
+ const day = (0, dayjs_1.default)(date).date();
100
+ return new decimal_js_1.default(day).div(totalDays).mul(nextAdminFee.amount).toDP(2).toNumber();
101
+ }
102
+ }
103
+ return 0;
104
+ }
105
+ }
106
+ exports.LoanStatementBalanceService = LoanStatementBalanceService;
@@ -0,0 +1,113 @@
1
+ import Decimal from 'decimal.js';
2
+ import dayjs from 'dayjs';
3
+
4
+ import { ILoanPaymentWithId, LoanPaymentModel } from '../models/LoanPayment.model';
5
+ import {
6
+ LoanStatementTransactionModel,
7
+ ILoanStatementTransactionDoc,
8
+ } from '../models/LoanStatementTransaction.model';
9
+ import { ELoanChargeType } from '../enums/loan-charge-type.enum';
10
+
11
+ import { LoanChargesService } from './loan-charges.service';
12
+ import { LoanStatementService } from './loan-statement.service';
13
+ import { LoanTransactionsService } from './loan-transactions.service';
14
+
15
+ export class LoanStatementBalanceService {
16
+
17
+ constructor(
18
+ private readonly loanChargesService: LoanChargesService,
19
+ private readonly getLoanStatementService: () => LoanStatementService,
20
+ private readonly loanTransactionsService: LoanTransactionsService,
21
+ ) {
22
+ }
23
+
24
+ async cleanDecreasePayment(payment: ILoanPaymentWithId, userId: string) {
25
+ if (!!payment.paid) {
26
+ let firstPaidStatement: any = null;
27
+ await Promise.all(payment.paid.map(async (paid) => {
28
+ const foundPayment = await LoanStatementTransactionModel.findById(paid.statementId);
29
+ if (!foundPayment) {
30
+ return;
31
+ }
32
+ if (!firstPaidStatement ||
33
+ (foundPayment.date.getTime() < firstPaidStatement.date.getTime()) ||
34
+ (firstPaidStatement.date.getTime() === foundPayment.date.getTime() && firstPaidStatement.order > foundPayment.order)
35
+ ) {
36
+ firstPaidStatement = foundPayment;
37
+ }
38
+ await LoanStatementTransactionModel.findByIdAndUpdate(paid.statementId, {
39
+ amountPaid: new Decimal(foundPayment.amountPaid).sub(paid.amount).toNumber(),
40
+ settlementCode: null,
41
+ });
42
+ }));
43
+ if (firstPaidStatement) {
44
+ await this.calculateProductBalance(payment.productId.toString(), firstPaidStatement.date);
45
+ }
46
+ }
47
+ if (!!payment.loanTransactions) {
48
+ await Promise.all(payment.loanTransactions.map(async (t) => {
49
+ await this.loanTransactionsService.deleteLoanTransaction(t.transactionId.toString(), false, userId);
50
+ }));
51
+ }
52
+ await LoanPaymentModel.findByIdAndUpdate(payment._id, { paid: [] });
53
+ }
54
+
55
+ async calculateProductBalance(productId: string, startDate: Date) {
56
+ const loanStatementService = this.getLoanStatementService();
57
+ const statements = await loanStatementService.getTransactionsFromDate(productId, startDate);
58
+ for (const statement of statements) {
59
+ await this.updateBalance(statement);
60
+ }
61
+ }
62
+
63
+ async updateBalance(loanStatementTransaction: ILoanStatementTransactionDoc) {
64
+ const loanStatementService = this.getLoanStatementService();
65
+ const previousTransaction = await loanStatementService.getPreviousTransaction(loanStatementTransaction);
66
+ const previousBalance = !previousTransaction ? 0 : previousTransaction.balance;
67
+ const newBalance = new Decimal(previousBalance).add(loanStatementTransaction.amount).sub(loanStatementTransaction.amountPaid).toNumber();
68
+ await LoanStatementTransactionModel.findByIdAndUpdate(loanStatementTransaction._id, { balance: newBalance });
69
+ }
70
+
71
+ async getLastStatementTransactionForDate(productId: string, startDate: Date) {
72
+ const charges = await this.loanChargesService.getLoanChargeForProduct(productId);
73
+ const lastStatements = await LoanStatementTransactionModel.aggregate<ILoanStatementTransactionDoc>([
74
+ {
75
+ $match: {
76
+ 'chargeId': { $in: charges.map((charge) => charge._id) },
77
+ 'date': { $lt: startDate },
78
+ },
79
+ }, {
80
+ $sort: {
81
+ 'date': -1,
82
+ 'order': -1,
83
+ },
84
+ }, {
85
+ $limit: 1,
86
+ },
87
+ ]);
88
+ if (lastStatements.length === 0) {
89
+ return null;
90
+ }
91
+ return lastStatements[0];
92
+ }
93
+
94
+ async getNextAdminTransactionForDate(productId: string, date: Date) {
95
+ const charges = await this.loanChargesService.getLoanChargeForProduct(productId);
96
+ const adminCharge = charges.find((c) => c.chargeType === ELoanChargeType.ADMIN_FEE);
97
+ if (adminCharge) {
98
+ const nextAdminFee = await LoanStatementTransactionModel
99
+ .findOne({
100
+ chargeId: adminCharge._id,
101
+ date: { $gte: dayjs(date).startOf('month').toDate() },
102
+ })
103
+ .sort({ date: 1 })
104
+ .lean();
105
+ if (nextAdminFee) {
106
+ const totalDays = dayjs(date).daysInMonth();
107
+ const day = dayjs(date).date();
108
+ return new Decimal(day).div(totalDays).mul(nextAdminFee.amount).toDP(2).toNumber();
109
+ }
110
+ }
111
+ return 0;
112
+ }
113
+ }
@@ -0,0 +1,8 @@
1
+ import { LoanStatementBalanceService } from './loan-statement-balance.service';
2
+ import { MonthEndDataService } from './month-end-data.service';
3
+ export declare class LoanStatementEffectsService {
4
+ private readonly loanStatementBalanceService;
5
+ private readonly monthEndDataService;
6
+ constructor(loanStatementBalanceService: LoanStatementBalanceService, monthEndDataService: MonthEndDataService);
7
+ saveMonthData(productId: string, statementDate: Date): Promise<void>;
8
+ }
@@ -0,0 +1,42 @@
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.LoanStatementEffectsService = void 0;
7
+ const dayjs_1 = __importDefault(require("dayjs"));
8
+ const mongoose_1 = __importDefault(require("mongoose"));
9
+ const loan_products_db_1 = require("../db/loan-products.db");
10
+ const MonthEndData_Model_1 = require("../models/MonthEndData.Model");
11
+ class LoanStatementEffectsService {
12
+ loanStatementBalanceService;
13
+ monthEndDataService;
14
+ constructor(loanStatementBalanceService, monthEndDataService) {
15
+ this.loanStatementBalanceService = loanStatementBalanceService;
16
+ this.monthEndDataService = monthEndDataService;
17
+ }
18
+ async saveMonthData(productId, statementDate) {
19
+ if ((0, dayjs_1.default)(statementDate).date() !== 1) {
20
+ return;
21
+ }
22
+ const balance = await (0, loan_products_db_1.getLoanProductBalance)(productId, statementDate);
23
+ const lastTransaction = await this.loanStatementBalanceService.getLastStatementTransactionForDate(productId, statementDate);
24
+ const month = (0, dayjs_1.default)(statementDate).subtract(1, 'd').month() + 1;
25
+ const year = (0, dayjs_1.default)(statementDate).subtract(1, 'd').year();
26
+ const keptData = {
27
+ [MonthEndData_Model_1.EMonthEndDataType.BALANCE]: balance?.balance ?? 0,
28
+ [MonthEndData_Model_1.EMonthEndDataType.FLOATED_BALANCE]: balance?.floatedBalance ?? 0,
29
+ [MonthEndData_Model_1.EMonthEndDataType.STATEMENT_BALANCE]: lastTransaction?.balance ?? 0,
30
+ };
31
+ await Promise.all(Object.entries(keptData).map(async ([dataType, dataValue]) => {
32
+ await this.monthEndDataService.upsertMonthEndData({
33
+ productId: new mongoose_1.default.Types.ObjectId(productId),
34
+ year,
35
+ month,
36
+ dataType: dataType,
37
+ dataValue,
38
+ });
39
+ }));
40
+ }
41
+ }
42
+ exports.LoanStatementEffectsService = LoanStatementEffectsService;
@@ -0,0 +1,41 @@
1
+ import dayjs from 'dayjs';
2
+ import mongoose from 'mongoose';
3
+
4
+ import { getLoanProductBalance as getLoanProductBalanceDB } from '../db/loan-products.db';
5
+
6
+ import { LoanStatementBalanceService } from './loan-statement-balance.service';
7
+ import { EMonthEndDataType } from '../models/MonthEndData.Model';
8
+ import { MonthEndDataService } from './month-end-data.service';
9
+
10
+ export class LoanStatementEffectsService {
11
+ constructor(
12
+ private readonly loanStatementBalanceService: LoanStatementBalanceService,
13
+ private readonly monthEndDataService: MonthEndDataService,
14
+ ) {
15
+ }
16
+
17
+ async saveMonthData(productId: string, statementDate: Date) {
18
+ if (dayjs(statementDate).date() !== 1) {
19
+ return;
20
+ }
21
+ const balance = await getLoanProductBalanceDB(productId, statementDate);
22
+ const lastTransaction = await this.loanStatementBalanceService.getLastStatementTransactionForDate(productId, statementDate);
23
+ const month = dayjs(statementDate).subtract(1, 'd').month() + 1;
24
+ const year = dayjs(statementDate).subtract(1, 'd').year();
25
+
26
+ const keptData = {
27
+ [EMonthEndDataType.BALANCE]: balance?.balance ?? 0,
28
+ [EMonthEndDataType.FLOATED_BALANCE]: balance?.floatedBalance ?? 0,
29
+ [EMonthEndDataType.STATEMENT_BALANCE]: lastTransaction?.balance ?? 0,
30
+ };
31
+ await Promise.all(Object.entries(keptData).map(async ([dataType, dataValue]) => {
32
+ await this.monthEndDataService.upsertMonthEndData({
33
+ productId: new mongoose.Types.ObjectId(productId),
34
+ year,
35
+ month,
36
+ dataType: dataType as EMonthEndDataType,
37
+ dataValue,
38
+ });
39
+ }));
40
+ }
41
+ }
@@ -0,0 +1,208 @@
1
+ /// <reference types="mongoose/types/aggregate" />
2
+ /// <reference types="mongoose/types/callback" />
3
+ /// <reference types="mongoose/types/collection" />
4
+ /// <reference types="mongoose/types/connection" />
5
+ /// <reference types="mongoose/types/cursor" />
6
+ /// <reference types="mongoose/types/document" />
7
+ /// <reference types="mongoose/types/error" />
8
+ /// <reference types="mongoose/types/expressions" />
9
+ /// <reference types="mongoose/types/helpers" />
10
+ /// <reference types="mongoose/types/middlewares" />
11
+ /// <reference types="mongoose/types/indexes" />
12
+ /// <reference types="mongoose/types/models" />
13
+ /// <reference types="mongoose/types/mongooseoptions" />
14
+ /// <reference types="mongoose/types/pipelinestage" />
15
+ /// <reference types="mongoose/types/populate" />
16
+ /// <reference types="mongoose/types/query" />
17
+ /// <reference types="mongoose/types/schemaoptions" />
18
+ /// <reference types="mongoose/types/schematypes" />
19
+ /// <reference types="mongoose/types/session" />
20
+ /// <reference types="mongoose/types/types" />
21
+ /// <reference types="mongoose/types/utility" />
22
+ /// <reference types="mongoose/types/validation" />
23
+ /// <reference types="mongoose/types/virtuals" />
24
+ /// <reference types="mongoose/types/inferschematype" />
25
+ import mongoose from 'mongoose';
26
+ import { ISelectedMonth } from '../helpers/date.helper';
27
+ import { IStatementPeriod } from './loan-statement.service';
28
+ import { LoanChargesService } from './loan-charges.service';
29
+ import { TermLoanService } from './term-loan.service';
30
+ export type SelectablePeriod = 'LAST_MONTH' | 'CURRENT_MONTH' | 'ENTIRE_LOAN' | 'SELECTED_PERIOD';
31
+ export declare class LoanStatementStatusService {
32
+ private readonly getLoanChargesService;
33
+ private readonly termLoanService;
34
+ constructor(getLoanChargesService: () => LoanChargesService, termLoanService: TermLoanService);
35
+ initStatementStatuses(): Promise<void>;
36
+ getStatementDateFromStringPeriod(period: SelectablePeriod): ISelectedMonth;
37
+ getStatementDateForDate(date: Date): ISelectedMonth;
38
+ getStatementDateFromPeriod(period: IStatementPeriod): ISelectedMonth;
39
+ getDateFromStatementDate(statementDate: ISelectedMonth): Date;
40
+ getPeriodsFromStatementDate(statementDate: ISelectedMonth): IStatementPeriod[];
41
+ toggleStatementLock(productId: string, statementDate: ISelectedMonth): Promise<void>;
42
+ updateStatementStatus(productId: string, statementDate: ISelectedMonth, actual: boolean): Promise<void>;
43
+ getAllStatementsStatus(statementDate: ISelectedMonth): Promise<{
44
+ product: import("../models/LoanProducts.model").ILoanProductDoc;
45
+ productId: mongoose.Types.ObjectId;
46
+ actual: boolean;
47
+ locked: boolean;
48
+ lastCalculated: Date;
49
+ year: number;
50
+ month: number;
51
+ _id: any;
52
+ __v?: any;
53
+ $assertPopulated: <Paths = {}>(path: string | string[], values?: Partial<Paths>) => Omit<import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc, keyof Paths> & Paths;
54
+ $clone: () => import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc;
55
+ $getAllSubdocs: () => mongoose.Document<any, any, any>[];
56
+ $ignore: (path: string) => void;
57
+ $isDefault: (path: string) => boolean;
58
+ $isDeleted: (val?: boolean) => boolean;
59
+ $getPopulatedDocs: () => mongoose.Document<any, any, any>[];
60
+ $inc: (path: string | string[], val?: number) => import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc;
61
+ $isEmpty: (path: string) => boolean;
62
+ $isValid: (path: string) => boolean;
63
+ $locals: mongoose.FlattenMaps<Record<string, unknown>>;
64
+ $markValid: (path: string) => void;
65
+ $model: {
66
+ <ModelType = mongoose.Model<unknown, {}, {}, {}, mongoose.Document<unknown, {}, unknown> & Required<{
67
+ _id: unknown;
68
+ }>, any>>(name: string): ModelType;
69
+ <ModelType_1 = mongoose.Model<any, {}, {}, {}, any, any>>(): ModelType_1;
70
+ };
71
+ $op: "save" | "validate" | "remove";
72
+ $session: (session?: mongoose.mongo.ClientSession) => mongoose.mongo.ClientSession;
73
+ $set: {
74
+ (path: string | Record<string, any>, val: any, type: any, options?: mongoose.DocumentSetOptions): import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc;
75
+ (path: string | Record<string, any>, val: any, options?: mongoose.DocumentSetOptions): import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc;
76
+ (value: string | Record<string, any>): import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc;
77
+ };
78
+ $where: mongoose.FlattenMaps<Record<string, unknown>>;
79
+ baseModelName?: string;
80
+ collection: mongoose.Collection<mongoose.mongo.BSON.Document>;
81
+ db: mongoose.FlattenMaps<mongoose.Connection>;
82
+ deleteOne: (options?: mongoose.QueryOptions<unknown>) => any;
83
+ depopulate: (path?: string | string[]) => import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc;
84
+ directModifiedPaths: () => string[];
85
+ equals: (doc: mongoose.Document<any, any, any>) => boolean;
86
+ errors?: mongoose.Error.ValidationError;
87
+ get: {
88
+ <T extends string | number | symbol>(path: T, type?: any, options?: any): any;
89
+ (path: string, type?: any, options?: any): any;
90
+ };
91
+ getChanges: () => mongoose.UpdateQuery<import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc>;
92
+ id?: any;
93
+ increment: () => import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc;
94
+ init: (obj: mongoose.AnyObject, opts?: mongoose.AnyObject) => import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc;
95
+ invalidate: {
96
+ <T_1 extends string | number | symbol>(path: T_1, errorMsg: string | NativeError, value?: any, kind?: string): NativeError;
97
+ (path: string, errorMsg: string | NativeError, value?: any, kind?: string): NativeError;
98
+ };
99
+ isDirectModified: {
100
+ <T_2 extends string | number | symbol>(path: T_2 | T_2[]): boolean;
101
+ (path: string | string[]): boolean;
102
+ };
103
+ isDirectSelected: {
104
+ <T_3 extends string | number | symbol>(path: T_3): boolean;
105
+ (path: string): boolean;
106
+ };
107
+ isInit: {
108
+ <T_4 extends string | number | symbol>(path: T_4): boolean;
109
+ (path: string): boolean;
110
+ };
111
+ isModified: {
112
+ <T_5 extends string | number | symbol>(path?: T_5 | T_5[], options?: {
113
+ ignoreAtomics?: boolean;
114
+ }): boolean;
115
+ (path?: string | string[], options?: {
116
+ ignoreAtomics?: boolean;
117
+ }): boolean;
118
+ };
119
+ isNew: boolean;
120
+ isSelected: {
121
+ <T_6 extends string | number | symbol>(path: T_6): boolean;
122
+ (path: string): boolean;
123
+ };
124
+ markModified: {
125
+ <T_7 extends string | number | symbol>(path: T_7, scope?: any): void;
126
+ (path: string, scope?: any): void;
127
+ };
128
+ model: {
129
+ <ModelType_2 = mongoose.Model<unknown, {}, {}, {}, mongoose.Document<unknown, {}, unknown> & Required<{
130
+ _id: unknown;
131
+ }>, any>>(name: string): ModelType_2;
132
+ <ModelType_3 = mongoose.Model<any, {}, {}, {}, any, any>>(): ModelType_3;
133
+ };
134
+ modifiedPaths: (options?: {
135
+ includeChildren?: boolean;
136
+ }) => string[];
137
+ overwrite: (obj: mongoose.AnyObject) => import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc;
138
+ $parent: () => mongoose.Document<any, any, any>;
139
+ populate: {
140
+ <Paths_1 = {}>(path: string | mongoose.PopulateOptions | (string | mongoose.PopulateOptions)[]): Promise<mongoose.MergeType<import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc, Paths_1>>;
141
+ <Paths_2 = {}>(path: string, select?: string | mongoose.AnyObject, model?: mongoose.Model<any, {}, {}, {}, any, any>, match?: mongoose.AnyObject, options?: mongoose.PopulateOptions): Promise<mongoose.MergeType<import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc, Paths_2>>;
142
+ };
143
+ populated: (path: string) => any;
144
+ replaceOne: (replacement?: mongoose.AnyObject, options?: mongoose.QueryOptions<unknown>) => mongoose.Query<any, import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc, {}, import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc, "find">;
145
+ save: (options?: mongoose.SaveOptions) => Promise<import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc>;
146
+ schema: mongoose.FlattenMaps<mongoose.Schema<any, mongoose.Model<any, any, any, any, any, any>, {}, {}, {}, {}, mongoose.DefaultSchemaOptions, {
147
+ [x: string]: unknown;
148
+ }, mongoose.Document<unknown, {}, mongoose.FlatRecord<{
149
+ [x: string]: unknown;
150
+ }>> & mongoose.FlatRecord<{
151
+ [x: string]: unknown;
152
+ }> & Required<{
153
+ _id: unknown;
154
+ }>>>;
155
+ set: {
156
+ <T_8 extends string | number | symbol>(path: T_8, val: any, type: any, options?: mongoose.DocumentSetOptions): import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc;
157
+ (path: string | Record<string, any>, val: any, type: any, options?: mongoose.DocumentSetOptions): import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc;
158
+ (path: string | Record<string, any>, val: any, options?: mongoose.DocumentSetOptions): import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc;
159
+ (value: string | Record<string, any>): import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc;
160
+ };
161
+ toJSON: {
162
+ <T_9 = any>(options?: mongoose.ToObjectOptions<mongoose.Document<unknown, {}, unknown> & Required<{
163
+ _id: unknown;
164
+ }>> & {
165
+ flattenMaps?: true;
166
+ }): mongoose.FlattenMaps<T_9>;
167
+ <T_10 = any>(options: mongoose.ToObjectOptions<mongoose.Document<unknown, {}, unknown> & Required<{
168
+ _id: unknown;
169
+ }>> & {
170
+ flattenMaps: false;
171
+ }): T_10;
172
+ };
173
+ toObject: <T_11 = any>(options?: mongoose.ToObjectOptions<mongoose.Document<unknown, {}, unknown> & Required<{
174
+ _id: unknown;
175
+ }>>) => mongoose.Require_id<T_11>;
176
+ unmarkModified: {
177
+ <T_12 extends string | number | symbol>(path: T_12): void;
178
+ (path: string): void;
179
+ };
180
+ updateOne: (update?: mongoose.UpdateWithAggregationPipeline | mongoose.UpdateQuery<import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc>, options?: mongoose.QueryOptions<unknown>) => mongoose.Query<any, import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc, {}, import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc, "find">;
181
+ validate: {
182
+ <T_13 extends string | number | symbol>(pathsToValidate?: T_13 | T_13[], options?: mongoose.AnyObject): Promise<void>;
183
+ (pathsToValidate?: mongoose.PathsToValidate, options?: mongoose.AnyObject): Promise<void>;
184
+ (options: {
185
+ pathsToSkip?: mongoose.pathsToSkip;
186
+ }): Promise<void>;
187
+ };
188
+ validateSync: {
189
+ (options: {
190
+ [k: string]: any;
191
+ pathsToSkip?: mongoose.pathsToSkip;
192
+ }): mongoose.Error.ValidationError;
193
+ <T_14 extends string | number | symbol>(pathsToValidate?: T_14 | T_14[], options?: mongoose.AnyObject): mongoose.Error.ValidationError;
194
+ (pathsToValidate?: mongoose.PathsToValidate, options?: mongoose.AnyObject): mongoose.Error.ValidationError;
195
+ };
196
+ }[]>;
197
+ getStatementStatus(productId: string, date: Date): Promise<mongoose.Document<unknown, {}, import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc> & import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc & {
198
+ _id: mongoose.Types.ObjectId;
199
+ }>;
200
+ getCreateStatementStatus(productId: string, statementDate: ISelectedMonth): Promise<mongoose.Document<unknown, {}, import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc> & import("../models/LoanStatementStatus.model").ILoanStatementStatusDoc & {
201
+ _id: mongoose.Types.ObjectId;
202
+ }>;
203
+ validateDate(productId: string, date: Date): Promise<"Statement is locked!" | "Internal Server Error">;
204
+ getBorrowerStatement(borrowerId: string): Promise<{
205
+ [K in SelectablePeriod | 'TERM_LOAN']?: boolean;
206
+ }>;
207
+ getBorrowerMonthStatus(borrowerId: string, statementDate: ISelectedMonth): Promise<boolean>;
208
+ }