@tomei/finance 0.6.88 → 0.6.90

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