@tomei/rental 0.17.4-dev.9 → 0.17.5

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 (298) hide show
  1. package/.commitlintrc.json +23 -23
  2. package/.gitlab-ci.yml +16 -16
  3. package/.husky/commit-msg +9 -9
  4. package/.husky/pre-commit +7 -7
  5. package/.prettierrc +4 -4
  6. package/Jenkinsfile +51 -51
  7. package/README.md +8 -8
  8. package/dist/ClassMappings/ItemClassMap.d.ts +4 -0
  9. package/dist/ClassMappings/ItemClassMap.js +8 -0
  10. package/dist/ClassMappings/ItemClassMap.js.map +1 -0
  11. package/dist/ClassMappings/index.d.ts +2 -0
  12. package/dist/ClassMappings/index.js +6 -0
  13. package/dist/ClassMappings/index.js.map +1 -0
  14. package/dist/components/agreement/agreement.d.ts +27 -0
  15. package/dist/components/agreement/agreement.js +120 -0
  16. package/dist/components/agreement/agreement.js.map +1 -0
  17. package/dist/components/agreement/agreement.repository.d.ts +8 -0
  18. package/dist/components/agreement/agreement.repository.js +52 -0
  19. package/dist/components/agreement/agreement.repository.js.map +1 -0
  20. package/dist/components/agreement-history/agreement-history.d.ts +17 -0
  21. package/dist/components/agreement-history/agreement-history.js +40 -0
  22. package/dist/components/agreement-history/agreement-history.js.map +1 -0
  23. package/dist/components/agreement-history/agreement-history.repository.d.ts +8 -0
  24. package/dist/components/agreement-history/agreement-history.repository.js +52 -0
  25. package/dist/components/agreement-history/agreement-history.repository.js.map +1 -0
  26. package/dist/components/agreement-signature/agreement-signature.d.ts +27 -0
  27. package/dist/components/agreement-signature/agreement-signature.js +99 -0
  28. package/dist/components/agreement-signature/agreement-signature.js.map +1 -0
  29. package/dist/components/agreement-signature/agreement-signature.repository.d.ts +8 -0
  30. package/dist/components/agreement-signature/agreement-signature.repository.js +53 -0
  31. package/dist/components/agreement-signature/agreement-signature.repository.js.map +1 -0
  32. package/dist/components/booking/booking.d.ts +46 -0
  33. package/dist/components/booking/booking.js +289 -0
  34. package/dist/components/booking/booking.js.map +1 -0
  35. package/dist/components/booking/booking.repository.d.ts +8 -0
  36. package/dist/components/booking/booking.repository.js +52 -0
  37. package/dist/components/booking/booking.repository.js.map +1 -0
  38. package/dist/components/hirer-change-request-new-hirer/hirer-change-request-new-hirer.d.ts +32 -0
  39. package/dist/components/hirer-change-request-new-hirer/hirer-change-request-new-hirer.js +106 -0
  40. package/dist/components/hirer-change-request-new-hirer/hirer-change-request-new-hirer.js.map +1 -0
  41. package/dist/components/hirer-change-request-new-hirer/hirer-change-request-new-hirer.repository.d.ts +9 -0
  42. package/dist/components/hirer-change-request-new-hirer/hirer-change-request-new-hirer.repository.js +62 -0
  43. package/dist/components/hirer-change-request-new-hirer/hirer-change-request-new-hirer.repository.js.map +1 -0
  44. package/dist/components/hirer-change-request-remove-hirer/hirer-change-request-remove-hirer.d.ts +22 -0
  45. package/dist/components/hirer-change-request-remove-hirer/hirer-change-request-remove-hirer.js +89 -0
  46. package/dist/components/hirer-change-request-remove-hirer/hirer-change-request-remove-hirer.js.map +1 -0
  47. package/dist/components/hirer-change-request-remove-hirer/hirer-change-request-remove-hirer.repository.d.ts +9 -0
  48. package/dist/components/hirer-change-request-remove-hirer/hirer-change-request-remove-hirer.repository.js +63 -0
  49. package/dist/components/hirer-change-request-remove-hirer/hirer-change-request-remove-hirer.repository.js.map +1 -0
  50. package/dist/components/hirer-change-request-signature/hirer-change-request-signature.d.ts +30 -0
  51. package/dist/components/hirer-change-request-signature/hirer-change-request-signature.js +208 -0
  52. package/dist/components/hirer-change-request-signature/hirer-change-request-signature.js.map +1 -0
  53. package/dist/components/hirer-change-request-signature/hirer-change-request-signature.repository.d.ts +9 -0
  54. package/dist/components/hirer-change-request-signature/hirer-change-request-signature.repository.js +63 -0
  55. package/dist/components/hirer-change-request-signature/hirer-change-request-signature.repository.js.map +1 -0
  56. package/dist/components/joint-hirer/joint-hirer.d.ts +26 -0
  57. package/dist/components/joint-hirer/joint-hirer.js +137 -0
  58. package/dist/components/joint-hirer/joint-hirer.js.map +1 -0
  59. package/dist/components/joint-hirer/joint-hirer.repository.d.ts +8 -0
  60. package/dist/components/joint-hirer/joint-hirer.repository.js +52 -0
  61. package/dist/components/joint-hirer/joint-hirer.repository.js.map +1 -0
  62. package/dist/components/rental/rental.d.ts +72 -0
  63. package/dist/components/rental/rental.js +844 -0
  64. package/dist/components/rental/rental.js.map +1 -0
  65. package/dist/components/rental/rental.repository.d.ts +8 -0
  66. package/dist/components/rental/rental.repository.js +52 -0
  67. package/dist/components/rental/rental.repository.js.map +1 -0
  68. package/dist/components/rental-hirer-change-request/rental-hirer-change-request.d.ts +71 -0
  69. package/dist/components/rental-hirer-change-request/rental-hirer-change-request.js +531 -0
  70. package/dist/components/rental-hirer-change-request/rental-hirer-change-request.js.map +1 -0
  71. package/dist/components/rental-hirer-change-request/rental-hirer-change-request.repository.d.ts +9 -0
  72. package/dist/components/rental-hirer-change-request/rental-hirer-change-request.repository.js +62 -0
  73. package/dist/components/rental-hirer-change-request/rental-hirer-change-request.repository.js.map +1 -0
  74. package/dist/components/rental-price/rental-price.d.ts +18 -0
  75. package/dist/components/rental-price/rental-price.js +66 -0
  76. package/dist/components/rental-price/rental-price.js.map +1 -0
  77. package/dist/components/rental-price/rental-price.repository.d.ts +8 -0
  78. package/dist/components/rental-price/rental-price.repository.js +52 -0
  79. package/dist/components/rental-price/rental-price.repository.js.map +1 -0
  80. package/dist/database.d.ts +4 -0
  81. package/dist/database.js +37 -0
  82. package/dist/database.js.map +1 -0
  83. package/dist/enum/account-type.enum.d.ts +4 -0
  84. package/dist/enum/account-type.enum.js +9 -0
  85. package/dist/enum/account-type.enum.js.map +1 -0
  86. package/dist/enum/aggrement-status.enum.d.ts +5 -0
  87. package/dist/enum/aggrement-status.enum.js +10 -0
  88. package/dist/enum/aggrement-status.enum.js.map +1 -0
  89. package/dist/enum/agreement-signature-status.enum.d.ts +4 -0
  90. package/dist/enum/agreement-signature-status.enum.js +9 -0
  91. package/dist/enum/agreement-signature-status.enum.js.map +1 -0
  92. package/dist/enum/agreement-signature-verification-method.enum.d.ts +4 -0
  93. package/dist/enum/agreement-signature-verification-method.enum.js +9 -0
  94. package/dist/enum/agreement-signature-verification-method.enum.js.map +1 -0
  95. package/dist/enum/booking.enum.d.ts +5 -0
  96. package/dist/enum/booking.enum.js +10 -0
  97. package/dist/enum/booking.enum.js.map +1 -0
  98. package/dist/enum/hirer-type.enum.d.ts +4 -0
  99. package/dist/enum/hirer-type.enum.js +9 -0
  100. package/dist/enum/hirer-type.enum.js.map +1 -0
  101. package/dist/enum/index.d.ts +11 -0
  102. package/dist/enum/index.js +24 -0
  103. package/dist/enum/index.js.map +1 -0
  104. package/dist/enum/rental-hirer-change-request-hirer-role.d.ts +4 -0
  105. package/dist/enum/rental-hirer-change-request-hirer-role.js +9 -0
  106. package/dist/enum/rental-hirer-change-request-hirer-role.js.map +1 -0
  107. package/dist/enum/rental-hirer-change-request-status.d.ts +7 -0
  108. package/dist/enum/rental-hirer-change-request-status.js +12 -0
  109. package/dist/enum/rental-hirer-change-request-status.js.map +1 -0
  110. package/dist/enum/rental-hirer-change-request-type.d.ts +4 -0
  111. package/dist/enum/rental-hirer-change-request-type.js +9 -0
  112. package/dist/enum/rental-hirer-change-request-type.js.map +1 -0
  113. package/dist/enum/rental-status.enum.d.ts +9 -0
  114. package/dist/enum/rental-status.enum.js +14 -0
  115. package/dist/enum/rental-status.enum.js.map +1 -0
  116. package/dist/interfaces/agreemeent-signature-attr.interface.d.ts +14 -0
  117. package/dist/interfaces/agreemeent-signature-attr.interface.js +3 -0
  118. package/dist/interfaces/agreemeent-signature-attr.interface.js.map +1 -0
  119. package/dist/interfaces/agreement-attr.interface.d.ts +7 -0
  120. package/dist/interfaces/agreement-attr.interface.js +3 -0
  121. package/dist/interfaces/agreement-attr.interface.js.map +1 -0
  122. package/dist/interfaces/agreement-history-attr.interface.d.ts +7 -0
  123. package/dist/interfaces/agreement-history-attr.interface.js +3 -0
  124. package/dist/interfaces/agreement-history-attr.interface.js.map +1 -0
  125. package/dist/interfaces/booking-attr.interface.d.ts +18 -0
  126. package/dist/interfaces/booking-attr.interface.js +3 -0
  127. package/dist/interfaces/booking-attr.interface.js.map +1 -0
  128. package/dist/interfaces/booking-find-all-search-attr.interface.d.ts +12 -0
  129. package/dist/interfaces/booking-find-all-search-attr.interface.js +3 -0
  130. package/dist/interfaces/booking-find-all-search-attr.interface.js.map +1 -0
  131. package/dist/interfaces/hirer-change-request-new-hirer-attr.interface.d.ts +15 -0
  132. package/dist/interfaces/hirer-change-request-new-hirer-attr.interface.js +3 -0
  133. package/dist/interfaces/hirer-change-request-new-hirer-attr.interface.js.map +1 -0
  134. package/dist/interfaces/hirer-change-request-remove-hirer-attr.interface.d.ts +5 -0
  135. package/dist/interfaces/hirer-change-request-remove-hirer-attr.interface.js +3 -0
  136. package/dist/interfaces/hirer-change-request-remove-hirer-attr.interface.js.map +1 -0
  137. package/dist/interfaces/hirer-change-request-signature-attr.interface.d.ts +14 -0
  138. package/dist/interfaces/hirer-change-request-signature-attr.interface.js +3 -0
  139. package/dist/interfaces/hirer-change-request-signature-attr.interface.js.map +1 -0
  140. package/dist/interfaces/index.d.ts +14 -0
  141. package/dist/interfaces/index.js +3 -0
  142. package/dist/interfaces/index.js.map +1 -0
  143. package/dist/interfaces/joint-hirer-attr.interface.d.ts +11 -0
  144. package/dist/interfaces/joint-hirer-attr.interface.js +3 -0
  145. package/dist/interfaces/joint-hirer-attr.interface.js.map +1 -0
  146. package/dist/interfaces/rental-attr.interface.d.ts +24 -0
  147. package/dist/interfaces/rental-attr.interface.js +3 -0
  148. package/dist/interfaces/rental-attr.interface.js.map +1 -0
  149. package/dist/interfaces/rental-find-all-search-attr.interface.d.ts +10 -0
  150. package/dist/interfaces/rental-find-all-search-attr.interface.js +3 -0
  151. package/dist/interfaces/rental-find-all-search-attr.interface.js.map +1 -0
  152. package/dist/interfaces/rental-hirer-change-request.attr.interface.d.ts +16 -0
  153. package/dist/interfaces/rental-hirer-change-request.attr.interface.js +3 -0
  154. package/dist/interfaces/rental-hirer-change-request.attr.interface.js.map +1 -0
  155. package/dist/interfaces/rental-hirer-change-request.update.interface.d.ts +4 -0
  156. package/dist/interfaces/rental-hirer-change-request.update.interface.js +3 -0
  157. package/dist/interfaces/rental-hirer-change-request.update.interface.js.map +1 -0
  158. package/dist/interfaces/rental-price-attr.interface.d.ts +7 -0
  159. package/dist/interfaces/rental-price-attr.interface.js +3 -0
  160. package/dist/interfaces/rental-price-attr.interface.js.map +1 -0
  161. package/dist/interfaces/response-hirer-signature-attr.interface.d.ts +14 -0
  162. package/dist/interfaces/response-hirer-signature-attr.interface.js +3 -0
  163. package/dist/interfaces/response-hirer-signature-attr.interface.js.map +1 -0
  164. package/dist/models/agreement-history.entity.d.ts +10 -0
  165. package/dist/models/agreement-history.entity.js +65 -0
  166. package/dist/models/agreement-history.entity.js.map +1 -0
  167. package/dist/models/agreement-signature.entity.d.ts +22 -0
  168. package/dist/models/agreement-signature.entity.js +123 -0
  169. package/dist/models/agreement-signature.entity.js.map +1 -0
  170. package/dist/models/agreement.entity.d.ts +14 -0
  171. package/dist/models/agreement.entity.js +70 -0
  172. package/dist/models/agreement.entity.js.map +1 -0
  173. package/dist/models/booking.entity.d.ts +21 -0
  174. package/dist/models/booking.entity.js +128 -0
  175. package/dist/models/booking.entity.js.map +1 -0
  176. package/dist/models/hirer-change-request-new-hirer.entity.d.ts +19 -0
  177. package/dist/models/hirer-change-request-new-hirer.entity.js +121 -0
  178. package/dist/models/hirer-change-request-new-hirer.entity.js.map +1 -0
  179. package/dist/models/hirer-change-request-remove-hirer.entity.d.ts +11 -0
  180. package/dist/models/hirer-change-request-remove-hirer.entity.js +57 -0
  181. package/dist/models/hirer-change-request-remove-hirer.entity.js.map +1 -0
  182. package/dist/models/hirer-change-request-signature.entity.d.ts +18 -0
  183. package/dist/models/hirer-change-request-signature.entity.js +101 -0
  184. package/dist/models/hirer-change-request-signature.entity.js.map +1 -0
  185. package/dist/models/index.d.ts +12 -0
  186. package/dist/models/index.js +26 -0
  187. package/dist/models/index.js.map +1 -0
  188. package/dist/models/joint-hirer.entity.d.ts +14 -0
  189. package/dist/models/joint-hirer.entity.js +91 -0
  190. package/dist/models/joint-hirer.entity.js.map +1 -0
  191. package/dist/models/rental-hirer-change-request.entity.d.ts +22 -0
  192. package/dist/models/rental-hirer-change-request.entity.js +108 -0
  193. package/dist/models/rental-hirer-change-request.entity.js.map +1 -0
  194. package/dist/models/rental-price.entity.d.ts +8 -0
  195. package/dist/models/rental-price.entity.js +59 -0
  196. package/dist/models/rental-price.entity.js.map +1 -0
  197. package/dist/models/rental.entity.d.ts +29 -0
  198. package/dist/models/rental.entity.js +160 -0
  199. package/dist/models/rental.entity.js.map +1 -0
  200. package/dist/src/components/agreement/agreement.js +9 -9
  201. package/dist/src/components/joint-hirer/joint-hirer.js +1 -1
  202. package/dist/src/components/joint-hirer/joint-hirer.js.map +1 -1
  203. package/dist/src/components/rental/rental.d.ts +2 -1
  204. package/dist/src/components/rental/rental.js +19 -17
  205. package/dist/src/components/rental/rental.js.map +1 -1
  206. package/dist/src/components/rental-hirer-change-request/rental-hirer-change-request.js.map +1 -1
  207. package/dist/src/enum/agreement-signature-verification-method.enum.d.ts +4 -0
  208. package/dist/src/enum/agreement-signature-verification-method.enum.js +9 -0
  209. package/dist/src/enum/agreement-signature-verification-method.enum.js.map +1 -0
  210. package/dist/src/enum/index.d.ts +2 -1
  211. package/dist/src/enum/index.js +3 -1
  212. package/dist/src/enum/index.js.map +1 -1
  213. package/dist/src/models/agreement-signature.entity.d.ts +4 -0
  214. package/dist/src/models/agreement-signature.entity.js +22 -0
  215. package/dist/src/models/agreement-signature.entity.js.map +1 -1
  216. package/dist/tsconfig.build.tsbuildinfo +1 -0
  217. package/dist/tsconfig.tsbuildinfo +1 -1
  218. package/eslint.config.mjs +58 -58
  219. package/jest.config.js +10 -10
  220. package/migrations/20250529092130-add-status-to-joint-hirer.js +19 -19
  221. package/migrations/agreement-signature-table-migration.js +76 -64
  222. package/migrations/booking-table-migration.js +79 -79
  223. package/migrations/hirer-change-request-new-hirer-migration.js +72 -72
  224. package/migrations/hirer-change-request-remove-hirer-migration.js +39 -39
  225. package/migrations/hirer-change-request-signature-migration.js +65 -65
  226. package/migrations/joint-hirer-table-migration.js +52 -52
  227. package/migrations/rental-aggreement-history-migration.js +41 -41
  228. package/migrations/rental-aggrement-table-migration.js +30 -30
  229. package/migrations/rental-hirer-change-request-migrations.js +64 -64
  230. package/migrations/rental-price-table-migration.js +32 -32
  231. package/migrations/rental-table-migrations.js +96 -96
  232. package/package.json +80 -80
  233. package/sonar-project.properties +12 -12
  234. package/src/ClassMappings/ItemClassMap.ts +7 -7
  235. package/src/ClassMappings/index.ts +3 -3
  236. package/src/components/agreement/agreement.repository.ts +54 -54
  237. package/src/components/agreement/agreement.ts +187 -187
  238. package/src/components/agreement-history/agreement-history.repository.ts +54 -54
  239. package/src/components/agreement-history/agreement-history.ts +57 -57
  240. package/src/components/agreement-signature/agreement-signature.repository.ts +55 -55
  241. package/src/components/agreement-signature/agreement-signature.ts +143 -143
  242. package/src/components/booking/booking.repository.ts +51 -51
  243. package/src/components/booking/booking.ts +492 -492
  244. package/src/components/hirer-change-request-new-hirer/hirer-change-request-new-hirer.repository.ts +64 -64
  245. package/src/components/hirer-change-request-new-hirer/hirer-change-request-new-hirer.ts +153 -153
  246. package/src/components/hirer-change-request-remove-hirer/hirer-change-request-remove-hirer.repository.ts +65 -65
  247. package/src/components/hirer-change-request-remove-hirer/hirer-change-request-remove-hirer.ts +134 -134
  248. package/src/components/hirer-change-request-signature/hirer-change-request-signature.repository.ts +65 -65
  249. package/src/components/hirer-change-request-signature/hirer-change-request-signature.ts +272 -272
  250. package/src/components/joint-hirer/joint-hirer.repository.ts +54 -54
  251. package/src/components/joint-hirer/joint-hirer.ts +252 -252
  252. package/src/components/rental/rental.repository.ts +51 -51
  253. package/src/components/rental/rental.ts +1466 -1461
  254. package/src/components/rental-hirer-change-request/rental-hirer-change-request.repository.ts +64 -64
  255. package/src/components/rental-hirer-change-request/rental-hirer-change-request.ts +907 -930
  256. package/src/components/rental-price/rental-price.repository.ts +54 -54
  257. package/src/components/rental-price/rental-price.ts +100 -100
  258. package/src/database.ts +39 -39
  259. package/src/enum/account-type.enum.ts +4 -4
  260. package/src/enum/agreement-signature-status.enum.ts +4 -4
  261. package/src/enum/agreement-signature-verification-method.enum.ts +4 -0
  262. package/src/enum/booking.enum.ts +5 -5
  263. package/src/enum/hirer-type.enum.ts +4 -4
  264. package/src/enum/index.ts +23 -21
  265. package/src/enum/rental-hirer-change-request-hirer-role.ts +4 -4
  266. package/src/enum/rental-hirer-change-request-status.ts +7 -7
  267. package/src/enum/rental-hirer-change-request-type.ts +4 -4
  268. package/src/enum/rental-status.enum.ts +39 -39
  269. package/src/index.ts +54 -54
  270. package/src/interfaces/agreemeent-signature-attr.interface.ts +15 -15
  271. package/src/interfaces/agreement-attr.interface.ts +7 -7
  272. package/src/interfaces/agreement-history-attr.interface.ts +7 -7
  273. package/src/interfaces/booking-attr.interface.ts +19 -19
  274. package/src/interfaces/booking-find-all-search-attr.interface.ts +12 -12
  275. package/src/interfaces/hirer-change-request-new-hirer-attr.interface.ts +15 -15
  276. package/src/interfaces/hirer-change-request-remove-hirer-attr.interface.ts +5 -5
  277. package/src/interfaces/hirer-change-request-signature-attr.interface.ts +15 -15
  278. package/src/interfaces/index.ts +29 -29
  279. package/src/interfaces/joint-hirer-attr.interface.ts +11 -11
  280. package/src/interfaces/rental-attr.interface.ts +25 -25
  281. package/src/interfaces/rental-find-all-search-attr.interface.ts +11 -11
  282. package/src/interfaces/rental-hirer-change-request.attr.interface.ts +17 -17
  283. package/src/interfaces/rental-hirer-change-request.update.interface.ts +4 -4
  284. package/src/interfaces/rental-price-attr.interface.ts +7 -7
  285. package/src/interfaces/response-hirer-signature-attr.interface.ts +15 -15
  286. package/src/models/agreement-history.entity.ts +51 -51
  287. package/src/models/agreement-signature.entity.ts +105 -86
  288. package/src/models/agreement.entity.ts +47 -47
  289. package/src/models/booking.entity.ts +105 -105
  290. package/src/models/hirer-change-request-new-hirer.entity.ts +102 -102
  291. package/src/models/hirer-change-request-remove-hirer.entity.ts +47 -47
  292. package/src/models/hirer-change-request-signature.entity.ts +86 -86
  293. package/src/models/index.ts +25 -25
  294. package/src/models/joint-hirer.entity.ts +70 -70
  295. package/src/models/rental-price.entity.ts +38 -38
  296. package/src/models/rental.entity.ts +133 -133
  297. package/tsconfig.build.json +5 -5
  298. package/tsconfig.json +24 -24
@@ -1,1461 +1,1466 @@
1
- import { IRentalAttr } from '../../interfaces/rental-attr.interface';
2
- import { RentalStatusEnum } from '../../enum/rental-status.enum';
3
- import { RentalRepository } from './rental.repository';
4
- import { ClassError, ObjectBase } from '@tomei/general';
5
- import { ApplicationConfig } from '@tomei/config';
6
- import { LoginUser } from '@tomei/sso';
7
- import { RentalPrice } from '../rental-price/rental-price';
8
- import { Op, QueryTypes } from 'sequelize';
9
- import { ActionEnum, Activity } from '@tomei/activity-history';
10
- import { IRentalFindAllSearchAttr } from '../../interfaces/rental-find-all-search-attr.interface';
11
- import { RentalAccountTypeEnum } from '../../enum/account-type.enum';
12
- import { JointHirer } from '../joint-hirer/joint-hirer';
13
- import { JointHirerModel } from '../../models/joint-hirer.entity';
14
- import { AgreementRepository } from '../agreement/agreement.repository';
15
- import * as rentalDb from '../../database';
16
- import { RentalModel } from '../../models/rental.entity';
17
- import { JointHirerRepository } from '../joint-hirer/joint-hirer.repository';
18
- import { AgreementModel } from '../../models';
19
- import { Agreement } from '../agreement/agreement';
20
- import { AggrementStatusEnum } from '../../enum/aggrement-status.enum';
21
- import { AgreementSignatureRepository } from '../agreement-signature/agreement-signature.repository';
22
- import { AgreementSignatureStatusEnum } from '../../enum/agreement-signature-status.enum';
23
- import { HirerTypeEnum } from '../../enum/hirer-type.enum';
24
- import { AgreementHistoryRepository } from '../agreement-history/agreement-history.repository';
25
- import { DocType, Document, IAccountSystem } from '@tomei/finance';
26
- import { ItemClassMap } from '../../ClassMappings/ItemClassMap';
27
-
28
- export class Rental extends ObjectBase {
29
- ObjectId: string;
30
- ObjectName: string;
31
- ObjectType = 'Rental';
32
- TableName: string;
33
- CustomerId: string;
34
- CustomerType: string;
35
- ItemId: string;
36
- ItemType: string;
37
- PriceId: string;
38
- StartDateTime: Date;
39
- EndDateTime: Date;
40
- CancelRemarks: string;
41
- TerminateRemarks: string;
42
- AgreementNo: string;
43
- AccountType: RentalAccountTypeEnum;
44
- JointHirers: JointHirer[] = [];
45
- Invoices: Document[] = [];
46
- Item: any;
47
- protected _Status: RentalStatusEnum | string;
48
- protected _EscheatmentYN: string = 'N';
49
- protected _CreatedById: string;
50
- protected _CreatedAt: Date;
51
- protected _UpdatedById: string;
52
- protected _UpdatedAt: Date;
53
- protected static _Repo = new RentalRepository();
54
- protected static _AgreementRepo = new AgreementRepository();
55
- protected static _JointHirerRepo = new JointHirerRepository();
56
- protected static _AgreementSignatureRepo = new AgreementSignatureRepository();
57
- protected static _AgreementHistoryRepo = new AgreementHistoryRepository();
58
-
59
- get RentalId(): string {
60
- return this.ObjectId;
61
- }
62
-
63
- set RentalId(value: string) {
64
- this.ObjectId = value;
65
- }
66
-
67
- get Status(): RentalStatusEnum | string {
68
- return this._Status;
69
- }
70
-
71
- get EscheatmentYN(): string {
72
- return this._EscheatmentYN;
73
- }
74
-
75
- get CreatedById(): string {
76
- return this._CreatedById;
77
- }
78
-
79
- get CreatedAt(): Date {
80
- return this._CreatedAt;
81
- }
82
-
83
- get UpdatedById(): string {
84
- return this._UpdatedById;
85
- }
86
-
87
- get UpdatedAt(): Date {
88
- return this._UpdatedAt;
89
- }
90
-
91
- private setTerminated() {
92
- this._Status = RentalStatusEnum.TERMINATED;
93
- }
94
-
95
- protected constructor(rentalAttr?: IRentalAttr) {
96
- super();
97
- if (rentalAttr) {
98
- this.RentalId = rentalAttr.RentalId;
99
- this.CustomerId = rentalAttr.CustomerId;
100
- this.CustomerType = rentalAttr.CustomerType;
101
- this.ItemId = rentalAttr.ItemId;
102
- this.ItemType = rentalAttr.ItemType;
103
- this.PriceId = rentalAttr.PriceId;
104
- this.StartDateTime = rentalAttr.StartDateTime;
105
- this.EndDateTime = rentalAttr.EndDateTime;
106
- this.CancelRemarks = rentalAttr.CancelRemarks;
107
- this.TerminateRemarks = rentalAttr.TerminateRemarks;
108
- this.AgreementNo = rentalAttr.AgreementNo;
109
- this.AccountType = rentalAttr.AccountType;
110
- this._Status = rentalAttr.Status;
111
- this._EscheatmentYN = rentalAttr.EscheatmentYN;
112
- this._CreatedById = rentalAttr.CreatedById;
113
- this._CreatedAt = rentalAttr.CreatedAt;
114
- this._UpdatedById = rentalAttr.UpdatedById;
115
- this._UpdatedAt = rentalAttr.UpdatedAt;
116
- }
117
- }
118
-
119
- public static async init(dbTransaction?: any, rentalId?: string) {
120
- try {
121
- if (rentalId) {
122
- const rental = await Rental._Repo.findByPk(rentalId, dbTransaction);
123
- if (rental) {
124
- return new Rental(rental);
125
- } else {
126
- throw new ClassError('Rental', 'RentalErrMsg00', 'Rental Not Found');
127
- }
128
- }
129
- return new Rental();
130
- } catch (error) {
131
- console.error('Error initializing Rental:', error);
132
- throw new ClassError(
133
- 'Rental',
134
- 'RentalErrMsg00',
135
- 'Failed To Initialize Rental',
136
- );
137
- }
138
- }
139
-
140
- /**
141
- * Create a new Rental record.
142
- * @param {RentalPrice} rentalPrice - The rental pricing information.
143
- * @param {LoginUser} loginUser - The user initiating the creation.
144
- * @param {any} [dbTransaction] - Optional database transaction for atomic operations.
145
- * @throws {ClassError} Throws an error if:
146
- * 1. loginUser does not have 'Rental - Create' privilege.
147
- * 2. Rental item is not available at the current date.
148
- * @returns {Promise<any>} A Promise resolving to the created rental record.
149
- */
150
- public async create(
151
- rentalPrice: RentalPrice,
152
- loginUser: LoginUser,
153
- jointHirers?: JointHirer[],
154
- dbTransaction?: any,
155
- ): Promise<any> {
156
- try {
157
- /*Part 1: Check Privilege*/
158
- const systemCode =
159
- ApplicationConfig.getComponentConfigValue('system-code');
160
- const isPrivileged = await loginUser.checkPrivileges(
161
- systemCode,
162
- 'Rental - Create',
163
- );
164
-
165
- if (!isPrivileged) {
166
- throw new ClassError(
167
- 'Rental',
168
- 'RentalErrMsg01',
169
- "You do not have 'Rental - Create' privilege.",
170
- );
171
- }
172
-
173
- /*Part 2: Make Sure Rental Item Available*/
174
- const isItemAvailable = await Rental.isItemAvailable(
175
- this.ItemId,
176
- this.ItemType,
177
- this.StartDateTime,
178
- this.EndDateTime,
179
- dbTransaction,
180
- );
181
-
182
- if (!isItemAvailable) {
183
- throw new ClassError(
184
- 'Rental',
185
- 'RentalErrMsg02',
186
- 'Rental Item is not available at current date.',
187
- );
188
- }
189
-
190
- // Part 3: Create Rental Agreement Record
191
- // Call Rental._AgreementRepo create method by passing:
192
- // AgreementNo: this.AgreementNo
193
- // Status: "Not Generated"
194
- // dbTransaction
195
- await Rental._AgreementRepo.create(
196
- {
197
- AgreementNo: this.AgreementNo,
198
- Status: 'Not Generated',
199
- },
200
- {
201
- transaction: dbTransaction,
202
- },
203
- );
204
-
205
- //Create a record into rental_AgreementSignature table
206
- //Create the main customer's signature record
207
- await Rental._AgreementSignatureRepo.create(
208
- {
209
- SignatureId: this.createId(),
210
- AgreementNo: this.AgreementNo,
211
- Party: HirerTypeEnum.PRIMARY,
212
- PartyId: this.CustomerId,
213
- PartyType: 'Customer',
214
- SignatureStatus: AgreementSignatureStatusEnum.PENDING,
215
- SignedAt: null,
216
- CreatedById: loginUser.ObjectId,
217
- CreatedAt: new Date(),
218
- UpdatedById: loginUser.ObjectId,
219
- UpdatedAt: new Date(),
220
- },
221
- { transaction: dbTransaction },
222
- );
223
-
224
- // Create signatures record for joint hirers if any
225
- if (jointHirers && jointHirers.length > 0) {
226
- for (const jointHirer of jointHirers) {
227
- await Rental._AgreementSignatureRepo.create(
228
- {
229
- SignatureId: this.createId(),
230
- AgreementNo: this.AgreementNo,
231
- Party: HirerTypeEnum.JOINT,
232
- PartyId: jointHirer.CustomerId,
233
- PartyType: 'Customer',
234
- SignatureStatus: AgreementSignatureStatusEnum.PENDING,
235
- SignedAt: null,
236
- CreatedById: loginUser.ObjectId,
237
- CreatedAt: new Date(),
238
- UpdatedById: loginUser.ObjectId,
239
- UpdatedAt: new Date(),
240
- },
241
- { transaction: dbTransaction },
242
- );
243
- }
244
- }
245
-
246
- /*Part 4: Insert Rental & The Agreed Rental Price*/
247
- if (!rentalPrice.PriceId) {
248
- const rentalPriceData = await rentalPrice.create(
249
- loginUser,
250
- dbTransaction,
251
- );
252
- this.PriceId = rentalPriceData.PriceId;
253
- } else {
254
- this.PriceId = rentalPrice.PriceId;
255
- }
256
- this.RentalId = this.createId();
257
- // if (!this.Status) {
258
- this._Status = RentalStatusEnum.PENDING_SIGNING;
259
- // }
260
- this._CreatedById = loginUser.ObjectId;
261
- this._UpdatedById = loginUser.ObjectId;
262
- this._CreatedAt = new Date();
263
- this._UpdatedAt = new Date();
264
-
265
- const data = {
266
- RentalId: this.RentalId,
267
- CustomerId: this.CustomerId,
268
- CustomerType: this.CustomerType,
269
- ItemId: this.ItemId,
270
- ItemType: this.ItemType,
271
- PriceId: this.PriceId,
272
- StartDateTime: this.StartDateTime,
273
- EndDateTime: this.EndDateTime,
274
- CancelRemarks: this.CancelRemarks,
275
- TerminateRemarks: this.TerminateRemarks,
276
- AgreementNo: this.AgreementNo,
277
- AccountType: this.AccountType,
278
- Status: this.Status,
279
- EscheatmentYN: this.EscheatmentYN,
280
- CreatedById: this.CreatedById,
281
- CreatedAt: this.CreatedAt,
282
- UpdatedById: this.UpdatedById,
283
- UpdatedAt: this.UpdatedAt,
284
- };
285
-
286
- await Rental._Repo.create(data, {
287
- transaction: dbTransaction,
288
- });
289
-
290
- //For every data inside Param.jointHirers, update the rentalId and call jointHirer.create
291
- if (jointHirers) {
292
- for (let i = 0; i < jointHirers.length; i++) {
293
- jointHirers[i].RentalId = this.RentalId;
294
- await jointHirers[i].create(loginUser, dbTransaction);
295
- this.JointHirers.push(jointHirers[i]);
296
- }
297
- }
298
-
299
- /*Part 5: Record Create Rental Activity*/
300
- const activity = new Activity();
301
- activity.ActivityId = activity.createId();
302
- activity.Action = ActionEnum.CREATE;
303
- activity.Description = 'Add Rental';
304
- activity.EntityType = 'Rental';
305
- activity.EntityId = this.RentalId;
306
- activity.EntityValueBefore = JSON.stringify({});
307
- activity.EntityValueAfter = JSON.stringify(data);
308
- await activity.create(loginUser.ObjectId, dbTransaction);
309
-
310
- /*Part 6: Return Result*/
311
- return this;
312
- } catch (error) {
313
- throw error;
314
- }
315
- }
316
-
317
- public static async isItemAvailable(
318
- itemId: string,
319
- itemType: string,
320
- startDateTime: Date,
321
- endDateTime: Date,
322
- dbTransaction?: any,
323
- ) {
324
- try {
325
- const rental = await Rental._Repo.findOne({
326
- where: {
327
- ItemId: itemId,
328
- ItemType: itemType,
329
- StartDateTime: {
330
- [Op.lte]: endDateTime,
331
- },
332
- EndDateTime: {
333
- [Op.gte]: startDateTime,
334
- },
335
- },
336
- transaction: dbTransaction,
337
- });
338
-
339
- if (!rental) {
340
- // No rental found → item is available
341
- return true;
342
- }
343
-
344
- if (
345
- rental.Status === RentalStatusEnum.TERMINATED ||
346
- rental.Status === RentalStatusEnum.CANCELLED
347
- ) {
348
- // Rental found but status is Terminated or Cancelled → item is available
349
- return true;
350
- }
351
-
352
- // Rental exists and is active → item is not available
353
- return false;
354
- } catch (error) {
355
- throw error;
356
- }
357
- }
358
-
359
- public static async findAll(
360
- loginUser: LoginUser,
361
- dbTransaction: any,
362
- page?: number,
363
- row?: number,
364
- search?: IRentalFindAllSearchAttr,
365
- ) {
366
- try {
367
- const systemCode =
368
- await ApplicationConfig.getComponentConfigValue('system-code');
369
-
370
- const isPrivileged = await loginUser.checkPrivileges(
371
- systemCode,
372
- 'Rental - View',
373
- );
374
-
375
- if (!isPrivileged) {
376
- throw new ClassError(
377
- 'Rental',
378
- 'RentalErrMsg01',
379
- "You do not have 'Rental - View' privilege.",
380
- );
381
- }
382
-
383
- const queryObj: any = {};
384
-
385
- let options: any = {
386
- transaction: dbTransaction,
387
- order: [['CreatedAt', 'DESC']],
388
- };
389
-
390
- if (page && row) {
391
- options = {
392
- ...options,
393
- limit: row,
394
- offset: row * (page - 1),
395
- };
396
- }
397
-
398
- if (search) {
399
- Object.entries(search).forEach(([key, value]) => {
400
- if (key === 'StartDateTime') {
401
- queryObj[key] = {
402
- [Op.gte]: value,
403
- };
404
- } else if (key === 'EndDateTime') {
405
- queryObj[key] = {
406
- [Op.lte]: value,
407
- };
408
- } else if (key === 'CustomerId') {
409
- queryObj[key] = {
410
- [Op.substring]: value,
411
- };
412
-
413
- options.include = [
414
- {
415
- model: JointHirerModel,
416
- required: false,
417
- where: {
418
- CustomerId: {
419
- [Op.substring]: value,
420
- },
421
- },
422
- },
423
- ];
424
- } else {
425
- queryObj[key] = {
426
- [Op.substring]: value,
427
- };
428
- }
429
- });
430
- if (options?.include?.length > 1) {
431
- options.include.push({
432
- model: AgreementModel,
433
- required: false,
434
- });
435
- } else {
436
- options.include = [
437
- {
438
- model: AgreementModel,
439
- required: false,
440
- },
441
- ];
442
- }
443
-
444
- options = {
445
- ...options,
446
- where: queryObj,
447
- };
448
- }
449
-
450
- return await Rental._Repo.findAndCountAll(options);
451
- } catch (err) {
452
- throw err;
453
- }
454
- }
455
-
456
- public static async checkActiveByItemId(
457
- loginUser: LoginUser,
458
- itemId: string,
459
- itemType: string,
460
- dbTransaction?: any,
461
- ) {
462
- try {
463
- const systemCode =
464
- await ApplicationConfig.getComponentConfigValue('system-code');
465
-
466
- const isPrivileged = await loginUser.checkPrivileges(
467
- systemCode,
468
- 'Rental - View',
469
- );
470
-
471
- if (!isPrivileged) {
472
- throw new ClassError(
473
- 'Rental',
474
- 'RentalErrMsg01',
475
- "You do not have 'Rental - View' privilege.",
476
- );
477
- }
478
-
479
- const queryObj: any = {
480
- ItemId: itemId,
481
- ItemType: itemType,
482
- Status: RentalStatusEnum.ACTIVE,
483
- };
484
-
485
- const options: any = {
486
- transaction: dbTransaction,
487
- where: queryObj,
488
- };
489
-
490
- const rental = await Rental._Repo.findOne(options);
491
-
492
- if (rental) {
493
- return true;
494
- } else {
495
- return false;
496
- }
497
- } catch (err) {
498
- throw err;
499
- }
500
- }
501
-
502
- /**
503
- * Sets the StartDateTime property of the Rental class as custom setter.
504
- * @param {Date} startDateTime - The start date and time of the rental.
505
- * @throws {ClassError} Throws an error if:
506
- * 1. startDateTime is a past date.
507
- * 2. startDateTime is more than the EndDateTime.
508
- * @returns {void}
509
- */
510
- setStartDateTime(startDateTime: Date): void {
511
- const startDateTimeObject = new Date(startDateTime);
512
- startDateTimeObject.setHours(0, 0, 0, 0);
513
-
514
- /*Part 1: Make Sure Future Date Time*/
515
- if (startDateTimeObject < new Date(new Date().setHours(0, 0, 0, 0))) {
516
- throw new ClassError(
517
- 'Rental',
518
- 'RentalErrMsg02',
519
- 'StartDateTime cannot be a past datetime.',
520
- );
521
- }
522
-
523
- /*Part 2: Make Sure Less Than End Date Time*/
524
- if (this.EndDateTime && startDateTimeObject > this.EndDateTime) {
525
- throw new ClassError(
526
- 'Rental',
527
- 'RentalErrMsg03',
528
- 'StartDateTime cannot be more than EndDateTime.',
529
- );
530
- }
531
-
532
- /*Part 3: Set Status Whether Reserved or Active*/
533
- if (startDateTimeObject > new Date(new Date().setHours(0, 0, 0, 0))) {
534
- this._Status = RentalStatusEnum.RESERVED;
535
- } else {
536
- this._Status = RentalStatusEnum.ACTIVE;
537
- }
538
- }
539
-
540
- public async periodEndProcess(
541
- loginUser: LoginUser,
542
- dbTransaction: any,
543
- stockInventory: any,
544
- ) {
545
- try {
546
- // Privilege Checking
547
- const systemCode =
548
- await ApplicationConfig.getComponentConfigValue('system-code');
549
-
550
- const isPrivileged = await loginUser.checkPrivileges(
551
- systemCode,
552
- 'Rental – PeriodEndProcess',
553
- );
554
-
555
- if (!isPrivileged) {
556
- throw new ClassError(
557
- 'Rental',
558
- 'RentalErrMsg04',
559
- "You do not have 'Rental - PeriodEndProcess' privilege.",
560
- );
561
- }
562
-
563
- // Validate Existing Rental
564
- if (this.AgreementNo === undefined || this.AgreementNo === null) {
565
- throw new ClassError(
566
- 'Rental',
567
- 'RentalErrMsg05',
568
- 'Rental must be existing rental.',
569
- );
570
- }
571
-
572
- // Validate Rental End Period
573
- if (this.EndDateTime === new Date(new Date().setHours(0, 0, 0, 0))) {
574
- throw new ClassError(
575
- 'Rental',
576
- 'RentalErrMsg06',
577
- 'Rental period is not ending today.',
578
- );
579
- }
580
-
581
- // Mark Rental Item as Available
582
- await stockInventory.setAvailable(loginUser, dbTransaction);
583
-
584
- // Capture Record Info Before Changes
585
- const entityValueBefore = {
586
- RentalId: this.RentalId,
587
- CustomerId: this.CustomerId,
588
- CustomerType: this.CustomerType,
589
- ItemId: this.ItemId,
590
- ItemType: this.ItemType,
591
- PriceId: this.PriceId,
592
- StartDateTime: this.StartDateTime,
593
- EndDateTime: this.EndDateTime,
594
- CancelRemarks: this.CancelRemarks,
595
- TerminateRemarks: this.TerminateRemarks,
596
- AgreementNo: this.AgreementNo,
597
- AccountType: this.AccountType,
598
- Status: this.Status,
599
- EscheatmentYN: this.EscheatmentYN,
600
- CreatedById: this.CreatedById,
601
- CreatedAt: this.CreatedAt,
602
- UpdatedById: this.UpdatedById,
603
- UpdatedAt: this.UpdatedAt,
604
- };
605
-
606
- // Mark Rental as Terminated and Capture Updater Info
607
- this.setTerminated();
608
- this._UpdatedById = loginUser.ObjectId;
609
- this._UpdatedAt = new Date();
610
-
611
- // Capture Record Info after Changes
612
- const entityValueAfter = {
613
- RentalId: this.RentalId,
614
- CustomerId: this.CustomerId,
615
- CustomerType: this.CustomerType,
616
- ItemId: this.ItemId,
617
- ItemType: this.ItemType,
618
- PriceId: this.PriceId,
619
- StartDateTime: this.StartDateTime,
620
- EndDateTime: this.EndDateTime,
621
- CancelRemarks: this.CancelRemarks,
622
- TerminateRemarks: this.TerminateRemarks,
623
- AgreementNo: this.AgreementNo,
624
- AccountType: this.AccountType,
625
- Status: this.Status,
626
- EscheatmentYN: this.EscheatmentYN,
627
- CreatedById: this.CreatedById,
628
- CreatedAt: this.CreatedAt,
629
- UpdatedById: this.UpdatedById,
630
- UpdatedAt: this.UpdatedAt,
631
- };
632
-
633
- // Record the Update Activity
634
- const activity = new Activity();
635
- activity.ActivityId = activity.createId();
636
- activity.Action = ActionEnum.UPDATE;
637
- activity.Description = 'Set Rental as Terminated';
638
- activity.EntityType = 'Rental';
639
- activity.EntityId = this.RentalId;
640
- activity.EntityValueBefore = JSON.stringify(entityValueBefore);
641
- activity.EntityValueAfter = JSON.stringify(entityValueAfter);
642
- await activity.create(loginUser.ObjectId, dbTransaction);
643
-
644
- return this;
645
- } catch (err) {
646
- throw err;
647
- }
648
- }
649
-
650
- async getCustomerActiveRentals(
651
- loginUser: LoginUser,
652
- dbTransaction: any,
653
- CustomerId: string,
654
- ): Promise<IRentalAttr[]> {
655
- try {
656
- // Part 1: Privilege Checking
657
- // Call loginUser.checkPrivileges() by passing:
658
- // SystemCode: <get_from_app_config>
659
- // PrivilegeCode: "RENTAL_VIEW"
660
- const systemCode =
661
- ApplicationConfig.getComponentConfigValue('system-code');
662
- const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_VIEW');
663
-
664
- if (!isPrivileged) {
665
- throw new ClassError(
666
- 'Rental',
667
- 'RentalErrMsg01',
668
- "You do not have 'Rental - View' privilege.",
669
- );
670
- }
671
-
672
- // Part 2: Retrieve Rentals and Returns
673
- // Call Rental._Repo findAll method by passing:
674
- // where:
675
- // Status: "Active"
676
- // [Op.OR]:
677
- // CustomerId: Params.CustomerId
678
- // '$JointHirers.CustomerId$': Params.CustomerId
679
- // include:
680
- // model: JointHirerModel
681
- // attributes: []
682
- const query = `
683
- SELECT
684
- r.*
685
- FROM
686
- rental_Rental r
687
- LEFT JOIN
688
- rental_JointHirer jh ON r.RentalId = jh.RentalId
689
- WHERE
690
- r.Status = 'Active'
691
- AND (
692
- r.CustomerId = '${CustomerId}'
693
- OR jh.CustomerId = '${CustomerId}'
694
- )
695
- GROUP BY
696
- r.RentalId
697
- `;
698
- const db = rentalDb.getConnection();
699
- const result = await db.query(query, {
700
- type: QueryTypes.SELECT,
701
- transaction: dbTransaction,
702
- model: RentalModel,
703
- mapToModel: true,
704
- });
705
-
706
- // Format the returned records
707
- const records: IRentalAttr[] = result.map((record: RentalModel) => {
708
- return {
709
- RentalId: record.RentalId,
710
- CustomerId: record.CustomerId,
711
- CustomerType: record.CustomerType,
712
- ItemId: record.ItemId,
713
- ItemType: record.ItemType,
714
- PriceId: record.PriceId,
715
- StartDateTime: record.StartDateTime,
716
- EndDateTime: record.EndDateTime,
717
- CancelRemarks: record.CancelRemarks,
718
- TerminateRemarks: record.TerminateRemarks,
719
- AgreementNo: record.AgreementNo,
720
- AccountType: record.AccountType,
721
- Status: record.Status,
722
- EscheatmentYN: record.EscheatmentYN,
723
- CreatedById: record.CreatedById,
724
- CreatedAt: record.CreatedAt,
725
- UpdatedById: record.UpdatedById,
726
- UpdatedAt: record.UpdatedAt,
727
- };
728
- });
729
- // Return the returned records.
730
- return records;
731
- } catch (error) {
732
- throw error;
733
- }
734
- }
735
-
736
- async getJointHirers(dbTransaction: any) {
737
- try {
738
- if (!this.RentalId) {
739
- throw new ClassError('Rental', 'RentalErrMsg01', 'RentalId is missing');
740
- }
741
- if (this.AccountType !== RentalAccountTypeEnum.JOINT) {
742
- throw new ClassError(
743
- 'Rental',
744
- 'RentalErrMsg07',
745
- 'This rental does not have joint hirers.',
746
- );
747
- }
748
-
749
- const jointHirers = await Rental._JointHirerRepo.findAll({
750
- where: {
751
- RentalId: this.RentalId,
752
- },
753
- transaction: dbTransaction,
754
- });
755
- // Map the jointHirers to JointHirer instances
756
- const jointHirerInstances = Promise.all(
757
- jointHirers.map(async (hirer: JointHirerModel) => {
758
- return await JointHirer.init(hirer.HirerId, dbTransaction);
759
- }),
760
- );
761
- return jointHirerInstances;
762
- } catch (error) {
763
- console.error('Error in getJointHirers:', error);
764
- throw error;
765
- }
766
- }
767
-
768
- async getCustomerIds(loginUser: LoginUser, dbTransaction: any) {
769
- try {
770
- // Part 1: Privilege Checking
771
- // Call loginUser.checkPrivileges() by passing:
772
- // SystemCode: <get_from_app_config>
773
- // PrivilegeCode: "RENTAL_VIEW"
774
- const systemCode =
775
- ApplicationConfig.getComponentConfigValue('system-code');
776
- const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_VIEW');
777
-
778
- if (!isPrivileged) {
779
- throw new ClassError(
780
- 'Rental',
781
- 'RentalErrMsg01',
782
- "You do not have 'Rental - View' privilege.",
783
- );
784
- }
785
-
786
- // Part 2: Validation
787
- // Make sure this.RentalId exists, if not throw new ClassError by passing
788
- if (!this.RentalId) {
789
- throw new ClassError('Rental', 'RentalErrMsg01', 'RentalId is missing');
790
- }
791
-
792
- //Part 3: Retrieve Listing and Returns
793
- // 3.1 Call Rental._JointHirerRepo findAll method by passing:
794
- // where:
795
- // RentalId: this.RentalId
796
- // dbTransaction
797
- const options: any = {
798
- where: {
799
- RentalId: this.RentalId,
800
- Status: 'Active',
801
- },
802
- transaction: dbTransaction,
803
- };
804
-
805
- const joinHirers = await Rental._JointHirerRepo.findAll(options);
806
-
807
- // 3.2 Create a new array variable and set its value to joint hirer and Rental.CustomerId
808
- // array translated to only CustomerId. Then, append this.CustomerId to the array.
809
- const customerIds: string[] = [this.CustomerId];
810
- for (let i = 0; i < joinHirers.length; i++) {
811
- const jointHirer = joinHirers[i];
812
- customerIds.push(jointHirer.CustomerId);
813
- }
814
-
815
- // 3.3 Return the array.
816
- return customerIds;
817
- } catch (error) {
818
- throw error;
819
- }
820
- }
821
-
822
- async signAgreement(
823
- loginUser: LoginUser,
824
- party: string,
825
- PartyId: string,
826
- PartyType: string,
827
- dbTransaction: any,
828
- statusAfterSign?: RentalStatusEnum | string,
829
- ) {
830
- try {
831
- // Part 1: Privilege Checking
832
- // Call loginUser.checkPrivileges() by passing:
833
- // SystemCode: <get_from_app_config>
834
- // PrivilegeCode: "RENTAL_SIGN"
835
- const systemCode =
836
- ApplicationConfig.getComponentConfigValue('system-code');
837
- const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_SIGN');
838
-
839
- if (!isPrivileged) {
840
- throw new ClassError(
841
- 'Rental',
842
- 'RentalErrMsg01',
843
- "You do not have 'RENTAL_SIGN' privilege.",
844
- );
845
- }
846
-
847
- // Part 2: Validation
848
- // Make sure this.Status is "Pending Signing" and agreementStatus is "Generated", if not throw new ClassError
849
- const agreement = await Agreement.init(this.AgreementNo, dbTransaction);
850
- if (
851
- this.Status !== RentalStatusEnum.PENDING_SIGNING &&
852
- agreement.Status !== AggrementStatusEnum.GENERATED
853
- ) {
854
- throw new ClassError(
855
- 'Rental',
856
- 'RentalErrMsg01',
857
- 'Rental is not ready to be signed yet.',
858
- );
859
- }
860
-
861
- //Make sure CustomerId inside the listing and SignatureStatus is "Pending"
862
- const signatureList = await Agreement.getSignatureList(
863
- loginUser,
864
- this.AgreementNo,
865
- dbTransaction,
866
- );
867
- const customerSignature = signatureList.find(
868
- (sig) =>
869
- sig.PartyId === PartyId &&
870
- sig.PartyType === PartyType &&
871
- sig.Party === party &&
872
- sig.SignatureStatus === AgreementSignatureStatusEnum.PENDING,
873
- );
874
-
875
- if (!customerSignature) {
876
- throw new ClassError(
877
- 'Rental',
878
- 'RentalErrMsg01',
879
- 'Signature is not pending.',
880
- );
881
- }
882
-
883
- //Update rental_AgreementSignature
884
- const signaturePayload = {
885
- SignatureStatus: AgreementSignatureStatusEnum.SIGNED,
886
- SignedAt: new Date(),
887
- UpdatedById: loginUser.ObjectId,
888
- UpdatedAt: new Date(),
889
- };
890
-
891
- await Rental._AgreementSignatureRepo.update(signaturePayload, {
892
- where: {
893
- AgreementNo: this.AgreementNo,
894
- Party: party,
895
- PartyId: PartyId,
896
- PartyType: PartyType,
897
- },
898
- transaction: dbTransaction,
899
- });
900
-
901
- const signatureActivity = new Activity();
902
- signatureActivity.ActivityId = signatureActivity.createId();
903
- signatureActivity.Action = ActionEnum.UPDATE;
904
- signatureActivity.Description = 'Update hirer signature';
905
- signatureActivity.EntityType = 'AgreementSignature';
906
- signatureActivity.EntityId = this.AgreementNo;
907
- signatureActivity.EntityValueBefore = JSON.stringify(customerSignature);
908
- signatureActivity.EntityValueAfter = JSON.stringify(signaturePayload);
909
- await signatureActivity.create(loginUser.ObjectId, dbTransaction);
910
-
911
- const updatedSignatureList = await Agreement.getSignatureList(
912
- loginUser,
913
- this.AgreementNo,
914
- dbTransaction,
915
- );
916
-
917
- const pendingSignatures = updatedSignatureList.filter(
918
- (sig) => sig.SignatureStatus === 'Pending',
919
- );
920
- if (pendingSignatures.length > 0) {
921
- return;
922
- }
923
-
924
- //Part 3: Update Agreement Status
925
- // 3.1 Set EntityValueBefore to current agreement instance.
926
- const entityValueAgreementBefore = {
927
- AgreementNo: agreement.AgreementNo,
928
- Status: agreement.Status,
929
- DateSigned: agreement.DateSigned,
930
- };
931
-
932
- // 3.2 Set below agreement attributes:
933
- // DateSigned: current date & time
934
- // Status: "Signed"
935
- const payload = {
936
- DateSigned: new Date(),
937
- Status: AggrementStatusEnum.SIGNED,
938
- };
939
-
940
- // 3.3 Call Rental._AgreementRepo update()
941
- await Rental._AgreementRepo.update(payload, {
942
- where: {
943
- AgreementNo: this.AgreementNo,
944
- },
945
- transaction: dbTransaction,
946
- });
947
-
948
- const entityValueAgreementAfter = {
949
- entityValueAgreementBefore,
950
- ...payload,
951
- };
952
-
953
- // Part 4: Record Update Agreement Activity
954
- const activity = new Activity();
955
- activity.ActivityId = activity.createId();
956
- activity.Action = ActionEnum.UPDATE;
957
- activity.Description = 'Update agreement';
958
- activity.EntityType = 'RentalAgreement';
959
- activity.EntityId = this.AgreementNo;
960
- activity.EntityValueBefore = JSON.stringify(entityValueAgreementBefore);
961
- activity.EntityValueAfter = JSON.stringify(entityValueAgreementAfter);
962
- await activity.create(loginUser.ObjectId, dbTransaction);
963
-
964
- // Part 5: Update Rental Status
965
- // 5.1 Set EntityValueBefore to current rental instance.
966
- const entityValueRentalBefore = {
967
- RentalId: this.RentalId,
968
- CustomerId: this.CustomerId,
969
- CustomerType: this.CustomerType,
970
- ItemId: this.ItemId,
971
- ItemType: this.ItemType,
972
- PriceId: this.PriceId,
973
- StartDateTime: this.StartDateTime,
974
- EndDateTime: this.EndDateTime,
975
- CancelRemarks: this.CancelRemarks,
976
- TerminateRemarks: this.TerminateRemarks,
977
- AgreementNo: this.AgreementNo,
978
- AccountType: this.AccountType,
979
- Status: this.Status,
980
- EscheatmentYN: this.EscheatmentYN,
981
- CreatedById: this.CreatedById,
982
- CreatedAt: this.CreatedAt,
983
- UpdatedById: this.UpdatedById,
984
- UpdatedAt: this.UpdatedAt,
985
- };
986
- // 5.2: Set below rental attributes:
987
- // Status: "Pending Key Collection"
988
- // UpdatedById: loginUser.ObjectId
989
- // UpdatedAt: current date & time
990
-
991
- this._Status = statusAfterSign
992
- ? statusAfterSign
993
- : RentalStatusEnum.ACTIVE;
994
-
995
- const payloadRental = {
996
- Status: this._Status,
997
- UpdatedById: loginUser.ObjectId,
998
- UpdatedAt: new Date(),
999
- };
1000
-
1001
- // 5.3: Call Rental._Repo update() method by passing:
1002
- // populate rental instance attributes
1003
- // dbTransaction
1004
- await Rental._Repo.update(payloadRental, {
1005
- where: {
1006
- RentalId: this.RentalId,
1007
- },
1008
- transaction: dbTransaction,
1009
- });
1010
-
1011
- const entityValueRentalAfter = {
1012
- entityValueRentalBefore,
1013
- ...payloadRental,
1014
- };
1015
-
1016
- // Part 6: Record Update Agreement Activity
1017
- const rentalActivity = new Activity();
1018
- rentalActivity.ActivityId = activity.createId();
1019
- rentalActivity.Action = ActionEnum.UPDATE;
1020
- rentalActivity.Description = 'Sign rental agreement';
1021
- rentalActivity.EntityType = 'Rental';
1022
- rentalActivity.EntityId = this.RentalId;
1023
- rentalActivity.EntityValueBefore = JSON.stringify(
1024
- entityValueRentalBefore,
1025
- );
1026
- rentalActivity.EntityValueAfter = JSON.stringify(entityValueRentalAfter);
1027
- await rentalActivity.create(loginUser.ObjectId, dbTransaction);
1028
- } catch (error) {
1029
- throw error;
1030
- }
1031
- }
1032
-
1033
- async generateAgreement(
1034
- loginUser: LoginUser,
1035
- dbTransaction: any,
1036
- MediaId: string,
1037
- ) {
1038
- //This method will generate a new rental agreement.
1039
- try {
1040
- // Part 1: Privilege Checking
1041
- // Call loginUser.checkPrivileges() by passing:
1042
- // SystemCode: "<get_from_app_config>"
1043
- // PrivilegeCode: "RENTAL_AGREEMENT_CREATE"
1044
-
1045
- const systemCode =
1046
- ApplicationConfig.getComponentConfigValue('system-code');
1047
- const isPrivileged = loginUser.checkPrivileges(
1048
- systemCode,
1049
- 'RENTAL_AGREEMENT_CREATE',
1050
- );
1051
-
1052
- if (!isPrivileged) {
1053
- throw new ClassError(
1054
- 'Rental',
1055
- 'RentalErrMsg01',
1056
- "You do not have 'RENTAL_AGREEMENT_CREATE' privilege.",
1057
- );
1058
- }
1059
-
1060
- // Part 2: Validation
1061
- // Instantiate existing RentalAgreement by passing:
1062
- // dbTransaction
1063
- // AgreementNo: this.AgreementNo
1064
- // Make sure Params.MediaId exists, if not throw new ClassError by passing:
1065
- // Classname: "Rental"
1066
- // MessageCode: "RentalErrMsg0X"
1067
- // Message: "MediaId is required."
1068
- const agreement = await Agreement.init(this.AgreementNo, dbTransaction);
1069
- if (!MediaId) {
1070
- throw new ClassError(
1071
- 'Rental',
1072
- 'RentalErrMsg0X',
1073
- 'MediaId is required.',
1074
- );
1075
- }
1076
-
1077
- // Part 3: Update Agreement Record
1078
- // Set EntityValueBefore to the agreement instance.
1079
- // Set below agreement attributes:
1080
- // Status: "Generated"
1081
- // MediaId: Params.MediaId
1082
-
1083
- const EntityValueBefore = agreement;
1084
- agreement.Status = AggrementStatusEnum.GENERATED;
1085
- agreement.MediaId = MediaId;
1086
-
1087
- // Call Rental._AgreementRepo update method by passing:
1088
- // Status: agreement.Status
1089
- // MediaId: agreement.MediaId
1090
- // dbTransaction
1091
-
1092
- await Rental._AgreementRepo.update(
1093
- {
1094
- Status: agreement.Status,
1095
- MediaId: agreement.MediaId,
1096
- },
1097
- {
1098
- where: {
1099
- AgreementNo: this.AgreementNo,
1100
- },
1101
- transaction: dbTransaction,
1102
- },
1103
- );
1104
-
1105
- // Part 4: Record Update Agreement Activity
1106
- // Initialise EntityValueAfter variable and set to agreement instance
1107
- const EntityValueAfter = agreement;
1108
- // Instantiate new activity from Activity class, call createId() method, then set:
1109
- const activity = new Activity();
1110
- // Action: ActionEnum.UPDATE
1111
- // Description: "Generate agreement."
1112
- // EntityType: "RentalAgreement"
1113
- // EntityId: this.AgreementNo
1114
- // EntityValueBefore: EntityValueBefore
1115
- // EntityValueAfter: EntityValueAfter
1116
- activity.ActivityId = activity.createId();
1117
- activity.Action = ActionEnum.UPDATE;
1118
- activity.Description = 'Generate agreement.';
1119
- activity.EntityType = 'RentalAgreement';
1120
- activity.EntityId = this.AgreementNo;
1121
- activity.EntityValueBefore = JSON.stringify(EntityValueBefore);
1122
- activity.EntityValueAfter = JSON.stringify(EntityValueAfter);
1123
-
1124
- // Call new activity create method by passing:
1125
- // dbTransaction
1126
- // userId: loginUser.ObjectId
1127
- await activity.create(loginUser.ObjectId, dbTransaction);
1128
-
1129
- // Part 5: Add Record To Agreement History Table
1130
- // Make sure there is a private static readonly _AgreementHistoryRepo variable.
1131
- // Set newRecord to an object with below key-value:
1132
- // AgreementNo: this.AgreementNo
1133
- // MediaId: params.MediaId
1134
- // ActivityCompleted: "Agreement Generated"
1135
- // CreatedAt: Current Timestamp
1136
- // Use _AgreementHistoryRepo.create() method and pass newRecord and dbTransaction.
1137
- const agreementHistory = await Rental._AgreementHistoryRepo.create(
1138
- {
1139
- AgreementNo: this.AgreementNo,
1140
- MediaId,
1141
- ActivityCompleted: 'Agreement Generated',
1142
- CreatedAt: new Date(),
1143
- },
1144
- { transaction: dbTransaction },
1145
- );
1146
-
1147
- // Part 6: Record Agreement History Activity
1148
- // Initialise EntityValueAfter variable and set to newRecord from previous part.
1149
- // Instantiate new activity from Activity class, call createId() method, then set:
1150
- // Action: ActionEnum.CREATE
1151
- // Description: "Generate agreement."
1152
- // EntityType: "RentalAgreementHistory"
1153
- // EntityId: HistoryId from previous part.
1154
- // EntityValueBefore: empty object.
1155
- // EntityValueAfter: EntityValueAfter
1156
- // Call new activity create method by passing:
1157
- // dbTransaction
1158
- // userId: loginUser.ObjectId
1159
- const entityValueAfter = agreementHistory.get({ plain: true });
1160
- const activityHistory = new Activity();
1161
- activityHistory.ActivityId = activityHistory.createId();
1162
- activityHistory.Action = ActionEnum.CREATE;
1163
- activityHistory.Description = 'Generate agreement.';
1164
- activityHistory.EntityType = 'RentalAgreementHistory';
1165
- activityHistory.EntityId = agreementHistory.HistoryId.toString();
1166
- activityHistory.EntityValueBefore = JSON.stringify({});
1167
- activityHistory.EntityValueAfter = JSON.stringify(entityValueAfter);
1168
- await activityHistory.create(loginUser.ObjectId, dbTransaction);
1169
- } catch (error) {
1170
- throw error;
1171
- }
1172
- }
1173
-
1174
- public toJSON(): IRentalAttr {
1175
- return {
1176
- RentalId: this.RentalId,
1177
- CustomerId: this.CustomerId,
1178
- CustomerType: this.CustomerType,
1179
- ItemId: this.ItemId,
1180
- ItemType: this.ItemType,
1181
- PriceId: this.PriceId,
1182
- StartDateTime: this.StartDateTime,
1183
- EndDateTime: this.EndDateTime,
1184
- Status: this.Status,
1185
- CancelRemarks: this.CancelRemarks,
1186
- TerminateRemarks: this.TerminateRemarks,
1187
- EscheatmentYN: this.EscheatmentYN,
1188
- AgreementNo: this.AgreementNo,
1189
- AccountType: this.AccountType,
1190
- CreatedById: this.CreatedById,
1191
- CreatedAt: this.CreatedAt,
1192
- UpdatedById: this.UpdatedById,
1193
- UpdatedAt: this.UpdatedAt,
1194
- };
1195
- }
1196
-
1197
- public async getInvoices(
1198
- loginUser: LoginUser,
1199
- dbTransaction: any,
1200
- accountingSystem?: IAccountSystem,
1201
- ) {
1202
- try {
1203
- // Part 1: Privilege Checking
1204
- // Call loginUser.checkPrivileges() by passing:
1205
- // SystemCode: <get_from_app_config>
1206
- // PrivilegeCode: "RENTAL_VIEW_INVOICE"
1207
- const systemCode =
1208
- ApplicationConfig.getComponentConfigValue('system-code');
1209
- const isPrivileged = loginUser.checkPrivileges(
1210
- systemCode,
1211
- 'RENTAL_VIEW_INVOICE',
1212
- );
1213
-
1214
- if (!isPrivileged) {
1215
- throw new ClassError(
1216
- 'Rental',
1217
- 'RentalErrMsg01',
1218
- "You do not have 'RENTAL_VIEW_INVOICE' privilege.",
1219
- );
1220
- }
1221
-
1222
- // Part 2: Validation
1223
- // Make sure this._ObjectId exists, if not throw new ClassError by passing
1224
- if (!this.ObjectId) {
1225
- throw new ClassError(
1226
- 'Rental',
1227
- 'RentalErrMsg01',
1228
- 'ObjectId is missing.',
1229
- );
1230
- }
1231
-
1232
- // Part 3: Check Existing Invoices
1233
- if (this.Invoices.length > 0) {
1234
- return this.Invoices;
1235
- }
1236
-
1237
- // Part 4: Retrieve Invoices and Returns
1238
- const search = {
1239
- DocType: DocType.INVOICE,
1240
- RelatedObjectId: this.ObjectId,
1241
- RelatedObjectType: this.ObjectType,
1242
- };
1243
-
1244
- const documents = await Document.findAll(
1245
- loginUser,
1246
- dbTransaction,
1247
- undefined,
1248
- undefined,
1249
- search,
1250
- undefined,
1251
- accountingSystem,
1252
- );
1253
-
1254
- this.Invoices = documents.rows.map((doc) => {
1255
- const document = new Document(dbTransaction, doc);
1256
- return document;
1257
- });
1258
-
1259
- return this.Invoices;
1260
- } catch (error) {
1261
- throw error;
1262
- }
1263
- }
1264
-
1265
- public async getItem(dbTransaction: any): Promise<any> {
1266
- if (this.Item) {
1267
- return this.Item;
1268
- } else {
1269
- const ItemClass = ItemClassMap[this.ItemType];
1270
-
1271
- if (!ItemClass || typeof ItemClass.init !== 'function') {
1272
- throw new Error(`Invalid or unregistered ItemType: ${this.ItemType}`);
1273
- }
1274
-
1275
- ItemClass._Repo = ItemClass._Repo || ItemClass.getRepo();
1276
-
1277
- if (!ItemClass._Repo) {
1278
- throw new Error(
1279
- `ItemType ${this.ItemType} does not have a repository.`,
1280
- );
1281
- }
1282
-
1283
- const itemInstance = await ItemClass.init(this.ItemId, dbTransaction);
1284
-
1285
- if (!itemInstance) {
1286
- throw new Error(`${this.ItemType} not found with ID ${this.ItemId}`);
1287
- }
1288
- this.Item = itemInstance;
1289
-
1290
- // Make sure item has setAvailable method
1291
- if (typeof this.Item.setAvailable !== 'function') {
1292
- throw new Error(`${this.ItemType} does not implement setAvailable()`);
1293
- }
1294
- return this.Item;
1295
- }
1296
- }
1297
-
1298
- public async cancel(
1299
- loginUser: LoginUser,
1300
- dbTransaction: any,
1301
- remarks: string,
1302
- ): Promise<Rental> {
1303
- try {
1304
- // Part 1: Privilege Checking
1305
- const systemCode =
1306
- ApplicationConfig.getComponentConfigValue('system-code');
1307
- const isPrivileged = await loginUser.checkPrivileges(
1308
- systemCode,
1309
- 'RENTAL_CANCEL',
1310
- );
1311
-
1312
- if (!isPrivileged) {
1313
- throw new ClassError(
1314
- 'Rental',
1315
- 'RentalErrMsg01',
1316
- "You do not have 'RENTAL_CANCEL' privilege.",
1317
- );
1318
- }
1319
-
1320
- // Part 2: Validation
1321
- if (!this.ObjectId) {
1322
- throw new ClassError(
1323
- 'Rental',
1324
- 'RentalErrMsg01',
1325
- 'Rental not found. Rental Id is empty.',
1326
- );
1327
- }
1328
-
1329
- if (
1330
- this.Status === RentalStatusEnum.ACTIVE ||
1331
- this.Status === RentalStatusEnum.SUSPENDED
1332
- ) {
1333
- throw new ClassError(
1334
- 'Rental',
1335
- 'RentalErrMsg01',
1336
- `Rental already ${this.Status}, please do termination process.`,
1337
- );
1338
- }
1339
-
1340
- if (!remarks) {
1341
- throw new ClassError(
1342
- 'Rental',
1343
- 'RentalErrMsg01',
1344
- 'Cancellation remarks is required.',
1345
- );
1346
- }
1347
-
1348
- // Part 3: Capture Record Info Before Changes
1349
- const entityValueBefore = this.toJSON();
1350
-
1351
- // Part 4: Update Rental Status and Remarks
1352
- this._Status = RentalStatusEnum.CANCELLED;
1353
- this.CancelRemarks = remarks;
1354
- this._UpdatedById = loginUser.ObjectId;
1355
- this._UpdatedAt = new Date();
1356
-
1357
- // Part 5: Update Rental Record
1358
- await Rental._Repo.update(
1359
- {
1360
- Status: this.Status,
1361
- CancelRemarks: this.CancelRemarks,
1362
- UpdatedById: this.UpdatedById,
1363
- UpdatedAt: this.UpdatedAt,
1364
- },
1365
- {
1366
- where: {
1367
- RentalId: this.RentalId,
1368
- },
1369
- transaction: dbTransaction,
1370
- },
1371
- );
1372
-
1373
- // Part 6: Mark Item as Available
1374
- const item = await this.getItem(dbTransaction);
1375
-
1376
- await item.setAvailable(loginUser, dbTransaction);
1377
-
1378
- // Part 7: Capture Record Info After Changes
1379
- const entityValueAfter = this.toJSON();
1380
- // Part 8: Record Activity
1381
- const activity = new Activity();
1382
- activity.ActivityId = activity.createId();
1383
- activity.Action = ActionEnum.UPDATE;
1384
- activity.Description = 'Rental Cancellation';
1385
- activity.EntityType = this.ObjectType;
1386
- activity.EntityId = this.ObjectId;
1387
- activity.EntityValueBefore = JSON.stringify(entityValueBefore);
1388
- activity.EntityValueAfter = JSON.stringify(entityValueAfter);
1389
- await activity.create(loginUser.ObjectId, dbTransaction);
1390
- return this;
1391
- } catch (error) {
1392
- throw error;
1393
- }
1394
- }
1395
-
1396
- public async update(
1397
- loginUser: LoginUser,
1398
- dbTransaction: any,
1399
- updates: Partial<IRentalAttr>,
1400
- ): Promise<Rental> {
1401
- try {
1402
- // Part 1: Privilege Checking
1403
- const systemCode =
1404
- ApplicationConfig.getComponentConfigValue('system-code');
1405
- const isPrivileged = await loginUser.checkPrivileges(
1406
- systemCode,
1407
- 'RENTAL_UPDATE',
1408
- );
1409
-
1410
- if (!isPrivileged) {
1411
- throw new ClassError(
1412
- 'Rental',
1413
- 'RentalErrMsg01',
1414
- "You do not have 'RENTAL_UPDATE' privilege.",
1415
- );
1416
- }
1417
-
1418
- // Part 2: Validation
1419
- if (!this.ObjectId) {
1420
- throw new ClassError(
1421
- 'Rental',
1422
- 'RentalErrMsg01',
1423
- 'Rental not found. Rental Id is empty.',
1424
- );
1425
- }
1426
-
1427
- // Part 3: Capture Record Info Before Changes
1428
- const entityValueBefore = this.toJSON();
1429
-
1430
- // Part 4: Update Rental Record
1431
- await Rental._Repo.update(updates, {
1432
- where: {
1433
- RentalId: this.RentalId,
1434
- },
1435
- transaction: dbTransaction,
1436
- });
1437
-
1438
- // Part 5: Update object instance properties and capture after changes
1439
- Object.assign(this, updates);
1440
- this._UpdatedById = loginUser.ObjectId;
1441
- this._UpdatedAt = new Date();
1442
-
1443
- const entityValueAfter = this.toJSON();
1444
-
1445
- // Part 6: Record Activity
1446
- const activity = new Activity();
1447
- activity.ActivityId = activity.createId();
1448
- activity.Action = ActionEnum.UPDATE;
1449
- activity.Description = 'Update Rental';
1450
- activity.EntityType = this.ObjectType;
1451
- activity.EntityId = this.ObjectId;
1452
- activity.EntityValueBefore = JSON.stringify(entityValueBefore);
1453
- activity.EntityValueAfter = JSON.stringify(entityValueAfter);
1454
- await activity.create(loginUser.ObjectId, dbTransaction);
1455
-
1456
- return this;
1457
- } catch (error) {
1458
- throw error;
1459
- }
1460
- }
1461
- }
1
+ import { IRentalAttr } from '../../interfaces/rental-attr.interface';
2
+ import { RentalStatusEnum } from '../../enum/rental-status.enum';
3
+ import { RentalRepository } from './rental.repository';
4
+ import { ClassError, ObjectBase } from '@tomei/general';
5
+ import { ApplicationConfig } from '@tomei/config';
6
+ import { LoginUser } from '@tomei/sso';
7
+ import { RentalPrice } from '../rental-price/rental-price';
8
+ import { Op, QueryTypes } from 'sequelize';
9
+ import { ActionEnum, Activity } from '@tomei/activity-history';
10
+ import { IRentalFindAllSearchAttr } from '../../interfaces/rental-find-all-search-attr.interface';
11
+ import { RentalAccountTypeEnum } from '../../enum/account-type.enum';
12
+ import { JointHirer } from '../joint-hirer/joint-hirer';
13
+ import { JointHirerModel } from '../../models/joint-hirer.entity';
14
+ import { AgreementRepository } from '../agreement/agreement.repository';
15
+ import * as rentalDb from '../../database';
16
+ import { RentalModel } from '../../models/rental.entity';
17
+ import { JointHirerRepository } from '../joint-hirer/joint-hirer.repository';
18
+ import { AgreementModel } from '../../models';
19
+ import { Agreement } from '../agreement/agreement';
20
+ import { AggrementStatusEnum } from '../../enum/aggrement-status.enum';
21
+ import { AgreementSignatureRepository } from '../agreement-signature/agreement-signature.repository';
22
+ import { AgreementSignatureStatusEnum } from '../../enum/agreement-signature-status.enum';
23
+ import { HirerTypeEnum } from '../../enum/hirer-type.enum';
24
+ import { AgreementHistoryRepository } from '../agreement-history/agreement-history.repository';
25
+ import { DocType, Document, IAccountSystem } from '@tomei/finance';
26
+ import { ItemClassMap } from '../../ClassMappings/ItemClassMap';
27
+ import { AgreementSignatureVerificationMethodEnum } from '../../enum/agreement-signature-verification-method.enum';
28
+
29
+ export class Rental extends ObjectBase {
30
+ ObjectId: string;
31
+ ObjectName: string;
32
+ ObjectType = 'Rental';
33
+ TableName: string;
34
+ CustomerId: string;
35
+ CustomerType: string;
36
+ ItemId: string;
37
+ ItemType: string;
38
+ PriceId: string;
39
+ StartDateTime: Date;
40
+ EndDateTime: Date;
41
+ CancelRemarks: string;
42
+ TerminateRemarks: string;
43
+ AgreementNo: string;
44
+ AccountType: RentalAccountTypeEnum;
45
+ JointHirers: JointHirer[] = [];
46
+ Invoices: Document[] = [];
47
+ Item: any;
48
+ protected _Status: RentalStatusEnum | string;
49
+ protected _EscheatmentYN: string = 'N';
50
+ protected _CreatedById: string;
51
+ protected _CreatedAt: Date;
52
+ protected _UpdatedById: string;
53
+ protected _UpdatedAt: Date;
54
+ protected static _Repo = new RentalRepository();
55
+ protected static _AgreementRepo = new AgreementRepository();
56
+ protected static _JointHirerRepo = new JointHirerRepository();
57
+ protected static _AgreementSignatureRepo = new AgreementSignatureRepository();
58
+ protected static _AgreementHistoryRepo = new AgreementHistoryRepository();
59
+
60
+ get RentalId(): string {
61
+ return this.ObjectId;
62
+ }
63
+
64
+ set RentalId(value: string) {
65
+ this.ObjectId = value;
66
+ }
67
+
68
+ get Status(): RentalStatusEnum | string {
69
+ return this._Status;
70
+ }
71
+
72
+ get EscheatmentYN(): string {
73
+ return this._EscheatmentYN;
74
+ }
75
+
76
+ get CreatedById(): string {
77
+ return this._CreatedById;
78
+ }
79
+
80
+ get CreatedAt(): Date {
81
+ return this._CreatedAt;
82
+ }
83
+
84
+ get UpdatedById(): string {
85
+ return this._UpdatedById;
86
+ }
87
+
88
+ get UpdatedAt(): Date {
89
+ return this._UpdatedAt;
90
+ }
91
+
92
+ private setTerminated() {
93
+ this._Status = RentalStatusEnum.TERMINATED;
94
+ }
95
+
96
+ protected constructor(rentalAttr?: IRentalAttr) {
97
+ super();
98
+ if (rentalAttr) {
99
+ this.RentalId = rentalAttr.RentalId;
100
+ this.CustomerId = rentalAttr.CustomerId;
101
+ this.CustomerType = rentalAttr.CustomerType;
102
+ this.ItemId = rentalAttr.ItemId;
103
+ this.ItemType = rentalAttr.ItemType;
104
+ this.PriceId = rentalAttr.PriceId;
105
+ this.StartDateTime = rentalAttr.StartDateTime;
106
+ this.EndDateTime = rentalAttr.EndDateTime;
107
+ this.CancelRemarks = rentalAttr.CancelRemarks;
108
+ this.TerminateRemarks = rentalAttr.TerminateRemarks;
109
+ this.AgreementNo = rentalAttr.AgreementNo;
110
+ this.AccountType = rentalAttr.AccountType;
111
+ this._Status = rentalAttr.Status;
112
+ this._EscheatmentYN = rentalAttr.EscheatmentYN;
113
+ this._CreatedById = rentalAttr.CreatedById;
114
+ this._CreatedAt = rentalAttr.CreatedAt;
115
+ this._UpdatedById = rentalAttr.UpdatedById;
116
+ this._UpdatedAt = rentalAttr.UpdatedAt;
117
+ }
118
+ }
119
+
120
+ public static async init(dbTransaction?: any, rentalId?: string) {
121
+ try {
122
+ if (rentalId) {
123
+ const rental = await Rental._Repo.findByPk(rentalId, dbTransaction);
124
+ if (rental) {
125
+ return new Rental(rental);
126
+ } else {
127
+ throw new ClassError('Rental', 'RentalErrMsg00', 'Rental Not Found');
128
+ }
129
+ }
130
+ return new Rental();
131
+ } catch (error) {
132
+ throw new ClassError(
133
+ 'Rental',
134
+ 'RentalErrMsg00',
135
+ 'Failed To Initialize Rental',
136
+ );
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Create a new Rental record.
142
+ * @param {RentalPrice} rentalPrice - The rental pricing information.
143
+ * @param {LoginUser} loginUser - The user initiating the creation.
144
+ * @param {any} [dbTransaction] - Optional database transaction for atomic operations.
145
+ * @throws {ClassError} Throws an error if:
146
+ * 1. loginUser does not have 'Rental - Create' privilege.
147
+ * 2. Rental item is not available at the current date.
148
+ * @returns {Promise<any>} A Promise resolving to the created rental record.
149
+ */
150
+ public async create(
151
+ rentalPrice: RentalPrice,
152
+ loginUser: LoginUser,
153
+ jointHirers?: JointHirer[],
154
+ dbTransaction?: any,
155
+ ): Promise<any> {
156
+ try {
157
+ /*Part 1: Check Privilege*/
158
+ const systemCode =
159
+ ApplicationConfig.getComponentConfigValue('system-code');
160
+ const isPrivileged = await loginUser.checkPrivileges(
161
+ systemCode,
162
+ 'Rental - Create',
163
+ );
164
+
165
+ if (!isPrivileged) {
166
+ throw new ClassError(
167
+ 'Rental',
168
+ 'RentalErrMsg01',
169
+ "You do not have 'Rental - Create' privilege.",
170
+ );
171
+ }
172
+
173
+ /*Part 2: Make Sure Rental Item Available*/
174
+ const isItemAvailable = await Rental.isItemAvailable(
175
+ this.ItemId,
176
+ this.ItemType,
177
+ this.StartDateTime,
178
+ this.EndDateTime,
179
+ dbTransaction,
180
+ );
181
+
182
+ if (!isItemAvailable) {
183
+ throw new ClassError(
184
+ 'Rental',
185
+ 'RentalErrMsg02',
186
+ 'Rental Item is not available at current date.',
187
+ );
188
+ }
189
+
190
+ // Part 3: Create Rental Agreement Record
191
+ // Call Rental._AgreementRepo create method by passing:
192
+ // AgreementNo: this.AgreementNo
193
+ // Status: "Not Generated"
194
+ // dbTransaction
195
+ await Rental._AgreementRepo.create(
196
+ {
197
+ AgreementNo: this.AgreementNo,
198
+ Status: 'Not Generated',
199
+ },
200
+ {
201
+ transaction: dbTransaction,
202
+ },
203
+ );
204
+
205
+ //Create a record into rental_AgreementSignature table
206
+ //Create the main customer's signature record
207
+ await Rental._AgreementSignatureRepo.create(
208
+ {
209
+ SignatureId: this.createId(),
210
+ AgreementNo: this.AgreementNo,
211
+ Party: HirerTypeEnum.PRIMARY,
212
+ PartyId: this.CustomerId,
213
+ PartyType: 'Customer',
214
+ SignatureStatus: AgreementSignatureStatusEnum.PENDING,
215
+ SignedAt: null,
216
+ CreatedById: loginUser.ObjectId,
217
+ CreatedAt: new Date(),
218
+ UpdatedById: loginUser.ObjectId,
219
+ UpdatedAt: new Date(),
220
+ },
221
+ { transaction: dbTransaction },
222
+ );
223
+
224
+ // Create signatures record for joint hirers if any
225
+ if (jointHirers && jointHirers.length > 0) {
226
+ for (const jointHirer of jointHirers) {
227
+ await Rental._AgreementSignatureRepo.create(
228
+ {
229
+ SignatureId: this.createId(),
230
+ AgreementNo: this.AgreementNo,
231
+ Party: HirerTypeEnum.JOINT,
232
+ PartyId: jointHirer.CustomerId,
233
+ PartyType: 'Customer',
234
+ SignatureStatus: AgreementSignatureStatusEnum.PENDING,
235
+ SignedAt: null,
236
+ CreatedById: loginUser.ObjectId,
237
+ CreatedAt: new Date(),
238
+ UpdatedById: loginUser.ObjectId,
239
+ UpdatedAt: new Date(),
240
+ },
241
+ { transaction: dbTransaction },
242
+ );
243
+ }
244
+ }
245
+
246
+ /*Part 4: Insert Rental & The Agreed Rental Price*/
247
+ if (!rentalPrice.PriceId) {
248
+ const rentalPriceData = await rentalPrice.create(
249
+ loginUser,
250
+ dbTransaction,
251
+ );
252
+ this.PriceId = rentalPriceData.PriceId;
253
+ } else {
254
+ this.PriceId = rentalPrice.PriceId;
255
+ }
256
+ this.RentalId = this.createId();
257
+ // if (!this.Status) {
258
+ this._Status = RentalStatusEnum.PENDING_SIGNING;
259
+ // }
260
+ this._CreatedById = loginUser.ObjectId;
261
+ this._UpdatedById = loginUser.ObjectId;
262
+ this._CreatedAt = new Date();
263
+ this._UpdatedAt = new Date();
264
+
265
+ const data = {
266
+ RentalId: this.RentalId,
267
+ CustomerId: this.CustomerId,
268
+ CustomerType: this.CustomerType,
269
+ ItemId: this.ItemId,
270
+ ItemType: this.ItemType,
271
+ PriceId: this.PriceId,
272
+ StartDateTime: this.StartDateTime,
273
+ EndDateTime: this.EndDateTime,
274
+ CancelRemarks: this.CancelRemarks,
275
+ TerminateRemarks: this.TerminateRemarks,
276
+ AgreementNo: this.AgreementNo,
277
+ AccountType: this.AccountType,
278
+ Status: this.Status,
279
+ EscheatmentYN: this.EscheatmentYN,
280
+ CreatedById: this.CreatedById,
281
+ CreatedAt: this.CreatedAt,
282
+ UpdatedById: this.UpdatedById,
283
+ UpdatedAt: this.UpdatedAt,
284
+ };
285
+
286
+ await Rental._Repo.create(data, {
287
+ transaction: dbTransaction,
288
+ });
289
+
290
+ //For every data inside Param.jointHirers, update the rentalId and call jointHirer.create
291
+ if (jointHirers) {
292
+ for (let i = 0; i < jointHirers.length; i++) {
293
+ jointHirers[i].RentalId = this.RentalId;
294
+ await jointHirers[i].create(loginUser, dbTransaction);
295
+ this.JointHirers.push(jointHirers[i]);
296
+ }
297
+ }
298
+
299
+ /*Part 5: Record Create Rental Activity*/
300
+ const activity = new Activity();
301
+ activity.ActivityId = activity.createId();
302
+ activity.Action = ActionEnum.CREATE;
303
+ activity.Description = 'Add Rental';
304
+ activity.EntityType = 'Rental';
305
+ activity.EntityId = this.RentalId;
306
+ activity.EntityValueBefore = JSON.stringify({});
307
+ activity.EntityValueAfter = JSON.stringify(data);
308
+ await activity.create(loginUser.ObjectId, dbTransaction);
309
+
310
+ /*Part 6: Return Result*/
311
+ return this;
312
+ } catch (error) {
313
+ throw error;
314
+ }
315
+ }
316
+
317
+ public static async isItemAvailable(
318
+ itemId: string,
319
+ itemType: string,
320
+ startDateTime: Date,
321
+ endDateTime: Date,
322
+ dbTransaction?: any,
323
+ ) {
324
+ try {
325
+ const rental = await Rental._Repo.findOne({
326
+ where: {
327
+ ItemId: itemId,
328
+ ItemType: itemType,
329
+ StartDateTime: {
330
+ [Op.lte]: endDateTime,
331
+ },
332
+ EndDateTime: {
333
+ [Op.gte]: startDateTime,
334
+ },
335
+ },
336
+ transaction: dbTransaction,
337
+ });
338
+
339
+ if (!rental) {
340
+ // No rental found → item is available
341
+ return true;
342
+ }
343
+
344
+ if (
345
+ rental.Status === RentalStatusEnum.TERMINATED ||
346
+ rental.Status === RentalStatusEnum.CANCELLED
347
+ ) {
348
+ // Rental found but status is Terminated or Cancelled → item is available
349
+ return true;
350
+ }
351
+
352
+ // Rental exists and is active → item is not available
353
+ return false;
354
+ } catch (error) {
355
+ throw error;
356
+ }
357
+ }
358
+
359
+ public static async findAll(
360
+ loginUser: LoginUser,
361
+ dbTransaction: any,
362
+ page?: number,
363
+ row?: number,
364
+ search?: IRentalFindAllSearchAttr,
365
+ ) {
366
+ try {
367
+ const systemCode =
368
+ await ApplicationConfig.getComponentConfigValue('system-code');
369
+
370
+ const isPrivileged = await loginUser.checkPrivileges(
371
+ systemCode,
372
+ 'Rental - View',
373
+ );
374
+
375
+ if (!isPrivileged) {
376
+ throw new ClassError(
377
+ 'Rental',
378
+ 'RentalErrMsg01',
379
+ "You do not have 'Rental - View' privilege.",
380
+ );
381
+ }
382
+
383
+ const queryObj: any = {};
384
+
385
+ let options: any = {
386
+ transaction: dbTransaction,
387
+ order: [['CreatedAt', 'DESC']],
388
+ };
389
+
390
+ if (page && row) {
391
+ options = {
392
+ ...options,
393
+ limit: row,
394
+ offset: row * (page - 1),
395
+ };
396
+ }
397
+
398
+ if (search) {
399
+ Object.entries(search).forEach(([key, value]) => {
400
+ if (key === 'StartDateTime') {
401
+ queryObj[key] = {
402
+ [Op.gte]: value,
403
+ };
404
+ } else if (key === 'EndDateTime') {
405
+ queryObj[key] = {
406
+ [Op.lte]: value,
407
+ };
408
+ } else if (key === 'CustomerId') {
409
+ queryObj[key] = {
410
+ [Op.substring]: value,
411
+ };
412
+
413
+ options.include = [
414
+ {
415
+ model: JointHirerModel,
416
+ required: false,
417
+ where: {
418
+ CustomerId: {
419
+ [Op.substring]: value,
420
+ },
421
+ },
422
+ },
423
+ ];
424
+ } else {
425
+ queryObj[key] = {
426
+ [Op.substring]: value,
427
+ };
428
+ }
429
+ });
430
+ if (options?.include?.length > 1) {
431
+ options.include.push({
432
+ model: AgreementModel,
433
+ required: false,
434
+ });
435
+ } else {
436
+ options.include = [
437
+ {
438
+ model: AgreementModel,
439
+ required: false,
440
+ },
441
+ ];
442
+ }
443
+
444
+ options = {
445
+ ...options,
446
+ where: queryObj,
447
+ };
448
+ }
449
+
450
+ return await Rental._Repo.findAndCountAll(options);
451
+ } catch (err) {
452
+ throw err;
453
+ }
454
+ }
455
+
456
+ public static async checkActiveByItemId(
457
+ loginUser: LoginUser,
458
+ itemId: string,
459
+ itemType: string,
460
+ dbTransaction?: any,
461
+ ) {
462
+ try {
463
+ const systemCode =
464
+ await ApplicationConfig.getComponentConfigValue('system-code');
465
+
466
+ const isPrivileged = await loginUser.checkPrivileges(
467
+ systemCode,
468
+ 'Rental - View',
469
+ );
470
+
471
+ if (!isPrivileged) {
472
+ throw new ClassError(
473
+ 'Rental',
474
+ 'RentalErrMsg01',
475
+ "You do not have 'Rental - View' privilege.",
476
+ );
477
+ }
478
+
479
+ const queryObj: any = {
480
+ ItemId: itemId,
481
+ ItemType: itemType,
482
+ Status: RentalStatusEnum.ACTIVE,
483
+ };
484
+
485
+ const options: any = {
486
+ transaction: dbTransaction,
487
+ where: queryObj,
488
+ };
489
+
490
+ const rental = await Rental._Repo.findOne(options);
491
+
492
+ if (rental) {
493
+ return true;
494
+ } else {
495
+ return false;
496
+ }
497
+ } catch (err) {
498
+ throw err;
499
+ }
500
+ }
501
+
502
+ /**
503
+ * Sets the StartDateTime property of the Rental class as custom setter.
504
+ * @param {Date} startDateTime - The start date and time of the rental.
505
+ * @throws {ClassError} Throws an error if:
506
+ * 1. startDateTime is a past date.
507
+ * 2. startDateTime is more than the EndDateTime.
508
+ * @returns {void}
509
+ */
510
+ setStartDateTime(startDateTime: Date): void {
511
+ const startDateTimeObject = new Date(startDateTime);
512
+ startDateTimeObject.setHours(0, 0, 0, 0);
513
+
514
+ /*Part 1: Make Sure Future Date Time*/
515
+ if (startDateTimeObject < new Date(new Date().setHours(0, 0, 0, 0))) {
516
+ throw new ClassError(
517
+ 'Rental',
518
+ 'RentalErrMsg02',
519
+ 'StartDateTime cannot be a past datetime.',
520
+ );
521
+ }
522
+
523
+ /*Part 2: Make Sure Less Than End Date Time*/
524
+ if (this.EndDateTime && startDateTimeObject > this.EndDateTime) {
525
+ throw new ClassError(
526
+ 'Rental',
527
+ 'RentalErrMsg03',
528
+ 'StartDateTime cannot be more than EndDateTime.',
529
+ );
530
+ }
531
+
532
+ /*Part 3: Set Status Whether Reserved or Active*/
533
+ if (startDateTimeObject > new Date(new Date().setHours(0, 0, 0, 0))) {
534
+ this._Status = RentalStatusEnum.RESERVED;
535
+ } else {
536
+ this._Status = RentalStatusEnum.ACTIVE;
537
+ }
538
+ }
539
+
540
+ public async periodEndProcess(
541
+ loginUser: LoginUser,
542
+ dbTransaction: any,
543
+ stockInventory: any,
544
+ ) {
545
+ try {
546
+ // Privilege Checking
547
+ const systemCode =
548
+ await ApplicationConfig.getComponentConfigValue('system-code');
549
+
550
+ const isPrivileged = await loginUser.checkPrivileges(
551
+ systemCode,
552
+ 'Rental – PeriodEndProcess',
553
+ );
554
+
555
+ if (!isPrivileged) {
556
+ throw new ClassError(
557
+ 'Rental',
558
+ 'RentalErrMsg04',
559
+ "You do not have 'Rental - PeriodEndProcess' privilege.",
560
+ );
561
+ }
562
+
563
+ // Validate Existing Rental
564
+ if (this.AgreementNo === undefined || this.AgreementNo === null) {
565
+ throw new ClassError(
566
+ 'Rental',
567
+ 'RentalErrMsg05',
568
+ 'Rental must be existing rental.',
569
+ );
570
+ }
571
+
572
+ // Validate Rental End Period
573
+ if (this.EndDateTime === new Date(new Date().setHours(0, 0, 0, 0))) {
574
+ throw new ClassError(
575
+ 'Rental',
576
+ 'RentalErrMsg06',
577
+ 'Rental period is not ending today.',
578
+ );
579
+ }
580
+
581
+ // Mark Rental Item as Available
582
+ await stockInventory.setAvailable(loginUser, dbTransaction);
583
+
584
+ // Capture Record Info Before Changes
585
+ const entityValueBefore = {
586
+ RentalId: this.RentalId,
587
+ CustomerId: this.CustomerId,
588
+ CustomerType: this.CustomerType,
589
+ ItemId: this.ItemId,
590
+ ItemType: this.ItemType,
591
+ PriceId: this.PriceId,
592
+ StartDateTime: this.StartDateTime,
593
+ EndDateTime: this.EndDateTime,
594
+ CancelRemarks: this.CancelRemarks,
595
+ TerminateRemarks: this.TerminateRemarks,
596
+ AgreementNo: this.AgreementNo,
597
+ AccountType: this.AccountType,
598
+ Status: this.Status,
599
+ EscheatmentYN: this.EscheatmentYN,
600
+ CreatedById: this.CreatedById,
601
+ CreatedAt: this.CreatedAt,
602
+ UpdatedById: this.UpdatedById,
603
+ UpdatedAt: this.UpdatedAt,
604
+ };
605
+
606
+ // Mark Rental as Terminated and Capture Updater Info
607
+ this.setTerminated();
608
+ this._UpdatedById = loginUser.ObjectId;
609
+ this._UpdatedAt = new Date();
610
+
611
+ // Capture Record Info after Changes
612
+ const entityValueAfter = {
613
+ RentalId: this.RentalId,
614
+ CustomerId: this.CustomerId,
615
+ CustomerType: this.CustomerType,
616
+ ItemId: this.ItemId,
617
+ ItemType: this.ItemType,
618
+ PriceId: this.PriceId,
619
+ StartDateTime: this.StartDateTime,
620
+ EndDateTime: this.EndDateTime,
621
+ CancelRemarks: this.CancelRemarks,
622
+ TerminateRemarks: this.TerminateRemarks,
623
+ AgreementNo: this.AgreementNo,
624
+ AccountType: this.AccountType,
625
+ Status: this.Status,
626
+ EscheatmentYN: this.EscheatmentYN,
627
+ CreatedById: this.CreatedById,
628
+ CreatedAt: this.CreatedAt,
629
+ UpdatedById: this.UpdatedById,
630
+ UpdatedAt: this.UpdatedAt,
631
+ };
632
+
633
+ // Record the Update Activity
634
+ const activity = new Activity();
635
+ activity.ActivityId = activity.createId();
636
+ activity.Action = ActionEnum.UPDATE;
637
+ activity.Description = 'Set Rental as Terminated';
638
+ activity.EntityType = 'Rental';
639
+ activity.EntityId = this.RentalId;
640
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
641
+ activity.EntityValueAfter = JSON.stringify(entityValueAfter);
642
+ await activity.create(loginUser.ObjectId, dbTransaction);
643
+
644
+ return this;
645
+ } catch (err) {
646
+ throw err;
647
+ }
648
+ }
649
+
650
+ async getCustomerActiveRentals(
651
+ loginUser: LoginUser,
652
+ dbTransaction: any,
653
+ CustomerId: string,
654
+ ): Promise<IRentalAttr[]> {
655
+ try {
656
+ // Part 1: Privilege Checking
657
+ // Call loginUser.checkPrivileges() by passing:
658
+ // SystemCode: <get_from_app_config>
659
+ // PrivilegeCode: "RENTAL_VIEW"
660
+ const systemCode =
661
+ ApplicationConfig.getComponentConfigValue('system-code');
662
+ const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_VIEW');
663
+
664
+ if (!isPrivileged) {
665
+ throw new ClassError(
666
+ 'Rental',
667
+ 'RentalErrMsg01',
668
+ "You do not have 'Rental - View' privilege.",
669
+ );
670
+ }
671
+
672
+ // Part 2: Retrieve Rentals and Returns
673
+ // Call Rental._Repo findAll method by passing:
674
+ // where:
675
+ // Status: "Active"
676
+ // [Op.OR]:
677
+ // CustomerId: Params.CustomerId
678
+ // '$JointHirers.CustomerId$': Params.CustomerId
679
+ // include:
680
+ // model: JointHirerModel
681
+ // attributes: []
682
+ const query = `
683
+ SELECT
684
+ r.*
685
+ FROM
686
+ rental_Rental r
687
+ LEFT JOIN
688
+ rental_JointHirer jh ON r.RentalId = jh.RentalId
689
+ WHERE
690
+ r.Status = 'Active'
691
+ AND (
692
+ r.CustomerId = '${CustomerId}'
693
+ OR jh.CustomerId = '${CustomerId}'
694
+ )
695
+ GROUP BY
696
+ r.RentalId
697
+ `;
698
+ const db = rentalDb.getConnection();
699
+ const result = await db.query(query, {
700
+ type: QueryTypes.SELECT,
701
+ transaction: dbTransaction,
702
+ model: RentalModel,
703
+ mapToModel: true,
704
+ });
705
+
706
+ // Format the returned records
707
+ const records: IRentalAttr[] = result.map((record: RentalModel) => {
708
+ return {
709
+ RentalId: record.RentalId,
710
+ CustomerId: record.CustomerId,
711
+ CustomerType: record.CustomerType,
712
+ ItemId: record.ItemId,
713
+ ItemType: record.ItemType,
714
+ PriceId: record.PriceId,
715
+ StartDateTime: record.StartDateTime,
716
+ EndDateTime: record.EndDateTime,
717
+ CancelRemarks: record.CancelRemarks,
718
+ TerminateRemarks: record.TerminateRemarks,
719
+ AgreementNo: record.AgreementNo,
720
+ AccountType: record.AccountType,
721
+ Status: record.Status,
722
+ EscheatmentYN: record.EscheatmentYN,
723
+ CreatedById: record.CreatedById,
724
+ CreatedAt: record.CreatedAt,
725
+ UpdatedById: record.UpdatedById,
726
+ UpdatedAt: record.UpdatedAt,
727
+ };
728
+ });
729
+ // Return the returned records.
730
+ return records;
731
+ } catch (error) {
732
+ throw error;
733
+ }
734
+ }
735
+
736
+ async getJointHirers(dbTransaction: any) {
737
+ try {
738
+ if (!this.RentalId) {
739
+ throw new ClassError('Rental', 'RentalErrMsg01', 'RentalId is missing');
740
+ }
741
+ if (this.AccountType !== RentalAccountTypeEnum.JOINT) {
742
+ throw new ClassError(
743
+ 'Rental',
744
+ 'RentalErrMsg07',
745
+ 'This rental does not have joint hirers.',
746
+ );
747
+ }
748
+
749
+ const jointHirers = await Rental._JointHirerRepo.findAll({
750
+ where: {
751
+ RentalId: this.RentalId,
752
+ },
753
+ transaction: dbTransaction,
754
+ });
755
+ // Map the jointHirers to JointHirer instances
756
+ const jointHirerInstances = Promise.all(
757
+ jointHirers.map(async (hirer: JointHirerModel) => {
758
+ return await JointHirer.init(hirer.HirerId, dbTransaction);
759
+ }),
760
+ );
761
+ return jointHirerInstances;
762
+ } catch (error) {
763
+ console.error('Error in getJointHirers:', error);
764
+ throw error;
765
+ }
766
+ }
767
+
768
+ async getCustomerIds(loginUser: LoginUser, dbTransaction: any) {
769
+ try {
770
+ // Part 1: Privilege Checking
771
+ // Call loginUser.checkPrivileges() by passing:
772
+ // SystemCode: <get_from_app_config>
773
+ // PrivilegeCode: "RENTAL_VIEW"
774
+ const systemCode =
775
+ ApplicationConfig.getComponentConfigValue('system-code');
776
+ const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_VIEW');
777
+
778
+ if (!isPrivileged) {
779
+ throw new ClassError(
780
+ 'Rental',
781
+ 'RentalErrMsg01',
782
+ "You do not have 'Rental - View' privilege.",
783
+ );
784
+ }
785
+
786
+ // Part 2: Validation
787
+ // Make sure this.RentalId exists, if not throw new ClassError by passing
788
+ if (!this.RentalId) {
789
+ throw new ClassError('Rental', 'RentalErrMsg01', 'RentalId is missing');
790
+ }
791
+
792
+ //Part 3: Retrieve Listing and Returns
793
+ // 3.1 Call Rental._JointHirerRepo findAll method by passing:
794
+ // where:
795
+ // RentalId: this.RentalId
796
+ // dbTransaction
797
+ const options: any = {
798
+ where: {
799
+ RentalId: this.RentalId,
800
+ Status: 'Active',
801
+ },
802
+ transaction: dbTransaction,
803
+ };
804
+
805
+ const joinHirers = await Rental._JointHirerRepo.findAll(options);
806
+
807
+ // 3.2 Create a new array variable and set its value to joint hirer and Rental.CustomerId
808
+ // array translated to only CustomerId. Then, append this.CustomerId to the array.
809
+ const customerIds: string[] = [this.CustomerId];
810
+ for (let i = 0; i < joinHirers.length; i++) {
811
+ const jointHirer = joinHirers[i];
812
+ customerIds.push(jointHirer.CustomerId);
813
+ }
814
+
815
+ // 3.3 Return the array.
816
+ return customerIds;
817
+ } catch (error) {
818
+ throw error;
819
+ }
820
+ }
821
+
822
+ async signAgreement(
823
+ loginUser: LoginUser,
824
+ party: string,
825
+ PartyId: string,
826
+ PartyType: string,
827
+ dbTransaction: any,
828
+ statusAfterSign?: RentalStatusEnum | string,
829
+ method?: AgreementSignatureVerificationMethodEnum,
830
+ justification?: string,
831
+ ) {
832
+ try {
833
+ // Part 1: Privilege Checking
834
+ // Call loginUser.checkPrivileges() by passing:
835
+ // SystemCode: <get_from_app_config>
836
+ // PrivilegeCode: "RENTAL_SIGN"
837
+ const systemCode =
838
+ ApplicationConfig.getComponentConfigValue('system-code');
839
+ const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_SIGN');
840
+
841
+ if (!isPrivileged) {
842
+ throw new ClassError(
843
+ 'Rental',
844
+ 'RentalErrMsg01',
845
+ "You do not have 'RENTAL_SIGN' privilege.",
846
+ );
847
+ }
848
+
849
+ // Part 2: Validation
850
+ // Make sure this.Status is "Pending Signing" and agreementStatus is "Generated", if not throw new ClassError
851
+ const agreement = await Agreement.init(this.AgreementNo, dbTransaction);
852
+ if (
853
+ this.Status !== RentalStatusEnum.PENDING_SIGNING &&
854
+ agreement.Status !== AggrementStatusEnum.GENERATED
855
+ ) {
856
+ throw new ClassError(
857
+ 'Rental',
858
+ 'RentalErrMsg01',
859
+ 'Rental is not ready to be signed yet.',
860
+ );
861
+ }
862
+
863
+ //Make sure CustomerId inside the listing and SignatureStatus is "Pending"
864
+ const signatureList = await Agreement.getSignatureList(
865
+ loginUser,
866
+ this.AgreementNo,
867
+ dbTransaction,
868
+ );
869
+ const customerSignature = signatureList.find(
870
+ (sig) =>
871
+ sig.PartyId === PartyId &&
872
+ sig.PartyType === PartyType &&
873
+ sig.Party === party &&
874
+ sig.SignatureStatus === AgreementSignatureStatusEnum.PENDING,
875
+ );
876
+
877
+ if (!customerSignature) {
878
+ throw new ClassError(
879
+ 'Rental',
880
+ 'RentalErrMsg01',
881
+ 'Signature is not pending.',
882
+ );
883
+ }
884
+
885
+ //Update rental_AgreementSignature
886
+ const signaturePayload = {
887
+ SignatureStatus: AgreementSignatureStatusEnum.SIGNED,
888
+ SignedAt: new Date(),
889
+ UpdatedById: loginUser.ObjectId,
890
+ UpdatedAt: new Date(),
891
+ VerificationMethod: method,
892
+ VerificationJustification: justification,
893
+ VerifiedById: loginUser.ObjectId,
894
+ };
895
+
896
+ await Rental._AgreementSignatureRepo.update(signaturePayload, {
897
+ where: {
898
+ AgreementNo: this.AgreementNo,
899
+ Party: party,
900
+ PartyId: PartyId,
901
+ PartyType: PartyType,
902
+ },
903
+ transaction: dbTransaction,
904
+ });
905
+
906
+ const signatureActivity = new Activity();
907
+ signatureActivity.ActivityId = signatureActivity.createId();
908
+ signatureActivity.Action = ActionEnum.UPDATE;
909
+ signatureActivity.Description = 'Update hirer signature';
910
+ signatureActivity.EntityType = 'AgreementSignature';
911
+ signatureActivity.EntityId = this.AgreementNo;
912
+ signatureActivity.EntityValueBefore = JSON.stringify(customerSignature);
913
+ signatureActivity.EntityValueAfter = JSON.stringify(signaturePayload);
914
+ await signatureActivity.create(loginUser.ObjectId, dbTransaction);
915
+
916
+ const updatedSignatureList = await Agreement.getSignatureList(
917
+ loginUser,
918
+ this.AgreementNo,
919
+ dbTransaction,
920
+ );
921
+
922
+ const pendingSignatures = updatedSignatureList.filter(
923
+ (sig) => sig.SignatureStatus === 'Pending',
924
+ );
925
+ if (pendingSignatures.length > 0) {
926
+ return;
927
+ }
928
+
929
+ //Part 3: Update Agreement Status
930
+ // 3.1 Set EntityValueBefore to current agreement instance.
931
+ const entityValueAgreementBefore = {
932
+ AgreementNo: agreement.AgreementNo,
933
+ Status: agreement.Status,
934
+ DateSigned: agreement.DateSigned,
935
+ };
936
+
937
+ // 3.2 Set below agreement attributes:
938
+ // DateSigned: current date & time
939
+ // Status: "Signed"
940
+ const payload = {
941
+ DateSigned: new Date(),
942
+ Status: AggrementStatusEnum.SIGNED,
943
+ };
944
+
945
+ // 3.3 Call Rental._AgreementRepo update()
946
+ await Rental._AgreementRepo.update(payload, {
947
+ where: {
948
+ AgreementNo: this.AgreementNo,
949
+ },
950
+ transaction: dbTransaction,
951
+ });
952
+
953
+ const entityValueAgreementAfter = {
954
+ entityValueAgreementBefore,
955
+ ...payload,
956
+ };
957
+
958
+ // Part 4: Record Update Agreement Activity
959
+ const activity = new Activity();
960
+ activity.ActivityId = activity.createId();
961
+ activity.Action = ActionEnum.UPDATE;
962
+ activity.Description = 'Update agreement';
963
+ activity.EntityType = 'RentalAgreement';
964
+ activity.EntityId = this.AgreementNo;
965
+ activity.EntityValueBefore = JSON.stringify(entityValueAgreementBefore);
966
+ activity.EntityValueAfter = JSON.stringify(entityValueAgreementAfter);
967
+ await activity.create(loginUser.ObjectId, dbTransaction);
968
+
969
+ // Part 5: Update Rental Status
970
+ // 5.1 Set EntityValueBefore to current rental instance.
971
+ const entityValueRentalBefore = {
972
+ RentalId: this.RentalId,
973
+ CustomerId: this.CustomerId,
974
+ CustomerType: this.CustomerType,
975
+ ItemId: this.ItemId,
976
+ ItemType: this.ItemType,
977
+ PriceId: this.PriceId,
978
+ StartDateTime: this.StartDateTime,
979
+ EndDateTime: this.EndDateTime,
980
+ CancelRemarks: this.CancelRemarks,
981
+ TerminateRemarks: this.TerminateRemarks,
982
+ AgreementNo: this.AgreementNo,
983
+ AccountType: this.AccountType,
984
+ Status: this.Status,
985
+ EscheatmentYN: this.EscheatmentYN,
986
+ CreatedById: this.CreatedById,
987
+ CreatedAt: this.CreatedAt,
988
+ UpdatedById: this.UpdatedById,
989
+ UpdatedAt: this.UpdatedAt,
990
+ };
991
+ // 5.2: Set below rental attributes:
992
+ // Status: "Pending Key Collection"
993
+ // UpdatedById: loginUser.ObjectId
994
+ // UpdatedAt: current date & time
995
+
996
+ this._Status = statusAfterSign
997
+ ? statusAfterSign
998
+ : RentalStatusEnum.ACTIVE;
999
+
1000
+ const payloadRental = {
1001
+ Status: this._Status,
1002
+ UpdatedById: loginUser.ObjectId,
1003
+ UpdatedAt: new Date(),
1004
+ };
1005
+
1006
+ // 5.3: Call Rental._Repo update() method by passing:
1007
+ // populate rental instance attributes
1008
+ // dbTransaction
1009
+ await Rental._Repo.update(payloadRental, {
1010
+ where: {
1011
+ RentalId: this.RentalId,
1012
+ },
1013
+ transaction: dbTransaction,
1014
+ });
1015
+
1016
+ const entityValueRentalAfter = {
1017
+ entityValueRentalBefore,
1018
+ ...payloadRental,
1019
+ };
1020
+
1021
+ // Part 6: Record Update Agreement Activity
1022
+ const rentalActivity = new Activity();
1023
+ rentalActivity.ActivityId = activity.createId();
1024
+ rentalActivity.Action = ActionEnum.UPDATE;
1025
+ rentalActivity.Description = 'Sign rental agreement';
1026
+ rentalActivity.EntityType = 'Rental';
1027
+ rentalActivity.EntityId = this.RentalId;
1028
+ rentalActivity.EntityValueBefore = JSON.stringify(
1029
+ entityValueRentalBefore,
1030
+ );
1031
+ rentalActivity.EntityValueAfter = JSON.stringify(entityValueRentalAfter);
1032
+ await rentalActivity.create(loginUser.ObjectId, dbTransaction);
1033
+ } catch (error) {
1034
+ throw error;
1035
+ }
1036
+ }
1037
+
1038
+ async generateAgreement(
1039
+ loginUser: LoginUser,
1040
+ dbTransaction: any,
1041
+ MediaId: string,
1042
+ ) {
1043
+ //This method will generate a new rental agreement.
1044
+ try {
1045
+ // Part 1: Privilege Checking
1046
+ // Call loginUser.checkPrivileges() by passing:
1047
+ // SystemCode: "<get_from_app_config>"
1048
+ // PrivilegeCode: "RENTAL_AGREEMENT_CREATE"
1049
+
1050
+ const systemCode =
1051
+ ApplicationConfig.getComponentConfigValue('system-code');
1052
+ const isPrivileged = loginUser.checkPrivileges(
1053
+ systemCode,
1054
+ 'RENTAL_AGREEMENT_CREATE',
1055
+ );
1056
+
1057
+ if (!isPrivileged) {
1058
+ throw new ClassError(
1059
+ 'Rental',
1060
+ 'RentalErrMsg01',
1061
+ "You do not have 'RENTAL_AGREEMENT_CREATE' privilege.",
1062
+ );
1063
+ }
1064
+
1065
+ // Part 2: Validation
1066
+ // Instantiate existing RentalAgreement by passing:
1067
+ // dbTransaction
1068
+ // AgreementNo: this.AgreementNo
1069
+ // Make sure Params.MediaId exists, if not throw new ClassError by passing:
1070
+ // Classname: "Rental"
1071
+ // MessageCode: "RentalErrMsg0X"
1072
+ // Message: "MediaId is required."
1073
+ const agreement = await Agreement.init(this.AgreementNo, dbTransaction);
1074
+ if (!MediaId) {
1075
+ throw new ClassError(
1076
+ 'Rental',
1077
+ 'RentalErrMsg0X',
1078
+ 'MediaId is required.',
1079
+ );
1080
+ }
1081
+
1082
+ // Part 3: Update Agreement Record
1083
+ // Set EntityValueBefore to the agreement instance.
1084
+ // Set below agreement attributes:
1085
+ // Status: "Generated"
1086
+ // MediaId: Params.MediaId
1087
+
1088
+ const EntityValueBefore = agreement;
1089
+ agreement.Status = AggrementStatusEnum.GENERATED;
1090
+ agreement.MediaId = MediaId;
1091
+
1092
+ // Call Rental._AgreementRepo update method by passing:
1093
+ // Status: agreement.Status
1094
+ // MediaId: agreement.MediaId
1095
+ // dbTransaction
1096
+
1097
+ await Rental._AgreementRepo.update(
1098
+ {
1099
+ Status: agreement.Status,
1100
+ MediaId: agreement.MediaId,
1101
+ },
1102
+ {
1103
+ where: {
1104
+ AgreementNo: this.AgreementNo,
1105
+ },
1106
+ transaction: dbTransaction,
1107
+ },
1108
+ );
1109
+
1110
+ // Part 4: Record Update Agreement Activity
1111
+ // Initialise EntityValueAfter variable and set to agreement instance
1112
+ const EntityValueAfter = agreement;
1113
+ // Instantiate new activity from Activity class, call createId() method, then set:
1114
+ const activity = new Activity();
1115
+ // Action: ActionEnum.UPDATE
1116
+ // Description: "Generate agreement."
1117
+ // EntityType: "RentalAgreement"
1118
+ // EntityId: this.AgreementNo
1119
+ // EntityValueBefore: EntityValueBefore
1120
+ // EntityValueAfter: EntityValueAfter
1121
+ activity.ActivityId = activity.createId();
1122
+ activity.Action = ActionEnum.UPDATE;
1123
+ activity.Description = 'Generate agreement.';
1124
+ activity.EntityType = 'RentalAgreement';
1125
+ activity.EntityId = this.AgreementNo;
1126
+ activity.EntityValueBefore = JSON.stringify(EntityValueBefore);
1127
+ activity.EntityValueAfter = JSON.stringify(EntityValueAfter);
1128
+
1129
+ // Call new activity create method by passing:
1130
+ // dbTransaction
1131
+ // userId: loginUser.ObjectId
1132
+ await activity.create(loginUser.ObjectId, dbTransaction);
1133
+
1134
+ // Part 5: Add Record To Agreement History Table
1135
+ // Make sure there is a private static readonly _AgreementHistoryRepo variable.
1136
+ // Set newRecord to an object with below key-value:
1137
+ // AgreementNo: this.AgreementNo
1138
+ // MediaId: params.MediaId
1139
+ // ActivityCompleted: "Agreement Generated"
1140
+ // CreatedAt: Current Timestamp
1141
+ // Use _AgreementHistoryRepo.create() method and pass newRecord and dbTransaction.
1142
+ const agreementHistory = await Rental._AgreementHistoryRepo.create(
1143
+ {
1144
+ AgreementNo: this.AgreementNo,
1145
+ MediaId,
1146
+ ActivityCompleted: 'Agreement Generated',
1147
+ CreatedAt: new Date(),
1148
+ },
1149
+ { transaction: dbTransaction },
1150
+ );
1151
+
1152
+ // Part 6: Record Agreement History Activity
1153
+ // Initialise EntityValueAfter variable and set to newRecord from previous part.
1154
+ // Instantiate new activity from Activity class, call createId() method, then set:
1155
+ // Action: ActionEnum.CREATE
1156
+ // Description: "Generate agreement."
1157
+ // EntityType: "RentalAgreementHistory"
1158
+ // EntityId: HistoryId from previous part.
1159
+ // EntityValueBefore: empty object.
1160
+ // EntityValueAfter: EntityValueAfter
1161
+ // Call new activity create method by passing:
1162
+ // dbTransaction
1163
+ // userId: loginUser.ObjectId
1164
+ const entityValueAfter = agreementHistory.get({ plain: true });
1165
+ const activityHistory = new Activity();
1166
+ activityHistory.ActivityId = activityHistory.createId();
1167
+ activityHistory.Action = ActionEnum.CREATE;
1168
+ activityHistory.Description = 'Generate agreement.';
1169
+ activityHistory.EntityType = 'RentalAgreementHistory';
1170
+ activityHistory.EntityId = agreementHistory.HistoryId.toString();
1171
+ activityHistory.EntityValueBefore = JSON.stringify({});
1172
+ activityHistory.EntityValueAfter = JSON.stringify(entityValueAfter);
1173
+ await activityHistory.create(loginUser.ObjectId, dbTransaction);
1174
+ } catch (error) {
1175
+ throw error;
1176
+ }
1177
+ }
1178
+
1179
+ public toJSON(): IRentalAttr {
1180
+ return {
1181
+ RentalId: this.RentalId,
1182
+ CustomerId: this.CustomerId,
1183
+ CustomerType: this.CustomerType,
1184
+ ItemId: this.ItemId,
1185
+ ItemType: this.ItemType,
1186
+ PriceId: this.PriceId,
1187
+ StartDateTime: this.StartDateTime,
1188
+ EndDateTime: this.EndDateTime,
1189
+ Status: this.Status,
1190
+ CancelRemarks: this.CancelRemarks,
1191
+ TerminateRemarks: this.TerminateRemarks,
1192
+ EscheatmentYN: this.EscheatmentYN,
1193
+ AgreementNo: this.AgreementNo,
1194
+ AccountType: this.AccountType,
1195
+ CreatedById: this.CreatedById,
1196
+ CreatedAt: this.CreatedAt,
1197
+ UpdatedById: this.UpdatedById,
1198
+ UpdatedAt: this.UpdatedAt,
1199
+ };
1200
+ }
1201
+
1202
+ public async getInvoices(
1203
+ loginUser: LoginUser,
1204
+ dbTransaction: any,
1205
+ accountingSystem?: IAccountSystem,
1206
+ ) {
1207
+ try {
1208
+ // Part 1: Privilege Checking
1209
+ // Call loginUser.checkPrivileges() by passing:
1210
+ // SystemCode: <get_from_app_config>
1211
+ // PrivilegeCode: "RENTAL_VIEW_INVOICE"
1212
+ const systemCode =
1213
+ ApplicationConfig.getComponentConfigValue('system-code');
1214
+ const isPrivileged = loginUser.checkPrivileges(
1215
+ systemCode,
1216
+ 'RENTAL_VIEW_INVOICE',
1217
+ );
1218
+
1219
+ if (!isPrivileged) {
1220
+ throw new ClassError(
1221
+ 'Rental',
1222
+ 'RentalErrMsg01',
1223
+ "You do not have 'RENTAL_VIEW_INVOICE' privilege.",
1224
+ );
1225
+ }
1226
+
1227
+ // Part 2: Validation
1228
+ // Make sure this._ObjectId exists, if not throw new ClassError by passing
1229
+ if (!this.ObjectId) {
1230
+ throw new ClassError(
1231
+ 'Rental',
1232
+ 'RentalErrMsg01',
1233
+ 'ObjectId is missing.',
1234
+ );
1235
+ }
1236
+
1237
+ // Part 3: Check Existing Invoices
1238
+ if (this.Invoices.length > 0) {
1239
+ return this.Invoices;
1240
+ }
1241
+
1242
+ // Part 4: Retrieve Invoices and Returns
1243
+ const search = {
1244
+ DocType: DocType.INVOICE,
1245
+ RelatedObjectId: this.ObjectId,
1246
+ RelatedObjectType: this.ObjectType,
1247
+ };
1248
+
1249
+ const documents = await Document.findAll(
1250
+ loginUser,
1251
+ dbTransaction,
1252
+ undefined,
1253
+ undefined,
1254
+ search,
1255
+ undefined,
1256
+ accountingSystem,
1257
+ );
1258
+
1259
+ this.Invoices = documents.rows.map((doc) => {
1260
+ const document = new Document(dbTransaction, doc);
1261
+ return document;
1262
+ });
1263
+
1264
+ return this.Invoices;
1265
+ } catch (error) {
1266
+ throw error;
1267
+ }
1268
+ }
1269
+
1270
+ public async getItem(dbTransaction: any): Promise<any> {
1271
+ if (this.Item) {
1272
+ return this.Item;
1273
+ } else {
1274
+ const ItemClass = ItemClassMap[this.ItemType];
1275
+
1276
+ if (!ItemClass || typeof ItemClass.init !== 'function') {
1277
+ throw new Error(`Invalid or unregistered ItemType: ${this.ItemType}`);
1278
+ }
1279
+
1280
+ ItemClass._Repo = ItemClass._Repo || ItemClass.getRepo();
1281
+
1282
+ if (!ItemClass._Repo) {
1283
+ throw new Error(
1284
+ `ItemType ${this.ItemType} does not have a repository.`,
1285
+ );
1286
+ }
1287
+
1288
+ const itemInstance = await ItemClass.init(this.ItemId, dbTransaction);
1289
+
1290
+ if (!itemInstance) {
1291
+ throw new Error(`${this.ItemType} not found with ID ${this.ItemId}`);
1292
+ }
1293
+ this.Item = itemInstance;
1294
+
1295
+ // Make sure item has setAvailable method
1296
+ if (typeof this.Item.setAvailable !== 'function') {
1297
+ throw new Error(`${this.ItemType} does not implement setAvailable()`);
1298
+ }
1299
+ return this.Item;
1300
+ }
1301
+ }
1302
+
1303
+ public async cancel(
1304
+ loginUser: LoginUser,
1305
+ dbTransaction: any,
1306
+ remarks: string,
1307
+ ): Promise<Rental> {
1308
+ try {
1309
+ // Part 1: Privilege Checking
1310
+ const systemCode =
1311
+ ApplicationConfig.getComponentConfigValue('system-code');
1312
+ const isPrivileged = await loginUser.checkPrivileges(
1313
+ systemCode,
1314
+ 'RENTAL_CANCEL',
1315
+ );
1316
+
1317
+ if (!isPrivileged) {
1318
+ throw new ClassError(
1319
+ 'Rental',
1320
+ 'RentalErrMsg01',
1321
+ "You do not have 'RENTAL_CANCEL' privilege.",
1322
+ );
1323
+ }
1324
+
1325
+ // Part 2: Validation
1326
+ if (!this.ObjectId) {
1327
+ throw new ClassError(
1328
+ 'Rental',
1329
+ 'RentalErrMsg01',
1330
+ 'Rental not found. Rental Id is empty.',
1331
+ );
1332
+ }
1333
+
1334
+ if (
1335
+ this.Status === RentalStatusEnum.ACTIVE ||
1336
+ this.Status === RentalStatusEnum.SUSPENDED
1337
+ ) {
1338
+ throw new ClassError(
1339
+ 'Rental',
1340
+ 'RentalErrMsg01',
1341
+ `Rental already ${this.Status}, please do termination process.`,
1342
+ );
1343
+ }
1344
+
1345
+ if (!remarks) {
1346
+ throw new ClassError(
1347
+ 'Rental',
1348
+ 'RentalErrMsg01',
1349
+ 'Cancellation remarks is required.',
1350
+ );
1351
+ }
1352
+
1353
+ // Part 3: Capture Record Info Before Changes
1354
+ const entityValueBefore = this.toJSON();
1355
+
1356
+ // Part 4: Update Rental Status and Remarks
1357
+ this._Status = RentalStatusEnum.CANCELLED;
1358
+ this.CancelRemarks = remarks;
1359
+ this._UpdatedById = loginUser.ObjectId;
1360
+ this._UpdatedAt = new Date();
1361
+
1362
+ // Part 5: Update Rental Record
1363
+ await Rental._Repo.update(
1364
+ {
1365
+ Status: this.Status,
1366
+ CancelRemarks: this.CancelRemarks,
1367
+ UpdatedById: this.UpdatedById,
1368
+ UpdatedAt: this.UpdatedAt,
1369
+ },
1370
+ {
1371
+ where: {
1372
+ RentalId: this.RentalId,
1373
+ },
1374
+ transaction: dbTransaction,
1375
+ },
1376
+ );
1377
+
1378
+ // Part 6: Mark Item as Available
1379
+ const item = await this.getItem(dbTransaction);
1380
+
1381
+ await item.setAvailable(loginUser, dbTransaction);
1382
+
1383
+ // Part 7: Capture Record Info After Changes
1384
+ const entityValueAfter = this.toJSON();
1385
+ // Part 8: Record Activity
1386
+ const activity = new Activity();
1387
+ activity.ActivityId = activity.createId();
1388
+ activity.Action = ActionEnum.UPDATE;
1389
+ activity.Description = 'Rental Cancellation';
1390
+ activity.EntityType = this.ObjectType;
1391
+ activity.EntityId = this.ObjectId;
1392
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
1393
+ activity.EntityValueAfter = JSON.stringify(entityValueAfter);
1394
+ await activity.create(loginUser.ObjectId, dbTransaction);
1395
+ return this;
1396
+ } catch (error) {
1397
+ throw error;
1398
+ }
1399
+ }
1400
+
1401
+ public async update(
1402
+ loginUser: LoginUser,
1403
+ dbTransaction: any,
1404
+ updates: Partial<IRentalAttr>,
1405
+ ): Promise<Rental> {
1406
+ try {
1407
+ // Part 1: Privilege Checking
1408
+ const systemCode =
1409
+ ApplicationConfig.getComponentConfigValue('system-code');
1410
+ const isPrivileged = await loginUser.checkPrivileges(
1411
+ systemCode,
1412
+ 'RENTAL_UPDATE',
1413
+ );
1414
+
1415
+ if (!isPrivileged) {
1416
+ throw new ClassError(
1417
+ 'Rental',
1418
+ 'RentalErrMsg01',
1419
+ "You do not have 'RENTAL_UPDATE' privilege.",
1420
+ );
1421
+ }
1422
+
1423
+ // Part 2: Validation
1424
+ if (!this.ObjectId) {
1425
+ throw new ClassError(
1426
+ 'Rental',
1427
+ 'RentalErrMsg01',
1428
+ 'Rental not found. Rental Id is empty.',
1429
+ );
1430
+ }
1431
+
1432
+ // Part 3: Capture Record Info Before Changes
1433
+ const entityValueBefore = this.toJSON();
1434
+
1435
+ // Part 4: Update Rental Record
1436
+ await Rental._Repo.update(updates, {
1437
+ where: {
1438
+ RentalId: this.RentalId,
1439
+ },
1440
+ transaction: dbTransaction,
1441
+ });
1442
+
1443
+ // Part 5: Update object instance properties and capture after changes
1444
+ Object.assign(this, updates);
1445
+ this._UpdatedById = loginUser.ObjectId;
1446
+ this._UpdatedAt = new Date();
1447
+
1448
+ const entityValueAfter = this.toJSON();
1449
+
1450
+ // Part 6: Record Activity
1451
+ const activity = new Activity();
1452
+ activity.ActivityId = activity.createId();
1453
+ activity.Action = ActionEnum.UPDATE;
1454
+ activity.Description = 'Update Rental';
1455
+ activity.EntityType = this.ObjectType;
1456
+ activity.EntityId = this.ObjectId;
1457
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
1458
+ activity.EntityValueAfter = JSON.stringify(entityValueAfter);
1459
+ await activity.create(loginUser.ObjectId, dbTransaction);
1460
+
1461
+ return this;
1462
+ } catch (error) {
1463
+ throw error;
1464
+ }
1465
+ }
1466
+ }