@flusys/nestjs-iam 6.0.2 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/cjs/controllers/action.controller.spec.js +79 -0
  2. package/cjs/controllers/company-action-permission.controller.spec.js +65 -0
  3. package/cjs/controllers/my-permission.controller.spec.js +56 -0
  4. package/cjs/controllers/role-permission.controller.spec.js +140 -0
  5. package/cjs/controllers/role.controller.spec.js +86 -0
  6. package/cjs/controllers/user-action-permission.controller.spec.js +68 -0
  7. package/cjs/docs/iam-swagger.config.spec.js +99 -0
  8. package/cjs/entities/index.spec.js +56 -0
  9. package/cjs/helpers/company-access.helper.spec.js +68 -0
  10. package/cjs/helpers/permission-mode.helper.spec.js +54 -0
  11. package/cjs/modules/iam.module.spec.js +293 -0
  12. package/cjs/services/action.service.spec.js +314 -0
  13. package/cjs/services/iam-config.service.spec.js +110 -0
  14. package/cjs/services/iam-datasource.service.spec.js +117 -0
  15. package/cjs/services/permission-cache.service.spec.js +252 -0
  16. package/cjs/services/permission.service.spec.js +967 -0
  17. package/cjs/services/role.service.spec.js +312 -0
  18. package/fesm/controllers/action.controller.spec.js +75 -0
  19. package/fesm/controllers/company-action-permission.controller.spec.js +61 -0
  20. package/fesm/controllers/my-permission.controller.spec.js +52 -0
  21. package/fesm/controllers/role-permission.controller.spec.js +136 -0
  22. package/fesm/controllers/role.controller.spec.js +82 -0
  23. package/fesm/controllers/user-action-permission.controller.spec.js +64 -0
  24. package/fesm/docs/iam-swagger.config.spec.js +95 -0
  25. package/fesm/entities/index.spec.js +52 -0
  26. package/fesm/helpers/company-access.helper.spec.js +64 -0
  27. package/fesm/helpers/permission-mode.helper.spec.js +50 -0
  28. package/fesm/modules/iam.module.spec.js +289 -0
  29. package/fesm/services/action.service.spec.js +310 -0
  30. package/fesm/services/iam-config.service.spec.js +106 -0
  31. package/fesm/services/iam-datasource.service.spec.js +113 -0
  32. package/fesm/services/permission-cache.service.spec.js +248 -0
  33. package/fesm/services/permission.service.spec.js +963 -0
  34. package/fesm/services/role.service.spec.js +308 -0
  35. package/package.json +3 -3
@@ -0,0 +1,312 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ const _testing = require("@nestjs/testing");
6
+ const _modules = require("@flusys/nestjs-shared/modules");
7
+ const _repositorymock = require("@test-utils/mocks/repository.mock");
8
+ const _loggedusermock = require("@test-utils/mocks/logged-user.mock");
9
+ const _roleentity = require("../entities/role.entity");
10
+ const _rolewithcompanyentity = require("../entities/role-with-company.entity");
11
+ const _iamconfigservice = require("./iam-config.service");
12
+ const _iamdatasourceservice = require("./iam-datasource.service");
13
+ const _permissioncacheservice = require("./permission-cache.service");
14
+ const _roleservice = require("./role.service");
15
+ function buildRole(overrides = {}) {
16
+ return {
17
+ id: 'role-uuid-1',
18
+ readOnly: false,
19
+ name: 'Manager',
20
+ description: null,
21
+ isActive: true,
22
+ serial: 1,
23
+ createdAt: new Date(),
24
+ updatedAt: new Date(),
25
+ deletedAt: null,
26
+ createdById: null,
27
+ updatedById: null,
28
+ deletedById: null,
29
+ ...overrides
30
+ };
31
+ }
32
+ describe('RoleService', ()=>{
33
+ let service;
34
+ let mockRepo;
35
+ let mockIamConfigService;
36
+ let mockPermissionCacheService;
37
+ beforeEach(async ()=>{
38
+ mockRepo = (0, _repositorymock.createMockRepository)();
39
+ const mockDataSourceProvider = (0, _repositorymock.createMockDataSourceProvider)(mockRepo);
40
+ mockIamConfigService = {
41
+ isCompanyFeatureEnabled: jest.fn().mockReturnValue(false)
42
+ };
43
+ mockPermissionCacheService = {
44
+ invalidateUsers: jest.fn()
45
+ };
46
+ const module = await _testing.Test.createTestingModule({
47
+ providers: [
48
+ _roleservice.RoleService,
49
+ {
50
+ provide: 'CACHE_INSTANCE',
51
+ useValue: {}
52
+ },
53
+ {
54
+ provide: _modules.UtilsService,
55
+ useValue: {}
56
+ },
57
+ {
58
+ provide: _iamconfigservice.IAMConfigService,
59
+ useValue: mockIamConfigService
60
+ },
61
+ {
62
+ provide: _iamdatasourceservice.IAMDataSourceService,
63
+ useValue: mockDataSourceProvider
64
+ },
65
+ {
66
+ provide: _permissioncacheservice.PermissionCacheService,
67
+ useValue: mockPermissionCacheService
68
+ }
69
+ ]
70
+ }).compile();
71
+ service = await module.resolve(_roleservice.RoleService);
72
+ });
73
+ describe('resolveEntity', ()=>{
74
+ it('resolves to Role when the company feature is disabled', ()=>{
75
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(false);
76
+ expect(service.resolveEntity()).toBe(_roleentity.Role);
77
+ });
78
+ it('resolves to RoleWithCompany when the company feature is enabled', ()=>{
79
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(true);
80
+ expect(service.resolveEntity()).toBe(_rolewithcompanyentity.RoleWithCompany);
81
+ });
82
+ });
83
+ describe('convertSingleDtoToEntity', ()=>{
84
+ it('creates a plain entity without companyId when the company feature is disabled', async ()=>{
85
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(false);
86
+ await service.ensureDataSourceRepository();
87
+ mockRepo.create.mockReturnValue({});
88
+ const entity = await service.convertSingleDtoToEntity({
89
+ name: 'Manager'
90
+ }, (0, _loggedusermock.buildMockUser)());
91
+ expect(entity.companyId).toBeUndefined();
92
+ });
93
+ it('stamps companyId from the DTO on create when the company feature is enabled', async ()=>{
94
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(true);
95
+ await service.ensureDataSourceRepository();
96
+ mockRepo.create.mockReturnValue({});
97
+ const entity = await service.convertSingleDtoToEntity({
98
+ name: 'Manager',
99
+ companyId: 'company-explicit'
100
+ }, (0, _loggedusermock.buildMockUser)({
101
+ companyId: 'company-from-user'
102
+ }));
103
+ expect(entity.companyId).toBe('company-explicit');
104
+ });
105
+ it('falls back to the user companyId on create when the DTO omits it', async ()=>{
106
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(true);
107
+ await service.ensureDataSourceRepository();
108
+ mockRepo.create.mockReturnValue({});
109
+ const entity = await service.convertSingleDtoToEntity({
110
+ name: 'Manager'
111
+ }, (0, _loggedusermock.buildMockUser)({
112
+ companyId: 'company-from-user'
113
+ }));
114
+ expect(entity.companyId).toBe('company-from-user');
115
+ });
116
+ it('does not override companyId on update when the DTO omits it', async ()=>{
117
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(true);
118
+ await service.ensureDataSourceRepository();
119
+ const existing = buildRole({
120
+ id: 'role-uuid-1',
121
+ companyId: 'existing-company'
122
+ });
123
+ mockRepo.findOne.mockResolvedValue(existing);
124
+ const entity = await service.convertSingleDtoToEntity({
125
+ id: 'role-uuid-1',
126
+ name: 'Manager Updated'
127
+ }, (0, _loggedusermock.buildMockUser)({
128
+ companyId: 'company-from-user'
129
+ }));
130
+ expect(entity.companyId).toBe('existing-company');
131
+ });
132
+ it('overrides companyId on update when explicitly provided in the DTO', async ()=>{
133
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(true);
134
+ await service.ensureDataSourceRepository();
135
+ const existing = buildRole({
136
+ id: 'role-uuid-1',
137
+ companyId: 'existing-company'
138
+ });
139
+ mockRepo.findOne.mockResolvedValue(existing);
140
+ const entity = await service.convertSingleDtoToEntity({
141
+ id: 'role-uuid-1',
142
+ name: 'Manager Updated',
143
+ companyId: 'new-company'
144
+ }, (0, _loggedusermock.buildMockUser)());
145
+ expect(entity.companyId).toBe('new-company');
146
+ });
147
+ it('throws NotFoundException when updating a role that does not exist', async ()=>{
148
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(false);
149
+ await service.ensureDataSourceRepository();
150
+ mockRepo.findOne.mockResolvedValue(null);
151
+ await expect(service.convertSingleDtoToEntity({
152
+ id: 'missing-role'
153
+ }, (0, _loggedusermock.buildMockUser)())).rejects.toThrow();
154
+ });
155
+ });
156
+ describe('getSelectQuery', ()=>{
157
+ it('selects the default field set without companyId when the company feature is disabled', async ()=>{
158
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(false);
159
+ const query = mockRepo.createQueryBuilder();
160
+ await service.getSelectQuery(query, (0, _loggedusermock.buildMockUser)());
161
+ expect(query.select).toHaveBeenCalledWith(expect.not.arrayContaining([
162
+ 'role.companyId'
163
+ ]));
164
+ });
165
+ it('includes companyId in the default field set when the company feature is enabled', async ()=>{
166
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(true);
167
+ const query = mockRepo.createQueryBuilder();
168
+ await service.getSelectQuery(query, (0, _loggedusermock.buildMockUser)());
169
+ expect(query.select).toHaveBeenCalledWith(expect.arrayContaining([
170
+ 'role.companyId'
171
+ ]));
172
+ });
173
+ it('uses the explicitly provided select list as-is', async ()=>{
174
+ const query = mockRepo.createQueryBuilder();
175
+ await service.getSelectQuery(query, (0, _loggedusermock.buildMockUser)(), [
176
+ 'id',
177
+ 'name'
178
+ ]);
179
+ expect(query.select).toHaveBeenCalledWith([
180
+ 'role.id',
181
+ 'role.name'
182
+ ]);
183
+ });
184
+ });
185
+ describe('getGlobalSearchQuery', ()=>{
186
+ it('filters by name or description', async ()=>{
187
+ const query = mockRepo.createQueryBuilder();
188
+ await service.getGlobalSearchQuery(query, 'manager');
189
+ expect(query.andWhere).toHaveBeenCalledWith('(role.name LIKE :search OR role.description LIKE :search)', {
190
+ search: '%manager%'
191
+ });
192
+ });
193
+ });
194
+ describe('getExtraManipulateQuery', ()=>{
195
+ it('applies a company filter clause when the company feature is enabled and the user has a company', async ()=>{
196
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(true);
197
+ const query = mockRepo.createQueryBuilder();
198
+ await service.getExtraManipulateQuery(query, {}, (0, _loggedusermock.buildMockUser)({
199
+ companyId: 'company-1'
200
+ }));
201
+ expect(query.andWhere).toHaveBeenCalledWith('role.companyId = :companyId', {
202
+ companyId: 'company-1'
203
+ });
204
+ });
205
+ it('does not apply a company filter when the company feature is disabled', async ()=>{
206
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(false);
207
+ const query = mockRepo.createQueryBuilder();
208
+ await service.getExtraManipulateQuery(query, {}, (0, _loggedusermock.buildMockUser)({
209
+ companyId: 'company-1'
210
+ }));
211
+ expect(query.andWhere).not.toHaveBeenCalled();
212
+ });
213
+ });
214
+ describe('convertEntityToResponseDto', ()=>{
215
+ it('defaults companyId to null when the entity has no companyId field', ()=>{
216
+ const entity = buildRole();
217
+ const dto = service.convertEntityToResponseDto(entity, false);
218
+ expect(dto.companyId).toBeNull();
219
+ });
220
+ it('surfaces companyId when present on the entity', ()=>{
221
+ const entity = buildRole({
222
+ companyId: 'company-1'
223
+ });
224
+ const dto = service.convertEntityToResponseDto(entity, false);
225
+ expect(dto.companyId).toBe('company-1');
226
+ });
227
+ });
228
+ describe('beforeDeleteOperation', ()=>{
229
+ function buildQueryRunner(permissionRepo) {
230
+ return {
231
+ manager: {
232
+ getRepository: jest.fn().mockReturnValue(permissionRepo)
233
+ }
234
+ };
235
+ }
236
+ it('does nothing when the delete DTO has no ids', async ()=>{
237
+ const permissionRepo = (0, _repositorymock.createMockRepository)();
238
+ const queryRunner = buildQueryRunner(permissionRepo);
239
+ await service.beforeDeleteOperation({
240
+ id: [],
241
+ type: 'delete'
242
+ }, (0, _loggedusermock.buildMockUser)(), queryRunner);
243
+ expect(permissionRepo.find).not.toHaveBeenCalled();
244
+ });
245
+ it('cascades ROLE_ACTION and USER_ROLE cleanup and invalidates affected users cache', async ()=>{
246
+ mockIamConfigService.isCompanyFeatureEnabled.mockReturnValue(false);
247
+ const permissionRepo = (0, _repositorymock.createMockRepository)();
248
+ permissionRepo.find.mockResolvedValue([
249
+ {
250
+ userId: 'user-1'
251
+ },
252
+ {
253
+ userId: 'user-2'
254
+ },
255
+ {
256
+ userId: null
257
+ }
258
+ ]);
259
+ const queryRunner = buildQueryRunner(permissionRepo);
260
+ await service.beforeDeleteOperation({
261
+ id: 'role-uuid-1',
262
+ type: 'delete'
263
+ }, (0, _loggedusermock.buildMockUser)(), queryRunner);
264
+ expect(permissionRepo.delete).toHaveBeenCalledWith(expect.objectContaining({
265
+ permissionType: 'role_action',
266
+ sourceType: 'role'
267
+ }));
268
+ expect(permissionRepo.delete).toHaveBeenCalledWith(expect.objectContaining({
269
+ permissionType: 'user_role',
270
+ targetType: 'role'
271
+ }));
272
+ expect(mockPermissionCacheService.invalidateUsers).toHaveBeenCalledWith([
273
+ 'user-1',
274
+ 'user-2'
275
+ ]);
276
+ });
277
+ it('does not invalidate any cache when no users are affected', async ()=>{
278
+ const permissionRepo = (0, _repositorymock.createMockRepository)();
279
+ permissionRepo.find.mockResolvedValue([]);
280
+ const queryRunner = buildQueryRunner(permissionRepo);
281
+ await service.beforeDeleteOperation({
282
+ id: [
283
+ 'role-uuid-1'
284
+ ],
285
+ type: 'delete'
286
+ }, (0, _loggedusermock.buildMockUser)(), queryRunner);
287
+ expect(mockPermissionCacheService.invalidateUsers).not.toHaveBeenCalled();
288
+ });
289
+ it('supports array ids and dedupes affected user ids', async ()=>{
290
+ const permissionRepo = (0, _repositorymock.createMockRepository)();
291
+ permissionRepo.find.mockResolvedValue([
292
+ {
293
+ userId: 'user-1'
294
+ },
295
+ {
296
+ userId: 'user-1'
297
+ }
298
+ ]);
299
+ const queryRunner = buildQueryRunner(permissionRepo);
300
+ await service.beforeDeleteOperation({
301
+ id: [
302
+ 'role-uuid-1',
303
+ 'role-uuid-2'
304
+ ],
305
+ type: 'delete'
306
+ }, (0, _loggedusermock.buildMockUser)(), queryRunner);
307
+ expect(mockPermissionCacheService.invalidateUsers).toHaveBeenCalledWith([
308
+ 'user-1'
309
+ ]);
310
+ });
311
+ });
312
+ });
@@ -0,0 +1,75 @@
1
+ import { buildMockUser } from '@test-utils/mocks/logged-user.mock';
2
+ import { ActionController } from './action.controller';
3
+ describe('ActionController', ()=>{
4
+ let controller;
5
+ let mockActionService;
6
+ let mockIamConfigService;
7
+ beforeEach(()=>{
8
+ mockActionService = {
9
+ insert: jest.fn(),
10
+ findById: jest.fn(),
11
+ getAll: jest.fn(),
12
+ update: jest.fn(),
13
+ delete: jest.fn(),
14
+ getActionsForPermission: jest.fn(),
15
+ getActionTree: jest.fn()
16
+ };
17
+ mockIamConfigService = {};
18
+ controller = new ActionController(mockActionService, mockIamConfigService);
19
+ });
20
+ it('wires the injected service onto the generated controller base', ()=>{
21
+ expect(controller.actionService).toBe(mockActionService);
22
+ expect(controller.service).toBe(mockActionService);
23
+ });
24
+ describe('getActionsForPermission', ()=>{
25
+ it('returns actions scoped to the caller session company when no companyId is given', async ()=>{
26
+ const user = buildMockUser();
27
+ mockActionService.getActionsForPermission.mockResolvedValue([
28
+ {
29
+ id: 'action-1',
30
+ code: 'user.create'
31
+ }
32
+ ]);
33
+ const result = await controller.getActionsForPermission({}, user);
34
+ expect(mockActionService.getActionsForPermission).toHaveBeenCalledWith(user, undefined);
35
+ expect(result.success).toBe(true);
36
+ expect(result.data).toEqual([
37
+ {
38
+ id: 'action-1',
39
+ code: 'user.create'
40
+ }
41
+ ]);
42
+ });
43
+ it('forwards an explicit companyId override', async ()=>{
44
+ const user = buildMockUser();
45
+ mockActionService.getActionsForPermission.mockResolvedValue([]);
46
+ await controller.getActionsForPermission({
47
+ companyId: 'company-2'
48
+ }, user);
49
+ expect(mockActionService.getActionsForPermission).toHaveBeenCalledWith(user, 'company-2');
50
+ });
51
+ });
52
+ describe('getActionTree', ()=>{
53
+ it('returns the hierarchical action tree with query filters applied', async ()=>{
54
+ const user = buildMockUser();
55
+ mockActionService.getActionTree.mockResolvedValue([
56
+ {
57
+ id: 'action-1',
58
+ children: []
59
+ }
60
+ ]);
61
+ const result = await controller.getActionTree({
62
+ search: 'user',
63
+ isActive: true,
64
+ withDeleted: false
65
+ }, user);
66
+ expect(mockActionService.getActionTree).toHaveBeenCalledWith(user, 'user', true, false);
67
+ expect(result.data).toEqual([
68
+ {
69
+ id: 'action-1',
70
+ children: []
71
+ }
72
+ ]);
73
+ });
74
+ });
75
+ });
@@ -0,0 +1,61 @@
1
+ import { CompanyActionPermissionController } from './company-action-permission.controller';
2
+ describe('CompanyActionPermissionController', ()=>{
3
+ let controller;
4
+ let mockPermissionService;
5
+ beforeEach(()=>{
6
+ mockPermissionService = {
7
+ assignCompanyActions: jest.fn(),
8
+ getCompanyActions: jest.fn()
9
+ };
10
+ controller = new CompanyActionPermissionController(mockPermissionService);
11
+ });
12
+ describe('assignCompanyActions', ()=>{
13
+ it('whitelists actions for a company', async ()=>{
14
+ mockPermissionService.assignCompanyActions.mockResolvedValue({
15
+ added: 3,
16
+ removed: 0,
17
+ total: 3
18
+ });
19
+ const result = await controller.assignCompanyActions({
20
+ companyId: 'company-1',
21
+ actionIds: [
22
+ 'action-1',
23
+ 'action-2',
24
+ 'action-3'
25
+ ]
26
+ });
27
+ expect(mockPermissionService.assignCompanyActions).toHaveBeenCalledWith({
28
+ companyId: 'company-1',
29
+ actionIds: [
30
+ 'action-1',
31
+ 'action-2',
32
+ 'action-3'
33
+ ]
34
+ });
35
+ expect(result.success).toBe(true);
36
+ expect(result.data).toEqual({
37
+ added: 3,
38
+ removed: 0,
39
+ total: 3
40
+ });
41
+ });
42
+ });
43
+ describe('getCompanyActions', ()=>{
44
+ it('returns the whitelisted actions for a company', async ()=>{
45
+ mockPermissionService.getCompanyActions.mockResolvedValue([
46
+ {
47
+ actionId: 'action-1'
48
+ }
49
+ ]);
50
+ const result = await controller.getCompanyActions({
51
+ companyId: 'company-1'
52
+ });
53
+ expect(mockPermissionService.getCompanyActions).toHaveBeenCalledWith('company-1');
54
+ expect(result.data).toEqual([
55
+ {
56
+ actionId: 'action-1'
57
+ }
58
+ ]);
59
+ });
60
+ });
61
+ });
@@ -0,0 +1,52 @@
1
+ import { buildMockUser } from '@test-utils/mocks/logged-user.mock';
2
+ import { MyPermissionController } from './my-permission.controller';
3
+ describe('MyPermissionController', ()=>{
4
+ let controller;
5
+ let mockPermissionService;
6
+ beforeEach(()=>{
7
+ mockPermissionService = {
8
+ getMyPermissions: jest.fn()
9
+ };
10
+ controller = new MyPermissionController(mockPermissionService);
11
+ });
12
+ describe('getMyPermissions', ()=>{
13
+ it('resolves permissions for the current user, branch, and company', async ()=>{
14
+ const user = buildMockUser({
15
+ id: 'user-1',
16
+ companyId: 'company-1',
17
+ branchId: 'branch-1'
18
+ });
19
+ const permissions = {
20
+ menus: [],
21
+ actions: [
22
+ 'user.create'
23
+ ]
24
+ };
25
+ mockPermissionService.getMyPermissions.mockResolvedValue(permissions);
26
+ const result = await controller.getMyPermissions({
27
+ parentCodes: [
28
+ 'user'
29
+ ]
30
+ }, user);
31
+ expect(mockPermissionService.getMyPermissions).toHaveBeenCalledWith('user-1', 'branch-1', 'company-1', [
32
+ 'user'
33
+ ]);
34
+ expect(result).toEqual({
35
+ success: true,
36
+ message: 'Permissions loaded successfully',
37
+ messageKey: expect.any(String),
38
+ data: permissions
39
+ });
40
+ });
41
+ it('passes null for missing branch and company context', async ()=>{
42
+ const user = buildMockUser({
43
+ id: 'user-1',
44
+ companyId: undefined,
45
+ branchId: undefined
46
+ });
47
+ mockPermissionService.getMyPermissions.mockResolvedValue({});
48
+ await controller.getMyPermissions({}, user);
49
+ expect(mockPermissionService.getMyPermissions).toHaveBeenCalledWith('user-1', null, null, undefined);
50
+ });
51
+ });
52
+ });
@@ -0,0 +1,136 @@
1
+ import { ForbiddenException } from '@nestjs/common';
2
+ import { buildMockUser } from '@test-utils/mocks/logged-user.mock';
3
+ import { RolePermissionController } from './role-permission.controller';
4
+ describe('RolePermissionController', ()=>{
5
+ let controller;
6
+ let mockPermissionService;
7
+ let mockConfig;
8
+ beforeEach(()=>{
9
+ mockPermissionService = {
10
+ assignRoleActions: jest.fn(),
11
+ getRoleActions: jest.fn(),
12
+ assignUserRoles: jest.fn(),
13
+ getUserRoles: jest.fn()
14
+ };
15
+ mockConfig = {
16
+ isCompanyFeatureEnabled: jest.fn().mockReturnValue(false)
17
+ };
18
+ controller = new RolePermissionController(mockPermissionService, mockConfig);
19
+ });
20
+ describe('assignRoleActions', ()=>{
21
+ it('assigns actions to a role and returns the operation summary', async ()=>{
22
+ mockPermissionService.assignRoleActions.mockResolvedValue({
23
+ added: 2,
24
+ removed: 1,
25
+ total: 3
26
+ });
27
+ const result = await controller.assignRoleActions({
28
+ roleId: 'role-1',
29
+ actionIds: [
30
+ 'action-1',
31
+ 'action-2'
32
+ ]
33
+ });
34
+ expect(mockPermissionService.assignRoleActions).toHaveBeenCalledWith({
35
+ roleId: 'role-1',
36
+ actionIds: [
37
+ 'action-1',
38
+ 'action-2'
39
+ ]
40
+ });
41
+ expect(result.success).toBe(true);
42
+ expect(result.data).toEqual({
43
+ added: 2,
44
+ removed: 1,
45
+ total: 3
46
+ });
47
+ });
48
+ });
49
+ describe('getRoleActions', ()=>{
50
+ it('returns actions assigned to the role', async ()=>{
51
+ mockPermissionService.getRoleActions.mockResolvedValue([
52
+ {
53
+ actionId: 'action-1'
54
+ }
55
+ ]);
56
+ const result = await controller.getRoleActions({
57
+ roleId: 'role-1'
58
+ });
59
+ expect(mockPermissionService.getRoleActions).toHaveBeenCalledWith('role-1');
60
+ expect(result.data).toEqual([
61
+ {
62
+ actionId: 'action-1'
63
+ }
64
+ ]);
65
+ });
66
+ });
67
+ describe('assignUserRoles', ()=>{
68
+ it('assigns roles to a user when the caller has access to the target company', async ()=>{
69
+ mockConfig.isCompanyFeatureEnabled.mockReturnValue(true);
70
+ const user = buildMockUser({
71
+ companyId: 'company-1'
72
+ });
73
+ mockPermissionService.assignUserRoles.mockResolvedValue({
74
+ added: 1,
75
+ removed: 0,
76
+ total: 1
77
+ });
78
+ const result = await controller.assignUserRoles({
79
+ userId: 'user-2',
80
+ roleIds: [
81
+ 'role-1'
82
+ ],
83
+ companyId: 'company-1'
84
+ }, user);
85
+ expect(mockPermissionService.assignUserRoles).toHaveBeenCalledWith({
86
+ userId: 'user-2',
87
+ roleIds: [
88
+ 'role-1'
89
+ ],
90
+ companyId: 'company-1'
91
+ });
92
+ expect(result.data).toEqual({
93
+ added: 1,
94
+ removed: 0,
95
+ total: 1
96
+ });
97
+ });
98
+ it('rejects assignment when the caller has no access to the target company', async ()=>{
99
+ mockConfig.isCompanyFeatureEnabled.mockReturnValue(true);
100
+ const user = buildMockUser({
101
+ companyId: 'company-1'
102
+ });
103
+ await expect(controller.assignUserRoles({
104
+ userId: 'user-2',
105
+ roleIds: [
106
+ 'role-1'
107
+ ],
108
+ companyId: 'company-2'
109
+ }, user)).rejects.toThrow(ForbiddenException);
110
+ expect(mockPermissionService.assignUserRoles).not.toHaveBeenCalled();
111
+ });
112
+ });
113
+ describe('getUserRoles', ()=>{
114
+ it('returns roles assigned to the user scoped by branch and company', async ()=>{
115
+ const user = buildMockUser({
116
+ companyId: 'company-1'
117
+ });
118
+ mockPermissionService.getUserRoles.mockResolvedValue([
119
+ {
120
+ roleId: 'role-1'
121
+ }
122
+ ]);
123
+ const result = await controller.getUserRoles({
124
+ userId: 'user-2',
125
+ branchId: 'branch-1',
126
+ companyId: 'company-1'
127
+ }, user);
128
+ expect(mockPermissionService.getUserRoles).toHaveBeenCalledWith('user-2', 'branch-1', 'company-1');
129
+ expect(result.data).toEqual([
130
+ {
131
+ roleId: 'role-1'
132
+ }
133
+ ]);
134
+ });
135
+ });
136
+ });