@tomei/finance 0.6.89 → 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 +29 -8
  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 -2310
  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,2310 +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
- let accSystemRefId: string;
499
-
500
- if (!account.AccountType) {
501
- throw new Error('AccountType is required.');
502
- }
503
-
504
- // Retrieve & validate accountNoLength from finance config file
505
- const accountNoLength = ComponentConfig.getComponentConfigValue(
506
- 'finance-config.json',
507
- 'accountNoLength',
508
- );
509
-
510
- if (accountNoLength && account.AccountNo.length > accountNoLength) {
511
- throw new Error(
512
- `Account No length should not exceed ${accountNoLength} characters.`,
513
- );
514
- }
515
-
516
- let createAccountPayload: any = {
517
- Name: account.Name,
518
- AcctNum: account.AccountNo,
519
- AccountType: account.AccountType,
520
- AccountSubType: account.AccountSubtype,
521
- };
522
-
523
- if (this.AccountingSystem) {
524
- accSystemRefId = await this.AccountingSystem.createAccount(
525
- createAccountPayload,
526
- );
527
- }
528
-
529
- if (account.isParentAccountExists()) {
530
- createAccountPayload = {
531
- ...createAccountPayload,
532
- CurrencyRef: 'MYR',
533
- ParentRef: account.ParentAccountNo,
534
- SubAccount: true,
535
- };
536
- }
537
-
538
- console.log(
539
- 'Finance Company Create Account: Before accSystemAccountId Create',
540
- );
541
-
542
- console.log(
543
- 'Finance Company Create Account: After accSystemAccountId Create',
544
- );
545
-
546
- console.log('Finance Company Create Account: Before new Account Create');
547
-
548
- if (accSystemRefId) {
549
- account.PostedToAccSystemYN = 'Y';
550
- account.PostedById = loginUser.ObjectId;
551
- account.PostedDateTime = new Date();
552
- }
553
-
554
- const newAccount = await account.save(
555
- this.CompanyId,
556
- accSystemRefId || 'REF',
557
- loginUser.ObjectId,
558
- dbTransaction,
559
- );
560
-
561
- console.log('Finance Company Create Account: After new Account Create');
562
-
563
- const payload = {
564
- Action: 'Create',
565
- Activity: 'Account Created',
566
- Description: `Account (ID: ${newAccount.AccountNo}) has been created`,
567
- EntityType: 'Account',
568
- EntityValueBefore: JSON.stringify({}),
569
- EntityValueAfter: JSON.stringify(newAccount),
570
- PerformedById: loginUser.ObjectId,
571
- PerformedAt: new Date(),
572
- EntityId: newAccount.AccountNo,
573
- };
574
-
575
- await axios.post(
576
- `${process.env.COMMON_API_URL}/activity-histories`,
577
- payload,
578
- );
579
-
580
- return account;
581
- } catch (error) {
582
- throw error;
583
- }
584
- }
585
-
586
- /**
587
- * Issue an invoice
588
- *
589
- * @param dbTransaction - The database transaction to be used
590
- * @param loginUser - The user issuing the invoice
591
- * @param invoice - The document containing the invoice details
592
- * @param customer - The customer to be issued the invoice
593
- * @param dtAccountNo - The account number of the Account Receivable (AR) account to debit. If not provided, will debit the customer's default AR account
594
- *
595
- * @returns {Document} - Document object representing the full details of the invoice issued
596
- */
597
- async issueInvoice(
598
- /*todo: loginUser & customer is NOT supposed to be optional */
599
- dbTransaction: any,
600
- invoice: Document,
601
- loginUser?: LoginUserBase,
602
- customer?: FinanceCustomerBase,
603
- dtAccountNo?: string,
604
- ): Promise<Document> {
605
- try {
606
- /*Check if the invoice number already exists (should be unique)*/
607
- const duplicateInvoice = await FinanceCompany._DocumentRepository.findOne(
608
- {
609
- where: {
610
- DocNo: invoice.DocNo,
611
- },
612
- transaction: dbTransaction,
613
- },
614
- );
615
-
616
- if (duplicateInvoice) {
617
- throw new Error('Invoice number already exists');
618
- }
619
-
620
- const documentItems = await invoice.DocumentItems;
621
-
622
- /*Check if the document has at least 1 document item*/
623
- if (!documentItems.length) {
624
- throw new Error('Document must have at least 1 document item');
625
- }
626
-
627
- /*Check if each document item has CtAccountNo provided*/
628
- for (const invoiceItem of documentItems) {
629
- if (!invoiceItem.CtAccountNo) {
630
- throw new Error(
631
- 'Each document item should have CtAccountNo provided',
632
- );
633
- }
634
- }
635
-
636
- /*Set up the document type*/
637
- invoice.DocType = DocType.INVOICE;
638
-
639
- /*Generating the invoice*/
640
- let invoiceMedia: {
641
- HTMLMedia: MediasModel;
642
- PDFMedia: MediasModel;
643
- };
644
-
645
- if (invoice.UseAccSystemDocYN === 'Y') {
646
- /*todo: Posting to accounting system to generate invoice*/
647
- // await this.AccountingSystem.createInvoice(invoice);
648
- } else {
649
- /*todo: check config file to see which invoice template is to be used for specific project*/
650
-
651
- /*Generating invoice based on template*/
652
- invoiceMedia = await invoice.generateInvoice(
653
- invoice.IssuedById,
654
- customer,
655
- dbTransaction,
656
- );
657
- }
658
-
659
- /*Saving the document and document items to the database*/
660
- await FinanceCompany._DocumentRepository.create(
661
- {
662
- DocNo: invoice.DocNo,
663
- DocType: invoice.DocType,
664
- DocDate: invoice.DocDate,
665
- CompanyId: invoice.CompanyId,
666
- Currency: invoice.Currency,
667
- Amount: invoice.Amount,
668
- Description: invoice.Description,
669
- Status: invoice.Status,
670
- IssuedById: invoice.IssuedById,
671
- IssuedToId: invoice.IssuedToId,
672
- IssuedToType: invoice.IssuedToType,
673
- RelatedObjectId: invoice.RelatedObjectId,
674
- RelatedObjectType: invoice.RelatedObjectType,
675
- CreatedById: invoice.CreatedById,
676
- CreatedAt: new Date(),
677
- UpdatedById: invoice.UpdatedById,
678
- UpdatedAt: new Date(),
679
- DocPDFFileMediaId: invoiceMedia.PDFMedia.MediaId,
680
- DocHTMLFileMediaId: invoiceMedia.HTMLMedia.MediaId,
681
- AccSystemRefId: invoice.AccSystemRefId,
682
- PostedToAccSystemYN: invoice.PostedToAccSystemYN,
683
- PostedById:
684
- invoice.UseAccSystemDocYN == 'Y' ? invoice.PostedById : null,
685
- PostedDateTime: new Date(),
686
- UseAccSystemDocYN: invoice.UseAccSystemDocYN,
687
- },
688
- {
689
- transaction: dbTransaction,
690
- },
691
- );
692
-
693
- for (const documentItem of documentItems) {
694
- await FinanceCompany._DocumentItemRepository.create(
695
- {
696
- DocumentItemId: this._createId().toUpperCase(),
697
- DocNo: invoice.DocNo,
698
- Name: documentItem.Name,
699
- NameBM: documentItem.NameBM,
700
- Description: documentItem.Description,
701
- ItemId: documentItem.ItemId,
702
- ItemType: documentItem.ItemType,
703
- ItemSKU: documentItem.ItemSKU,
704
- ItemSerialNo: documentItem.ItemSerialNo,
705
- Currency: documentItem.Currency,
706
- UnitPrice: documentItem.UnitPrice,
707
- Quantity: documentItem.Quantity,
708
- QuantityUOM: documentItem.QuantityUOM,
709
- Amount: documentItem.Amount,
710
- TaxCode: documentItem.TaxCode,
711
- TaxAmount: documentItem.TaxAmount,
712
- TaxRate: documentItem.TaxRate,
713
- TaxInclusiveYN: documentItem.TaxInclusiveYN,
714
- DtAccountNo: documentItem.DtAccountNo
715
- ? documentItem.DtAccountNo
716
- : null,
717
- CtAccountNo: documentItem.CtAccountNo
718
- ? documentItem.CtAccountNo
719
- : null,
720
- },
721
- {
722
- transaction: dbTransaction,
723
- },
724
- );
725
- }
726
-
727
- const transactionDate = new Date();
728
- const htCreditAccountAmount = new HashTable();
729
- const htCreditAccountCurrency = new HashTable();
730
- const htCreditAccountPurpose = new HashTable();
731
-
732
- documentItems.forEach((invoiceItem) => {
733
- if (!htCreditAccountAmount.exists(invoiceItem.CtAccountNo)) {
734
- //add the credit account to the hash table
735
- htCreditAccountAmount.add(
736
- invoiceItem.CtAccountNo,
737
- invoiceItem.Amount,
738
- );
739
-
740
- htCreditAccountCurrency.add(
741
- invoiceItem.CtAccountNo,
742
- invoiceItem.Currency,
743
- );
744
-
745
- htCreditAccountPurpose.add(invoiceItem.CtAccountNo, invoiceItem.Name);
746
- } else {
747
- //update the credit account amount
748
- const d = htCreditAccountAmount.get(invoiceItem.CtAccountNo);
749
- htCreditAccountAmount.add(
750
- invoiceItem.CtAccountNo,
751
- d + invoiceItem.Amount,
752
- );
753
- }
754
- });
755
-
756
- const savedItems = htCreditAccountAmount.list();
757
-
758
- for (const item of savedItems) {
759
- const journalEntry = new JournalEntry(dbTransaction);
760
- //Temporary fix to successfully save journal entry in PostJournal
761
- journalEntry.init({
762
- CompanyId: this.CompanyId,
763
- Name: 'Issue Invoice ' + invoice.DocNo,
764
- });
765
- // const account = await Account.initAccount(dbTransaction, item.value[0]);
766
- const creditAmount = item.value[1];
767
- const currency = htCreditAccountCurrency.get(item.value[0]);
768
- const purpose = htCreditAccountPurpose.get(item.value[0]);
769
-
770
- const dt = await journalEntry.newLedgerTransaction(
771
- TransactionTypeOptions.DEBIT,
772
- );
773
-
774
- if (dtAccountNo) {
775
- /*Transacting using AR account provided*/
776
- dt.AccountNo = dtAccountNo;
777
- } else {
778
- /*Transacting based on default customer AR account*/
779
- const arAccount = await customer.getAccountReceivable();
780
- dt.AccountNo = arAccount.AccountNo;
781
- }
782
-
783
- dt.Currency = currency ? currency : 'MYR';
784
- dt.DebitAmount = creditAmount ? creditAmount : 0.0;
785
- dt.Date = transactionDate;
786
- dt.Description = `${purpose}`;
787
- dt.Name = `${purpose}`;
788
- dt.RelatedDocNo = invoice.DocNo;
789
- dt.RelatedObjectId = invoice.RelatedObjectId;
790
- dt.RelatedObjectType = invoice.RelatedObjectType;
791
-
792
- const ct = await journalEntry.newLedgerTransaction(
793
- TransactionTypeOptions.CREDIT,
794
- );
795
- ct.AccountNo = item.value[0];
796
- ct.Currency = currency ? currency : 'MYR';
797
- ct.CreditAmount = creditAmount ? creditAmount : 0.0;
798
- ct.Date = transactionDate;
799
- ct.Description = customer.FullName;
800
- ct.Name = customer.FullName;
801
- ct.RelatedDocNo = invoice.DocNo;
802
- ct.RelatedObjectId = invoice.RelatedObjectId;
803
- ct.RelatedObjectType = invoice.RelatedObjectType;
804
-
805
- await this.postJournal(dbTransaction, journalEntry, loginUser);
806
- }
807
-
808
- return invoice;
809
- } catch (err) {
810
- // tslint:disable-next-line:no-console
811
- console.log('Issue invoice err: ', err);
812
- throw err;
813
- }
814
- }
815
-
816
- /**
817
- * Issue a debit note
818
- *
819
- * @param dbTransaction - The database transaction to be used
820
- * @param loginUser - The user issuing the invoice
821
- * @param invoice - The document containing the invoice details
822
- * @param customer - The customer to be issued the invoice
823
- * @param dtAccountNo - The account number of the Account Receivable (AR) account to debit. If not provided, will debit the customer's default AR account
824
- *
825
- * @returns {Document} - Document object representing the full details of the invoice issued
826
- */
827
- async issueDebitNote(
828
- dbTransaction: any,
829
- loginUser: LoginUserBase,
830
- invoice: Document,
831
- customer: FinanceCustomerBase,
832
- dtAccountNo?: string,
833
- ): Promise<Document> {
834
- try {
835
- /*Check if the invoice number already exists (should be unique)*/
836
- const duplicateInvoice = await FinanceCompany._DocumentRepository.findOne(
837
- {
838
- where: {
839
- DocNo: invoice.DocNo,
840
- },
841
- transaction: dbTransaction,
842
- },
843
- );
844
-
845
- if (duplicateInvoice) {
846
- throw new Error('Invoice number already exists');
847
- }
848
-
849
- const documentItems = await invoice.DocumentItems;
850
-
851
- /*Check if the document has at least 1 document item*/
852
- if (!documentItems.length) {
853
- throw new Error('Document must have at least 1 document item');
854
- }
855
-
856
- /*Check if each document item has CtAccountNo provided*/
857
- for (const invoiceItem of documentItems) {
858
- if (!invoiceItem.CtAccountNo) {
859
- throw new Error(
860
- 'Each document item should have CtAccountNo provided',
861
- );
862
- }
863
- }
864
-
865
- /*Set up the document type*/
866
- invoice.DocType = DocType.DEBIT_NOTE;
867
- // invoice.DocNo = this._createId().toUpperCase();
868
-
869
- /*Saving the document and document items to the database*/
870
- await FinanceCompany._DocumentRepository.create(
871
- {
872
- DocNo: invoice.DocNo,
873
- DocType: invoice.DocType,
874
- DocDate: invoice.DocDate,
875
- CompanyId: invoice.CompanyId,
876
- Currency: invoice.Currency,
877
- Amount: invoice.Amount,
878
- Description: invoice.Description,
879
- Status: invoice.Status,
880
- IssuedById: loginUser.ObjectId,
881
- IssuedToId: customer.ObjectId,
882
- IssuedToType: invoice.IssuedToType,
883
- RelatedObjectId: invoice.RelatedObjectId,
884
- RelatedObjectType: invoice.RelatedObjectType,
885
- CreatedById: loginUser.ObjectId,
886
- CreatedAt: new Date(),
887
- UpdatedById: loginUser.ObjectId,
888
- UpdatedAt: new Date(),
889
- DocPDFFileMediaId: invoice.DocPDFFileMediaId,
890
- DocHTMLFileMediaId: invoice.DocHTMLFileMediaId,
891
- AccSystemRefId: invoice.AccSystemRefId,
892
- PostedToAccSystemYN: invoice.PostedToAccSystemYN,
893
- PostedById:
894
- invoice.PostedToAccSystemYN == 'Y' ? invoice.PostedById : null,
895
- PostedDateTime: new Date(),
896
- UseAccSystemDocYN: invoice.UseAccSystemDocYN,
897
- },
898
- {
899
- transaction: dbTransaction,
900
- },
901
- );
902
-
903
- documentItems.forEach(async (documentItem) => {
904
- await FinanceCompany._DocumentItemRepository.create(
905
- {
906
- DocumentItemId: this._createId().toUpperCase(),
907
- DocNo: documentItem.DocNo,
908
- Name: documentItem.Name,
909
- NameBM: documentItem.NameBM,
910
- Description: documentItem.Description,
911
- ItemId: documentItem.ItemId,
912
- ItemType: documentItem.ItemType,
913
- ItemSKU: documentItem.ItemSKU,
914
- ItemSerialNo: documentItem.ItemSerialNo,
915
- Currency: documentItem.Currency,
916
- UnitPrice: documentItem.UnitPrice,
917
- Quantity: documentItem.Quantity,
918
- QuantityUOM: documentItem.QuantityUOM,
919
- Amount: documentItem.Amount,
920
- TaxCode: documentItem.TaxCode,
921
- TaxAmount: documentItem.TaxAmount,
922
- TaxRate: documentItem.TaxRate,
923
- TaxInclusiveYN: documentItem.TaxInclusiveYN,
924
- DtAccountNo: documentItem.DtAccountNo,
925
- CtAccountNo: documentItem.CtAccountNo,
926
- },
927
- {
928
- transaction: dbTransaction,
929
- },
930
- );
931
- });
932
-
933
- /*Generating the invoice*/
934
- if (invoice.UseAccSystemDocYN === 'Y') {
935
- /*todo: Posting to accounting system to generate invoice*/
936
- // await this.AccountingSystem.createInvoice(invoice);
937
- } else {
938
- /*todo: check config file to see which invoice template is to be used for specific project*/
939
-
940
- /*Generating invoice based on template*/
941
- invoice.generateInvoice(loginUser.IDNo, customer);
942
- }
943
-
944
- const transactionDate = new Date();
945
- const htCreditAccountAmount = new HashTable();
946
- const htCreditAccountCurrency = new HashTable();
947
- const htCreditAccountPurpose = new HashTable();
948
-
949
- documentItems.forEach((invoiceItem) => {
950
- if (!htCreditAccountAmount.exists(invoiceItem.CtAccountNo)) {
951
- //add the credit account to the hash table
952
- htCreditAccountAmount.add(
953
- invoiceItem.CtAccountNo,
954
- invoiceItem.Amount,
955
- );
956
-
957
- htCreditAccountCurrency.add(
958
- invoiceItem.CtAccountNo,
959
- invoiceItem.Currency,
960
- );
961
-
962
- htCreditAccountPurpose.add(invoiceItem.CtAccountNo, invoiceItem.Name);
963
- } else {
964
- //update the credit account amount
965
- const d = htCreditAccountAmount.get(invoiceItem.CtAccountNo);
966
- htCreditAccountAmount.add(
967
- invoiceItem.CtAccountNo,
968
- d + invoiceItem.Amount,
969
- );
970
- }
971
- });
972
-
973
- const savedItems = htCreditAccountAmount.list();
974
-
975
- for (const item of savedItems) {
976
- const journalEntry = new JournalEntry(dbTransaction);
977
- //Temporary fix to successfully save journal entry in PostJournal
978
- journalEntry.init({
979
- CompanyId: this.CompanyId,
980
- Name: 'issue Invoice ' + invoice.DocNo,
981
- });
982
- // const account = await Account.initAccount(dbTransaction, item.value[0]);
983
- const creditAmount = item.value[1];
984
- const currency = htCreditAccountCurrency.get(item.value[0]);
985
- const purpose = htCreditAccountPurpose.get(item.value[0]);
986
-
987
- const dt = await journalEntry.newLedgerTransaction(
988
- TransactionTypeOptions.DEBIT,
989
- );
990
-
991
- if (dtAccountNo) {
992
- /*Transacting using AR account provided*/
993
- dt.AccountNo = dtAccountNo;
994
- } else {
995
- /*Transacting based on default customer AR account*/
996
- const arAccount = await customer.getAccountReceivable();
997
- dt.AccountNo = arAccount.AccountNo;
998
- }
999
-
1000
- dt.Currency = currency ? currency : 'MYR';
1001
- dt.DebitAmount = creditAmount ? creditAmount : 0.0;
1002
- dt.Date = transactionDate;
1003
- dt.Description = `${purpose}`;
1004
- dt.Name = `${purpose}`;
1005
- dt.RelatedDocNo = invoice.DocNo;
1006
- dt.RelatedObjectId = invoice.RelatedObjectId;
1007
- dt.RelatedObjectType = invoice.RelatedObjectType;
1008
-
1009
- const ct = await journalEntry.newLedgerTransaction(
1010
- TransactionTypeOptions.CREDIT,
1011
- );
1012
- ct.AccountNo = item.value[0];
1013
- ct.Currency = currency ? currency : 'MYR';
1014
- ct.CreditAmount = creditAmount ? creditAmount : 0.0;
1015
- ct.Date = transactionDate;
1016
- ct.Description = customer.FullName;
1017
- ct.Name = customer.FullName;
1018
- ct.RelatedDocNo = invoice.DocNo;
1019
- ct.RelatedObjectId = invoice.RelatedObjectId;
1020
- ct.RelatedObjectType = invoice.RelatedObjectType;
1021
-
1022
- await this.postJournal(dbTransaction, journalEntry, loginUser);
1023
- }
1024
-
1025
- return invoice;
1026
- } catch (err) {
1027
- // tslint:disable-next-line:no-console
1028
- console.log('Issue debit note err: ', err);
1029
- throw err;
1030
- }
1031
- }
1032
-
1033
- /**
1034
- * Issue a credit note
1035
- *
1036
- * @param dbTransaction - The database transaction to be used
1037
- * @param loginUser - The user issuing the credit note
1038
- * @param creditNote - The document containing the credit note details
1039
- * @param customer - The customer to be issued the credit note
1040
- * @param ctAccountNo - The account number of the Account Payable (AP) account to debit. If not provided, will debit the customer's default AR account
1041
- *
1042
- * @returns {Document} - Document object representing the full details of the invoice issued
1043
- */
1044
- async issueCreditNote(
1045
- dbTransaction: any,
1046
- loginUser: LoginUserBase,
1047
- creditNote: Document,
1048
- customer: FinanceCustomerBase,
1049
- ctAccountNo?: string,
1050
- ): Promise<Document> {
1051
- try {
1052
- /*Check if the invoice number already exists (should be unique)*/
1053
- const duplicateCreditNote =
1054
- await FinanceCompany._DocumentRepository.findOne({
1055
- where: {
1056
- DocNo: creditNote.DocNo,
1057
- },
1058
- transaction: dbTransaction,
1059
- });
1060
-
1061
- if (duplicateCreditNote) {
1062
- throw new Error('Invoice number already exists');
1063
- }
1064
-
1065
- const documentItems = await creditNote.DocumentItems;
1066
-
1067
- /*Check if the document has at least 1 document item*/
1068
- if (!documentItems.length) {
1069
- throw new Error('Document must have at least 1 document item');
1070
- }
1071
-
1072
- //Map each creditNote.DocumentItems and do checking below:
1073
- //1. Set actualDocument to the instantiation of existing Document. (to check valid Document)
1074
- //2. Check for each actualDocument to make sure IssuedToId all the same. If not, throw ClassError.
1075
- //3. Check if each document item has DtAccountNo provided
1076
- for (const invoiceItem of documentItems) {
1077
- if (!invoiceItem.DtAccountNo) {
1078
- throw new Error(
1079
- 'Each document item should have DtAccountNo provided',
1080
- );
1081
- }
1082
-
1083
- const actualDocument = await Document.initDocument(
1084
- dbTransaction,
1085
- invoiceItem.ItemId,
1086
- );
1087
-
1088
- if (actualDocument.IssuedToId !== creditNote.IssuedToId) {
1089
- throw new ClassError(
1090
- 'FinanceCompany',
1091
- 'FinanceCompanyErrMsgOX',
1092
- 'To issue credit note, all invoices must belong to same customer.',
1093
- );
1094
- }
1095
- }
1096
-
1097
- /*Set up the document type*/
1098
- creditNote.DocType = DocType.CREDIT_NOTE;
1099
- creditNote.Status = DocumentStatus.SETTLED;
1100
-
1101
- /*Saving the document and document items to the database*/
1102
- await FinanceCompany._DocumentRepository.create(
1103
- {
1104
- DocNo: creditNote.DocNo,
1105
- DocType: creditNote.DocType,
1106
- DocDate: creditNote.DocDate,
1107
- CompanyId: creditNote.CompanyId,
1108
- Currency: creditNote.Currency,
1109
- Amount: creditNote.Amount,
1110
- Description: creditNote.Description,
1111
- Status: creditNote.Status,
1112
- IssuedById: loginUser.ObjectId,
1113
- IssuedToId: customer.ObjectId,
1114
- IssuedToType: creditNote.IssuedToType,
1115
- RelatedObjectId: creditNote.RelatedObjectId,
1116
- RelatedObjectType: creditNote.RelatedObjectType,
1117
- CreatedById: loginUser.ObjectId,
1118
- CreatedAt: new Date(),
1119
- UpdatedById: loginUser.ObjectId,
1120
- UpdatedAt: new Date(),
1121
- DocPDFFileMediaId: creditNote.DocPDFFileMediaId,
1122
- DocHTMLFileMediaId: creditNote.DocHTMLFileMediaId,
1123
- AccSystemRefId: creditNote.AccSystemRefId,
1124
- PostedToAccSystemYN: creditNote.PostedToAccSystemYN,
1125
- PostedById:
1126
- creditNote.PostedToAccSystemYN == 'Y'
1127
- ? creditNote.PostedById
1128
- : null,
1129
- PostedDateTime: new Date(),
1130
- UseAccSystemDocYN: creditNote.UseAccSystemDocYN,
1131
- },
1132
- {
1133
- transaction: dbTransaction,
1134
- },
1135
- );
1136
-
1137
- for (const docItem of documentItems) {
1138
- await FinanceCompany._DocumentItemRepository.create(
1139
- {
1140
- DocumentItemId: this._createId().toUpperCase(),
1141
- DocNo: docItem.DocNo,
1142
- Name: docItem.Name,
1143
- NameBM: docItem.NameBM,
1144
- Description: docItem.Description,
1145
- ItemId: docItem.ItemId,
1146
- ItemType: docItem.ItemType,
1147
- ItemSKU: docItem.ItemSKU,
1148
- ItemSerialNo: docItem.ItemSerialNo,
1149
- Currency: docItem.Currency,
1150
- UnitPrice: docItem.UnitPrice,
1151
- Quantity: docItem.Quantity,
1152
- QuantityUOM: docItem.QuantityUOM,
1153
- Amount: docItem.Amount,
1154
- TaxCode: docItem.TaxCode,
1155
- TaxAmount: docItem.TaxAmount,
1156
- TaxRate: docItem.TaxRate,
1157
- TaxInclusiveYN: docItem.TaxInclusiveYN,
1158
- DtAccountNo: docItem.DtAccountNo ? docItem.DtAccountNo : null,
1159
- CtAccountNo: docItem.CtAccountNo ? docItem.CtAccountNo : null,
1160
- },
1161
- {
1162
- transaction: dbTransaction,
1163
- },
1164
- );
1165
-
1166
- //Call Document.settleByCreditNote to settle the invoice
1167
- await Document.settleByCreditNote(
1168
- loginUser,
1169
- dbTransaction,
1170
- docItem.ItemId,
1171
- docItem.Amount,
1172
- );
1173
- }
1174
-
1175
- /*Generating the credit note*/
1176
- if (creditNote.UseAccSystemDocYN === 'Y') {
1177
- /*todo: Posting to accounting system to generate creditNote*/
1178
- // await this.AccountingSystem.createCreditNote(creditNote);
1179
- } else {
1180
- /*todo: check config file to see which invoice template is to be used for specific project*/
1181
-
1182
- /*Generating credit note based on template*/
1183
- creditNote.generateCreditNote(loginUser.IDNo, customer);
1184
- }
1185
-
1186
- const journalEntry = new JournalEntry(dbTransaction);
1187
- //Temporary fix to successfully save journal entry in PostJournal
1188
- journalEntry.init({
1189
- CompanyId: this.CompanyId,
1190
- Name: 'Issue Credit Note ' + creditNote.DocNo,
1191
- });
1192
-
1193
- const transactionDate = new Date();
1194
-
1195
- const creditTransaction = await journalEntry.newLedgerTransaction(
1196
- TransactionTypeOptions.CREDIT,
1197
- );
1198
-
1199
- if (ctAccountNo) {
1200
- /*Transacting using AR account provided*/
1201
- creditTransaction.AccountNo = ctAccountNo;
1202
- } else {
1203
- /*Transacting based on default customer AR account*/
1204
- // creditTransaction.AccountNo = customer.CustSystemCode + '-AP';
1205
- // getAccountPayable
1206
- const arAccount = await customer.getAccountPayable();
1207
- creditTransaction.AccountNo = arAccount.AccountNo;
1208
- }
1209
-
1210
- creditTransaction.Currency = creditNote.Currency;
1211
- creditTransaction.CreditAmount = creditNote.Amount;
1212
- creditTransaction.Date = transactionDate;
1213
- creditTransaction.Description = creditNote.DocNo;
1214
- creditTransaction.Name = creditNote.DocNo;
1215
- creditTransaction.RelatedDocNo = creditNote.DocNo;
1216
- creditTransaction.RelatedObjectId = creditNote.RelatedObjectId;
1217
- creditTransaction.RelatedObjectType = creditNote.RelatedObjectType;
1218
-
1219
- for (const invoiceItem of documentItems) {
1220
- const itemLedger = await journalEntry.newLedgerTransaction(
1221
- TransactionTypeOptions.DEBIT,
1222
- );
1223
- itemLedger.AccountNo = invoiceItem.DtAccountNo;
1224
- itemLedger.Currency = invoiceItem.Currency;
1225
- itemLedger.DebitAmount = invoiceItem.Amount;
1226
- itemLedger.Date = transactionDate;
1227
- itemLedger.Description = invoiceItem.Name;
1228
- // itemLedger.Name = invoiceItem.Name;
1229
- itemLedger.RelatedDocNo = creditNote.DocNo;
1230
- itemLedger.RelatedObjectId = creditNote.RelatedObjectId;
1231
- itemLedger.RelatedObjectType = creditNote.RelatedObjectType;
1232
- }
1233
-
1234
- await this.postJournal(dbTransaction, journalEntry, loginUser);
1235
-
1236
- const entityValueAfter = {
1237
- LedgerNo: creditTransaction.LedgerNo,
1238
- TransactionType: creditTransaction.TransactionType,
1239
- JournalEntryId: creditTransaction.JournalEntryId,
1240
- AccountNo: creditTransaction.AccountNo,
1241
- Date: creditTransaction.Date,
1242
- Name: creditTransaction.Name,
1243
- Description: creditTransaction.Description,
1244
- Currency: creditTransaction.Currency,
1245
- DebitAmount: creditTransaction.DebitAmount,
1246
- CreditAmount: creditTransaction.CreditAmount,
1247
- RelatedObjectId: creditTransaction.RelatedObjectId,
1248
- RelatedObjectType: creditTransaction.RelatedObjectType,
1249
- RelatedDocNo: creditTransaction.RelatedDocNo,
1250
- RelatedPaymentId: creditTransaction.RelatedPaymentId,
1251
- };
1252
- const payload = {
1253
- Action: 'Create',
1254
- Activity: 'Issuing a Credit Note Transaction',
1255
- Description: `Credit Transaction (ID: ${creditTransaction.LedgerNo}) has been created`,
1256
- EntityType: 'CreditTransaction',
1257
- EntityValueBefore: JSON.stringify({}),
1258
- EntityValueAfter: JSON.stringify(entityValueAfter),
1259
- PerformedById: loginUser.ObjectId,
1260
- PerformedAt: transactionDate,
1261
- EntityId: creditTransaction.LedgerNo,
1262
- };
1263
-
1264
- await axios.post(
1265
- `${process.env.COMMON_API_URL}/activity-histories`,
1266
- payload,
1267
- );
1268
-
1269
- return creditNote;
1270
- } catch (err) {
1271
- // tslint:disable-next-line:no-console
1272
- console.log('Issue credit note err: ', err);
1273
- throw err;
1274
- }
1275
- }
1276
-
1277
- /**
1278
- * Register a payment collected
1279
- *
1280
- * @param dbTransaction - The database transaction to be used
1281
- * @param loginUser - The user collecting the payment
1282
- * @param payment - The payment object containing payment details
1283
- * @param customer - The customer making the payment
1284
- * @param ctAccountNo - The account number of the customer's Account Receivable account to transact, else the default customer account payable receivable will be used
1285
- * @param receiptNo - The document receipt number
1286
- *
1287
- * @returns {Payment} - Payment object representing the full detals of the payment collection recorded
1288
- */
1289
- async collectPayment(
1290
- dbTransaction: any,
1291
- loginUser: LoginUserBase,
1292
- payment: Payment,
1293
- collectPaymentType: CollectPaymentType = CollectPaymentType.AUTOMATIC,
1294
- ): Promise<Payment> {
1295
- try {
1296
- /*validation 1: Make sure that the payment has at least 1 payment item*/
1297
- const paymentItems = await payment.getPaymentItems();
1298
- if (paymentItems.length < 1) {
1299
- throw new Error(
1300
- 'Atleast one payment item is required to identify what payment is being paid for.',
1301
- );
1302
- }
1303
-
1304
- /*validation 2: Make sure that the payment has at least 1 payment method*/
1305
- const paymentPaidWithItems = await payment.getPaymentPaidWith();
1306
- if (paymentPaidWithItems.length < 1) {
1307
- throw new Error(
1308
- 'Atleast one payment paid with item is required to identify how the payment was made.',
1309
- );
1310
- }
1311
-
1312
- /*Saving payment, payment items, and payment paid with details to the database*/
1313
- payment.PaymentId = this._createId().toUpperCase();
1314
- payment.PaymentType = PaymentType.PAYMENT_RECEIVED;
1315
- payment.ReceivedBy = loginUser.ObjectId;
1316
- payment.IssuedBy = loginUser.ObjectId;
1317
-
1318
- await FinanceCompany._PaymentRepository.create(
1319
- {
1320
- PaymentId: payment.PaymentId,
1321
- PaymentType: payment.PaymentType,
1322
- PaymentDate: payment.PaymentDate,
1323
- Description: payment.Description,
1324
- Currency: payment.Currency,
1325
- Amount: payment.Amount,
1326
- Status:
1327
- collectPaymentType === CollectPaymentType.AUTOMATIC
1328
- ? PaymentStatus.CONFIRMED
1329
- : PaymentStatus.PENDING,
1330
- PostedToAccSystemYN: 'N',
1331
- ReceivedBy: payment.ReceivedBy,
1332
- IssuedBy: payment.IssuedBy,
1333
- Remarks: payment.Remarks,
1334
- RelatedObjectId: payment.RelatedObjectId,
1335
- RelatedObjectType: payment.RelatedObjectType,
1336
- ReceiptDocNo: payment.ReceiptDocNo,
1337
- UpdatedAt: new Date(),
1338
- UpdatedBy: loginUser.ObjectId,
1339
- CreatedAt: new Date(),
1340
- CreatedBy: loginUser.ObjectId,
1341
- },
1342
- { transaction: dbTransaction },
1343
- );
1344
-
1345
- for (const paymentItem of paymentItems) {
1346
- await FinanceCompany._PaymentItemRepository.create(
1347
- {
1348
- PaymentId: payment.PaymentId,
1349
- PayForObjectId: paymentItem.PayForObjectId,
1350
- PayForObjectType: paymentItem.PayForObjectType,
1351
- Currency: paymentItem.Currency,
1352
- Amount: paymentItem.Amount,
1353
- Name: paymentItem.Name,
1354
- Description: paymentItem.Description,
1355
- },
1356
- { transaction: dbTransaction },
1357
- );
1358
-
1359
- // await paymentItem.paid(dbTransaction);
1360
- }
1361
-
1362
- for (const paymentPaidWithItem of paymentPaidWithItems) {
1363
- // Validate payment method type used
1364
- await PaymentMethodType.initMethodType(
1365
- dbTransaction,
1366
- paymentPaidWithItem.MethodTypeId,
1367
- );
1368
-
1369
- await FinanceCompany._PaymentPaidWithRepository.create(
1370
- {
1371
- PaymentId: payment.PaymentId,
1372
- MethodTypeId: paymentPaidWithItem.MethodTypeId,
1373
- Currency: paymentPaidWithItem.Currency,
1374
- Amount: paymentPaidWithItem.Amount,
1375
- Status: paymentPaidWithItem.Status,
1376
- TransactionId: paymentPaidWithItem.TransactionId,
1377
- RefBank: paymentPaidWithItem.RefBank,
1378
- RefName: paymentPaidWithItem.RefName,
1379
- RefNo: paymentPaidWithItem.RefNo,
1380
- RefOther1: paymentPaidWithItem.RefOther1,
1381
- RefOther2: paymentPaidWithItem.RefOther2,
1382
- RefOther3: paymentPaidWithItem.RefOther3,
1383
- RefOther4: paymentPaidWithItem.RefOther4,
1384
- RefOther5: paymentPaidWithItem.RefOther5,
1385
- Remarks: paymentPaidWithItem.Remarks,
1386
- PaymentMediaId: paymentPaidWithItem.PaymentMediaId,
1387
- },
1388
- { transaction: dbTransaction },
1389
- );
1390
- }
1391
-
1392
- /*todo: saving a record into the activity history table*/
1393
-
1394
- return payment;
1395
- } catch (error) {
1396
- throw error;
1397
- }
1398
- }
1399
-
1400
- /**
1401
- * Method to make payment to a customer.
1402
- *
1403
- * @param dbTransaction - The database transaction to be used
1404
- * @param loginUser - The user logging in and the user who collected the payment.
1405
- * @param payment - The payment object containing payment details
1406
- * @param customer - The customer who is receiving the payment.
1407
- * @param ctAccountNo - The account number of the customer's Account Payable account to transact, else the default customer account payable will be used.
1408
- *
1409
- * @returns {Payment} - Payment object representing the full details of the payment collection recorded
1410
- */
1411
- async makePayment(
1412
- dbTransaction: any,
1413
- loginUser: LoginUserBase,
1414
- payment: Payment,
1415
- customer: FinanceCustomerBase,
1416
- dtAccountNo?: string,
1417
- ): Promise<Payment> {
1418
- let paymentMethodType: PaymentMethodType;
1419
- try {
1420
- const paymentPaidWith = await payment.getPaymentPaidWith();
1421
- if (paymentPaidWith.length < 1) {
1422
- throw new Error(
1423
- 'Atleast one payment paid with item is required to identify how the payment was made.',
1424
- );
1425
- }
1426
- paymentMethodType = await PaymentMethodType.initMethodType(
1427
- dbTransaction,
1428
- paymentPaidWith[0].MethodTypeId,
1429
- );
1430
-
1431
- const paymentItems = await payment.getPaymentItems();
1432
- if (paymentItems.length < 1) {
1433
- throw new Error(
1434
- 'Atleast one payment item is required to identify what payment is being paid for',
1435
- );
1436
- }
1437
-
1438
- payment.PaymentId = this._createId().toUpperCase();
1439
- payment.PaymentType = PaymentType.PAYOUT;
1440
- payment.ReceivedBy = loginUser.ObjectId;
1441
- payment.IssuedBy = loginUser.ObjectId;
1442
-
1443
- await FinanceCompany._PaymentRepository.create(
1444
- {
1445
- PaymentId: payment.PaymentId,
1446
- PaymentType: payment.PaymentType,
1447
- PaymentDate: payment.PaymentDate,
1448
- Description: payment.Description,
1449
- Currency: payment.Currency,
1450
- ReceivedBy: payment.ReceivedBy,
1451
- IssuedBy: payment.IssuedBy,
1452
- Remarks: payment.Remarks,
1453
- RelatedObjectId: payment.RelatedObjectId,
1454
- RelatedObjectType: payment.RelatedObjectType,
1455
- Amount: payment.Amount,
1456
- Status: PaymentStatus.CONFIRMED,
1457
- PostedToAccSystemYN: 'N',
1458
- UpdatedAt: new Date(),
1459
- UpdatedBy: loginUser.ObjectId,
1460
- CreatedAt: new Date(),
1461
- CreatedBy: loginUser.ObjectId,
1462
- },
1463
- { transaction: dbTransaction },
1464
- );
1465
-
1466
- paymentItems.forEach(async (paymentItem) => {
1467
- await FinanceCompany._PaymentItemRepository.create(
1468
- {
1469
- PaymentId: payment.PaymentId,
1470
- PayForObjectId: paymentItem.PayForObjectId,
1471
- PayForObjectType: paymentItem.PayForObjectType,
1472
- Currency: paymentItem.Currency,
1473
- Amount: paymentItem.Amount,
1474
- Name: paymentItem.Name,
1475
- Description: paymentItem.Description,
1476
- },
1477
- { transaction: dbTransaction },
1478
- );
1479
-
1480
- await paymentItem.paid(dbTransaction);
1481
- });
1482
-
1483
- for (const paymentPaidWithItem of paymentPaidWith) {
1484
- await FinanceCompany._PaymentPaidWithRepository.create(
1485
- {
1486
- PaymentId: payment.PaymentId,
1487
- MethodTypeId: paymentPaidWithItem.MethodTypeId,
1488
- Currency: paymentPaidWithItem.Currency,
1489
- Amount: paymentPaidWithItem.Amount,
1490
- Status: paymentPaidWithItem.Status,
1491
- TransactionId: paymentPaidWithItem.TransactionId,
1492
- RefBank: paymentPaidWithItem.RefBank,
1493
- RefName: paymentPaidWithItem.RefName,
1494
- RefNo: paymentPaidWithItem.RefNo,
1495
- RefOther1: paymentPaidWithItem.RefOther1,
1496
- RefOther2: paymentPaidWithItem.RefOther2,
1497
- RefOther3: paymentPaidWithItem.RefOther3,
1498
- RefOther4: paymentPaidWithItem.RefOther4,
1499
- RefOther5: paymentPaidWithItem.RefOther5,
1500
- Remarks: paymentPaidWithItem.Remarks,
1501
- PaymentMediaId: paymentPaidWithItem.PaymentMediaId,
1502
- },
1503
- { transaction: dbTransaction },
1504
- );
1505
- }
1506
- const transactionDate = new Date();
1507
- for (const paymentPaidWithItem of paymentPaidWith) {
1508
- try {
1509
- paymentMethodType = await PaymentMethodType.initMethodType(
1510
- dbTransaction,
1511
- paymentPaidWithItem.MethodTypeId,
1512
- );
1513
-
1514
- const journalEntry = new JournalEntry(dbTransaction);
1515
- //Temporary fix to successfully save journal entry in PostJournal
1516
- journalEntry.init({
1517
- CompanyId: this.CompanyId,
1518
- Name: 'Make Payment for ' + payment.PaymentId,
1519
- });
1520
-
1521
- const creditLT = await journalEntry.newLedgerTransaction(
1522
- TransactionTypeOptions.CREDIT,
1523
- );
1524
- creditLT.AccountNo = paymentMethodType.AccountNo;
1525
- creditLT.Currency = paymentPaidWithItem.Currency;
1526
- creditLT.CreditAmount = paymentPaidWithItem.Amount;
1527
- creditLT.Date = transactionDate;
1528
- creditLT.Description = customer.FullName;
1529
- creditLT.Name = customer.FullName;
1530
- creditLT.RelatedObjectId = payment.RelatedObjectId;
1531
- creditLT.RelatedObjectType = payment.RelatedObjectType;
1532
-
1533
- const debitLT = await journalEntry.newLedgerTransaction(
1534
- TransactionTypeOptions.DEBIT,
1535
- );
1536
- if (dtAccountNo) {
1537
- debitLT.AccountNo = dtAccountNo;
1538
- } else {
1539
- const apAccount = await customer.getAccountPayable();
1540
- debitLT.AccountNo = apAccount.AccountNo;
1541
- }
1542
- debitLT.Currency = paymentPaidWithItem.Currency;
1543
- debitLT.DebitAmount = paymentPaidWithItem.Amount;
1544
- debitLT.Date = transactionDate;
1545
- debitLT.Description = paymentMethodType.Name;
1546
- debitLT.Name = paymentMethodType.Name;
1547
- debitLT.RelatedObjectId = payment.RelatedObjectId;
1548
- debitLT.RelatedObjectType = payment.RelatedObjectType;
1549
-
1550
- await this.postJournal(dbTransaction, journalEntry, loginUser);
1551
- } catch (error) {
1552
- if (error instanceof RecordNotFoundError) {
1553
- throw new Error('Invalid Payment Method Type Id');
1554
- } else {
1555
- throw error;
1556
- }
1557
- }
1558
- }
1559
- /*todo: saving a record into the activity history table*/
1560
-
1561
- return payment;
1562
- } catch (error) {
1563
- if (error instanceof RecordNotFoundError) {
1564
- throw new Error('Invalid PaymentMethodType id');
1565
- } else {
1566
- throw error;
1567
- }
1568
- }
1569
- }
1570
-
1571
- get PaymentMethods(): Promise<PaymentMethod[]> {
1572
- return new Promise((resolve, reject) => {
1573
- if (this.CompanyId !== 'New') {
1574
- FinanceCompany._PaymentMethodRepository
1575
- .findAll({
1576
- where: {
1577
- CompanyId: this.CompanyId,
1578
- },
1579
- // transaction: this._DbTransaction,
1580
- })
1581
- .then((paymentMethod) => {
1582
- const paymentMethodObjects = paymentMethod.map(
1583
- (paymentMethodData) => {
1584
- return new Promise((resolve, reject) => {
1585
- FinanceCompany._PaymentMethodTypeRepository
1586
- .findAll({
1587
- where: {
1588
- MethodId: paymentMethodData.MethodId,
1589
- },
1590
- // transaction: this._DbTransaction,
1591
- raw: true,
1592
- })
1593
- .then((paymentMethodTypes) => {
1594
- const paymentMethodObjects = {
1595
- ...paymentMethodData.get({ plain: true }),
1596
- Types: paymentMethodTypes,
1597
- };
1598
- resolve(paymentMethodObjects);
1599
- })
1600
- .catch((err) => {
1601
- reject(err);
1602
- });
1603
- }).then((paymentMethods) => paymentMethods);
1604
- },
1605
- );
1606
- return Promise.all(paymentMethodObjects);
1607
- })
1608
- .then((paymentMethodObjects) => {
1609
- this._PaymentMethods = paymentMethodObjects;
1610
- resolve(this._PaymentMethods);
1611
- })
1612
- .catch((err) => {
1613
- reject(err);
1614
- });
1615
- } else {
1616
- resolve(this._PaymentMethods);
1617
- }
1618
- });
1619
- }
1620
-
1621
- get TaxCodes(): Promise<Tax[]> {
1622
- return new Promise((resolve, reject) => {
1623
- if (this.CompanyId !== 'New') {
1624
- FinanceCompany._TaxRepository
1625
- .findAll({
1626
- where: {
1627
- CompanyId: this.CompanyId,
1628
- },
1629
- transaction: this._DbTransaction,
1630
- })
1631
- .then((taxes) => {
1632
- const taxList = [];
1633
- taxes.forEach((tax) => {
1634
- taxList.push(
1635
- new Tax({
1636
- TaxCode: tax.TaxCode,
1637
- TaxRate:
1638
- typeof tax.TaxRate === 'number'
1639
- ? tax.TaxRate
1640
- : parseFloat(tax.TaxRate),
1641
- Description: tax.Description,
1642
- CompanyId: tax.CompanyId,
1643
- CreatedAt: tax.CreatedAt,
1644
- CreatedById: tax.CreatedById,
1645
- UpdatedAt: tax.UpdatedAt,
1646
- UpdatedById: tax.UpdatedById,
1647
- }),
1648
- );
1649
- });
1650
- this._Taxes = taxList;
1651
- resolve(this._Taxes);
1652
- })
1653
- .catch((err) => {
1654
- reject(err);
1655
- });
1656
- } else {
1657
- resolve(this._Taxes);
1658
- }
1659
- });
1660
- }
1661
-
1662
- /**
1663
- * Method to load / reload the payment methods based on the configuration file
1664
- */
1665
- async LoadPaymentMethods(
1666
- companyId: string,
1667
- paymentMethods: any,
1668
- transaction?: any,
1669
- ): Promise<void> {
1670
- const paymentMethod = new PaymentMethod();
1671
- for (const method in paymentMethods) {
1672
- const paymentMethodData =
1673
- await FinanceCompany._PaymentMethodRepository.findOne({
1674
- where: {
1675
- MethodId: paymentMethods[method].id,
1676
- Name: paymentMethods[method].name,
1677
- },
1678
- transaction: transaction,
1679
- });
1680
-
1681
- if (!paymentMethodData) {
1682
- const newPaymentMethod =
1683
- await FinanceCompany._PaymentMethodRepository.create(
1684
- {
1685
- MethodId: paymentMethods[method].id,
1686
- Name: paymentMethods[method].name,
1687
- CompanyId: companyId,
1688
- },
1689
- {
1690
- transaction: transaction,
1691
- },
1692
- );
1693
-
1694
- this._PaymentMethods.push(newPaymentMethod);
1695
- }
1696
- this._PaymentMethods.push(paymentMethodData);
1697
- }
1698
-
1699
- this._PaymentMethods.forEach(async (item) => {
1700
- const p = item?.get({ plain: true });
1701
-
1702
- for (const method in paymentMethods) {
1703
- if (!p) {
1704
- continue;
1705
- }
1706
-
1707
- if (p.MethodId === paymentMethods[method]?.id) {
1708
- const paymentMethodTypeData =
1709
- await FinanceCompany._PaymentMethodTypeRepository.findOne({
1710
- where: {
1711
- MethodId: p.MethodId,
1712
- },
1713
- transaction: transaction,
1714
- });
1715
-
1716
- if (!paymentMethodTypeData) {
1717
- const configPaymentMethodTypes = paymentMethods[method]?.types;
1718
-
1719
- for (const methodType in configPaymentMethodTypes) {
1720
- // TODO: Create a seeder for payment method account
1721
- /*validate whether account data already exists*/
1722
- const accountData =
1723
- await FinanceCompany._AccountRepository.findOne({
1724
- where: {
1725
- AccountNo: configPaymentMethodTypes[methodType].accountNo,
1726
- },
1727
- transaction: transaction,
1728
- });
1729
-
1730
- /*generating account data if not exist */
1731
- if (!accountData) {
1732
- const accountPayload = {
1733
- CompanyId: companyId,
1734
- Name: configPaymentMethodTypes[methodType].name,
1735
- AccountType: 'PaymentMethod',
1736
- CreatedAt: new Date(),
1737
- CreatedById: 'System',
1738
- AccSystemRefId: 'REF',
1739
- PostedToAccSystemYN: 'N',
1740
- };
1741
-
1742
- try {
1743
- await FinanceCompany._AccountRepository.create(
1744
- {
1745
- AccountNo: configPaymentMethodTypes[methodType].accountNo,
1746
- ...accountPayload,
1747
- },
1748
- {
1749
- transaction: transaction,
1750
- },
1751
- );
1752
-
1753
- await FinanceCompany._AccountRepository.create(
1754
- {
1755
- AccountNo:
1756
- configPaymentMethodTypes[methodType]
1757
- .processingFeeAccountNo,
1758
- ...accountPayload,
1759
- },
1760
- {
1761
- transaction: transaction,
1762
- },
1763
- );
1764
- } catch (err) {
1765
- throw err;
1766
- }
1767
- }
1768
-
1769
- const paymentMethodTypePayload = {
1770
- MethodId: p.MethodId,
1771
- MethodTypeId: configPaymentMethodTypes[methodType].id,
1772
- Name: configPaymentMethodTypes[methodType].name,
1773
- AccountNo: configPaymentMethodTypes[methodType].accountNo,
1774
- ProcessingFeeRate:
1775
- configPaymentMethodTypes[methodType].processingFeeRate,
1776
- ProcessingFeeAccountNo:
1777
- configPaymentMethodTypes[methodType].processingFeeAccountNo,
1778
- };
1779
-
1780
- try {
1781
- await paymentMethod.newPaymentMethodType(
1782
- paymentMethodTypePayload,
1783
- transaction,
1784
- );
1785
- } catch (err) {}
1786
- }
1787
- }
1788
- }
1789
- }
1790
- });
1791
- }
1792
-
1793
- /**
1794
- * Method to load / reload the payment methods based on the configuration file
1795
- */
1796
- async LoadTaxCodes(
1797
- companyId: string,
1798
- companyTaxes: any,
1799
- transaction?: any,
1800
- ): Promise<void> {
1801
- for (const tax in companyTaxes) {
1802
- let tx = await FinanceCompany._TaxRepository.findOne({
1803
- where: {
1804
- TaxCode: companyTaxes[tax].taxCode,
1805
- },
1806
- transaction: transaction,
1807
- });
1808
-
1809
- if (!tx) {
1810
- const newTx = await FinanceCompany._TaxRepository.create(
1811
- {
1812
- TaxCode: companyTaxes[tax].taxCode,
1813
- TaxRate: companyTaxes[tax].taxRate,
1814
- Description: companyTaxes[tax].description,
1815
- CompanyId: companyId,
1816
- UpdatedAt: new Date(),
1817
- CreatedById: 'System',
1818
- CreatedAt: new Date(),
1819
- UpdatedById: 'System',
1820
- },
1821
- {
1822
- transaction: transaction,
1823
- },
1824
- );
1825
-
1826
- tx = newTx;
1827
- }
1828
- this._Taxes.push(new Tax(tx.get({ plain: true })));
1829
- }
1830
- }
1831
-
1832
- async collectPaymentForMultipleCustomers(
1833
- dbTransaction: any,
1834
- loginUser: LoginUserBase,
1835
- payment: Payment,
1836
- creditTransaction: {
1837
- AccountNo: string;
1838
- Currency: string;
1839
- Amount: number;
1840
- }[],
1841
- receiptNo?: string,
1842
- collectPaymentType: CollectPaymentType = CollectPaymentType.AUTOMATIC,
1843
- ): Promise<Payment> {
1844
- //Method to collect payment for multiple customer.
1845
- try {
1846
- //Part 1: Privilege Checking\
1847
- const systemCode = await ApplicationConfig.getComponentConfigValue(
1848
- 'system-code',
1849
- );
1850
- const isPrivileged = await loginUser.checkPrivileges(
1851
- systemCode,
1852
- 'Collect Payment For Multiple Customers',
1853
- );
1854
-
1855
- if (!isPrivileged) {
1856
- throw new Error('User is not authorized to perform this action');
1857
- }
1858
-
1859
- //Part 2: Validation
1860
- //Make sure that the payment has at least 1 payment item
1861
- const paymentItems = await payment.getPaymentItems();
1862
- if (paymentItems.length < 1) {
1863
- throw new Error(
1864
- 'Atleast one payment item is required to identify what payment is being paid for.',
1865
- );
1866
- }
1867
-
1868
- //Make sure that the payment has at least 1 payment method
1869
- const paymentPaidWithItems = await payment.getPaymentPaidWith();
1870
- if (paymentPaidWithItems.length < 1) {
1871
- throw new Error(
1872
- 'Atleast one payment paid with item is required to identify how the payment was made.',
1873
- );
1874
- }
1875
-
1876
- //Make sure the payment items length is equal to creditTransactions length records.
1877
- if (paymentItems.length !== creditTransaction.length) {
1878
- throw new Error(
1879
- 'Payment items length is not equal to creditTransaction length',
1880
- );
1881
- }
1882
-
1883
- //Make sure the payment items total Amount is equal to credit transactions total Amount.
1884
- let totalAmount = 0;
1885
- paymentItems.forEach((paymentItem) => {
1886
- totalAmount += paymentItem.Amount;
1887
- });
1888
-
1889
- const totalCreditTransactionAmount = creditTransaction.reduce(
1890
- (accumulator, currentValue) => {
1891
- return accumulator + currentValue.Amount;
1892
- },
1893
- 0,
1894
- );
1895
-
1896
- if (totalAmount !== totalCreditTransactionAmount) {
1897
- throw new Error(
1898
- 'Payment items total Amount is dnot equal to credit transactions total Amount',
1899
- );
1900
- }
1901
-
1902
- //Part 3:Generate Receipt (KIV)
1903
-
1904
- //Part 4: Saving Payment, Payment Items and Payment Paid with Details to the Database
1905
-
1906
- //Set below Payment attributes:
1907
- payment.PaymentId = this._createId().toUpperCase();
1908
- payment.PaymentType = PaymentType.PAYMENT_RECEIVED;
1909
- payment.ReceivedBy = loginUser.ObjectId;
1910
- payment.IssuedBy = loginUser.ObjectId;
1911
-
1912
- //Call Payment Repository create() method by passing:
1913
- await FinanceCompany._PaymentRepository.create(
1914
- {
1915
- PaymentId: payment.PaymentId,
1916
- PaymentType: payment.PaymentType,
1917
- PaymentDate: payment.PaymentDate,
1918
- Description: payment.Description,
1919
- Currency: payment.Currency,
1920
- Amount: payment.Amount,
1921
- Status:
1922
- collectPaymentType === CollectPaymentType.MANUAL
1923
- ? PaymentStatus.PENDING
1924
- : PaymentStatus.CONFIRMED,
1925
- PostedToAccSystemYN: 'N',
1926
- ReceivedBy: payment.ReceivedBy,
1927
- IssuedBy: payment.IssuedBy,
1928
- Remarks: payment.Remarks,
1929
- RelatedObjectId: payment.RelatedObjectId,
1930
- RelatedObjectType: payment.RelatedObjectType,
1931
- ReceiptDocNo: payment.ReceiptDocNo,
1932
- UpdatedAt: new Date(),
1933
- UpdatedBy: loginUser.ObjectId,
1934
- CreatedAt: new Date(),
1935
- CreatedBy: loginUser.ObjectId,
1936
- },
1937
- { transaction: dbTransaction },
1938
- );
1939
-
1940
- //Map Payment.PaymentItems and insert record by passing dbTransaction
1941
- paymentItems.forEach(async (paymentItem) => {
1942
- await FinanceCompany._PaymentItemRepository.create(
1943
- {
1944
- PaymentId: payment.PaymentId,
1945
- PayForObjectId: paymentItem.PayForObjectId,
1946
- PayForObjectType: paymentItem.PayForObjectType,
1947
- Currency: paymentItem.Currency,
1948
- Amount: paymentItem.Amount,
1949
- Name: paymentItem.Name,
1950
- Description: paymentItem.Description,
1951
- },
1952
- { transaction: dbTransaction },
1953
- );
1954
- });
1955
-
1956
- // Map Payment.PaymentPaidWith and insert record by passing dbTransaction.
1957
- paymentPaidWithItems.forEach(async (paymentPaidWithItem) => {
1958
- await FinanceCompany._PaymentPaidWithRepository.create(
1959
- {
1960
- PaymentId: payment.PaymentId,
1961
- MethodTypeId: paymentPaidWithItem.MethodTypeId,
1962
- Currency: paymentPaidWithItem.Currency,
1963
- Amount: paymentPaidWithItem.Amount,
1964
- Status: paymentPaidWithItem.Status,
1965
- LedgerNo: paymentPaidWithItem.TransactionId,
1966
- RefBank: paymentPaidWithItem.RefBank,
1967
- RefName: paymentPaidWithItem.RefName,
1968
- RefNo: paymentPaidWithItem.RefNo,
1969
- RefOther1: paymentPaidWithItem.RefOther1,
1970
- RefOther2: paymentPaidWithItem.RefOther2,
1971
- RefOther3: paymentPaidWithItem.RefOther3,
1972
- RefOther4: paymentPaidWithItem.RefOther4,
1973
- RefOther5: paymentPaidWithItem.RefOther5,
1974
- Remarks: paymentPaidWithItem.Remarks,
1975
- PaymentMediaId: paymentPaidWithItem.PaymentMediaId,
1976
- },
1977
- { transaction: dbTransaction },
1978
- );
1979
- });
1980
-
1981
- //Part 5: Registering the Journal Entries for the transaction
1982
- //Initialise TransactionDate
1983
- // const transactionDate = new Date();
1984
- // //Initialise new JournalEntry
1985
- // const journalEntry = new JournalEntry(dbTransaction);
1986
- // journalEntry.init({
1987
- // CompanyId: this.CompanyId,
1988
- // Name: 'Collect-payments for ' + payment.PaymentId,
1989
- // });
1990
-
1991
- // // For each Payment.PaymentPaidWith:
1992
- // for (const paymentPaidWithItem of paymentPaidWithItems) {
1993
- // const paymentMethodType = await PaymentMethodType.initMethodType(
1994
- // dbTransaction,
1995
- // paymentPaidWithItem.MethodTypeId,
1996
- // );
1997
-
1998
- // //Initialise new Debit LedgerTransaction by calling JournalEntry.newLedgerTransaction() method and set below attributes:
1999
- // const debitLT = await journalEntry.newLedgerTransaction(
2000
- // TransactionTypeOptions.DEBIT,
2001
- // );
2002
- // debitLT.AccountNo = paymentMethodType.AccountNo;
2003
- // debitLT.Currency = paymentPaidWithItem.Currency;
2004
- // debitLT.DebitAmount = paymentPaidWithItem.Amount;
2005
- // debitLT.Date = transactionDate;
2006
- // debitLT.Description = 'Payment Received';
2007
- // debitLT.RelatedPaymentId = payment.PaymentId;
2008
- // }
2009
-
2010
- // //For each creditTransactions, Initialise new Credit LedgerTransaction by calling JournalEntry.newLedgerTransaction() method
2011
- // for (const ct of creditTransaction) {
2012
- // const creditLT = await journalEntry.newLedgerTransaction(
2013
- // TransactionTypeOptions.CREDIT,
2014
- // );
2015
- // creditLT.AccountNo = ct.AccountNo;
2016
- // creditLT.Currency = ct.Currency;
2017
- // creditLT.CreditAmount = ct.Amount;
2018
- // creditLT.Date = transactionDate;
2019
- // creditLT.Description = 'Payment Received';
2020
- // creditLT.RelatedPaymentId = payment.PaymentId;
2021
- // }
2022
-
2023
- // // Call this.postJournal()
2024
- // await this.postJournal(dbTransaction, journalEntry, loginUser);
2025
-
2026
- return payment;
2027
- } catch (error) {
2028
- throw error;
2029
- }
2030
- }
2031
-
2032
- /**
2033
- * Confirms a payment and performs necessary actions such as creating a payment receipt and registering journal entries.
2034
- * @param dbTransaction - The database transaction object.
2035
- * @param loginUser - The logged-in user object.
2036
- * @param customer - The customer object.
2037
- * @param payment - The payment object.
2038
- * @param status - The status of the payment (CONFIRMED, REJECTED, or FAILED).
2039
- * @param remarks - Additional remarks for the payment.
2040
- * @param ctAccountNo - Optional. The account number for the credit transaction.
2041
- * @param receiptNo - Optional. The receipt number for the payment.
2042
- * @returns A promise that resolves when the payment is confirmed.
2043
- * @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.
2044
- */
2045
- async confirmPayment(
2046
- dbTransaction: any,
2047
- loginUser: LoginUserBase,
2048
- customer: FinanceCustomerBase,
2049
- payment: Payment,
2050
- status:
2051
- | PaymentStatus.CONFIRMED
2052
- | PaymentStatus.REJECTED
2053
- | PaymentStatus.FAILED,
2054
- remarks: string,
2055
- ctAccountNo?: string,
2056
- receiptNo?: string,
2057
- ): Promise<void> {
2058
- try {
2059
- this._DbTransaction = dbTransaction;
2060
- const systemCode =
2061
- ApplicationConfig.getComponentConfigValue('system-code');
2062
-
2063
- const isPrivileged = await loginUser.checkPrivileges(
2064
- systemCode,
2065
- 'FinanceCompany - Confirm Payment',
2066
- );
2067
- if (!isPrivileged) {
2068
- throw new ClassError(
2069
- 'FinanceCompany',
2070
- 'FinanceCompanyConfirmPaymentErrMsg00',
2071
- `You do not have 'Payment - Confirm' privilege.`,
2072
- );
2073
- }
2074
-
2075
- if (payment.PaymentId === 'New') {
2076
- throw new ClassError(
2077
- 'FinanceCompany',
2078
- 'FinanceCompanyConfirmPaymentErrMsg01',
2079
- `Payment not found.`,
2080
- );
2081
- }
2082
-
2083
- if (payment.Status !== PaymentStatus.PENDING) {
2084
- throw new ClassError(
2085
- 'Payment',
2086
- 'PaymentConfirmPaymentErrMsg02',
2087
- `Payment status is not 'Pending'.`,
2088
- );
2089
- }
2090
-
2091
- payment.Remarks = remarks;
2092
- let receiptDocNo = null;
2093
- switch (status) {
2094
- case PaymentStatus.REJECTED:
2095
- payment.Status = PaymentStatus.REJECTED;
2096
- break;
2097
- case PaymentStatus.FAILED:
2098
- payment.Status = PaymentStatus.FAILED;
2099
- break;
2100
- case PaymentStatus.CONFIRMED:
2101
- payment.Status = PaymentStatus.CONFIRMED;
2102
- //Creating the payment receipt
2103
- /*Generating the receipt*/
2104
- const receiptDocuments: any =
2105
- await FinanceCompany._DocumentRepository.findAll({
2106
- where: {
2107
- DocType: DocType.RECEIPT,
2108
- CompanyId: this.ObjectId,
2109
- },
2110
- });
2111
-
2112
- const receipt = new Document(dbTransaction);
2113
-
2114
- if (receiptNo) {
2115
- receipt.DocNo = receiptNo;
2116
- } else {
2117
- receipt.DocNo = `EZC-RCT-${receiptDocuments.length + 1}`;
2118
- }
2119
- receipt.DocType = DocType.RECEIPT;
2120
- receipt.DocDate = new Date();
2121
- receipt.CompanyId = this.ObjectId;
2122
- receipt.Currency = payment.Currency;
2123
- receipt.Description = 'Payment Received';
2124
- receipt.IssuedById = loginUser.ObjectId;
2125
- receipt.IssuedToId = customer.CustomerId;
2126
- receipt.IssuedToType = type(customer);
2127
- receipt.RelatedObjectId = payment.RelatedObjectId;
2128
- receipt.RelatedObjectType = payment.RelatedObjectType;
2129
- receipt.UseAccSystemDocYN = 'N';
2130
- receipt.CreatedById = loginUser.ObjectId;
2131
- receipt.UpdatedById = loginUser.ObjectId;
2132
-
2133
- const paymentItems = await payment.getPaymentItems(dbTransaction);
2134
- for (const paymentItem of paymentItems) {
2135
- const receiptItem = new DocumentItem(dbTransaction, receipt);
2136
- receiptItem.Name = `Payment for ${paymentItem.PayForObjectType} No. ${paymentItem.PayForObjectId}`;
2137
- receiptItem.NameBM = `Bayaran untuk ${paymentItem.PayForObjectType} No. ${paymentItem.PayForObjectId}`;
2138
- receiptItem.Description = '-';
2139
- receiptItem.Currency = paymentItem.Currency;
2140
- receiptItem.UnitPrice = paymentItem.Amount;
2141
- receiptItem.Quantity = 1;
2142
- receiptItem.Amount = receiptItem.UnitPrice * receiptItem.Quantity;
2143
- receiptItem.ItemId = receipt.DocNo;
2144
- receiptItem.ItemType = type(payment);
2145
- receiptItem.CtAccountNo = ctAccountNo;
2146
-
2147
- await paymentItem.paid(dbTransaction);
2148
- await receipt.newDocumentItem(receiptItem);
2149
- }
2150
-
2151
- const receiptMedia = await receipt.generateReceipt(
2152
- receipt.IssuedById,
2153
- customer,
2154
- dbTransaction,
2155
- );
2156
-
2157
- /*Saving the receipt document and document items to the database*/
2158
- await FinanceCompany._DocumentRepository.create(
2159
- {
2160
- DocNo: receipt.DocNo,
2161
- DocType: receipt.DocType,
2162
- DocDate: receipt.DocDate,
2163
- CompanyId: receipt.CompanyId,
2164
- Currency: receipt.Currency,
2165
- Amount: receipt.Amount,
2166
- Description: receipt.Description,
2167
- Status: receipt.Status,
2168
- IssuedById: receipt.IssuedById,
2169
- IssuedToId: receipt.IssuedToId,
2170
- IssuedToType: receipt.IssuedToType,
2171
- RelatedObjectId: receipt.RelatedObjectId,
2172
- RelatedObjectType: receipt.RelatedObjectType,
2173
- CreatedById: receipt.CreatedById,
2174
- CreatedAt: new Date(),
2175
- UpdatedById: receipt.UpdatedById,
2176
- UpdatedAt: new Date(),
2177
- DocPDFFileMediaId: receiptMedia.PDFMedia.MediaId,
2178
- DocHTMLFileMediaId: receiptMedia.HTMLMedia.MediaId,
2179
- AccSystemRefId: receipt.AccSystemRefId,
2180
- PostedToAccSystemYN: receipt.PostedToAccSystemYN,
2181
- PostedById:
2182
- receipt.PostedToAccSystemYN == 'Y' ? receipt.PostedById : null,
2183
- PostedDateTime: new Date(),
2184
- UseAccSystemDocYN: receipt.UseAccSystemDocYN,
2185
- },
2186
- {
2187
- transaction: dbTransaction,
2188
- },
2189
- );
2190
-
2191
- const receiptItems = await receipt.DocumentItems;
2192
-
2193
- for (const receiptItem of receiptItems) {
2194
- await FinanceCompany._DocumentItemRepository.create(
2195
- {
2196
- DocumentItemId: this._createId().toUpperCase(),
2197
- DocNo: receipt.DocNo,
2198
- Name: receiptItem.Name,
2199
- NameBM: receiptItem.NameBM,
2200
- Description: receiptItem.Description,
2201
- ItemId: receiptItem.ItemId,
2202
- ItemType: receiptItem.ItemType,
2203
- ItemSKU: receiptItem.ItemSKU,
2204
- ItemSerialNo: receiptItem.ItemSerialNo,
2205
- Currency: receiptItem.Currency,
2206
- UnitPrice: receiptItem.UnitPrice,
2207
- Quantity: receiptItem.Quantity,
2208
- QuantityUOM: receiptItem.QuantityUOM,
2209
- Amount: receiptItem.Amount,
2210
- TaxCode: receiptItem.TaxCode,
2211
- TaxAmount: receiptItem.TaxAmount,
2212
- TaxRate: receiptItem.TaxRate,
2213
- TaxInclusiveYN: receiptItem.TaxInclusiveYN,
2214
- DtAccountNo: receiptItem.DtAccountNo
2215
- ? receiptItem.DtAccountNo
2216
- : null,
2217
- CtAccountNo: receiptItem.CtAccountNo
2218
- ? receiptItem.CtAccountNo
2219
- : null,
2220
- },
2221
- {
2222
- transaction: dbTransaction,
2223
- },
2224
- );
2225
- }
2226
- //Set the receipt doc no to the payment
2227
- payment.ReceiptDocNo = receipt.DocNo;
2228
- receiptDocNo = receipt.DocNo;
2229
-
2230
- /*Registering the Journal Entries for the transaction*/
2231
- const transactionDate = new Date();
2232
- const paymentPaidWithItems = await payment.getPaymentPaidWith(
2233
- dbTransaction,
2234
- );
2235
-
2236
- for (const paymentPaidWith of paymentPaidWithItems) {
2237
- let paymentMethodType = await PaymentMethodType.initMethodType(
2238
- dbTransaction,
2239
- paymentPaidWith.MethodTypeId,
2240
- );
2241
-
2242
- const journalEntry = new JournalEntry(dbTransaction);
2243
-
2244
- journalEntry.init({
2245
- CompanyId: this.CompanyId,
2246
- Name: 'Collect-payments for ' + payment.PaymentId,
2247
- });
2248
-
2249
- const debitLT = await journalEntry.newLedgerTransaction(
2250
- TransactionTypeOptions.DEBIT,
2251
- );
2252
- debitLT.AccountNo = paymentMethodType.AccountNo;
2253
- debitLT.Currency = paymentPaidWith.Currency;
2254
- debitLT.DebitAmount = paymentPaidWith.Amount;
2255
- debitLT.Date = transactionDate;
2256
- debitLT.Description = 'Payment Received'; //customer.FullName;
2257
- debitLT.Name = customer.FullName;
2258
- debitLT.RelatedObjectId = payment.PaymentId;
2259
- debitLT.RelatedObjectType = 'Payment';
2260
- debitLT.RelatedPaymentId = payment.PaymentId;
2261
-
2262
- const creditLT = await journalEntry.newLedgerTransaction(
2263
- TransactionTypeOptions.CREDIT,
2264
- );
2265
-
2266
- if (ctAccountNo) {
2267
- creditLT.AccountNo = ctAccountNo;
2268
- } else {
2269
- const arAccount = await customer.getAccountReceivable();
2270
- creditLT.AccountNo = arAccount.AccountNo;
2271
- }
2272
- creditLT.Currency = paymentPaidWith.Currency;
2273
- creditLT.CreditAmount = paymentPaidWith.Amount;
2274
- creditLT.Date = transactionDate;
2275
- creditLT.Description = 'Payment Received'; //paymentMethodType.Name;
2276
- creditLT.Name = paymentMethodType.Name;
2277
- creditLT.RelatedObjectId = payment.PaymentId;
2278
- creditLT.RelatedObjectType = type(payment);
2279
- creditLT.RelatedPaymentId = payment.PaymentId;
2280
-
2281
- await this.postJournal(dbTransaction, journalEntry, loginUser);
2282
- }
2283
- break;
2284
- default:
2285
- throw new ClassError(
2286
- 'FinanceCompany',
2287
- 'FinanceCompanyConfirmPaymentErrMsg03',
2288
- `Invalid status.`,
2289
- );
2290
- }
2291
-
2292
- await FinanceCompany._PaymentRepository.update(
2293
- {
2294
- ReceiptDocNo: receiptDocNo,
2295
- Status: payment.Status,
2296
- UpdatedAt: new Date(),
2297
- UpdatedBy: loginUser.ObjectId,
2298
- },
2299
- {
2300
- where: {
2301
- PaymentId: payment.PaymentId,
2302
- },
2303
- transaction: dbTransaction,
2304
- },
2305
- );
2306
- } catch (error) {
2307
- throw error;
2308
- }
2309
- }
2310
- }
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
+ }