@tomei/rental 0.10.4 → 0.11.1

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 (52) hide show
  1. package/.commitlintrc.json +22 -22
  2. package/.eslintrc +16 -16
  3. package/.eslintrc.js +35 -35
  4. package/.gitlab-ci.yml +16 -16
  5. package/.husky/commit-msg +15 -15
  6. package/.husky/pre-commit +7 -7
  7. package/.prettierrc +4 -4
  8. package/Jenkinsfile +51 -51
  9. package/README.md +8 -8
  10. package/dist/src/components/rental/rental.d.ts +1 -0
  11. package/dist/src/components/rental/rental.js +55 -15
  12. package/dist/src/components/rental/rental.js.map +1 -1
  13. package/dist/tsconfig.tsbuildinfo +1 -1
  14. package/jest.config.js +10 -10
  15. package/migrations/booking-table-migration.js +79 -79
  16. package/migrations/joint-hirer-table-migration.js +52 -52
  17. package/migrations/rental-aggrement-table-migration.js +30 -30
  18. package/migrations/rental-price-table-migration.js +32 -32
  19. package/migrations/rental-table-migrations.js +96 -96
  20. package/package.json +75 -75
  21. package/sonar-project.properties +12 -12
  22. package/src/components/agreement/agreement.repository.ts +54 -54
  23. package/src/components/agreement/agreement.ts +49 -49
  24. package/src/components/booking/booking.repository.ts +51 -51
  25. package/src/components/booking/booking.ts +343 -343
  26. package/src/components/joint-hirer/joint-hirer.repository.ts +54 -54
  27. package/src/components/rental/rental.repository.ts +51 -51
  28. package/src/components/rental/rental.ts +961 -861
  29. package/src/components/rental-price/rental-price.repository.ts +54 -54
  30. package/src/components/rental-price/rental-price.ts +100 -100
  31. package/src/database.ts +27 -27
  32. package/src/enum/account-type.enum.ts +4 -4
  33. package/src/enum/booking.enum.ts +5 -5
  34. package/src/enum/index.ts +11 -11
  35. package/src/enum/rental-status.enum.ts +39 -39
  36. package/src/index.ts +28 -28
  37. package/src/interfaces/agreement-attr.interface.ts +7 -7
  38. package/src/interfaces/booking-attr.interface.ts +19 -19
  39. package/src/interfaces/booking-find-all-search-attr.interface.ts +12 -12
  40. package/src/interfaces/index.ts +15 -15
  41. package/src/interfaces/joint-hirer-attr.interface.ts +10 -10
  42. package/src/interfaces/rental-attr.interface.ts +25 -25
  43. package/src/interfaces/rental-find-all-search-attr.interface.ts +11 -11
  44. package/src/interfaces/rental-price-attr.interface.ts +7 -7
  45. package/src/models/agreement.entity.ts +39 -39
  46. package/src/models/booking.entity.ts +105 -105
  47. package/src/models/index.ts +13 -13
  48. package/src/models/joint-hirer.entity.ts +63 -63
  49. package/src/models/rental-price.entity.ts +38 -38
  50. package/src/models/rental.entity.ts +133 -133
  51. package/tsconfig.build.json +5 -5
  52. package/tsconfig.json +23 -23
@@ -1,861 +1,961 @@
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
- await rentalPrice.create(loginUser, dbTransaction);
196
-
197
- this.PriceId = rentalPrice.PriceId;
198
-
199
- this.RentalId = this.createId();
200
- // if (!this.Status) {
201
- this._Status = RentalStatusEnum.PENDING_SIGNING;
202
- // }
203
- this._CreatedById = loginUser.ObjectId;
204
- this._UpdatedById = loginUser.ObjectId;
205
- this._CreatedAt = new Date();
206
- this._UpdatedAt = new Date();
207
-
208
- const data = {
209
- RentalId: this.RentalId,
210
- CustomerId: this.CustomerId,
211
- CustomerType: this.CustomerType,
212
- ItemId: this.ItemId,
213
- ItemType: this.ItemType,
214
- PriceId: this.PriceId,
215
- StartDateTime: this.StartDateTime,
216
- EndDateTime: this.EndDateTime,
217
- CancelRemarks: this.CancelRemarks,
218
- TerminateRemarks: this.TerminateRemarks,
219
- AgreementNo: this.AgreementNo,
220
- AccountType: this.AccountType,
221
- Status: this.Status,
222
- EscheatmentYN: this.EscheatmentYN,
223
- CreatedById: this.CreatedById,
224
- CreatedAt: this.CreatedAt,
225
- UpdatedById: this.UpdatedById,
226
- UpdatedAt: this.UpdatedAt,
227
- };
228
-
229
- await Rental._Repo.create(data, {
230
- transaction: dbTransaction,
231
- });
232
-
233
- //For every data inside Param.jointHirers, update the rentalId and call jointHirer.create
234
- if (jointHirers) {
235
- for (let i = 0; i < jointHirers.length; i++) {
236
- jointHirers[i].RentalId = this.RentalId;
237
- await jointHirers[i].create(loginUser, dbTransaction);
238
- this.JointHirers.push(jointHirers[i]);
239
- }
240
- }
241
-
242
- /*Part 5: Record Create Rental Activity*/
243
- const activity = new Activity();
244
- activity.ActivityId = activity.createId();
245
- activity.Action = ActionEnum.ADD;
246
- activity.Description = 'Add Rental';
247
- activity.EntityType = 'Rental';
248
- activity.EntityId = this.RentalId;
249
- activity.EntityValueBefore = JSON.stringify({});
250
- activity.EntityValueAfter = JSON.stringify(data);
251
- await activity.create(loginUser.ObjectId, dbTransaction);
252
-
253
- /*Part 6: Return Result*/
254
- return this;
255
- } catch (error) {
256
- throw error;
257
- }
258
- }
259
-
260
- public static async isItemAvailable(
261
- itemId: string,
262
- itemType: string,
263
- startDateTime: Date,
264
- endDateTime: Date,
265
- dbTransaction?: any,
266
- ) {
267
- try {
268
- const item = await Rental._Repo.findOne({
269
- where: {
270
- ItemId: itemId,
271
- ItemType: itemType,
272
- StartDateTime: {
273
- [Op.lte]: endDateTime,
274
- },
275
- EndDateTime: {
276
- [Op.gte]: startDateTime,
277
- },
278
- },
279
- transaction: dbTransaction,
280
- });
281
-
282
- if (item) {
283
- return false;
284
- } else {
285
- return true;
286
- }
287
- } catch (error) {
288
- throw error;
289
- }
290
- }
291
-
292
- public static async findAll(
293
- loginUser: LoginUser,
294
- dbTransaction: any,
295
- page?: number,
296
- row?: number,
297
- search?: IRentalFindAllSearchAttr,
298
- ) {
299
- try {
300
- const systemCode = await ApplicationConfig.getComponentConfigValue(
301
- 'system-code',
302
- );
303
-
304
- const isPrivileged = await loginUser.checkPrivileges(
305
- systemCode,
306
- 'Rental - View',
307
- );
308
-
309
- if (!isPrivileged) {
310
- throw new ClassError(
311
- 'Rental',
312
- 'RentalErrMsg01',
313
- "You do not have 'Rental - View' privilege.",
314
- );
315
- }
316
-
317
- const queryObj: any = {};
318
-
319
- let options: any = {
320
- transaction: dbTransaction,
321
- order: [['CreatedAt', 'DESC']],
322
- };
323
-
324
- if (page && row) {
325
- options = {
326
- ...options,
327
- limit: row,
328
- offset: row * (page - 1),
329
- };
330
- }
331
-
332
- if (search) {
333
- Object.entries(search).forEach(([key, value]) => {
334
- if (key === 'StartDateTime') {
335
- queryObj[key] = {
336
- [Op.gte]: value,
337
- };
338
- } else if (key === 'EndDateTime') {
339
- queryObj[key] = {
340
- [Op.lte]: value,
341
- };
342
- } else if (key === 'CustomerId') {
343
- queryObj[key] = {
344
- [Op.substring]: value,
345
- };
346
-
347
- options.include = [
348
- {
349
- model: JointHirerModel,
350
- required: false,
351
- where: {
352
- CustomerId: {
353
- [Op.substring]: value,
354
- },
355
- },
356
- },
357
- ];
358
- } else {
359
- queryObj[key] = {
360
- [Op.substring]: value,
361
- };
362
- }
363
- });
364
- if (options?.include?.length > 1) {
365
- options.include.push({
366
- model: AgreementModel,
367
- required: false,
368
- });
369
- } else {
370
- options.include = [
371
- {
372
- model: AgreementModel,
373
- required: false,
374
- },
375
- ];
376
- }
377
-
378
- options = {
379
- ...options,
380
- where: queryObj,
381
- };
382
- }
383
-
384
- return await Rental._Repo.findAndCountAll(options);
385
- } catch (err) {
386
- throw err;
387
- }
388
- }
389
-
390
- public static async checkActiveByItemId(
391
- loginUser: LoginUser,
392
- itemId: string,
393
- itemType: string,
394
- dbTransaction?: any,
395
- ) {
396
- try {
397
- const systemCode = await ApplicationConfig.getComponentConfigValue(
398
- 'system-code',
399
- );
400
-
401
- const isPrivileged = await loginUser.checkPrivileges(
402
- systemCode,
403
- 'Rental - View',
404
- );
405
-
406
- if (!isPrivileged) {
407
- throw new ClassError(
408
- 'Rental',
409
- 'RentalErrMsg01',
410
- "You do not have 'Rental - View' privilege.",
411
- );
412
- }
413
-
414
- const queryObj: any = {
415
- ItemId: itemId,
416
- ItemType: itemType,
417
- Status: RentalStatusEnum.ACTIVE,
418
- };
419
-
420
- const options: any = {
421
- transaction: dbTransaction,
422
- where: queryObj,
423
- };
424
-
425
- const rental = await Rental._Repo.findOne(options);
426
-
427
- if (rental) {
428
- return true;
429
- } else {
430
- return false;
431
- }
432
- } catch (err) {
433
- throw err;
434
- }
435
- }
436
-
437
- /**
438
- * Sets the StartDateTime property of the Rental class as custom setter.
439
- * @param {Date} startDateTime - The start date and time of the rental.
440
- * @throws {ClassError} Throws an error if:
441
- * 1. startDateTime is a past date.
442
- * 2. startDateTime is more than the EndDateTime.
443
- * @returns {void}
444
- */
445
- setStartDateTime(startDateTime: Date): void {
446
- const startDateTimeObject = new Date(startDateTime);
447
- startDateTimeObject.setHours(0, 0, 0, 0);
448
-
449
- /*Part 1: Make Sure Future Date Time*/
450
- if (startDateTimeObject < new Date(new Date().setHours(0, 0, 0, 0))) {
451
- throw new ClassError(
452
- 'Rental',
453
- 'RentalErrMsg02',
454
- 'StartDateTime cannot be a past datetime.',
455
- );
456
- }
457
-
458
- /*Part 2: Make Sure Less Than End Date Time*/
459
- if (this.EndDateTime && startDateTimeObject > this.EndDateTime) {
460
- throw new ClassError(
461
- 'Rental',
462
- 'RentalErrMsg03',
463
- 'StartDateTime cannot be more than EndDateTime.',
464
- );
465
- }
466
-
467
- /*Part 3: Set Status Whether Reserved or Active*/
468
- if (startDateTimeObject > new Date(new Date().setHours(0, 0, 0, 0))) {
469
- this._Status = RentalStatusEnum.RESERVED;
470
- } else {
471
- this._Status = RentalStatusEnum.ACTIVE;
472
- }
473
- }
474
-
475
- public async periodEndProcess(
476
- loginUser: LoginUser,
477
- dbTransaction: any,
478
- stockInventory: any,
479
- ) {
480
- try {
481
- // Privilege Checking
482
- const systemCode = await ApplicationConfig.getComponentConfigValue(
483
- 'system-code',
484
- );
485
-
486
- const isPrivileged = await loginUser.checkPrivileges(
487
- systemCode,
488
- 'Rental – PeriodEndProcess',
489
- );
490
-
491
- if (!isPrivileged) {
492
- throw new ClassError(
493
- 'Rental',
494
- 'RentalErrMsg04',
495
- "You do not have 'Rental - PeriodEndProcess' privilege.",
496
- );
497
- }
498
-
499
- // Validate Existing Rental
500
- if (this.AgreementNo === undefined || this.AgreementNo === null) {
501
- throw new ClassError(
502
- 'Rental',
503
- 'RentalErrMsg05',
504
- 'Rental must be existing rental.',
505
- );
506
- }
507
-
508
- // Validate Rental End Period
509
- if (this.EndDateTime === new Date(new Date().setHours(0, 0, 0, 0))) {
510
- throw new ClassError(
511
- 'Rental',
512
- 'RentalErrMsg06',
513
- 'Rental period is not ending today.',
514
- );
515
- }
516
-
517
- // Mark Rental Item as Available
518
- await stockInventory.setAvailable(loginUser, dbTransaction);
519
-
520
- // Capture Record Info Before Changes
521
- const entityValueBefore = {
522
- RentalId: this.RentalId,
523
- CustomerId: this.CustomerId,
524
- CustomerType: this.CustomerType,
525
- ItemId: this.ItemId,
526
- ItemType: this.ItemType,
527
- PriceId: this.PriceId,
528
- StartDateTime: this.StartDateTime,
529
- EndDateTime: this.EndDateTime,
530
- CancelRemarks: this.CancelRemarks,
531
- TerminateRemarks: this.TerminateRemarks,
532
- AgreementNo: this.AgreementNo,
533
- AccountType: this.AccountType,
534
- Status: this.Status,
535
- EscheatmentYN: this.EscheatmentYN,
536
- CreatedById: this.CreatedById,
537
- CreatedAt: this.CreatedAt,
538
- UpdatedById: this.UpdatedById,
539
- UpdatedAt: this.UpdatedAt,
540
- };
541
-
542
- // Mark Rental as Terminated and Capture Updater Info
543
- this.setTerminated();
544
- this._UpdatedById = loginUser.ObjectId;
545
- this._UpdatedAt = new Date();
546
-
547
- // Capture Record Info after Changes
548
- const entityValueAfter = {
549
- RentalId: this.RentalId,
550
- CustomerId: this.CustomerId,
551
- CustomerType: this.CustomerType,
552
- ItemId: this.ItemId,
553
- ItemType: this.ItemType,
554
- PriceId: this.PriceId,
555
- StartDateTime: this.StartDateTime,
556
- EndDateTime: this.EndDateTime,
557
- CancelRemarks: this.CancelRemarks,
558
- TerminateRemarks: this.TerminateRemarks,
559
- AgreementNo: this.AgreementNo,
560
- AccountType: this.AccountType,
561
- Status: this.Status,
562
- EscheatmentYN: this.EscheatmentYN,
563
- CreatedById: this.CreatedById,
564
- CreatedAt: this.CreatedAt,
565
- UpdatedById: this.UpdatedById,
566
- UpdatedAt: this.UpdatedAt,
567
- };
568
-
569
- // Record the Update Activity
570
- const activity = new Activity();
571
- activity.ActivityId = activity.createId();
572
- activity.Action = ActionEnum.UPDATE;
573
- activity.Description = 'Set Rental as Terminated';
574
- activity.EntityType = 'Rental';
575
- activity.EntityId = this.RentalId;
576
- activity.EntityValueBefore = JSON.stringify(entityValueBefore);
577
- activity.EntityValueAfter = JSON.stringify(entityValueAfter);
578
- await activity.create(loginUser.ObjectId, dbTransaction);
579
-
580
- return this;
581
- } catch (err) {
582
- throw err;
583
- }
584
- }
585
-
586
- async getCustomerActiveRentals(
587
- loginUser: LoginUser,
588
- dbTransaction: any,
589
- CustomerId: string,
590
- ): Promise<IRentalAttr[]> {
591
- try {
592
- // Part 1: Privilege Checking
593
- // Call loginUser.checkPrivileges() by passing:
594
- // SystemCode: <get_from_app_config>
595
- // PrivilegeCode: "RENTAL_VIEW"
596
- const systemCode =
597
- ApplicationConfig.getComponentConfigValue('system-code');
598
- const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_VIEW');
599
-
600
- if (!isPrivileged) {
601
- throw new ClassError(
602
- 'Rental',
603
- 'RentalErrMsg01',
604
- "You do not have 'Rental - View' privilege.",
605
- );
606
- }
607
-
608
- // Part 2: Retrieve Rentals and Returns
609
- // Call Rental._Repo findAll method by passing:
610
- // where:
611
- // Status: "Active"
612
- // [Op.OR]:
613
- // CustomerId: Params.CustomerId
614
- // '$JointHirers.CustomerId$': Params.CustomerId
615
- // include:
616
- // model: JointHirerModel
617
- // attributes: []
618
- const query = `
619
- SELECT
620
- r.*
621
- FROM
622
- rental_Rental r
623
- LEFT JOIN
624
- rental_JointHirer jh ON r.RentalId = jh.RentalId
625
- WHERE
626
- r.Status = 'Active'
627
- AND (
628
- r.CustomerId = '${CustomerId}'
629
- OR jh.CustomerId = '${CustomerId}'
630
- )
631
- GROUP BY
632
- r.RentalId
633
- `;
634
- const db = rentalDb.getConnection();
635
- const result = await db.query(query, {
636
- type: QueryTypes.SELECT,
637
- transaction: dbTransaction,
638
- model: RentalModel,
639
- mapToModel: true,
640
- });
641
-
642
- // Format the returned records
643
- const records: IRentalAttr[] = result.map((record: RentalModel) => {
644
- return {
645
- RentalId: record.RentalId,
646
- CustomerId: record.CustomerId,
647
- CustomerType: record.CustomerType,
648
- ItemId: record.ItemId,
649
- ItemType: record.ItemType,
650
- PriceId: record.PriceId,
651
- StartDateTime: record.StartDateTime,
652
- EndDateTime: record.EndDateTime,
653
- CancelRemarks: record.CancelRemarks,
654
- TerminateRemarks: record.TerminateRemarks,
655
- AgreementNo: record.AgreementNo,
656
- AccountType: record.AccountType,
657
- Status: record.Status,
658
- EscheatmentYN: record.EscheatmentYN,
659
- CreatedById: record.CreatedById,
660
- CreatedAt: record.CreatedAt,
661
- UpdatedById: record.UpdatedById,
662
- UpdatedAt: record.UpdatedAt,
663
- };
664
- });
665
- // Return the returned records.
666
- return records;
667
- } catch (error) {
668
- throw error;
669
- }
670
- }
671
-
672
- async getCustomerIds(loginUser: LoginUser, dbTransaction: any) {
673
- try {
674
- // Part 1: Privilege Checking
675
- // Call loginUser.checkPrivileges() by passing:
676
- // SystemCode: <get_from_app_config>
677
- // PrivilegeCode: "RENTAL_VIEW"
678
- const systemCode =
679
- ApplicationConfig.getComponentConfigValue('system-code');
680
- const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_VIEW');
681
-
682
- if (!isPrivileged) {
683
- throw new ClassError(
684
- 'Rental',
685
- 'RentalErrMsg01',
686
- "You do not have 'Rental - View' privilege.",
687
- );
688
- }
689
-
690
- // Part 2: Validation
691
- // Make sure this.RentalId exists, if not throw new ClassError by passing
692
- if (!this.RentalId) {
693
- throw new ClassError('Rental', 'RentalErrMsg01', 'RentalId is missing');
694
- }
695
-
696
- //Part 3: Retrieve Listing and Returns
697
- // 3.1 Call Rental._JointHirerRepo findAll method by passing:
698
- // where:
699
- // RentalId: this.RentalId
700
- // dbTransaction
701
- const options: any = {
702
- where: {
703
- RentalId: this.RentalId,
704
- },
705
- transaction: dbTransaction,
706
- };
707
-
708
- const joinHirers = await Rental._JointHirerRepo.findAll(options);
709
-
710
- // 3.2 Create a new array variable and set its value to joint hirer and Rental.CustomerId
711
- // array translated to only CustomerId. Then, append this.CustomerId to the array.
712
- const customerIds: string[] = [this.CustomerId];
713
- for (let i = 0; i < joinHirers.length; i++) {
714
- const jointHirer = joinHirers[i];
715
- customerIds.push(jointHirer.CustomerId);
716
- }
717
-
718
- // 3.3 Return the array.
719
- return customerIds;
720
- } catch (error) {
721
- throw error;
722
- }
723
- }
724
-
725
- async signAgreement(loginUser: LoginUser, dbTransaction: any) {
726
- try {
727
- // Part 1: Privilege Checking
728
- // Call loginUser.checkPrivileges() by passing:
729
- // SystemCode: <get_from_app_config>
730
- // PrivilegeCode: "RENTAL_SIGN"
731
- const systemCode =
732
- ApplicationConfig.getComponentConfigValue('system-code');
733
- const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_SIGN');
734
-
735
- if (!isPrivileged) {
736
- throw new ClassError(
737
- 'Rental',
738
- 'RentalErrMsg01',
739
- "You do not have 'RENTAL_SIGN' privilege.",
740
- );
741
- }
742
-
743
- // Part 2: Validation
744
- // Make sure this.Status is "Pending Signing" and agreementStatus is "Generated", if not throw new ClassError
745
- const agreement = await Agreement.init(this.AgreementNo, dbTransaction);
746
- if (
747
- this.Status !== RentalStatusEnum.PENDING_SIGNING &&
748
- agreement.Status !== AggrementStatusEnum.GENERATED
749
- ) {
750
- throw new ClassError(
751
- 'Rental',
752
- 'RentalErrMsg01',
753
- 'Rental is not ready to be signed yet.',
754
- );
755
- }
756
-
757
- //Part 3: Update Agreement Status
758
- // 3.1 Set EntityValueBefore to current agreement instance.
759
- const entityValueAgreementBefore = {
760
- AgreementNo: agreement.AgreementNo,
761
- Status: agreement.Status,
762
- DateSigned: agreement.DateSigned,
763
- };
764
-
765
- // 3.2 Set below agreement attributes:
766
- // DateSigned: current date & time
767
- // Status: "Signed"
768
- const payload = {
769
- DateSigned: new Date(),
770
- Status: AggrementStatusEnum.SIGNED,
771
- };
772
-
773
- // 3.3 Call Rental._AgreementRepo update()
774
- await Rental._AgreementRepo.update(payload, {
775
- where: {
776
- AgreementNo: this.AgreementNo,
777
- },
778
- transaction: dbTransaction,
779
- });
780
-
781
- const entityValueAgreementAfter = {
782
- entityValueAgreementBefore,
783
- ...payload,
784
- };
785
-
786
- // Part 4: Record Update Agreement Activity
787
- const activity = new Activity();
788
- activity.ActivityId = activity.createId();
789
- activity.Action = ActionEnum.UPDATE;
790
- activity.Description = 'Update agreement';
791
- activity.EntityType = 'RentalAgreement';
792
- activity.EntityId = this.AgreementNo;
793
- activity.EntityValueBefore = JSON.stringify(entityValueAgreementBefore);
794
- activity.EntityValueAfter = JSON.stringify(entityValueAgreementAfter);
795
- await activity.create(loginUser.ObjectId, dbTransaction);
796
-
797
- // Part 5: Update Rental Status
798
- // 5.1 Set EntityValueBefore to current rental instance.
799
- const entityValueRentalBefore = {
800
- RentalId: this.RentalId,
801
- CustomerId: this.CustomerId,
802
- CustomerType: this.CustomerType,
803
- ItemId: this.ItemId,
804
- ItemType: this.ItemType,
805
- PriceId: this.PriceId,
806
- StartDateTime: this.StartDateTime,
807
- EndDateTime: this.EndDateTime,
808
- CancelRemarks: this.CancelRemarks,
809
- TerminateRemarks: this.TerminateRemarks,
810
- AgreementNo: this.AgreementNo,
811
- AccountType: this.AccountType,
812
- Status: this.Status,
813
- EscheatmentYN: this.EscheatmentYN,
814
- CreatedById: this.CreatedById,
815
- CreatedAt: this.CreatedAt,
816
- UpdatedById: this.UpdatedById,
817
- UpdatedAt: this.UpdatedAt,
818
- };
819
- // 5.2: Set below rental attributes:
820
- // Status: "Pending Key Collection"
821
- // UpdatedById: loginUser.ObjectId
822
- // UpdatedAt: current date & time
823
-
824
- const payloadRental = {
825
- Status: RentalStatusEnum.PENDING_KEY_COLLECTION,
826
- UpdatedById: loginUser.ObjectId,
827
- UpdatedAt: new Date(),
828
- };
829
-
830
- // 5.3: Call Rental._Repo update() method by passing:
831
- // populate rental instance attributes
832
- // dbTransaction
833
- await Rental._Repo.update(payloadRental, {
834
- where: {
835
- RentalId: this.RentalId,
836
- },
837
- transaction: dbTransaction,
838
- });
839
-
840
- const entityValueRentalAfter = {
841
- entityValueRentalBefore,
842
- ...payloadRental,
843
- };
844
-
845
- // Part 6: Record Update Agreement Activity
846
- const rentalActivity = new Activity();
847
- rentalActivity.ActivityId = activity.createId();
848
- rentalActivity.Action = ActionEnum.UPDATE;
849
- rentalActivity.Description = 'Sign rental agreement';
850
- rentalActivity.EntityType = 'Rental';
851
- rentalActivity.EntityId = this.RentalId;
852
- rentalActivity.EntityValueBefore = JSON.stringify(
853
- entityValueRentalBefore,
854
- );
855
- rentalActivity.EntityValueAfter = JSON.stringify(entityValueRentalAfter);
856
- await rentalActivity.create(loginUser.ObjectId, dbTransaction);
857
- } catch (error) {
858
- throw error;
859
- }
860
- }
861
- }
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
+ await rentalPrice.create(loginUser, dbTransaction);
196
+
197
+ this.PriceId = rentalPrice.PriceId;
198
+
199
+ this.RentalId = this.createId();
200
+ // if (!this.Status) {
201
+ this._Status = RentalStatusEnum.PENDING_SIGNING;
202
+ // }
203
+ this._CreatedById = loginUser.ObjectId;
204
+ this._UpdatedById = loginUser.ObjectId;
205
+ this._CreatedAt = new Date();
206
+ this._UpdatedAt = new Date();
207
+
208
+ const data = {
209
+ RentalId: this.RentalId,
210
+ CustomerId: this.CustomerId,
211
+ CustomerType: this.CustomerType,
212
+ ItemId: this.ItemId,
213
+ ItemType: this.ItemType,
214
+ PriceId: this.PriceId,
215
+ StartDateTime: this.StartDateTime,
216
+ EndDateTime: this.EndDateTime,
217
+ CancelRemarks: this.CancelRemarks,
218
+ TerminateRemarks: this.TerminateRemarks,
219
+ AgreementNo: this.AgreementNo,
220
+ AccountType: this.AccountType,
221
+ Status: this.Status,
222
+ EscheatmentYN: this.EscheatmentYN,
223
+ CreatedById: this.CreatedById,
224
+ CreatedAt: this.CreatedAt,
225
+ UpdatedById: this.UpdatedById,
226
+ UpdatedAt: this.UpdatedAt,
227
+ };
228
+
229
+ await Rental._Repo.create(data, {
230
+ transaction: dbTransaction,
231
+ });
232
+
233
+ //For every data inside Param.jointHirers, update the rentalId and call jointHirer.create
234
+ if (jointHirers) {
235
+ for (let i = 0; i < jointHirers.length; i++) {
236
+ jointHirers[i].RentalId = this.RentalId;
237
+ await jointHirers[i].create(loginUser, dbTransaction);
238
+ this.JointHirers.push(jointHirers[i]);
239
+ }
240
+ }
241
+
242
+ /*Part 5: Record Create Rental Activity*/
243
+ const activity = new Activity();
244
+ activity.ActivityId = activity.createId();
245
+ activity.Action = ActionEnum.ADD;
246
+ activity.Description = 'Add Rental';
247
+ activity.EntityType = 'Rental';
248
+ activity.EntityId = this.RentalId;
249
+ activity.EntityValueBefore = JSON.stringify({});
250
+ activity.EntityValueAfter = JSON.stringify(data);
251
+ await activity.create(loginUser.ObjectId, dbTransaction);
252
+
253
+ /*Part 6: Return Result*/
254
+ return this;
255
+ } catch (error) {
256
+ throw error;
257
+ }
258
+ }
259
+
260
+ public static async isItemAvailable(
261
+ itemId: string,
262
+ itemType: string,
263
+ startDateTime: Date,
264
+ endDateTime: Date,
265
+ dbTransaction?: any,
266
+ ) {
267
+ try {
268
+ const item = await Rental._Repo.findOne({
269
+ where: {
270
+ ItemId: itemId,
271
+ ItemType: itemType,
272
+ StartDateTime: {
273
+ [Op.lte]: endDateTime,
274
+ },
275
+ EndDateTime: {
276
+ [Op.gte]: startDateTime,
277
+ },
278
+ },
279
+ transaction: dbTransaction,
280
+ });
281
+
282
+ if (item) {
283
+ return false;
284
+ } else {
285
+ return true;
286
+ }
287
+ } catch (error) {
288
+ throw error;
289
+ }
290
+ }
291
+
292
+ public static async findAll(
293
+ loginUser: LoginUser,
294
+ dbTransaction: any,
295
+ page?: number,
296
+ row?: number,
297
+ search?: IRentalFindAllSearchAttr,
298
+ ) {
299
+ try {
300
+ const systemCode = await ApplicationConfig.getComponentConfigValue(
301
+ 'system-code',
302
+ );
303
+
304
+ const isPrivileged = await loginUser.checkPrivileges(
305
+ systemCode,
306
+ 'Rental - View',
307
+ );
308
+
309
+ if (!isPrivileged) {
310
+ throw new ClassError(
311
+ 'Rental',
312
+ 'RentalErrMsg01',
313
+ "You do not have 'Rental - View' privilege.",
314
+ );
315
+ }
316
+
317
+ const queryObj: any = {};
318
+
319
+ let options: any = {
320
+ transaction: dbTransaction,
321
+ order: [['CreatedAt', 'DESC']],
322
+ };
323
+
324
+ if (page && row) {
325
+ options = {
326
+ ...options,
327
+ limit: row,
328
+ offset: row * (page - 1),
329
+ };
330
+ }
331
+
332
+ if (search) {
333
+ Object.entries(search).forEach(([key, value]) => {
334
+ if (key === 'StartDateTime') {
335
+ queryObj[key] = {
336
+ [Op.gte]: value,
337
+ };
338
+ } else if (key === 'EndDateTime') {
339
+ queryObj[key] = {
340
+ [Op.lte]: value,
341
+ };
342
+ } else if (key === 'CustomerId') {
343
+ queryObj[key] = {
344
+ [Op.substring]: value,
345
+ };
346
+
347
+ options.include = [
348
+ {
349
+ model: JointHirerModel,
350
+ required: false,
351
+ where: {
352
+ CustomerId: {
353
+ [Op.substring]: value,
354
+ },
355
+ },
356
+ },
357
+ ];
358
+ } else {
359
+ queryObj[key] = {
360
+ [Op.substring]: value,
361
+ };
362
+ }
363
+ });
364
+ if (options?.include?.length > 1) {
365
+ options.include.push({
366
+ model: AgreementModel,
367
+ required: false,
368
+ });
369
+ } else {
370
+ options.include = [
371
+ {
372
+ model: AgreementModel,
373
+ required: false,
374
+ },
375
+ ];
376
+ }
377
+
378
+ options = {
379
+ ...options,
380
+ where: queryObj,
381
+ };
382
+ }
383
+
384
+ return await Rental._Repo.findAndCountAll(options);
385
+ } catch (err) {
386
+ throw err;
387
+ }
388
+ }
389
+
390
+ public static async checkActiveByItemId(
391
+ loginUser: LoginUser,
392
+ itemId: string,
393
+ itemType: string,
394
+ dbTransaction?: any,
395
+ ) {
396
+ try {
397
+ const systemCode = await ApplicationConfig.getComponentConfigValue(
398
+ 'system-code',
399
+ );
400
+
401
+ const isPrivileged = await loginUser.checkPrivileges(
402
+ systemCode,
403
+ 'Rental - View',
404
+ );
405
+
406
+ if (!isPrivileged) {
407
+ throw new ClassError(
408
+ 'Rental',
409
+ 'RentalErrMsg01',
410
+ "You do not have 'Rental - View' privilege.",
411
+ );
412
+ }
413
+
414
+ const queryObj: any = {
415
+ ItemId: itemId,
416
+ ItemType: itemType,
417
+ Status: RentalStatusEnum.ACTIVE,
418
+ };
419
+
420
+ const options: any = {
421
+ transaction: dbTransaction,
422
+ where: queryObj,
423
+ };
424
+
425
+ const rental = await Rental._Repo.findOne(options);
426
+
427
+ if (rental) {
428
+ return true;
429
+ } else {
430
+ return false;
431
+ }
432
+ } catch (err) {
433
+ throw err;
434
+ }
435
+ }
436
+
437
+ /**
438
+ * Sets the StartDateTime property of the Rental class as custom setter.
439
+ * @param {Date} startDateTime - The start date and time of the rental.
440
+ * @throws {ClassError} Throws an error if:
441
+ * 1. startDateTime is a past date.
442
+ * 2. startDateTime is more than the EndDateTime.
443
+ * @returns {void}
444
+ */
445
+ setStartDateTime(startDateTime: Date): void {
446
+ const startDateTimeObject = new Date(startDateTime);
447
+ startDateTimeObject.setHours(0, 0, 0, 0);
448
+
449
+ /*Part 1: Make Sure Future Date Time*/
450
+ if (startDateTimeObject < new Date(new Date().setHours(0, 0, 0, 0))) {
451
+ throw new ClassError(
452
+ 'Rental',
453
+ 'RentalErrMsg02',
454
+ 'StartDateTime cannot be a past datetime.',
455
+ );
456
+ }
457
+
458
+ /*Part 2: Make Sure Less Than End Date Time*/
459
+ if (this.EndDateTime && startDateTimeObject > this.EndDateTime) {
460
+ throw new ClassError(
461
+ 'Rental',
462
+ 'RentalErrMsg03',
463
+ 'StartDateTime cannot be more than EndDateTime.',
464
+ );
465
+ }
466
+
467
+ /*Part 3: Set Status Whether Reserved or Active*/
468
+ if (startDateTimeObject > new Date(new Date().setHours(0, 0, 0, 0))) {
469
+ this._Status = RentalStatusEnum.RESERVED;
470
+ } else {
471
+ this._Status = RentalStatusEnum.ACTIVE;
472
+ }
473
+ }
474
+
475
+ public async periodEndProcess(
476
+ loginUser: LoginUser,
477
+ dbTransaction: any,
478
+ stockInventory: any,
479
+ ) {
480
+ try {
481
+ // Privilege Checking
482
+ const systemCode = await ApplicationConfig.getComponentConfigValue(
483
+ 'system-code',
484
+ );
485
+
486
+ const isPrivileged = await loginUser.checkPrivileges(
487
+ systemCode,
488
+ 'Rental – PeriodEndProcess',
489
+ );
490
+
491
+ if (!isPrivileged) {
492
+ throw new ClassError(
493
+ 'Rental',
494
+ 'RentalErrMsg04',
495
+ "You do not have 'Rental - PeriodEndProcess' privilege.",
496
+ );
497
+ }
498
+
499
+ // Validate Existing Rental
500
+ if (this.AgreementNo === undefined || this.AgreementNo === null) {
501
+ throw new ClassError(
502
+ 'Rental',
503
+ 'RentalErrMsg05',
504
+ 'Rental must be existing rental.',
505
+ );
506
+ }
507
+
508
+ // Validate Rental End Period
509
+ if (this.EndDateTime === new Date(new Date().setHours(0, 0, 0, 0))) {
510
+ throw new ClassError(
511
+ 'Rental',
512
+ 'RentalErrMsg06',
513
+ 'Rental period is not ending today.',
514
+ );
515
+ }
516
+
517
+ // Mark Rental Item as Available
518
+ await stockInventory.setAvailable(loginUser, dbTransaction);
519
+
520
+ // Capture Record Info Before Changes
521
+ const entityValueBefore = {
522
+ RentalId: this.RentalId,
523
+ CustomerId: this.CustomerId,
524
+ CustomerType: this.CustomerType,
525
+ ItemId: this.ItemId,
526
+ ItemType: this.ItemType,
527
+ PriceId: this.PriceId,
528
+ StartDateTime: this.StartDateTime,
529
+ EndDateTime: this.EndDateTime,
530
+ CancelRemarks: this.CancelRemarks,
531
+ TerminateRemarks: this.TerminateRemarks,
532
+ AgreementNo: this.AgreementNo,
533
+ AccountType: this.AccountType,
534
+ Status: this.Status,
535
+ EscheatmentYN: this.EscheatmentYN,
536
+ CreatedById: this.CreatedById,
537
+ CreatedAt: this.CreatedAt,
538
+ UpdatedById: this.UpdatedById,
539
+ UpdatedAt: this.UpdatedAt,
540
+ };
541
+
542
+ // Mark Rental as Terminated and Capture Updater Info
543
+ this.setTerminated();
544
+ this._UpdatedById = loginUser.ObjectId;
545
+ this._UpdatedAt = new Date();
546
+
547
+ // Capture Record Info after Changes
548
+ const entityValueAfter = {
549
+ RentalId: this.RentalId,
550
+ CustomerId: this.CustomerId,
551
+ CustomerType: this.CustomerType,
552
+ ItemId: this.ItemId,
553
+ ItemType: this.ItemType,
554
+ PriceId: this.PriceId,
555
+ StartDateTime: this.StartDateTime,
556
+ EndDateTime: this.EndDateTime,
557
+ CancelRemarks: this.CancelRemarks,
558
+ TerminateRemarks: this.TerminateRemarks,
559
+ AgreementNo: this.AgreementNo,
560
+ AccountType: this.AccountType,
561
+ Status: this.Status,
562
+ EscheatmentYN: this.EscheatmentYN,
563
+ CreatedById: this.CreatedById,
564
+ CreatedAt: this.CreatedAt,
565
+ UpdatedById: this.UpdatedById,
566
+ UpdatedAt: this.UpdatedAt,
567
+ };
568
+
569
+ // Record the Update Activity
570
+ const activity = new Activity();
571
+ activity.ActivityId = activity.createId();
572
+ activity.Action = ActionEnum.UPDATE;
573
+ activity.Description = 'Set Rental as Terminated';
574
+ activity.EntityType = 'Rental';
575
+ activity.EntityId = this.RentalId;
576
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
577
+ activity.EntityValueAfter = JSON.stringify(entityValueAfter);
578
+ await activity.create(loginUser.ObjectId, dbTransaction);
579
+
580
+ return this;
581
+ } catch (err) {
582
+ throw err;
583
+ }
584
+ }
585
+
586
+ async getCustomerActiveRentals(
587
+ loginUser: LoginUser,
588
+ dbTransaction: any,
589
+ CustomerId: string,
590
+ ): Promise<IRentalAttr[]> {
591
+ try {
592
+ // Part 1: Privilege Checking
593
+ // Call loginUser.checkPrivileges() by passing:
594
+ // SystemCode: <get_from_app_config>
595
+ // PrivilegeCode: "RENTAL_VIEW"
596
+ const systemCode =
597
+ ApplicationConfig.getComponentConfigValue('system-code');
598
+ const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_VIEW');
599
+
600
+ if (!isPrivileged) {
601
+ throw new ClassError(
602
+ 'Rental',
603
+ 'RentalErrMsg01',
604
+ "You do not have 'Rental - View' privilege.",
605
+ );
606
+ }
607
+
608
+ // Part 2: Retrieve Rentals and Returns
609
+ // Call Rental._Repo findAll method by passing:
610
+ // where:
611
+ // Status: "Active"
612
+ // [Op.OR]:
613
+ // CustomerId: Params.CustomerId
614
+ // '$JointHirers.CustomerId$': Params.CustomerId
615
+ // include:
616
+ // model: JointHirerModel
617
+ // attributes: []
618
+ const query = `
619
+ SELECT
620
+ r.*
621
+ FROM
622
+ rental_Rental r
623
+ LEFT JOIN
624
+ rental_JointHirer jh ON r.RentalId = jh.RentalId
625
+ WHERE
626
+ r.Status = 'Active'
627
+ AND (
628
+ r.CustomerId = '${CustomerId}'
629
+ OR jh.CustomerId = '${CustomerId}'
630
+ )
631
+ GROUP BY
632
+ r.RentalId
633
+ `;
634
+ const db = rentalDb.getConnection();
635
+ const result = await db.query(query, {
636
+ type: QueryTypes.SELECT,
637
+ transaction: dbTransaction,
638
+ model: RentalModel,
639
+ mapToModel: true,
640
+ });
641
+
642
+ // Format the returned records
643
+ const records: IRentalAttr[] = result.map((record: RentalModel) => {
644
+ return {
645
+ RentalId: record.RentalId,
646
+ CustomerId: record.CustomerId,
647
+ CustomerType: record.CustomerType,
648
+ ItemId: record.ItemId,
649
+ ItemType: record.ItemType,
650
+ PriceId: record.PriceId,
651
+ StartDateTime: record.StartDateTime,
652
+ EndDateTime: record.EndDateTime,
653
+ CancelRemarks: record.CancelRemarks,
654
+ TerminateRemarks: record.TerminateRemarks,
655
+ AgreementNo: record.AgreementNo,
656
+ AccountType: record.AccountType,
657
+ Status: record.Status,
658
+ EscheatmentYN: record.EscheatmentYN,
659
+ CreatedById: record.CreatedById,
660
+ CreatedAt: record.CreatedAt,
661
+ UpdatedById: record.UpdatedById,
662
+ UpdatedAt: record.UpdatedAt,
663
+ };
664
+ });
665
+ // Return the returned records.
666
+ return records;
667
+ } catch (error) {
668
+ throw error;
669
+ }
670
+ }
671
+
672
+ async getCustomerIds(loginUser: LoginUser, dbTransaction: any) {
673
+ try {
674
+ // Part 1: Privilege Checking
675
+ // Call loginUser.checkPrivileges() by passing:
676
+ // SystemCode: <get_from_app_config>
677
+ // PrivilegeCode: "RENTAL_VIEW"
678
+ const systemCode =
679
+ ApplicationConfig.getComponentConfigValue('system-code');
680
+ const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_VIEW');
681
+
682
+ if (!isPrivileged) {
683
+ throw new ClassError(
684
+ 'Rental',
685
+ 'RentalErrMsg01',
686
+ "You do not have 'Rental - View' privilege.",
687
+ );
688
+ }
689
+
690
+ // Part 2: Validation
691
+ // Make sure this.RentalId exists, if not throw new ClassError by passing
692
+ if (!this.RentalId) {
693
+ throw new ClassError('Rental', 'RentalErrMsg01', 'RentalId is missing');
694
+ }
695
+
696
+ //Part 3: Retrieve Listing and Returns
697
+ // 3.1 Call Rental._JointHirerRepo findAll method by passing:
698
+ // where:
699
+ // RentalId: this.RentalId
700
+ // dbTransaction
701
+ const options: any = {
702
+ where: {
703
+ RentalId: this.RentalId,
704
+ },
705
+ transaction: dbTransaction,
706
+ };
707
+
708
+ const joinHirers = await Rental._JointHirerRepo.findAll(options);
709
+
710
+ // 3.2 Create a new array variable and set its value to joint hirer and Rental.CustomerId
711
+ // array translated to only CustomerId. Then, append this.CustomerId to the array.
712
+ const customerIds: string[] = [this.CustomerId];
713
+ for (let i = 0; i < joinHirers.length; i++) {
714
+ const jointHirer = joinHirers[i];
715
+ customerIds.push(jointHirer.CustomerId);
716
+ }
717
+
718
+ // 3.3 Return the array.
719
+ return customerIds;
720
+ } catch (error) {
721
+ throw error;
722
+ }
723
+ }
724
+
725
+ async signAgreement(loginUser: LoginUser, dbTransaction: any) {
726
+ try {
727
+ // Part 1: Privilege Checking
728
+ // Call loginUser.checkPrivileges() by passing:
729
+ // SystemCode: <get_from_app_config>
730
+ // PrivilegeCode: "RENTAL_SIGN"
731
+ const systemCode =
732
+ ApplicationConfig.getComponentConfigValue('system-code');
733
+ const isPrivileged = loginUser.checkPrivileges(systemCode, 'RENTAL_SIGN');
734
+
735
+ if (!isPrivileged) {
736
+ throw new ClassError(
737
+ 'Rental',
738
+ 'RentalErrMsg01',
739
+ "You do not have 'RENTAL_SIGN' privilege.",
740
+ );
741
+ }
742
+
743
+ // Part 2: Validation
744
+ // Make sure this.Status is "Pending Signing" and agreementStatus is "Generated", if not throw new ClassError
745
+ const agreement = await Agreement.init(this.AgreementNo, dbTransaction);
746
+ if (
747
+ this.Status !== RentalStatusEnum.PENDING_SIGNING &&
748
+ agreement.Status !== AggrementStatusEnum.GENERATED
749
+ ) {
750
+ throw new ClassError(
751
+ 'Rental',
752
+ 'RentalErrMsg01',
753
+ 'Rental is not ready to be signed yet.',
754
+ );
755
+ }
756
+
757
+ //Part 3: Update Agreement Status
758
+ // 3.1 Set EntityValueBefore to current agreement instance.
759
+ const entityValueAgreementBefore = {
760
+ AgreementNo: agreement.AgreementNo,
761
+ Status: agreement.Status,
762
+ DateSigned: agreement.DateSigned,
763
+ };
764
+
765
+ // 3.2 Set below agreement attributes:
766
+ // DateSigned: current date & time
767
+ // Status: "Signed"
768
+ const payload = {
769
+ DateSigned: new Date(),
770
+ Status: AggrementStatusEnum.SIGNED,
771
+ };
772
+
773
+ // 3.3 Call Rental._AgreementRepo update()
774
+ await Rental._AgreementRepo.update(payload, {
775
+ where: {
776
+ AgreementNo: this.AgreementNo,
777
+ },
778
+ transaction: dbTransaction,
779
+ });
780
+
781
+ const entityValueAgreementAfter = {
782
+ entityValueAgreementBefore,
783
+ ...payload,
784
+ };
785
+
786
+ // Part 4: Record Update Agreement Activity
787
+ const activity = new Activity();
788
+ activity.ActivityId = activity.createId();
789
+ activity.Action = ActionEnum.UPDATE;
790
+ activity.Description = 'Update agreement';
791
+ activity.EntityType = 'RentalAgreement';
792
+ activity.EntityId = this.AgreementNo;
793
+ activity.EntityValueBefore = JSON.stringify(entityValueAgreementBefore);
794
+ activity.EntityValueAfter = JSON.stringify(entityValueAgreementAfter);
795
+ await activity.create(loginUser.ObjectId, dbTransaction);
796
+
797
+ // Part 5: Update Rental Status
798
+ // 5.1 Set EntityValueBefore to current rental instance.
799
+ const entityValueRentalBefore = {
800
+ RentalId: this.RentalId,
801
+ CustomerId: this.CustomerId,
802
+ CustomerType: this.CustomerType,
803
+ ItemId: this.ItemId,
804
+ ItemType: this.ItemType,
805
+ PriceId: this.PriceId,
806
+ StartDateTime: this.StartDateTime,
807
+ EndDateTime: this.EndDateTime,
808
+ CancelRemarks: this.CancelRemarks,
809
+ TerminateRemarks: this.TerminateRemarks,
810
+ AgreementNo: this.AgreementNo,
811
+ AccountType: this.AccountType,
812
+ Status: this.Status,
813
+ EscheatmentYN: this.EscheatmentYN,
814
+ CreatedById: this.CreatedById,
815
+ CreatedAt: this.CreatedAt,
816
+ UpdatedById: this.UpdatedById,
817
+ UpdatedAt: this.UpdatedAt,
818
+ };
819
+ // 5.2: Set below rental attributes:
820
+ // Status: "Pending Key Collection"
821
+ // UpdatedById: loginUser.ObjectId
822
+ // UpdatedAt: current date & time
823
+
824
+ const payloadRental = {
825
+ Status: RentalStatusEnum.PENDING_KEY_COLLECTION,
826
+ UpdatedById: loginUser.ObjectId,
827
+ UpdatedAt: new Date(),
828
+ };
829
+
830
+ // 5.3: Call Rental._Repo update() method by passing:
831
+ // populate rental instance attributes
832
+ // dbTransaction
833
+ await Rental._Repo.update(payloadRental, {
834
+ where: {
835
+ RentalId: this.RentalId,
836
+ },
837
+ transaction: dbTransaction,
838
+ });
839
+
840
+ const entityValueRentalAfter = {
841
+ entityValueRentalBefore,
842
+ ...payloadRental,
843
+ };
844
+
845
+ // Part 6: Record Update Agreement Activity
846
+ const rentalActivity = new Activity();
847
+ rentalActivity.ActivityId = activity.createId();
848
+ rentalActivity.Action = ActionEnum.UPDATE;
849
+ rentalActivity.Description = 'Sign rental agreement';
850
+ rentalActivity.EntityType = 'Rental';
851
+ rentalActivity.EntityId = this.RentalId;
852
+ rentalActivity.EntityValueBefore = JSON.stringify(
853
+ entityValueRentalBefore,
854
+ );
855
+ rentalActivity.EntityValueAfter = JSON.stringify(entityValueRentalAfter);
856
+ await rentalActivity.create(loginUser.ObjectId, dbTransaction);
857
+ } catch (error) {
858
+ throw error;
859
+ }
860
+ }
861
+
862
+ async generateAgreement(
863
+ loginUser: LoginUser,
864
+ dbTransaction: any,
865
+ MediaId: string,
866
+ ) {
867
+ //This method will generate a new rental agreement.
868
+ try {
869
+ // Part 1: Privilege Checking
870
+ // Call loginUser.checkPrivileges() by passing:
871
+ // SystemCode: "<get_from_app_config>"
872
+ // PrivilegeCode: "RENTAL_AGREEMENT_CREATE"
873
+
874
+ const systemCode =
875
+ ApplicationConfig.getComponentConfigValue('system-code');
876
+ const isPrivileged = loginUser.checkPrivileges(
877
+ systemCode,
878
+ 'RENTAL_AGREEMENT_CREATE',
879
+ );
880
+
881
+ if (!isPrivileged) {
882
+ throw new ClassError(
883
+ 'Rental',
884
+ 'RentalErrMsg01',
885
+ "You do not have 'RENTAL_AGREEMENT_CREATE' privilege.",
886
+ );
887
+ }
888
+
889
+ // Part 2: Validation
890
+ // Instantiate existing RentalAgreement by passing:
891
+ // dbTransaction
892
+ // AgreementNo: this.AgreementNo
893
+ // Make sure Params.MediaId exists, if not throw new ClassError by passing:
894
+ // Classname: "Rental"
895
+ // MessageCode: "RentalErrMsg0X"
896
+ // Message: "MediaId is required."
897
+ const agreement = await Agreement.init(this.AgreementNo, dbTransaction);
898
+ if (!MediaId) {
899
+ throw new ClassError(
900
+ 'Rental',
901
+ 'RentalErrMsg0X',
902
+ 'MediaId is required.',
903
+ );
904
+ }
905
+
906
+ // Part 3: Update Agreement Record
907
+ // Set EntityValueBefore to the agreement instance.
908
+ // Set below agreement attributes:
909
+ // Status: "Generated"
910
+ // MediaId: Params.MediaId
911
+
912
+ const EntityValueBefore = agreement;
913
+ agreement.Status = AggrementStatusEnum.GENERATED;
914
+ agreement.MediaId = MediaId;
915
+
916
+ // Call Rental._AgreementRepo update method by passing:
917
+ // Status: agreement.Status
918
+ // MediaId: agreement.MediaId
919
+ // dbTransaction
920
+
921
+ await Rental._AgreementRepo.update(
922
+ {
923
+ Status: agreement.Status,
924
+ MediaId: agreement.MediaId,
925
+ },
926
+ {
927
+ where: {
928
+ AgreementNo: this.AgreementNo,
929
+ },
930
+ transaction: dbTransaction,
931
+ },
932
+ );
933
+
934
+ // Part 4: Record Update Agreement Activity
935
+ // Initialise EntityValueAfter variable and set to agreement instance
936
+ const EntityValueAfter = agreement;
937
+ // Instantiate new activity from Activity class, call createId() method, then set:
938
+ const activity = new Activity();
939
+ // Action: ActionEnum.UPDATE
940
+ // Description: "Generate agreement."
941
+ // EntityType: "RentalAgreement"
942
+ // EntityId: this.AgreementNo
943
+ // EntityValueBefore: EntityValueBefore
944
+ // EntityValueAfter: EntityValueAfter
945
+ activity.ActivityId = activity.createId();
946
+ activity.Action = ActionEnum.UPDATE;
947
+ activity.Description = 'Generate agreement.';
948
+ activity.EntityType = 'RentalAgreement';
949
+ activity.EntityId = this.AgreementNo;
950
+ activity.EntityValueBefore = JSON.stringify(EntityValueBefore);
951
+ activity.EntityValueAfter = JSON.stringify(EntityValueAfter);
952
+
953
+ // Call new activity create method by passing:
954
+ // dbTransaction
955
+ // userId: loginUser.ObjectId
956
+ await activity.create(loginUser.ObjectId, dbTransaction);
957
+ } catch (error) {
958
+ throw error;
959
+ }
960
+ }
961
+ }