@tomei/sso 0.33.8 → 0.34.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,1456 +1,1485 @@
1
- import { ClassError, ObjectBase } from '@tomei/general';
2
- import { GroupRepository } from './group.repository';
3
- import { IGroupAttr } from '../../interfaces/group.interface';
4
- import { GroupTypeEnum } from 'enum';
5
- import { LoginUser } from '../login-user/login-user';
6
- import { IGroupSearchAttr } from '../../interfaces/group-search-attr.interface';
7
- import { ApplicationConfig } from '@tomei/config';
8
- import { Op } from 'sequelize';
9
- import { ActionEnum, Activity } from '@tomei/activity-history';
10
- import { GroupSystemAccessRepository } from '../group-system-access/group-system-access.repository';
11
- import SystemModel from '../../models/system.entity';
12
- import { GroupSystemAccess } from '../group-system-access';
13
- import { RedisService } from '../../redis-client/redis.service';
14
- import SystemPrivilegeModel from '../../models/system-privilege.entity';
15
- import { GroupPrivilegeRepository } from '../group-privilege/group-privilege.repository';
16
- import { SystemPrivilege } from '../system-privilege/system-privilege';
17
- import GroupPrivilegeModel from '../../models/group-privilege.entity';
18
- import { GroupObjectPrivilegeRepository } from '../group-object-privilege/group-object-privilege.repository';
19
- import { GroupObjectPrivilege } from '../group-object-privilege/group-object-privilege';
20
- import { GroupPrivilege } from '../group-privilege/group-privilege';
21
-
22
- export class Group extends ObjectBase {
23
- ObjectId: string;
24
- ObjectName: string;
25
- TableName: 'sso_Group';
26
- ObjectType = 'Group';
27
-
28
- Name: string;
29
- Description: string;
30
- Type: GroupTypeEnum;
31
- ParentGroupCode: string;
32
- InheritParentPrivilegeYN: string;
33
- InheritParentSystemAccessYN: string;
34
- Status: string;
35
- ParentGroup?: any;
36
- private _CreatedById: number;
37
- private _CreatedAt: Date;
38
- private _UpdatedById: number;
39
- private _UpdatedAt: Date;
40
- private static _Repo = new GroupRepository();
41
- private static _GroupSystemAccessRepo = new GroupSystemAccessRepository();
42
- private static _GroupPrivilegeRepo = new GroupPrivilegeRepository();
43
- private static _GroupObjectPrivilegeRepo = new GroupObjectPrivilegeRepository();
44
- private static _RedisService: RedisService;
45
- get GroupCode(): string {
46
- return this.ObjectId;
47
- }
48
-
49
- set GroupCode(value: string) {
50
- this.ObjectId = value;
51
- }
52
-
53
- get CreatedById(): number {
54
- return this._CreatedById;
55
- }
56
-
57
- get CreatedAt(): Date {
58
- return this._CreatedAt;
59
- }
60
-
61
- get UpdatedById(): number {
62
- return this._UpdatedById;
63
- }
64
-
65
- get UpdatedAt(): Date {
66
- return this._UpdatedAt;
67
- }
68
-
69
- private constructor(groupAttr?: IGroupAttr) {
70
- super();
71
- if (groupAttr) {
72
- this.GroupCode = groupAttr.GroupCode;
73
- this.Name = groupAttr.Name;
74
- this.Description = groupAttr?.Description;
75
- this.Type = groupAttr?.Type;
76
- this.ParentGroupCode = groupAttr?.ParentGroupCode;
77
- this.InheritParentPrivilegeYN = groupAttr?.InheritParentPrivilegeYN;
78
- this.InheritParentSystemAccessYN = groupAttr?.InheritParentSystemAccessYN;
79
- this.Status = groupAttr?.Status;
80
- this._CreatedById = groupAttr.CreatedById;
81
- this._CreatedAt = groupAttr.CreatedAt;
82
- this._UpdatedById = groupAttr.UpdatedById;
83
- this._UpdatedAt = groupAttr.UpdatedAt;
84
- }
85
- }
86
-
87
- public static async init(dbTransaction: any, GroupCode?: string) {
88
- try {
89
- Group._RedisService = await RedisService.init();
90
- if (GroupCode) {
91
- const group = await Group._Repo.findByPk(GroupCode, {
92
- transaction: dbTransaction,
93
- });
94
- if (group) {
95
- return new Group(group);
96
- } else {
97
- throw Error('Group not found');
98
- }
99
- }
100
- return new Group();
101
- } catch (error) {
102
- throw new ClassError(
103
- 'Group',
104
- 'GroupErrMsg01',
105
- 'Failed To Initialize Group',
106
- );
107
- }
108
- }
109
-
110
- public static async findAll(
111
- page: number,
112
- row: number,
113
- dbTransaction: any,
114
- loginUser: LoginUser,
115
- search?: IGroupSearchAttr,
116
- ) {
117
- //This method will list all group based on the query params.
118
- //Part 1: Privilege Checking
119
- const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
120
- const isPrivileged = await loginUser.checkPrivileges(
121
- systemCode,
122
- 'GROUP_LIST',
123
- );
124
-
125
- if (!isPrivileged) {
126
- throw new ClassError(
127
- 'Group',
128
- 'GroupErrMsg04',
129
- 'User is not privileged to list group',
130
- );
131
- }
132
-
133
- //Part 2: Retrieve listing
134
- const queryObj: any = {};
135
-
136
- let options: any = {
137
- transaction: dbTransaction,
138
- };
139
-
140
- if (page && row) {
141
- options = {
142
- ...options,
143
- limit: row,
144
- offset: row * (page - 1),
145
- order: [['CreatedAt', 'DESC']],
146
- };
147
- }
148
-
149
- if (search) {
150
- Object.entries(search).forEach(([key, value]) => {
151
- queryObj[key] = {
152
- [Op.substring]: value,
153
- };
154
- });
155
-
156
- options = {
157
- ...options,
158
- where: queryObj,
159
- };
160
-
161
- const result = await Group._Repo.findAllWithPagination(options);
162
-
163
- //Map the result to Group instance
164
- return {
165
- Count: result.count,
166
- Groups: result.rows.map(
167
- (group) => new Group(group.get({ plain: true })),
168
- ),
169
- };
170
- }
171
- }
172
-
173
- public static async create(
174
- loginUser: LoginUser,
175
- dbTransaction: any,
176
- group: Group,
177
- ) {
178
- try {
179
- //Part 1: Privilege Checking
180
- const systemCode =
181
- ApplicationConfig.getComponentConfigValue('system-code');
182
- const isPrivileged = await loginUser.checkPrivileges(
183
- systemCode,
184
- 'GROUP_CREATE',
185
- );
186
- if (!isPrivileged) {
187
- throw new Error('You do not have permission to create group');
188
- }
189
-
190
- //Part 2: Validation
191
- if (!group.GroupCode) {
192
- throw new ClassError(
193
- 'Group',
194
- 'GroupErrMsg02',
195
- 'Group Code is required',
196
- );
197
- }
198
-
199
- if (!group.Name) {
200
- throw new ClassError(
201
- 'Group',
202
- 'GroupErrMsg02',
203
- 'Group Name is required',
204
- );
205
- }
206
-
207
- if (!group.Type) {
208
- throw new ClassError(
209
- 'Group',
210
- 'GroupErrMsg02',
211
- 'Group Type is required',
212
- );
213
- }
214
-
215
- //Check if group code is unique
216
- const existingGroupCode = await Group._Repo.findByPk(group.GroupCode, {
217
- transaction: dbTransaction,
218
- });
219
-
220
- if (existingGroupCode) {
221
- throw new ClassError(
222
- 'Group',
223
- 'GroupErrMsg03',
224
- 'Duplicate GroupCode found.',
225
- );
226
- }
227
-
228
- //Validate parent group code if passed. Call Group._Repo.findByPk
229
- if (group.ParentGroupCode) {
230
- const parentGroup = await Group._Repo.findByPk(group.ParentGroupCode, {
231
- transaction: dbTransaction,
232
- });
233
-
234
- if (!parentGroup) {
235
- throw new ClassError(
236
- 'Group',
237
- 'GroupErrMsg04',
238
- 'ParentGroupCode is not found.',
239
- );
240
- }
241
-
242
- //If Params.group.GroupCode = Params.group?.ParentGroupCode, throw new ClassError
243
- if (group.GroupCode === group.ParentGroupCode) {
244
- throw new ClassError(
245
- 'Group',
246
- 'GroupErrMsg05',
247
- 'GroupCode and ParentGroupCode cannot be the same.',
248
- );
249
- }
250
- }
251
-
252
- //Part 3: Create Group
253
- //Initialise new Group instance and populate
254
- const newGroup = new Group(group);
255
- newGroup.ObjectId = group.GroupCode;
256
- newGroup.Name = group.Name;
257
- newGroup.Type = group.Type;
258
- newGroup.Description = group.Description;
259
- newGroup.ParentGroupCode = group.ParentGroupCode;
260
- newGroup.InheritParentPrivilegeYN = group.InheritParentPrivilegeYN;
261
- newGroup.InheritParentSystemAccessYN = group.InheritParentSystemAccessYN;
262
- newGroup.Status = 'Active';
263
- newGroup._CreatedById = loginUser.UserId;
264
- newGroup._UpdatedById = loginUser.UserId;
265
-
266
- //Call Group._Repo create method
267
- const entityGroupAfter = {
268
- GroupCode: newGroup.ObjectId,
269
- Name: newGroup.Name,
270
- Type: newGroup.Type,
271
- Description: newGroup.Description,
272
- ParentGroupCode: newGroup.ParentGroupCode,
273
- InheritParentPrivilegeYN: newGroup.InheritParentPrivilegeYN,
274
- InheritParentSystemAccessYN: newGroup.InheritParentSystemAccessYN,
275
- Status: newGroup.Status,
276
- CreatedById: newGroup._CreatedById,
277
- UpdatedById: newGroup._UpdatedById,
278
- CreatedAt: newGroup._CreatedAt,
279
- UpdatedAt: newGroup._UpdatedAt,
280
- };
281
-
282
- await Group._Repo.create(entityGroupAfter, {
283
- transaction: dbTransaction,
284
- });
285
-
286
- //Part 4: Record Create Group Activity and return newGroup
287
-
288
- const entityValueBefore = {};
289
-
290
- //Instantiate new activity
291
- const activity = new Activity();
292
- activity.ActivityId = activity.createId();
293
- activity.Action = ActionEnum.ADD;
294
- activity.Description = 'Create Group';
295
- activity.EntityType = 'Group';
296
- activity.EntityId = newGroup.ObjectId;
297
- activity.EntityValueBefore = JSON.stringify(entityValueBefore);
298
- activity.EntityValueAfter = JSON.stringify(entityGroupAfter);
299
-
300
- //Call Activity.create method
301
- await activity.create(loginUser.ObjectId, dbTransaction);
302
-
303
- return newGroup;
304
- } catch (error) {
305
- throw error;
306
- }
307
- }
308
-
309
- protected static async checkDuplicateGroupCode(
310
- dbTransaction: any,
311
- GroupCode,
312
- ) {
313
- const isGroupCodeExist = await Group._Repo.findOne({
314
- where: { GroupCode },
315
- transaction: dbTransaction,
316
- });
317
-
318
- if (isGroupCodeExist) {
319
- throw new ClassError(
320
- 'Group',
321
- 'GroupErrMsg07',
322
- 'GroupCode already exists.',
323
- );
324
- }
325
- }
326
-
327
- public async update(
328
- loginUser: LoginUser,
329
- dbTransaction: any,
330
- group: {
331
- GroupCode: string;
332
- NewGroupCode?: string;
333
- Name?: string;
334
- Description?: string;
335
- Type?: GroupTypeEnum;
336
- ParentGroupCode?: string;
337
- InheritParentPrivilegeYN?: string;
338
- InheritParentSystemAccessYN?: string;
339
- Status?: string;
340
- },
341
- ) {
342
- //Part 1: Privilege Checking
343
- const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
344
- const isPrivileged = await loginUser.checkPrivileges(
345
- systemCode,
346
- 'GROUP_UPDATE',
347
- );
348
-
349
- if (!isPrivileged) {
350
- throw new ClassError(
351
- 'Group',
352
- 'GroupErrMsg06',
353
- 'You do not have the privilege to update Group',
354
- );
355
- }
356
- try {
357
- const currentGroup = await Group.init(dbTransaction, group.GroupCode);
358
- if (group.NewGroupCode) {
359
- await Group.checkDuplicateGroupCode(dbTransaction, group.NewGroupCode);
360
- }
361
-
362
- if (
363
- group.ParentGroupCode &&
364
- currentGroup.ParentGroupCode !== group.ParentGroupCode
365
- ) {
366
- const parentGroup = await Group.init(
367
- dbTransaction,
368
- group.ParentGroupCode,
369
- );
370
- if (!parentGroup) {
371
- throw new ClassError(
372
- 'Group',
373
- 'GroupErrMsg08',
374
- 'Parent Group Code not found',
375
- );
376
- }
377
- }
378
-
379
- const entityValueBefore = {
380
- GroupCode: currentGroup.GroupCode,
381
- Name: currentGroup.Name,
382
- Type: currentGroup.Type,
383
- Description: currentGroup.Description,
384
- ParentGroupCode: currentGroup.ParentGroupCode,
385
- InheritParentPrivilegeYN: currentGroup.InheritParentPrivilegeYN,
386
- InheritParentSystemAccessYN: currentGroup.InheritParentSystemAccessYN,
387
- Status: currentGroup.Status,
388
- CreatedById: currentGroup._CreatedById,
389
- UpdatedById: currentGroup._UpdatedById,
390
- CreatedAt: currentGroup._CreatedAt,
391
- UpdatedAt: currentGroup._UpdatedAt,
392
- };
393
-
394
- currentGroup.GroupCode = group?.NewGroupCode || currentGroup.GroupCode;
395
- currentGroup.Name = group?.Name || currentGroup.Name;
396
- currentGroup.Type = group?.Type || currentGroup.Type;
397
- currentGroup.Description = group?.Description || currentGroup.Description;
398
- currentGroup.ParentGroupCode =
399
- group?.ParentGroupCode || currentGroup.ParentGroupCode;
400
- currentGroup.InheritParentPrivilegeYN =
401
- group?.InheritParentPrivilegeYN ||
402
- currentGroup.InheritParentPrivilegeYN;
403
- currentGroup.InheritParentSystemAccessYN =
404
- group?.InheritParentSystemAccessYN ||
405
- currentGroup.InheritParentSystemAccessYN;
406
- currentGroup.Status = group?.Status || currentGroup.Status;
407
- currentGroup._UpdatedById = loginUser.UserId;
408
- currentGroup._UpdatedAt = new Date();
409
-
410
- await Group._Repo.update(
411
- {
412
- GroupCode: currentGroup.GroupCode,
413
- Name: currentGroup.Name,
414
- Type: currentGroup.Type,
415
- Description: currentGroup.Description,
416
- ParentGroupCode: currentGroup.ParentGroupCode,
417
- InheritParentPrivilegeYN: currentGroup.InheritParentPrivilegeYN,
418
- InheritParentSystemAccessYN: currentGroup.InheritParentSystemAccessYN,
419
- Status: currentGroup.Status,
420
- UpdatedById: currentGroup._UpdatedById,
421
- UpdatedAt: currentGroup._UpdatedAt,
422
- },
423
- {
424
- where: {
425
- GroupCode: group.GroupCode,
426
- },
427
- transaction: dbTransaction,
428
- },
429
- );
430
-
431
- const entityValueAfter = {
432
- GroupCode: currentGroup.GroupCode,
433
- Name: currentGroup.Name,
434
- Type: currentGroup.Type,
435
- Description: currentGroup.Description,
436
- ParentGroupCode: currentGroup.ParentGroupCode,
437
- InheritParentPrivilegeYN: currentGroup.InheritParentPrivilegeYN,
438
- InheritParentSystemAccessYN: currentGroup.InheritParentSystemAccessYN,
439
- Status: currentGroup.Status,
440
- CreatedById: currentGroup._CreatedById,
441
- UpdatedById: currentGroup._UpdatedById,
442
- CreatedAt: currentGroup._CreatedAt,
443
- UpdatedAt: currentGroup._UpdatedAt,
444
- };
445
-
446
- const activity = new Activity();
447
- activity.ActivityId = activity.createId();
448
- activity.Action = ActionEnum.UPDATE;
449
- activity.Description = `Update Group ${group.Type}`;
450
- activity.EntityType = 'Group';
451
- activity.EntityId = group.GroupCode;
452
- activity.EntityValueBefore = JSON.stringify(entityValueBefore);
453
- activity.EntityValueAfter = JSON.stringify(entityValueAfter);
454
- await activity.create(loginUser.ObjectId, dbTransaction);
455
-
456
- return currentGroup;
457
- } catch (error) {
458
- throw error;
459
- }
460
- }
461
-
462
- public static async getSystemAccesses(
463
- loginUser: LoginUser,
464
- dbTransaction: any,
465
- GroupCode: string,
466
- Page: number,
467
- Rows: number,
468
- Search: {
469
- SystemCode?: string;
470
- Status?: string;
471
- },
472
- ) {
473
- // Part 1: Privilege Checking
474
- const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
475
- const isPrivileged = await loginUser.checkPrivileges(
476
- systemCode,
477
- 'SYSTEM_ACCESS_VIEW',
478
- );
479
-
480
- if (!isPrivileged) {
481
- throw new ClassError(
482
- 'Group',
483
- 'GroupErrMsg06',
484
- 'You do not have the privilege to view system access',
485
- );
486
- }
487
-
488
- try {
489
- // Part 2: Validation
490
- await Group.init(dbTransaction, GroupCode);
491
-
492
- // Part 3: Retrieve System Access and returns
493
- const queryObj: any = { GroupCode: GroupCode };
494
-
495
- if (Search) {
496
- Object.entries(Search).forEach(([key, value]) => {
497
- queryObj[key] = value;
498
- });
499
- }
500
-
501
- let options: any = {
502
- where: queryObj,
503
- distinct: true,
504
- transaction: dbTransaction,
505
- };
506
-
507
- if (Page && Rows) {
508
- options = {
509
- ...options,
510
- limit: Rows,
511
- offset: Rows * (Page - 1),
512
- order: [['CreatedAt', 'DESC']],
513
- };
514
- }
515
-
516
- const systemAccess = await Group._GroupSystemAccessRepo.findAndCountAll(
517
- options,
518
- );
519
- return systemAccess;
520
- } catch (error) {
521
- return error;
522
- }
523
- }
524
-
525
- private static async getInheritedSystemAccess(
526
- dbTransaction: any,
527
- group: Group,
528
- ): Promise<any[]> {
529
- const options: any = {
530
- where: {
531
- GroupCode: group.GroupCode,
532
- Status: 'Active',
533
- },
534
- include: [
535
- {
536
- model: SystemModel,
537
- },
538
- ],
539
- transaction: dbTransaction,
540
- };
541
- let systemAccess = await Group._GroupSystemAccessRepo.findAll(options);
542
-
543
- if (group.InheritParentSystemAccessYN === 'Y' && group.ParentGroupCode) {
544
- const parentGroup = await Group.init(
545
- dbTransaction,
546
- group.ParentGroupCode,
547
- );
548
- const parentSystemAccesses = await this.getInheritedSystemAccess(
549
- dbTransaction,
550
- parentGroup,
551
- );
552
- systemAccess = systemAccess.concat(parentSystemAccesses);
553
- }
554
- return systemAccess;
555
- }
556
-
557
- public static async getParentSystemAccesses(
558
- loginUser: LoginUser,
559
- dbTransaction: any,
560
- GroupCode: string,
561
- ) {
562
- // Part 1: Privilege Checking
563
- const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
564
- const isPrivileged = await loginUser.checkPrivileges(
565
- systemCode,
566
- 'SYSTEM_ACCESS_VIEW',
567
- );
568
-
569
- if (!isPrivileged) {
570
- throw new ClassError(
571
- 'Group',
572
- 'GroupErrMsg06',
573
- 'You do not have the privilege to view system access',
574
- );
575
- }
576
-
577
- try {
578
- const group = await Group.init(dbTransaction, GroupCode);
579
- if (group.InheritParentSystemAccessYN !== 'Y' && !group.ParentGroupCode) {
580
- return [];
581
- } else {
582
- const parentGroup = await Group.init(
583
- dbTransaction,
584
- group.ParentGroupCode,
585
- );
586
- const inheritSystemAccess = await Group.getInheritedSystemAccess(
587
- dbTransaction,
588
- parentGroup,
589
- );
590
- return inheritSystemAccess;
591
- }
592
- } catch (error) {
593
- throw error;
594
- }
595
- }
596
-
597
- public static async addSystemAccesses(
598
- loginUser: LoginUser,
599
- dbTransaction: any,
600
- GroupCode: string,
601
- SystemCodes: string[],
602
- ) {
603
- // Part 1: Privilege Checking
604
- const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
605
- const isPrivileged = await loginUser.checkPrivileges(
606
- systemCode,
607
- 'SYSTEM_ACCESS_CREATE',
608
- );
609
-
610
- if (!isPrivileged) {
611
- throw new ClassError(
612
- 'Group',
613
- 'GroupErrMsg07',
614
- 'You do not have the privilege to create system access',
615
- );
616
- }
617
-
618
- try {
619
- if (SystemCodes.length > 0) {
620
- for (const element of SystemCodes) {
621
- const CurrentGroupSystemAccess = await Group.getSystemAccesses(
622
- loginUser,
623
- dbTransaction,
624
- GroupCode,
625
- 1,
626
- Number.MAX_SAFE_INTEGER,
627
- { SystemCode: element },
628
- );
629
-
630
- if (CurrentGroupSystemAccess?.count > 0) {
631
- throw new ClassError(
632
- 'Group',
633
- 'GroupErrMsg08',
634
- 'System access already exists',
635
- );
636
- }
637
-
638
- const groupSystemAccess = await GroupSystemAccess.init(dbTransaction);
639
- groupSystemAccess.createId();
640
- groupSystemAccess.GroupCode = GroupCode;
641
- groupSystemAccess.SystemCode = element;
642
- groupSystemAccess.Status = 'Active';
643
- groupSystemAccess.CreatedById = +loginUser.ObjectId;
644
- groupSystemAccess.CreatedAt = new Date();
645
- groupSystemAccess.UpdatedById = +loginUser.ObjectId;
646
- groupSystemAccess.UpdatedAt = new Date();
647
-
648
- const EntityValueAfter = {
649
- GroupCode: groupSystemAccess.GroupCode,
650
- SystemCode: groupSystemAccess.SystemCode,
651
- Status: groupSystemAccess.Status,
652
- CreatedById: groupSystemAccess.CreatedById,
653
- CreatedAt: groupSystemAccess.CreatedAt,
654
- UpdatedById: groupSystemAccess.UpdatedById,
655
- UpdatedAt: groupSystemAccess.UpdatedAt,
656
- };
657
-
658
- const systemAccess = await Group._GroupSystemAccessRepo.create(
659
- EntityValueAfter,
660
- {
661
- transaction: dbTransaction,
662
- },
663
- );
664
-
665
- const activity = new Activity();
666
- activity.ActivityId = activity.createId();
667
- activity.Action = ActionEnum.ADD;
668
- activity.Description = 'Create Group System Access';
669
- activity.EntityType = 'GroupSystemAccess';
670
- activity.EntityId = systemAccess.GroupSystemAccessId?.toString();
671
- activity.EntityValueBefore = JSON.stringify({});
672
- activity.EntityValueAfter = JSON.stringify(EntityValueAfter);
673
-
674
- await activity.create(loginUser.ObjectId, dbTransaction);
675
- }
676
-
677
- return { Message: 'Successfully added.' };
678
- }
679
- } catch (error) {
680
- throw error;
681
- }
682
- }
683
-
684
- public static async deleteSystemAccess(
685
- loginUser: LoginUser,
686
- dbTransaction: any,
687
- GroupCode: string,
688
- SystemCode: string,
689
- ) {
690
- // Part 1: Privilege Checking
691
- const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
692
- const isPrivileged = await loginUser.checkPrivileges(
693
- systemCode,
694
- 'SYSTEM_ACCESS_DELETE',
695
- );
696
-
697
- if (!isPrivileged) {
698
- throw new ClassError(
699
- 'Group',
700
- 'GroupErrMsg08',
701
- 'You do not have the privilege to delete system access',
702
- );
703
- }
704
-
705
- try {
706
- const currentGroupSystemAccess = await Group.getSystemAccesses(
707
- loginUser,
708
- dbTransaction,
709
- GroupCode,
710
- 1,
711
- Number.MAX_SAFE_INTEGER,
712
- { SystemCode: SystemCode },
713
- );
714
-
715
- if (currentGroupSystemAccess.count < 1) {
716
- throw new ClassError(
717
- 'Group',
718
- 'GroupErrMsg10',
719
- 'No associated system access found.',
720
- );
721
- }
722
-
723
- await Group._GroupSystemAccessRepo.delete(
724
- GroupCode,
725
- SystemCode,
726
- dbTransaction,
727
- );
728
-
729
- const EntityValueBefore = {
730
- GroupCode: currentGroupSystemAccess?.rows[0]?.GroupCode,
731
- SystemCode: currentGroupSystemAccess?.rows[0]?.SystemCode,
732
- Status: currentGroupSystemAccess?.rows[0]?.Status,
733
- CreatedById: currentGroupSystemAccess?.rows[0]?.CreatedById,
734
- CreatedAt: currentGroupSystemAccess?.rows[0]?.CreatedAt,
735
- UpdatedById: currentGroupSystemAccess?.rows[0]?.UpdatedById,
736
- UpdatedAt: currentGroupSystemAccess?.rows[0]?.UpdatedAt,
737
- };
738
-
739
- const activity = new Activity();
740
- activity.ActivityId = activity.createId();
741
- activity.Action = ActionEnum.DELETE;
742
- activity.Description = 'Delete Group System Access';
743
- activity.EntityType = 'GroupSystemAccess';
744
- activity.EntityId =
745
- currentGroupSystemAccess?.rows[0]?.GroupSystemAccessId?.toString();
746
- activity.EntityValueBefore = JSON.stringify(EntityValueBefore);
747
- activity.EntityValueAfter = JSON.stringify({});
748
-
749
- await activity.create(loginUser.ObjectId, dbTransaction);
750
-
751
- return { Message: 'System access removed.', SystemCode: SystemCode };
752
- } catch (error) {
753
- throw error;
754
- }
755
- }
756
-
757
- public static async getSystemPrivileges(
758
- loginUser: LoginUser,
759
- dbTransaction: any,
760
- GroupCode: string,
761
- search?: {
762
- SystemCode?: string;
763
- Status?: string;
764
- },
765
- ) {
766
- try {
767
- //Part 1: Privilege Checking
768
- const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
769
- const isPrivileged = await loginUser.checkPrivileges(
770
- systemCode,
771
- 'GROUP_PRIVILEGE_VIEW',
772
- );
773
-
774
- if (!isPrivileged) {
775
- throw new ClassError(
776
- 'Group',
777
- 'GroupErrMsg11',
778
- 'You do not have the privilege to view group privileges',
779
- );
780
- }
781
-
782
- //Set group to instantiation of existing Group
783
- await Group.init(dbTransaction, GroupCode);
784
-
785
- //Part 3: Retrieve Group Own Privilege
786
- //Retrieve group data and it's privileged by calling Group._Repo.findAll
787
- let where: any = {
788
- GroupCode,
789
- };
790
-
791
- let systemWhere: any = {};
792
-
793
- if (search) {
794
- if (search.Status) {
795
- where = {
796
- ...where,
797
- Status: search.Status,
798
- };
799
- }
800
-
801
- if (search.SystemCode) {
802
- systemWhere = {
803
- SystemCode: {
804
- [Op.substring]: search.SystemCode,
805
- },
806
- };
807
- }
808
- }
809
-
810
- const groupOwnPrivileges = await Group._GroupPrivilegeRepo.findAll({
811
- where,
812
- include: [
813
- {
814
- model: SystemPrivilegeModel,
815
- where: systemWhere,
816
- },
817
- ],
818
- transaction: dbTransaction,
819
- });
820
-
821
- //Create variable called privileges and Map the SystemPrivilege data retrieved from 3.1 into SystemPrivilege object and push it to the privileges variables
822
- let privileges: SystemPrivilege[] = [];
823
-
824
- for (const groupPrivilege of groupOwnPrivileges) {
825
- const systemPrivilege = await SystemPrivilege.init(
826
- dbTransaction,
827
- );
828
- systemPrivilege.setAttributes(groupPrivilege.Privilege.get({ plain: true }));
829
- privileges.push(systemPrivilege);
830
- }
831
-
832
- return privileges;
833
- } catch (error) {
834
- throw error;
835
- }
836
- }
837
-
838
- public static async getInheritedSystemPrivileges(
839
- dbTransaction: any,
840
- GroupCode: string,
841
- search?: {
842
- SystemCode?: string;
843
- Status?: string;
844
- PrivilegeCode?: string;
845
- },
846
- ): Promise<SystemPrivilege[]> {
847
- try {
848
- //Retrieve group data and it's privileges by calling Group._Repo.findAll
849
- let where: any = {
850
- GroupCode,
851
- };
852
-
853
- let groupPrivilegeWhere: any = {};
854
- let systemPrivilegeWhere: any = {};
855
-
856
- if (search) {
857
- if (search.Status) {
858
- groupPrivilegeWhere = {
859
- Status: search.Status,
860
- };
861
- }
862
-
863
- if (search.SystemCode) {
864
- systemPrivilegeWhere = {
865
- SystemCode: {
866
- [Op.substring]: search.SystemCode,
867
- },
868
- };
869
- }
870
- }
871
- const group = await Group._Repo.findOne({
872
- where: where,
873
- include: [
874
- {
875
- model: GroupPrivilegeModel,
876
- where: groupPrivilegeWhere,
877
- include: [
878
- {
879
- model: SystemPrivilegeModel,
880
- where: systemPrivilegeWhere,
881
- },
882
- ],
883
- },
884
- ],
885
- transaction: dbTransaction,
886
- });
887
-
888
- //Retrieve group object privileges by calling LoginUser._GroupObjectPrivilegeRepo.findAll
889
- let objectWhere: any = {
890
- GroupCode,
891
- };
892
- let systemWhere: any = {};
893
- if (search) {
894
- Object.entries(search).forEach(([key, value]) => {
895
- if (key === 'SystemCode') {
896
- systemWhere[key] = {
897
- [Op.substring]: value,
898
- };
899
- } else {
900
- objectWhere[key] = {
901
- [Op.substring]: value,
902
- };
903
- }
904
- });
905
- }
906
- const groupObjectPrivileges = await Group._GroupObjectPrivilegeRepo.findAll({
907
- where: objectWhere,
908
- include: [
909
- {
910
- model: SystemPrivilegeModel,
911
- where: systemWhere,
912
- },
913
- ],
914
- transaction: dbTransaction,
915
- });
916
-
917
- //Map to SystemPrivilege object
918
- let privileges: SystemPrivilege[] = [];
919
- for (const groupPrivilege of group.GroupPrivileges) {
920
- const systemPrivilege = await SystemPrivilege.init(dbTransaction);
921
- systemPrivilege.setAttributes(groupPrivilege.Privilege.get({ plain: true }));
922
- privileges.push(systemPrivilege);
923
- }
924
-
925
- for (const groupObjectPrivilege of groupObjectPrivileges) {
926
- const systemPrivilege = await SystemPrivilege.init(dbTransaction);
927
- systemPrivilege.setAttributes(groupObjectPrivilege.Privilege.get({ plain: true }));
928
- privileges.push(systemPrivilege);
929
- }
930
-
931
- //Part 2: Retrieve Privileges Inherited from Parent Group
932
- //if group data retrieved from 1.1 have InheritParentPrivilegeYN == "Y" and ParentGroupCode value is not empty. Call this method again
933
- if (group.InheritParentPrivilegeYN === 'Y' && group.ParentGroupCode) {
934
- const inheritedPrivileges = await Group.getInheritedSystemPrivileges(
935
- dbTransaction,
936
- group.ParentGroupCode,
937
- search,
938
- );
939
- privileges = privileges.concat(inheritedPrivileges);
940
- }
941
-
942
- //format to make sure no duplicate
943
- const uniquePrivileges = Array.from(new Set(privileges.map(a => a.PrivilegeCode)))
944
- .map(PrivilegeCode => {
945
- return privileges.find(a => a.PrivilegeCode === PrivilegeCode);
946
- });
947
-
948
- return uniquePrivileges;
949
- } catch (error) {
950
- throw error;
951
- }
952
- }
953
-
954
- public static async getParentSystemPrivileges(
955
- loginUser: LoginUser,
956
- dbTransaction: any,
957
- GroupCode: string,
958
- search?: {
959
- SystemCode?: string;
960
- Status?: string;
961
- PrivilegeCode?: string;
962
- },
963
- ): Promise<SystemPrivilege[]> {
964
- try {
965
- //Part 1: Privilege Checking
966
- const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
967
- const isPrivileged = await loginUser.checkPrivileges(
968
- systemCode,
969
- 'GROUP_PRIVILEGE_VIEW',
970
- );
971
-
972
- if (!isPrivileged) {
973
- throw new ClassError(
974
- 'Group',
975
- 'GroupErrMsg11',
976
- 'You do not have the privilege to view group privileges',
977
- );
978
- }
979
-
980
- //Part 2: Validation
981
- //Set group to instantiation of existing Group
982
- const group = await Group.init(dbTransaction, GroupCode);
983
- //Check if group.InheritParentPrivilegeYN == "Y" and ParentGroupCode value is not empty. if no then return an empty array
984
- if (group.InheritParentPrivilegeYN !== 'Y' && !group.ParentGroupCode) {
985
- return [];
986
- }
987
-
988
- //Part 3: Retrieve Group Own Privilege
989
- //Retrieve group data and it's privileged by calling Group.getIheritedSystemPrivileges
990
- const privileges = await Group.getInheritedSystemPrivileges(
991
- dbTransaction,
992
- group.ParentGroupCode,
993
- search,
994
- );
995
-
996
- return privileges;
997
- } catch (error) {
998
- throw error;
999
- }
1000
- }
1001
-
1002
- public static async assignGroupObjectPrivilege(
1003
- loginUser: LoginUser,
1004
- dbTransaction: any,
1005
- GroupCode: string,
1006
- GroupObjectPrivileges: GroupObjectPrivilege[]
1007
- ): Promise<string> {
1008
- try {
1009
- //Part 1: Privilege Checking
1010
- const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
1011
- const isPrivileged = await loginUser.checkPrivileges(
1012
- systemCode,
1013
- 'GROUP_OBJECT_PRIVILEGE_ASSIGN',
1014
- );
1015
-
1016
- if (!isPrivileged) {
1017
- throw new ClassError(
1018
- 'Group',
1019
- 'GroupErrMsg12',
1020
- 'You do not have the privilege to assign group object privilege',
1021
- );
1022
- }
1023
-
1024
- //Part 2: Validation
1025
- //Initialise group with group init
1026
- const group = await Group.init(dbTransaction, GroupCode);
1027
- //Retrieve all group system access by calling Group.getSystemAccesses
1028
- const groupSystemAccesses = await Group.getSystemAccesses(
1029
- loginUser,
1030
- dbTransaction,
1031
- GroupCode,
1032
- 1,
1033
- Number.MAX_SAFE_INTEGER,
1034
- {},
1035
- );
1036
-
1037
- //If Group.InheritParentSystemAccess == "Y" and Group.ParentGroupCode exist, initialise parent group
1038
- let parentGroupSystemAccesses: any = {};
1039
- if (group.InheritParentSystemAccessYN === 'Y' && group.ParentGroupCode) {
1040
- //Retrieve all parent group system access by calling Group.getSystemAccesses
1041
- parentGroupSystemAccesses = await Group.getSystemAccesses(
1042
- loginUser,
1043
- dbTransaction,
1044
- group.ParentGroupCode,
1045
- 1,
1046
- Number.MAX_SAFE_INTEGER,
1047
- {},
1048
- );
1049
- }
1050
-
1051
- // For each Params.GroupObjectPrivileges.
1052
- for (const groupObjectPrivilege of GroupObjectPrivileges) {
1053
- //Initialise existing System privilege
1054
- const systemPrivilege = await SystemPrivilege.init(dbTransaction, groupObjectPrivilege.PrivilegeCode);
1055
- //Check whether the system codes used by that privilege is exist inside the group system access
1056
- const combinedSystemAccesses = {
1057
- ...groupSystemAccesses.rows,
1058
- ...parentGroupSystemAccesses.rows,
1059
- };
1060
- const systemAccess = combinedSystemAccesses.find(
1061
- (systemAccess) => systemAccess.SystemCode === systemPrivilege.SystemCode,
1062
- );
1063
- if (!systemAccess) {
1064
- throw new ClassError(
1065
- 'Group',
1066
- 'GroupErrMsg13',
1067
- 'Failed to assign privilege ' + groupObjectPrivilege.PrivilegeCode + ' due to non-existent system access.',
1068
- );
1069
- }
1070
-
1071
- //Check whether the group object privilege already exist by using Group._GroupObjectPrivilegesRepo.findOne
1072
- const groupObjectPrivilegeData = await Group._GroupObjectPrivilegeRepo.findOne({
1073
- where: {
1074
- GroupCode,
1075
- PrivilegeCode: groupObjectPrivilege.PrivilegeCode,
1076
- ObjectId: groupObjectPrivilege.ObjectId,
1077
- ObjectType: groupObjectPrivilege.ObjectType,
1078
- },
1079
- transaction: dbTransaction,
1080
- });
1081
- //If GroupObjectPrivilege record exist. Skip this loop and proceed to the next privilege code
1082
- if (groupObjectPrivilegeData) {
1083
- continue;
1084
- } else {
1085
- //Call GroupObjectPrivilege.create
1086
- await GroupObjectPrivilege.create(
1087
- loginUser,
1088
- dbTransaction,
1089
- groupObjectPrivilege,
1090
- );
1091
- }
1092
- }
1093
-
1094
- return 'Successfully added.';
1095
- } catch (error) {
1096
- throw error;
1097
- }
1098
- }
1099
-
1100
- public static async getGroubObjectPrivileges(
1101
- loginUser: LoginUser,
1102
- dbTransaction: any,
1103
- GroupCode: string,
1104
- search?: {
1105
- PrivilegeCode?: string;
1106
- ObjectType?: string;
1107
- ObjectId?: string;
1108
- SystemCode?: string;
1109
- }
1110
- ): Promise<SystemPrivilege[]> {
1111
- try {
1112
- // Part 1: Privilege Checking
1113
- const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
1114
- const isPrivileged = await loginUser.checkPrivileges(
1115
- systemCode,
1116
- 'GROUP_PRIVILEGE_VIEW',
1117
- );
1118
-
1119
- if (!isPrivileged) {
1120
- throw new ClassError(
1121
- 'Group',
1122
- 'GroupErrMsg11',
1123
- 'You do not have the privilege to view group privileges',
1124
- );
1125
- }
1126
-
1127
- // Part 2: Validation
1128
- // Set group to instantiation of existing Group
1129
- await Group.init(dbTransaction, GroupCode);
1130
-
1131
- // Part 3: Retrieve Group Own Privilege
1132
- // Retrieve group object privileges by calling LoginUser._GroupObjectPrivilegeRepo.findAll
1133
- let where: any = {
1134
- GroupCode,
1135
- };
1136
-
1137
- let systemWhere: any = {};
1138
-
1139
- if (search) {
1140
- Object.entries(search).forEach(([key, value]) => {
1141
- if (key === 'SystemCode') {
1142
- systemWhere[key] = {
1143
- [Op.substring]: value,
1144
- };
1145
- } else {
1146
- where[key] = {
1147
- [Op.substring]: value,
1148
- };
1149
- }
1150
- });
1151
- }
1152
-
1153
- const groupObjectPrivileges = await Group._GroupObjectPrivilegeRepo.findAll({
1154
- where,
1155
- include: [
1156
- {
1157
- model: SystemPrivilegeModel,
1158
- where: systemWhere,
1159
- },
1160
- ],
1161
- transaction: dbTransaction,
1162
- });
1163
- // Create variable called privileges and Map the SystemPrivilege data retrieved from 3.1 into SystemPrivilege object and push it to the privileges variables
1164
- let privileges: SystemPrivilege[] = [];
1165
- for (const groupObjectPrivilege of groupObjectPrivileges) {
1166
- const systemPrivilege = await SystemPrivilege.init(
1167
- dbTransaction,
1168
- );
1169
- systemPrivilege.setAttributes(groupObjectPrivilege.Privilege.get({ plain: true }));
1170
- privileges.push(systemPrivilege);
1171
- }
1172
-
1173
- //Remove duplicate
1174
- const uniquePrivileges = Array.from(new Set(privileges.map(a => a.PrivilegeCode)))
1175
- .map(PrivilegeCode => {
1176
- return privileges.find(a => a.PrivilegeCode === PrivilegeCode);
1177
- });
1178
-
1179
- // Create the result based on the spec on return then returns it.
1180
- return uniquePrivileges;
1181
- } catch (error) {
1182
- throw error;
1183
- }
1184
- }
1185
-
1186
- public static async assignGroupPrivileges(
1187
- loginUser: LoginUser,
1188
- dbTransaction: any,
1189
- GroupCode: string,
1190
- PrivilegeCodes: string[],
1191
- ) {
1192
- try {
1193
- // Part 1: Privilege Checking
1194
- const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
1195
- const isPrivileged = await loginUser.checkPrivileges(
1196
- systemCode,
1197
- 'GROUP_PRIVILEGE_ASSIGN',
1198
- );
1199
-
1200
- if (!isPrivileged) {
1201
- throw new ClassError(
1202
- 'Group',
1203
- 'GroupErrMsg06',
1204
- 'You do not have the privilege to assign group privileges',
1205
- );
1206
- }
1207
-
1208
- // Part 2: Validation, Create and Record Activity
1209
- // Initialise group with group init
1210
-
1211
- const group = await Group.init(dbTransaction, GroupCode);
1212
-
1213
- // Retrieve all group system access by calling Group.getSystemAccess
1214
- const groupSystemAccesses = await Group.getSystemAccesses(
1215
- loginUser,
1216
- dbTransaction,
1217
- GroupCode,
1218
- 1,
1219
- Number.MAX_SAFE_INTEGER,
1220
- {},
1221
- );
1222
-
1223
- // If Group.InheritParentSystemAccess == "Y" and Group.ParentGroupCode exist
1224
- let parentGroupSystemAccesses: any = {};
1225
- if (group.InheritParentSystemAccessYN === 'Y' && group.ParentGroupCode) {
1226
- // Retrieve all parent group system access by calling Group.getSystemAccess
1227
- parentGroupSystemAccesses = await Group.getSystemAccesses(
1228
- loginUser,
1229
- dbTransaction,
1230
- group.ParentGroupCode,
1231
- 1,
1232
- Number.MAX_SAFE_INTEGER,
1233
- {},
1234
- );
1235
- }
1236
-
1237
- // For each Params.PrivilegesCodes.
1238
- for (const PrivilegeCode of PrivilegeCodes) {
1239
- // Initialise existing System privilege by calling SystemPrivilege.init
1240
- const systemPrivilege = await SystemPrivilege.init(dbTransaction, PrivilegeCode);
1241
- //Check whether the system codes used by that privilege is exist inside the group system access retrieved from step 2.2 & 2.4. If system code does not exist in group system access, throw a new ClassError by passing:
1242
- // Classname: "Group"
1243
- // MessageCode: "GroupErrMsg0X"
1244
- // Message: "Failed to assign privilege <PrivilegeCode> due to non-existent system access."
1245
- const combinedSystemAccesses = {
1246
- ...groupSystemAccesses.rows,
1247
- ...parentGroupSystemAccesses.rows,
1248
- };
1249
- const systemAccess = combinedSystemAccesses.find(
1250
- (systemAccess) => systemAccess.SystemCode === systemPrivilege.SystemCode,
1251
- );
1252
- if (!systemAccess) {
1253
- throw new ClassError(
1254
- 'Group',
1255
- 'GroupErrMsg13',
1256
- 'Failed to assign privilege ' + PrivilegeCode + ' due to non-existent system access.',
1257
- );
1258
- }
1259
-
1260
- //Check whether the group privilege exist by using Group._GroupPrivilegesRepo.findOne
1261
- const groupPrivilege = await Group._GroupPrivilegeRepo.findOne({
1262
- where: {
1263
- GroupCode,
1264
- PrivilegeCode,
1265
- },
1266
- transaction: dbTransaction,
1267
- });
1268
-
1269
- //If GroupPrivilege record exist and status is "Active". Skip this loop and proceed to the next privilege code
1270
- if (groupPrivilege && groupPrivilege.Status === 'Active') {
1271
- continue;
1272
- }
1273
-
1274
- let entityValueBefore = {};
1275
- let entityValueAfter = {};
1276
- let action = ActionEnum.ADD;
1277
- let description = 'Create Group Privilege';
1278
- let entityId = null;
1279
- //If GroupPrivilege record exist and status is not "Active" do the following:
1280
- if (groupPrivilege && groupPrivilege.Status !== 'Active') {
1281
- //Set this GroupPrivilege entity as EntityValueBefore
1282
- entityValueBefore = {
1283
- GroupCode: groupPrivilege.GroupCode,
1284
- PrivilegeCode: groupPrivilege.PrivilegeCode,
1285
- Status: groupPrivilege.Status,
1286
- CreatedById: groupPrivilege.CreatedById,
1287
- CreatedAt: groupPrivilege.CreatedAt,
1288
- UpdatedById: groupPrivilege.UpdatedById,
1289
- UpdatedAt: groupPrivilege.UpdatedAt,
1290
- };
1291
-
1292
- //Update the status to active using Group._GroupPrivilegesRepo.Update.
1293
- const updatedPayload = {
1294
- Status: 'Active',
1295
- UpdatedById: loginUser.UserId,
1296
- UpdatedAt: new Date(),
1297
- };
1298
- await Group._GroupPrivilegeRepo.update(
1299
- updatedPayload,
1300
- {
1301
- where: {
1302
- GroupCode,
1303
- PrivilegeCode,
1304
- },
1305
- transaction: dbTransaction,
1306
- },
1307
- );
1308
-
1309
- //Set updated GroupPrivilege as EntityValueAfter
1310
- entityValueAfter = {
1311
- GroupCode: groupPrivilege.GroupCode,
1312
- PrivilegeCode: groupPrivilege.PrivilegeCode,
1313
- Status: updatedPayload.Status,
1314
- CreatedById: groupPrivilege.CreatedById,
1315
- CreatedAt: groupPrivilege.CreatedAt,
1316
- UpdatedById: updatedPayload.UpdatedById,
1317
- UpdatedAt: updatedPayload.UpdatedAt,
1318
- };
1319
-
1320
- //Instantiate new activity from Activity class
1321
- action = ActionEnum.UPDATE;
1322
- description = 'Update Group Privilege';
1323
- entityId = groupPrivilege.GroupPrivilegeId;
1324
- } else {
1325
- //If GroupPrivilege record does not exist, do the following:
1326
- //Initialise empty GroupPrivilege.
1327
- const newGroupPrivilege = await GroupPrivilege.init(dbTransaction);
1328
- //Set the attributes
1329
- newGroupPrivilege.setAttributes({
1330
- GroupCode,
1331
- PrivilegeCode,
1332
- Status: 'Active',
1333
- CreatedById: loginUser.UserId,
1334
- CreatedAt: new Date(),
1335
- UpdatedById: loginUser.UserId,
1336
- UpdatedAt: new Date(),
1337
- });
1338
-
1339
- // Set EntityValueAfter to above instance.
1340
- entityValueAfter = {
1341
- GroupCode: newGroupPrivilege.GroupCode,
1342
- PrivilegeCode: newGroupPrivilege.PrivilegeCode,
1343
- Status: newGroupPrivilege.Status,
1344
- CreatedById: newGroupPrivilege.CreatedById,
1345
- CreatedAt: newGroupPrivilege.CreatedAt,
1346
- UpdatedById: newGroupPrivilege.UpdatedById,
1347
- UpdatedAt: newGroupPrivilege.UpdatedAt,
1348
- };
1349
-
1350
- //Call Group._GroupPrivilegesRepo.create
1351
- const groupPrivilege = await Group._GroupPrivilegeRepo.create(entityValueAfter, {
1352
- transaction: dbTransaction,
1353
- });
1354
- action = ActionEnum.ADD;
1355
- description = 'Create Group Privilege';
1356
- entityId = groupPrivilege.GroupPrivilegeId;
1357
- }
1358
-
1359
- //Instantiate new activity from Activity class, call createId() method, then set:
1360
- const activity = new Activity();
1361
- activity.ActivityId = activity.createId();
1362
- activity.Action = action;
1363
- activity.Description = description;
1364
- activity.EntityType = 'GroupPrivilege';
1365
- activity.EntityId = entityId;
1366
- activity.EntityValueBefore = JSON.stringify(entityValueBefore);
1367
- activity.EntityValueAfter = JSON.stringify(entityValueAfter);
1368
-
1369
- //Call new activity create method
1370
- await activity.create(loginUser.ObjectId, dbTransaction);
1371
- }
1372
-
1373
- return 'Successfully added.';
1374
- } catch (error) {
1375
- throw error;
1376
- }
1377
- }
1378
-
1379
- public static async deleteGroupPrivilege(
1380
- loginUser: LoginUser,
1381
- dbTransaction: any,
1382
- GroupCode: string,
1383
- PrivilegeCodes: string[],
1384
- ) {
1385
- try {
1386
- // Part 1: Privilege Checking
1387
- const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
1388
- const isPrivileged = await loginUser.checkPrivileges(
1389
- systemCode,
1390
- 'GROUP_PRIVILEGE_DELETE',
1391
- );
1392
-
1393
- if (!isPrivileged) {
1394
- throw new ClassError(
1395
- 'Group',
1396
- 'GroupErrMsg06',
1397
- 'You do not have the privilege to delete group privileges',
1398
- );
1399
- }
1400
-
1401
- // Part 2: Validation, Create and Record Activity
1402
- // For each Params.PrivilegesCodes.
1403
- for (const PrivilegeCode of PrivilegeCodes) {
1404
- //Check whether the record exist in database by calling Group._GroupPrivilegeRepo.findOne
1405
- const groupPrivilege = await Group._GroupPrivilegeRepo.findOne({
1406
- where: {
1407
- GroupCode,
1408
- PrivilegeCode,
1409
- },
1410
- transaction: dbTransaction,
1411
- });
1412
-
1413
- //If the record does not exist, throw a new ClassError
1414
- if (!groupPrivilege) {
1415
- throw new ClassError(
1416
- 'Group',
1417
- 'GroupErrMsg14',
1418
- 'GroupPrivilege not found.',
1419
- );
1420
- }
1421
-
1422
- //Set the EntityValueBefore to the GroupPrivilegesValue from step 1.c.
1423
- const entityValueBefore = {
1424
- GroupCode: groupPrivilege.GroupCode,
1425
- PrivilegeCode: groupPrivilege.PrivilegeCode,
1426
- Status: groupPrivilege.Status,
1427
- CreatedById: groupPrivilege.CreatedById,
1428
- CreatedAt: groupPrivilege.CreatedAt,
1429
- UpdatedById: groupPrivilege.UpdatedById,
1430
- UpdatedAt: groupPrivilege.UpdatedAt,
1431
- };
1432
-
1433
- //Call Group._GroupPrivilegeRepo.delete
1434
- await Group._GroupPrivilegeRepo.delete(
1435
- GroupCode,
1436
- PrivilegeCode,
1437
- dbTransaction,
1438
- );
1439
- // Instantiate new activity from Activity class, call createId() method, then set:
1440
- const activity = new Activity();
1441
- activity.ActivityId = activity.createId();
1442
- activity.Action = ActionEnum.DELETE;
1443
- activity.Description = 'DELETE Group Privilege';
1444
- activity.EntityType = 'GroupPrivilege';
1445
- activity.EntityId = groupPrivilege.GroupPrivilegeId.toString();
1446
- activity.EntityValueBefore = JSON.stringify(entityValueBefore);
1447
- activity.EntityValueAfter = JSON.stringify({});
1448
- //Call new activity create method
1449
- await activity.create(loginUser.ObjectId, dbTransaction);
1450
- }
1451
- return 'Successfully deleted.';
1452
- } catch (error) {
1453
- throw error;
1454
- }
1455
- }
1456
- }
1
+ import { ClassError, ObjectBase } from '@tomei/general';
2
+ import { GroupRepository } from './group.repository';
3
+ import { IGroupAttr } from '../../interfaces/group.interface';
4
+ import { GroupTypeEnum } from 'enum';
5
+ import { LoginUser } from '../login-user/login-user';
6
+ import { IGroupSearchAttr } from '../../interfaces/group-search-attr.interface';
7
+ import { ApplicationConfig } from '@tomei/config';
8
+ import { Op } from 'sequelize';
9
+ import { ActionEnum, Activity } from '@tomei/activity-history';
10
+ import { GroupSystemAccessRepository } from '../group-system-access/group-system-access.repository';
11
+ import SystemModel from '../../models/system.entity';
12
+ import { GroupSystemAccess } from '../group-system-access';
13
+ import { RedisService } from '../../redis-client/redis.service';
14
+ import SystemPrivilegeModel from '../../models/system-privilege.entity';
15
+ import { GroupPrivilegeRepository } from '../group-privilege/group-privilege.repository';
16
+ import { SystemPrivilege } from '../system-privilege/system-privilege';
17
+ import GroupPrivilegeModel from '../../models/group-privilege.entity';
18
+ import { GroupObjectPrivilegeRepository } from '../group-object-privilege/group-object-privilege.repository';
19
+ import { GroupObjectPrivilege } from '../group-object-privilege/group-object-privilege';
20
+ import { GroupPrivilege } from '../group-privilege/group-privilege';
21
+
22
+ export class Group extends ObjectBase {
23
+ ObjectId: string;
24
+ ObjectName: string;
25
+ TableName: 'sso_Group';
26
+ ObjectType = 'Group';
27
+
28
+ Name: string;
29
+ Description: string;
30
+ Type: GroupTypeEnum;
31
+ ParentGroupCode: string;
32
+ InheritParentPrivilegeYN: string;
33
+ InheritParentSystemAccessYN: string;
34
+ Status: string;
35
+ ParentGroup?: any;
36
+ private _CreatedById: number;
37
+ private _CreatedAt: Date;
38
+ private _UpdatedById: number;
39
+ private _UpdatedAt: Date;
40
+ private static _Repo = new GroupRepository();
41
+ private static _GroupSystemAccessRepo = new GroupSystemAccessRepository();
42
+ private static _GroupPrivilegeRepo = new GroupPrivilegeRepository();
43
+ private static _GroupObjectPrivilegeRepo =
44
+ new GroupObjectPrivilegeRepository();
45
+ private static _RedisService: RedisService;
46
+ get GroupCode(): string {
47
+ return this.ObjectId;
48
+ }
49
+
50
+ set GroupCode(value: string) {
51
+ this.ObjectId = value;
52
+ }
53
+
54
+ get CreatedById(): number {
55
+ return this._CreatedById;
56
+ }
57
+
58
+ get CreatedAt(): Date {
59
+ return this._CreatedAt;
60
+ }
61
+
62
+ get UpdatedById(): number {
63
+ return this._UpdatedById;
64
+ }
65
+
66
+ get UpdatedAt(): Date {
67
+ return this._UpdatedAt;
68
+ }
69
+
70
+ private constructor(groupAttr?: IGroupAttr) {
71
+ super();
72
+ if (groupAttr) {
73
+ this.GroupCode = groupAttr.GroupCode;
74
+ this.Name = groupAttr.Name;
75
+ this.Description = groupAttr?.Description;
76
+ this.Type = groupAttr?.Type;
77
+ this.ParentGroupCode = groupAttr?.ParentGroupCode;
78
+ this.InheritParentPrivilegeYN = groupAttr?.InheritParentPrivilegeYN;
79
+ this.InheritParentSystemAccessYN = groupAttr?.InheritParentSystemAccessYN;
80
+ this.Status = groupAttr?.Status;
81
+ this._CreatedById = groupAttr.CreatedById;
82
+ this._CreatedAt = groupAttr.CreatedAt;
83
+ this._UpdatedById = groupAttr.UpdatedById;
84
+ this._UpdatedAt = groupAttr.UpdatedAt;
85
+ }
86
+ }
87
+
88
+ public static async init(dbTransaction: any, GroupCode?: string) {
89
+ try {
90
+ Group._RedisService = await RedisService.init();
91
+ if (GroupCode) {
92
+ const group = await Group._Repo.findByPk(GroupCode, {
93
+ transaction: dbTransaction,
94
+ });
95
+ if (group) {
96
+ return new Group(group);
97
+ } else {
98
+ throw Error('Group not found');
99
+ }
100
+ }
101
+ return new Group();
102
+ } catch (error) {
103
+ throw new ClassError(
104
+ 'Group',
105
+ 'GroupErrMsg01',
106
+ 'Failed To Initialize Group',
107
+ );
108
+ }
109
+ }
110
+
111
+ public static async findAll(
112
+ page: number,
113
+ row: number,
114
+ dbTransaction: any,
115
+ loginUser: LoginUser,
116
+ search?: IGroupSearchAttr,
117
+ ) {
118
+ //This method will list all group based on the query params.
119
+ //Part 1: Privilege Checking
120
+ const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
121
+ const isPrivileged = await loginUser.checkPrivileges(
122
+ systemCode,
123
+ 'GROUP_LIST',
124
+ );
125
+
126
+ if (!isPrivileged) {
127
+ throw new ClassError(
128
+ 'Group',
129
+ 'GroupErrMsg04',
130
+ 'User is not privileged to list group',
131
+ );
132
+ }
133
+
134
+ //Part 2: Retrieve listing
135
+ const queryObj: any = {};
136
+
137
+ let options: any = {
138
+ transaction: dbTransaction,
139
+ };
140
+
141
+ if (page && row) {
142
+ options = {
143
+ ...options,
144
+ limit: row,
145
+ offset: row * (page - 1),
146
+ order: [['CreatedAt', 'DESC']],
147
+ };
148
+ }
149
+
150
+ if (search) {
151
+ Object.entries(search).forEach(([key, value]) => {
152
+ queryObj[key] = {
153
+ [Op.substring]: value,
154
+ };
155
+ });
156
+
157
+ options = {
158
+ ...options,
159
+ where: queryObj,
160
+ };
161
+
162
+ const result = await Group._Repo.findAllWithPagination(options);
163
+
164
+ //Map the result to Group instance
165
+ return {
166
+ Count: result.count,
167
+ Groups: result.rows.map(
168
+ (group) => new Group(group.get({ plain: true })),
169
+ ),
170
+ };
171
+ }
172
+ }
173
+
174
+ public static async create(
175
+ loginUser: LoginUser,
176
+ dbTransaction: any,
177
+ group: Group,
178
+ ) {
179
+ try {
180
+ //Part 1: Privilege Checking
181
+ const systemCode =
182
+ ApplicationConfig.getComponentConfigValue('system-code');
183
+ const isPrivileged = await loginUser.checkPrivileges(
184
+ systemCode,
185
+ 'GROUP_CREATE',
186
+ );
187
+ if (!isPrivileged) {
188
+ throw new Error('You do not have permission to create group');
189
+ }
190
+
191
+ //Part 2: Validation
192
+ if (!group.GroupCode) {
193
+ throw new ClassError(
194
+ 'Group',
195
+ 'GroupErrMsg02',
196
+ 'Group Code is required',
197
+ );
198
+ }
199
+
200
+ if (!group.Name) {
201
+ throw new ClassError(
202
+ 'Group',
203
+ 'GroupErrMsg02',
204
+ 'Group Name is required',
205
+ );
206
+ }
207
+
208
+ if (!group.Type) {
209
+ throw new ClassError(
210
+ 'Group',
211
+ 'GroupErrMsg02',
212
+ 'Group Type is required',
213
+ );
214
+ }
215
+
216
+ //Check if group code is unique
217
+ const existingGroupCode = await Group._Repo.findByPk(group.GroupCode, {
218
+ transaction: dbTransaction,
219
+ });
220
+
221
+ if (existingGroupCode) {
222
+ throw new ClassError(
223
+ 'Group',
224
+ 'GroupErrMsg03',
225
+ 'Duplicate GroupCode found.',
226
+ );
227
+ }
228
+
229
+ //Validate parent group code if passed. Call Group._Repo.findByPk
230
+ if (group.ParentGroupCode) {
231
+ const parentGroup = await Group._Repo.findByPk(group.ParentGroupCode, {
232
+ transaction: dbTransaction,
233
+ });
234
+
235
+ if (!parentGroup) {
236
+ throw new ClassError(
237
+ 'Group',
238
+ 'GroupErrMsg04',
239
+ 'ParentGroupCode is not found.',
240
+ );
241
+ }
242
+
243
+ //If Params.group.GroupCode = Params.group?.ParentGroupCode, throw new ClassError
244
+ if (group.GroupCode === group.ParentGroupCode) {
245
+ throw new ClassError(
246
+ 'Group',
247
+ 'GroupErrMsg05',
248
+ 'GroupCode and ParentGroupCode cannot be the same.',
249
+ );
250
+ }
251
+ }
252
+
253
+ //Part 3: Create Group
254
+ //Initialise new Group instance and populate
255
+ const newGroup = new Group(group);
256
+ newGroup.ObjectId = group.GroupCode;
257
+ newGroup.Name = group.Name;
258
+ newGroup.Type = group.Type;
259
+ newGroup.Description = group.Description;
260
+ newGroup.ParentGroupCode = group.ParentGroupCode;
261
+ newGroup.InheritParentPrivilegeYN = group.InheritParentPrivilegeYN;
262
+ newGroup.InheritParentSystemAccessYN = group.InheritParentSystemAccessYN;
263
+ newGroup.Status = 'Active';
264
+ newGroup._CreatedById = loginUser.UserId;
265
+ newGroup._UpdatedById = loginUser.UserId;
266
+
267
+ //Call Group._Repo create method
268
+ const entityGroupAfter = {
269
+ GroupCode: newGroup.ObjectId,
270
+ Name: newGroup.Name,
271
+ Type: newGroup.Type,
272
+ Description: newGroup.Description,
273
+ ParentGroupCode: newGroup.ParentGroupCode,
274
+ InheritParentPrivilegeYN: newGroup.InheritParentPrivilegeYN,
275
+ InheritParentSystemAccessYN: newGroup.InheritParentSystemAccessYN,
276
+ Status: newGroup.Status,
277
+ CreatedById: newGroup._CreatedById,
278
+ UpdatedById: newGroup._UpdatedById,
279
+ CreatedAt: newGroup._CreatedAt,
280
+ UpdatedAt: newGroup._UpdatedAt,
281
+ };
282
+
283
+ await Group._Repo.create(entityGroupAfter, {
284
+ transaction: dbTransaction,
285
+ });
286
+
287
+ //Part 4: Record Create Group Activity and return newGroup
288
+
289
+ const entityValueBefore = {};
290
+
291
+ //Instantiate new activity
292
+ const activity = new Activity();
293
+ activity.ActivityId = activity.createId();
294
+ activity.Action = ActionEnum.ADD;
295
+ activity.Description = 'Create Group';
296
+ activity.EntityType = 'Group';
297
+ activity.EntityId = newGroup.ObjectId;
298
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
299
+ activity.EntityValueAfter = JSON.stringify(entityGroupAfter);
300
+
301
+ //Call Activity.create method
302
+ await activity.create(loginUser.ObjectId, dbTransaction);
303
+
304
+ return newGroup;
305
+ } catch (error) {
306
+ throw error;
307
+ }
308
+ }
309
+
310
+ protected static async checkDuplicateGroupCode(
311
+ dbTransaction: any,
312
+ GroupCode,
313
+ ) {
314
+ const isGroupCodeExist = await Group._Repo.findOne({
315
+ where: { GroupCode },
316
+ transaction: dbTransaction,
317
+ });
318
+
319
+ if (isGroupCodeExist) {
320
+ throw new ClassError(
321
+ 'Group',
322
+ 'GroupErrMsg07',
323
+ 'GroupCode already exists.',
324
+ );
325
+ }
326
+ }
327
+
328
+ public async update(
329
+ loginUser: LoginUser,
330
+ dbTransaction: any,
331
+ group: {
332
+ GroupCode: string;
333
+ NewGroupCode?: string;
334
+ Name?: string;
335
+ Description?: string;
336
+ Type?: GroupTypeEnum;
337
+ ParentGroupCode?: string;
338
+ InheritParentPrivilegeYN?: string;
339
+ InheritParentSystemAccessYN?: string;
340
+ Status?: string;
341
+ },
342
+ ) {
343
+ //Part 1: Privilege Checking
344
+ const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
345
+ const isPrivileged = await loginUser.checkPrivileges(
346
+ systemCode,
347
+ 'GROUP_UPDATE',
348
+ );
349
+
350
+ if (!isPrivileged) {
351
+ throw new ClassError(
352
+ 'Group',
353
+ 'GroupErrMsg06',
354
+ 'You do not have the privilege to update Group',
355
+ );
356
+ }
357
+ try {
358
+ const currentGroup = await Group.init(dbTransaction, group.GroupCode);
359
+ if (group.NewGroupCode) {
360
+ await Group.checkDuplicateGroupCode(dbTransaction, group.NewGroupCode);
361
+ }
362
+
363
+ if (
364
+ group.ParentGroupCode &&
365
+ currentGroup.ParentGroupCode !== group.ParentGroupCode
366
+ ) {
367
+ const parentGroup = await Group.init(
368
+ dbTransaction,
369
+ group.ParentGroupCode,
370
+ );
371
+ if (!parentGroup) {
372
+ throw new ClassError(
373
+ 'Group',
374
+ 'GroupErrMsg08',
375
+ 'Parent Group Code not found',
376
+ );
377
+ }
378
+ }
379
+
380
+ const entityValueBefore = {
381
+ GroupCode: currentGroup.GroupCode,
382
+ Name: currentGroup.Name,
383
+ Type: currentGroup.Type,
384
+ Description: currentGroup.Description,
385
+ ParentGroupCode: currentGroup.ParentGroupCode,
386
+ InheritParentPrivilegeYN: currentGroup.InheritParentPrivilegeYN,
387
+ InheritParentSystemAccessYN: currentGroup.InheritParentSystemAccessYN,
388
+ Status: currentGroup.Status,
389
+ CreatedById: currentGroup._CreatedById,
390
+ UpdatedById: currentGroup._UpdatedById,
391
+ CreatedAt: currentGroup._CreatedAt,
392
+ UpdatedAt: currentGroup._UpdatedAt,
393
+ };
394
+
395
+ currentGroup.GroupCode = group?.NewGroupCode || currentGroup.GroupCode;
396
+ currentGroup.Name = group?.Name || currentGroup.Name;
397
+ currentGroup.Type = group?.Type || currentGroup.Type;
398
+ currentGroup.Description = group?.Description || currentGroup.Description;
399
+ currentGroup.ParentGroupCode =
400
+ group?.ParentGroupCode || currentGroup.ParentGroupCode;
401
+ currentGroup.InheritParentPrivilegeYN =
402
+ group?.InheritParentPrivilegeYN ||
403
+ currentGroup.InheritParentPrivilegeYN;
404
+ currentGroup.InheritParentSystemAccessYN =
405
+ group?.InheritParentSystemAccessYN ||
406
+ currentGroup.InheritParentSystemAccessYN;
407
+ currentGroup.Status = group?.Status || currentGroup.Status;
408
+ currentGroup._UpdatedById = loginUser.UserId;
409
+ currentGroup._UpdatedAt = new Date();
410
+
411
+ await Group._Repo.update(
412
+ {
413
+ GroupCode: currentGroup.GroupCode,
414
+ Name: currentGroup.Name,
415
+ Type: currentGroup.Type,
416
+ Description: currentGroup.Description,
417
+ ParentGroupCode: currentGroup.ParentGroupCode,
418
+ InheritParentPrivilegeYN: currentGroup.InheritParentPrivilegeYN,
419
+ InheritParentSystemAccessYN: currentGroup.InheritParentSystemAccessYN,
420
+ Status: currentGroup.Status,
421
+ UpdatedById: currentGroup._UpdatedById,
422
+ UpdatedAt: currentGroup._UpdatedAt,
423
+ },
424
+ {
425
+ where: {
426
+ GroupCode: group.GroupCode,
427
+ },
428
+ transaction: dbTransaction,
429
+ },
430
+ );
431
+
432
+ const entityValueAfter = {
433
+ GroupCode: currentGroup.GroupCode,
434
+ Name: currentGroup.Name,
435
+ Type: currentGroup.Type,
436
+ Description: currentGroup.Description,
437
+ ParentGroupCode: currentGroup.ParentGroupCode,
438
+ InheritParentPrivilegeYN: currentGroup.InheritParentPrivilegeYN,
439
+ InheritParentSystemAccessYN: currentGroup.InheritParentSystemAccessYN,
440
+ Status: currentGroup.Status,
441
+ CreatedById: currentGroup._CreatedById,
442
+ UpdatedById: currentGroup._UpdatedById,
443
+ CreatedAt: currentGroup._CreatedAt,
444
+ UpdatedAt: currentGroup._UpdatedAt,
445
+ };
446
+
447
+ const activity = new Activity();
448
+ activity.ActivityId = activity.createId();
449
+ activity.Action = ActionEnum.UPDATE;
450
+ activity.Description = `Update Group ${group.Type}`;
451
+ activity.EntityType = 'Group';
452
+ activity.EntityId = group.GroupCode;
453
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
454
+ activity.EntityValueAfter = JSON.stringify(entityValueAfter);
455
+ await activity.create(loginUser.ObjectId, dbTransaction);
456
+
457
+ return currentGroup;
458
+ } catch (error) {
459
+ throw error;
460
+ }
461
+ }
462
+
463
+ public static async getSystemAccesses(
464
+ loginUser: LoginUser,
465
+ dbTransaction: any,
466
+ GroupCode: string,
467
+ Page: number,
468
+ Rows: number,
469
+ Search: {
470
+ SystemCode?: string;
471
+ Status?: string;
472
+ },
473
+ ) {
474
+ // Part 1: Privilege Checking
475
+ const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
476
+ const isPrivileged = await loginUser.checkPrivileges(
477
+ systemCode,
478
+ 'SYSTEM_ACCESS_VIEW',
479
+ );
480
+
481
+ if (!isPrivileged) {
482
+ throw new ClassError(
483
+ 'Group',
484
+ 'GroupErrMsg06',
485
+ 'You do not have the privilege to view system access',
486
+ );
487
+ }
488
+
489
+ try {
490
+ // Part 2: Validation
491
+ await Group.init(dbTransaction, GroupCode);
492
+
493
+ // Part 3: Retrieve System Access and returns
494
+ const queryObj: any = { GroupCode: GroupCode };
495
+
496
+ if (Search) {
497
+ Object.entries(Search).forEach(([key, value]) => {
498
+ queryObj[key] = value;
499
+ });
500
+ }
501
+
502
+ let options: any = {
503
+ where: queryObj,
504
+ distinct: true,
505
+ transaction: dbTransaction,
506
+ };
507
+
508
+ if (Page && Rows) {
509
+ options = {
510
+ ...options,
511
+ limit: Rows,
512
+ offset: Rows * (Page - 1),
513
+ order: [['CreatedAt', 'DESC']],
514
+ };
515
+ }
516
+
517
+ const systemAccess = await Group._GroupSystemAccessRepo.findAndCountAll(
518
+ options,
519
+ );
520
+ return systemAccess;
521
+ } catch (error) {
522
+ return error;
523
+ }
524
+ }
525
+
526
+ private static async getInheritedSystemAccess(
527
+ dbTransaction: any,
528
+ group: Group,
529
+ ): Promise<any[]> {
530
+ const options: any = {
531
+ where: {
532
+ GroupCode: group.GroupCode,
533
+ Status: 'Active',
534
+ },
535
+ include: [
536
+ {
537
+ model: SystemModel,
538
+ },
539
+ ],
540
+ transaction: dbTransaction,
541
+ };
542
+ let systemAccess = await Group._GroupSystemAccessRepo.findAll(options);
543
+
544
+ if (group.InheritParentSystemAccessYN === 'Y' && group.ParentGroupCode) {
545
+ const parentGroup = await Group.init(
546
+ dbTransaction,
547
+ group.ParentGroupCode,
548
+ );
549
+ const parentSystemAccesses = await this.getInheritedSystemAccess(
550
+ dbTransaction,
551
+ parentGroup,
552
+ );
553
+ systemAccess = systemAccess.concat(parentSystemAccesses);
554
+ }
555
+ return systemAccess;
556
+ }
557
+
558
+ public static async getParentSystemAccesses(
559
+ loginUser: LoginUser,
560
+ dbTransaction: any,
561
+ GroupCode: string,
562
+ ) {
563
+ // Part 1: Privilege Checking
564
+ const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
565
+ const isPrivileged = await loginUser.checkPrivileges(
566
+ systemCode,
567
+ 'SYSTEM_ACCESS_VIEW',
568
+ );
569
+
570
+ if (!isPrivileged) {
571
+ throw new ClassError(
572
+ 'Group',
573
+ 'GroupErrMsg06',
574
+ 'You do not have the privilege to view system access',
575
+ );
576
+ }
577
+
578
+ try {
579
+ const group = await Group.init(dbTransaction, GroupCode);
580
+ if (group.InheritParentSystemAccessYN !== 'Y' || !group.ParentGroupCode) {
581
+ return [];
582
+ } else {
583
+ const parentGroup = await Group.init(
584
+ dbTransaction,
585
+ group.ParentGroupCode,
586
+ );
587
+ const inheritSystemAccess = await Group.getInheritedSystemAccess(
588
+ dbTransaction,
589
+ parentGroup,
590
+ );
591
+ return inheritSystemAccess;
592
+ }
593
+ } catch (error) {
594
+ throw error;
595
+ }
596
+ }
597
+
598
+ public static async addSystemAccesses(
599
+ loginUser: LoginUser,
600
+ dbTransaction: any,
601
+ GroupCode: string,
602
+ SystemCodes: string[],
603
+ ) {
604
+ // Part 1: Privilege Checking
605
+ const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
606
+ const isPrivileged = await loginUser.checkPrivileges(
607
+ systemCode,
608
+ 'SYSTEM_ACCESS_CREATE',
609
+ );
610
+
611
+ if (!isPrivileged) {
612
+ throw new ClassError(
613
+ 'Group',
614
+ 'GroupErrMsg07',
615
+ 'You do not have the privilege to create system access',
616
+ );
617
+ }
618
+
619
+ try {
620
+ if (SystemCodes.length > 0) {
621
+ for (const element of SystemCodes) {
622
+ const CurrentGroupSystemAccess = await Group.getSystemAccesses(
623
+ loginUser,
624
+ dbTransaction,
625
+ GroupCode,
626
+ 1,
627
+ Number.MAX_SAFE_INTEGER,
628
+ { SystemCode: element },
629
+ );
630
+
631
+ if (CurrentGroupSystemAccess?.count > 0) {
632
+ throw new ClassError(
633
+ 'Group',
634
+ 'GroupErrMsg08',
635
+ 'System access already exists',
636
+ );
637
+ }
638
+
639
+ const groupSystemAccess = await GroupSystemAccess.init(dbTransaction);
640
+ groupSystemAccess.createId();
641
+ groupSystemAccess.GroupCode = GroupCode;
642
+ groupSystemAccess.SystemCode = element;
643
+ groupSystemAccess.Status = 'Active';
644
+ groupSystemAccess.CreatedById = +loginUser.ObjectId;
645
+ groupSystemAccess.CreatedAt = new Date();
646
+ groupSystemAccess.UpdatedById = +loginUser.ObjectId;
647
+ groupSystemAccess.UpdatedAt = new Date();
648
+
649
+ const EntityValueAfter = {
650
+ GroupCode: groupSystemAccess.GroupCode,
651
+ SystemCode: groupSystemAccess.SystemCode,
652
+ Status: groupSystemAccess.Status,
653
+ CreatedById: groupSystemAccess.CreatedById,
654
+ CreatedAt: groupSystemAccess.CreatedAt,
655
+ UpdatedById: groupSystemAccess.UpdatedById,
656
+ UpdatedAt: groupSystemAccess.UpdatedAt,
657
+ };
658
+
659
+ const systemAccess = await Group._GroupSystemAccessRepo.create(
660
+ EntityValueAfter,
661
+ {
662
+ transaction: dbTransaction,
663
+ },
664
+ );
665
+
666
+ const activity = new Activity();
667
+ activity.ActivityId = activity.createId();
668
+ activity.Action = ActionEnum.ADD;
669
+ activity.Description = 'Create Group System Access';
670
+ activity.EntityType = 'GroupSystemAccess';
671
+ activity.EntityId = systemAccess.GroupSystemAccessId?.toString();
672
+ activity.EntityValueBefore = JSON.stringify({});
673
+ activity.EntityValueAfter = JSON.stringify(EntityValueAfter);
674
+
675
+ await activity.create(loginUser.ObjectId, dbTransaction);
676
+ }
677
+
678
+ return { Message: 'Successfully added.' };
679
+ }
680
+ } catch (error) {
681
+ throw error;
682
+ }
683
+ }
684
+
685
+ public static async deleteSystemAccess(
686
+ loginUser: LoginUser,
687
+ dbTransaction: any,
688
+ GroupCode: string,
689
+ SystemCode: string,
690
+ ) {
691
+ // Part 1: Privilege Checking
692
+ const systemCode = ApplicationConfig.getComponentConfigValue('system-code');
693
+ const isPrivileged = await loginUser.checkPrivileges(
694
+ systemCode,
695
+ 'SYSTEM_ACCESS_DELETE',
696
+ );
697
+
698
+ if (!isPrivileged) {
699
+ throw new ClassError(
700
+ 'Group',
701
+ 'GroupErrMsg08',
702
+ 'You do not have the privilege to delete system access',
703
+ );
704
+ }
705
+
706
+ try {
707
+ const currentGroupSystemAccess = await Group.getSystemAccesses(
708
+ loginUser,
709
+ dbTransaction,
710
+ GroupCode,
711
+ 1,
712
+ Number.MAX_SAFE_INTEGER,
713
+ { SystemCode: SystemCode },
714
+ );
715
+
716
+ if (currentGroupSystemAccess.count < 1) {
717
+ throw new ClassError(
718
+ 'Group',
719
+ 'GroupErrMsg10',
720
+ 'No associated system access found.',
721
+ );
722
+ }
723
+
724
+ await Group._GroupSystemAccessRepo.delete(
725
+ GroupCode,
726
+ SystemCode,
727
+ dbTransaction,
728
+ );
729
+
730
+ const EntityValueBefore = {
731
+ GroupCode: currentGroupSystemAccess?.rows[0]?.GroupCode,
732
+ SystemCode: currentGroupSystemAccess?.rows[0]?.SystemCode,
733
+ Status: currentGroupSystemAccess?.rows[0]?.Status,
734
+ CreatedById: currentGroupSystemAccess?.rows[0]?.CreatedById,
735
+ CreatedAt: currentGroupSystemAccess?.rows[0]?.CreatedAt,
736
+ UpdatedById: currentGroupSystemAccess?.rows[0]?.UpdatedById,
737
+ UpdatedAt: currentGroupSystemAccess?.rows[0]?.UpdatedAt,
738
+ };
739
+
740
+ const activity = new Activity();
741
+ activity.ActivityId = activity.createId();
742
+ activity.Action = ActionEnum.DELETE;
743
+ activity.Description = 'Delete Group System Access';
744
+ activity.EntityType = 'GroupSystemAccess';
745
+ activity.EntityId =
746
+ currentGroupSystemAccess?.rows[0]?.GroupSystemAccessId?.toString();
747
+ activity.EntityValueBefore = JSON.stringify(EntityValueBefore);
748
+ activity.EntityValueAfter = JSON.stringify({});
749
+
750
+ await activity.create(loginUser.ObjectId, dbTransaction);
751
+
752
+ return { Message: 'System access removed.', SystemCode: SystemCode };
753
+ } catch (error) {
754
+ throw error;
755
+ }
756
+ }
757
+
758
+ public static async getSystemPrivileges(
759
+ loginUser: LoginUser,
760
+ dbTransaction: any,
761
+ GroupCode: string,
762
+ search?: {
763
+ SystemCode?: string;
764
+ Status?: string;
765
+ },
766
+ ) {
767
+ try {
768
+ //Part 1: Privilege Checking
769
+ const systemCode =
770
+ ApplicationConfig.getComponentConfigValue('system-code');
771
+ const isPrivileged = await loginUser.checkPrivileges(
772
+ systemCode,
773
+ 'GROUP_PRIVILEGE_VIEW',
774
+ );
775
+
776
+ if (!isPrivileged) {
777
+ throw new ClassError(
778
+ 'Group',
779
+ 'GroupErrMsg11',
780
+ 'You do not have the privilege to view group privileges',
781
+ );
782
+ }
783
+
784
+ //Set group to instantiation of existing Group
785
+ await Group.init(dbTransaction, GroupCode);
786
+
787
+ //Part 3: Retrieve Group Own Privilege
788
+ //Retrieve group data and it's privileged by calling Group._Repo.findAll
789
+ let where: any = {
790
+ GroupCode,
791
+ };
792
+
793
+ let systemWhere: any = {};
794
+
795
+ if (search) {
796
+ if (search.Status) {
797
+ where = {
798
+ ...where,
799
+ Status: search.Status,
800
+ };
801
+ }
802
+
803
+ if (search.SystemCode) {
804
+ systemWhere = {
805
+ SystemCode: {
806
+ [Op.substring]: search.SystemCode,
807
+ },
808
+ };
809
+ }
810
+ }
811
+
812
+ const groupOwnPrivileges = await Group._GroupPrivilegeRepo.findAll({
813
+ where,
814
+ include: [
815
+ {
816
+ model: SystemPrivilegeModel,
817
+ where: systemWhere,
818
+ },
819
+ ],
820
+ transaction: dbTransaction,
821
+ });
822
+
823
+ //Create variable called privileges and Map the SystemPrivilege data retrieved from 3.1 into SystemPrivilege object and push it to the privileges variables
824
+ const privileges: SystemPrivilege[] = [];
825
+
826
+ for (const groupPrivilege of groupOwnPrivileges) {
827
+ const systemPrivilege = await SystemPrivilege.init(dbTransaction);
828
+ systemPrivilege.setAttributes(
829
+ groupPrivilege.Privilege.get({ plain: true }),
830
+ );
831
+ privileges.push(systemPrivilege);
832
+ }
833
+
834
+ return privileges;
835
+ } catch (error) {
836
+ throw error;
837
+ }
838
+ }
839
+
840
+ public static async getInheritedSystemPrivileges(
841
+ dbTransaction: any,
842
+ GroupCode: string,
843
+ search?: {
844
+ SystemCode?: string;
845
+ Status?: string;
846
+ PrivilegeCode?: string;
847
+ },
848
+ ): Promise<SystemPrivilege[]> {
849
+ try {
850
+ //Retrieve group data and it's privileges by calling Group._Repo.findAll
851
+ const where: any = {
852
+ GroupCode,
853
+ };
854
+
855
+ let groupPrivilegeWhere: any = {};
856
+ let systemPrivilegeWhere: any = {};
857
+
858
+ if (search) {
859
+ if (search.Status) {
860
+ groupPrivilegeWhere = {
861
+ Status: search.Status,
862
+ };
863
+ }
864
+
865
+ if (search.SystemCode) {
866
+ systemPrivilegeWhere = {
867
+ SystemCode: {
868
+ [Op.substring]: search.SystemCode,
869
+ },
870
+ };
871
+ }
872
+ }
873
+ const group = await Group._Repo.findOne({
874
+ where: where,
875
+ include: [
876
+ {
877
+ model: GroupPrivilegeModel,
878
+ where: groupPrivilegeWhere,
879
+ separate: true,
880
+ include: [
881
+ {
882
+ model: SystemPrivilegeModel,
883
+ where: systemPrivilegeWhere,
884
+ },
885
+ ],
886
+ },
887
+ ],
888
+ transaction: dbTransaction,
889
+ });
890
+
891
+ //Retrieve group object privileges by calling LoginUser._GroupObjectPrivilegeRepo.findAll
892
+ const objectWhere: any = {
893
+ GroupCode,
894
+ };
895
+ const systemWhere: any = {};
896
+ if (search) {
897
+ Object.entries(search).forEach(([key, value]) => {
898
+ if (key === 'SystemCode') {
899
+ systemWhere[key] = {
900
+ [Op.substring]: value,
901
+ };
902
+ } else {
903
+ objectWhere[key] = {
904
+ [Op.substring]: value,
905
+ };
906
+ }
907
+ });
908
+ }
909
+ const groupObjectPrivileges =
910
+ await Group._GroupObjectPrivilegeRepo.findAll({
911
+ where: objectWhere,
912
+ include: [
913
+ {
914
+ model: SystemPrivilegeModel,
915
+ where: systemWhere,
916
+ },
917
+ ],
918
+ transaction: dbTransaction,
919
+ });
920
+
921
+ //Map to SystemPrivilege object
922
+ let privileges: SystemPrivilege[] = [];
923
+ for (const groupPrivilege of group.GroupPrivileges) {
924
+ const systemPrivilege = await SystemPrivilege.init(dbTransaction);
925
+ systemPrivilege.setAttributes(
926
+ groupPrivilege.Privilege.get({ plain: true }),
927
+ );
928
+ privileges.push(systemPrivilege);
929
+ }
930
+
931
+ for (const groupObjectPrivilege of groupObjectPrivileges) {
932
+ const systemPrivilege = await SystemPrivilege.init(dbTransaction);
933
+ systemPrivilege.setAttributes(
934
+ groupObjectPrivilege.Privilege.get({ plain: true }),
935
+ );
936
+ privileges.push(systemPrivilege);
937
+ }
938
+
939
+ //Part 2: Retrieve Privileges Inherited from Parent Group
940
+ //if group data retrieved from 1.1 have InheritParentPrivilegeYN == "Y" and ParentGroupCode value is not empty. Call this method again
941
+ if (group.InheritParentPrivilegeYN === 'Y' && group.ParentGroupCode) {
942
+ const inheritedPrivileges = await Group.getInheritedSystemPrivileges(
943
+ dbTransaction,
944
+ group.ParentGroupCode,
945
+ search,
946
+ );
947
+ privileges = privileges.concat(inheritedPrivileges);
948
+ }
949
+
950
+ //format to make sure no duplicate
951
+ const uniquePrivileges = Array.from(
952
+ new Set(privileges.map((a) => a.PrivilegeCode)),
953
+ ).map((PrivilegeCode) => {
954
+ return privileges.find((a) => a.PrivilegeCode === PrivilegeCode);
955
+ });
956
+
957
+ return uniquePrivileges;
958
+ } catch (error) {
959
+ throw error;
960
+ }
961
+ }
962
+
963
+ public static async getParentSystemPrivileges(
964
+ loginUser: LoginUser,
965
+ dbTransaction: any,
966
+ GroupCode: string,
967
+ search?: {
968
+ SystemCode?: string;
969
+ Status?: string;
970
+ PrivilegeCode?: string;
971
+ },
972
+ ): Promise<SystemPrivilege[]> {
973
+ try {
974
+ //Part 1: Privilege Checking
975
+ const systemCode =
976
+ ApplicationConfig.getComponentConfigValue('system-code');
977
+ const isPrivileged = await loginUser.checkPrivileges(
978
+ systemCode,
979
+ 'GROUP_PRIVILEGE_VIEW',
980
+ );
981
+
982
+ if (!isPrivileged) {
983
+ throw new ClassError(
984
+ 'Group',
985
+ 'GroupErrMsg11',
986
+ 'You do not have the privilege to view group privileges',
987
+ );
988
+ }
989
+
990
+ //Part 2: Validation
991
+ //Set group to instantiation of existing Group
992
+ const group = await Group.init(dbTransaction, GroupCode);
993
+ //Check if group.InheritParentPrivilegeYN == "Y" and ParentGroupCode value is not empty. if no then return an empty array
994
+ if (group.InheritParentPrivilegeYN !== 'Y' || !group.ParentGroupCode) {
995
+ return [];
996
+ }
997
+
998
+ //Part 3: Retrieve Group Own Privilege
999
+ //Retrieve group data and it's privileged by calling Group.getIheritedSystemPrivileges
1000
+ const privileges = await Group.getInheritedSystemPrivileges(
1001
+ dbTransaction,
1002
+ group.ParentGroupCode,
1003
+ search,
1004
+ );
1005
+
1006
+ return privileges;
1007
+ } catch (error) {
1008
+ throw error;
1009
+ }
1010
+ }
1011
+
1012
+ public static async assignGroupObjectPrivilege(
1013
+ loginUser: LoginUser,
1014
+ dbTransaction: any,
1015
+ GroupCode: string,
1016
+ GroupObjectPrivileges: GroupObjectPrivilege[],
1017
+ ): Promise<string> {
1018
+ try {
1019
+ //Part 1: Privilege Checking
1020
+ const systemCode =
1021
+ ApplicationConfig.getComponentConfigValue('system-code');
1022
+ const isPrivileged = await loginUser.checkPrivileges(
1023
+ systemCode,
1024
+ 'GROUP_OBJECT_PRIVILEGE_ASSIGN',
1025
+ );
1026
+
1027
+ if (!isPrivileged) {
1028
+ throw new ClassError(
1029
+ 'Group',
1030
+ 'GroupErrMsg12',
1031
+ 'You do not have the privilege to assign group object privilege',
1032
+ );
1033
+ }
1034
+
1035
+ //Part 2: Validation
1036
+ //Initialise group with group init
1037
+ const group = await Group.init(dbTransaction, GroupCode);
1038
+ //Retrieve all group system access by calling Group.getSystemAccesses
1039
+ const groupSystemAccesses = await Group.getSystemAccesses(
1040
+ loginUser,
1041
+ dbTransaction,
1042
+ GroupCode,
1043
+ 1,
1044
+ Number.MAX_SAFE_INTEGER,
1045
+ {},
1046
+ );
1047
+
1048
+ //If Group.InheritParentSystemAccess == "Y" and Group.ParentGroupCode exist, initialise parent group
1049
+ let parentGroupSystemAccesses: any = {};
1050
+ if (group.InheritParentSystemAccessYN === 'Y' && group.ParentGroupCode) {
1051
+ //Retrieve all parent group system access by calling Group.getSystemAccesses
1052
+ parentGroupSystemAccesses = await Group.getSystemAccesses(
1053
+ loginUser,
1054
+ dbTransaction,
1055
+ group.ParentGroupCode,
1056
+ 1,
1057
+ Number.MAX_SAFE_INTEGER,
1058
+ {},
1059
+ );
1060
+ }
1061
+
1062
+ // For each Params.GroupObjectPrivileges.
1063
+ for (const groupObjectPrivilege of GroupObjectPrivileges) {
1064
+ //Initialise existing System privilege
1065
+ const systemPrivilege = await SystemPrivilege.init(
1066
+ dbTransaction,
1067
+ groupObjectPrivilege.PrivilegeCode,
1068
+ );
1069
+ //Check whether the system codes used by that privilege is exist inside the group system access
1070
+ const combinedSystemAccesses = {
1071
+ ...groupSystemAccesses.rows,
1072
+ ...parentGroupSystemAccesses.rows,
1073
+ };
1074
+ const systemAccess = combinedSystemAccesses.find(
1075
+ (systemAccess) =>
1076
+ systemAccess.SystemCode === systemPrivilege.SystemCode,
1077
+ );
1078
+ if (!systemAccess) {
1079
+ throw new ClassError(
1080
+ 'Group',
1081
+ 'GroupErrMsg13',
1082
+ 'Failed to assign privilege ' +
1083
+ groupObjectPrivilege.PrivilegeCode +
1084
+ ' due to non-existent system access.',
1085
+ );
1086
+ }
1087
+
1088
+ //Check whether the group object privilege already exist by using Group._GroupObjectPrivilegesRepo.findOne
1089
+ const groupObjectPrivilegeData =
1090
+ await Group._GroupObjectPrivilegeRepo.findOne({
1091
+ where: {
1092
+ GroupCode,
1093
+ PrivilegeCode: groupObjectPrivilege.PrivilegeCode,
1094
+ ObjectId: groupObjectPrivilege.ObjectId,
1095
+ ObjectType: groupObjectPrivilege.ObjectType,
1096
+ },
1097
+ transaction: dbTransaction,
1098
+ });
1099
+ //If GroupObjectPrivilege record exist. Skip this loop and proceed to the next privilege code
1100
+ if (groupObjectPrivilegeData) {
1101
+ continue;
1102
+ } else {
1103
+ //Call GroupObjectPrivilege.create
1104
+ await GroupObjectPrivilege.create(
1105
+ loginUser,
1106
+ dbTransaction,
1107
+ groupObjectPrivilege,
1108
+ );
1109
+ }
1110
+ }
1111
+
1112
+ return 'Successfully added.';
1113
+ } catch (error) {
1114
+ throw error;
1115
+ }
1116
+ }
1117
+
1118
+ public static async getGroubObjectPrivileges(
1119
+ loginUser: LoginUser,
1120
+ dbTransaction: any,
1121
+ GroupCode: string,
1122
+ search?: {
1123
+ PrivilegeCode?: string;
1124
+ ObjectType?: string;
1125
+ ObjectId?: string;
1126
+ SystemCode?: string;
1127
+ },
1128
+ ): Promise<SystemPrivilege[]> {
1129
+ try {
1130
+ // Part 1: Privilege Checking
1131
+ const systemCode =
1132
+ ApplicationConfig.getComponentConfigValue('system-code');
1133
+ const isPrivileged = await loginUser.checkPrivileges(
1134
+ systemCode,
1135
+ 'GROUP_PRIVILEGE_VIEW',
1136
+ );
1137
+
1138
+ if (!isPrivileged) {
1139
+ throw new ClassError(
1140
+ 'Group',
1141
+ 'GroupErrMsg11',
1142
+ 'You do not have the privilege to view group privileges',
1143
+ );
1144
+ }
1145
+
1146
+ // Part 2: Validation
1147
+ // Set group to instantiation of existing Group
1148
+ await Group.init(dbTransaction, GroupCode);
1149
+
1150
+ // Part 3: Retrieve Group Own Privilege
1151
+ // Retrieve group object privileges by calling LoginUser._GroupObjectPrivilegeRepo.findAll
1152
+ const where: any = {
1153
+ GroupCode,
1154
+ };
1155
+
1156
+ const systemWhere: any = {};
1157
+
1158
+ if (search) {
1159
+ Object.entries(search).forEach(([key, value]) => {
1160
+ if (key === 'SystemCode') {
1161
+ systemWhere[key] = {
1162
+ [Op.substring]: value,
1163
+ };
1164
+ } else {
1165
+ where[key] = {
1166
+ [Op.substring]: value,
1167
+ };
1168
+ }
1169
+ });
1170
+ }
1171
+
1172
+ const groupObjectPrivileges =
1173
+ await Group._GroupObjectPrivilegeRepo.findAll({
1174
+ where,
1175
+ include: [
1176
+ {
1177
+ model: SystemPrivilegeModel,
1178
+ where: systemWhere,
1179
+ },
1180
+ ],
1181
+ transaction: dbTransaction,
1182
+ });
1183
+ // Create variable called privileges and Map the SystemPrivilege data retrieved from 3.1 into SystemPrivilege object and push it to the privileges variables
1184
+ const privileges: SystemPrivilege[] = [];
1185
+ for (const groupObjectPrivilege of groupObjectPrivileges) {
1186
+ const systemPrivilege = await SystemPrivilege.init(dbTransaction);
1187
+ systemPrivilege.setAttributes(
1188
+ groupObjectPrivilege.Privilege.get({ plain: true }),
1189
+ );
1190
+ privileges.push(systemPrivilege);
1191
+ }
1192
+
1193
+ //Remove duplicate
1194
+ const uniquePrivileges = Array.from(
1195
+ new Set(privileges.map((a) => a.PrivilegeCode)),
1196
+ ).map((PrivilegeCode) => {
1197
+ return privileges.find((a) => a.PrivilegeCode === PrivilegeCode);
1198
+ });
1199
+
1200
+ // Create the result based on the spec on return then returns it.
1201
+ return uniquePrivileges;
1202
+ } catch (error) {
1203
+ throw error;
1204
+ }
1205
+ }
1206
+
1207
+ public static async assignGroupPrivileges(
1208
+ loginUser: LoginUser,
1209
+ dbTransaction: any,
1210
+ GroupCode: string,
1211
+ PrivilegeCodes: string[],
1212
+ ) {
1213
+ try {
1214
+ // Part 1: Privilege Checking
1215
+ const systemCode =
1216
+ ApplicationConfig.getComponentConfigValue('system-code');
1217
+ const isPrivileged = await loginUser.checkPrivileges(
1218
+ systemCode,
1219
+ 'GROUP_PRIVILEGE_ASSIGN',
1220
+ );
1221
+
1222
+ if (!isPrivileged) {
1223
+ throw new ClassError(
1224
+ 'Group',
1225
+ 'GroupErrMsg06',
1226
+ 'You do not have the privilege to assign group privileges',
1227
+ );
1228
+ }
1229
+
1230
+ // Part 2: Validation, Create and Record Activity
1231
+ // Initialise group with group init
1232
+
1233
+ const group = await Group.init(dbTransaction, GroupCode);
1234
+
1235
+ // Retrieve all group system access by calling Group.getSystemAccess
1236
+ const groupSystemAccesses = await Group.getSystemAccesses(
1237
+ loginUser,
1238
+ dbTransaction,
1239
+ GroupCode,
1240
+ 1,
1241
+ Number.MAX_SAFE_INTEGER,
1242
+ {},
1243
+ );
1244
+
1245
+ // If Group.InheritParentSystemAccess == "Y" and Group.ParentGroupCode exist
1246
+ let parentGroupSystemAccesses: any = {};
1247
+ if (group.InheritParentSystemAccessYN === 'Y' && group.ParentGroupCode) {
1248
+ // Retrieve all parent group system access by calling Group.getSystemAccess
1249
+ parentGroupSystemAccesses = await Group.getSystemAccesses(
1250
+ loginUser,
1251
+ dbTransaction,
1252
+ group.ParentGroupCode,
1253
+ 1,
1254
+ Number.MAX_SAFE_INTEGER,
1255
+ {},
1256
+ );
1257
+ }
1258
+
1259
+ // For each Params.PrivilegesCodes.
1260
+ for (const PrivilegeCode of PrivilegeCodes) {
1261
+ // Initialise existing System privilege by calling SystemPrivilege.init
1262
+ const systemPrivilege = await SystemPrivilege.init(
1263
+ dbTransaction,
1264
+ PrivilegeCode,
1265
+ );
1266
+ //Check whether the system codes used by that privilege is exist inside the group system access retrieved from step 2.2 & 2.4. If system code does not exist in group system access, throw a new ClassError by passing:
1267
+ // Classname: "Group"
1268
+ // MessageCode: "GroupErrMsg0X"
1269
+ // Message: "Failed to assign privilege <PrivilegeCode> due to non-existent system access."
1270
+ const combinedSystemAccesses = [
1271
+ ...groupSystemAccesses.rows,
1272
+ ...parentGroupSystemAccesses.rows,
1273
+ ];
1274
+ const systemAccess = combinedSystemAccesses.find(
1275
+ (systemAccess) =>
1276
+ systemAccess.SystemCode === systemPrivilege.SystemCode,
1277
+ );
1278
+ if (!systemAccess) {
1279
+ throw new ClassError(
1280
+ 'Group',
1281
+ 'GroupErrMsg13',
1282
+ 'Failed to assign privilege ' +
1283
+ PrivilegeCode +
1284
+ ' due to non-existent system access.',
1285
+ );
1286
+ }
1287
+
1288
+ //Check whether the group privilege exist by using Group._GroupPrivilegesRepo.findOne
1289
+ const groupPrivilege = await Group._GroupPrivilegeRepo.findOne({
1290
+ where: {
1291
+ GroupCode,
1292
+ PrivilegeCode,
1293
+ },
1294
+ transaction: dbTransaction,
1295
+ });
1296
+
1297
+ //If GroupPrivilege record exist and status is "Active". Skip this loop and proceed to the next privilege code
1298
+ if (groupPrivilege && groupPrivilege.Status === 'Active') {
1299
+ continue;
1300
+ }
1301
+
1302
+ let entityValueBefore = {};
1303
+ let entityValueAfter = {};
1304
+ let action = ActionEnum.ADD;
1305
+ let description = 'Create Group Privilege';
1306
+ let entityId = null;
1307
+ //If GroupPrivilege record exist and status is not "Active" do the following:
1308
+ if (groupPrivilege && groupPrivilege.Status !== 'Active') {
1309
+ //Set this GroupPrivilege entity as EntityValueBefore
1310
+ entityValueBefore = {
1311
+ GroupCode: groupPrivilege.GroupCode,
1312
+ PrivilegeCode: groupPrivilege.PrivilegeCode,
1313
+ Status: groupPrivilege.Status,
1314
+ CreatedById: groupPrivilege.CreatedById,
1315
+ CreatedAt: groupPrivilege.CreatedAt,
1316
+ UpdatedById: groupPrivilege.UpdatedById,
1317
+ UpdatedAt: groupPrivilege.UpdatedAt,
1318
+ };
1319
+
1320
+ //Update the status to active using Group._GroupPrivilegesRepo.Update.
1321
+ const updatedPayload = {
1322
+ Status: 'Active',
1323
+ UpdatedById: loginUser.UserId,
1324
+ UpdatedAt: new Date(),
1325
+ };
1326
+ await Group._GroupPrivilegeRepo.update(updatedPayload, {
1327
+ where: {
1328
+ GroupCode,
1329
+ PrivilegeCode,
1330
+ },
1331
+ transaction: dbTransaction,
1332
+ });
1333
+
1334
+ //Set updated GroupPrivilege as EntityValueAfter
1335
+ entityValueAfter = {
1336
+ GroupCode: groupPrivilege.GroupCode,
1337
+ PrivilegeCode: groupPrivilege.PrivilegeCode,
1338
+ Status: updatedPayload.Status,
1339
+ CreatedById: groupPrivilege.CreatedById,
1340
+ CreatedAt: groupPrivilege.CreatedAt,
1341
+ UpdatedById: updatedPayload.UpdatedById,
1342
+ UpdatedAt: updatedPayload.UpdatedAt,
1343
+ };
1344
+
1345
+ //Instantiate new activity from Activity class
1346
+ action = ActionEnum.UPDATE;
1347
+ description = 'Update Group Privilege';
1348
+ entityId = groupPrivilege.GroupPrivilegeId;
1349
+ } else {
1350
+ //If GroupPrivilege record does not exist, do the following:
1351
+ //Initialise empty GroupPrivilege.
1352
+ const newGroupPrivilege = await GroupPrivilege.init(dbTransaction);
1353
+ //Set the attributes
1354
+ newGroupPrivilege.setAttributes({
1355
+ GroupCode,
1356
+ PrivilegeCode,
1357
+ Status: 'Active',
1358
+ CreatedById: loginUser.UserId,
1359
+ CreatedAt: new Date(),
1360
+ UpdatedById: loginUser.UserId,
1361
+ UpdatedAt: new Date(),
1362
+ });
1363
+
1364
+ // Set EntityValueAfter to above instance.
1365
+ entityValueAfter = {
1366
+ GroupCode: newGroupPrivilege.GroupCode,
1367
+ PrivilegeCode: newGroupPrivilege.PrivilegeCode,
1368
+ Status: newGroupPrivilege.Status,
1369
+ CreatedById: newGroupPrivilege.CreatedById,
1370
+ CreatedAt: newGroupPrivilege.CreatedAt,
1371
+ UpdatedById: newGroupPrivilege.UpdatedById,
1372
+ UpdatedAt: newGroupPrivilege.UpdatedAt,
1373
+ };
1374
+
1375
+ //Call Group._GroupPrivilegesRepo.create
1376
+ const groupPrivilege = await Group._GroupPrivilegeRepo.create(
1377
+ entityValueAfter,
1378
+ {
1379
+ transaction: dbTransaction,
1380
+ },
1381
+ );
1382
+ action = ActionEnum.ADD;
1383
+ description = 'Create Group Privilege';
1384
+ entityId = groupPrivilege.GroupPrivilegeId;
1385
+ }
1386
+
1387
+ //Instantiate new activity from Activity class, call createId() method, then set:
1388
+ const activity = new Activity();
1389
+ activity.ActivityId = activity.createId();
1390
+ activity.Action = action;
1391
+ activity.Description = description;
1392
+ activity.EntityType = 'GroupPrivilege';
1393
+ activity.EntityId = entityId;
1394
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
1395
+ activity.EntityValueAfter = JSON.stringify(entityValueAfter);
1396
+
1397
+ //Call new activity create method
1398
+ await activity.create(loginUser.ObjectId, dbTransaction);
1399
+ }
1400
+
1401
+ return 'Successfully added.';
1402
+ } catch (error) {
1403
+ throw error;
1404
+ }
1405
+ }
1406
+
1407
+ public static async deleteGroupPrivilege(
1408
+ loginUser: LoginUser,
1409
+ dbTransaction: any,
1410
+ GroupCode: string,
1411
+ PrivilegeCodes: string[],
1412
+ ) {
1413
+ try {
1414
+ // Part 1: Privilege Checking
1415
+ const systemCode =
1416
+ ApplicationConfig.getComponentConfigValue('system-code');
1417
+ const isPrivileged = await loginUser.checkPrivileges(
1418
+ systemCode,
1419
+ 'GROUP_PRIVILEGE_DELETE',
1420
+ );
1421
+
1422
+ if (!isPrivileged) {
1423
+ throw new ClassError(
1424
+ 'Group',
1425
+ 'GroupErrMsg06',
1426
+ 'You do not have the privilege to delete group privileges',
1427
+ );
1428
+ }
1429
+
1430
+ // Part 2: Validation, Create and Record Activity
1431
+ // For each Params.PrivilegesCodes.
1432
+ for (const PrivilegeCode of PrivilegeCodes) {
1433
+ //Check whether the record exist in database by calling Group._GroupPrivilegeRepo.findOne
1434
+ const groupPrivilege = await Group._GroupPrivilegeRepo.findOne({
1435
+ where: {
1436
+ GroupCode,
1437
+ PrivilegeCode,
1438
+ },
1439
+ transaction: dbTransaction,
1440
+ });
1441
+
1442
+ //If the record does not exist, throw a new ClassError
1443
+ if (!groupPrivilege) {
1444
+ throw new ClassError(
1445
+ 'Group',
1446
+ 'GroupErrMsg14',
1447
+ 'GroupPrivilege not found.',
1448
+ );
1449
+ }
1450
+
1451
+ //Set the EntityValueBefore to the GroupPrivilegesValue from step 1.c.
1452
+ const entityValueBefore = {
1453
+ GroupCode: groupPrivilege.GroupCode,
1454
+ PrivilegeCode: groupPrivilege.PrivilegeCode,
1455
+ Status: groupPrivilege.Status,
1456
+ CreatedById: groupPrivilege.CreatedById,
1457
+ CreatedAt: groupPrivilege.CreatedAt,
1458
+ UpdatedById: groupPrivilege.UpdatedById,
1459
+ UpdatedAt: groupPrivilege.UpdatedAt,
1460
+ };
1461
+
1462
+ //Call Group._GroupPrivilegeRepo.delete
1463
+ await Group._GroupPrivilegeRepo.delete(
1464
+ GroupCode,
1465
+ PrivilegeCode,
1466
+ dbTransaction,
1467
+ );
1468
+ // Instantiate new activity from Activity class, call createId() method, then set:
1469
+ const activity = new Activity();
1470
+ activity.ActivityId = activity.createId();
1471
+ activity.Action = ActionEnum.DELETE;
1472
+ activity.Description = 'DELETE Group Privilege';
1473
+ activity.EntityType = 'GroupPrivilege';
1474
+ activity.EntityId = groupPrivilege.GroupPrivilegeId.toString();
1475
+ activity.EntityValueBefore = JSON.stringify(entityValueBefore);
1476
+ activity.EntityValueAfter = JSON.stringify({});
1477
+ //Call new activity create method
1478
+ await activity.create(loginUser.ObjectId, dbTransaction);
1479
+ }
1480
+ return 'Successfully deleted.';
1481
+ } catch (error) {
1482
+ throw error;
1483
+ }
1484
+ }
1485
+ }