@tomei/finance 0.6.21 → 0.6.22

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 (287) 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.entity.d.ts +13 -0
  116. package/dist/finance-company/finance-company.entity.js +66 -0
  117. package/dist/finance-company/finance-company.entity.js.map +1 -0
  118. package/dist/finance-company/index.d.ts +3 -0
  119. package/dist/finance-company/index.js +8 -0
  120. package/dist/finance-company/index.js.map +1 -0
  121. package/dist/finance-company/interfaces/finance-company-attr.interface.d.ts +10 -0
  122. package/dist/finance-company/interfaces/finance-company-attr.interface.js +3 -0
  123. package/dist/finance-company/interfaces/finance-company-attr.interface.js.map +1 -0
  124. package/dist/finance-company/interfaces/finance-company.repository.interface.d.ts +3 -0
  125. package/dist/finance-company/interfaces/finance-company.repository.interface.js +3 -0
  126. package/dist/finance-company/interfaces/finance-company.repository.interface.js.map +1 -0
  127. package/dist/interfaces/account-system-entity.interface.d.ts +7 -0
  128. package/dist/interfaces/account-system-entity.interface.js +3 -0
  129. package/dist/interfaces/account-system-entity.interface.js.map +1 -0
  130. package/dist/interfaces/customer.repository.interface.d.ts +3 -0
  131. package/dist/interfaces/customer.repository.interface.js +3 -0
  132. package/dist/interfaces/customer.repository.interface.js.map +1 -0
  133. package/dist/interfaces/finance-customer.repository.interface.d.ts +3 -0
  134. package/dist/interfaces/finance-customer.repository.interface.js +3 -0
  135. package/dist/interfaces/finance-customer.repository.interface.js.map +1 -0
  136. package/dist/interfaces/systemConfig.interface.d.ts +0 -0
  137. package/dist/interfaces/systemConfig.interface.js +1 -0
  138. package/dist/interfaces/systemConfig.interface.js.map +1 -0
  139. package/dist/intuit-client/client.d.ts +14 -0
  140. package/dist/intuit-client/client.js +44 -0
  141. package/dist/intuit-client/client.js.map +1 -0
  142. package/dist/journal-entry/entities/journal-entry.entity.d.ts +16 -0
  143. package/dist/journal-entry/entities/journal-entry.entity.js +129 -0
  144. package/dist/journal-entry/entities/journal-entry.entity.js.map +1 -0
  145. package/dist/journal-entry/index.d.ts +6 -0
  146. package/dist/journal-entry/index.js +10 -0
  147. package/dist/journal-entry/index.js.map +1 -0
  148. package/dist/journal-entry/interfaces/journal-entry.repository.interface.d.ts +10 -0
  149. package/dist/journal-entry/interfaces/journal-entry.repository.interface.js +3 -0
  150. package/dist/journal-entry/interfaces/journal-entry.repository.interface.js.map +1 -0
  151. package/dist/ledger-transaction/entities/ledger-transaction.entity.d.ts +19 -0
  152. package/dist/ledger-transaction/entities/ledger-transaction.entity.js +157 -0
  153. package/dist/ledger-transaction/entities/ledger-transaction.entity.js.map +1 -0
  154. package/dist/ledger-transaction/index.d.ts +6 -0
  155. package/dist/ledger-transaction/index.js +10 -0
  156. package/dist/ledger-transaction/index.js.map +1 -0
  157. package/dist/payment/entities/payment-item.entity.d.ts +10 -0
  158. package/dist/payment/entities/payment-item.entity.js +62 -0
  159. package/dist/payment/entities/payment-item.entity.js.map +1 -0
  160. package/dist/payment/entities/payment.entity.d.ts +25 -0
  161. package/dist/payment/entities/payment.entity.js +152 -0
  162. package/dist/payment/entities/payment.entity.js.map +1 -0
  163. package/dist/payment/index.d.ts +10 -0
  164. package/dist/payment/index.js +18 -0
  165. package/dist/payment/index.js.map +1 -0
  166. package/dist/payment/interfaces/payment-item-attr.interface.d.ts +8 -0
  167. package/dist/payment/interfaces/payment-item-attr.interface.js +7 -0
  168. package/dist/payment/interfaces/payment-item-attr.interface.js.map +1 -0
  169. package/dist/payment/interfaces/payment-item.repository.interface.d.ts +3 -0
  170. package/dist/payment/interfaces/payment-item.repository.interface.js +3 -0
  171. package/dist/payment/interfaces/payment-item.repository.interface.js.map +1 -0
  172. package/dist/payment/interfaces/payment.repository.interface.d.ts +3 -0
  173. package/dist/payment/interfaces/payment.repository.interface.js +3 -0
  174. package/dist/payment/interfaces/payment.repository.interface.js.map +1 -0
  175. package/dist/payment/payment-item.repository.d.ts +5 -0
  176. package/dist/payment/payment-item.repository.js +12 -0
  177. package/dist/payment/payment-item.repository.js.map +1 -0
  178. package/dist/payment-item/interfaces/payment-item.repository.interface.d.ts +3 -0
  179. package/dist/payment-item/interfaces/payment-item.repository.interface.js +3 -0
  180. package/dist/payment-item/interfaces/payment-item.repository.interface.js.map +1 -0
  181. package/dist/payment-item/payment-item.js +4 -4
  182. package/dist/quickbook-client/client.d.ts +39 -0
  183. package/dist/quickbook-client/client.js +205 -0
  184. package/dist/quickbook-client/client.js.map +1 -0
  185. package/dist/quickbook-client/constant.d.ts +1 -0
  186. package/dist/quickbook-client/constant.js +5 -0
  187. package/dist/quickbook-client/constant.js.map +1 -0
  188. package/dist/quickbook-client/index.d.ts +5 -0
  189. package/dist/quickbook-client/index.js +6 -0
  190. package/dist/quickbook-client/index.js.map +1 -0
  191. package/dist/quickbook-client/interfaces/quickbook-client-call-options.interface.d.ts +6 -0
  192. package/dist/quickbook-client/interfaces/quickbook-client-call-options.interface.js +3 -0
  193. package/dist/quickbook-client/interfaces/quickbook-client-call-options.interface.js.map +1 -0
  194. package/dist/quickbook-client/interfaces/quickbook-client-create-account-options.interface.d.ts +9 -0
  195. package/dist/quickbook-client/interfaces/quickbook-client-create-account-options.interface.js +3 -0
  196. package/dist/quickbook-client/interfaces/quickbook-client-create-account-options.interface.js.map +1 -0
  197. package/dist/quickbook-client/interfaces/quickbook-client-create-customer-options.interface.d.ts +7 -0
  198. package/dist/quickbook-client/interfaces/quickbook-client-create-customer-options.interface.js +3 -0
  199. package/dist/quickbook-client/interfaces/quickbook-client-create-customer-options.interface.js.map +1 -0
  200. package/dist/quickbook-client/interfaces/quickbook-client-options.interface.d.ts +8 -0
  201. package/dist/quickbook-client/interfaces/quickbook-client-options.interface.js +3 -0
  202. package/dist/quickbook-client/interfaces/quickbook-client-options.interface.js.map +1 -0
  203. package/dist/quickbook-client/quickbook-client.module-definition.d.ts +2 -0
  204. package/dist/quickbook-client/quickbook-client.module-definition.js +9 -0
  205. package/dist/quickbook-client/quickbook-client.module-definition.js.map +1 -0
  206. package/dist/quickbook-client/quickbook-client.module.d.ts +6 -0
  207. package/dist/quickbook-client/quickbook-client.module.js +34 -0
  208. package/dist/quickbook-client/quickbook-client.module.js.map +1 -0
  209. package/dist/tsconfig.tsbuildinfo +1 -1
  210. package/invoice-template/assets/css/style.css.map +12 -12
  211. package/invoice-template/assets/css/style.min.css +1 -1
  212. package/invoice-template/assets/img/arrow_bg.svg +11 -11
  213. package/invoice-template/assets/img/coffy_shop_img.svg +18 -18
  214. package/invoice-template/assets/img/logo_accent.svg +3 -3
  215. package/invoice-template/assets/img/logo_white.svg +4 -4
  216. package/invoice-template/assets/img/sign.svg +12 -12
  217. package/invoice-template/assets/img/tomei-logo.svg +9 -9
  218. package/invoice-template/assets/js/html2canvas.min.js +10379 -10379
  219. package/invoice-template/assets/js/jquery.min.js +1 -1
  220. package/invoice-template/assets/sass/common/_color_variable.scss +12 -12
  221. package/invoice-template/assets/sass/common/_typography.scss +178 -178
  222. package/invoice-template/assets/sass/style.scss +12 -12
  223. package/migrations/finance-account-migration.js +97 -97
  224. package/migrations/finance-company-migration.js +29 -29
  225. package/migrations/finance-customer-migration.js +51 -51
  226. package/migrations/finance-document-item-migration.js +111 -111
  227. package/migrations/finance-document-migration.js +116 -116
  228. package/migrations/finance-payment-item-migration.js +52 -52
  229. package/migrations/finance-payment-method-migration.js +31 -31
  230. package/migrations/finance-payment-method-type-migration.js +55 -55
  231. package/migrations/finance-payment-migration.js +96 -96
  232. package/migrations/finance-post-history-migration.js +45 -45
  233. package/nest-cli.json +19 -19
  234. package/package.json +82 -82
  235. package/src/account/account.repository.ts +11 -11
  236. package/src/account/account.ts +271 -271
  237. package/src/account/interfaces/account-attr.interface.ts +31 -31
  238. package/src/account-system-entity/account-system-entity.ts +65 -65
  239. package/src/account-system-entity/post-history.repository.ts +11 -11
  240. package/src/config.ts +382 -382
  241. package/src/customer/customer.ts +299 -299
  242. package/src/customer/finance-customer.repository.ts +13 -13
  243. package/src/customer/interfaces/customer.repository.interface.ts +3 -3
  244. package/src/customer/interfaces/finance-customer-attr.interface.ts +10 -10
  245. package/src/customer/interfaces/finance-customer.repository.interface.ts +4 -4
  246. package/src/database.ts +15 -15
  247. package/src/document/document-item.repository.ts +11 -11
  248. package/src/document/document.repository.ts +11 -11
  249. package/src/document/document.ts +2 -2
  250. package/src/document/interfaces/document-attr.interface.ts +28 -28
  251. package/src/document/interfaces/document-item-attr.interface.ts +22 -22
  252. package/src/document/interfaces/document-item.repository.interface.ts +4 -4
  253. package/src/enum/doc-type.enum.ts +8 -8
  254. package/src/enum/index.ts +17 -17
  255. package/src/enum/payment-method.enum.ts +3 -3
  256. package/src/enum/payment-type.enum.ts +4 -4
  257. package/src/finance-company/finance-company.repository.ts +11 -11
  258. package/src/finance-company/finance-company.ts +1778 -1778
  259. package/src/helpers/typeof.ts +29 -29
  260. package/src/index.ts +32 -32
  261. package/src/interfaces/account-system.interface.ts +20 -20
  262. package/src/interfaces/index.ts +3 -3
  263. package/src/models/account.entity.ts +206 -206
  264. package/src/models/customer.entity.ts +93 -93
  265. package/src/models/document-item.entity.ts +143 -143
  266. package/src/models/document.entity.ts +211 -211
  267. package/src/models/finance-company.entity.ts +25 -25
  268. package/src/models/journal-entry.entity.ts +110 -110
  269. package/src/models/ledger-transaction.entity.ts +148 -148
  270. package/src/models/payment-item.entity.ts +60 -60
  271. package/src/models/payment-method-type.entity.ts +70 -70
  272. package/src/models/payment-method.entity.ts +51 -51
  273. package/src/models/payment.entity.ts +161 -161
  274. package/src/models/post-history.entity.ts +41 -41
  275. package/src/payment/interfaces/payment-attr.interface.ts +23 -23
  276. package/src/payment/interfaces/payment-params.interface.ts +8 -8
  277. package/src/payment/payment.repository.ts +11 -11
  278. package/src/payment/payment.ts +217 -217
  279. package/src/payment-item/interfaces/payment-item-attr.interface.ts +10 -10
  280. package/src/payment-item/payment-item.repository.ts +11 -11
  281. package/src/payment-item/payment-item.ts +128 -128
  282. package/src/payment-method/payment-method.repository.ts +11 -11
  283. package/src/payment-method-type/payment-method-type.repository.ts +11 -11
  284. package/src/test-document.ts +25 -25
  285. package/tsconfig.build.json +4 -4
  286. package/tsconfig.json +22 -22
  287. package/tslint.json +18 -18
@@ -1,1778 +1,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
-
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
+
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
+ }