@tomei/finance 0.6.76 → 0.6.78

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