@tomei/rental 0.12.4 → 0.13.0

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 (99) hide show
  1. package/.commitlintrc.json +22 -22
  2. package/.gitlab-ci.yml +16 -16
  3. package/.husky/commit-msg +15 -15
  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/src/components/agreement/agreement.d.ts +6 -1
  9. package/dist/src/components/agreement/agreement.js +39 -0
  10. package/dist/src/components/agreement/agreement.js.map +1 -1
  11. package/dist/src/components/hirer-signature/hirer-signature.d.ts +27 -0
  12. package/dist/src/components/hirer-signature/hirer-signature.js +112 -0
  13. package/dist/src/components/hirer-signature/hirer-signature.js.map +1 -0
  14. package/dist/src/components/hirer-signature/hirer-signature.repository.d.ts +8 -0
  15. package/dist/src/components/hirer-signature/hirer-signature.repository.js +67 -0
  16. package/dist/src/components/hirer-signature/hirer-signature.repository.js.map +1 -0
  17. package/dist/src/components/rental/rental.d.ts +3 -1
  18. package/dist/src/components/rental/rental.js +84 -16
  19. package/dist/src/components/rental/rental.js.map +1 -1
  20. package/dist/src/database.js +2 -0
  21. package/dist/src/database.js.map +1 -1
  22. package/dist/src/enum/hirer-signature-status.enum.d.ts +4 -0
  23. package/dist/src/enum/hirer-signature-status.enum.js +9 -0
  24. package/dist/src/enum/hirer-signature-status.enum.js.map +1 -0
  25. package/dist/src/enum/hirer-type.enum.d.ts +4 -0
  26. package/dist/src/enum/hirer-type.enum.js +9 -0
  27. package/dist/src/enum/hirer-type.enum.js.map +1 -0
  28. package/dist/src/enum/index.d.ts +3 -1
  29. package/dist/src/enum/index.js +5 -1
  30. package/dist/src/enum/index.js.map +1 -1
  31. package/dist/src/index.d.ts +3 -1
  32. package/dist/src/index.js +5 -1
  33. package/dist/src/index.js.map +1 -1
  34. package/dist/src/interfaces/hirer-signature-attr.interface.d.ts +14 -0
  35. package/dist/src/interfaces/hirer-signature-attr.interface.js +3 -0
  36. package/dist/src/interfaces/hirer-signature-attr.interface.js.map +1 -0
  37. package/dist/src/interfaces/index.d.ts +3 -1
  38. package/dist/src/interfaces/response-hirer-signature-attr.interface.d.ts +15 -0
  39. package/dist/src/interfaces/response-hirer-signature-attr.interface.js +3 -0
  40. package/dist/src/interfaces/response-hirer-signature-attr.interface.js.map +1 -0
  41. package/dist/src/models/agreement.entity.d.ts +2 -0
  42. package/dist/src/models/agreement.entity.js +5 -0
  43. package/dist/src/models/agreement.entity.js.map +1 -1
  44. package/dist/src/models/hirer-signature.entity.d.ts +16 -0
  45. package/dist/src/models/hirer-signature.entity.js +100 -0
  46. package/dist/src/models/hirer-signature.entity.js.map +1 -0
  47. package/dist/src/models/index.d.ts +2 -1
  48. package/dist/src/models/index.js +3 -1
  49. package/dist/src/models/index.js.map +1 -1
  50. package/dist/tsconfig.tsbuildinfo +1 -1
  51. package/eslint.config.mjs +58 -58
  52. package/jest.config.js +10 -10
  53. package/migrations/booking-table-migration.js +79 -79
  54. package/migrations/hirer-signature-table-migration.js +64 -0
  55. package/migrations/joint-hirer-table-migration.js +52 -52
  56. package/migrations/rental-aggrement-table-migration.js +30 -30
  57. package/migrations/rental-price-table-migration.js +32 -32
  58. package/migrations/rental-table-migrations.js +96 -96
  59. package/package.json +75 -75
  60. package/sonar-project.properties +12 -12
  61. package/src/components/agreement/agreement.repository.ts +54 -54
  62. package/src/components/agreement/agreement.ts +117 -49
  63. package/src/components/booking/booking.repository.ts +51 -51
  64. package/src/components/booking/booking.ts +492 -492
  65. package/src/components/hirer-signature/hirer-signature.repository.ts +54 -0
  66. package/src/components/hirer-signature/hirer-signature.ts +140 -0
  67. package/src/components/joint-hirer/joint-hirer.repository.ts +54 -54
  68. package/src/components/joint-hirer/joint-hirer.ts +137 -137
  69. package/src/components/rental/rental.repository.ts +51 -51
  70. package/src/components/rental/rental.ts +1073 -963
  71. package/src/components/rental-price/rental-price.repository.ts +54 -54
  72. package/src/components/rental-price/rental-price.ts +100 -100
  73. package/src/database.ts +29 -27
  74. package/src/enum/account-type.enum.ts +4 -4
  75. package/src/enum/booking.enum.ts +5 -5
  76. package/src/enum/hirer-signature-status.enum.ts +4 -0
  77. package/src/enum/hirer-type.enum.ts +4 -0
  78. package/src/enum/index.ts +15 -11
  79. package/src/enum/rental-status.enum.ts +39 -39
  80. package/src/index.ts +32 -28
  81. package/src/interfaces/agreement-attr.interface.ts +7 -7
  82. package/src/interfaces/booking-attr.interface.ts +19 -19
  83. package/src/interfaces/booking-find-all-search-attr.interface.ts +12 -12
  84. package/src/interfaces/hirer-signature-attr.interface.ts +15 -0
  85. package/src/interfaces/index.ts +19 -15
  86. package/src/interfaces/joint-hirer-attr.interface.ts +10 -10
  87. package/src/interfaces/rental-attr.interface.ts +25 -25
  88. package/src/interfaces/rental-find-all-search-attr.interface.ts +11 -11
  89. package/src/interfaces/rental-price-attr.interface.ts +7 -7
  90. package/src/interfaces/response-hirer-signature-attr.interface.ts +16 -0
  91. package/src/models/agreement.entity.ts +43 -39
  92. package/src/models/booking.entity.ts +105 -105
  93. package/src/models/hirer-signature.entity.ts +81 -0
  94. package/src/models/index.ts +15 -13
  95. package/src/models/joint-hirer.entity.ts +63 -63
  96. package/src/models/rental-price.entity.ts +38 -38
  97. package/src/models/rental.entity.ts +133 -133
  98. package/tsconfig.build.json +5 -5
  99. package/tsconfig.json +24 -24
@@ -1,963 +1,1073 @@
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
-
22
- export class Rental extends ObjectBase {
23
- ObjectId: string;
24
- ObjectName: string;
25
- ObjectType = 'Rental';
26
- TableName: string;
27
- CustomerId: string;
28
- CustomerType: string;
29
- ItemId: string;
30
- ItemType: string;
31
- PriceId: string;
32
- StartDateTime: Date;
33
- EndDateTime: Date;
34
- CancelRemarks: string;
35
- TerminateRemarks: string;
36
- AgreementNo: string;
37
- AccountType: RentalAccountTypeEnum;
38
- JointHirers: JointHirer[] = [];
39
- protected _Status: RentalStatusEnum;
40
- protected _EscheatmentYN: string = 'N';
41
- protected _CreatedById: string;
42
- protected _CreatedAt: Date;
43
- protected _UpdatedById: string;
44
- protected _UpdatedAt: Date;
45
- protected static _Repo = new RentalRepository();
46
- protected static _AgreementRepo = new AgreementRepository();
47
- protected static _JointHirerRepo = new JointHirerRepository();
48
-
49
- get RentalId(): string {
50
- return this.ObjectId;
51
- }
52
-
53
- set RentalId(value: string) {
54
- this.ObjectId = value;
55
- }
56
-
57
- get Status(): RentalStatusEnum {
58
- return this._Status;
59
- }
60
-
61
- get EscheatmentYN(): string {
62
- return this._EscheatmentYN;
63
- }
64
-
65
- get CreatedById(): string {
66
- return this._CreatedById;
67
- }
68
-
69
- get CreatedAt(): Date {
70
- return this._CreatedAt;
71
- }
72
-
73
- get UpdatedById(): string {
74
- return this._UpdatedById;
75
- }
76
-
77
- get UpdatedAt(): Date {
78
- return this._UpdatedAt;
79
- }
80
-
81
- private setTerminated() {
82
- this._Status = RentalStatusEnum.TERMINATED;
83
- }
84
-
85
- protected constructor(rentalAttr?: IRentalAttr) {
86
- super();
87
- if (rentalAttr) {
88
- this.RentalId = rentalAttr.RentalId;
89
- this.CustomerId = rentalAttr.CustomerId;
90
- this.CustomerType = rentalAttr.CustomerType;
91
- this.ItemId = rentalAttr.ItemId;
92
- this.ItemType = rentalAttr.ItemType;
93
- this.PriceId = rentalAttr.PriceId;
94
- this.StartDateTime = rentalAttr.StartDateTime;
95
- this.EndDateTime = rentalAttr.EndDateTime;
96
- this.CancelRemarks = rentalAttr.CancelRemarks;
97
- this.TerminateRemarks = rentalAttr.TerminateRemarks;
98
- this.AgreementNo = rentalAttr.AgreementNo;
99
- this.AccountType = rentalAttr.AccountType;
100
- this._Status = rentalAttr.Status;
101
- this._EscheatmentYN = rentalAttr.EscheatmentYN;
102
- this._CreatedById = rentalAttr.CreatedById;
103
- this._CreatedAt = rentalAttr.CreatedAt;
104
- this._UpdatedById = rentalAttr.UpdatedById;
105
- this._UpdatedAt = rentalAttr.UpdatedAt;
106
- }
107
- }
108
-
109
- public static async init(dbTransaction?: any, rentalId?: string) {
110
- try {
111
- if (rentalId) {
112
- const rental = await Rental._Repo.findByPk(rentalId, dbTransaction);
113
- if (rental) {
114
- return new Rental(rental);
115
- } else {
116
- throw new ClassError('Rental', 'RentalErrMsg00', 'Rental Not Found');
117
- }
118
- }
119
- return new Rental();
120
- } catch (error) {
121
- throw new ClassError(
122
- 'Rental',
123
- 'RentalErrMsg00',
124
- 'Failed To Initialize Price',
125
- );
126
- }
127
- }
128
-
129
- /**
130
- * Create a new Rental record.
131
- * @param {RentalPrice} rentalPrice - The rental pricing information.
132
- * @param {LoginUser} loginUser - The user initiating the creation.
133
- * @param {any} [dbTransaction] - Optional database transaction for atomic operations.
134
- * @throws {ClassError} Throws an error if:
135
- * 1. loginUser does not have 'Rental - Create' privilege.
136
- * 2. Rental item is not available at the current date.
137
- * @returns {Promise<any>} A Promise resolving to the created rental record.
138
- */
139
- public async create(
140
- rentalPrice: RentalPrice,
141
- loginUser: LoginUser,
142
- jointHirers?: JointHirer[],
143
- dbTransaction?: any,
144
- ): Promise<any> {
145
- try {
146
- /*Part 1: Check Privilege*/
147
- const systemCode =
148
- ApplicationConfig.getComponentConfigValue('system-code');
149
- const isPrivileged = await loginUser.checkPrivileges(
150
- systemCode,
151
- 'Rental - Create',
152
- );
153
-
154
- if (!isPrivileged) {
155
- throw new ClassError(
156
- 'Rental',
157
- 'RentalErrMsg01',
158
- "You do not have 'Rental - Create' privilege.",
159
- );
160
- }
161
-
162
- /*Part 2: Make Sure Rental Item Available*/
163
- const isItemAvailable = await Rental.isItemAvailable(
164
- this.ItemId,
165
- this.ItemType,
166
- this.StartDateTime,
167
- this.EndDateTime,
168
- dbTransaction,
169
- );
170
-
171
- if (!isItemAvailable) {
172
- throw new ClassError(
173
- 'Rental',
174
- 'RentalErrMsg02',
175
- 'Rental Item is not available at current date.',
176
- );
177
- }
178
-
179
- // Part 3: Create Rental Agreement Record
180
- // Call Rental._AgreementRepo create method by passing:
181
- // AgreementNo: this.AgreementNo
182
- // Status: "Not Generated"
183
- // dbTransaction
184
- await Rental._AgreementRepo.create(
185
- {
186
- AgreementNo: this.AgreementNo,
187
- Status: 'Not Generated',
188
- },
189
- {
190
- transaction: dbTransaction,
191
- },
192
- );
193
-
194
- /*Part 4: Insert Rental & The Agreed Rental Price*/
195
- if (!rentalPrice.PriceId) {
196
- const rentalPriceData = await rentalPrice.create(
197
- loginUser,
198
- dbTransaction,
199
- );
200
- this.PriceId = rentalPriceData.PriceId;
201
- } else {
202
- this.PriceId = rentalPrice.PriceId;
203
- }
204
- this.RentalId = this.createId();
205
- // if (!this.Status) {
206
- this._Status = RentalStatusEnum.PENDING_SIGNING;
207
- // }
208
- this._CreatedById = loginUser.ObjectId;
209
- this._UpdatedById = loginUser.ObjectId;
210
- this._CreatedAt = new Date();
211
- this._UpdatedAt = new Date();
212
-
213
- const data = {
214
- RentalId: this.RentalId,
215
- CustomerId: this.CustomerId,
216
- CustomerType: this.CustomerType,
217
- ItemId: this.ItemId,
218
- ItemType: this.ItemType,
219
- PriceId: this.PriceId,
220
- StartDateTime: this.StartDateTime,
221
- EndDateTime: this.EndDateTime,
222
- CancelRemarks: this.CancelRemarks,
223
- TerminateRemarks: this.TerminateRemarks,
224
- AgreementNo: this.AgreementNo,
225
- AccountType: this.AccountType,
226
- Status: this.Status,
227
- EscheatmentYN: this.EscheatmentYN,
228
- CreatedById: this.CreatedById,
229
- CreatedAt: this.CreatedAt,
230
- UpdatedById: this.UpdatedById,
231
- UpdatedAt: this.UpdatedAt,
232
- };
233
-
234
- await Rental._Repo.create(data, {
235
- transaction: dbTransaction,
236
- });
237
-
238
- //For every data inside Param.jointHirers, update the rentalId and call jointHirer.create
239
- if (jointHirers) {
240
- for (let i = 0; i < jointHirers.length; i++) {
241
- jointHirers[i].RentalId = this.RentalId;
242
- await jointHirers[i].create(loginUser, dbTransaction);
243
- this.JointHirers.push(jointHirers[i]);
244
- }
245
- }
246
-
247
- /*Part 5: Record Create Rental Activity*/
248
- const activity = new Activity();
249
- activity.ActivityId = activity.createId();
250
- activity.Action = ActionEnum.CREATE;
251
- activity.Description = 'Add Rental';
252
- activity.EntityType = 'Rental';
253
- activity.EntityId = this.RentalId;
254
- activity.EntityValueBefore = JSON.stringify({});
255
- activity.EntityValueAfter = JSON.stringify(data);
256
- await activity.create(loginUser.ObjectId, dbTransaction);
257
-
258
- /*Part 6: Return Result*/
259
- return this;
260
- } catch (error) {
261
- throw error;
262
- }
263
- }
264
-
265
- public static async isItemAvailable(
266
- itemId: string,
267
- itemType: string,
268
- startDateTime: Date,
269
- endDateTime: Date,
270
- dbTransaction?: any,
271
- ) {
272
- try {
273
- const item = await Rental._Repo.findOne({
274
- where: {
275
- ItemId: itemId,
276
- ItemType: itemType,
277
- StartDateTime: {
278
- [Op.lte]: endDateTime,
279
- },
280
- EndDateTime: {
281
- [Op.gte]: startDateTime,
282
- },
283
- },
284
- transaction: dbTransaction,
285
- });
286
-
287
- if (item) {
288
- return false;
289
- } else {
290
- return true;
291
- }
292
- } catch (error) {
293
- throw error;
294
- }
295
- }
296
-
297
- public static async findAll(
298
- loginUser: LoginUser,
299
- dbTransaction: any,
300
- page?: number,
301
- row?: number,
302
- search?: IRentalFindAllSearchAttr,
303
- ) {
304
- try {
305
- const systemCode =
306
- await ApplicationConfig.getComponentConfigValue('system-code');
307
-
308
- const isPrivileged = await loginUser.checkPrivileges(
309
- systemCode,
310
- 'Rental - View',
311
- );
312
-
313
- if (!isPrivileged) {
314
- throw new ClassError(
315
- 'Rental',
316
- 'RentalErrMsg01',
317
- "You do not have 'Rental - View' privilege.",
318
- );
319
- }
320
-
321
- const queryObj: any = {};
322
-
323
- let options: any = {
324
- transaction: dbTransaction,
325
- order: [['CreatedAt', 'DESC']],
326
- };
327
-
328
- if (page && row) {
329
- options = {
330
- ...options,
331
- limit: row,
332
- offset: row * (page - 1),
333
- };
334
- }
335
-
336
- if (search) {
337
- Object.entries(search).forEach(([key, value]) => {
338
- if (key === 'StartDateTime') {
339
- queryObj[key] = {
340
- [Op.gte]: value,
341
- };
342
- } else if (key === 'EndDateTime') {
343
- queryObj[key] = {
344
- [Op.lte]: value,
345
- };
346
- } else if (key === 'CustomerId') {
347
- queryObj[key] = {
348
- [Op.substring]: value,
349
- };
350
-
351
- options.include = [
352
- {
353
- model: JointHirerModel,
354
- required: false,
355
- where: {
356
- CustomerId: {
357
- [Op.substring]: value,
358
- },
359
- },
360
- },
361
- ];
362
- } else {
363
- queryObj[key] = {
364
- [Op.substring]: value,
365
- };
366
- }
367
- });
368
- if (options?.include?.length > 1) {
369
- options.include.push({
370
- model: AgreementModel,
371
- required: false,
372
- });
373
- } else {
374
- options.include = [
375
- {
376
- model: AgreementModel,
377
- required: false,
378
- },
379
- ];
380
- }
381
-
382
- options = {
383
- ...options,
384
- where: queryObj,
385
- };
386
- }
387
-
388
- return await Rental._Repo.findAndCountAll(options);
389
- } catch (err) {
390
- throw err;
391
- }
392
- }
393
-
394
- public static async checkActiveByItemId(
395
- loginUser: LoginUser,
396
- itemId: string,
397
- itemType: string,
398
- dbTransaction?: any,
399
- ) {
400
- try {
401
- const systemCode =
402
- await ApplicationConfig.getComponentConfigValue('system-code');
403
-
404
- const isPrivileged = await loginUser.checkPrivileges(
405
- systemCode,
406
- 'Rental - View',
407
- );
408
-
409
- if (!isPrivileged) {
410
- throw new ClassError(
411
- 'Rental',
412
- 'RentalErrMsg01',
413
- "You do not have 'Rental - View' privilege.",
414
- );
415
- }
416
-
417
- const queryObj: any = {
418
- ItemId: itemId,
419
- ItemType: itemType,
420
- Status: RentalStatusEnum.ACTIVE,
421
- };
422
-
423
- const options: any = {
424
- transaction: dbTransaction,
425
- where: queryObj,
426
- };
427
-
428
- const rental = await Rental._Repo.findOne(options);
429
-
430
- if (rental) {
431
- return true;
432
- } else {
433
- return false;
434
- }
435
- } catch (err) {
436
- throw err;
437
- }
438
- }
439
-
440
- /**
441
- * Sets the StartDateTime property of the Rental class as custom setter.
442
- * @param {Date} startDateTime - The start date and time of the rental.
443
- * @throws {ClassError} Throws an error if:
444
- * 1. startDateTime is a past date.
445
- * 2. startDateTime is more than the EndDateTime.
446
- * @returns {void}
447
- */
448
- setStartDateTime(startDateTime: Date): void {
449
- const startDateTimeObject = new Date(startDateTime);
450
- startDateTimeObject.setHours(0, 0, 0, 0);
451
-
452
- /*Part 1: Make Sure Future Date Time*/
453
- if (startDateTimeObject < new Date(new Date().setHours(0, 0, 0, 0))) {
454
- throw new ClassError(
455
- 'Rental',
456
- 'RentalErrMsg02',
457
- 'StartDateTime cannot be a past datetime.',
458
- );
459
- }
460
-
461
- /*Part 2: Make Sure Less Than End Date Time*/
462
- if (this.EndDateTime && startDateTimeObject > this.EndDateTime) {
463
- throw new ClassError(
464
- 'Rental',
465
- 'RentalErrMsg03',
466
- 'StartDateTime cannot be more than EndDateTime.',
467
- );
468
- }
469
-
470
- /*Part 3: Set Status Whether Reserved or Active*/
471
- if (startDateTimeObject > new Date(new Date().setHours(0, 0, 0, 0))) {
472
- this._Status = RentalStatusEnum.RESERVED;
473
- } else {
474
- this._Status = RentalStatusEnum.ACTIVE;
475
- }
476
- }
477
-
478
- public async periodEndProcess(
479
- loginUser: LoginUser,
480
- dbTransaction: any,
481
- stockInventory: any,
482
- ) {
483
- try {
484
- // Privilege Checking
485
- const systemCode =
486
- await ApplicationConfig.getComponentConfigValue('system-code');
487
-
488
- const isPrivileged = await loginUser.checkPrivileges(
489
- systemCode,
490
- 'Rental PeriodEndProcess',
491
- );
492
-
493
- if (!isPrivileged) {
494
- throw new ClassError(
495
- 'Rental',
496
- 'RentalErrMsg04',
497
- "You do not have 'Rental - PeriodEndProcess' privilege.",
498
- );
499
- }
500
-
501
- // Validate Existing Rental
502
- if (this.AgreementNo === undefined || this.AgreementNo === null) {
503
- throw new ClassError(
504
- 'Rental',
505
- 'RentalErrMsg05',
506
- 'Rental must be existing rental.',
507
- );
508
- }
509
-
510
- // Validate Rental End Period
511
- if (this.EndDateTime === new Date(new Date().setHours(0, 0, 0, 0))) {
512
- throw new ClassError(
513
- 'Rental',
514
- 'RentalErrMsg06',
515
- 'Rental period is not ending today.',
516
- );
517
- }
518
-
519
- // Mark Rental Item as Available
520
- await stockInventory.setAvailable(loginUser, dbTransaction);
521
-
522
- // Capture Record Info Before Changes
523
- const entityValueBefore = {
524
- RentalId: this.RentalId,
525
- CustomerId: this.CustomerId,
526
- CustomerType: this.CustomerType,
527
- ItemId: this.ItemId,
528
- ItemType: this.ItemType,
529
- PriceId: this.PriceId,
530
- StartDateTime: this.StartDateTime,
531
- EndDateTime: this.EndDateTime,
532
- CancelRemarks: this.CancelRemarks,
533
- TerminateRemarks: this.TerminateRemarks,
534
- AgreementNo: this.AgreementNo,
535
- AccountType: this.AccountType,
536
- Status: this.Status,
537
- EscheatmentYN: this.EscheatmentYN,
538
- CreatedById: this.CreatedById,
539
- CreatedAt: this.CreatedAt,
540
- UpdatedById: this.UpdatedById,
541
- UpdatedAt: this.UpdatedAt,
542
- };
543
-
544
- // Mark Rental as Terminated and Capture Updater Info
545
- this.setTerminated();
546
- this._UpdatedById = loginUser.ObjectId;
547
- this._UpdatedAt = new Date();
548
-
549
- // Capture Record Info after Changes
550
- const entityValueAfter = {
551
- RentalId: this.RentalId,
552
- CustomerId: this.CustomerId,
553
- CustomerType: this.CustomerType,
554
- ItemId: this.ItemId,
555
- ItemType: this.ItemType,
556
- PriceId: this.PriceId,
557
- StartDateTime: this.StartDateTime,
558
- EndDateTime: this.EndDateTime,
559
- CancelRemarks: this.CancelRemarks,
560
- TerminateRemarks: this.TerminateRemarks,
561
- AgreementNo: this.AgreementNo,
562
- AccountType: this.AccountType,
563
- Status: this.Status,
564
- EscheatmentYN: this.EscheatmentYN,
565
- CreatedById: this.CreatedById,
566
- CreatedAt: this.CreatedAt,
567
- UpdatedById: this.UpdatedById,
568
- UpdatedAt: this.UpdatedAt,
569
- };
570
-
571
- // Record the Update Activity
572
- const activity = new Activity();
573
- activity.ActivityId = activity.createId();
574
- activity.Action = ActionEnum.UPDATE;
575
- activity.Description = 'Set Rental as Terminated';
576
- activity.EntityType = 'Rental';
577
- activity.EntityId = this.RentalId;
578
- activity.EntityValueBefore = JSON.stringify(entityValueBefore);
579
- activity.EntityValueAfter = JSON.stringify(entityValueAfter);
580
- await activity.create(loginUser.ObjectId, dbTransaction);
581
-
582
- return this;
583
- } catch (err) {
584
- throw err;
585
- }
586
- }
587
-
588
- async getCustomerActiveRentals(
589
- loginUser: LoginUser,
590
- dbTransaction: any,
591
- CustomerId: string,
592
- ): Promise<IRentalAttr[]> {
593
- try {
594
- // Part 1: Privilege Checking
595
- // Call loginUser.checkPrivileges() by passing:
596
- // SystemCode: <get_from_app_config>
597
- // PrivilegeCode: "RENTAL_VIEW"
598
- const systemCode =
599
- ApplicationConfig.getComponentConfigValue('system-code');
600
- const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_VIEW');
601
-
602
- if (!isPrivileged) {
603
- throw new ClassError(
604
- 'Rental',
605
- 'RentalErrMsg01',
606
- "You do not have 'Rental - View' privilege.",
607
- );
608
- }
609
-
610
- // Part 2: Retrieve Rentals and Returns
611
- // Call Rental._Repo findAll method by passing:
612
- // where:
613
- // Status: "Active"
614
- // [Op.OR]:
615
- // CustomerId: Params.CustomerId
616
- // '$JointHirers.CustomerId$': Params.CustomerId
617
- // include:
618
- // model: JointHirerModel
619
- // attributes: []
620
- const query = `
621
- SELECT
622
- r.*
623
- FROM
624
- rental_Rental r
625
- LEFT JOIN
626
- rental_JointHirer jh ON r.RentalId = jh.RentalId
627
- WHERE
628
- r.Status = 'Active'
629
- AND (
630
- r.CustomerId = '${CustomerId}'
631
- OR jh.CustomerId = '${CustomerId}'
632
- )
633
- GROUP BY
634
- r.RentalId
635
- `;
636
- const db = rentalDb.getConnection();
637
- const result = await db.query(query, {
638
- type: QueryTypes.SELECT,
639
- transaction: dbTransaction,
640
- model: RentalModel,
641
- mapToModel: true,
642
- });
643
-
644
- // Format the returned records
645
- const records: IRentalAttr[] = result.map((record: RentalModel) => {
646
- return {
647
- RentalId: record.RentalId,
648
- CustomerId: record.CustomerId,
649
- CustomerType: record.CustomerType,
650
- ItemId: record.ItemId,
651
- ItemType: record.ItemType,
652
- PriceId: record.PriceId,
653
- StartDateTime: record.StartDateTime,
654
- EndDateTime: record.EndDateTime,
655
- CancelRemarks: record.CancelRemarks,
656
- TerminateRemarks: record.TerminateRemarks,
657
- AgreementNo: record.AgreementNo,
658
- AccountType: record.AccountType,
659
- Status: record.Status,
660
- EscheatmentYN: record.EscheatmentYN,
661
- CreatedById: record.CreatedById,
662
- CreatedAt: record.CreatedAt,
663
- UpdatedById: record.UpdatedById,
664
- UpdatedAt: record.UpdatedAt,
665
- };
666
- });
667
- // Return the returned records.
668
- return records;
669
- } catch (error) {
670
- throw error;
671
- }
672
- }
673
-
674
- async getCustomerIds(loginUser: LoginUser, dbTransaction: any) {
675
- try {
676
- // Part 1: Privilege Checking
677
- // Call loginUser.checkPrivileges() by passing:
678
- // SystemCode: <get_from_app_config>
679
- // PrivilegeCode: "RENTAL_VIEW"
680
- const systemCode =
681
- ApplicationConfig.getComponentConfigValue('system-code');
682
- const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_VIEW');
683
-
684
- if (!isPrivileged) {
685
- throw new ClassError(
686
- 'Rental',
687
- 'RentalErrMsg01',
688
- "You do not have 'Rental - View' privilege.",
689
- );
690
- }
691
-
692
- // Part 2: Validation
693
- // Make sure this.RentalId exists, if not throw new ClassError by passing
694
- if (!this.RentalId) {
695
- throw new ClassError('Rental', 'RentalErrMsg01', 'RentalId is missing');
696
- }
697
-
698
- //Part 3: Retrieve Listing and Returns
699
- // 3.1 Call Rental._JointHirerRepo findAll method by passing:
700
- // where:
701
- // RentalId: this.RentalId
702
- // dbTransaction
703
- const options: any = {
704
- where: {
705
- RentalId: this.RentalId,
706
- },
707
- transaction: dbTransaction,
708
- };
709
-
710
- const joinHirers = await Rental._JointHirerRepo.findAll(options);
711
-
712
- // 3.2 Create a new array variable and set its value to joint hirer and Rental.CustomerId
713
- // array translated to only CustomerId. Then, append this.CustomerId to the array.
714
- const customerIds: string[] = [this.CustomerId];
715
- for (let i = 0; i < joinHirers.length; i++) {
716
- const jointHirer = joinHirers[i];
717
- customerIds.push(jointHirer.CustomerId);
718
- }
719
-
720
- // 3.3 Return the array.
721
- return customerIds;
722
- } catch (error) {
723
- throw error;
724
- }
725
- }
726
-
727
- async signAgreement(loginUser: LoginUser, dbTransaction: any) {
728
- try {
729
- // Part 1: Privilege Checking
730
- // Call loginUser.checkPrivileges() by passing:
731
- // SystemCode: <get_from_app_config>
732
- // PrivilegeCode: "RENTAL_SIGN"
733
- const systemCode =
734
- ApplicationConfig.getComponentConfigValue('system-code');
735
- const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_SIGN');
736
-
737
- if (!isPrivileged) {
738
- throw new ClassError(
739
- 'Rental',
740
- 'RentalErrMsg01',
741
- "You do not have 'RENTAL_SIGN' privilege.",
742
- );
743
- }
744
-
745
- // Part 2: Validation
746
- // Make sure this.Status is "Pending Signing" and agreementStatus is "Generated", if not throw new ClassError
747
- const agreement = await Agreement.init(this.AgreementNo, dbTransaction);
748
- if (
749
- this.Status !== RentalStatusEnum.PENDING_SIGNING &&
750
- agreement.Status !== AggrementStatusEnum.GENERATED
751
- ) {
752
- throw new ClassError(
753
- 'Rental',
754
- 'RentalErrMsg01',
755
- 'Rental is not ready to be signed yet.',
756
- );
757
- }
758
-
759
- //Part 3: Update Agreement Status
760
- // 3.1 Set EntityValueBefore to current agreement instance.
761
- const entityValueAgreementBefore = {
762
- AgreementNo: agreement.AgreementNo,
763
- Status: agreement.Status,
764
- DateSigned: agreement.DateSigned,
765
- };
766
-
767
- // 3.2 Set below agreement attributes:
768
- // DateSigned: current date & time
769
- // Status: "Signed"
770
- const payload = {
771
- DateSigned: new Date(),
772
- Status: AggrementStatusEnum.SIGNED,
773
- };
774
-
775
- // 3.3 Call Rental._AgreementRepo update()
776
- await Rental._AgreementRepo.update(payload, {
777
- where: {
778
- AgreementNo: this.AgreementNo,
779
- },
780
- transaction: dbTransaction,
781
- });
782
-
783
- const entityValueAgreementAfter = {
784
- entityValueAgreementBefore,
785
- ...payload,
786
- };
787
-
788
- // Part 4: Record Update Agreement Activity
789
- const activity = new Activity();
790
- activity.ActivityId = activity.createId();
791
- activity.Action = ActionEnum.UPDATE;
792
- activity.Description = 'Update agreement';
793
- activity.EntityType = 'RentalAgreement';
794
- activity.EntityId = this.AgreementNo;
795
- activity.EntityValueBefore = JSON.stringify(entityValueAgreementBefore);
796
- activity.EntityValueAfter = JSON.stringify(entityValueAgreementAfter);
797
- await activity.create(loginUser.ObjectId, dbTransaction);
798
-
799
- // Part 5: Update Rental Status
800
- // 5.1 Set EntityValueBefore to current rental instance.
801
- const entityValueRentalBefore = {
802
- RentalId: this.RentalId,
803
- CustomerId: this.CustomerId,
804
- CustomerType: this.CustomerType,
805
- ItemId: this.ItemId,
806
- ItemType: this.ItemType,
807
- PriceId: this.PriceId,
808
- StartDateTime: this.StartDateTime,
809
- EndDateTime: this.EndDateTime,
810
- CancelRemarks: this.CancelRemarks,
811
- TerminateRemarks: this.TerminateRemarks,
812
- AgreementNo: this.AgreementNo,
813
- AccountType: this.AccountType,
814
- Status: this.Status,
815
- EscheatmentYN: this.EscheatmentYN,
816
- CreatedById: this.CreatedById,
817
- CreatedAt: this.CreatedAt,
818
- UpdatedById: this.UpdatedById,
819
- UpdatedAt: this.UpdatedAt,
820
- };
821
- // 5.2: Set below rental attributes:
822
- // Status: "Pending Key Collection"
823
- // UpdatedById: loginUser.ObjectId
824
- // UpdatedAt: current date & time
825
-
826
- const payloadRental = {
827
- Status: RentalStatusEnum.PENDING_KEY_COLLECTION,
828
- UpdatedById: loginUser.ObjectId,
829
- UpdatedAt: new Date(),
830
- };
831
-
832
- // 5.3: Call Rental._Repo update() method by passing:
833
- // populate rental instance attributes
834
- // dbTransaction
835
- await Rental._Repo.update(payloadRental, {
836
- where: {
837
- RentalId: this.RentalId,
838
- },
839
- transaction: dbTransaction,
840
- });
841
-
842
- const entityValueRentalAfter = {
843
- entityValueRentalBefore,
844
- ...payloadRental,
845
- };
846
-
847
- // Part 6: Record Update Agreement Activity
848
- const rentalActivity = new Activity();
849
- rentalActivity.ActivityId = activity.createId();
850
- rentalActivity.Action = ActionEnum.UPDATE;
851
- rentalActivity.Description = 'Sign rental agreement';
852
- rentalActivity.EntityType = 'Rental';
853
- rentalActivity.EntityId = this.RentalId;
854
- rentalActivity.EntityValueBefore = JSON.stringify(
855
- entityValueRentalBefore,
856
- );
857
- rentalActivity.EntityValueAfter = JSON.stringify(entityValueRentalAfter);
858
- await rentalActivity.create(loginUser.ObjectId, dbTransaction);
859
- } catch (error) {
860
- throw error;
861
- }
862
- }
863
-
864
- async generateAgreement(
865
- loginUser: LoginUser,
866
- dbTransaction: any,
867
- MediaId: string,
868
- ) {
869
- //This method will generate a new rental agreement.
870
- try {
871
- // Part 1: Privilege Checking
872
- // Call loginUser.checkPrivileges() by passing:
873
- // SystemCode: "<get_from_app_config>"
874
- // PrivilegeCode: "RENTAL_AGREEMENT_CREATE"
875
-
876
- const systemCode =
877
- ApplicationConfig.getComponentConfigValue('system-code');
878
- const isPrivileged = loginUser.checkPrivileges(
879
- systemCode,
880
- 'RENTAL_AGREEMENT_CREATE',
881
- );
882
-
883
- if (!isPrivileged) {
884
- throw new ClassError(
885
- 'Rental',
886
- 'RentalErrMsg01',
887
- "You do not have 'RENTAL_AGREEMENT_CREATE' privilege.",
888
- );
889
- }
890
-
891
- // Part 2: Validation
892
- // Instantiate existing RentalAgreement by passing:
893
- // dbTransaction
894
- // AgreementNo: this.AgreementNo
895
- // Make sure Params.MediaId exists, if not throw new ClassError by passing:
896
- // Classname: "Rental"
897
- // MessageCode: "RentalErrMsg0X"
898
- // Message: "MediaId is required."
899
- const agreement = await Agreement.init(this.AgreementNo, dbTransaction);
900
- if (!MediaId) {
901
- throw new ClassError(
902
- 'Rental',
903
- 'RentalErrMsg0X',
904
- 'MediaId is required.',
905
- );
906
- }
907
-
908
- // Part 3: Update Agreement Record
909
- // Set EntityValueBefore to the agreement instance.
910
- // Set below agreement attributes:
911
- // Status: "Generated"
912
- // MediaId: Params.MediaId
913
-
914
- const EntityValueBefore = agreement;
915
- agreement.Status = AggrementStatusEnum.GENERATED;
916
- agreement.MediaId = MediaId;
917
-
918
- // Call Rental._AgreementRepo update method by passing:
919
- // Status: agreement.Status
920
- // MediaId: agreement.MediaId
921
- // dbTransaction
922
-
923
- await Rental._AgreementRepo.update(
924
- {
925
- Status: agreement.Status,
926
- MediaId: agreement.MediaId,
927
- },
928
- {
929
- where: {
930
- AgreementNo: this.AgreementNo,
931
- },
932
- transaction: dbTransaction,
933
- },
934
- );
935
-
936
- // Part 4: Record Update Agreement Activity
937
- // Initialise EntityValueAfter variable and set to agreement instance
938
- const EntityValueAfter = agreement;
939
- // Instantiate new activity from Activity class, call createId() method, then set:
940
- const activity = new Activity();
941
- // Action: ActionEnum.UPDATE
942
- // Description: "Generate agreement."
943
- // EntityType: "RentalAgreement"
944
- // EntityId: this.AgreementNo
945
- // EntityValueBefore: EntityValueBefore
946
- // EntityValueAfter: EntityValueAfter
947
- activity.ActivityId = activity.createId();
948
- activity.Action = ActionEnum.UPDATE;
949
- activity.Description = 'Generate agreement.';
950
- activity.EntityType = 'RentalAgreement';
951
- activity.EntityId = this.AgreementNo;
952
- activity.EntityValueBefore = JSON.stringify(EntityValueBefore);
953
- activity.EntityValueAfter = JSON.stringify(EntityValueAfter);
954
-
955
- // Call new activity create method by passing:
956
- // dbTransaction
957
- // userId: loginUser.ObjectId
958
- await activity.create(loginUser.ObjectId, dbTransaction);
959
- } catch (error) {
960
- throw error;
961
- }
962
- }
963
- }
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 { HirerSignatureRepository } from '../hirer-signature/hirer-signature.repository';
22
+ import { HirerSignatureStatusEnum } from '../../enum/hirer-signature-status.enum';
23
+ import { HirerTypeEnum } from '../../enum/hirer-type.enum';
24
+
25
+ export class Rental extends ObjectBase {
26
+ ObjectId: string;
27
+ ObjectName: string;
28
+ ObjectType = 'Rental';
29
+ TableName: string;
30
+ CustomerId: string;
31
+ CustomerType: string;
32
+ ItemId: string;
33
+ ItemType: string;
34
+ PriceId: string;
35
+ StartDateTime: Date;
36
+ EndDateTime: Date;
37
+ CancelRemarks: string;
38
+ TerminateRemarks: string;
39
+ AgreementNo: string;
40
+ AccountType: RentalAccountTypeEnum;
41
+ JointHirers: JointHirer[] = [];
42
+ protected _Status: RentalStatusEnum;
43
+ protected _EscheatmentYN: string = 'N';
44
+ protected _CreatedById: string;
45
+ protected _CreatedAt: Date;
46
+ protected _UpdatedById: string;
47
+ protected _UpdatedAt: Date;
48
+ protected static _Repo = new RentalRepository();
49
+ protected static _AgreementRepo = new AgreementRepository();
50
+ protected static _JointHirerRepo = new JointHirerRepository();
51
+ protected static _HirerSignatureRepo = new HirerSignatureRepository();
52
+
53
+ get RentalId(): string {
54
+ return this.ObjectId;
55
+ }
56
+
57
+ set RentalId(value: string) {
58
+ this.ObjectId = value;
59
+ }
60
+
61
+ get Status(): RentalStatusEnum {
62
+ return this._Status;
63
+ }
64
+
65
+ get EscheatmentYN(): string {
66
+ return this._EscheatmentYN;
67
+ }
68
+
69
+ get CreatedById(): string {
70
+ return this._CreatedById;
71
+ }
72
+
73
+ get CreatedAt(): Date {
74
+ return this._CreatedAt;
75
+ }
76
+
77
+ get UpdatedById(): string {
78
+ return this._UpdatedById;
79
+ }
80
+
81
+ get UpdatedAt(): Date {
82
+ return this._UpdatedAt;
83
+ }
84
+
85
+ private setTerminated() {
86
+ this._Status = RentalStatusEnum.TERMINATED;
87
+ }
88
+
89
+ protected constructor(rentalAttr?: IRentalAttr) {
90
+ super();
91
+ if (rentalAttr) {
92
+ this.RentalId = rentalAttr.RentalId;
93
+ this.CustomerId = rentalAttr.CustomerId;
94
+ this.CustomerType = rentalAttr.CustomerType;
95
+ this.ItemId = rentalAttr.ItemId;
96
+ this.ItemType = rentalAttr.ItemType;
97
+ this.PriceId = rentalAttr.PriceId;
98
+ this.StartDateTime = rentalAttr.StartDateTime;
99
+ this.EndDateTime = rentalAttr.EndDateTime;
100
+ this.CancelRemarks = rentalAttr.CancelRemarks;
101
+ this.TerminateRemarks = rentalAttr.TerminateRemarks;
102
+ this.AgreementNo = rentalAttr.AgreementNo;
103
+ this.AccountType = rentalAttr.AccountType;
104
+ this._Status = rentalAttr.Status;
105
+ this._EscheatmentYN = rentalAttr.EscheatmentYN;
106
+ this._CreatedById = rentalAttr.CreatedById;
107
+ this._CreatedAt = rentalAttr.CreatedAt;
108
+ this._UpdatedById = rentalAttr.UpdatedById;
109
+ this._UpdatedAt = rentalAttr.UpdatedAt;
110
+ }
111
+ }
112
+
113
+ public static async init(dbTransaction?: any, rentalId?: string) {
114
+ try {
115
+ if (rentalId) {
116
+ const rental = await Rental._Repo.findByPk(rentalId, dbTransaction);
117
+ if (rental) {
118
+ return new Rental(rental);
119
+ } else {
120
+ throw new ClassError('Rental', 'RentalErrMsg00', 'Rental Not Found');
121
+ }
122
+ }
123
+ return new Rental();
124
+ } catch (error) {
125
+ throw new ClassError(
126
+ 'Rental',
127
+ 'RentalErrMsg00',
128
+ 'Failed To Initialize Price',
129
+ );
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Create a new Rental record.
135
+ * @param {RentalPrice} rentalPrice - The rental pricing information.
136
+ * @param {LoginUser} loginUser - The user initiating the creation.
137
+ * @param {any} [dbTransaction] - Optional database transaction for atomic operations.
138
+ * @throws {ClassError} Throws an error if:
139
+ * 1. loginUser does not have 'Rental - Create' privilege.
140
+ * 2. Rental item is not available at the current date.
141
+ * @returns {Promise<any>} A Promise resolving to the created rental record.
142
+ */
143
+ public async create(
144
+ rentalPrice: RentalPrice,
145
+ loginUser: LoginUser,
146
+ jointHirers?: JointHirer[],
147
+ dbTransaction?: any,
148
+ ): Promise<any> {
149
+ try {
150
+ /*Part 1: Check Privilege*/
151
+ const systemCode =
152
+ ApplicationConfig.getComponentConfigValue('system-code');
153
+ const isPrivileged = await loginUser.checkPrivileges(
154
+ systemCode,
155
+ 'Rental - Create',
156
+ );
157
+
158
+ if (!isPrivileged) {
159
+ throw new ClassError(
160
+ 'Rental',
161
+ 'RentalErrMsg01',
162
+ "You do not have 'Rental - Create' privilege.",
163
+ );
164
+ }
165
+
166
+ /*Part 2: Make Sure Rental Item Available*/
167
+ const isItemAvailable = await Rental.isItemAvailable(
168
+ this.ItemId,
169
+ this.ItemType,
170
+ this.StartDateTime,
171
+ this.EndDateTime,
172
+ dbTransaction,
173
+ );
174
+
175
+ if (!isItemAvailable) {
176
+ throw new ClassError(
177
+ 'Rental',
178
+ 'RentalErrMsg02',
179
+ 'Rental Item is not available at current date.',
180
+ );
181
+ }
182
+
183
+ // Part 3: Create Rental Agreement Record
184
+ // Call Rental._AgreementRepo create method by passing:
185
+ // AgreementNo: this.AgreementNo
186
+ // Status: "Not Generated"
187
+ // dbTransaction
188
+ await Rental._AgreementRepo.create(
189
+ {
190
+ AgreementNo: this.AgreementNo,
191
+ Status: 'Not Generated',
192
+ },
193
+ {
194
+ transaction: dbTransaction,
195
+ },
196
+ );
197
+
198
+ //Create a record into rental_HirerSignature table
199
+ //Create the main customer's signature record
200
+ await Rental._HirerSignatureRepo.create(
201
+ {
202
+ HirerSignatureId: this.createId(),
203
+ AgreementNo: this.AgreementNo,
204
+ HirerType: HirerTypeEnum.PRIMARY,
205
+ CustomerId: this.CustomerId,
206
+ CustomerType: 'Customer',
207
+ SignatureStatus: HirerSignatureStatusEnum.PENDING,
208
+ SignedAt: new Date(),
209
+ CreatedById: loginUser.ObjectId,
210
+ CreatedAt: new Date(),
211
+ UpdatedById: loginUser.ObjectId,
212
+ UpdatedAt: new Date(),
213
+ },
214
+ { transaction: dbTransaction },
215
+ );
216
+
217
+ // Create signatures record for joint hirers if any
218
+ if (jointHirers && jointHirers.length > 0) {
219
+ for (const jointHirer of jointHirers) {
220
+ await Rental._HirerSignatureRepo.create(
221
+ {
222
+ HirerSignatureId: this.createId(),
223
+ AgreementNo: this.AgreementNo,
224
+ HirerType: HirerTypeEnum.JOINT,
225
+ CustomerId: jointHirer.CustomerId,
226
+ CustomerType: 'SDBCustomer',
227
+ SignatureStatus: HirerSignatureStatusEnum.PENDING,
228
+ SignedAt: new Date(),
229
+ CreatedById: loginUser.ObjectId,
230
+ CreatedAt: new Date(),
231
+ UpdatedById: loginUser.ObjectId,
232
+ UpdatedAt: new Date(),
233
+ },
234
+ { transaction: dbTransaction },
235
+ );
236
+ }
237
+ }
238
+
239
+ /*Part 4: Insert Rental & The Agreed Rental Price*/
240
+ if (!rentalPrice.PriceId) {
241
+ const rentalPriceData = await rentalPrice.create(
242
+ loginUser,
243
+ dbTransaction,
244
+ );
245
+ this.PriceId = rentalPriceData.PriceId;
246
+ } else {
247
+ this.PriceId = rentalPrice.PriceId;
248
+ }
249
+ this.RentalId = this.createId();
250
+ // if (!this.Status) {
251
+ this._Status = RentalStatusEnum.PENDING_SIGNING;
252
+ // }
253
+ this._CreatedById = loginUser.ObjectId;
254
+ this._UpdatedById = loginUser.ObjectId;
255
+ this._CreatedAt = new Date();
256
+ this._UpdatedAt = new Date();
257
+
258
+ const data = {
259
+ RentalId: this.RentalId,
260
+ CustomerId: this.CustomerId,
261
+ CustomerType: this.CustomerType,
262
+ ItemId: this.ItemId,
263
+ ItemType: this.ItemType,
264
+ PriceId: this.PriceId,
265
+ StartDateTime: this.StartDateTime,
266
+ EndDateTime: this.EndDateTime,
267
+ CancelRemarks: this.CancelRemarks,
268
+ TerminateRemarks: this.TerminateRemarks,
269
+ AgreementNo: this.AgreementNo,
270
+ AccountType: this.AccountType,
271
+ Status: this.Status,
272
+ EscheatmentYN: this.EscheatmentYN,
273
+ CreatedById: this.CreatedById,
274
+ CreatedAt: this.CreatedAt,
275
+ UpdatedById: this.UpdatedById,
276
+ UpdatedAt: this.UpdatedAt,
277
+ };
278
+
279
+ await Rental._Repo.create(data, {
280
+ transaction: dbTransaction,
281
+ });
282
+
283
+ //For every data inside Param.jointHirers, update the rentalId and call jointHirer.create
284
+ if (jointHirers) {
285
+ for (let i = 0; i < jointHirers.length; i++) {
286
+ jointHirers[i].RentalId = this.RentalId;
287
+ await jointHirers[i].create(loginUser, dbTransaction);
288
+ this.JointHirers.push(jointHirers[i]);
289
+ }
290
+ }
291
+
292
+ /*Part 5: Record Create Rental Activity*/
293
+ const activity = new Activity();
294
+ activity.ActivityId = activity.createId();
295
+ activity.Action = ActionEnum.CREATE;
296
+ activity.Description = 'Add Rental';
297
+ activity.EntityType = 'Rental';
298
+ activity.EntityId = this.RentalId;
299
+ activity.EntityValueBefore = JSON.stringify({});
300
+ activity.EntityValueAfter = JSON.stringify(data);
301
+ await activity.create(loginUser.ObjectId, dbTransaction);
302
+
303
+ /*Part 6: Return Result*/
304
+ return this;
305
+ } catch (error) {
306
+ throw error;
307
+ }
308
+ }
309
+
310
+ public static async isItemAvailable(
311
+ itemId: string,
312
+ itemType: string,
313
+ startDateTime: Date,
314
+ endDateTime: Date,
315
+ dbTransaction?: any,
316
+ ) {
317
+ try {
318
+ const item = await Rental._Repo.findOne({
319
+ where: {
320
+ ItemId: itemId,
321
+ ItemType: itemType,
322
+ StartDateTime: {
323
+ [Op.lte]: endDateTime,
324
+ },
325
+ EndDateTime: {
326
+ [Op.gte]: startDateTime,
327
+ },
328
+ },
329
+ transaction: dbTransaction,
330
+ });
331
+
332
+ if (item) {
333
+ return false;
334
+ } else {
335
+ return true;
336
+ }
337
+ } catch (error) {
338
+ throw error;
339
+ }
340
+ }
341
+
342
+ public static async findAll(
343
+ loginUser: LoginUser,
344
+ dbTransaction: any,
345
+ page?: number,
346
+ row?: number,
347
+ search?: IRentalFindAllSearchAttr,
348
+ ) {
349
+ try {
350
+ const systemCode =
351
+ await ApplicationConfig.getComponentConfigValue('system-code');
352
+
353
+ const isPrivileged = await loginUser.checkPrivileges(
354
+ systemCode,
355
+ 'Rental - View',
356
+ );
357
+
358
+ if (!isPrivileged) {
359
+ throw new ClassError(
360
+ 'Rental',
361
+ 'RentalErrMsg01',
362
+ "You do not have 'Rental - View' privilege.",
363
+ );
364
+ }
365
+
366
+ const queryObj: any = {};
367
+
368
+ let options: any = {
369
+ transaction: dbTransaction,
370
+ order: [['CreatedAt', 'DESC']],
371
+ };
372
+
373
+ if (page && row) {
374
+ options = {
375
+ ...options,
376
+ limit: row,
377
+ offset: row * (page - 1),
378
+ };
379
+ }
380
+
381
+ if (search) {
382
+ Object.entries(search).forEach(([key, value]) => {
383
+ if (key === 'StartDateTime') {
384
+ queryObj[key] = {
385
+ [Op.gte]: value,
386
+ };
387
+ } else if (key === 'EndDateTime') {
388
+ queryObj[key] = {
389
+ [Op.lte]: value,
390
+ };
391
+ } else if (key === 'CustomerId') {
392
+ queryObj[key] = {
393
+ [Op.substring]: value,
394
+ };
395
+
396
+ options.include = [
397
+ {
398
+ model: JointHirerModel,
399
+ required: false,
400
+ where: {
401
+ CustomerId: {
402
+ [Op.substring]: value,
403
+ },
404
+ },
405
+ },
406
+ ];
407
+ } else {
408
+ queryObj[key] = {
409
+ [Op.substring]: value,
410
+ };
411
+ }
412
+ });
413
+ if (options?.include?.length > 1) {
414
+ options.include.push({
415
+ model: AgreementModel,
416
+ required: false,
417
+ });
418
+ } else {
419
+ options.include = [
420
+ {
421
+ model: AgreementModel,
422
+ required: false,
423
+ },
424
+ ];
425
+ }
426
+
427
+ options = {
428
+ ...options,
429
+ where: queryObj,
430
+ };
431
+ }
432
+
433
+ return await Rental._Repo.findAndCountAll(options);
434
+ } catch (err) {
435
+ throw err;
436
+ }
437
+ }
438
+
439
+ public static async checkActiveByItemId(
440
+ loginUser: LoginUser,
441
+ itemId: string,
442
+ itemType: string,
443
+ dbTransaction?: any,
444
+ ) {
445
+ try {
446
+ const systemCode =
447
+ await ApplicationConfig.getComponentConfigValue('system-code');
448
+
449
+ const isPrivileged = await loginUser.checkPrivileges(
450
+ systemCode,
451
+ 'Rental - View',
452
+ );
453
+
454
+ if (!isPrivileged) {
455
+ throw new ClassError(
456
+ 'Rental',
457
+ 'RentalErrMsg01',
458
+ "You do not have 'Rental - View' privilege.",
459
+ );
460
+ }
461
+
462
+ const queryObj: any = {
463
+ ItemId: itemId,
464
+ ItemType: itemType,
465
+ Status: RentalStatusEnum.ACTIVE,
466
+ };
467
+
468
+ const options: any = {
469
+ transaction: dbTransaction,
470
+ where: queryObj,
471
+ };
472
+
473
+ const rental = await Rental._Repo.findOne(options);
474
+
475
+ if (rental) {
476
+ return true;
477
+ } else {
478
+ return false;
479
+ }
480
+ } catch (err) {
481
+ throw err;
482
+ }
483
+ }
484
+
485
+ /**
486
+ * Sets the StartDateTime property of the Rental class as custom setter.
487
+ * @param {Date} startDateTime - The start date and time of the rental.
488
+ * @throws {ClassError} Throws an error if:
489
+ * 1. startDateTime is a past date.
490
+ * 2. startDateTime is more than the EndDateTime.
491
+ * @returns {void}
492
+ */
493
+ setStartDateTime(startDateTime: Date): void {
494
+ const startDateTimeObject = new Date(startDateTime);
495
+ startDateTimeObject.setHours(0, 0, 0, 0);
496
+
497
+ /*Part 1: Make Sure Future Date Time*/
498
+ if (startDateTimeObject < new Date(new Date().setHours(0, 0, 0, 0))) {
499
+ throw new ClassError(
500
+ 'Rental',
501
+ 'RentalErrMsg02',
502
+ 'StartDateTime cannot be a past datetime.',
503
+ );
504
+ }
505
+
506
+ /*Part 2: Make Sure Less Than End Date Time*/
507
+ if (this.EndDateTime && startDateTimeObject > this.EndDateTime) {
508
+ throw new ClassError(
509
+ 'Rental',
510
+ 'RentalErrMsg03',
511
+ 'StartDateTime cannot be more than EndDateTime.',
512
+ );
513
+ }
514
+
515
+ /*Part 3: Set Status Whether Reserved or Active*/
516
+ if (startDateTimeObject > new Date(new Date().setHours(0, 0, 0, 0))) {
517
+ this._Status = RentalStatusEnum.RESERVED;
518
+ } else {
519
+ this._Status = RentalStatusEnum.ACTIVE;
520
+ }
521
+ }
522
+
523
+ public async periodEndProcess(
524
+ loginUser: LoginUser,
525
+ dbTransaction: any,
526
+ stockInventory: any,
527
+ ) {
528
+ try {
529
+ // Privilege Checking
530
+ const systemCode =
531
+ await ApplicationConfig.getComponentConfigValue('system-code');
532
+
533
+ const isPrivileged = await loginUser.checkPrivileges(
534
+ systemCode,
535
+ 'Rental – PeriodEndProcess',
536
+ );
537
+
538
+ if (!isPrivileged) {
539
+ throw new ClassError(
540
+ 'Rental',
541
+ 'RentalErrMsg04',
542
+ "You do not have 'Rental - PeriodEndProcess' privilege.",
543
+ );
544
+ }
545
+
546
+ // Validate Existing Rental
547
+ if (this.AgreementNo === undefined || this.AgreementNo === null) {
548
+ throw new ClassError(
549
+ 'Rental',
550
+ 'RentalErrMsg05',
551
+ 'Rental must be existing rental.',
552
+ );
553
+ }
554
+
555
+ // Validate Rental End Period
556
+ if (this.EndDateTime === new Date(new Date().setHours(0, 0, 0, 0))) {
557
+ throw new ClassError(
558
+ 'Rental',
559
+ 'RentalErrMsg06',
560
+ 'Rental period is not ending today.',
561
+ );
562
+ }
563
+
564
+ // Mark Rental Item as Available
565
+ await stockInventory.setAvailable(loginUser, dbTransaction);
566
+
567
+ // Capture Record Info Before Changes
568
+ const entityValueBefore = {
569
+ RentalId: this.RentalId,
570
+ CustomerId: this.CustomerId,
571
+ CustomerType: this.CustomerType,
572
+ ItemId: this.ItemId,
573
+ ItemType: this.ItemType,
574
+ PriceId: this.PriceId,
575
+ StartDateTime: this.StartDateTime,
576
+ EndDateTime: this.EndDateTime,
577
+ CancelRemarks: this.CancelRemarks,
578
+ TerminateRemarks: this.TerminateRemarks,
579
+ AgreementNo: this.AgreementNo,
580
+ AccountType: this.AccountType,
581
+ Status: this.Status,
582
+ EscheatmentYN: this.EscheatmentYN,
583
+ CreatedById: this.CreatedById,
584
+ CreatedAt: this.CreatedAt,
585
+ UpdatedById: this.UpdatedById,
586
+ UpdatedAt: this.UpdatedAt,
587
+ };
588
+
589
+ // Mark Rental as Terminated and Capture Updater Info
590
+ this.setTerminated();
591
+ this._UpdatedById = loginUser.ObjectId;
592
+ this._UpdatedAt = new Date();
593
+
594
+ // Capture Record Info after Changes
595
+ const entityValueAfter = {
596
+ RentalId: this.RentalId,
597
+ CustomerId: this.CustomerId,
598
+ CustomerType: this.CustomerType,
599
+ ItemId: this.ItemId,
600
+ ItemType: this.ItemType,
601
+ PriceId: this.PriceId,
602
+ StartDateTime: this.StartDateTime,
603
+ EndDateTime: this.EndDateTime,
604
+ CancelRemarks: this.CancelRemarks,
605
+ TerminateRemarks: this.TerminateRemarks,
606
+ AgreementNo: this.AgreementNo,
607
+ AccountType: this.AccountType,
608
+ Status: this.Status,
609
+ EscheatmentYN: this.EscheatmentYN,
610
+ CreatedById: this.CreatedById,
611
+ CreatedAt: this.CreatedAt,
612
+ UpdatedById: this.UpdatedById,
613
+ UpdatedAt: this.UpdatedAt,
614
+ };
615
+
616
+ // Record the Update Activity
617
+ const activity = new Activity();
618
+ activity.ActivityId = activity.createId();
619
+ activity.Action = ActionEnum.UPDATE;
620
+ activity.Description = 'Set Rental as Terminated';
621
+ activity.EntityType = 'Rental';
622
+ activity.EntityId = this.RentalId;
623
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
624
+ activity.EntityValueAfter = JSON.stringify(entityValueAfter);
625
+ await activity.create(loginUser.ObjectId, dbTransaction);
626
+
627
+ return this;
628
+ } catch (err) {
629
+ throw err;
630
+ }
631
+ }
632
+
633
+ async getCustomerActiveRentals(
634
+ loginUser: LoginUser,
635
+ dbTransaction: any,
636
+ CustomerId: string,
637
+ ): Promise<IRentalAttr[]> {
638
+ try {
639
+ // Part 1: Privilege Checking
640
+ // Call loginUser.checkPrivileges() by passing:
641
+ // SystemCode: <get_from_app_config>
642
+ // PrivilegeCode: "RENTAL_VIEW"
643
+ const systemCode =
644
+ ApplicationConfig.getComponentConfigValue('system-code');
645
+ const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_VIEW');
646
+
647
+ if (!isPrivileged) {
648
+ throw new ClassError(
649
+ 'Rental',
650
+ 'RentalErrMsg01',
651
+ "You do not have 'Rental - View' privilege.",
652
+ );
653
+ }
654
+
655
+ // Part 2: Retrieve Rentals and Returns
656
+ // Call Rental._Repo findAll method by passing:
657
+ // where:
658
+ // Status: "Active"
659
+ // [Op.OR]:
660
+ // CustomerId: Params.CustomerId
661
+ // '$JointHirers.CustomerId$': Params.CustomerId
662
+ // include:
663
+ // model: JointHirerModel
664
+ // attributes: []
665
+ const query = `
666
+ SELECT
667
+ r.*
668
+ FROM
669
+ rental_Rental r
670
+ LEFT JOIN
671
+ rental_JointHirer jh ON r.RentalId = jh.RentalId
672
+ WHERE
673
+ r.Status = 'Active'
674
+ AND (
675
+ r.CustomerId = '${CustomerId}'
676
+ OR jh.CustomerId = '${CustomerId}'
677
+ )
678
+ GROUP BY
679
+ r.RentalId
680
+ `;
681
+ const db = rentalDb.getConnection();
682
+ const result = await db.query(query, {
683
+ type: QueryTypes.SELECT,
684
+ transaction: dbTransaction,
685
+ model: RentalModel,
686
+ mapToModel: true,
687
+ });
688
+
689
+ // Format the returned records
690
+ const records: IRentalAttr[] = result.map((record: RentalModel) => {
691
+ return {
692
+ RentalId: record.RentalId,
693
+ CustomerId: record.CustomerId,
694
+ CustomerType: record.CustomerType,
695
+ ItemId: record.ItemId,
696
+ ItemType: record.ItemType,
697
+ PriceId: record.PriceId,
698
+ StartDateTime: record.StartDateTime,
699
+ EndDateTime: record.EndDateTime,
700
+ CancelRemarks: record.CancelRemarks,
701
+ TerminateRemarks: record.TerminateRemarks,
702
+ AgreementNo: record.AgreementNo,
703
+ AccountType: record.AccountType,
704
+ Status: record.Status,
705
+ EscheatmentYN: record.EscheatmentYN,
706
+ CreatedById: record.CreatedById,
707
+ CreatedAt: record.CreatedAt,
708
+ UpdatedById: record.UpdatedById,
709
+ UpdatedAt: record.UpdatedAt,
710
+ };
711
+ });
712
+ // Return the returned records.
713
+ return records;
714
+ } catch (error) {
715
+ throw error;
716
+ }
717
+ }
718
+
719
+ async getCustomerIds(loginUser: LoginUser, dbTransaction: any) {
720
+ try {
721
+ // Part 1: Privilege Checking
722
+ // Call loginUser.checkPrivileges() by passing:
723
+ // SystemCode: <get_from_app_config>
724
+ // PrivilegeCode: "RENTAL_VIEW"
725
+ const systemCode =
726
+ ApplicationConfig.getComponentConfigValue('system-code');
727
+ const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_VIEW');
728
+
729
+ if (!isPrivileged) {
730
+ throw new ClassError(
731
+ 'Rental',
732
+ 'RentalErrMsg01',
733
+ "You do not have 'Rental - View' privilege.",
734
+ );
735
+ }
736
+
737
+ // Part 2: Validation
738
+ // Make sure this.RentalId exists, if not throw new ClassError by passing
739
+ if (!this.RentalId) {
740
+ throw new ClassError('Rental', 'RentalErrMsg01', 'RentalId is missing');
741
+ }
742
+
743
+ //Part 3: Retrieve Listing and Returns
744
+ // 3.1 Call Rental._JointHirerRepo findAll method by passing:
745
+ // where:
746
+ // RentalId: this.RentalId
747
+ // dbTransaction
748
+ const options: any = {
749
+ where: {
750
+ RentalId: this.RentalId,
751
+ },
752
+ transaction: dbTransaction,
753
+ };
754
+
755
+ const joinHirers = await Rental._JointHirerRepo.findAll(options);
756
+
757
+ // 3.2 Create a new array variable and set its value to joint hirer and Rental.CustomerId
758
+ // array translated to only CustomerId. Then, append this.CustomerId to the array.
759
+ const customerIds: string[] = [this.CustomerId];
760
+ for (let i = 0; i < joinHirers.length; i++) {
761
+ const jointHirer = joinHirers[i];
762
+ customerIds.push(jointHirer.CustomerId);
763
+ }
764
+
765
+ // 3.3 Return the array.
766
+ return customerIds;
767
+ } catch (error) {
768
+ throw error;
769
+ }
770
+ }
771
+
772
+ async signAgreement(
773
+ loginUser: LoginUser,
774
+ CustomerId: string,
775
+ dbTransaction: any,
776
+ ) {
777
+ try {
778
+ // Part 1: Privilege Checking
779
+ // Call loginUser.checkPrivileges() by passing:
780
+ // SystemCode: <get_from_app_config>
781
+ // PrivilegeCode: "RENTAL_SIGN"
782
+ const systemCode =
783
+ ApplicationConfig.getComponentConfigValue('system-code');
784
+ const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_SIGN');
785
+
786
+ if (!isPrivileged) {
787
+ throw new ClassError(
788
+ 'Rental',
789
+ 'RentalErrMsg01',
790
+ "You do not have 'RENTAL_SIGN' privilege.",
791
+ );
792
+ }
793
+
794
+ // Part 2: Validation
795
+ // Make sure this.Status is "Pending Signing" and agreementStatus is "Generated", if not throw new ClassError
796
+ const agreement = await Agreement.init(this.AgreementNo, dbTransaction);
797
+ if (
798
+ this.Status !== RentalStatusEnum.PENDING_SIGNING &&
799
+ agreement.Status !== AggrementStatusEnum.GENERATED
800
+ ) {
801
+ throw new ClassError(
802
+ 'Rental',
803
+ 'RentalErrMsg01',
804
+ 'Rental is not ready to be signed yet.',
805
+ );
806
+ }
807
+
808
+ //Make sure CustomerId inside the listing and SignatureStatus is "Pending"
809
+ const signatureList = await Agreement.getSignatureList(
810
+ loginUser,
811
+ this.AgreementNo,
812
+ dbTransaction,
813
+ );
814
+ const customerSignature = signatureList.find(
815
+ (sig) =>
816
+ sig.CustomerId === CustomerId &&
817
+ sig.SignatureStatus === HirerSignatureStatusEnum.PENDING,
818
+ );
819
+
820
+ if (!customerSignature) {
821
+ throw new ClassError(
822
+ 'Rental',
823
+ 'RentalErrMsg01',
824
+ 'Customer signature is not pending.',
825
+ );
826
+ }
827
+
828
+ //Update rental_HirerSignature
829
+ const signaturePayload = {
830
+ SignatureStatus: HirerSignatureStatusEnum.SIGNED,
831
+ SignedAt: new Date(),
832
+ UpdatedById: loginUser.ObjectId,
833
+ UpdatedAt: new Date(),
834
+ };
835
+
836
+ await Rental._HirerSignatureRepo.update(signaturePayload, {
837
+ where: {
838
+ AgreementNo: this.AgreementNo,
839
+ CustomerId: CustomerId,
840
+ },
841
+ transaction: dbTransaction,
842
+ });
843
+
844
+ const signatureActivity = new Activity();
845
+ signatureActivity.ActivityId = signatureActivity.createId();
846
+ signatureActivity.Action = ActionEnum.UPDATE;
847
+ signatureActivity.Description = 'Update hirer signature';
848
+ signatureActivity.EntityType = 'HirerSignature';
849
+ signatureActivity.EntityId = this.AgreementNo;
850
+ signatureActivity.EntityValueBefore = JSON.stringify(customerSignature);
851
+ signatureActivity.EntityValueAfter = JSON.stringify(signaturePayload);
852
+ await signatureActivity.create(loginUser.ObjectId, dbTransaction);
853
+
854
+ const updatedSignatureList = await Agreement.getSignatureList(
855
+ loginUser,
856
+ this.AgreementNo,
857
+ dbTransaction,
858
+ );
859
+
860
+ const pendingSignatures = updatedSignatureList.filter(
861
+ (sig) => sig.SignatureStatus === 'Pending',
862
+ );
863
+ if (pendingSignatures.length > 0) {
864
+ return;
865
+ }
866
+
867
+ //Part 3: Update Agreement Status
868
+ // 3.1 Set EntityValueBefore to current agreement instance.
869
+ const entityValueAgreementBefore = {
870
+ AgreementNo: agreement.AgreementNo,
871
+ Status: agreement.Status,
872
+ DateSigned: agreement.DateSigned,
873
+ };
874
+
875
+ // 3.2 Set below agreement attributes:
876
+ // DateSigned: current date & time
877
+ // Status: "Signed"
878
+ const payload = {
879
+ DateSigned: new Date(),
880
+ Status: AggrementStatusEnum.SIGNED,
881
+ };
882
+
883
+ // 3.3 Call Rental._AgreementRepo update()
884
+ await Rental._AgreementRepo.update(payload, {
885
+ where: {
886
+ AgreementNo: this.AgreementNo,
887
+ },
888
+ transaction: dbTransaction,
889
+ });
890
+
891
+ const entityValueAgreementAfter = {
892
+ entityValueAgreementBefore,
893
+ ...payload,
894
+ };
895
+
896
+ // Part 4: Record Update Agreement Activity
897
+ const activity = new Activity();
898
+ activity.ActivityId = activity.createId();
899
+ activity.Action = ActionEnum.UPDATE;
900
+ activity.Description = 'Update agreement';
901
+ activity.EntityType = 'RentalAgreement';
902
+ activity.EntityId = this.AgreementNo;
903
+ activity.EntityValueBefore = JSON.stringify(entityValueAgreementBefore);
904
+ activity.EntityValueAfter = JSON.stringify(entityValueAgreementAfter);
905
+ await activity.create(loginUser.ObjectId, dbTransaction);
906
+
907
+ // Part 5: Update Rental Status
908
+ // 5.1 Set EntityValueBefore to current rental instance.
909
+ const entityValueRentalBefore = {
910
+ RentalId: this.RentalId,
911
+ CustomerId: this.CustomerId,
912
+ CustomerType: this.CustomerType,
913
+ ItemId: this.ItemId,
914
+ ItemType: this.ItemType,
915
+ PriceId: this.PriceId,
916
+ StartDateTime: this.StartDateTime,
917
+ EndDateTime: this.EndDateTime,
918
+ CancelRemarks: this.CancelRemarks,
919
+ TerminateRemarks: this.TerminateRemarks,
920
+ AgreementNo: this.AgreementNo,
921
+ AccountType: this.AccountType,
922
+ Status: this.Status,
923
+ EscheatmentYN: this.EscheatmentYN,
924
+ CreatedById: this.CreatedById,
925
+ CreatedAt: this.CreatedAt,
926
+ UpdatedById: this.UpdatedById,
927
+ UpdatedAt: this.UpdatedAt,
928
+ };
929
+ // 5.2: Set below rental attributes:
930
+ // Status: "Pending Key Collection"
931
+ // UpdatedById: loginUser.ObjectId
932
+ // UpdatedAt: current date & time
933
+
934
+ const payloadRental = {
935
+ Status: RentalStatusEnum.PENDING_KEY_COLLECTION,
936
+ UpdatedById: loginUser.ObjectId,
937
+ UpdatedAt: new Date(),
938
+ };
939
+
940
+ // 5.3: Call Rental._Repo update() method by passing:
941
+ // populate rental instance attributes
942
+ // dbTransaction
943
+ await Rental._Repo.update(payloadRental, {
944
+ where: {
945
+ RentalId: this.RentalId,
946
+ },
947
+ transaction: dbTransaction,
948
+ });
949
+
950
+ const entityValueRentalAfter = {
951
+ entityValueRentalBefore,
952
+ ...payloadRental,
953
+ };
954
+
955
+ this._Status = RentalStatusEnum.PENDING_KEY_COLLECTION;
956
+
957
+ // Part 6: Record Update Agreement Activity
958
+ const rentalActivity = new Activity();
959
+ rentalActivity.ActivityId = activity.createId();
960
+ rentalActivity.Action = ActionEnum.UPDATE;
961
+ rentalActivity.Description = 'Sign rental agreement';
962
+ rentalActivity.EntityType = 'Rental';
963
+ rentalActivity.EntityId = this.RentalId;
964
+ rentalActivity.EntityValueBefore = JSON.stringify(
965
+ entityValueRentalBefore,
966
+ );
967
+ rentalActivity.EntityValueAfter = JSON.stringify(entityValueRentalAfter);
968
+ await rentalActivity.create(loginUser.ObjectId, dbTransaction);
969
+ } catch (error) {
970
+ throw error;
971
+ }
972
+ }
973
+
974
+ async generateAgreement(
975
+ loginUser: LoginUser,
976
+ dbTransaction: any,
977
+ MediaId: string,
978
+ ) {
979
+ //This method will generate a new rental agreement.
980
+ try {
981
+ // Part 1: Privilege Checking
982
+ // Call loginUser.checkPrivileges() by passing:
983
+ // SystemCode: "<get_from_app_config>"
984
+ // PrivilegeCode: "RENTAL_AGREEMENT_CREATE"
985
+
986
+ const systemCode =
987
+ ApplicationConfig.getComponentConfigValue('system-code');
988
+ const isPrivileged = loginUser.checkPrivileges(
989
+ systemCode,
990
+ 'RENTAL_AGREEMENT_CREATE',
991
+ );
992
+
993
+ if (!isPrivileged) {
994
+ throw new ClassError(
995
+ 'Rental',
996
+ 'RentalErrMsg01',
997
+ "You do not have 'RENTAL_AGREEMENT_CREATE' privilege.",
998
+ );
999
+ }
1000
+
1001
+ // Part 2: Validation
1002
+ // Instantiate existing RentalAgreement by passing:
1003
+ // dbTransaction
1004
+ // AgreementNo: this.AgreementNo
1005
+ // Make sure Params.MediaId exists, if not throw new ClassError by passing:
1006
+ // Classname: "Rental"
1007
+ // MessageCode: "RentalErrMsg0X"
1008
+ // Message: "MediaId is required."
1009
+ const agreement = await Agreement.init(this.AgreementNo, dbTransaction);
1010
+ if (!MediaId) {
1011
+ throw new ClassError(
1012
+ 'Rental',
1013
+ 'RentalErrMsg0X',
1014
+ 'MediaId is required.',
1015
+ );
1016
+ }
1017
+
1018
+ // Part 3: Update Agreement Record
1019
+ // Set EntityValueBefore to the agreement instance.
1020
+ // Set below agreement attributes:
1021
+ // Status: "Generated"
1022
+ // MediaId: Params.MediaId
1023
+
1024
+ const EntityValueBefore = agreement;
1025
+ agreement.Status = AggrementStatusEnum.GENERATED;
1026
+ agreement.MediaId = MediaId;
1027
+
1028
+ // Call Rental._AgreementRepo update method by passing:
1029
+ // Status: agreement.Status
1030
+ // MediaId: agreement.MediaId
1031
+ // dbTransaction
1032
+
1033
+ await Rental._AgreementRepo.update(
1034
+ {
1035
+ Status: agreement.Status,
1036
+ MediaId: agreement.MediaId,
1037
+ },
1038
+ {
1039
+ where: {
1040
+ AgreementNo: this.AgreementNo,
1041
+ },
1042
+ transaction: dbTransaction,
1043
+ },
1044
+ );
1045
+
1046
+ // Part 4: Record Update Agreement Activity
1047
+ // Initialise EntityValueAfter variable and set to agreement instance
1048
+ const EntityValueAfter = agreement;
1049
+ // Instantiate new activity from Activity class, call createId() method, then set:
1050
+ const activity = new Activity();
1051
+ // Action: ActionEnum.UPDATE
1052
+ // Description: "Generate agreement."
1053
+ // EntityType: "RentalAgreement"
1054
+ // EntityId: this.AgreementNo
1055
+ // EntityValueBefore: EntityValueBefore
1056
+ // EntityValueAfter: EntityValueAfter
1057
+ activity.ActivityId = activity.createId();
1058
+ activity.Action = ActionEnum.UPDATE;
1059
+ activity.Description = 'Generate agreement.';
1060
+ activity.EntityType = 'RentalAgreement';
1061
+ activity.EntityId = this.AgreementNo;
1062
+ activity.EntityValueBefore = JSON.stringify(EntityValueBefore);
1063
+ activity.EntityValueAfter = JSON.stringify(EntityValueAfter);
1064
+
1065
+ // Call new activity create method by passing:
1066
+ // dbTransaction
1067
+ // userId: loginUser.ObjectId
1068
+ await activity.create(loginUser.ObjectId, dbTransaction);
1069
+ } catch (error) {
1070
+ throw error;
1071
+ }
1072
+ }
1073
+ }