@tomei/finance 0.6.52 → 0.6.53

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