@tomei/finance 0.5.5 → 0.5.6

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