File size: 19,992 Bytes
3418204
 
 
 
 
 
 
 
9fb631c
9e133e9
3418204
 
 
 
 
 
f0d69b8
3418204
f0d69b8
3418204
 
f0d69b8
3418204
 
 
 
 
 
 
 
 
 
 
01be06d
4c550c2
 
3418204
 
9fb631c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3418204
 
4c550c2
 
 
 
 
3418204
 
 
 
 
 
01be06d
3418204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c42fd03
01be06d
631e3a2
01be06d
 
 
 
 
 
9e133e9
3418204
 
 
 
 
 
 
 
 
 
f0d69b8
 
47e77e5
 
 
 
01be06d
3418204
01be06d
3418204
 
4c550c2
3418204
 
 
 
 
4c550c2
3418204
 
 
 
 
 
 
 
 
 
4c550c2
 
 
 
3418204
 
 
 
 
 
 
 
 
 
 
 
 
 
f0d69b8
3418204
 
 
47e77e5
3418204
 
4c550c2
 
 
 
3418204
9cf881e
 
 
 
 
 
3418204
47e77e5
 
3418204
 
f0d69b8
3418204
 
 
631e3a2
3418204
 
 
 
 
 
 
c7beb09
 
 
 
 
 
 
 
 
 
 
 
 
 
3418204
4c550c2
 
3418204
 
4c550c2
 
 
 
 
 
 
c7beb09
4c550c2
 
01be06d
4c550c2
3418204
 
47e77e5
3418204
 
 
 
 
 
 
c42fd03
3418204
631e3a2
3418204
 
c42fd03
4c550c2
 
 
 
 
631e3a2
01be06d
 
 
 
 
4c550c2
 
 
 
 
 
 
 
 
 
 
 
 
3418204
 
4c550c2
 
c7beb09
4c550c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47e77e5
 
c7beb09
47e77e5
 
 
c7beb09
47e77e5
4c550c2
c7beb09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47e77e5
 
 
 
 
 
 
 
 
c7beb09
 
 
 
 
 
3418204
47e77e5
4c550c2
47e77e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c550c2
 
 
3418204
47e77e5
 
 
 
 
3418204
 
01be06d
4c550c2
 
47e77e5
 
4c550c2
 
 
47e77e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c550c2
 
47e77e5
 
 
 
 
4c550c2
 
 
 
 
47e77e5
 
3418204
 
 
f0d69b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47e77e5
f0d69b8
 
 
 
47e77e5
f0d69b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3418204
f0d69b8
3418204
 
01be06d
4c550c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
631e3a2
01be06d
4c550c2
 
 
 
 
c42fd03
4c550c2
01be06d
 
 
4c550c2
 
 
01be06d
 
c42fd03
4c550c2
01be06d
 
4c550c2
01be06d
 
 
 
 
 
631e3a2
01be06d
 
 
 
3418204
 
c42fd03
 
631e3a2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TaskTrackingSystem.Database.AppDbContextModels;
using TaskTrackingSystem.Shared;
using TaskTrackingSystem.Shared.Models.Role;
using TaskTrackingSystem.WebApi.Infrastructure;
using RoleEntity = TaskTrackingSystem.Database.AppDbContextModels.Role;

namespace TaskTrackingSystem.WebApi.Features.Role
{
    public class RoleService
    {
        private readonly AppDbContext _db;
        private readonly Infrastructure.AuditLogService _auditLog;

        public RoleService(AppDbContext db, Infrastructure.AuditLogService auditLog)
        {
            _db = db;
            _auditLog = auditLog;
        }

        public async Task<IEnumerable<RoleDto>> GetAllRolesAsync()
        {
            return await _db.Roles
                .Where(r => r.IsDeleted != true)
                .Select(r => new RoleDto
                {
                    Id = r.Id,
                    Name = r.Name,
                    Description = r.Description,
                    CreatedAt = r.CreatedAt ?? DateTime.UtcNow
                })
                .ToListAsync();
        }

        public async Task<PagedResult<RoleDto>> GetPagedRolesAsync(string? search, int page, int pageSize)
        {
            var query = _db.Roles.Where(r => r.IsDeleted != true);

            if (!string.IsNullOrWhiteSpace(search))
            {
                var searchTerm = search.Trim().ToLower();
                query = query.Where(r =>
                    (r.Name != null && r.Name.ToLower().Contains(searchTerm)) ||
                    (r.Description != null && r.Description.ToLower().Contains(searchTerm)));
            }

            return await query
                .OrderBy(r => r.Name)
                .Select(r => new RoleDto
                {
                    Id = r.Id,
                    Name = r.Name,
                    Description = r.Description,
                    CreatedAt = r.CreatedAt ?? DateTime.UtcNow
                })
                .ToPagedResultAsync(page, pageSize);
        }

        public async Task<RoleDto?> GetRoleByIdAsync(long id)
        {
            var role = await _db.Roles.FirstOrDefaultAsync(r => r.Id == id && r.IsDeleted != true);
            if (role == null)
            {
                return null;
            }

            return new RoleDto
            {
                Id = role.Id,
                Name = role.Name,
                Description = role.Description,
                CreatedAt = role.CreatedAt ?? DateTime.UtcNow
            };
        }

        public async Task<Result<RoleDto>> CreateRoleAsync(CreateRoleDto dto, long? currentUserId = null)
        {
            if (string.IsNullOrWhiteSpace(dto.Name))
            {
                return Result<RoleDto>.Failure(ResultMessages.RoleNameRequired, 400);
            }

            var nameExists = await _db.Roles.AnyAsync(r => r.Name == dto.Name && r.IsDeleted != true);
            if (nameExists)
            {
                return Result<RoleDto>.Failure("Role name is already taken.", 400);
            }

            if (dto.AccessCodes != null && dto.AccessCodes.Any())
            {
                var validCodesResult = await ValidateAccessCodesAsync(dto.AccessCodes);
                if (!validCodesResult.IsSuccess)
                {
                    return Result<RoleDto>.Failure(validCodesResult.ErrorMessage ?? ResultMessages.FailedToCreateRole, validCodesResult.StatusCode);
                }
            }

            var role = new RoleEntity
            {
                Name = dto.Name,
                Description = dto.Description,
                CreatedAt = DateTime.UtcNow,
                CreatedBy = currentUserId
            };

            _db.Roles.Add(role);
            await _db.SaveChangesAsync();

            await _auditLog.LogAsync("Create", "Role", $"Created new role '{role.Name}'");

            var assignResult = await AssignAccessToRoleAsync(
                role.Id,
                new AssignAccessDto { AccessCodes = dto.AccessCodes ?? new List<string>() },
                currentUserId);
            if (!assignResult.IsSuccess)
            {
                return Result<RoleDto>.Failure(assignResult.ErrorMessage ?? ResultMessages.FailedToCreateRole, assignResult.StatusCode);
            }

            return Result<RoleDto>.Success(new RoleDto
            {
                Id = role.Id,
                Name = role.Name,
                Description = role.Description,
                CreatedAt = role.CreatedAt ?? DateTime.UtcNow
            }, 201);
        }

        public async Task<Result> UpdateRoleAsync(long id, UpdateRoleDto dto, long? currentUserId = null)
        {
            if (string.IsNullOrWhiteSpace(dto.Name))
            {
                return Result.Failure(ResultMessages.RoleNameRequired, 400);
            }

            var role = await _db.Roles.FirstOrDefaultAsync(r => r.Id == id && r.IsDeleted != true);
            if (role == null)
            {
                return Result.Failure(ResultMessages.RoleNotFound(id), 404);
            }

            var nameExists = await _db.Roles.AnyAsync(r => r.Name == dto.Name && r.Id != id && r.IsDeleted != true);
            if (nameExists)
            {
                return Result.Failure("Role name is already taken by another role.", 400);
            }

            role.Name = dto.Name;
            role.Description = dto.Description;
            role.UpdatedAt = DateTime.UtcNow;
            role.UpdatedBy = currentUserId;

            _db.Roles.Update(role);
            await _db.SaveChangesAsync();
            await _auditLog.LogAsync("Update", "Role", $"Updated role name/description for '{role.Name}'");
            return Result.Success(200);
        }

        public async Task<Result> SoftDeleteRoleAsync(long id, long? currentUserId = null)
        {
            var role = await _db.Roles.FirstOrDefaultAsync(r => r.Id == id && r.IsDeleted != true);
            if (role == null)
            {
                return Result.Failure(ResultMessages.RoleNotFound(id), 404);
            }

            var usersCount = await _db.Users.CountAsync(u => u.RoleId == id && !u.IsDeleted);
            if (usersCount > 0)
            {
                return Result.Failure($"you can't delete this role because there are {usersCount} users in this role.", 400);
            }

            role.IsDeleted = true;
            role.UpdatedAt = DateTime.UtcNow;
            role.UpdatedBy = currentUserId;
            _db.Roles.Update(role);
            await _db.SaveChangesAsync();
            await _auditLog.LogAsync("Delete", "Role", $"Deleted role '{role.Name}'");
            return Result.Success(200);
        }

        public async Task<Result<List<string>>> GetAssignedAccessCodesByRoleIdAsync(long roleId)
        {
            var role = await _db.Roles.FirstOrDefaultAsync(r => r.Id == roleId && r.IsDeleted != true);
            if (role == null)
            {
                return Result<List<string>>.Failure(ResultMessages.RoleNotFound(roleId), 404);
            }

            var validMenuCodes = await _db.Menus
                .Where(m => !m.IsDeleted)
                .Select(m => m.MenuCode)
                .ToListAsync();

            var validPermissionCodes = await _db.Permissions
                .Where(p => !p.IsDeleted)
                .Select(p => p.PermissionCode)
                .ToListAsync();

            var validCodes = validMenuCodes
                .Concat(validPermissionCodes)
                .ToHashSet(StringComparer.OrdinalIgnoreCase);

            var menuCodes = await _db.RoleMenus
                .Where(rm => rm.RoleId == role.Id && !rm.IsDeleted)
                .Select(rm => rm.Menu.MenuCode)
                .ToListAsync();

            var permissionCodes = await _db.RolePermissions
                .Where(rp => rp.RoleId == role.Id && !rp.IsDeleted)
                .Select(rp => rp.Permission.PermissionCode)
                .ToListAsync();

            var assignedCodes = menuCodes
                .Concat(permissionCodes)
                .Where(code => validCodes.Contains(code))
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .ToList();

            return Result<List<string>>.Success(assignedCodes);
        }

        public async Task<Result> AssignAccessToRoleAsync(long roleId, AssignAccessDto dto, long? currentUserId = null)
        {
            var role = await _db.Roles.FirstOrDefaultAsync(r => r.Id == roleId && r.IsDeleted != true);
            if (role == null)
            {
                return Result.Failure(ResultMessages.RoleNotFound(roleId), 404);
            }

            if (dto.AccessCodes == null)
            {
                return Result.Failure(ResultMessages.AccessCodesCannotBeNull, 400);
            }

            var selectedCodes = dto.AccessCodes
                .Where(code => !string.IsNullOrWhiteSpace(code))
                .Select(code => code.Trim())
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .ToList();

            var validCodesResult = await ValidateAccessCodesAsync(selectedCodes);
            if (!validCodesResult.IsSuccess)
            {
                return Result.Failure(validCodesResult.ErrorMessage ?? ResultMessages.FailedToUpdateRole, validCodesResult.StatusCode);
            }

            var selectedMenus = await _db.Menus
                .Where(m => !m.IsDeleted && selectedCodes.Contains(m.MenuCode))
                .Select(m => new { m.MenuId, m.MenuCode, m.ParentMenuId })
                .ToListAsync();

            var selectedPermissions = await _db.Permissions
                .Where(p => !p.IsDeleted && selectedCodes.Contains(p.PermissionCode))
                .Select(p => new { p.PermissionId, p.PermissionCode, p.MenuId })
                .ToListAsync();

            var menuLookup = await _db.Menus
                .Where(m => !m.IsDeleted)
                .Select(m => new { m.MenuId, m.ParentMenuId })
                .ToListAsync();

            var menuIdLookup = menuLookup.ToDictionary(x => x.MenuId, x => x.ParentMenuId);
            var menuIdsToPersist = new HashSet<long>();
            var now = DateTime.UtcNow;

            foreach (var menu in selectedMenus)
            {
                AddWithAncestors(menu.MenuId, menuIdLookup, menuIdsToPersist);
            }

            foreach (var permission in selectedPermissions)
            {
                AddWithAncestors(permission.MenuId, menuIdLookup, menuIdsToPersist);
            }

            var permissionIdsToPersist = selectedPermissions
                .Select(p => p.PermissionId)
                .Distinct()
                .ToList();

            var existingRoleMenus = await _db.RoleMenus
                .Where(rm => rm.RoleId == role.Id)
                .OrderBy(rm => rm.RoleMenuId)
                .ToListAsync();
            var existingRolePermissions = await _db.RolePermissions
                .Where(rp => rp.RoleId == role.Id)
                .OrderBy(rp => rp.RolePermissionId)
                .ToListAsync();

            foreach (var duplicateMenuGroup in existingRoleMenus.GroupBy(rm => rm.MenuId).Where(g => g.Count() > 1))
            {
                foreach (var duplicate in duplicateMenuGroup.Skip(1))
                {
                    duplicate.IsDeleted = true;
                    duplicate.UpdatedAt = now;
                    duplicate.UpdatedById = currentUserId;
                }
            }

            foreach (var duplicatePermissionGroup in existingRolePermissions.GroupBy(rp => rp.PermissionId).Where(g => g.Count() > 1))
            {
                foreach (var duplicate in duplicatePermissionGroup.Skip(1))
                {
                    duplicate.IsDeleted = true;
                    duplicate.UpdatedAt = now;
                    duplicate.UpdatedById = currentUserId;
                }
            }

            var oldMenuIds = existingRoleMenus
                .Where(rm => !rm.IsDeleted)
                .Select(rm => rm.MenuId)
                .ToHashSet();
            var oldPermissionIds = existingRolePermissions
                .Where(rp => !rp.IsDeleted)
                .Select(rp => rp.PermissionId)
                .ToHashSet();

            var existingRoleMenusByMenuId = existingRoleMenus
                .GroupBy(rm => rm.MenuId)
                .ToDictionary(g => g.Key, g => g.First());
            var existingRolePermissionsByPermissionId = existingRolePermissions
                .GroupBy(rp => rp.PermissionId)
                .ToDictionary(g => g.Key, g => g.First());

            foreach (var existingMenu in existingRoleMenus)
            {
                var shouldBeActive = menuIdsToPersist.Contains(existingMenu.MenuId);

                if (shouldBeActive)
                {
                    if (existingMenu.IsDeleted)
                    {
                        existingMenu.IsDeleted = false;
                        existingMenu.UpdatedAt = now;
                        existingMenu.UpdatedById = currentUserId;
                    }
                }
                else if (!existingMenu.IsDeleted)
                {
                    existingMenu.IsDeleted = true;
                    existingMenu.UpdatedAt = now;
                    existingMenu.UpdatedById = currentUserId;
                }
            }

            foreach (var menuId in menuIdsToPersist)
            {
                if (existingRoleMenusByMenuId.ContainsKey(menuId))
                {
                    continue;
                }

                _db.RoleMenus.Add(new RoleMenu
                {
                    RoleId = role.Id,
                    MenuId = menuId,
                    IsDeleted = false,
                    CreatedAt = now,
                    CreatedById = currentUserId
                });
            }

            foreach (var existingPermission in existingRolePermissions)
            {
                var shouldBeActive = permissionIdsToPersist.Contains(existingPermission.PermissionId);

                if (shouldBeActive)
                {
                    if (existingPermission.IsDeleted)
                    {
                        existingPermission.IsDeleted = false;
                        existingPermission.UpdatedAt = now;
                        existingPermission.UpdatedById = currentUserId;
                    }
                }
                else if (!existingPermission.IsDeleted)
                {
                    existingPermission.IsDeleted = true;
                    existingPermission.UpdatedAt = now;
                    existingPermission.UpdatedById = currentUserId;
                }
            }

            foreach (var permissionId in permissionIdsToPersist)
            {
                if (existingRolePermissionsByPermissionId.ContainsKey(permissionId))
                {
                    continue;
                }

                _db.RolePermissions.Add(new RolePermission
                {
                    RoleId = role.Id,
                    PermissionId = permissionId,
                    IsDeleted = false,
                    CreatedAt = now,
                    CreatedById = currentUserId
                });
            }

            // Build a human-readable diff of what changed
            // Load all menu and permission names for diff display
            var allMenuNames = await _db.Menus
                .Where(m => !m.IsDeleted)
                .Select(m => new { m.MenuId, m.MenuName, m.MenuCode })
                .ToListAsync();
            var allPermNames = await _db.Permissions
                .Include(p => p.Menu)
                .Where(p => !p.IsDeleted)
                .Select(p => new { p.PermissionId, p.PermissionCode, p.ActionName, MenuName = p.Menu.MenuName })
                .ToListAsync();

            var menuNameLookup = allMenuNames.ToDictionary(m => m.MenuId, m => m.MenuName);
            var permNameLookup = allPermNames.ToDictionary(p => p.PermissionId,
                p => $"{p.MenuName}{p.ActionName}");

            var addedMenuNames = menuIdsToPersist
                .Except(oldMenuIds)
                .Select(id => menuNameLookup.TryGetValue(id, out var n) ? n : id.ToString())
                .OrderBy(n => n)
                .ToList();

            var removedMenuNames = oldMenuIds
                .Except(menuIdsToPersist)
                .Select(id => menuNameLookup.TryGetValue(id, out var n) ? n : id.ToString())
                .OrderBy(n => n)
                .ToList();

            var addedPermNames = permissionIdsToPersist
                .Except(oldPermissionIds)
                .Select(id => permNameLookup.TryGetValue(id, out var n) ? n : id.ToString())
                .OrderBy(n => n)
                .ToList();

            var removedPermNames = oldPermissionIds
                .Except(new HashSet<long>(permissionIdsToPersist))
                .Select(id => permNameLookup.TryGetValue(id, out var n) ? n : id.ToString())
                .OrderBy(n => n)
                .ToList();

            var descParts = new System.Text.StringBuilder();
            descParts.Append($"Updated access permissions for role '{role.Name}'.");

            if (addedMenuNames.Any() || addedPermNames.Any())
            {
                var added = addedMenuNames.Concat(addedPermNames).OrderBy(n => n).ToList();
                descParts.Append($" Granted: {string.Join(", ", added)}.");
            }

            if (removedMenuNames.Any() || removedPermNames.Any())
            {
                var removed = removedMenuNames.Concat(removedPermNames).OrderBy(n => n).ToList();
                descParts.Append($" Revoked: {string.Join(", ", removed)}.");
            }

            if (!addedMenuNames.Any() && !addedPermNames.Any() && !removedMenuNames.Any() && !removedPermNames.Any())
            {
                descParts.Append(" No changes detected.");
            }

            await _db.SaveChangesAsync();
            await _auditLog.LogAsync("AssignAccess", "Role", descParts.ToString());
            return Result.Success(200);
        }

        private static void AddWithAncestors(long menuId, IReadOnlyDictionary<long, long?> parentLookup, ISet<long> target)
        {
            var current = menuId;

            while (current > 0 && target.Add(current))
            {
                if (!parentLookup.TryGetValue(current, out var parentId) || !parentId.HasValue)
                {
                    break;
                }

                current = parentId.Value;
            }
        }

        private async Task<Result> ValidateAccessCodesAsync(IEnumerable<string> codes)
        {
            var normalizedCodes = codes
                .Where(code => !string.IsNullOrWhiteSpace(code))
                .Select(code => code.Trim())
                .ToList();

            var validAccessCodes = await _db.Menus
                .Where(m => !m.IsDeleted)
                .Select(m => m.MenuCode)
                .ToListAsync();

            var validPermissionCodes = await _db.Permissions
                .Where(p => !p.IsDeleted)
                .Select(p => p.PermissionCode)
                .ToListAsync();

            var validCodes = validAccessCodes
                .Concat(validPermissionCodes)
                .ToHashSet(StringComparer.OrdinalIgnoreCase);

            var invalidCodes = normalizedCodes
                .Where(code => !validCodes.Contains(code))
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .ToList();

            if (invalidCodes.Any())
            {
                return Result.Failure(ResultMessages.InvalidAccessCodes(string.Join(", ", invalidCodes)), 400);
            }

            return Result.Success(200);
        }
    }
}