@tomei/finance 0.6.35 → 0.6.37

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 (99) hide show
  1. package/.commitlintrc.json +22 -22
  2. package/.eslintrc.js +72 -72
  3. package/.husky/commit-msg +4 -4
  4. package/.husky/pre-commit +4 -4
  5. package/.prettierrc +4 -4
  6. package/CONTRIBUTING.md +30 -30
  7. package/LICENSE +21 -21
  8. package/README.md +13 -13
  9. package/configs/config.js +348 -348
  10. package/dist/document/document.js +1 -0
  11. package/dist/document/document.js.map +1 -1
  12. package/dist/models/payment.entity.d.ts +2 -0
  13. package/dist/models/payment.entity.js +5 -0
  14. package/dist/models/payment.entity.js.map +1 -1
  15. package/dist/payment-item/payment-item.js +4 -4
  16. package/dist/tsconfig.tsbuildinfo +1 -1
  17. package/invoice-template/assets/css/style.css.map +12 -12
  18. package/invoice-template/assets/css/style.min.css +1 -1
  19. package/invoice-template/assets/img/arrow_bg.svg +11 -11
  20. package/invoice-template/assets/img/coffy_shop_img.svg +18 -18
  21. package/invoice-template/assets/img/logo_accent.svg +3 -3
  22. package/invoice-template/assets/img/logo_white.svg +4 -4
  23. package/invoice-template/assets/img/sign.svg +12 -12
  24. package/invoice-template/assets/img/tomei-logo.svg +9 -9
  25. package/invoice-template/assets/js/html2canvas.min.js +10379 -10379
  26. package/invoice-template/assets/js/jquery.min.js +1 -1
  27. package/invoice-template/assets/sass/common/_color_variable.scss +12 -12
  28. package/invoice-template/assets/sass/common/_typography.scss +178 -178
  29. package/invoice-template/assets/sass/style.scss +12 -12
  30. package/migrations/finance-account-migration.js +97 -97
  31. package/migrations/finance-company-migration.js +29 -29
  32. package/migrations/finance-customer-migration.js +51 -51
  33. package/migrations/finance-document-item-migration.js +111 -111
  34. package/migrations/finance-document-migration.js +122 -122
  35. package/migrations/finance-payment-item-migration.js +52 -52
  36. package/migrations/finance-payment-method-migration.js +31 -31
  37. package/migrations/finance-payment-method-type-migration.js +55 -55
  38. package/migrations/finance-payment-migration.js +96 -96
  39. package/migrations/finance-post-history-migration.js +45 -45
  40. package/migrations/finance-tax-migration.js +52 -52
  41. package/nest-cli.json +19 -19
  42. package/package.json +82 -82
  43. package/src/account/account.repository.ts +11 -11
  44. package/src/account/account.ts +271 -271
  45. package/src/account/interfaces/account-attr.interface.ts +31 -31
  46. package/src/account-system-entity/account-system-entity.ts +65 -65
  47. package/src/account-system-entity/post-history.repository.ts +11 -11
  48. package/src/config.ts +382 -382
  49. package/src/customer/customer.ts +299 -299
  50. package/src/customer/finance-customer.repository.ts +13 -13
  51. package/src/customer/interfaces/customer.repository.interface.ts +3 -3
  52. package/src/customer/interfaces/finance-customer-attr.interface.ts +10 -10
  53. package/src/customer/interfaces/finance-customer.repository.interface.ts +4 -4
  54. package/src/database.ts +48 -48
  55. package/src/document/document-item.repository.ts +11 -11
  56. package/src/document/document.repository.ts +11 -11
  57. package/src/document/document.ts +1 -0
  58. package/src/document/interfaces/document-attr.interface.ts +28 -28
  59. package/src/document/interfaces/document-item-attr.interface.ts +22 -22
  60. package/src/document/interfaces/document-item.repository.interface.ts +4 -4
  61. package/src/enum/doc-type.enum.ts +8 -8
  62. package/src/enum/index.ts +17 -17
  63. package/src/enum/payment-method.enum.ts +3 -3
  64. package/src/enum/payment-type.enum.ts +4 -4
  65. package/src/finance-company/finance-company.repository.ts +11 -11
  66. package/src/finance-company/finance-company.ts +2062 -2062
  67. package/src/helpers/login-user.ts +33 -33
  68. package/src/helpers/typeof.ts +29 -29
  69. package/src/index.ts +32 -32
  70. package/src/interfaces/account-system.interface.ts +20 -20
  71. package/src/interfaces/index.ts +3 -3
  72. package/src/models/account.entity.ts +206 -206
  73. package/src/models/customer.entity.ts +93 -93
  74. package/src/models/document-item.entity.ts +143 -143
  75. package/src/models/document.entity.ts +211 -211
  76. package/src/models/finance-company.entity.ts +29 -29
  77. package/src/models/journal-entry.entity.ts +110 -110
  78. package/src/models/ledger-transaction.entity.ts +148 -148
  79. package/src/models/payment-item.entity.ts +60 -60
  80. package/src/models/payment-method-type.entity.ts +70 -70
  81. package/src/models/payment-method.entity.ts +51 -51
  82. package/src/models/payment.entity.ts +165 -161
  83. package/src/models/post-history.entity.ts +41 -41
  84. package/src/models/tax.entity.ts +75 -75
  85. package/src/payment/interfaces/payment-attr.interface.ts +23 -23
  86. package/src/payment/interfaces/payment-params.interface.ts +8 -8
  87. package/src/payment/payment.repository.ts +11 -11
  88. package/src/payment/payment.ts +217 -217
  89. package/src/payment-item/interfaces/payment-item-attr.interface.ts +10 -10
  90. package/src/payment-item/payment-item.repository.ts +11 -11
  91. package/src/payment-item/payment-item.ts +128 -128
  92. package/src/payment-method/payment-method.repository.ts +11 -11
  93. package/src/payment-method-type/payment-method-type.repository.ts +11 -11
  94. package/src/tax/interfaces/tax-attr.interface.ts +10 -10
  95. package/src/tax/tax.repository.ts +11 -11
  96. package/src/test-document.ts +25 -25
  97. package/tsconfig.build.json +4 -4
  98. package/tsconfig.json +22 -22
  99. package/tslint.json +18 -18
@@ -1,2062 +1,2062 @@
1
- import axios from 'axios';
2
- import * as cuid from 'cuid';
3
- import {
4
- HashTable,
5
- LoginUserBase,
6
- ObjectBase,
7
- RecordNotFoundError,
8
- } from '@tomei/general';
9
- import Account from '../account/account';
10
- import JournalEntry from '../journal-entry/journal-entry';
11
- import FinanceCustomerBase from '../customer/customer';
12
- import Document from '../document/document';
13
- import { IAccountSystem } from '../interfaces';
14
- import { FinanceCompanyRepository } from './finance-company.repository';
15
- import { FinanceCustomerRepository } from '../customer/finance-customer.repository';
16
- import { LedgerTransactionRepository } from '../ledger-transaction/ledger-transaction.repository';
17
- import {
18
- DocType,
19
- PaymentStatus,
20
- PaymentType,
21
- TransactionTypeOptions,
22
- } from '../enum';
23
- import PaymentMethodType from '../payment-method-type/payment-method-type';
24
- import { PaymentRepository } from '../payment/payment.repository';
25
- import { PaymentItemRepository } from '../payment-item/payment-item.repository';
26
- import Payment from '../payment/payment';
27
- import { DocumentRepository } from '../document/document.repository';
28
- import { DocumentItemRepository } from '../document/document-item.repository';
29
- import { PaymentMethodRepository } from '../payment-method/payment-method.repository';
30
- import { PaymentMethodTypeRepository } from '../payment-method-type/payment-method-type.repository';
31
- import PaymentMethod from '../payment-method/payment-method';
32
- import { AccountRepository } from '../account/account.repository';
33
- import { PaymentPaidWithRepository } from '../payment-paid-with/payment-paid-with.repository';
34
- import { MediasModel } from '@tomei/media';
35
- import DocumentItem from '../document/document-item';
36
- import { type } from '../helpers/typeof';
37
- import { LoginUser } from '@tomei/sso';
38
- import { ActionEnum, Activity } from '@tomei/activity-history';
39
- import { ApplicationConfig } from '@tomei/config';
40
- import { TaxRepository } from '../tax/tax.repository';
41
- import { Tax } from '../tax/tax';
42
-
43
- // eslint-disable-next-line @typescript-eslint/no-var-requires
44
- const getConfig = require('../config');
45
- // eslint-disable-next-line @typescript-eslint/no-var-requires
46
- const config = getConfig();
47
-
48
- export default class FinanceCompany extends ObjectBase {
49
- private _CompanyId = 'New';
50
- private _CompSystemCode = '';
51
- private _CompSystemRefId = '';
52
- private _AccSystemCode = '';
53
- private static _htFinanceCompanyIds = new HashTable();
54
- private static _htFinanceCompanies = new HashTable();
55
- private static _financeCompanyRepository = new FinanceCompanyRepository();
56
- private static _PaymentRepository = new PaymentRepository();
57
- private static _PaymentItemRepository = new PaymentItemRepository();
58
- private static _PaymentPaidWithRepository = new PaymentPaidWithRepository();
59
- private static _PaymentMethodRepository = new PaymentMethodRepository();
60
- private static _PaymentMethodTypeRepository =
61
- new PaymentMethodTypeRepository();
62
- private static _DocumentRepository = new DocumentRepository();
63
- private static _DocumentItemRepository = new DocumentItemRepository();
64
- private static _FinanceCustomerRepository = new FinanceCustomerRepository();
65
- private static _LedgerTransactionRepository =
66
- new LedgerTransactionRepository();
67
-
68
- private static _AccountRepository = new AccountRepository();
69
- private static _TaxRepository = new TaxRepository();
70
-
71
- private _AccountingSystem: IAccountSystem;
72
-
73
- private _DbTransaction: any;
74
- private _PaymentMethods = [];
75
- private _Taxes: Tax[] = [];
76
-
77
- get CompSystemCode(): string {
78
- return this._CompSystemCode;
79
- }
80
-
81
- private set CompSystemCode(code: string) {
82
- this._CompSystemCode = code;
83
- }
84
-
85
- get CompSystemRefId() {
86
- return this._CompSystemRefId;
87
- }
88
-
89
- set CompSystemRefId(id: string) {
90
- this._CompSystemRefId = id;
91
- }
92
-
93
- get AccSystemCode() {
94
- return this._AccSystemCode;
95
- }
96
-
97
- private set AccSystemCode(code: string) {
98
- this._AccSystemCode = code;
99
- }
100
-
101
- get CompanyId() {
102
- return this._CompanyId;
103
- }
104
-
105
- get ObjectId() {
106
- return this._CompanyId;
107
- }
108
-
109
- private set ObjectId(id: string) {
110
- this._CompanyId = id;
111
- }
112
-
113
- get ObjectName() {
114
- return `${this.CompSystemCode}-${this.CompSystemRefId}-${this.AccSystemCode}`;
115
- }
116
-
117
- get TableName() {
118
- return 'finance_Company';
119
- }
120
-
121
- get AccountingSystem(): IAccountSystem {
122
- return this._AccountingSystem;
123
- }
124
-
125
- set AccountingSystem(system: IAccountSystem) {
126
- this._AccountingSystem = system;
127
- }
128
-
129
- constructor(
130
- compSystemCode: string,
131
- compSystemRefId: string,
132
- accSystemCode: string,
133
- ) {
134
- super();
135
- this.CompSystemCode = compSystemCode;
136
- this.CompSystemRefId = compSystemRefId;
137
- this.AccSystemCode = accSystemCode;
138
- }
139
-
140
- static async getFinanceCompanyId(
141
- compSystemCode: string,
142
- compSystemRefId: string,
143
- accSystemCode: string,
144
- ): Promise<string> {
145
- let sCompanyId = '';
146
- /*Assemble the hashtable key*/
147
- const sKey = `${compSystemCode}-${compSystemRefId}-${accSystemCode}`;
148
- /*Check if the FinanceCompany has previously being loaded*/
149
- if (!FinanceCompany._htFinanceCompanyIds.get(sKey)) {
150
- /*Instantiate a new FinanceCompany*/
151
- const financeCompany = new FinanceCompany(
152
- compSystemCode,
153
- compSystemRefId,
154
- accSystemCode,
155
- );
156
-
157
- /*Retrieve the finance company from finance_Company table using compSystemCode,
158
- * CompSystemRefId and accSystemCode */
159
- const company = await FinanceCompany._financeCompanyRepository.findOne({
160
- where: {
161
- CompSystemCode: compSystemCode,
162
- CompSystemRefId: compSystemRefId,
163
- AccSystemCode: accSystemCode,
164
- },
165
- });
166
-
167
- /*Retrieve and store the companyId from the result*/
168
- financeCompany.ObjectId = company.CompanyId;
169
- sCompanyId = financeCompany.ObjectId;
170
-
171
- /*Add the details into the hashtable*/
172
- FinanceCompany._htFinanceCompanyIds.add(sKey, financeCompany.ObjectId);
173
- FinanceCompany._htFinanceCompanies.add(sCompanyId, financeCompany);
174
- }
175
-
176
- if (typeof FinanceCompany._htFinanceCompanyIds.get(sKey) === 'string') {
177
- sCompanyId = FinanceCompany._htFinanceCompanyIds.get(sKey);
178
- }
179
-
180
- return sCompanyId;
181
- }
182
-
183
- static async getFinanceCompany(companyId: string): Promise<FinanceCompany> {
184
- /*Check if the finance company is previously be loaded*/
185
- if (!FinanceCompany._htFinanceCompanies.get(companyId)) {
186
- /*Retrieve the finance company from finance_Company table using compSystemCode,
187
- * CompSystemRefId and accSystemCode */
188
- const company = await FinanceCompany._financeCompanyRepository.findOne({
189
- where: { CompanyId: companyId },
190
- });
191
-
192
- if (!company) {
193
- throw Error('No finance company found. Please create first.');
194
- }
195
-
196
- /*Using the result returned, instantiate a new FinanceCompany*/
197
- const compSystemCode = company.CompSystemCode;
198
- const compSystemRefId = company.CompSystemRefId;
199
- const accSystemCode = company.AccSystemCode;
200
-
201
- const financeCompany = new FinanceCompany(
202
- compSystemCode,
203
- compSystemRefId,
204
- accSystemCode,
205
- );
206
-
207
- /*Retrieve and store the CompanyId from the result*/
208
- financeCompany.ObjectId = company.CompanyId;
209
- financeCompany._CompanyId = company.CompanyId;
210
-
211
- /*Add the details into the hashtable*/
212
- const sKey = `${compSystemCode}-${compSystemRefId}-${accSystemCode}`;
213
- FinanceCompany._htFinanceCompanyIds.add(sKey, financeCompany.ObjectId);
214
- FinanceCompany._htFinanceCompanies.add(
215
- financeCompany.ObjectId,
216
- financeCompany,
217
- );
218
- }
219
- // tslint:disable-next-line:no-console
220
- console.log('return from hash table');
221
- return FinanceCompany._htFinanceCompanies.get(companyId);
222
- }
223
-
224
- static async createFinanceCompany(
225
- dbTransaction: any,
226
- loginUser: LoginUserBase,
227
- companyId: string,
228
- compSystemCode: string,
229
- compSystemRefId: string,
230
- accSystemCode: string,
231
- ) {
232
- /*Instantiate a new FinanceCompany*/
233
- const financeCompany = new FinanceCompany(
234
- compSystemCode,
235
- compSystemRefId,
236
- accSystemCode,
237
- );
238
-
239
- /*Validating if the finance company already exists in finance_Company*/
240
- const company = await FinanceCompany._financeCompanyRepository.findOne({
241
- where: {
242
- CompSystemCode: compSystemCode,
243
- CompSystemRefId: compSystemRefId,
244
- AccSystemCode: accSystemCode,
245
- },
246
- });
247
-
248
- if (company) {
249
- throw Error(
250
- 'There is already another Finance Company with the compSystemCode, CompSystemRefId and accSystemCode specified.',
251
- );
252
- }
253
-
254
- /*Generating the companyId*/
255
- financeCompany.ObjectId = companyId;
256
-
257
- /*Save the FinanceCompany to the finance_Company table*/
258
- await FinanceCompany._financeCompanyRepository.create(
259
- {
260
- CompanyId: financeCompany.CompanyId,
261
- CompSystemCode: financeCompany.CompSystemCode,
262
- CompSystemRefId: financeCompany.CompSystemRefId,
263
- AccSystemCode: financeCompany.AccSystemCode,
264
- },
265
- {
266
- transaction: dbTransaction,
267
- },
268
- );
269
-
270
- /*Add the details to hashtable*/
271
- const sKey = `${compSystemCode}-${compSystemRefId}-${accSystemCode}`;
272
- FinanceCompany._htFinanceCompanyIds.add(sKey, financeCompany.ObjectId);
273
- FinanceCompany._htFinanceCompanies.add(
274
- financeCompany.ObjectId,
275
- financeCompany,
276
- );
277
-
278
- // tslint:disable-next-line:no-console
279
- console.log('return from hash table');
280
- return FinanceCompany._htFinanceCompanies.get(companyId);
281
- }
282
-
283
- async createCustomer(
284
- dbTransaction: any,
285
- custSystemCode: string,
286
- custSystemRefId: string,
287
- customer: FinanceCustomerBase,
288
- loginUser: LoginUser,
289
- ) {
290
- try {
291
- if (!custSystemCode || !custSystemRefId) {
292
- throw new Error(
293
- 'CustSystemCode and CustomerRefId are required fields.',
294
- );
295
- }
296
-
297
- const financeCustomerData =
298
- await FinanceCompany._FinanceCustomerRepository.findOne({
299
- where: {
300
- CompanyId: this._CompanyId,
301
- CustSystemCode: custSystemCode,
302
- CustSystemRefId: custSystemRefId,
303
- },
304
- });
305
-
306
- if (financeCustomerData) {
307
- throw new Error('Customer already created previously.');
308
- }
309
-
310
- // Retrieve the type of accounting system, API Key, and API secret based on SysCode from the Config.ts
311
- // const customerId = await this.AccountingSystem.createCustomer({
312
- // customer,
313
- // });
314
- const customerId = 'REF';
315
-
316
- customer.CompanyId = this._CompanyId;
317
-
318
- const newCustomer = await customer.save(
319
- customerId,
320
- custSystemCode,
321
- custSystemRefId,
322
- dbTransaction,
323
- );
324
-
325
- const activity = new Activity();
326
- activity.ActivityId = cuid();
327
- activity.Action = ActionEnum.ADD;
328
- activity.Description = 'Add Finance Customer';
329
- activity.EntityType = 'FinanceCustomer';
330
- activity.EntityId = newCustomer.CustomerId;
331
- activity.EntityValueBefore = JSON.stringify({});
332
- activity.EntityValueAfter = JSON.stringify(newCustomer);
333
-
334
- await activity.create(loginUser, dbTransaction);
335
-
336
- return customer;
337
- } catch (error) {
338
- throw error;
339
- }
340
- }
341
-
342
- async postJournal(
343
- dbTransaction: any,
344
- journalEntry: JournalEntry,
345
- loginUser: LoginUserBase,
346
- ) {
347
- const debitTransactions = await journalEntry.DebitTransactions;
348
- const creditTransactions = await journalEntry.CreditTransactions;
349
- try {
350
- if (creditTransactions.length < 1 || debitTransactions?.length < 1) {
351
- throw new Error(
352
- 'There should be at least 1 debit ledger transaction and 1 credit ledger transaction in the journal entry',
353
- );
354
- }
355
-
356
- const totalCreditAmount = creditTransactions.reduce(
357
- (accumulator, currentValue) => accumulator + currentValue.CreditAmount,
358
- 0,
359
- );
360
- const totalDebitAmount = debitTransactions.reduce(
361
- (accumulator, currentValue) => accumulator + currentValue.DebitAmount,
362
- 0,
363
- );
364
-
365
- if (totalCreditAmount !== totalDebitAmount) {
366
- throw new Error(
367
- 'Credit ledger transaction and debit ledger transaction should the same amount',
368
- );
369
- }
370
-
371
- const newJournalEntry = await journalEntry.save(
372
- loginUser.ObjectId,
373
- dbTransaction,
374
- );
375
-
376
- for (const ledgerTransaction of debitTransactions) {
377
- ledgerTransaction.TransactionId = cuid();
378
- ledgerTransaction.JournalEntryId = newJournalEntry.JournalEntryId;
379
-
380
- await ledgerTransaction.save(dbTransaction);
381
- // const dt = await ledgerTransaction.newLedgerTransaction(
382
- // TransactionTypeOptions.DEBIT,
383
- // newJournalEntry.JournalEntryId,
384
- // );
385
- // await dt.save();
386
- }
387
-
388
- for (const ledgerTransaction of creditTransactions) {
389
- ledgerTransaction.TransactionId = cuid();
390
- ledgerTransaction.JournalEntryId = newJournalEntry.JournalEntryId;
391
-
392
- await ledgerTransaction.save(dbTransaction);
393
- // const ct = await ledgerTransaction.newLedgerTransaction(
394
- // TransactionTypeOptions.CREDIT,
395
- // newJournalEntry.JournalEntryId,
396
- // );
397
- // await ct.save();
398
- }
399
-
400
- // await this.AccountingSystem.postJournalEntry(newJournalEntry);
401
-
402
- const payload = {
403
- Action: 'Create',
404
- Activity: 'Post Journal Entry',
405
- Description: `Journal Entry (ID: ${newJournalEntry.JournalEntryId}) has been created`,
406
- EntityType: 'JournalEntry',
407
- EntityValueBefore: JSON.stringify({}),
408
- EntityValueAfter: JSON.stringify(newJournalEntry),
409
- PerformedById: loginUser.ObjectId,
410
- PerformedAt: new Date(),
411
- EntityId: newJournalEntry.JournalEntryId,
412
- };
413
-
414
- await axios.post(
415
- `${process.env.COMMON_API_URL}/activity-histories`,
416
- payload,
417
- );
418
- } catch (error) {
419
- throw error;
420
- }
421
- }
422
-
423
- async createAccount(
424
- dbTransaction: any,
425
- account: Account,
426
- loginUser: LoginUserBase,
427
- ) {
428
- try {
429
- if (!account.AccountType) {
430
- throw new Error('AccountType is required.');
431
- }
432
-
433
- let createAccountPayload: any = {
434
- Name: account.Name,
435
- AcctNum: account.AccountNo,
436
- AccountType: account.AccountType,
437
- AccountSubType: account.AccountSubtype,
438
- };
439
-
440
- if (account.isParentAccountExists()) {
441
- createAccountPayload = {
442
- ...createAccountPayload,
443
- CurrencyRef: 'MYR',
444
- ParentRef: account.ParentAccountNo,
445
- SubAccount: true,
446
- };
447
- }
448
-
449
- console.log(
450
- 'Finance Company Create Account: Before accSystemAccountId Create',
451
- );
452
-
453
- // const accSystemAccountId = await this.AccountingSystem.createAccount(
454
- // createAccountPayload,
455
- // );
456
-
457
- const accSystemAccountId = 'REF';
458
-
459
- console.log(
460
- 'Finance Company Create Account: After accSystemAccountId Create',
461
- );
462
-
463
- console.log('Finance Company Create Account: Before new Account Create');
464
- const newAccount = await account.save(
465
- this.CompanyId,
466
- accSystemAccountId,
467
- loginUser.ObjectId,
468
- dbTransaction,
469
- );
470
-
471
- console.log('Finance Company Create Account: After new Account Create');
472
-
473
- const payload = {
474
- Action: 'Create',
475
- Activity: 'Account Created',
476
- Description: `Account (ID: ${newAccount.AccountNo}) has been created`,
477
- EntityType: 'Account',
478
- EntityValueBefore: JSON.stringify({}),
479
- EntityValueAfter: JSON.stringify(newAccount),
480
- PerformedById: loginUser.ObjectId,
481
- PerformedAt: new Date(),
482
- EntityId: newAccount.AccountNo,
483
- };
484
-
485
- await axios.post(
486
- `${process.env.COMMON_API_URL}/activity-histories`,
487
- payload,
488
- );
489
-
490
- return account;
491
- } catch (error) {
492
- throw error;
493
- }
494
- }
495
-
496
- /**
497
- * Issue an invoice
498
- *
499
- * @param dbTransaction - The database transaction to be used
500
- * @param loginUser - The user issuing the invoice
501
- * @param invoice - The document containing the invoice details
502
- * @param customer - The customer to be issued the invoice
503
- * @param dtAccountNo - The account number of the Account Receivable (AR) account to debit. If not provided, will debit the customer's default AR account
504
- *
505
- * @returns {Document} - Document object representing the full details of the invoice issued
506
- */
507
- async issueInvoice(
508
- /*todo: loginUser & customer is NOT supposed to be optional */
509
- dbTransaction: any,
510
- invoice: Document,
511
- loginUser?: LoginUserBase,
512
- customer?: FinanceCustomerBase,
513
- dtAccountNo?: string,
514
- ): Promise<Document> {
515
- try {
516
- /*Check if the invoice number already exists (should be unique)*/
517
- const duplicateInvoice = await FinanceCompany._DocumentRepository.findOne(
518
- {
519
- where: {
520
- DocNo: invoice.DocNo,
521
- },
522
- transaction: dbTransaction,
523
- },
524
- );
525
-
526
- if (duplicateInvoice) {
527
- throw new Error('Invoice number already exists');
528
- }
529
-
530
- const documentItems = await invoice.DocumentItems;
531
-
532
- /*Check if the document has at least 1 document item*/
533
- if (!documentItems.length) {
534
- throw new Error('Document must have at least 1 document item');
535
- }
536
-
537
- /*Check if each document item has CtAccountNo provided*/
538
- for (const invoiceItem of documentItems) {
539
- if (!invoiceItem.CtAccountNo) {
540
- throw new Error(
541
- 'Each document item should have CtAccountNo provided',
542
- );
543
- }
544
- }
545
-
546
- /*Set up the document type*/
547
- invoice.DocType = DocType.INVOICE;
548
-
549
- /*Generating the invoice*/
550
- let invoiceMedia: {
551
- HTMLMedia: MediasModel;
552
- PDFMedia: MediasModel;
553
- };
554
-
555
- if (invoice.UseAccSystemDocYN === 'Y') {
556
- /*todo: Posting to accounting system to generate invoice*/
557
- // await this.AccountingSystem.createInvoice(invoice);
558
- } else {
559
- /*todo: check config file to see which invoice template is to be used for specific project*/
560
-
561
- /*Generating invoice based on template*/
562
- invoiceMedia = await invoice.generateInvoice(
563
- invoice.IssuedById,
564
- customer,
565
- dbTransaction,
566
- );
567
- }
568
-
569
- /*Saving the document and document items to the database*/
570
- await FinanceCompany._DocumentRepository.create(
571
- {
572
- DocNo: invoice.DocNo,
573
- DocType: invoice.DocType,
574
- DocDate: invoice.DocDate,
575
- CompanyId: invoice.CompanyId,
576
- Currency: invoice.Currency,
577
- Amount: invoice.Amount,
578
- Description: invoice.Description,
579
- Status: invoice.Status,
580
- IssuedById: invoice.IssuedById,
581
- IssuedToId: invoice.IssuedToId,
582
- IssuedToType: invoice.IssuedToType,
583
- RelatedObjectId: invoice.RelatedObjectId,
584
- RelatedObjectType: invoice.RelatedObjectType,
585
- CreatedById: invoice.CreatedById,
586
- CreatedAt: new Date(),
587
- UpdatedById: invoice.UpdatedById,
588
- UpdatedAt: new Date(),
589
- DocPDFFileMediaId: invoiceMedia.PDFMedia.MediaId,
590
- DocHTMLFileMediaId: invoiceMedia.HTMLMedia.MediaId,
591
- AccSystemRefId: invoice.AccSystemRefId,
592
- PostedToAccSystemYN: invoice.PostedToAccSystemYN,
593
- PostedById: invoice.PostedById,
594
- PostedDateTime: new Date(),
595
- UseAccSystemDocYN: invoice.UseAccSystemDocYN,
596
- },
597
- {
598
- transaction: dbTransaction,
599
- },
600
- );
601
-
602
- for (const documentItem of documentItems) {
603
- await FinanceCompany._DocumentItemRepository.create(
604
- {
605
- DocumentItemId: cuid(),
606
- DocNo: invoice.DocNo,
607
- Name: documentItem.Name,
608
- NameBM: documentItem.NameBM,
609
- Description: documentItem.Description,
610
- ItemId: documentItem.ItemId,
611
- ItemType: documentItem.ItemType,
612
- ItemSKU: documentItem.ItemSKU,
613
- ItemSerialNo: documentItem.ItemSerialNo,
614
- Currency: documentItem.Currency,
615
- UnitPrice: documentItem.UnitPrice,
616
- Quantity: documentItem.Quantity,
617
- QuantityUOM: documentItem.QuantityUOM,
618
- Amount: documentItem.Amount,
619
- TaxCode: documentItem.TaxCode,
620
- TaxAmount: documentItem.TaxAmount,
621
- TaxRate: documentItem.TaxRate,
622
- TaxInclusiveYN: documentItem.TaxInclusiveYN,
623
- DtAccountNo: documentItem.DtAccountNo
624
- ? documentItem.DtAccountNo
625
- : null,
626
- CtAccountNo: documentItem.CtAccountNo
627
- ? documentItem.CtAccountNo
628
- : null,
629
- },
630
- {
631
- transaction: dbTransaction,
632
- },
633
- );
634
- }
635
-
636
- const transactionDate = new Date();
637
- const htCreditAccountAmount = new HashTable();
638
- const htCreditAccountCurrency = new HashTable();
639
- const htCreditAccountPurpose = new HashTable();
640
-
641
- documentItems.forEach((invoiceItem) => {
642
- if (!htCreditAccountAmount.exists(invoiceItem.CtAccountNo)) {
643
- //add the credit account to the hash table
644
- htCreditAccountAmount.add(
645
- invoiceItem.CtAccountNo,
646
- invoiceItem.Amount,
647
- );
648
-
649
- htCreditAccountCurrency.add(
650
- invoiceItem.CtAccountNo,
651
- invoiceItem.Currency,
652
- );
653
-
654
- htCreditAccountPurpose.add(invoiceItem.CtAccountNo, invoiceItem.Name);
655
- } else {
656
- //update the credit account amount
657
- const d = htCreditAccountAmount.get(invoiceItem.CtAccountNo);
658
- htCreditAccountAmount.add(
659
- invoiceItem.CtAccountNo,
660
- d + invoiceItem.Amount,
661
- );
662
- }
663
- });
664
-
665
- const savedItems = htCreditAccountAmount.list();
666
-
667
- for (const item of savedItems) {
668
- const journalEntry = new JournalEntry(dbTransaction);
669
- //Temporary fix to successfully save journal entry in PostJournal
670
- journalEntry.init({
671
- CompanyId: this.CompanyId,
672
- Name: 'Issue Invoice ' + invoice.DocNo,
673
- });
674
- // const account = await Account.initAccount(dbTransaction, item.value[0]);
675
- const creditAmount = item.value[1];
676
- const currency = htCreditAccountCurrency.get(item.value[0]);
677
- const purpose = htCreditAccountPurpose.get(item.value[0]);
678
-
679
- const dt = await journalEntry.newLedgerTransaction(
680
- TransactionTypeOptions.DEBIT,
681
- );
682
-
683
- if (dtAccountNo) {
684
- /*Transacting using AR account provided*/
685
- dt.AccountNo = dtAccountNo;
686
- } else {
687
- /*Transacting based on default customer AR account*/
688
- const arAccount = await customer.getAccountReceivable();
689
- dt.AccountNo = arAccount.AccountNo;
690
- }
691
-
692
- dt.Currency = currency ? currency : 'MYR';
693
- dt.DebitAmount = creditAmount ? creditAmount : 0.0;
694
- dt.Date = transactionDate;
695
- dt.Description = `${purpose}`;
696
- dt.Name = `${purpose}`;
697
- dt.RelatedDocNo = invoice.DocNo;
698
- dt.RelatedObjectId = invoice.RelatedObjectId;
699
- dt.RelatedObjectType = invoice.RelatedObjectType;
700
-
701
- const ct = await journalEntry.newLedgerTransaction(
702
- TransactionTypeOptions.CREDIT,
703
- );
704
- ct.AccountNo = item.value[0];
705
- ct.Currency = currency ? currency : 'MYR';
706
- ct.CreditAmount = creditAmount ? creditAmount : 0.0;
707
- ct.Date = transactionDate;
708
- ct.Description = customer.FullName;
709
- ct.Name = customer.FullName;
710
- ct.RelatedDocNo = invoice.DocNo;
711
- ct.RelatedObjectId = invoice.RelatedObjectId;
712
- ct.RelatedObjectType = invoice.RelatedObjectType;
713
-
714
- await this.postJournal(dbTransaction, journalEntry, loginUser);
715
- }
716
-
717
- return invoice;
718
- } catch (err) {
719
- // tslint:disable-next-line:no-console
720
- console.log('Issue invoice err: ', err);
721
- throw err;
722
- }
723
- }
724
-
725
- /**
726
- * Issue a debit note
727
- *
728
- * @param dbTransaction - The database transaction to be used
729
- * @param loginUser - The user issuing the invoice
730
- * @param invoice - The document containing the invoice details
731
- * @param customer - The customer to be issued the invoice
732
- * @param dtAccountNo - The account number of the Account Receivable (AR) account to debit. If not provided, will debit the customer's default AR account
733
- *
734
- * @returns {Document} - Document object representing the full details of the invoice issued
735
- */
736
- async issueDebitNote(
737
- dbTransaction: any,
738
- loginUser: LoginUserBase,
739
- invoice: Document,
740
- customer: FinanceCustomerBase,
741
- dtAccountNo?: string,
742
- ): Promise<Document> {
743
- try {
744
- /*Check if the invoice number already exists (should be unique)*/
745
- const duplicateInvoice = await FinanceCompany._DocumentRepository.findOne(
746
- {
747
- where: {
748
- DocNo: invoice.DocNo,
749
- },
750
- transaction: dbTransaction,
751
- },
752
- );
753
-
754
- if (duplicateInvoice) {
755
- throw new Error('Invoice number already exists');
756
- }
757
-
758
- const documentItems = await invoice.DocumentItems;
759
-
760
- /*Check if the document has at least 1 document item*/
761
- if (!documentItems.length) {
762
- throw new Error('Document must have at least 1 document item');
763
- }
764
-
765
- /*Check if each document item has CtAccountNo provided*/
766
- for (const invoiceItem of documentItems) {
767
- if (!invoiceItem.CtAccountNo) {
768
- throw new Error(
769
- 'Each document item should have CtAccountNo provided',
770
- );
771
- }
772
- }
773
-
774
- /*Set up the document type*/
775
- invoice.DocType = DocType.DEBIT_NOTE;
776
- // invoice.DocNo = cuid();
777
-
778
- /*Saving the document and document items to the database*/
779
- await FinanceCompany._DocumentRepository.create(
780
- {
781
- DocNo: invoice.DocNo,
782
- DocType: invoice.DocType,
783
- DocDate: invoice.DocDate,
784
- CompanyId: invoice.CompanyId,
785
- Currency: invoice.Currency,
786
- Amount: invoice.Amount,
787
- Description: invoice.Description,
788
- Status: invoice.Status,
789
- IssuedById: loginUser.ObjectId,
790
- IssuedToId: customer.ObjectId,
791
- IssuedToType: invoice.IssuedToType,
792
- RelatedObjectId: invoice.RelatedObjectId,
793
- RelatedObjectType: invoice.RelatedObjectType,
794
- CreatedById: loginUser.ObjectId,
795
- CreatedAt: new Date(),
796
- UpdatedById: loginUser.ObjectId,
797
- UpdatedAt: new Date(),
798
- DocPDFFileMediaId: invoice.DocPDFFileMediaId,
799
- DocHTMLFileMediaId: invoice.DocHTMLFileMediaId,
800
- AccSystemRefId: invoice.AccSystemRefId,
801
- PostedToAccSystemYN: invoice.PostedToAccSystemYN,
802
- PostedById: invoice.PostedById,
803
- PostedDateTime: new Date(),
804
- UseAccSystemDocYN: invoice.UseAccSystemDocYN,
805
- },
806
- {
807
- transaction: dbTransaction,
808
- },
809
- );
810
-
811
- documentItems.forEach(async (documentItem) => {
812
- await FinanceCompany._DocumentItemRepository.create(
813
- {
814
- DocumentItemId: cuid(),
815
- DocNo: documentItem.DocNo,
816
- Name: documentItem.Name,
817
- NameBM: documentItem.NameBM,
818
- Description: documentItem.Description,
819
- ItemId: documentItem.ItemId,
820
- ItemType: documentItem.ItemType,
821
- ItemSKU: documentItem.ItemSKU,
822
- ItemSerialNo: documentItem.ItemSerialNo,
823
- Currency: documentItem.Currency,
824
- UnitPrice: documentItem.UnitPrice,
825
- Quantity: documentItem.Quantity,
826
- QuantityUOM: documentItem.QuantityUOM,
827
- Amount: documentItem.Amount,
828
- TaxCode: documentItem.TaxCode,
829
- TaxAmount: documentItem.TaxAmount,
830
- TaxRate: documentItem.TaxRate,
831
- TaxInclusiveYN: documentItem.TaxInclusiveYN,
832
- DtAccountNo: documentItem.DtAccountNo,
833
- CtAccountNo: documentItem.CtAccountNo,
834
- },
835
- {
836
- transaction: dbTransaction,
837
- },
838
- );
839
- });
840
-
841
- /*Generating the invoice*/
842
- if (invoice.UseAccSystemDocYN === 'Y') {
843
- /*todo: Posting to accounting system to generate invoice*/
844
- // await this.AccountingSystem.createInvoice(invoice);
845
- } else {
846
- /*todo: check config file to see which invoice template is to be used for specific project*/
847
-
848
- /*Generating invoice based on template*/
849
- invoice.generateInvoice(loginUser.IDNo, customer);
850
- }
851
-
852
- const transactionDate = new Date();
853
- const htCreditAccountAmount = new HashTable();
854
- const htCreditAccountCurrency = new HashTable();
855
- const htCreditAccountPurpose = new HashTable();
856
-
857
- documentItems.forEach((invoiceItem) => {
858
- if (!htCreditAccountAmount.exists(invoiceItem.CtAccountNo)) {
859
- //add the credit account to the hash table
860
- htCreditAccountAmount.add(
861
- invoiceItem.CtAccountNo,
862
- invoiceItem.Amount,
863
- );
864
-
865
- htCreditAccountCurrency.add(
866
- invoiceItem.CtAccountNo,
867
- invoiceItem.Currency,
868
- );
869
-
870
- htCreditAccountPurpose.add(invoiceItem.CtAccountNo, invoiceItem.Name);
871
- } else {
872
- //update the credit account amount
873
- const d = htCreditAccountAmount.get(invoiceItem.CtAccountNo);
874
- htCreditAccountAmount.add(
875
- invoiceItem.CtAccountNo,
876
- d + invoiceItem.Amount,
877
- );
878
- }
879
- });
880
-
881
- const savedItems = htCreditAccountAmount.list();
882
-
883
- for (const item of savedItems) {
884
- const journalEntry = new JournalEntry(dbTransaction);
885
- //Temporary fix to successfully save journal entry in PostJournal
886
- journalEntry.init({
887
- CompanyId: this.CompanyId,
888
- Name: 'issue Invoice ' + invoice.DocNo,
889
- });
890
- // const account = await Account.initAccount(dbTransaction, item.value[0]);
891
- const creditAmount = item.value[1];
892
- const currency = htCreditAccountCurrency.get(item.value[0]);
893
- const purpose = htCreditAccountPurpose.get(item.value[0]);
894
-
895
- const dt = await journalEntry.newLedgerTransaction(
896
- TransactionTypeOptions.DEBIT,
897
- );
898
-
899
- if (dtAccountNo) {
900
- /*Transacting using AR account provided*/
901
- dt.AccountNo = dtAccountNo;
902
- } else {
903
- /*Transacting based on default customer AR account*/
904
- const arAccount = await customer.getAccountReceivable();
905
- dt.AccountNo = arAccount.AccountNo;
906
- }
907
-
908
- dt.Currency = currency ? currency : 'MYR';
909
- dt.DebitAmount = creditAmount ? creditAmount : 0.0;
910
- dt.Date = transactionDate;
911
- dt.Description = `${purpose}`;
912
- dt.Name = `${purpose}`;
913
- dt.RelatedDocNo = invoice.DocNo;
914
- dt.RelatedObjectId = invoice.RelatedObjectId;
915
- dt.RelatedObjectType = invoice.RelatedObjectType;
916
-
917
- const ct = await journalEntry.newLedgerTransaction(
918
- TransactionTypeOptions.CREDIT,
919
- );
920
- ct.AccountNo = item.value[0];
921
- ct.Currency = currency ? currency : 'MYR';
922
- ct.CreditAmount = creditAmount ? creditAmount : 0.0;
923
- ct.Date = transactionDate;
924
- ct.Description = customer.FullName;
925
- ct.Name = customer.FullName;
926
- ct.RelatedDocNo = invoice.DocNo;
927
- ct.RelatedObjectId = invoice.RelatedObjectId;
928
- ct.RelatedObjectType = invoice.RelatedObjectType;
929
-
930
- await this.postJournal(dbTransaction, journalEntry, loginUser);
931
- }
932
-
933
- return invoice;
934
- } catch (err) {
935
- // tslint:disable-next-line:no-console
936
- console.log('Issue debit note err: ', err);
937
- throw err;
938
- }
939
- }
940
-
941
- /**
942
- * Issue a credit note
943
- *
944
- * @param dbTransaction - The database transaction to be used
945
- * @param loginUser - The user issuing the credit note
946
- * @param creditNote - The document containing the credit note details
947
- * @param customer - The customer to be issued the credit note
948
- * @param ctAccountNo - The account number of the Account Payable (AP) account to debit. If not provided, will debit the customer's default AR account
949
- *
950
- * @returns {Document} - Document object representing the full details of the invoice issued
951
- */
952
- async issueCreditNote(
953
- dbTransaction: any,
954
- loginUser: LoginUserBase,
955
- creditNote: Document,
956
- customer: FinanceCustomerBase,
957
- ctAccountNo?: string,
958
- ): Promise<Document> {
959
- try {
960
- /*Check if the invoice number already exists (should be unique)*/
961
- const duplicateCreditNote =
962
- await FinanceCompany._DocumentRepository.findOne({
963
- where: {
964
- DocNo: creditNote.DocNo,
965
- },
966
- transaction: dbTransaction,
967
- });
968
-
969
- if (duplicateCreditNote) {
970
- throw new Error('Invoice number already exists');
971
- }
972
-
973
- const documentItems = await creditNote.DocumentItems;
974
-
975
- /*Check if the document has at least 1 document item*/
976
- if (!documentItems.length) {
977
- throw new Error('Document must have at least 1 document item');
978
- }
979
-
980
- /*Check if each document item has CtAccountNo provided*/
981
- for (const invoiceItem of documentItems) {
982
- if (!invoiceItem.CtAccountNo) {
983
- throw new Error(
984
- 'Each document item should have CtAccountNo provided',
985
- );
986
- }
987
- }
988
-
989
- /*Set up the document type*/
990
- creditNote.DocType = DocType.DEBIT_NOTE;
991
-
992
- /*Saving the document and document items to the database*/
993
- await FinanceCompany._DocumentRepository.create(
994
- {
995
- DocNo: creditNote.DocNo,
996
- DocType: creditNote.DocType,
997
- DocDate: creditNote.DocDate,
998
- CompanyId: creditNote.CompanyId,
999
- Currency: creditNote.Currency,
1000
- Amount: creditNote.Amount,
1001
- Description: creditNote.Description,
1002
- Status: creditNote.Status,
1003
- IssuedById: loginUser.ObjectId,
1004
- IssuedToId: customer.ObjectId,
1005
- IssuedToType: creditNote.IssuedToType,
1006
- RelatedObjectId: creditNote.RelatedObjectId,
1007
- RelatedObjectType: creditNote.RelatedObjectType,
1008
- CreatedById: loginUser.ObjectId,
1009
- CreatedAt: new Date(),
1010
- UpdatedById: loginUser.ObjectId,
1011
- UpdatedAt: new Date(),
1012
- DocPDFFileMediaId: creditNote.DocPDFFileMediaId,
1013
- DocHTMLFileMediaId: creditNote.DocHTMLFileMediaId,
1014
- AccSystemRefId: creditNote.AccSystemRefId,
1015
- PostedToAccSystemYN: creditNote.PostedToAccSystemYN,
1016
- PostedById: creditNote.PostedById,
1017
- PostedDateTime: new Date(),
1018
- UseAccSystemDocYN: creditNote.UseAccSystemDocYN,
1019
- },
1020
- {
1021
- transaction: dbTransaction,
1022
- },
1023
- );
1024
-
1025
- documentItems.forEach(async (documentItem) => {
1026
- await FinanceCompany._DocumentItemRepository.create(
1027
- {
1028
- DocumentItemId: documentItem.DocumentItemId,
1029
- DocNo: documentItem.DocNo,
1030
- Name: documentItem.Name,
1031
- NameBM: documentItem.NameBM,
1032
- Description: documentItem.Description,
1033
- ItemId: documentItem.ItemId,
1034
- ItemType: documentItem.ItemType,
1035
- ItemSKU: documentItem.ItemSKU,
1036
- ItemSerialNo: documentItem.ItemSerialNo,
1037
- Currency: documentItem.Currency,
1038
- UnitPrice: documentItem.UnitPrice,
1039
- Quantity: documentItem.Quantity,
1040
- QuantityUOM: documentItem.QuantityUOM,
1041
- Amount: documentItem.Amount,
1042
- TaxCode: documentItem.TaxCode,
1043
- TaxAmount: documentItem.TaxAmount,
1044
- TaxRate: documentItem.TaxRate,
1045
- TaxInclusiveYN: documentItem.TaxInclusiveYN,
1046
- DtAccountNo: documentItem.DtAccountNo,
1047
- CtAccountNo: documentItem.CtAccountNo,
1048
- },
1049
- {
1050
- transaction: dbTransaction,
1051
- },
1052
- );
1053
- });
1054
-
1055
- /*Generating the credit note*/
1056
- if (creditNote.UseAccSystemDocYN === 'Y') {
1057
- /*todo: Posting to accounting system to generate creditNote*/
1058
- // await this.AccountingSystem.createCreditNote(creditNote);
1059
- } else {
1060
- /*todo: check config file to see which invoice template is to be used for specific project*/
1061
-
1062
- /*Generating credit note based on template*/
1063
- creditNote.generateCreditNote(loginUser.IDNo, customer);
1064
- }
1065
-
1066
- const journalEntry = new JournalEntry(dbTransaction);
1067
- //Temporary fix to successfully save journal entry in PostJournal
1068
- journalEntry.init({
1069
- CompanyId: this.CompanyId,
1070
- Name: 'Issue Debit Note ' + creditNote.DocNo,
1071
- });
1072
-
1073
- const transactionDate = new Date();
1074
-
1075
- const creditTransaction = await journalEntry.newLedgerTransaction(
1076
- TransactionTypeOptions.CREDIT,
1077
- );
1078
-
1079
- if (ctAccountNo) {
1080
- /*Transacting using AR account provided*/
1081
- creditTransaction.AccountNo = ctAccountNo;
1082
- } else {
1083
- /*Transacting based on default customer AR account*/
1084
- creditTransaction.AccountNo = customer.CustSystemCode + '-AP';
1085
- }
1086
-
1087
- creditTransaction.Currency = creditNote.Currency;
1088
- creditTransaction.CreditAmount = creditNote.Amount;
1089
- creditTransaction.Date = transactionDate;
1090
- creditTransaction.Description = creditNote.DocNo;
1091
- creditTransaction.Name = creditNote.DocNo;
1092
- creditTransaction.RelatedDocNo = creditNote.DocNo;
1093
- creditTransaction.RelatedObjectId = creditNote.RelatedObjectId;
1094
- creditTransaction.RelatedObjectType = creditNote.RelatedObjectType;
1095
-
1096
- for (const invoiceItem of documentItems) {
1097
- const itemLedger = await journalEntry.newLedgerTransaction(
1098
- TransactionTypeOptions.DEBIT,
1099
- );
1100
- itemLedger.AccountNo = invoiceItem.CtAccountNo;
1101
- itemLedger.Currency = invoiceItem.Currency;
1102
- itemLedger.DebitAmount = invoiceItem.Amount;
1103
- itemLedger.Date = transactionDate;
1104
- itemLedger.Description = invoiceItem.Description;
1105
- itemLedger.Name = invoiceItem.Name;
1106
- itemLedger.RelatedDocNo = creditNote.DocNo;
1107
- itemLedger.RelatedObjectId = creditNote.RelatedObjectId;
1108
- itemLedger.RelatedObjectType = creditNote.RelatedObjectType;
1109
- }
1110
-
1111
- this.postJournal(dbTransaction, journalEntry, loginUser);
1112
-
1113
- const payload = {
1114
- Action: 'Create',
1115
- Activity: 'Issuing a Credit Note Transaction',
1116
- Description: `Credit Transaction (ID: ${creditTransaction.TransactionId}) has been created`,
1117
- EntityType: 'CreditTransaction',
1118
- EntityValueBefore: JSON.stringify({}),
1119
- EntityValueAfter: JSON.stringify(creditTransaction),
1120
- PerformedById: loginUser.ObjectId,
1121
- PerformedAt: transactionDate,
1122
- EntityId: creditTransaction.TransactionId,
1123
- };
1124
-
1125
- await axios.post(
1126
- `${process.env.COMMON_API_URL}/activity-histories`,
1127
- payload,
1128
- );
1129
-
1130
- return creditNote;
1131
- } catch (err) {
1132
- // tslint:disable-next-line:no-console
1133
- console.log('Issue credit note err: ', err);
1134
- throw err;
1135
- }
1136
- }
1137
-
1138
- /**
1139
- * Register a payment collected
1140
- *
1141
- * @param dbTransaction - The database transaction to be used
1142
- * @param loginUser - The user collecting the payment
1143
- * @param payment - The payment object containing payment details
1144
- * @param customer - The customer making the payment
1145
- * @param ctAccountNo - The account number of the customer's Account Receivable account to transact, else the default customer account payable receivable will be used
1146
- * @param receiptNo - The document receipt number
1147
- *
1148
- * @returns {Payment} - Payment object representing the full detals of the payment collection recorded
1149
- */
1150
- async collectPayment(
1151
- dbTransaction: any,
1152
- loginUser: LoginUserBase,
1153
- payment: Payment,
1154
- customer: FinanceCustomerBase,
1155
- ctAccountNo?: string,
1156
- receiptNo?: string,
1157
- ): Promise<Payment> {
1158
- try {
1159
- /*validation 1: Make sure that the payment has at least 1 payment item*/
1160
- const paymentItems = await payment.PaymentItems;
1161
- if (paymentItems.length < 1) {
1162
- throw new Error(
1163
- 'Atleast one payment item is required to identify what payment is being paid for.',
1164
- );
1165
- }
1166
-
1167
- /*validation 2: Make sure that the payment has at least 1 payment method*/
1168
- const paymentPaidWithItems = await payment.PaymentPaidWith;
1169
- if (paymentPaidWithItems.length < 1) {
1170
- throw new Error(
1171
- 'Atleast one payment paid with item is required to identify how the payment was made.',
1172
- );
1173
- }
1174
-
1175
- /*Generating the receipt*/
1176
- const receiptDocuments: any =
1177
- await FinanceCompany._DocumentRepository.findAll({
1178
- where: {
1179
- DocType: DocType.RECEIPT,
1180
- CompanyId: this.ObjectId,
1181
- },
1182
- });
1183
-
1184
- const receipt = new Document(dbTransaction);
1185
-
1186
- if (receiptNo) {
1187
- receipt.DocNo = receiptNo;
1188
- } else {
1189
- receipt.DocNo = `EZC-RCT-${receiptDocuments.length + 1}`;
1190
- }
1191
- receipt.DocType = DocType.RECEIPT;
1192
- receipt.DocDate = new Date();
1193
- receipt.CompanyId = this.ObjectId;
1194
- receipt.Currency = payment.Currency;
1195
- receipt.Description = 'Payment Received';
1196
- receipt.IssuedById = loginUser.ObjectId;
1197
- receipt.IssuedToId = customer.CustomerId;
1198
- receipt.IssuedToType = type(customer);
1199
- receipt.RelatedObjectId = payment.RelatedObjectId;
1200
- receipt.RelatedObjectType = payment.RelatedObjectType;
1201
- receipt.UseAccSystemDocYN = 'N';
1202
- receipt.CreatedById = loginUser.ObjectId;
1203
- receipt.UpdatedById = loginUser.ObjectId;
1204
-
1205
- for (const paymentItem of paymentItems) {
1206
- const receiptItem = new DocumentItem(dbTransaction, receipt);
1207
- receiptItem.Name = `Payment for ${paymentItem.PayForObjectType} No. ${paymentItem.PayForObjectId}`;
1208
- receiptItem.NameBM = `Bayaran untuk ${paymentItem.PayForObjectType} No. ${paymentItem.PayForObjectId}`;
1209
- receiptItem.Description = '-';
1210
- receiptItem.Currency = paymentItem.Currency;
1211
- receiptItem.UnitPrice = paymentItem.Amount;
1212
- receiptItem.Quantity = 1;
1213
- receiptItem.Amount = receiptItem.UnitPrice * receiptItem.Quantity;
1214
- receiptItem.ItemId = receipt.DocNo;
1215
- receiptItem.ItemType = type(payment);
1216
- receiptItem.CtAccountNo = ctAccountNo;
1217
- await receipt.newDocumentItem(receiptItem);
1218
- }
1219
-
1220
- const receiptMedia = await receipt.generateReceipt(
1221
- receipt.IssuedById,
1222
- customer,
1223
- dbTransaction,
1224
- );
1225
-
1226
- /*Saving the receipt document and document items to the database*/
1227
- await FinanceCompany._DocumentRepository.create(
1228
- {
1229
- DocNo: receipt.DocNo,
1230
- DocType: receipt.DocType,
1231
- DocDate: receipt.DocDate,
1232
- CompanyId: receipt.CompanyId,
1233
- Currency: receipt.Currency,
1234
- Amount: receipt.Amount,
1235
- Description: receipt.Description,
1236
- Status: receipt.Status,
1237
- IssuedById: receipt.IssuedById,
1238
- IssuedToId: receipt.IssuedToId,
1239
- IssuedToType: receipt.IssuedToType,
1240
- RelatedObjectId: receipt.RelatedObjectId,
1241
- RelatedObjectType: receipt.RelatedObjectType,
1242
- CreatedById: receipt.CreatedById,
1243
- CreatedAt: new Date(),
1244
- UpdatedById: receipt.UpdatedById,
1245
- UpdatedAt: new Date(),
1246
- DocPDFFileMediaId: receiptMedia.PDFMedia.MediaId,
1247
- DocHTMLFileMediaId: receiptMedia.HTMLMedia.MediaId,
1248
- AccSystemRefId: receipt.AccSystemRefId,
1249
- PostedToAccSystemYN: receipt.PostedToAccSystemYN,
1250
- PostedById: receipt.PostedById,
1251
- PostedDateTime: new Date(),
1252
- UseAccSystemDocYN: receipt.UseAccSystemDocYN,
1253
- },
1254
- {
1255
- transaction: dbTransaction,
1256
- },
1257
- );
1258
-
1259
- const receiptItems = await receipt.DocumentItems;
1260
-
1261
- for (const receiptItem of receiptItems) {
1262
- await FinanceCompany._DocumentItemRepository.create(
1263
- {
1264
- DocumentItemId: cuid(),
1265
- DocNo: receipt.DocNo,
1266
- Name: receiptItem.Name,
1267
- NameBM: receiptItem.NameBM,
1268
- Description: receiptItem.Description,
1269
- ItemId: receiptItem.ItemId,
1270
- ItemType: receiptItem.ItemType,
1271
- ItemSKU: receiptItem.ItemSKU,
1272
- ItemSerialNo: receiptItem.ItemSerialNo,
1273
- Currency: receiptItem.Currency,
1274
- UnitPrice: receiptItem.UnitPrice,
1275
- Quantity: receiptItem.Quantity,
1276
- QuantityUOM: receiptItem.QuantityUOM,
1277
- Amount: receiptItem.Amount,
1278
- TaxCode: receiptItem.TaxCode,
1279
- TaxAmount: receiptItem.TaxAmount,
1280
- TaxRate: receiptItem.TaxRate,
1281
- TaxInclusiveYN: receiptItem.TaxInclusiveYN,
1282
- DtAccountNo: receiptItem.DtAccountNo
1283
- ? receiptItem.DtAccountNo
1284
- : null,
1285
- CtAccountNo: receiptItem.CtAccountNo
1286
- ? receiptItem.CtAccountNo
1287
- : null,
1288
- },
1289
- {
1290
- transaction: dbTransaction,
1291
- },
1292
- );
1293
- }
1294
-
1295
- /*Saving payment, payment items, and payment paid with details to the database*/
1296
- payment.PaymentId = cuid();
1297
- payment.PaymentType = PaymentType.PAYMENT_RECEIVED;
1298
- payment.ReceivedBy = loginUser.ObjectId;
1299
- payment.IssuedBy = loginUser.ObjectId;
1300
- payment.ReceiptDocNo = receipt.DocNo;
1301
-
1302
- await FinanceCompany._PaymentRepository.create(
1303
- {
1304
- PaymentId: payment.PaymentId,
1305
- PaymentType: payment.PaymentType,
1306
- PaymentDate: payment.PaymentDate,
1307
- Description: payment.Description,
1308
- Currency: payment.Currency,
1309
- Amount: payment.Amount,
1310
- Status: PaymentStatus.SUCCESSFUL,
1311
- PostedToAccSystemYN: 'N',
1312
- ReceivedBy: payment.ReceivedBy,
1313
- IssuedBy: payment.IssuedBy,
1314
- Remarks: payment.Remarks,
1315
- RelatedObjectId: payment.RelatedObjectId,
1316
- RelatedObjectType: payment.RelatedObjectType,
1317
- ReceiptDocNo: payment.ReceiptDocNo,
1318
- UpdatedAt: new Date(),
1319
- UpdatedBy: loginUser.ObjectId,
1320
- CreatedAt: new Date(),
1321
- CreatedBy: loginUser.ObjectId,
1322
- },
1323
- { transaction: dbTransaction },
1324
- );
1325
-
1326
- for (const paymentItem of paymentItems) {
1327
- await FinanceCompany._PaymentItemRepository.create(
1328
- {
1329
- PaymentId: payment.PaymentId,
1330
- PayForObjectId: paymentItem.PayForObjectId,
1331
- PayForObjectType: paymentItem.PayForObjectType,
1332
- Currency: paymentItem.Currency,
1333
- Amount: paymentItem.Amount,
1334
- Name: paymentItem.Name,
1335
- Description: paymentItem.Description,
1336
- },
1337
- { transaction: dbTransaction },
1338
- );
1339
-
1340
- await paymentItem.paid(dbTransaction);
1341
- }
1342
-
1343
- for (const paymentPaidWithItem of paymentPaidWithItems) {
1344
- await FinanceCompany._PaymentPaidWithRepository.create(
1345
- {
1346
- PaymentId: payment.PaymentId,
1347
- MethodTypeId: paymentPaidWithItem.MethodTypeId,
1348
- Currency: paymentPaidWithItem.Currency,
1349
- Amount: paymentPaidWithItem.Amount,
1350
- Status: paymentPaidWithItem.Status,
1351
- TransactionId: paymentPaidWithItem.TransactionId,
1352
- RefBank: paymentPaidWithItem.RefBank,
1353
- RefName: paymentPaidWithItem.RefName,
1354
- RefNo: paymentPaidWithItem.RefNo,
1355
- RefOther1: paymentPaidWithItem.RefOther1,
1356
- RefOther2: paymentPaidWithItem.RefOther2,
1357
- RefOther3: paymentPaidWithItem.RefOther3,
1358
- RefOther4: paymentPaidWithItem.RefOther4,
1359
- RefOther5: paymentPaidWithItem.RefOther5,
1360
- Remarks: paymentPaidWithItem.Remarks,
1361
- PaymentMediaId: paymentPaidWithItem.PaymentMediaId,
1362
- },
1363
- { transaction: dbTransaction },
1364
- );
1365
- }
1366
-
1367
- /*Registering the Journal Entries for the transaction*/
1368
- const transactionDate = new Date();
1369
-
1370
- for (const paymentPaidWith of paymentPaidWithItems) {
1371
- let paymentMethodType: PaymentMethodType;
1372
-
1373
- try {
1374
- paymentMethodType = await PaymentMethodType.initMethodType(
1375
- dbTransaction,
1376
- paymentPaidWith.MethodTypeId,
1377
- );
1378
- } catch (error) {
1379
- if (error instanceof RecordNotFoundError) {
1380
- throw new Error('Invalid Payment Method Type Id');
1381
- } else {
1382
- throw error;
1383
- }
1384
- }
1385
- const journalEntry = new JournalEntry(dbTransaction);
1386
-
1387
- journalEntry.init({
1388
- CompanyId: this.CompanyId,
1389
- Name: 'Collect-payments for ' + payment.PaymentId,
1390
- });
1391
-
1392
- const debitLT = await journalEntry.newLedgerTransaction(
1393
- TransactionTypeOptions.DEBIT,
1394
- );
1395
- debitLT.AccountNo = paymentMethodType.AccountNo;
1396
- debitLT.Currency = paymentPaidWith.Currency;
1397
- debitLT.DebitAmount = paymentPaidWith.Amount;
1398
- debitLT.Date = transactionDate;
1399
- debitLT.Description = 'Payment Received'; //customer.FullName;
1400
- debitLT.Name = customer.FullName;
1401
- debitLT.RelatedObjectId = receipt.RelatedObjectId;
1402
- debitLT.RelatedObjectType = payment.RelatedObjectType;
1403
- debitLT.RelatedPaymentId = payment.PaymentId;
1404
-
1405
- const creditLT = await journalEntry.newLedgerTransaction(
1406
- TransactionTypeOptions.CREDIT,
1407
- );
1408
-
1409
- if (ctAccountNo) {
1410
- creditLT.AccountNo = ctAccountNo;
1411
- } else {
1412
- const arAccount = await customer.getAccountReceivable();
1413
- creditLT.AccountNo = arAccount.AccountNo;
1414
- }
1415
- creditLT.Currency = paymentPaidWith.Currency;
1416
- creditLT.CreditAmount = paymentPaidWith.Amount;
1417
- creditLT.Date = transactionDate;
1418
- creditLT.Description = 'Payment Received'; //paymentMethodType.Name;
1419
- creditLT.Name = paymentMethodType.Name;
1420
- creditLT.RelatedObjectId = receipt.RelatedObjectId;
1421
- creditLT.RelatedObjectType = payment.RelatedObjectType;
1422
- creditLT.RelatedPaymentId = payment.PaymentId;
1423
-
1424
- await this.postJournal(dbTransaction, journalEntry, loginUser);
1425
- }
1426
-
1427
- /*todo: saving a record into the activity history table*/
1428
-
1429
- return payment;
1430
- } catch (error) {
1431
- throw error;
1432
- }
1433
- }
1434
-
1435
- /**
1436
- * Method to make payment to a customer.
1437
- *
1438
- * @param dbTransaction - The database transaction to be used
1439
- * @param loginUser - The user logging in and the user who collected the payment.
1440
- * @param payment - The payment object containing payment details
1441
- * @param customer - The customer who is receiving the payment.
1442
- * @param ctAccountNo - The account number of the customer's Account Payable account to transact, else the default customer account payable will be used.
1443
- *
1444
- * @returns {Payment} - Payment object representing the full details of the payment collection recorded
1445
- */
1446
- async makePayment(
1447
- dbTransaction: any,
1448
- loginUser: LoginUserBase,
1449
- payment: Payment,
1450
- customer: FinanceCustomerBase,
1451
- dtAccountNo?: string,
1452
- ): Promise<Payment> {
1453
- let paymentMethodType: PaymentMethodType;
1454
- try {
1455
- const paymentPaidWith = await payment.PaymentPaidWith;
1456
- if (paymentPaidWith.length < 1) {
1457
- throw new Error(
1458
- 'Atleast one payment paid with item is required to identify how the payment was made.',
1459
- );
1460
- }
1461
- paymentMethodType = await PaymentMethodType.initMethodType(
1462
- dbTransaction,
1463
- paymentPaidWith[0].MethodTypeId,
1464
- );
1465
-
1466
- const paymentItems = await payment.PaymentItems;
1467
- if (paymentItems.length < 1) {
1468
- throw new Error(
1469
- 'Atleast one payment item is required to identify what payment is being paid for',
1470
- );
1471
- }
1472
-
1473
- payment.PaymentId = cuid();
1474
- payment.PaymentType = PaymentType.PAYOUT;
1475
- payment.ReceivedBy = loginUser.ObjectId;
1476
- payment.IssuedBy = loginUser.ObjectId;
1477
-
1478
- await FinanceCompany._PaymentRepository.create(
1479
- {
1480
- PaymentId: payment.PaymentId,
1481
- PaymentType: payment.PaymentType,
1482
- PaymentDate: payment.PaymentDate,
1483
- Description: payment.Description,
1484
- Currency: payment.Currency,
1485
- ReceivedBy: payment.ReceivedBy,
1486
- IssuedBy: payment.IssuedBy,
1487
- Remarks: payment.Remarks,
1488
- RelatedObjectId: payment.RelatedObjectId,
1489
- RelatedObjectType: payment.RelatedObjectType,
1490
- Amount: payment.Amount,
1491
- Status: PaymentStatus.SUCCESSFUL,
1492
- PostedToAccSystemYN: 'N',
1493
- UpdatedAt: new Date(),
1494
- UpdatedBy: loginUser.ObjectId,
1495
- CreatedAt: new Date(),
1496
- CreatedBy: loginUser.ObjectId,
1497
- },
1498
- { transaction: dbTransaction },
1499
- );
1500
-
1501
- paymentItems.forEach(async (paymentItem) => {
1502
- await FinanceCompany._PaymentItemRepository.create(
1503
- {
1504
- PaymentId: payment.PaymentId,
1505
- PayForObjectId: paymentItem.PayForObjectId,
1506
- PayForObjectType: paymentItem.PayForObjectType,
1507
- Currency: paymentItem.Currency,
1508
- Amount: paymentItem.Amount,
1509
- Name: paymentItem.Name,
1510
- Description: paymentItem.Description,
1511
- },
1512
- { transaction: dbTransaction },
1513
- );
1514
-
1515
- await paymentItem.paid(dbTransaction);
1516
- });
1517
-
1518
- for (const paymentPaidWithItem of paymentPaidWith) {
1519
- await FinanceCompany._PaymentPaidWithRepository.create(
1520
- {
1521
- PaymentId: payment.PaymentId,
1522
- MethodTypeId: paymentPaidWithItem.MethodTypeId,
1523
- Currency: paymentPaidWithItem.Currency,
1524
- Amount: paymentPaidWithItem.Amount,
1525
- Status: paymentPaidWithItem.Status,
1526
- TransactionId: paymentPaidWithItem.TransactionId,
1527
- RefBank: paymentPaidWithItem.RefBank,
1528
- RefName: paymentPaidWithItem.RefName,
1529
- RefNo: paymentPaidWithItem.RefNo,
1530
- RefOther1: paymentPaidWithItem.RefOther1,
1531
- RefOther2: paymentPaidWithItem.RefOther2,
1532
- RefOther3: paymentPaidWithItem.RefOther3,
1533
- RefOther4: paymentPaidWithItem.RefOther4,
1534
- RefOther5: paymentPaidWithItem.RefOther5,
1535
- Remarks: paymentPaidWithItem.Remarks,
1536
- PaymentMediaId: paymentPaidWithItem.PaymentMediaId,
1537
- },
1538
- { transaction: dbTransaction },
1539
- );
1540
- }
1541
- const transactionDate = new Date();
1542
- for (const paymentPaidWithItem of paymentPaidWith) {
1543
- try {
1544
- paymentMethodType = await PaymentMethodType.initMethodType(
1545
- dbTransaction,
1546
- paymentPaidWithItem.MethodTypeId,
1547
- );
1548
-
1549
- const journalEntry = new JournalEntry(dbTransaction);
1550
- //Temporary fix to successfully save journal entry in PostJournal
1551
- journalEntry.init({
1552
- CompanyId: this.CompanyId,
1553
- Name: 'Make Payment for ' + payment.PaymentId,
1554
- });
1555
-
1556
- const creditLT = await journalEntry.newLedgerTransaction(
1557
- TransactionTypeOptions.CREDIT,
1558
- );
1559
- creditLT.AccountNo = paymentMethodType.AccountNo;
1560
- creditLT.Currency = paymentPaidWithItem.Currency;
1561
- creditLT.CreditAmount = paymentPaidWithItem.Amount;
1562
- creditLT.Date = transactionDate;
1563
- creditLT.Description = customer.FullName;
1564
- creditLT.Name = customer.FullName;
1565
- creditLT.RelatedObjectId = payment.RelatedObjectId;
1566
- creditLT.RelatedObjectType = payment.RelatedObjectType;
1567
-
1568
- const debitLT = await journalEntry.newLedgerTransaction(
1569
- TransactionTypeOptions.DEBIT,
1570
- );
1571
- if (dtAccountNo) {
1572
- debitLT.AccountNo = dtAccountNo;
1573
- } else {
1574
- const apAccount = await customer.getAccountPayable();
1575
- debitLT.AccountNo = apAccount.AccountNo;
1576
- }
1577
- debitLT.Currency = paymentPaidWithItem.Currency;
1578
- debitLT.DebitAmount = paymentPaidWithItem.Amount;
1579
- debitLT.Date = transactionDate;
1580
- debitLT.Description = paymentMethodType.Name;
1581
- debitLT.Name = paymentMethodType.Name;
1582
- debitLT.RelatedObjectId = payment.RelatedObjectId;
1583
- debitLT.RelatedObjectType = payment.RelatedObjectType;
1584
-
1585
- await this.postJournal(dbTransaction, journalEntry, loginUser);
1586
- } catch (error) {
1587
- if (error instanceof RecordNotFoundError) {
1588
- throw new Error('Invalid Payment Method Type Id');
1589
- } else {
1590
- throw error;
1591
- }
1592
- }
1593
- }
1594
- /*todo: saving a record into the activity history table*/
1595
-
1596
- return payment;
1597
- } catch (error) {
1598
- if (error instanceof RecordNotFoundError) {
1599
- throw new Error('Invalid PaymentMethodType id');
1600
- } else {
1601
- throw error;
1602
- }
1603
- }
1604
- }
1605
-
1606
- get PaymentMethods(): Promise<PaymentMethod[]> {
1607
- return new Promise((resolve, reject) => {
1608
- if (this.CompanyId !== 'New') {
1609
- FinanceCompany._PaymentMethodRepository
1610
- .findAll({
1611
- where: {
1612
- CompanyId: this.CompanyId,
1613
- },
1614
- transaction: this._DbTransaction,
1615
- })
1616
- .then((paymentMethod) => {
1617
- const paymentMethodObjects = paymentMethod.map(
1618
- (paymentMethodData) => {
1619
- return new Promise((resolve, reject) => {
1620
- FinanceCompany._PaymentMethodTypeRepository
1621
- .findAll({
1622
- where: {
1623
- MethodId: paymentMethodData.MethodId,
1624
- },
1625
- transaction: this._DbTransaction,
1626
- raw: true,
1627
- })
1628
- .then((paymentMethodTypes) => {
1629
- const paymentMethodObjects = {
1630
- ...paymentMethodData.get({ plain: true }),
1631
- Types: paymentMethodTypes,
1632
- };
1633
- resolve(paymentMethodObjects);
1634
- })
1635
- .catch((err) => {
1636
- reject(err);
1637
- });
1638
- }).then((paymentMethods) => paymentMethods);
1639
- },
1640
- );
1641
- return Promise.all(paymentMethodObjects);
1642
- })
1643
- .then((paymentMethodObjects) => {
1644
- this._PaymentMethods = paymentMethodObjects;
1645
- resolve(this._PaymentMethods);
1646
- })
1647
- .catch((err) => {
1648
- reject(err);
1649
- });
1650
- } else {
1651
- resolve(this._PaymentMethods);
1652
- }
1653
- });
1654
- }
1655
-
1656
- get TaxCodes(): Promise<Tax[]> {
1657
- return new Promise((resolve, reject) => {
1658
- if (this.CompanyId !== 'New') {
1659
- FinanceCompany._TaxRepository
1660
- .findAll({
1661
- where: {
1662
- CompanyId: this.CompanyId,
1663
- },
1664
- transaction: this._DbTransaction,
1665
- })
1666
- .then((taxes) => {
1667
- let taxList = [];
1668
- taxes.forEach((tax) => {
1669
- taxList.push(
1670
- new Tax({
1671
- TaxCode: tax.TaxCode,
1672
- TaxRate:
1673
- typeof tax.TaxRate === 'number'
1674
- ? tax.TaxRate
1675
- : parseFloat(tax.TaxRate),
1676
- Description: tax.Description,
1677
- CompanyId: tax.CompanyId,
1678
- CreatedAt: tax.CreatedAt,
1679
- CreatedById: tax.CreatedById,
1680
- UpdatedAt: tax.UpdatedAt,
1681
- UpdatedById: tax.UpdatedById,
1682
- }),
1683
- );
1684
- });
1685
- this._Taxes = taxList;
1686
- resolve(this._Taxes);
1687
- })
1688
- .catch((err) => {
1689
- reject(err);
1690
- });
1691
- } else {
1692
- resolve(this._Taxes);
1693
- }
1694
- });
1695
- }
1696
-
1697
- /**
1698
- * Method to load / reload the payment methods based on the configuration file
1699
- */
1700
- async LoadPaymentMethods(
1701
- companyId: string,
1702
- paymentMethods: any,
1703
- transaction?: any,
1704
- ): Promise<void> {
1705
- const paymentMethod = new PaymentMethod();
1706
- for (const method in paymentMethods) {
1707
- const paymentMethodData =
1708
- await FinanceCompany._PaymentMethodRepository.findOne({
1709
- where: {
1710
- MethodId: paymentMethods[method].id,
1711
- Name: paymentMethods[method].name,
1712
- },
1713
- transaction: transaction,
1714
- });
1715
-
1716
- if (!paymentMethodData) {
1717
- const newPaymentMethod =
1718
- await FinanceCompany._PaymentMethodRepository.create(
1719
- {
1720
- MethodId: paymentMethods[method].id,
1721
- Name: paymentMethods[method].name,
1722
- CompanyId: companyId,
1723
- },
1724
- {
1725
- transaction: transaction,
1726
- },
1727
- );
1728
-
1729
- this._PaymentMethods.push(newPaymentMethod);
1730
- }
1731
- this._PaymentMethods.push(paymentMethodData);
1732
- }
1733
-
1734
- this._PaymentMethods.forEach(async (item) => {
1735
- const p = item?.get({ plain: true });
1736
-
1737
- for (const method in paymentMethods) {
1738
- if (!p) {
1739
- continue;
1740
- }
1741
-
1742
- if (p.MethodId === paymentMethods[method]?.id) {
1743
- const paymentMethodTypeData =
1744
- await FinanceCompany._PaymentMethodTypeRepository.findOne({
1745
- where: {
1746
- MethodId: p.MethodId,
1747
- },
1748
- transaction: transaction,
1749
- });
1750
-
1751
- if (!paymentMethodTypeData) {
1752
- const configPaymentMethodTypes = paymentMethods[method]?.types;
1753
-
1754
- for (const methodType in configPaymentMethodTypes) {
1755
- // TODO: Create a seeder for payment method account
1756
- /*validate whether account data already exists*/
1757
- const accountData =
1758
- await FinanceCompany._AccountRepository.findOne({
1759
- where: {
1760
- AccountNo: configPaymentMethodTypes[methodType].accountNo,
1761
- },
1762
- transaction: transaction,
1763
- });
1764
-
1765
- /*generating account data if not exist */
1766
- if (!accountData) {
1767
- const accountPayload = {
1768
- CompanyId: companyId,
1769
- Name: configPaymentMethodTypes[methodType].name,
1770
- AccountType: 'PaymentMethod',
1771
- CreatedAt: new Date(),
1772
- CreatedById: 'System',
1773
- AccSystemRefId: 'REF',
1774
- PostedToAccSystemYN: 'N',
1775
- };
1776
-
1777
- try {
1778
- await FinanceCompany._AccountRepository.create(
1779
- {
1780
- AccountNo: configPaymentMethodTypes[methodType].accountNo,
1781
- ...accountPayload,
1782
- },
1783
- {
1784
- transaction: transaction,
1785
- },
1786
- );
1787
-
1788
- await FinanceCompany._AccountRepository.create(
1789
- {
1790
- AccountNo:
1791
- configPaymentMethodTypes[methodType]
1792
- .processingFeeAccountNo,
1793
- ...accountPayload,
1794
- },
1795
- {
1796
- transaction: transaction,
1797
- },
1798
- );
1799
- } catch (err) {
1800
- throw err;
1801
- }
1802
- }
1803
-
1804
- const paymentMethodTypePayload = {
1805
- MethodId: p.MethodId,
1806
- MethodTypeId: configPaymentMethodTypes[methodType].id,
1807
- Name: configPaymentMethodTypes[methodType].name,
1808
- AccountNo: configPaymentMethodTypes[methodType].accountNo,
1809
- ProcessingFeeRate:
1810
- configPaymentMethodTypes[methodType].processingFeeRate,
1811
- ProcessingFeeAccountNo:
1812
- configPaymentMethodTypes[methodType].processingFeeAccountNo,
1813
- };
1814
-
1815
- try {
1816
- await paymentMethod.newPaymentMethodType(
1817
- paymentMethodTypePayload,
1818
- transaction,
1819
- );
1820
- } catch (err) {}
1821
- }
1822
- }
1823
- }
1824
- }
1825
- });
1826
- }
1827
-
1828
- /**
1829
- * Method to load / reload the payment methods based on the configuration file
1830
- */
1831
- async LoadTaxCodes(
1832
- companyId: string,
1833
- companyTaxes: any,
1834
- transaction?: any,
1835
- ): Promise<void> {
1836
- for (const tax in companyTaxes) {
1837
- let tx = await FinanceCompany._TaxRepository.findOne({
1838
- where: {
1839
- TaxCode: companyTaxes[tax].taxCode,
1840
- },
1841
- transaction: transaction,
1842
- });
1843
-
1844
- if (!tx) {
1845
- const newTx = await FinanceCompany._TaxRepository.create(
1846
- {
1847
- TaxCode: companyTaxes[tax].taxCode,
1848
- TaxRate: companyTaxes[tax].taxRate,
1849
- Description: companyTaxes[tax].description,
1850
- CompanyId: companyId,
1851
- UpdatedAt: new Date(),
1852
- CreatedById: 'System',
1853
- CreatedAt: new Date(),
1854
- UpdatedById: 'System',
1855
- },
1856
- {
1857
- transaction: transaction,
1858
- },
1859
- );
1860
-
1861
- tx = newTx;
1862
- }
1863
- this._Taxes.push(new Tax(tx.get({ plain: true })));
1864
- }
1865
- }
1866
-
1867
- async collectPaymentForMultipleCustomers(
1868
- dbTransaction: any,
1869
- loginUser: LoginUserBase,
1870
- payment: Payment,
1871
- creditTransaction: {
1872
- AccountNo: string;
1873
- Currency: string;
1874
- Amount: number;
1875
- }[],
1876
- receiptNo?: string,
1877
- ): Promise<Payment> {
1878
- //Method to collect payment for multiple customer.
1879
- try {
1880
- //Part 1: Privilege Checking\
1881
- const systemCode = await ApplicationConfig.getComponentConfigValue(
1882
- 'system-code',
1883
- );
1884
- const isPrivileged = await loginUser.checkPrivileges(
1885
- systemCode,
1886
- 'Collect Payment For Multiple Customers',
1887
- );
1888
-
1889
- if (!isPrivileged) {
1890
- throw new Error('User is not authorized to perform this action');
1891
- }
1892
-
1893
- //Part 2: Validation
1894
- //Make sure that the payment has at least 1 payment item
1895
- const paymentItems = await payment.PaymentItems;
1896
- if (paymentItems.length < 1) {
1897
- throw new Error(
1898
- 'Atleast one payment item is required to identify what payment is being paid for.',
1899
- );
1900
- }
1901
-
1902
- //Make sure that the payment has at least 1 payment method
1903
- const paymentPaidWithItems = await payment.PaymentPaidWith;
1904
- if (paymentPaidWithItems.length < 1) {
1905
- throw new Error(
1906
- 'Atleast one payment paid with item is required to identify how the payment was made.',
1907
- );
1908
- }
1909
-
1910
- //Make sure the payment items length is equal to creditTransactions length records.
1911
- if (paymentItems.length !== creditTransaction.length) {
1912
- throw new Error(
1913
- 'Payment items length is not equal to creditTransaction length',
1914
- );
1915
- }
1916
-
1917
- //Make sure the payment items total Amount is equal to credit transactions total Amount.
1918
- let totalAmount = 0;
1919
- paymentItems.forEach((paymentItem) => {
1920
- totalAmount += paymentItem.Amount;
1921
- });
1922
-
1923
- const totalCreditTransactionAmount = creditTransaction.reduce(
1924
- (accumulator, currentValue) => {
1925
- return accumulator + currentValue.Amount;
1926
- },
1927
- 0,
1928
- );
1929
-
1930
- if (totalAmount !== totalCreditTransactionAmount) {
1931
- throw new Error(
1932
- 'Payment items total Amount is dnot equal to credit transactions total Amount',
1933
- );
1934
- }
1935
-
1936
- //Part 3:Generate Receipt (KIV)
1937
-
1938
- //Part 4: Saving Payment, Payment Items and Payment Paid with Details to the Database
1939
-
1940
- //Set below Payment attributes:
1941
- payment.PaymentId = cuid();
1942
- payment.PaymentType = PaymentType.PAYMENT_RECEIVED;
1943
- payment.ReceivedBy = loginUser.ObjectId;
1944
- payment.IssuedBy = loginUser.ObjectId;
1945
-
1946
- //Call Payment Repository create() method by passing:
1947
- await FinanceCompany._PaymentRepository.create(
1948
- {
1949
- PaymentId: payment.PaymentId,
1950
- PaymentType: payment.PaymentType,
1951
- PaymentDate: payment.PaymentDate,
1952
- Description: payment.Description,
1953
- Currency: payment.Currency,
1954
- Amount: payment.Amount,
1955
- Status: PaymentStatus.SUCCESSFUL,
1956
- PostedToAccSystemYN: 'N',
1957
- ReceivedBy: payment.ReceivedBy,
1958
- IssuedBy: payment.IssuedBy,
1959
- Remarks: payment.Remarks,
1960
- RelatedObjectId: payment.RelatedObjectId,
1961
- RelatedObjectType: payment.RelatedObjectType,
1962
- ReceiptDocNo: payment.ReceiptDocNo,
1963
- UpdatedAt: new Date(),
1964
- UpdatedBy: loginUser.ObjectId,
1965
- CreatedAt: new Date(),
1966
- CreatedBy: loginUser.ObjectId,
1967
- },
1968
- { transaction: dbTransaction },
1969
- );
1970
-
1971
- //Map Payment.PaymentItems and insert record by passing dbTransaction
1972
- paymentItems.forEach(async (paymentItem) => {
1973
- await FinanceCompany._PaymentItemRepository.create(
1974
- {
1975
- PaymentId: payment.PaymentId,
1976
- PayForObjectId: paymentItem.PayForObjectId,
1977
- PayForObjectType: paymentItem.PayForObjectType,
1978
- Currency: paymentItem.Currency,
1979
- Amount: paymentItem.Amount,
1980
- Name: paymentItem.Name,
1981
- Description: paymentItem.Description,
1982
- },
1983
- { transaction: dbTransaction },
1984
- );
1985
- });
1986
-
1987
- // Map Payment.PaymentPaidWith and insert record by passing dbTransaction.
1988
- paymentPaidWithItems.forEach(async (paymentPaidWithItem) => {
1989
- await FinanceCompany._PaymentPaidWithRepository.create(
1990
- {
1991
- PaymentId: payment.PaymentId,
1992
- MethodTypeId: paymentPaidWithItem.MethodTypeId,
1993
- Currency: paymentPaidWithItem.Currency,
1994
- Amount: paymentPaidWithItem.Amount,
1995
- Status: paymentPaidWithItem.Status,
1996
- TransactionId: paymentPaidWithItem.TransactionId,
1997
- RefBank: paymentPaidWithItem.RefBank,
1998
- RefName: paymentPaidWithItem.RefName,
1999
- RefNo: paymentPaidWithItem.RefNo,
2000
- RefOther1: paymentPaidWithItem.RefOther1,
2001
- RefOther2: paymentPaidWithItem.RefOther2,
2002
- RefOther3: paymentPaidWithItem.RefOther3,
2003
- RefOther4: paymentPaidWithItem.RefOther4,
2004
- RefOther5: paymentPaidWithItem.RefOther5,
2005
- Remarks: paymentPaidWithItem.Remarks,
2006
- PaymentMediaId: paymentPaidWithItem.PaymentMediaId,
2007
- },
2008
- { transaction: dbTransaction },
2009
- );
2010
- });
2011
-
2012
- //Part 5: Registering the Journal Entries for the transaction
2013
- //Initialise TransactionDate
2014
- const transactionDate = new Date();
2015
- //Initialise new JournalEntry
2016
- const journalEntry = new JournalEntry(dbTransaction);
2017
- journalEntry.init({
2018
- CompanyId: this.CompanyId,
2019
- Name: 'Collect-payments for ' + payment.PaymentId,
2020
- });
2021
-
2022
- // For each Payment.PaymentPaidWith:
2023
- for (const paymentPaidWithItem of paymentPaidWithItems) {
2024
- const paymentMethodType = await PaymentMethodType.initMethodType(
2025
- dbTransaction,
2026
- paymentPaidWithItem.MethodTypeId,
2027
- );
2028
-
2029
- //Initialise new Debit LedgerTransaction by calling JournalEntry.newLedgerTransaction() method and set below attributes:
2030
- const debitLT = await journalEntry.newLedgerTransaction(
2031
- TransactionTypeOptions.DEBIT,
2032
- );
2033
- debitLT.AccountNo = paymentMethodType.AccountNo;
2034
- debitLT.Currency = paymentPaidWithItem.Currency;
2035
- debitLT.DebitAmount = paymentPaidWithItem.Amount;
2036
- debitLT.Date = transactionDate;
2037
- debitLT.Description = 'Payment Received';
2038
- debitLT.RelatedPaymentId = payment.PaymentId;
2039
- }
2040
-
2041
- //For each creditTransactions, Initialise new Credit LedgerTransaction by calling JournalEntry.newLedgerTransaction() method
2042
- for (const ct of creditTransaction) {
2043
- const creditLT = await journalEntry.newLedgerTransaction(
2044
- TransactionTypeOptions.CREDIT,
2045
- );
2046
- creditLT.AccountNo = ct.AccountNo;
2047
- creditLT.Currency = ct.Currency;
2048
- creditLT.CreditAmount = ct.Amount;
2049
- creditLT.Date = transactionDate;
2050
- creditLT.Description = 'Payment Received';
2051
- creditLT.RelatedPaymentId = payment.PaymentId;
2052
- }
2053
-
2054
- // Call this.postJournal()
2055
- await this.postJournal(dbTransaction, journalEntry, loginUser);
2056
-
2057
- return payment;
2058
- } catch (error) {
2059
- throw error;
2060
- }
2061
- }
2062
- }
1
+ import axios from 'axios';
2
+ import * as cuid from 'cuid';
3
+ import {
4
+ HashTable,
5
+ LoginUserBase,
6
+ ObjectBase,
7
+ RecordNotFoundError,
8
+ } from '@tomei/general';
9
+ import Account from '../account/account';
10
+ import JournalEntry from '../journal-entry/journal-entry';
11
+ import FinanceCustomerBase from '../customer/customer';
12
+ import Document from '../document/document';
13
+ import { IAccountSystem } from '../interfaces';
14
+ import { FinanceCompanyRepository } from './finance-company.repository';
15
+ import { FinanceCustomerRepository } from '../customer/finance-customer.repository';
16
+ import { LedgerTransactionRepository } from '../ledger-transaction/ledger-transaction.repository';
17
+ import {
18
+ DocType,
19
+ PaymentStatus,
20
+ PaymentType,
21
+ TransactionTypeOptions,
22
+ } from '../enum';
23
+ import PaymentMethodType from '../payment-method-type/payment-method-type';
24
+ import { PaymentRepository } from '../payment/payment.repository';
25
+ import { PaymentItemRepository } from '../payment-item/payment-item.repository';
26
+ import Payment from '../payment/payment';
27
+ import { DocumentRepository } from '../document/document.repository';
28
+ import { DocumentItemRepository } from '../document/document-item.repository';
29
+ import { PaymentMethodRepository } from '../payment-method/payment-method.repository';
30
+ import { PaymentMethodTypeRepository } from '../payment-method-type/payment-method-type.repository';
31
+ import PaymentMethod from '../payment-method/payment-method';
32
+ import { AccountRepository } from '../account/account.repository';
33
+ import { PaymentPaidWithRepository } from '../payment-paid-with/payment-paid-with.repository';
34
+ import { MediasModel } from '@tomei/media';
35
+ import DocumentItem from '../document/document-item';
36
+ import { type } from '../helpers/typeof';
37
+ import { LoginUser } from '@tomei/sso';
38
+ import { ActionEnum, Activity } from '@tomei/activity-history';
39
+ import { ApplicationConfig } from '@tomei/config';
40
+ import { TaxRepository } from '../tax/tax.repository';
41
+ import { Tax } from '../tax/tax';
42
+
43
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
44
+ const getConfig = require('../config');
45
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
46
+ const config = getConfig();
47
+
48
+ export default class FinanceCompany extends ObjectBase {
49
+ private _CompanyId = 'New';
50
+ private _CompSystemCode = '';
51
+ private _CompSystemRefId = '';
52
+ private _AccSystemCode = '';
53
+ private static _htFinanceCompanyIds = new HashTable();
54
+ private static _htFinanceCompanies = new HashTable();
55
+ private static _financeCompanyRepository = new FinanceCompanyRepository();
56
+ private static _PaymentRepository = new PaymentRepository();
57
+ private static _PaymentItemRepository = new PaymentItemRepository();
58
+ private static _PaymentPaidWithRepository = new PaymentPaidWithRepository();
59
+ private static _PaymentMethodRepository = new PaymentMethodRepository();
60
+ private static _PaymentMethodTypeRepository =
61
+ new PaymentMethodTypeRepository();
62
+ private static _DocumentRepository = new DocumentRepository();
63
+ private static _DocumentItemRepository = new DocumentItemRepository();
64
+ private static _FinanceCustomerRepository = new FinanceCustomerRepository();
65
+ private static _LedgerTransactionRepository =
66
+ new LedgerTransactionRepository();
67
+
68
+ private static _AccountRepository = new AccountRepository();
69
+ private static _TaxRepository = new TaxRepository();
70
+
71
+ private _AccountingSystem: IAccountSystem;
72
+
73
+ private _DbTransaction: any;
74
+ private _PaymentMethods = [];
75
+ private _Taxes: Tax[] = [];
76
+
77
+ get CompSystemCode(): string {
78
+ return this._CompSystemCode;
79
+ }
80
+
81
+ private set CompSystemCode(code: string) {
82
+ this._CompSystemCode = code;
83
+ }
84
+
85
+ get CompSystemRefId() {
86
+ return this._CompSystemRefId;
87
+ }
88
+
89
+ set CompSystemRefId(id: string) {
90
+ this._CompSystemRefId = id;
91
+ }
92
+
93
+ get AccSystemCode() {
94
+ return this._AccSystemCode;
95
+ }
96
+
97
+ private set AccSystemCode(code: string) {
98
+ this._AccSystemCode = code;
99
+ }
100
+
101
+ get CompanyId() {
102
+ return this._CompanyId;
103
+ }
104
+
105
+ get ObjectId() {
106
+ return this._CompanyId;
107
+ }
108
+
109
+ private set ObjectId(id: string) {
110
+ this._CompanyId = id;
111
+ }
112
+
113
+ get ObjectName() {
114
+ return `${this.CompSystemCode}-${this.CompSystemRefId}-${this.AccSystemCode}`;
115
+ }
116
+
117
+ get TableName() {
118
+ return 'finance_Company';
119
+ }
120
+
121
+ get AccountingSystem(): IAccountSystem {
122
+ return this._AccountingSystem;
123
+ }
124
+
125
+ set AccountingSystem(system: IAccountSystem) {
126
+ this._AccountingSystem = system;
127
+ }
128
+
129
+ constructor(
130
+ compSystemCode: string,
131
+ compSystemRefId: string,
132
+ accSystemCode: string,
133
+ ) {
134
+ super();
135
+ this.CompSystemCode = compSystemCode;
136
+ this.CompSystemRefId = compSystemRefId;
137
+ this.AccSystemCode = accSystemCode;
138
+ }
139
+
140
+ static async getFinanceCompanyId(
141
+ compSystemCode: string,
142
+ compSystemRefId: string,
143
+ accSystemCode: string,
144
+ ): Promise<string> {
145
+ let sCompanyId = '';
146
+ /*Assemble the hashtable key*/
147
+ const sKey = `${compSystemCode}-${compSystemRefId}-${accSystemCode}`;
148
+ /*Check if the FinanceCompany has previously being loaded*/
149
+ if (!FinanceCompany._htFinanceCompanyIds.get(sKey)) {
150
+ /*Instantiate a new FinanceCompany*/
151
+ const financeCompany = new FinanceCompany(
152
+ compSystemCode,
153
+ compSystemRefId,
154
+ accSystemCode,
155
+ );
156
+
157
+ /*Retrieve the finance company from finance_Company table using compSystemCode,
158
+ * CompSystemRefId and accSystemCode */
159
+ const company = await FinanceCompany._financeCompanyRepository.findOne({
160
+ where: {
161
+ CompSystemCode: compSystemCode,
162
+ CompSystemRefId: compSystemRefId,
163
+ AccSystemCode: accSystemCode,
164
+ },
165
+ });
166
+
167
+ /*Retrieve and store the companyId from the result*/
168
+ financeCompany.ObjectId = company.CompanyId;
169
+ sCompanyId = financeCompany.ObjectId;
170
+
171
+ /*Add the details into the hashtable*/
172
+ FinanceCompany._htFinanceCompanyIds.add(sKey, financeCompany.ObjectId);
173
+ FinanceCompany._htFinanceCompanies.add(sCompanyId, financeCompany);
174
+ }
175
+
176
+ if (typeof FinanceCompany._htFinanceCompanyIds.get(sKey) === 'string') {
177
+ sCompanyId = FinanceCompany._htFinanceCompanyIds.get(sKey);
178
+ }
179
+
180
+ return sCompanyId;
181
+ }
182
+
183
+ static async getFinanceCompany(companyId: string): Promise<FinanceCompany> {
184
+ /*Check if the finance company is previously be loaded*/
185
+ if (!FinanceCompany._htFinanceCompanies.get(companyId)) {
186
+ /*Retrieve the finance company from finance_Company table using compSystemCode,
187
+ * CompSystemRefId and accSystemCode */
188
+ const company = await FinanceCompany._financeCompanyRepository.findOne({
189
+ where: { CompanyId: companyId },
190
+ });
191
+
192
+ if (!company) {
193
+ throw Error('No finance company found. Please create first.');
194
+ }
195
+
196
+ /*Using the result returned, instantiate a new FinanceCompany*/
197
+ const compSystemCode = company.CompSystemCode;
198
+ const compSystemRefId = company.CompSystemRefId;
199
+ const accSystemCode = company.AccSystemCode;
200
+
201
+ const financeCompany = new FinanceCompany(
202
+ compSystemCode,
203
+ compSystemRefId,
204
+ accSystemCode,
205
+ );
206
+
207
+ /*Retrieve and store the CompanyId from the result*/
208
+ financeCompany.ObjectId = company.CompanyId;
209
+ financeCompany._CompanyId = company.CompanyId;
210
+
211
+ /*Add the details into the hashtable*/
212
+ const sKey = `${compSystemCode}-${compSystemRefId}-${accSystemCode}`;
213
+ FinanceCompany._htFinanceCompanyIds.add(sKey, financeCompany.ObjectId);
214
+ FinanceCompany._htFinanceCompanies.add(
215
+ financeCompany.ObjectId,
216
+ financeCompany,
217
+ );
218
+ }
219
+ // tslint:disable-next-line:no-console
220
+ console.log('return from hash table');
221
+ return FinanceCompany._htFinanceCompanies.get(companyId);
222
+ }
223
+
224
+ static async createFinanceCompany(
225
+ dbTransaction: any,
226
+ loginUser: LoginUserBase,
227
+ companyId: string,
228
+ compSystemCode: string,
229
+ compSystemRefId: string,
230
+ accSystemCode: string,
231
+ ) {
232
+ /*Instantiate a new FinanceCompany*/
233
+ const financeCompany = new FinanceCompany(
234
+ compSystemCode,
235
+ compSystemRefId,
236
+ accSystemCode,
237
+ );
238
+
239
+ /*Validating if the finance company already exists in finance_Company*/
240
+ const company = await FinanceCompany._financeCompanyRepository.findOne({
241
+ where: {
242
+ CompSystemCode: compSystemCode,
243
+ CompSystemRefId: compSystemRefId,
244
+ AccSystemCode: accSystemCode,
245
+ },
246
+ });
247
+
248
+ if (company) {
249
+ throw Error(
250
+ 'There is already another Finance Company with the compSystemCode, CompSystemRefId and accSystemCode specified.',
251
+ );
252
+ }
253
+
254
+ /*Generating the companyId*/
255
+ financeCompany.ObjectId = companyId;
256
+
257
+ /*Save the FinanceCompany to the finance_Company table*/
258
+ await FinanceCompany._financeCompanyRepository.create(
259
+ {
260
+ CompanyId: financeCompany.CompanyId,
261
+ CompSystemCode: financeCompany.CompSystemCode,
262
+ CompSystemRefId: financeCompany.CompSystemRefId,
263
+ AccSystemCode: financeCompany.AccSystemCode,
264
+ },
265
+ {
266
+ transaction: dbTransaction,
267
+ },
268
+ );
269
+
270
+ /*Add the details to hashtable*/
271
+ const sKey = `${compSystemCode}-${compSystemRefId}-${accSystemCode}`;
272
+ FinanceCompany._htFinanceCompanyIds.add(sKey, financeCompany.ObjectId);
273
+ FinanceCompany._htFinanceCompanies.add(
274
+ financeCompany.ObjectId,
275
+ financeCompany,
276
+ );
277
+
278
+ // tslint:disable-next-line:no-console
279
+ console.log('return from hash table');
280
+ return FinanceCompany._htFinanceCompanies.get(companyId);
281
+ }
282
+
283
+ async createCustomer(
284
+ dbTransaction: any,
285
+ custSystemCode: string,
286
+ custSystemRefId: string,
287
+ customer: FinanceCustomerBase,
288
+ loginUser: LoginUser,
289
+ ) {
290
+ try {
291
+ if (!custSystemCode || !custSystemRefId) {
292
+ throw new Error(
293
+ 'CustSystemCode and CustomerRefId are required fields.',
294
+ );
295
+ }
296
+
297
+ const financeCustomerData =
298
+ await FinanceCompany._FinanceCustomerRepository.findOne({
299
+ where: {
300
+ CompanyId: this._CompanyId,
301
+ CustSystemCode: custSystemCode,
302
+ CustSystemRefId: custSystemRefId,
303
+ },
304
+ });
305
+
306
+ if (financeCustomerData) {
307
+ throw new Error('Customer already created previously.');
308
+ }
309
+
310
+ // Retrieve the type of accounting system, API Key, and API secret based on SysCode from the Config.ts
311
+ // const customerId = await this.AccountingSystem.createCustomer({
312
+ // customer,
313
+ // });
314
+ const customerId = 'REF';
315
+
316
+ customer.CompanyId = this._CompanyId;
317
+
318
+ const newCustomer = await customer.save(
319
+ customerId,
320
+ custSystemCode,
321
+ custSystemRefId,
322
+ dbTransaction,
323
+ );
324
+
325
+ const activity = new Activity();
326
+ activity.ActivityId = cuid();
327
+ activity.Action = ActionEnum.ADD;
328
+ activity.Description = 'Add Finance Customer';
329
+ activity.EntityType = 'FinanceCustomer';
330
+ activity.EntityId = newCustomer.CustomerId;
331
+ activity.EntityValueBefore = JSON.stringify({});
332
+ activity.EntityValueAfter = JSON.stringify(newCustomer);
333
+
334
+ await activity.create(loginUser, dbTransaction);
335
+
336
+ return customer;
337
+ } catch (error) {
338
+ throw error;
339
+ }
340
+ }
341
+
342
+ async postJournal(
343
+ dbTransaction: any,
344
+ journalEntry: JournalEntry,
345
+ loginUser: LoginUserBase,
346
+ ) {
347
+ const debitTransactions = await journalEntry.DebitTransactions;
348
+ const creditTransactions = await journalEntry.CreditTransactions;
349
+ try {
350
+ if (creditTransactions.length < 1 || debitTransactions?.length < 1) {
351
+ throw new Error(
352
+ 'There should be at least 1 debit ledger transaction and 1 credit ledger transaction in the journal entry',
353
+ );
354
+ }
355
+
356
+ const totalCreditAmount = creditTransactions.reduce(
357
+ (accumulator, currentValue) => accumulator + currentValue.CreditAmount,
358
+ 0,
359
+ );
360
+ const totalDebitAmount = debitTransactions.reduce(
361
+ (accumulator, currentValue) => accumulator + currentValue.DebitAmount,
362
+ 0,
363
+ );
364
+
365
+ if (totalCreditAmount !== totalDebitAmount) {
366
+ throw new Error(
367
+ 'Credit ledger transaction and debit ledger transaction should the same amount',
368
+ );
369
+ }
370
+
371
+ const newJournalEntry = await journalEntry.save(
372
+ loginUser.ObjectId,
373
+ dbTransaction,
374
+ );
375
+
376
+ for (const ledgerTransaction of debitTransactions) {
377
+ ledgerTransaction.TransactionId = cuid();
378
+ ledgerTransaction.JournalEntryId = newJournalEntry.JournalEntryId;
379
+
380
+ await ledgerTransaction.save(dbTransaction);
381
+ // const dt = await ledgerTransaction.newLedgerTransaction(
382
+ // TransactionTypeOptions.DEBIT,
383
+ // newJournalEntry.JournalEntryId,
384
+ // );
385
+ // await dt.save();
386
+ }
387
+
388
+ for (const ledgerTransaction of creditTransactions) {
389
+ ledgerTransaction.TransactionId = cuid();
390
+ ledgerTransaction.JournalEntryId = newJournalEntry.JournalEntryId;
391
+
392
+ await ledgerTransaction.save(dbTransaction);
393
+ // const ct = await ledgerTransaction.newLedgerTransaction(
394
+ // TransactionTypeOptions.CREDIT,
395
+ // newJournalEntry.JournalEntryId,
396
+ // );
397
+ // await ct.save();
398
+ }
399
+
400
+ // await this.AccountingSystem.postJournalEntry(newJournalEntry);
401
+
402
+ const payload = {
403
+ Action: 'Create',
404
+ Activity: 'Post Journal Entry',
405
+ Description: `Journal Entry (ID: ${newJournalEntry.JournalEntryId}) has been created`,
406
+ EntityType: 'JournalEntry',
407
+ EntityValueBefore: JSON.stringify({}),
408
+ EntityValueAfter: JSON.stringify(newJournalEntry),
409
+ PerformedById: loginUser.ObjectId,
410
+ PerformedAt: new Date(),
411
+ EntityId: newJournalEntry.JournalEntryId,
412
+ };
413
+
414
+ await axios.post(
415
+ `${process.env.COMMON_API_URL}/activity-histories`,
416
+ payload,
417
+ );
418
+ } catch (error) {
419
+ throw error;
420
+ }
421
+ }
422
+
423
+ async createAccount(
424
+ dbTransaction: any,
425
+ account: Account,
426
+ loginUser: LoginUserBase,
427
+ ) {
428
+ try {
429
+ if (!account.AccountType) {
430
+ throw new Error('AccountType is required.');
431
+ }
432
+
433
+ let createAccountPayload: any = {
434
+ Name: account.Name,
435
+ AcctNum: account.AccountNo,
436
+ AccountType: account.AccountType,
437
+ AccountSubType: account.AccountSubtype,
438
+ };
439
+
440
+ if (account.isParentAccountExists()) {
441
+ createAccountPayload = {
442
+ ...createAccountPayload,
443
+ CurrencyRef: 'MYR',
444
+ ParentRef: account.ParentAccountNo,
445
+ SubAccount: true,
446
+ };
447
+ }
448
+
449
+ console.log(
450
+ 'Finance Company Create Account: Before accSystemAccountId Create',
451
+ );
452
+
453
+ // const accSystemAccountId = await this.AccountingSystem.createAccount(
454
+ // createAccountPayload,
455
+ // );
456
+
457
+ const accSystemAccountId = 'REF';
458
+
459
+ console.log(
460
+ 'Finance Company Create Account: After accSystemAccountId Create',
461
+ );
462
+
463
+ console.log('Finance Company Create Account: Before new Account Create');
464
+ const newAccount = await account.save(
465
+ this.CompanyId,
466
+ accSystemAccountId,
467
+ loginUser.ObjectId,
468
+ dbTransaction,
469
+ );
470
+
471
+ console.log('Finance Company Create Account: After new Account Create');
472
+
473
+ const payload = {
474
+ Action: 'Create',
475
+ Activity: 'Account Created',
476
+ Description: `Account (ID: ${newAccount.AccountNo}) has been created`,
477
+ EntityType: 'Account',
478
+ EntityValueBefore: JSON.stringify({}),
479
+ EntityValueAfter: JSON.stringify(newAccount),
480
+ PerformedById: loginUser.ObjectId,
481
+ PerformedAt: new Date(),
482
+ EntityId: newAccount.AccountNo,
483
+ };
484
+
485
+ await axios.post(
486
+ `${process.env.COMMON_API_URL}/activity-histories`,
487
+ payload,
488
+ );
489
+
490
+ return account;
491
+ } catch (error) {
492
+ throw error;
493
+ }
494
+ }
495
+
496
+ /**
497
+ * Issue an invoice
498
+ *
499
+ * @param dbTransaction - The database transaction to be used
500
+ * @param loginUser - The user issuing the invoice
501
+ * @param invoice - The document containing the invoice details
502
+ * @param customer - The customer to be issued the invoice
503
+ * @param dtAccountNo - The account number of the Account Receivable (AR) account to debit. If not provided, will debit the customer's default AR account
504
+ *
505
+ * @returns {Document} - Document object representing the full details of the invoice issued
506
+ */
507
+ async issueInvoice(
508
+ /*todo: loginUser & customer is NOT supposed to be optional */
509
+ dbTransaction: any,
510
+ invoice: Document,
511
+ loginUser?: LoginUserBase,
512
+ customer?: FinanceCustomerBase,
513
+ dtAccountNo?: string,
514
+ ): Promise<Document> {
515
+ try {
516
+ /*Check if the invoice number already exists (should be unique)*/
517
+ const duplicateInvoice = await FinanceCompany._DocumentRepository.findOne(
518
+ {
519
+ where: {
520
+ DocNo: invoice.DocNo,
521
+ },
522
+ transaction: dbTransaction,
523
+ },
524
+ );
525
+
526
+ if (duplicateInvoice) {
527
+ throw new Error('Invoice number already exists');
528
+ }
529
+
530
+ const documentItems = await invoice.DocumentItems;
531
+
532
+ /*Check if the document has at least 1 document item*/
533
+ if (!documentItems.length) {
534
+ throw new Error('Document must have at least 1 document item');
535
+ }
536
+
537
+ /*Check if each document item has CtAccountNo provided*/
538
+ for (const invoiceItem of documentItems) {
539
+ if (!invoiceItem.CtAccountNo) {
540
+ throw new Error(
541
+ 'Each document item should have CtAccountNo provided',
542
+ );
543
+ }
544
+ }
545
+
546
+ /*Set up the document type*/
547
+ invoice.DocType = DocType.INVOICE;
548
+
549
+ /*Generating the invoice*/
550
+ let invoiceMedia: {
551
+ HTMLMedia: MediasModel;
552
+ PDFMedia: MediasModel;
553
+ };
554
+
555
+ if (invoice.UseAccSystemDocYN === 'Y') {
556
+ /*todo: Posting to accounting system to generate invoice*/
557
+ // await this.AccountingSystem.createInvoice(invoice);
558
+ } else {
559
+ /*todo: check config file to see which invoice template is to be used for specific project*/
560
+
561
+ /*Generating invoice based on template*/
562
+ invoiceMedia = await invoice.generateInvoice(
563
+ invoice.IssuedById,
564
+ customer,
565
+ dbTransaction,
566
+ );
567
+ }
568
+
569
+ /*Saving the document and document items to the database*/
570
+ await FinanceCompany._DocumentRepository.create(
571
+ {
572
+ DocNo: invoice.DocNo,
573
+ DocType: invoice.DocType,
574
+ DocDate: invoice.DocDate,
575
+ CompanyId: invoice.CompanyId,
576
+ Currency: invoice.Currency,
577
+ Amount: invoice.Amount,
578
+ Description: invoice.Description,
579
+ Status: invoice.Status,
580
+ IssuedById: invoice.IssuedById,
581
+ IssuedToId: invoice.IssuedToId,
582
+ IssuedToType: invoice.IssuedToType,
583
+ RelatedObjectId: invoice.RelatedObjectId,
584
+ RelatedObjectType: invoice.RelatedObjectType,
585
+ CreatedById: invoice.CreatedById,
586
+ CreatedAt: new Date(),
587
+ UpdatedById: invoice.UpdatedById,
588
+ UpdatedAt: new Date(),
589
+ DocPDFFileMediaId: invoiceMedia.PDFMedia.MediaId,
590
+ DocHTMLFileMediaId: invoiceMedia.HTMLMedia.MediaId,
591
+ AccSystemRefId: invoice.AccSystemRefId,
592
+ PostedToAccSystemYN: invoice.PostedToAccSystemYN,
593
+ PostedById: invoice.PostedById,
594
+ PostedDateTime: new Date(),
595
+ UseAccSystemDocYN: invoice.UseAccSystemDocYN,
596
+ },
597
+ {
598
+ transaction: dbTransaction,
599
+ },
600
+ );
601
+
602
+ for (const documentItem of documentItems) {
603
+ await FinanceCompany._DocumentItemRepository.create(
604
+ {
605
+ DocumentItemId: cuid(),
606
+ DocNo: invoice.DocNo,
607
+ Name: documentItem.Name,
608
+ NameBM: documentItem.NameBM,
609
+ Description: documentItem.Description,
610
+ ItemId: documentItem.ItemId,
611
+ ItemType: documentItem.ItemType,
612
+ ItemSKU: documentItem.ItemSKU,
613
+ ItemSerialNo: documentItem.ItemSerialNo,
614
+ Currency: documentItem.Currency,
615
+ UnitPrice: documentItem.UnitPrice,
616
+ Quantity: documentItem.Quantity,
617
+ QuantityUOM: documentItem.QuantityUOM,
618
+ Amount: documentItem.Amount,
619
+ TaxCode: documentItem.TaxCode,
620
+ TaxAmount: documentItem.TaxAmount,
621
+ TaxRate: documentItem.TaxRate,
622
+ TaxInclusiveYN: documentItem.TaxInclusiveYN,
623
+ DtAccountNo: documentItem.DtAccountNo
624
+ ? documentItem.DtAccountNo
625
+ : null,
626
+ CtAccountNo: documentItem.CtAccountNo
627
+ ? documentItem.CtAccountNo
628
+ : null,
629
+ },
630
+ {
631
+ transaction: dbTransaction,
632
+ },
633
+ );
634
+ }
635
+
636
+ const transactionDate = new Date();
637
+ const htCreditAccountAmount = new HashTable();
638
+ const htCreditAccountCurrency = new HashTable();
639
+ const htCreditAccountPurpose = new HashTable();
640
+
641
+ documentItems.forEach((invoiceItem) => {
642
+ if (!htCreditAccountAmount.exists(invoiceItem.CtAccountNo)) {
643
+ //add the credit account to the hash table
644
+ htCreditAccountAmount.add(
645
+ invoiceItem.CtAccountNo,
646
+ invoiceItem.Amount,
647
+ );
648
+
649
+ htCreditAccountCurrency.add(
650
+ invoiceItem.CtAccountNo,
651
+ invoiceItem.Currency,
652
+ );
653
+
654
+ htCreditAccountPurpose.add(invoiceItem.CtAccountNo, invoiceItem.Name);
655
+ } else {
656
+ //update the credit account amount
657
+ const d = htCreditAccountAmount.get(invoiceItem.CtAccountNo);
658
+ htCreditAccountAmount.add(
659
+ invoiceItem.CtAccountNo,
660
+ d + invoiceItem.Amount,
661
+ );
662
+ }
663
+ });
664
+
665
+ const savedItems = htCreditAccountAmount.list();
666
+
667
+ for (const item of savedItems) {
668
+ const journalEntry = new JournalEntry(dbTransaction);
669
+ //Temporary fix to successfully save journal entry in PostJournal
670
+ journalEntry.init({
671
+ CompanyId: this.CompanyId,
672
+ Name: 'Issue Invoice ' + invoice.DocNo,
673
+ });
674
+ // const account = await Account.initAccount(dbTransaction, item.value[0]);
675
+ const creditAmount = item.value[1];
676
+ const currency = htCreditAccountCurrency.get(item.value[0]);
677
+ const purpose = htCreditAccountPurpose.get(item.value[0]);
678
+
679
+ const dt = await journalEntry.newLedgerTransaction(
680
+ TransactionTypeOptions.DEBIT,
681
+ );
682
+
683
+ if (dtAccountNo) {
684
+ /*Transacting using AR account provided*/
685
+ dt.AccountNo = dtAccountNo;
686
+ } else {
687
+ /*Transacting based on default customer AR account*/
688
+ const arAccount = await customer.getAccountReceivable();
689
+ dt.AccountNo = arAccount.AccountNo;
690
+ }
691
+
692
+ dt.Currency = currency ? currency : 'MYR';
693
+ dt.DebitAmount = creditAmount ? creditAmount : 0.0;
694
+ dt.Date = transactionDate;
695
+ dt.Description = `${purpose}`;
696
+ dt.Name = `${purpose}`;
697
+ dt.RelatedDocNo = invoice.DocNo;
698
+ dt.RelatedObjectId = invoice.RelatedObjectId;
699
+ dt.RelatedObjectType = invoice.RelatedObjectType;
700
+
701
+ const ct = await journalEntry.newLedgerTransaction(
702
+ TransactionTypeOptions.CREDIT,
703
+ );
704
+ ct.AccountNo = item.value[0];
705
+ ct.Currency = currency ? currency : 'MYR';
706
+ ct.CreditAmount = creditAmount ? creditAmount : 0.0;
707
+ ct.Date = transactionDate;
708
+ ct.Description = customer.FullName;
709
+ ct.Name = customer.FullName;
710
+ ct.RelatedDocNo = invoice.DocNo;
711
+ ct.RelatedObjectId = invoice.RelatedObjectId;
712
+ ct.RelatedObjectType = invoice.RelatedObjectType;
713
+
714
+ await this.postJournal(dbTransaction, journalEntry, loginUser);
715
+ }
716
+
717
+ return invoice;
718
+ } catch (err) {
719
+ // tslint:disable-next-line:no-console
720
+ console.log('Issue invoice err: ', err);
721
+ throw err;
722
+ }
723
+ }
724
+
725
+ /**
726
+ * Issue a debit note
727
+ *
728
+ * @param dbTransaction - The database transaction to be used
729
+ * @param loginUser - The user issuing the invoice
730
+ * @param invoice - The document containing the invoice details
731
+ * @param customer - The customer to be issued the invoice
732
+ * @param dtAccountNo - The account number of the Account Receivable (AR) account to debit. If not provided, will debit the customer's default AR account
733
+ *
734
+ * @returns {Document} - Document object representing the full details of the invoice issued
735
+ */
736
+ async issueDebitNote(
737
+ dbTransaction: any,
738
+ loginUser: LoginUserBase,
739
+ invoice: Document,
740
+ customer: FinanceCustomerBase,
741
+ dtAccountNo?: string,
742
+ ): Promise<Document> {
743
+ try {
744
+ /*Check if the invoice number already exists (should be unique)*/
745
+ const duplicateInvoice = await FinanceCompany._DocumentRepository.findOne(
746
+ {
747
+ where: {
748
+ DocNo: invoice.DocNo,
749
+ },
750
+ transaction: dbTransaction,
751
+ },
752
+ );
753
+
754
+ if (duplicateInvoice) {
755
+ throw new Error('Invoice number already exists');
756
+ }
757
+
758
+ const documentItems = await invoice.DocumentItems;
759
+
760
+ /*Check if the document has at least 1 document item*/
761
+ if (!documentItems.length) {
762
+ throw new Error('Document must have at least 1 document item');
763
+ }
764
+
765
+ /*Check if each document item has CtAccountNo provided*/
766
+ for (const invoiceItem of documentItems) {
767
+ if (!invoiceItem.CtAccountNo) {
768
+ throw new Error(
769
+ 'Each document item should have CtAccountNo provided',
770
+ );
771
+ }
772
+ }
773
+
774
+ /*Set up the document type*/
775
+ invoice.DocType = DocType.DEBIT_NOTE;
776
+ // invoice.DocNo = cuid();
777
+
778
+ /*Saving the document and document items to the database*/
779
+ await FinanceCompany._DocumentRepository.create(
780
+ {
781
+ DocNo: invoice.DocNo,
782
+ DocType: invoice.DocType,
783
+ DocDate: invoice.DocDate,
784
+ CompanyId: invoice.CompanyId,
785
+ Currency: invoice.Currency,
786
+ Amount: invoice.Amount,
787
+ Description: invoice.Description,
788
+ Status: invoice.Status,
789
+ IssuedById: loginUser.ObjectId,
790
+ IssuedToId: customer.ObjectId,
791
+ IssuedToType: invoice.IssuedToType,
792
+ RelatedObjectId: invoice.RelatedObjectId,
793
+ RelatedObjectType: invoice.RelatedObjectType,
794
+ CreatedById: loginUser.ObjectId,
795
+ CreatedAt: new Date(),
796
+ UpdatedById: loginUser.ObjectId,
797
+ UpdatedAt: new Date(),
798
+ DocPDFFileMediaId: invoice.DocPDFFileMediaId,
799
+ DocHTMLFileMediaId: invoice.DocHTMLFileMediaId,
800
+ AccSystemRefId: invoice.AccSystemRefId,
801
+ PostedToAccSystemYN: invoice.PostedToAccSystemYN,
802
+ PostedById: invoice.PostedById,
803
+ PostedDateTime: new Date(),
804
+ UseAccSystemDocYN: invoice.UseAccSystemDocYN,
805
+ },
806
+ {
807
+ transaction: dbTransaction,
808
+ },
809
+ );
810
+
811
+ documentItems.forEach(async (documentItem) => {
812
+ await FinanceCompany._DocumentItemRepository.create(
813
+ {
814
+ DocumentItemId: cuid(),
815
+ DocNo: documentItem.DocNo,
816
+ Name: documentItem.Name,
817
+ NameBM: documentItem.NameBM,
818
+ Description: documentItem.Description,
819
+ ItemId: documentItem.ItemId,
820
+ ItemType: documentItem.ItemType,
821
+ ItemSKU: documentItem.ItemSKU,
822
+ ItemSerialNo: documentItem.ItemSerialNo,
823
+ Currency: documentItem.Currency,
824
+ UnitPrice: documentItem.UnitPrice,
825
+ Quantity: documentItem.Quantity,
826
+ QuantityUOM: documentItem.QuantityUOM,
827
+ Amount: documentItem.Amount,
828
+ TaxCode: documentItem.TaxCode,
829
+ TaxAmount: documentItem.TaxAmount,
830
+ TaxRate: documentItem.TaxRate,
831
+ TaxInclusiveYN: documentItem.TaxInclusiveYN,
832
+ DtAccountNo: documentItem.DtAccountNo,
833
+ CtAccountNo: documentItem.CtAccountNo,
834
+ },
835
+ {
836
+ transaction: dbTransaction,
837
+ },
838
+ );
839
+ });
840
+
841
+ /*Generating the invoice*/
842
+ if (invoice.UseAccSystemDocYN === 'Y') {
843
+ /*todo: Posting to accounting system to generate invoice*/
844
+ // await this.AccountingSystem.createInvoice(invoice);
845
+ } else {
846
+ /*todo: check config file to see which invoice template is to be used for specific project*/
847
+
848
+ /*Generating invoice based on template*/
849
+ invoice.generateInvoice(loginUser.IDNo, customer);
850
+ }
851
+
852
+ const transactionDate = new Date();
853
+ const htCreditAccountAmount = new HashTable();
854
+ const htCreditAccountCurrency = new HashTable();
855
+ const htCreditAccountPurpose = new HashTable();
856
+
857
+ documentItems.forEach((invoiceItem) => {
858
+ if (!htCreditAccountAmount.exists(invoiceItem.CtAccountNo)) {
859
+ //add the credit account to the hash table
860
+ htCreditAccountAmount.add(
861
+ invoiceItem.CtAccountNo,
862
+ invoiceItem.Amount,
863
+ );
864
+
865
+ htCreditAccountCurrency.add(
866
+ invoiceItem.CtAccountNo,
867
+ invoiceItem.Currency,
868
+ );
869
+
870
+ htCreditAccountPurpose.add(invoiceItem.CtAccountNo, invoiceItem.Name);
871
+ } else {
872
+ //update the credit account amount
873
+ const d = htCreditAccountAmount.get(invoiceItem.CtAccountNo);
874
+ htCreditAccountAmount.add(
875
+ invoiceItem.CtAccountNo,
876
+ d + invoiceItem.Amount,
877
+ );
878
+ }
879
+ });
880
+
881
+ const savedItems = htCreditAccountAmount.list();
882
+
883
+ for (const item of savedItems) {
884
+ const journalEntry = new JournalEntry(dbTransaction);
885
+ //Temporary fix to successfully save journal entry in PostJournal
886
+ journalEntry.init({
887
+ CompanyId: this.CompanyId,
888
+ Name: 'issue Invoice ' + invoice.DocNo,
889
+ });
890
+ // const account = await Account.initAccount(dbTransaction, item.value[0]);
891
+ const creditAmount = item.value[1];
892
+ const currency = htCreditAccountCurrency.get(item.value[0]);
893
+ const purpose = htCreditAccountPurpose.get(item.value[0]);
894
+
895
+ const dt = await journalEntry.newLedgerTransaction(
896
+ TransactionTypeOptions.DEBIT,
897
+ );
898
+
899
+ if (dtAccountNo) {
900
+ /*Transacting using AR account provided*/
901
+ dt.AccountNo = dtAccountNo;
902
+ } else {
903
+ /*Transacting based on default customer AR account*/
904
+ const arAccount = await customer.getAccountReceivable();
905
+ dt.AccountNo = arAccount.AccountNo;
906
+ }
907
+
908
+ dt.Currency = currency ? currency : 'MYR';
909
+ dt.DebitAmount = creditAmount ? creditAmount : 0.0;
910
+ dt.Date = transactionDate;
911
+ dt.Description = `${purpose}`;
912
+ dt.Name = `${purpose}`;
913
+ dt.RelatedDocNo = invoice.DocNo;
914
+ dt.RelatedObjectId = invoice.RelatedObjectId;
915
+ dt.RelatedObjectType = invoice.RelatedObjectType;
916
+
917
+ const ct = await journalEntry.newLedgerTransaction(
918
+ TransactionTypeOptions.CREDIT,
919
+ );
920
+ ct.AccountNo = item.value[0];
921
+ ct.Currency = currency ? currency : 'MYR';
922
+ ct.CreditAmount = creditAmount ? creditAmount : 0.0;
923
+ ct.Date = transactionDate;
924
+ ct.Description = customer.FullName;
925
+ ct.Name = customer.FullName;
926
+ ct.RelatedDocNo = invoice.DocNo;
927
+ ct.RelatedObjectId = invoice.RelatedObjectId;
928
+ ct.RelatedObjectType = invoice.RelatedObjectType;
929
+
930
+ await this.postJournal(dbTransaction, journalEntry, loginUser);
931
+ }
932
+
933
+ return invoice;
934
+ } catch (err) {
935
+ // tslint:disable-next-line:no-console
936
+ console.log('Issue debit note err: ', err);
937
+ throw err;
938
+ }
939
+ }
940
+
941
+ /**
942
+ * Issue a credit note
943
+ *
944
+ * @param dbTransaction - The database transaction to be used
945
+ * @param loginUser - The user issuing the credit note
946
+ * @param creditNote - The document containing the credit note details
947
+ * @param customer - The customer to be issued the credit note
948
+ * @param ctAccountNo - The account number of the Account Payable (AP) account to debit. If not provided, will debit the customer's default AR account
949
+ *
950
+ * @returns {Document} - Document object representing the full details of the invoice issued
951
+ */
952
+ async issueCreditNote(
953
+ dbTransaction: any,
954
+ loginUser: LoginUserBase,
955
+ creditNote: Document,
956
+ customer: FinanceCustomerBase,
957
+ ctAccountNo?: string,
958
+ ): Promise<Document> {
959
+ try {
960
+ /*Check if the invoice number already exists (should be unique)*/
961
+ const duplicateCreditNote =
962
+ await FinanceCompany._DocumentRepository.findOne({
963
+ where: {
964
+ DocNo: creditNote.DocNo,
965
+ },
966
+ transaction: dbTransaction,
967
+ });
968
+
969
+ if (duplicateCreditNote) {
970
+ throw new Error('Invoice number already exists');
971
+ }
972
+
973
+ const documentItems = await creditNote.DocumentItems;
974
+
975
+ /*Check if the document has at least 1 document item*/
976
+ if (!documentItems.length) {
977
+ throw new Error('Document must have at least 1 document item');
978
+ }
979
+
980
+ /*Check if each document item has CtAccountNo provided*/
981
+ for (const invoiceItem of documentItems) {
982
+ if (!invoiceItem.CtAccountNo) {
983
+ throw new Error(
984
+ 'Each document item should have CtAccountNo provided',
985
+ );
986
+ }
987
+ }
988
+
989
+ /*Set up the document type*/
990
+ creditNote.DocType = DocType.DEBIT_NOTE;
991
+
992
+ /*Saving the document and document items to the database*/
993
+ await FinanceCompany._DocumentRepository.create(
994
+ {
995
+ DocNo: creditNote.DocNo,
996
+ DocType: creditNote.DocType,
997
+ DocDate: creditNote.DocDate,
998
+ CompanyId: creditNote.CompanyId,
999
+ Currency: creditNote.Currency,
1000
+ Amount: creditNote.Amount,
1001
+ Description: creditNote.Description,
1002
+ Status: creditNote.Status,
1003
+ IssuedById: loginUser.ObjectId,
1004
+ IssuedToId: customer.ObjectId,
1005
+ IssuedToType: creditNote.IssuedToType,
1006
+ RelatedObjectId: creditNote.RelatedObjectId,
1007
+ RelatedObjectType: creditNote.RelatedObjectType,
1008
+ CreatedById: loginUser.ObjectId,
1009
+ CreatedAt: new Date(),
1010
+ UpdatedById: loginUser.ObjectId,
1011
+ UpdatedAt: new Date(),
1012
+ DocPDFFileMediaId: creditNote.DocPDFFileMediaId,
1013
+ DocHTMLFileMediaId: creditNote.DocHTMLFileMediaId,
1014
+ AccSystemRefId: creditNote.AccSystemRefId,
1015
+ PostedToAccSystemYN: creditNote.PostedToAccSystemYN,
1016
+ PostedById: creditNote.PostedById,
1017
+ PostedDateTime: new Date(),
1018
+ UseAccSystemDocYN: creditNote.UseAccSystemDocYN,
1019
+ },
1020
+ {
1021
+ transaction: dbTransaction,
1022
+ },
1023
+ );
1024
+
1025
+ documentItems.forEach(async (documentItem) => {
1026
+ await FinanceCompany._DocumentItemRepository.create(
1027
+ {
1028
+ DocumentItemId: documentItem.DocumentItemId,
1029
+ DocNo: documentItem.DocNo,
1030
+ Name: documentItem.Name,
1031
+ NameBM: documentItem.NameBM,
1032
+ Description: documentItem.Description,
1033
+ ItemId: documentItem.ItemId,
1034
+ ItemType: documentItem.ItemType,
1035
+ ItemSKU: documentItem.ItemSKU,
1036
+ ItemSerialNo: documentItem.ItemSerialNo,
1037
+ Currency: documentItem.Currency,
1038
+ UnitPrice: documentItem.UnitPrice,
1039
+ Quantity: documentItem.Quantity,
1040
+ QuantityUOM: documentItem.QuantityUOM,
1041
+ Amount: documentItem.Amount,
1042
+ TaxCode: documentItem.TaxCode,
1043
+ TaxAmount: documentItem.TaxAmount,
1044
+ TaxRate: documentItem.TaxRate,
1045
+ TaxInclusiveYN: documentItem.TaxInclusiveYN,
1046
+ DtAccountNo: documentItem.DtAccountNo,
1047
+ CtAccountNo: documentItem.CtAccountNo,
1048
+ },
1049
+ {
1050
+ transaction: dbTransaction,
1051
+ },
1052
+ );
1053
+ });
1054
+
1055
+ /*Generating the credit note*/
1056
+ if (creditNote.UseAccSystemDocYN === 'Y') {
1057
+ /*todo: Posting to accounting system to generate creditNote*/
1058
+ // await this.AccountingSystem.createCreditNote(creditNote);
1059
+ } else {
1060
+ /*todo: check config file to see which invoice template is to be used for specific project*/
1061
+
1062
+ /*Generating credit note based on template*/
1063
+ creditNote.generateCreditNote(loginUser.IDNo, customer);
1064
+ }
1065
+
1066
+ const journalEntry = new JournalEntry(dbTransaction);
1067
+ //Temporary fix to successfully save journal entry in PostJournal
1068
+ journalEntry.init({
1069
+ CompanyId: this.CompanyId,
1070
+ Name: 'Issue Debit Note ' + creditNote.DocNo,
1071
+ });
1072
+
1073
+ const transactionDate = new Date();
1074
+
1075
+ const creditTransaction = await journalEntry.newLedgerTransaction(
1076
+ TransactionTypeOptions.CREDIT,
1077
+ );
1078
+
1079
+ if (ctAccountNo) {
1080
+ /*Transacting using AR account provided*/
1081
+ creditTransaction.AccountNo = ctAccountNo;
1082
+ } else {
1083
+ /*Transacting based on default customer AR account*/
1084
+ creditTransaction.AccountNo = customer.CustSystemCode + '-AP';
1085
+ }
1086
+
1087
+ creditTransaction.Currency = creditNote.Currency;
1088
+ creditTransaction.CreditAmount = creditNote.Amount;
1089
+ creditTransaction.Date = transactionDate;
1090
+ creditTransaction.Description = creditNote.DocNo;
1091
+ creditTransaction.Name = creditNote.DocNo;
1092
+ creditTransaction.RelatedDocNo = creditNote.DocNo;
1093
+ creditTransaction.RelatedObjectId = creditNote.RelatedObjectId;
1094
+ creditTransaction.RelatedObjectType = creditNote.RelatedObjectType;
1095
+
1096
+ for (const invoiceItem of documentItems) {
1097
+ const itemLedger = await journalEntry.newLedgerTransaction(
1098
+ TransactionTypeOptions.DEBIT,
1099
+ );
1100
+ itemLedger.AccountNo = invoiceItem.CtAccountNo;
1101
+ itemLedger.Currency = invoiceItem.Currency;
1102
+ itemLedger.DebitAmount = invoiceItem.Amount;
1103
+ itemLedger.Date = transactionDate;
1104
+ itemLedger.Description = invoiceItem.Description;
1105
+ itemLedger.Name = invoiceItem.Name;
1106
+ itemLedger.RelatedDocNo = creditNote.DocNo;
1107
+ itemLedger.RelatedObjectId = creditNote.RelatedObjectId;
1108
+ itemLedger.RelatedObjectType = creditNote.RelatedObjectType;
1109
+ }
1110
+
1111
+ this.postJournal(dbTransaction, journalEntry, loginUser);
1112
+
1113
+ const payload = {
1114
+ Action: 'Create',
1115
+ Activity: 'Issuing a Credit Note Transaction',
1116
+ Description: `Credit Transaction (ID: ${creditTransaction.TransactionId}) has been created`,
1117
+ EntityType: 'CreditTransaction',
1118
+ EntityValueBefore: JSON.stringify({}),
1119
+ EntityValueAfter: JSON.stringify(creditTransaction),
1120
+ PerformedById: loginUser.ObjectId,
1121
+ PerformedAt: transactionDate,
1122
+ EntityId: creditTransaction.TransactionId,
1123
+ };
1124
+
1125
+ await axios.post(
1126
+ `${process.env.COMMON_API_URL}/activity-histories`,
1127
+ payload,
1128
+ );
1129
+
1130
+ return creditNote;
1131
+ } catch (err) {
1132
+ // tslint:disable-next-line:no-console
1133
+ console.log('Issue credit note err: ', err);
1134
+ throw err;
1135
+ }
1136
+ }
1137
+
1138
+ /**
1139
+ * Register a payment collected
1140
+ *
1141
+ * @param dbTransaction - The database transaction to be used
1142
+ * @param loginUser - The user collecting the payment
1143
+ * @param payment - The payment object containing payment details
1144
+ * @param customer - The customer making the payment
1145
+ * @param ctAccountNo - The account number of the customer's Account Receivable account to transact, else the default customer account payable receivable will be used
1146
+ * @param receiptNo - The document receipt number
1147
+ *
1148
+ * @returns {Payment} - Payment object representing the full detals of the payment collection recorded
1149
+ */
1150
+ async collectPayment(
1151
+ dbTransaction: any,
1152
+ loginUser: LoginUserBase,
1153
+ payment: Payment,
1154
+ customer: FinanceCustomerBase,
1155
+ ctAccountNo?: string,
1156
+ receiptNo?: string,
1157
+ ): Promise<Payment> {
1158
+ try {
1159
+ /*validation 1: Make sure that the payment has at least 1 payment item*/
1160
+ const paymentItems = await payment.PaymentItems;
1161
+ if (paymentItems.length < 1) {
1162
+ throw new Error(
1163
+ 'Atleast one payment item is required to identify what payment is being paid for.',
1164
+ );
1165
+ }
1166
+
1167
+ /*validation 2: Make sure that the payment has at least 1 payment method*/
1168
+ const paymentPaidWithItems = await payment.PaymentPaidWith;
1169
+ if (paymentPaidWithItems.length < 1) {
1170
+ throw new Error(
1171
+ 'Atleast one payment paid with item is required to identify how the payment was made.',
1172
+ );
1173
+ }
1174
+
1175
+ /*Generating the receipt*/
1176
+ const receiptDocuments: any =
1177
+ await FinanceCompany._DocumentRepository.findAll({
1178
+ where: {
1179
+ DocType: DocType.RECEIPT,
1180
+ CompanyId: this.ObjectId,
1181
+ },
1182
+ });
1183
+
1184
+ const receipt = new Document(dbTransaction);
1185
+
1186
+ if (receiptNo) {
1187
+ receipt.DocNo = receiptNo;
1188
+ } else {
1189
+ receipt.DocNo = `EZC-RCT-${receiptDocuments.length + 1}`;
1190
+ }
1191
+ receipt.DocType = DocType.RECEIPT;
1192
+ receipt.DocDate = new Date();
1193
+ receipt.CompanyId = this.ObjectId;
1194
+ receipt.Currency = payment.Currency;
1195
+ receipt.Description = 'Payment Received';
1196
+ receipt.IssuedById = loginUser.ObjectId;
1197
+ receipt.IssuedToId = customer.CustomerId;
1198
+ receipt.IssuedToType = type(customer);
1199
+ receipt.RelatedObjectId = payment.RelatedObjectId;
1200
+ receipt.RelatedObjectType = payment.RelatedObjectType;
1201
+ receipt.UseAccSystemDocYN = 'N';
1202
+ receipt.CreatedById = loginUser.ObjectId;
1203
+ receipt.UpdatedById = loginUser.ObjectId;
1204
+
1205
+ for (const paymentItem of paymentItems) {
1206
+ const receiptItem = new DocumentItem(dbTransaction, receipt);
1207
+ receiptItem.Name = `Payment for ${paymentItem.PayForObjectType} No. ${paymentItem.PayForObjectId}`;
1208
+ receiptItem.NameBM = `Bayaran untuk ${paymentItem.PayForObjectType} No. ${paymentItem.PayForObjectId}`;
1209
+ receiptItem.Description = '-';
1210
+ receiptItem.Currency = paymentItem.Currency;
1211
+ receiptItem.UnitPrice = paymentItem.Amount;
1212
+ receiptItem.Quantity = 1;
1213
+ receiptItem.Amount = receiptItem.UnitPrice * receiptItem.Quantity;
1214
+ receiptItem.ItemId = receipt.DocNo;
1215
+ receiptItem.ItemType = type(payment);
1216
+ receiptItem.CtAccountNo = ctAccountNo;
1217
+ await receipt.newDocumentItem(receiptItem);
1218
+ }
1219
+
1220
+ const receiptMedia = await receipt.generateReceipt(
1221
+ receipt.IssuedById,
1222
+ customer,
1223
+ dbTransaction,
1224
+ );
1225
+
1226
+ /*Saving the receipt document and document items to the database*/
1227
+ await FinanceCompany._DocumentRepository.create(
1228
+ {
1229
+ DocNo: receipt.DocNo,
1230
+ DocType: receipt.DocType,
1231
+ DocDate: receipt.DocDate,
1232
+ CompanyId: receipt.CompanyId,
1233
+ Currency: receipt.Currency,
1234
+ Amount: receipt.Amount,
1235
+ Description: receipt.Description,
1236
+ Status: receipt.Status,
1237
+ IssuedById: receipt.IssuedById,
1238
+ IssuedToId: receipt.IssuedToId,
1239
+ IssuedToType: receipt.IssuedToType,
1240
+ RelatedObjectId: receipt.RelatedObjectId,
1241
+ RelatedObjectType: receipt.RelatedObjectType,
1242
+ CreatedById: receipt.CreatedById,
1243
+ CreatedAt: new Date(),
1244
+ UpdatedById: receipt.UpdatedById,
1245
+ UpdatedAt: new Date(),
1246
+ DocPDFFileMediaId: receiptMedia.PDFMedia.MediaId,
1247
+ DocHTMLFileMediaId: receiptMedia.HTMLMedia.MediaId,
1248
+ AccSystemRefId: receipt.AccSystemRefId,
1249
+ PostedToAccSystemYN: receipt.PostedToAccSystemYN,
1250
+ PostedById: receipt.PostedById,
1251
+ PostedDateTime: new Date(),
1252
+ UseAccSystemDocYN: receipt.UseAccSystemDocYN,
1253
+ },
1254
+ {
1255
+ transaction: dbTransaction,
1256
+ },
1257
+ );
1258
+
1259
+ const receiptItems = await receipt.DocumentItems;
1260
+
1261
+ for (const receiptItem of receiptItems) {
1262
+ await FinanceCompany._DocumentItemRepository.create(
1263
+ {
1264
+ DocumentItemId: cuid(),
1265
+ DocNo: receipt.DocNo,
1266
+ Name: receiptItem.Name,
1267
+ NameBM: receiptItem.NameBM,
1268
+ Description: receiptItem.Description,
1269
+ ItemId: receiptItem.ItemId,
1270
+ ItemType: receiptItem.ItemType,
1271
+ ItemSKU: receiptItem.ItemSKU,
1272
+ ItemSerialNo: receiptItem.ItemSerialNo,
1273
+ Currency: receiptItem.Currency,
1274
+ UnitPrice: receiptItem.UnitPrice,
1275
+ Quantity: receiptItem.Quantity,
1276
+ QuantityUOM: receiptItem.QuantityUOM,
1277
+ Amount: receiptItem.Amount,
1278
+ TaxCode: receiptItem.TaxCode,
1279
+ TaxAmount: receiptItem.TaxAmount,
1280
+ TaxRate: receiptItem.TaxRate,
1281
+ TaxInclusiveYN: receiptItem.TaxInclusiveYN,
1282
+ DtAccountNo: receiptItem.DtAccountNo
1283
+ ? receiptItem.DtAccountNo
1284
+ : null,
1285
+ CtAccountNo: receiptItem.CtAccountNo
1286
+ ? receiptItem.CtAccountNo
1287
+ : null,
1288
+ },
1289
+ {
1290
+ transaction: dbTransaction,
1291
+ },
1292
+ );
1293
+ }
1294
+
1295
+ /*Saving payment, payment items, and payment paid with details to the database*/
1296
+ payment.PaymentId = cuid();
1297
+ payment.PaymentType = PaymentType.PAYMENT_RECEIVED;
1298
+ payment.ReceivedBy = loginUser.ObjectId;
1299
+ payment.IssuedBy = loginUser.ObjectId;
1300
+ payment.ReceiptDocNo = receipt.DocNo;
1301
+
1302
+ await FinanceCompany._PaymentRepository.create(
1303
+ {
1304
+ PaymentId: payment.PaymentId,
1305
+ PaymentType: payment.PaymentType,
1306
+ PaymentDate: payment.PaymentDate,
1307
+ Description: payment.Description,
1308
+ Currency: payment.Currency,
1309
+ Amount: payment.Amount,
1310
+ Status: PaymentStatus.SUCCESSFUL,
1311
+ PostedToAccSystemYN: 'N',
1312
+ ReceivedBy: payment.ReceivedBy,
1313
+ IssuedBy: payment.IssuedBy,
1314
+ Remarks: payment.Remarks,
1315
+ RelatedObjectId: payment.RelatedObjectId,
1316
+ RelatedObjectType: payment.RelatedObjectType,
1317
+ ReceiptDocNo: payment.ReceiptDocNo,
1318
+ UpdatedAt: new Date(),
1319
+ UpdatedBy: loginUser.ObjectId,
1320
+ CreatedAt: new Date(),
1321
+ CreatedBy: loginUser.ObjectId,
1322
+ },
1323
+ { transaction: dbTransaction },
1324
+ );
1325
+
1326
+ for (const paymentItem of paymentItems) {
1327
+ await FinanceCompany._PaymentItemRepository.create(
1328
+ {
1329
+ PaymentId: payment.PaymentId,
1330
+ PayForObjectId: paymentItem.PayForObjectId,
1331
+ PayForObjectType: paymentItem.PayForObjectType,
1332
+ Currency: paymentItem.Currency,
1333
+ Amount: paymentItem.Amount,
1334
+ Name: paymentItem.Name,
1335
+ Description: paymentItem.Description,
1336
+ },
1337
+ { transaction: dbTransaction },
1338
+ );
1339
+
1340
+ await paymentItem.paid(dbTransaction);
1341
+ }
1342
+
1343
+ for (const paymentPaidWithItem of paymentPaidWithItems) {
1344
+ await FinanceCompany._PaymentPaidWithRepository.create(
1345
+ {
1346
+ PaymentId: payment.PaymentId,
1347
+ MethodTypeId: paymentPaidWithItem.MethodTypeId,
1348
+ Currency: paymentPaidWithItem.Currency,
1349
+ Amount: paymentPaidWithItem.Amount,
1350
+ Status: paymentPaidWithItem.Status,
1351
+ TransactionId: paymentPaidWithItem.TransactionId,
1352
+ RefBank: paymentPaidWithItem.RefBank,
1353
+ RefName: paymentPaidWithItem.RefName,
1354
+ RefNo: paymentPaidWithItem.RefNo,
1355
+ RefOther1: paymentPaidWithItem.RefOther1,
1356
+ RefOther2: paymentPaidWithItem.RefOther2,
1357
+ RefOther3: paymentPaidWithItem.RefOther3,
1358
+ RefOther4: paymentPaidWithItem.RefOther4,
1359
+ RefOther5: paymentPaidWithItem.RefOther5,
1360
+ Remarks: paymentPaidWithItem.Remarks,
1361
+ PaymentMediaId: paymentPaidWithItem.PaymentMediaId,
1362
+ },
1363
+ { transaction: dbTransaction },
1364
+ );
1365
+ }
1366
+
1367
+ /*Registering the Journal Entries for the transaction*/
1368
+ const transactionDate = new Date();
1369
+
1370
+ for (const paymentPaidWith of paymentPaidWithItems) {
1371
+ let paymentMethodType: PaymentMethodType;
1372
+
1373
+ try {
1374
+ paymentMethodType = await PaymentMethodType.initMethodType(
1375
+ dbTransaction,
1376
+ paymentPaidWith.MethodTypeId,
1377
+ );
1378
+ } catch (error) {
1379
+ if (error instanceof RecordNotFoundError) {
1380
+ throw new Error('Invalid Payment Method Type Id');
1381
+ } else {
1382
+ throw error;
1383
+ }
1384
+ }
1385
+ const journalEntry = new JournalEntry(dbTransaction);
1386
+
1387
+ journalEntry.init({
1388
+ CompanyId: this.CompanyId,
1389
+ Name: 'Collect-payments for ' + payment.PaymentId,
1390
+ });
1391
+
1392
+ const debitLT = await journalEntry.newLedgerTransaction(
1393
+ TransactionTypeOptions.DEBIT,
1394
+ );
1395
+ debitLT.AccountNo = paymentMethodType.AccountNo;
1396
+ debitLT.Currency = paymentPaidWith.Currency;
1397
+ debitLT.DebitAmount = paymentPaidWith.Amount;
1398
+ debitLT.Date = transactionDate;
1399
+ debitLT.Description = 'Payment Received'; //customer.FullName;
1400
+ debitLT.Name = customer.FullName;
1401
+ debitLT.RelatedObjectId = receipt.RelatedObjectId;
1402
+ debitLT.RelatedObjectType = payment.RelatedObjectType;
1403
+ debitLT.RelatedPaymentId = payment.PaymentId;
1404
+
1405
+ const creditLT = await journalEntry.newLedgerTransaction(
1406
+ TransactionTypeOptions.CREDIT,
1407
+ );
1408
+
1409
+ if (ctAccountNo) {
1410
+ creditLT.AccountNo = ctAccountNo;
1411
+ } else {
1412
+ const arAccount = await customer.getAccountReceivable();
1413
+ creditLT.AccountNo = arAccount.AccountNo;
1414
+ }
1415
+ creditLT.Currency = paymentPaidWith.Currency;
1416
+ creditLT.CreditAmount = paymentPaidWith.Amount;
1417
+ creditLT.Date = transactionDate;
1418
+ creditLT.Description = 'Payment Received'; //paymentMethodType.Name;
1419
+ creditLT.Name = paymentMethodType.Name;
1420
+ creditLT.RelatedObjectId = receipt.RelatedObjectId;
1421
+ creditLT.RelatedObjectType = payment.RelatedObjectType;
1422
+ creditLT.RelatedPaymentId = payment.PaymentId;
1423
+
1424
+ await this.postJournal(dbTransaction, journalEntry, loginUser);
1425
+ }
1426
+
1427
+ /*todo: saving a record into the activity history table*/
1428
+
1429
+ return payment;
1430
+ } catch (error) {
1431
+ throw error;
1432
+ }
1433
+ }
1434
+
1435
+ /**
1436
+ * Method to make payment to a customer.
1437
+ *
1438
+ * @param dbTransaction - The database transaction to be used
1439
+ * @param loginUser - The user logging in and the user who collected the payment.
1440
+ * @param payment - The payment object containing payment details
1441
+ * @param customer - The customer who is receiving the payment.
1442
+ * @param ctAccountNo - The account number of the customer's Account Payable account to transact, else the default customer account payable will be used.
1443
+ *
1444
+ * @returns {Payment} - Payment object representing the full details of the payment collection recorded
1445
+ */
1446
+ async makePayment(
1447
+ dbTransaction: any,
1448
+ loginUser: LoginUserBase,
1449
+ payment: Payment,
1450
+ customer: FinanceCustomerBase,
1451
+ dtAccountNo?: string,
1452
+ ): Promise<Payment> {
1453
+ let paymentMethodType: PaymentMethodType;
1454
+ try {
1455
+ const paymentPaidWith = await payment.PaymentPaidWith;
1456
+ if (paymentPaidWith.length < 1) {
1457
+ throw new Error(
1458
+ 'Atleast one payment paid with item is required to identify how the payment was made.',
1459
+ );
1460
+ }
1461
+ paymentMethodType = await PaymentMethodType.initMethodType(
1462
+ dbTransaction,
1463
+ paymentPaidWith[0].MethodTypeId,
1464
+ );
1465
+
1466
+ const paymentItems = await payment.PaymentItems;
1467
+ if (paymentItems.length < 1) {
1468
+ throw new Error(
1469
+ 'Atleast one payment item is required to identify what payment is being paid for',
1470
+ );
1471
+ }
1472
+
1473
+ payment.PaymentId = cuid();
1474
+ payment.PaymentType = PaymentType.PAYOUT;
1475
+ payment.ReceivedBy = loginUser.ObjectId;
1476
+ payment.IssuedBy = loginUser.ObjectId;
1477
+
1478
+ await FinanceCompany._PaymentRepository.create(
1479
+ {
1480
+ PaymentId: payment.PaymentId,
1481
+ PaymentType: payment.PaymentType,
1482
+ PaymentDate: payment.PaymentDate,
1483
+ Description: payment.Description,
1484
+ Currency: payment.Currency,
1485
+ ReceivedBy: payment.ReceivedBy,
1486
+ IssuedBy: payment.IssuedBy,
1487
+ Remarks: payment.Remarks,
1488
+ RelatedObjectId: payment.RelatedObjectId,
1489
+ RelatedObjectType: payment.RelatedObjectType,
1490
+ Amount: payment.Amount,
1491
+ Status: PaymentStatus.SUCCESSFUL,
1492
+ PostedToAccSystemYN: 'N',
1493
+ UpdatedAt: new Date(),
1494
+ UpdatedBy: loginUser.ObjectId,
1495
+ CreatedAt: new Date(),
1496
+ CreatedBy: loginUser.ObjectId,
1497
+ },
1498
+ { transaction: dbTransaction },
1499
+ );
1500
+
1501
+ paymentItems.forEach(async (paymentItem) => {
1502
+ await FinanceCompany._PaymentItemRepository.create(
1503
+ {
1504
+ PaymentId: payment.PaymentId,
1505
+ PayForObjectId: paymentItem.PayForObjectId,
1506
+ PayForObjectType: paymentItem.PayForObjectType,
1507
+ Currency: paymentItem.Currency,
1508
+ Amount: paymentItem.Amount,
1509
+ Name: paymentItem.Name,
1510
+ Description: paymentItem.Description,
1511
+ },
1512
+ { transaction: dbTransaction },
1513
+ );
1514
+
1515
+ await paymentItem.paid(dbTransaction);
1516
+ });
1517
+
1518
+ for (const paymentPaidWithItem of paymentPaidWith) {
1519
+ await FinanceCompany._PaymentPaidWithRepository.create(
1520
+ {
1521
+ PaymentId: payment.PaymentId,
1522
+ MethodTypeId: paymentPaidWithItem.MethodTypeId,
1523
+ Currency: paymentPaidWithItem.Currency,
1524
+ Amount: paymentPaidWithItem.Amount,
1525
+ Status: paymentPaidWithItem.Status,
1526
+ TransactionId: paymentPaidWithItem.TransactionId,
1527
+ RefBank: paymentPaidWithItem.RefBank,
1528
+ RefName: paymentPaidWithItem.RefName,
1529
+ RefNo: paymentPaidWithItem.RefNo,
1530
+ RefOther1: paymentPaidWithItem.RefOther1,
1531
+ RefOther2: paymentPaidWithItem.RefOther2,
1532
+ RefOther3: paymentPaidWithItem.RefOther3,
1533
+ RefOther4: paymentPaidWithItem.RefOther4,
1534
+ RefOther5: paymentPaidWithItem.RefOther5,
1535
+ Remarks: paymentPaidWithItem.Remarks,
1536
+ PaymentMediaId: paymentPaidWithItem.PaymentMediaId,
1537
+ },
1538
+ { transaction: dbTransaction },
1539
+ );
1540
+ }
1541
+ const transactionDate = new Date();
1542
+ for (const paymentPaidWithItem of paymentPaidWith) {
1543
+ try {
1544
+ paymentMethodType = await PaymentMethodType.initMethodType(
1545
+ dbTransaction,
1546
+ paymentPaidWithItem.MethodTypeId,
1547
+ );
1548
+
1549
+ const journalEntry = new JournalEntry(dbTransaction);
1550
+ //Temporary fix to successfully save journal entry in PostJournal
1551
+ journalEntry.init({
1552
+ CompanyId: this.CompanyId,
1553
+ Name: 'Make Payment for ' + payment.PaymentId,
1554
+ });
1555
+
1556
+ const creditLT = await journalEntry.newLedgerTransaction(
1557
+ TransactionTypeOptions.CREDIT,
1558
+ );
1559
+ creditLT.AccountNo = paymentMethodType.AccountNo;
1560
+ creditLT.Currency = paymentPaidWithItem.Currency;
1561
+ creditLT.CreditAmount = paymentPaidWithItem.Amount;
1562
+ creditLT.Date = transactionDate;
1563
+ creditLT.Description = customer.FullName;
1564
+ creditLT.Name = customer.FullName;
1565
+ creditLT.RelatedObjectId = payment.RelatedObjectId;
1566
+ creditLT.RelatedObjectType = payment.RelatedObjectType;
1567
+
1568
+ const debitLT = await journalEntry.newLedgerTransaction(
1569
+ TransactionTypeOptions.DEBIT,
1570
+ );
1571
+ if (dtAccountNo) {
1572
+ debitLT.AccountNo = dtAccountNo;
1573
+ } else {
1574
+ const apAccount = await customer.getAccountPayable();
1575
+ debitLT.AccountNo = apAccount.AccountNo;
1576
+ }
1577
+ debitLT.Currency = paymentPaidWithItem.Currency;
1578
+ debitLT.DebitAmount = paymentPaidWithItem.Amount;
1579
+ debitLT.Date = transactionDate;
1580
+ debitLT.Description = paymentMethodType.Name;
1581
+ debitLT.Name = paymentMethodType.Name;
1582
+ debitLT.RelatedObjectId = payment.RelatedObjectId;
1583
+ debitLT.RelatedObjectType = payment.RelatedObjectType;
1584
+
1585
+ await this.postJournal(dbTransaction, journalEntry, loginUser);
1586
+ } catch (error) {
1587
+ if (error instanceof RecordNotFoundError) {
1588
+ throw new Error('Invalid Payment Method Type Id');
1589
+ } else {
1590
+ throw error;
1591
+ }
1592
+ }
1593
+ }
1594
+ /*todo: saving a record into the activity history table*/
1595
+
1596
+ return payment;
1597
+ } catch (error) {
1598
+ if (error instanceof RecordNotFoundError) {
1599
+ throw new Error('Invalid PaymentMethodType id');
1600
+ } else {
1601
+ throw error;
1602
+ }
1603
+ }
1604
+ }
1605
+
1606
+ get PaymentMethods(): Promise<PaymentMethod[]> {
1607
+ return new Promise((resolve, reject) => {
1608
+ if (this.CompanyId !== 'New') {
1609
+ FinanceCompany._PaymentMethodRepository
1610
+ .findAll({
1611
+ where: {
1612
+ CompanyId: this.CompanyId,
1613
+ },
1614
+ transaction: this._DbTransaction,
1615
+ })
1616
+ .then((paymentMethod) => {
1617
+ const paymentMethodObjects = paymentMethod.map(
1618
+ (paymentMethodData) => {
1619
+ return new Promise((resolve, reject) => {
1620
+ FinanceCompany._PaymentMethodTypeRepository
1621
+ .findAll({
1622
+ where: {
1623
+ MethodId: paymentMethodData.MethodId,
1624
+ },
1625
+ transaction: this._DbTransaction,
1626
+ raw: true,
1627
+ })
1628
+ .then((paymentMethodTypes) => {
1629
+ const paymentMethodObjects = {
1630
+ ...paymentMethodData.get({ plain: true }),
1631
+ Types: paymentMethodTypes,
1632
+ };
1633
+ resolve(paymentMethodObjects);
1634
+ })
1635
+ .catch((err) => {
1636
+ reject(err);
1637
+ });
1638
+ }).then((paymentMethods) => paymentMethods);
1639
+ },
1640
+ );
1641
+ return Promise.all(paymentMethodObjects);
1642
+ })
1643
+ .then((paymentMethodObjects) => {
1644
+ this._PaymentMethods = paymentMethodObjects;
1645
+ resolve(this._PaymentMethods);
1646
+ })
1647
+ .catch((err) => {
1648
+ reject(err);
1649
+ });
1650
+ } else {
1651
+ resolve(this._PaymentMethods);
1652
+ }
1653
+ });
1654
+ }
1655
+
1656
+ get TaxCodes(): Promise<Tax[]> {
1657
+ return new Promise((resolve, reject) => {
1658
+ if (this.CompanyId !== 'New') {
1659
+ FinanceCompany._TaxRepository
1660
+ .findAll({
1661
+ where: {
1662
+ CompanyId: this.CompanyId,
1663
+ },
1664
+ transaction: this._DbTransaction,
1665
+ })
1666
+ .then((taxes) => {
1667
+ let taxList = [];
1668
+ taxes.forEach((tax) => {
1669
+ taxList.push(
1670
+ new Tax({
1671
+ TaxCode: tax.TaxCode,
1672
+ TaxRate:
1673
+ typeof tax.TaxRate === 'number'
1674
+ ? tax.TaxRate
1675
+ : parseFloat(tax.TaxRate),
1676
+ Description: tax.Description,
1677
+ CompanyId: tax.CompanyId,
1678
+ CreatedAt: tax.CreatedAt,
1679
+ CreatedById: tax.CreatedById,
1680
+ UpdatedAt: tax.UpdatedAt,
1681
+ UpdatedById: tax.UpdatedById,
1682
+ }),
1683
+ );
1684
+ });
1685
+ this._Taxes = taxList;
1686
+ resolve(this._Taxes);
1687
+ })
1688
+ .catch((err) => {
1689
+ reject(err);
1690
+ });
1691
+ } else {
1692
+ resolve(this._Taxes);
1693
+ }
1694
+ });
1695
+ }
1696
+
1697
+ /**
1698
+ * Method to load / reload the payment methods based on the configuration file
1699
+ */
1700
+ async LoadPaymentMethods(
1701
+ companyId: string,
1702
+ paymentMethods: any,
1703
+ transaction?: any,
1704
+ ): Promise<void> {
1705
+ const paymentMethod = new PaymentMethod();
1706
+ for (const method in paymentMethods) {
1707
+ const paymentMethodData =
1708
+ await FinanceCompany._PaymentMethodRepository.findOne({
1709
+ where: {
1710
+ MethodId: paymentMethods[method].id,
1711
+ Name: paymentMethods[method].name,
1712
+ },
1713
+ transaction: transaction,
1714
+ });
1715
+
1716
+ if (!paymentMethodData) {
1717
+ const newPaymentMethod =
1718
+ await FinanceCompany._PaymentMethodRepository.create(
1719
+ {
1720
+ MethodId: paymentMethods[method].id,
1721
+ Name: paymentMethods[method].name,
1722
+ CompanyId: companyId,
1723
+ },
1724
+ {
1725
+ transaction: transaction,
1726
+ },
1727
+ );
1728
+
1729
+ this._PaymentMethods.push(newPaymentMethod);
1730
+ }
1731
+ this._PaymentMethods.push(paymentMethodData);
1732
+ }
1733
+
1734
+ this._PaymentMethods.forEach(async (item) => {
1735
+ const p = item?.get({ plain: true });
1736
+
1737
+ for (const method in paymentMethods) {
1738
+ if (!p) {
1739
+ continue;
1740
+ }
1741
+
1742
+ if (p.MethodId === paymentMethods[method]?.id) {
1743
+ const paymentMethodTypeData =
1744
+ await FinanceCompany._PaymentMethodTypeRepository.findOne({
1745
+ where: {
1746
+ MethodId: p.MethodId,
1747
+ },
1748
+ transaction: transaction,
1749
+ });
1750
+
1751
+ if (!paymentMethodTypeData) {
1752
+ const configPaymentMethodTypes = paymentMethods[method]?.types;
1753
+
1754
+ for (const methodType in configPaymentMethodTypes) {
1755
+ // TODO: Create a seeder for payment method account
1756
+ /*validate whether account data already exists*/
1757
+ const accountData =
1758
+ await FinanceCompany._AccountRepository.findOne({
1759
+ where: {
1760
+ AccountNo: configPaymentMethodTypes[methodType].accountNo,
1761
+ },
1762
+ transaction: transaction,
1763
+ });
1764
+
1765
+ /*generating account data if not exist */
1766
+ if (!accountData) {
1767
+ const accountPayload = {
1768
+ CompanyId: companyId,
1769
+ Name: configPaymentMethodTypes[methodType].name,
1770
+ AccountType: 'PaymentMethod',
1771
+ CreatedAt: new Date(),
1772
+ CreatedById: 'System',
1773
+ AccSystemRefId: 'REF',
1774
+ PostedToAccSystemYN: 'N',
1775
+ };
1776
+
1777
+ try {
1778
+ await FinanceCompany._AccountRepository.create(
1779
+ {
1780
+ AccountNo: configPaymentMethodTypes[methodType].accountNo,
1781
+ ...accountPayload,
1782
+ },
1783
+ {
1784
+ transaction: transaction,
1785
+ },
1786
+ );
1787
+
1788
+ await FinanceCompany._AccountRepository.create(
1789
+ {
1790
+ AccountNo:
1791
+ configPaymentMethodTypes[methodType]
1792
+ .processingFeeAccountNo,
1793
+ ...accountPayload,
1794
+ },
1795
+ {
1796
+ transaction: transaction,
1797
+ },
1798
+ );
1799
+ } catch (err) {
1800
+ throw err;
1801
+ }
1802
+ }
1803
+
1804
+ const paymentMethodTypePayload = {
1805
+ MethodId: p.MethodId,
1806
+ MethodTypeId: configPaymentMethodTypes[methodType].id,
1807
+ Name: configPaymentMethodTypes[methodType].name,
1808
+ AccountNo: configPaymentMethodTypes[methodType].accountNo,
1809
+ ProcessingFeeRate:
1810
+ configPaymentMethodTypes[methodType].processingFeeRate,
1811
+ ProcessingFeeAccountNo:
1812
+ configPaymentMethodTypes[methodType].processingFeeAccountNo,
1813
+ };
1814
+
1815
+ try {
1816
+ await paymentMethod.newPaymentMethodType(
1817
+ paymentMethodTypePayload,
1818
+ transaction,
1819
+ );
1820
+ } catch (err) {}
1821
+ }
1822
+ }
1823
+ }
1824
+ }
1825
+ });
1826
+ }
1827
+
1828
+ /**
1829
+ * Method to load / reload the payment methods based on the configuration file
1830
+ */
1831
+ async LoadTaxCodes(
1832
+ companyId: string,
1833
+ companyTaxes: any,
1834
+ transaction?: any,
1835
+ ): Promise<void> {
1836
+ for (const tax in companyTaxes) {
1837
+ let tx = await FinanceCompany._TaxRepository.findOne({
1838
+ where: {
1839
+ TaxCode: companyTaxes[tax].taxCode,
1840
+ },
1841
+ transaction: transaction,
1842
+ });
1843
+
1844
+ if (!tx) {
1845
+ const newTx = await FinanceCompany._TaxRepository.create(
1846
+ {
1847
+ TaxCode: companyTaxes[tax].taxCode,
1848
+ TaxRate: companyTaxes[tax].taxRate,
1849
+ Description: companyTaxes[tax].description,
1850
+ CompanyId: companyId,
1851
+ UpdatedAt: new Date(),
1852
+ CreatedById: 'System',
1853
+ CreatedAt: new Date(),
1854
+ UpdatedById: 'System',
1855
+ },
1856
+ {
1857
+ transaction: transaction,
1858
+ },
1859
+ );
1860
+
1861
+ tx = newTx;
1862
+ }
1863
+ this._Taxes.push(new Tax(tx.get({ plain: true })));
1864
+ }
1865
+ }
1866
+
1867
+ async collectPaymentForMultipleCustomers(
1868
+ dbTransaction: any,
1869
+ loginUser: LoginUserBase,
1870
+ payment: Payment,
1871
+ creditTransaction: {
1872
+ AccountNo: string;
1873
+ Currency: string;
1874
+ Amount: number;
1875
+ }[],
1876
+ receiptNo?: string,
1877
+ ): Promise<Payment> {
1878
+ //Method to collect payment for multiple customer.
1879
+ try {
1880
+ //Part 1: Privilege Checking\
1881
+ const systemCode = await ApplicationConfig.getComponentConfigValue(
1882
+ 'system-code',
1883
+ );
1884
+ const isPrivileged = await loginUser.checkPrivileges(
1885
+ systemCode,
1886
+ 'Collect Payment For Multiple Customers',
1887
+ );
1888
+
1889
+ if (!isPrivileged) {
1890
+ throw new Error('User is not authorized to perform this action');
1891
+ }
1892
+
1893
+ //Part 2: Validation
1894
+ //Make sure that the payment has at least 1 payment item
1895
+ const paymentItems = await payment.PaymentItems;
1896
+ if (paymentItems.length < 1) {
1897
+ throw new Error(
1898
+ 'Atleast one payment item is required to identify what payment is being paid for.',
1899
+ );
1900
+ }
1901
+
1902
+ //Make sure that the payment has at least 1 payment method
1903
+ const paymentPaidWithItems = await payment.PaymentPaidWith;
1904
+ if (paymentPaidWithItems.length < 1) {
1905
+ throw new Error(
1906
+ 'Atleast one payment paid with item is required to identify how the payment was made.',
1907
+ );
1908
+ }
1909
+
1910
+ //Make sure the payment items length is equal to creditTransactions length records.
1911
+ if (paymentItems.length !== creditTransaction.length) {
1912
+ throw new Error(
1913
+ 'Payment items length is not equal to creditTransaction length',
1914
+ );
1915
+ }
1916
+
1917
+ //Make sure the payment items total Amount is equal to credit transactions total Amount.
1918
+ let totalAmount = 0;
1919
+ paymentItems.forEach((paymentItem) => {
1920
+ totalAmount += paymentItem.Amount;
1921
+ });
1922
+
1923
+ const totalCreditTransactionAmount = creditTransaction.reduce(
1924
+ (accumulator, currentValue) => {
1925
+ return accumulator + currentValue.Amount;
1926
+ },
1927
+ 0,
1928
+ );
1929
+
1930
+ if (totalAmount !== totalCreditTransactionAmount) {
1931
+ throw new Error(
1932
+ 'Payment items total Amount is dnot equal to credit transactions total Amount',
1933
+ );
1934
+ }
1935
+
1936
+ //Part 3:Generate Receipt (KIV)
1937
+
1938
+ //Part 4: Saving Payment, Payment Items and Payment Paid with Details to the Database
1939
+
1940
+ //Set below Payment attributes:
1941
+ payment.PaymentId = cuid();
1942
+ payment.PaymentType = PaymentType.PAYMENT_RECEIVED;
1943
+ payment.ReceivedBy = loginUser.ObjectId;
1944
+ payment.IssuedBy = loginUser.ObjectId;
1945
+
1946
+ //Call Payment Repository create() method by passing:
1947
+ await FinanceCompany._PaymentRepository.create(
1948
+ {
1949
+ PaymentId: payment.PaymentId,
1950
+ PaymentType: payment.PaymentType,
1951
+ PaymentDate: payment.PaymentDate,
1952
+ Description: payment.Description,
1953
+ Currency: payment.Currency,
1954
+ Amount: payment.Amount,
1955
+ Status: PaymentStatus.SUCCESSFUL,
1956
+ PostedToAccSystemYN: 'N',
1957
+ ReceivedBy: payment.ReceivedBy,
1958
+ IssuedBy: payment.IssuedBy,
1959
+ Remarks: payment.Remarks,
1960
+ RelatedObjectId: payment.RelatedObjectId,
1961
+ RelatedObjectType: payment.RelatedObjectType,
1962
+ ReceiptDocNo: payment.ReceiptDocNo,
1963
+ UpdatedAt: new Date(),
1964
+ UpdatedBy: loginUser.ObjectId,
1965
+ CreatedAt: new Date(),
1966
+ CreatedBy: loginUser.ObjectId,
1967
+ },
1968
+ { transaction: dbTransaction },
1969
+ );
1970
+
1971
+ //Map Payment.PaymentItems and insert record by passing dbTransaction
1972
+ paymentItems.forEach(async (paymentItem) => {
1973
+ await FinanceCompany._PaymentItemRepository.create(
1974
+ {
1975
+ PaymentId: payment.PaymentId,
1976
+ PayForObjectId: paymentItem.PayForObjectId,
1977
+ PayForObjectType: paymentItem.PayForObjectType,
1978
+ Currency: paymentItem.Currency,
1979
+ Amount: paymentItem.Amount,
1980
+ Name: paymentItem.Name,
1981
+ Description: paymentItem.Description,
1982
+ },
1983
+ { transaction: dbTransaction },
1984
+ );
1985
+ });
1986
+
1987
+ // Map Payment.PaymentPaidWith and insert record by passing dbTransaction.
1988
+ paymentPaidWithItems.forEach(async (paymentPaidWithItem) => {
1989
+ await FinanceCompany._PaymentPaidWithRepository.create(
1990
+ {
1991
+ PaymentId: payment.PaymentId,
1992
+ MethodTypeId: paymentPaidWithItem.MethodTypeId,
1993
+ Currency: paymentPaidWithItem.Currency,
1994
+ Amount: paymentPaidWithItem.Amount,
1995
+ Status: paymentPaidWithItem.Status,
1996
+ TransactionId: paymentPaidWithItem.TransactionId,
1997
+ RefBank: paymentPaidWithItem.RefBank,
1998
+ RefName: paymentPaidWithItem.RefName,
1999
+ RefNo: paymentPaidWithItem.RefNo,
2000
+ RefOther1: paymentPaidWithItem.RefOther1,
2001
+ RefOther2: paymentPaidWithItem.RefOther2,
2002
+ RefOther3: paymentPaidWithItem.RefOther3,
2003
+ RefOther4: paymentPaidWithItem.RefOther4,
2004
+ RefOther5: paymentPaidWithItem.RefOther5,
2005
+ Remarks: paymentPaidWithItem.Remarks,
2006
+ PaymentMediaId: paymentPaidWithItem.PaymentMediaId,
2007
+ },
2008
+ { transaction: dbTransaction },
2009
+ );
2010
+ });
2011
+
2012
+ //Part 5: Registering the Journal Entries for the transaction
2013
+ //Initialise TransactionDate
2014
+ const transactionDate = new Date();
2015
+ //Initialise new JournalEntry
2016
+ const journalEntry = new JournalEntry(dbTransaction);
2017
+ journalEntry.init({
2018
+ CompanyId: this.CompanyId,
2019
+ Name: 'Collect-payments for ' + payment.PaymentId,
2020
+ });
2021
+
2022
+ // For each Payment.PaymentPaidWith:
2023
+ for (const paymentPaidWithItem of paymentPaidWithItems) {
2024
+ const paymentMethodType = await PaymentMethodType.initMethodType(
2025
+ dbTransaction,
2026
+ paymentPaidWithItem.MethodTypeId,
2027
+ );
2028
+
2029
+ //Initialise new Debit LedgerTransaction by calling JournalEntry.newLedgerTransaction() method and set below attributes:
2030
+ const debitLT = await journalEntry.newLedgerTransaction(
2031
+ TransactionTypeOptions.DEBIT,
2032
+ );
2033
+ debitLT.AccountNo = paymentMethodType.AccountNo;
2034
+ debitLT.Currency = paymentPaidWithItem.Currency;
2035
+ debitLT.DebitAmount = paymentPaidWithItem.Amount;
2036
+ debitLT.Date = transactionDate;
2037
+ debitLT.Description = 'Payment Received';
2038
+ debitLT.RelatedPaymentId = payment.PaymentId;
2039
+ }
2040
+
2041
+ //For each creditTransactions, Initialise new Credit LedgerTransaction by calling JournalEntry.newLedgerTransaction() method
2042
+ for (const ct of creditTransaction) {
2043
+ const creditLT = await journalEntry.newLedgerTransaction(
2044
+ TransactionTypeOptions.CREDIT,
2045
+ );
2046
+ creditLT.AccountNo = ct.AccountNo;
2047
+ creditLT.Currency = ct.Currency;
2048
+ creditLT.CreditAmount = ct.Amount;
2049
+ creditLT.Date = transactionDate;
2050
+ creditLT.Description = 'Payment Received';
2051
+ creditLT.RelatedPaymentId = payment.PaymentId;
2052
+ }
2053
+
2054
+ // Call this.postJournal()
2055
+ await this.postJournal(dbTransaction, journalEntry, loginUser);
2056
+
2057
+ return payment;
2058
+ } catch (error) {
2059
+ throw error;
2060
+ }
2061
+ }
2062
+ }