sunpengfei
2025-08-06 bc6813b74e9a390eae2181d460c647445b7cb25a
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
using FlexJobApi.Core;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace FlexJobApi.User.Application
{
    /// <summary>
    /// 保存菜单按钮
    /// </summary>
    public class SaveMenuButtonCommandHandler(
            IRepository<Menu> rep
        ) : IRequestHandler<SaveMenuButtonCommand, Guid>
    {
        private readonly IRepository<Menu> rep = rep;
 
        /// <inheritdoc/>
        public async Task<Guid> Handle(SaveMenuButtonCommand request, CancellationToken cancellationToken)
        {
            var parent = await rep.FirstOrDefaultAsync(it => it.Id == request.ParentId);
            if (parent == null) throw Oops.Oh(EnumErrorCodeType.s404, "上级菜单");
            if (request.Id.HasValue)
            {
                var entity = await rep.FirstOrDefaultAsync(it => it.Id == request.Id);
                if (entity == null) throw Oops.Oh(EnumErrorCodeType.s404, "该菜单");
                if (entity.ParentId != request.ParentId) throw Oops.Oh(EnumErrorCodeType.s410, "上级Id");
                request.Adapt(entity);
                if (await CheckExist(entity)) throw Oops.Oh(EnumErrorCodeType.s406, "菜单编号");
                await rep.UpdateAsync(entity);
                return entity.Id;
            }
            else
            {
                var entity = new Menu();
                entity.Path = $"{parent.Path}{parent.Code}/";
                entity.Type = EnumMenuType.Button;
                entity.VisitLevel = parent.VisitLevel;
                request.Adapt(entity);
                if (await CheckExist(entity)) throw Oops.Oh(EnumErrorCodeType.s406, "菜单编号");
                await rep.InsertAsync(entity);
                return entity.Id;
            }
        }
 
        /// <summary>
        /// 校验菜单是否重复
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private async Task<bool> CheckExist(Menu entity)
        {
            return await rep.AsQueryable().AsNoTracking()
                .AnyAsync(it =>
                    it.ParentId == entity.ParentId
                    && it.Type == entity.Type
                    && it.Group == entity.Group
                    && it.Location == entity.Location
                    && it.Code == entity.Code
                    && it.Id != entity.Id);
        }
    }
}