@tomei/finance 0.6.21 → 0.6.23

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