ThRbacMenuAppService.cs
14.7 KB
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
using FoodLabeling.Application.Services.DbModels;
using FoodLabeling.Th.Application.Contracts.Dtos.RbacMenu;
using FoodLabeling.Th.Application.Contracts.IServices;
using FoodLabeling.Th.Domain.Shared.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Yi.Framework.Rbac.Domain.Shared.Enums;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace FoodLabeling.Th.Application.Services;
/// <summary>
/// 泰额版租户业务库 menu 表 CRUD(字符串 Id/ParentId,不使用 TreeHelper)
/// </summary>
[Authorize]
public class ThRbacMenuAppService : ApplicationService, IThRbacMenuAppService
{
private readonly ISqlSugarDbContext _dbContext;
public ThRbacMenuAppService(ISqlSugarDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// 分页查询菜单列表
/// </summary>
/// <remarks>
/// 在当前租户业务库 `menu` 表查询,过滤逻辑删除数据。
///
/// 示例请求:
/// ```json
/// {
/// "skipCount": 0,
/// "maxResultCount": 20,
/// "menuName": "Label",
/// "state": true,
/// "menuSource": 1
/// }
/// ```
///
/// 参数说明:
/// - skipCount: 跳过条数
/// - maxResultCount: 每页条数
/// - menuName: 菜单名称模糊匹配
/// - state: 启用状态
/// - menuSource: 菜单来源(MenuSourceEnum)
/// - menuType: 菜单类型(MenuTypeEnum)
/// </remarks>
/// <param name="input">分页与筛选条件</param>
/// <returns>分页菜单列表</returns>
/// <response code="200">成功返回分页列表</response>
/// <response code="401">未登录</response>
/// <response code="500">服务器错误</response>
[HttpGet("th-rbac-menu/list")]
public virtual async Task<PagedResultDto<ThRbacMenuGetListOutputDto>> GetListAsync([FromQuery] ThRbacMenuGetListInputVo input)
{
RefAsync<int> total = 0;
var query = BuildFilteredQuery(input)
.OrderBy(x => x.OrderNum, OrderByType.Desc);
var entities = await query.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
var items = entities.Select(MapToListDto).ToList();
return new PagedResultDto<ThRbacMenuGetListOutputDto>(total, items);
}
/// <summary>
/// 根据 Id 获取菜单详情
/// </summary>
/// <remarks>
/// 在当前租户业务库按主键查询未删除菜单。
/// </remarks>
/// <param name="id">菜单 Id(字符串)</param>
/// <returns>菜单详情</returns>
/// <response code="200">成功返回菜单</response>
/// <response code="400">菜单不存在</response>
/// <response code="401">未登录</response>
/// <response code="500">服务器错误</response>
[HttpGet("th-rbac-menu/{id}")]
public virtual async Task<ThRbacMenuGetListOutputDto> GetAsync(string id)
{
var entity = await FindActiveMenuAsync(id);
return MapToListDto(entity);
}
/// <summary>
/// 新增菜单
/// </summary>
/// <remarks>
/// 写入当前租户业务库 `menu` 表;Id 使用雪花算法字符串。
///
/// 示例请求:
/// ```json
/// {
/// "menuName": "Settings",
/// "parentId": "0",
/// "menuType": 1,
/// "menuSource": 2,
/// "router": "/settings",
/// "orderNum": 10,
/// "state": true
/// }
/// ```
///
/// 参数说明:
/// - menuName: 菜单名称(必填)
/// - parentId: 父级 Id,根节点为 0
/// - menuType: 菜单类型(MenuTypeEnum)
/// - menuSource: 菜单来源(MenuSourceEnum)
/// </remarks>
/// <param name="input">新增菜单入参</param>
/// <returns>新建菜单详情</returns>
/// <response code="200">创建成功</response>
/// <response code="400">参数校验失败</response>
/// <response code="401">未登录</response>
/// <response code="500">服务器错误</response>
[HttpPost("th-rbac-menu")]
public virtual async Task<ThRbacMenuGetListOutputDto> CreateAsync([FromBody] ThRbacMenuCreateInputVo input)
{
var name = input.MenuName?.Trim();
if (string.IsNullOrWhiteSpace(name))
{
throw new UserFriendlyException("菜单名称不能为空");
}
var parentId = NormalizeParentId(input.ParentId);
await EnsureParentExistsAsync(parentId);
var entity = new MenuDbEntity
{
Id = YitIdHelper.NextId().ToString(),
MenuName = name,
ParentId = parentId,
MenuType = (int)input.MenuType,
MenuSource = (int)input.MenuSource,
PermissionCode = input.PermissionCode?.Trim(),
Router = input.Router?.Trim(),
RouterName = input.RouterName?.Trim(),
Component = input.Component?.Trim(),
MenuIcon = input.MenuIcon?.Trim(),
OrderNum = input.OrderNum,
State = input.State,
IsDeleted = false,
CreationTime = DateTime.Now,
IsCache = false,
IsLink = false,
IsShow = input.IsShow,
ConcurrencyStamp = string.Empty
};
await _dbContext.SqlSugarClient.Insertable(entity).ExecuteCommandAsync();
return await GetAsync(entity.Id);
}
/// <summary>
/// 编辑菜单
/// </summary>
/// <remarks>
/// 更新当前租户业务库中指定 Id 的菜单;禁止将 ParentId 设为自身。
///
/// 示例请求:
/// ```json
/// {
/// "menuName": "Settings",
/// "parentId": "0",
/// "menuType": 1,
/// "menuSource": 2,
/// "orderNum": 20,
/// "state": true
/// }
/// ```
/// </remarks>
/// <param name="id">菜单 Id</param>
/// <param name="input">编辑入参</param>
/// <returns>更新后的菜单详情</returns>
/// <response code="200">更新成功</response>
/// <response code="400">参数错误或菜单不存在</response>
/// <response code="401">未登录</response>
/// <response code="500">服务器错误</response>
[HttpPut("th-rbac-menu/{id}")]
public virtual async Task<ThRbacMenuGetListOutputDto> UpdateAsync(string id, [FromBody] ThRbacMenuUpdateInputVo input)
{
var entity = await FindActiveMenuAsync(id);
var name = input.MenuName?.Trim();
if (string.IsNullOrWhiteSpace(name))
{
throw new UserFriendlyException("菜单名称不能为空");
}
var parentId = NormalizeParentId(input.ParentId);
if (string.Equals(parentId, id, StringComparison.Ordinal))
{
throw new UserFriendlyException("父级菜单不能为自身");
}
await EnsureParentExistsAsync(parentId, id);
entity.MenuName = name;
entity.ParentId = parentId;
entity.MenuType = (int)input.MenuType;
entity.MenuSource = (int)input.MenuSource;
entity.PermissionCode = input.PermissionCode?.Trim();
entity.Router = input.Router?.Trim();
entity.RouterName = input.RouterName?.Trim();
entity.Component = input.Component?.Trim();
entity.MenuIcon = input.MenuIcon?.Trim();
entity.OrderNum = input.OrderNum;
entity.State = input.State;
entity.IsShow = input.IsShow;
entity.LastModificationTime = DateTime.Now;
await _dbContext.SqlSugarClient.Updateable(entity)
.Where(x => x.Id == entity.Id)
.ExecuteCommandAsync();
return await GetAsync(entity.Id);
}
/// <summary>
/// 批量删除菜单(逻辑删除)
/// </summary>
/// <remarks>
/// 将指定 Id 列表对应菜单标记为 IsDeleted=true。
///
/// 示例请求:
/// ```json
/// ["1234567890123456789", "9876543210987654321"]
/// ```
///
/// 参数说明:
/// - ids: 待删除菜单 Id 数组
/// </remarks>
/// <param name="ids">菜单 Id 列表</param>
/// <returns>无内容</returns>
/// <response code="200">删除成功</response>
/// <response code="401">未登录</response>
/// <response code="500">服务器错误</response>
[HttpDelete("th-rbac-menu")]
public virtual async Task DeleteAsync([FromBody] List<string> ids)
{
var idList = ids?
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => x.Trim())
.Distinct(StringComparer.Ordinal)
.ToList() ?? new List<string>();
if (idList.Count == 0)
{
return;
}
await _dbContext.SqlSugarClient.Updateable<MenuDbEntity>()
.SetColumns(x => new MenuDbEntity { IsDeleted = true, LastModificationTime = DateTime.Now })
.Where(x => idList.Contains(x.Id) && x.IsDeleted == false)
.ExecuteCommandAsync();
}
/// <summary>
/// 获取全部菜单树
/// </summary>
/// <remarks>
/// 返回当前租户业务库全部未删除菜单,按 ParentId 字符串组树(不使用 Guid TreeHelper)。
/// 树节点按 OrderNum 降序排序。
/// </remarks>
/// <returns>根节点菜单树</returns>
/// <response code="200">成功返回菜单树</response>
/// <response code="401">未登录</response>
/// <response code="500">服务器错误</response>
[HttpGet("th-rbac-menu/tree")]
public virtual async Task<List<ThRbacMenuTreeDto>> GetTreeAsync()
{
var menus = await _dbContext.SqlSugarClient.Queryable<MenuDbEntity>()
.Where(x => x.IsDeleted == false)
.OrderBy(x => x.OrderNum, OrderByType.Desc)
.ToListAsync();
var nodes = menus.Select(MapToTreeDto).ToList();
return BuildMenuTree(nodes);
}
private ISugarQueryable<MenuDbEntity> BuildFilteredQuery(ThRbacMenuGetListInputVo input)
{
return _dbContext.SqlSugarClient.Queryable<MenuDbEntity>()
.Where(x => x.IsDeleted == false)
.WhereIF(!string.IsNullOrWhiteSpace(input.MenuName), x => x.MenuName.Contains(input.MenuName!.Trim()))
.WhereIF(input.State is not null, x => x.State == input.State)
.WhereIF(input.MenuSource is not null, x => x.MenuSource == (int)input.MenuSource!.Value)
.WhereIF(input.MenuType is not null, x => x.MenuType == (int)input.MenuType!.Value);
}
private async Task<MenuDbEntity> FindActiveMenuAsync(string id)
{
if (string.IsNullOrWhiteSpace(id))
{
throw new UserFriendlyException("菜单 Id 不能为空");
}
var entity = await _dbContext.SqlSugarClient.Queryable<MenuDbEntity>()
.Where(x => x.Id == id.Trim() && x.IsDeleted == false)
.SingleAsync();
if (entity is null)
{
throw new UserFriendlyException("菜单不存在");
}
return entity;
}
private async Task EnsureParentExistsAsync(string parentId, string? currentId = null)
{
if (IsRootParentId(parentId))
{
return;
}
var parent = await _dbContext.SqlSugarClient.Queryable<MenuDbEntity>()
.Where(x => x.Id == parentId && x.IsDeleted == false)
.SingleAsync();
if (parent is null)
{
throw new UserFriendlyException("父级菜单不存在");
}
if (currentId is not null && string.Equals(parent.ParentId, currentId, StringComparison.Ordinal))
{
throw new UserFriendlyException("不能将菜单移动到其子节点下");
}
}
private static string NormalizeParentId(string? parentId)
{
return string.IsNullOrWhiteSpace(parentId) ? "0" : parentId.Trim();
}
private static bool IsRootParentId(string parentId)
{
return parentId == "0" || parentId == "00000000-0000-0000-0000-000000000000";
}
private static ThRbacMenuGetListOutputDto MapToListDto(MenuDbEntity x)
{
return new ThRbacMenuGetListOutputDto
{
Id = x.Id,
ParentId = x.ParentId,
MenuName = x.MenuName ?? string.Empty,
RouterName = x.RouterName,
Router = x.Router,
PermissionCode = x.PermissionCode,
MenuType = (MenuTypeEnum)x.MenuType,
MenuSource = (MenuSourceEnum)x.MenuSource,
OrderNum = x.OrderNum,
State = x.State
};
}
private static ThRbacMenuTreeDto MapToTreeDto(MenuDbEntity m)
{
return new ThRbacMenuTreeDto
{
Id = m.Id,
IsDeleted = m.IsDeleted,
CreationTime = m.CreationTime,
CreatorId = m.CreatorId,
LastModifierId = m.LastModifierId,
LastModificationTime = m.LastModificationTime,
OrderNum = m.OrderNum,
State = m.State,
MenuName = m.MenuName ?? string.Empty,
RouterName = m.RouterName,
MenuType = (MenuTypeEnum)m.MenuType,
PermissionCode = m.PermissionCode,
ParentId = m.ParentId,
MenuIcon = m.MenuIcon,
Router = m.Router,
IsLink = m.IsLink,
IsCache = m.IsCache,
IsShow = m.IsShow,
Remark = m.Remark,
Component = m.Component,
MenuSource = (MenuSourceEnum)m.MenuSource,
Query = m.Query,
ConcurrencyStamp = m.ConcurrencyStamp,
Children = new List<ThRbacMenuTreeDto>()
};
}
private static List<ThRbacMenuTreeDto> BuildMenuTree(List<ThRbacMenuTreeDto> nodes)
{
var nodeById = nodes
.Where(x => !string.IsNullOrWhiteSpace(x.Id))
.GroupBy(x => x.Id)
.ToDictionary(g => g.Key, g => g.First());
foreach (var node in nodes)
{
node.Children ??= new List<ThRbacMenuTreeDto>();
var parentId = NormalizeParentId(node.ParentId);
if (IsRootParentId(parentId))
{
continue;
}
if (nodeById.TryGetValue(parentId, out var parent))
{
parent.Children ??= new List<ThRbacMenuTreeDto>();
parent.Children.Add(node);
}
}
var roots = nodes
.Where(n =>
{
var pid = NormalizeParentId(n.ParentId);
return IsRootParentId(pid) || !nodeById.ContainsKey(pid);
})
.ToList();
SortTree(roots);
return roots;
}
private static void SortTree(List<ThRbacMenuTreeDto> nodes)
{
nodes.Sort((a, b) => b.OrderNum.CompareTo(a.OrderNum));
foreach (var node in nodes)
{
if (node.Children is { Count: > 0 })
{
SortTree(node.Children);
}
}
}
}