| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using OzonRepositories.Context; |
| | | 3 | | using Services.Authorization.Dtos; |
| | | 4 | | |
| | | 5 | | namespace Services.Authorization.Services; |
| | | 6 | | |
| | | 7 | | public sealed class MenuService : IMenuService |
| | | 8 | | { |
| | | 9 | | private readonly ApplicationDbContext _db; |
| | | 10 | | private readonly IPermissionService _permissions; |
| | | 11 | | |
| | 22 | 12 | | public MenuService(ApplicationDbContext db, IPermissionService permissions) |
| | | 13 | | { |
| | 22 | 14 | | _db = db; |
| | 22 | 15 | | _permissions = permissions; |
| | 22 | 16 | | } |
| | | 17 | | |
| | | 18 | | public async Task<List<MenuItemDto>> GetUserMenuAsync(string userId, CancellationToken ct = default) |
| | | 19 | | { |
| | 23 | 20 | | var bundle = await _permissions.GetUserPermissionsAsync(userId, ct); |
| | 22 | 21 | | var allowedPageIds = bundle.IsSuperAdmin |
| | 22 | 22 | | ? null |
| | 30 | 23 | | : bundle.Pages.Where(p => p.CanView).Select(p => p.PageId).ToHashSet(); |
| | | 24 | | |
| | 22 | 25 | | var pages = await _db.AppPages.AsNoTracking() |
| | 22 | 26 | | .Where(p => p.IsActive && p.IsMenuItem) |
| | 22 | 27 | | .OrderBy(p => p.SortOrder).ThenBy(p => p.DisplayName) |
| | 22 | 28 | | .ToListAsync(ct); |
| | | 29 | | |
| | 22 | 30 | | if (allowedPageIds is not null) |
| | 11 | 31 | | pages = pages.Where(p => allowedPageIds.Contains(p.Id)).ToList(); |
| | | 32 | | |
| | 88 | 33 | | var dict = pages.ToDictionary(p => p.Id, p => new MenuItemDto |
| | 55 | 34 | | { |
| | 55 | 35 | | PageId = p.Id, |
| | 55 | 36 | | Code = p.Code, |
| | 55 | 37 | | DisplayName = p.DisplayName, |
| | 55 | 38 | | Icon = p.Icon, |
| | 55 | 39 | | SortOrder = p.SortOrder, |
| | 55 | 40 | | Url = BuildUrl(p.Area, p.Controller, p.Action) |
| | 55 | 41 | | }); |
| | | 42 | | |
| | 22 | 43 | | var roots = new List<MenuItemDto>(); |
| | 110 | 44 | | foreach (var p in pages) |
| | | 45 | | { |
| | 33 | 46 | | var node = dict[p.Id]; |
| | 33 | 47 | | if (p.ParentId.HasValue && dict.TryGetValue(p.ParentId.Value, out var parent)) |
| | 6 | 48 | | parent.Children.Add(node); |
| | | 49 | | else |
| | 27 | 50 | | roots.Add(node); |
| | | 51 | | } |
| | 22 | 52 | | return roots; |
| | 22 | 53 | | } |
| | | 54 | | |
| | | 55 | | private static string BuildUrl(string? area, string controller, string action) |
| | | 56 | | { |
| | 33 | 57 | | var a = string.IsNullOrWhiteSpace(area) ? string.Empty : "/" + area.Trim('/'); |
| | 33 | 58 | | return $"{a}/{controller}/{action}"; |
| | | 59 | | } |
| | | 60 | | } |