using System.Linq.Expressions; using Fake.Application; using Fake.Domain.Exceptions; using Microsoft.AspNetCore.Mvc; using Oms.Application.Dtos.Approval; using Oms.Application.Dtos.Shared; using Oms.Application.Shared; using Oms.Domain.ApprovalAggregate.Consts; using Oms.Domain.ApprovalAggregate.Entities; using Oms.Domain.ApprovalAggregate.Repositories; namespace Oms.Application.Services.Approval; /// /// 审批定义配置 API。 /// [ApiExplorerSettings(GroupName = "OMS-Approval")] public class ApprovalDefinitionService : ApplicationService { private IApprovalDefinitionRepository DefinitionRepository => LazyServiceProvider.GetRequiredService(); private ApprovalPermissionGuard PermissionGuard => LazyServiceProvider.GetRequiredService(); private ApprovalConditionEvaluator ConditionEvaluator => LazyServiceProvider.GetRequiredService(); private ApprovalCandidateResolver CandidateResolver => LazyServiceProvider.GetRequiredService(); /// /// 分页查询审批定义。 /// [HttpGet("/system/approval/definition/list")] public async Task> GetListAsync( [FromQuery] ApprovalDefinitionListInput input) { await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.DefinitionQuery); var keyword = input.Keyword?.Trim(); Expression> predicate = x => (string.IsNullOrWhiteSpace(keyword) || x.OperationCode.Contains(keyword) || x.OperationName.Contains(keyword)) && (input.IsEnabled == null || x.IsEnabled == input.IsEnabled.Value); var pageIndex = OmsDocHelper.NormalizePage(input.Page); var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize <= 0 ? 50 : input.PageSize); var (items, total) = await RepositoryPageHelper.GetPageAsync( DefinitionRepository, predicate, pageIndex, pageSize, q => q.OrderByDescending(x => x.UpdateTime).ThenByDescending(x => x.Id)); return new OmsPageResult { Items = items.Select(MapOutput).ToList(), Total = total }; } /// /// 查询审批定义详情。 /// [HttpGet("/system/approval/definition/get")] public async Task GetAsync([FromQuery] int id) { await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.DefinitionQuery); var entity = await GetOrThrowAsync(id); return MapOutput(entity); } /// /// 获取可配置操作目录。 /// [HttpGet("/system/approval/operation-catalog")] public async Task> GetCatalogAsync() { await PermissionGuard.EnsureAsync( CurrentUser, ApprovalPermissionCodes.DefinitionQuery, ApprovalPermissionCodes.DefinitionCreate, ApprovalPermissionCodes.DefinitionUpdate); return ApprovalOperationCatalog.All.Select(x => new ApprovalOperationCatalogItemOutput { Code = x.Code, Name = x.Name, Module = x.Module, SupportsCondition = x.SupportsCondition, ConditionHint = x.ConditionHint }).ToList(); } /// /// 新增或更新审批定义。同一 OperationCode 仅允许一条有效定义。 /// [HttpPost("/system/approval/definition/save")] public async Task SaveAsync(ApprovalDefinitionSaveInput input) { var isCreate = !input.Id.HasValue || input.Id.Value <= 0; await PermissionGuard.EnsureAsync( CurrentUser, isCreate ? ApprovalPermissionCodes.DefinitionCreate : ApprovalPermissionCodes.DefinitionUpdate); var operationCode = input.OperationCode?.Trim() ?? string.Empty; if (string.IsNullOrWhiteSpace(operationCode)) { throw new BusinessException("操作编码不能为空"); } if (!ApprovalOperationCatalog.IsKnown(operationCode)) { throw new BusinessException($"未知操作编码:{operationCode}"); } var approverType = NormalizeApproverType(input.ApproverType); var approverIds = ApprovalIdHelper.JoinIds(input.ApproverIds); if (string.IsNullOrWhiteSpace(approverIds)) { throw new BusinessException("审批候选人不能为空"); } // 保存时展开校验,避免角色下无人 await CandidateResolver.ExpandCandidateUserIdsAsync(approverType, approverIds); var formula = string.IsNullOrWhiteSpace(input.ConditionFormula) ? null : input.ConditionFormula.Trim(); ConditionEvaluator.EnsureFormulaAllowed(operationCode, formula); var catalogItem = ApprovalOperationCatalog.Find(operationCode)!; var remark = string.IsNullOrWhiteSpace(input.Remark) ? null : input.Remark.Trim(); if (isCreate) { await EnsureOperationUniqueAsync(operationCode, null); var created = await DefinitionRepository.InsertAsync(new ApprovalDefinition { OperationCode = operationCode, OperationName = catalogItem.Name, IsEnabled = input.IsEnabled, ConditionFormula = formula, ApproverType = approverType, ApproverIds = approverIds, ForbidSelfApprove = input.ForbidSelfApprove, Remark = remark }); return MapOutput(created); } var entity = await GetOrThrowAsync(input.Id!.Value); if (!string.Equals(entity.OperationCode, operationCode, StringComparison.OrdinalIgnoreCase)) { await EnsureOperationUniqueAsync(operationCode, entity.Id); } entity.OperationCode = operationCode; entity.OperationName = catalogItem.Name; entity.IsEnabled = input.IsEnabled; entity.ConditionFormula = formula; entity.ApproverType = approverType; entity.ApproverIds = approverIds; entity.ForbidSelfApprove = input.ForbidSelfApprove; entity.Remark = remark; await DefinitionRepository.UpdateAsync(entity); return MapOutput(entity); } /// /// 启用或停用审批定义。 /// [HttpPost("/system/approval/definition/enable")] public async Task EnableAsync(ApprovalDefinitionEnableInput input) { await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.DefinitionEnable); var entity = await GetOrThrowAsync(input.Id); entity.IsEnabled = input.IsEnabled; await DefinitionRepository.UpdateAsync(entity); } /// /// 删除审批定义(软删)。 /// [HttpPost("/system/approval/definition/delete")] public async Task DeleteAsync(IdInput input) { await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.DefinitionDelete); var entity = await GetOrThrowAsync(input.Id); await DefinitionRepository.DeleteAsync(entity); } /// /// 条件公式试算。 /// [HttpPost("/system/approval/definition/test-condition")] public async Task TestConditionAsync(ApprovalConditionTestInput input) { await PermissionGuard.EnsureAsync( CurrentUser, ApprovalPermissionCodes.DefinitionQuery, ApprovalPermissionCodes.DefinitionUpdate); var (ok, matched, message) = ConditionEvaluator.TryTest( input.OperationCode?.Trim() ?? string.Empty, input.ConditionFormula, input.Context); return new ApprovalConditionTestOutput { Ok = ok, Matched = matched, Message = message }; } private async Task EnsureOperationUniqueAsync(string operationCode, int? excludeId) { var existed = await DefinitionRepository.FirstOrDefaultAsync(x => x.OperationCode == operationCode); if (existed != null && existed.Id != excludeId) { throw new BusinessException($"操作 {operationCode} 已存在审批定义"); } } private async Task GetOrThrowAsync(int id) { var entity = await DefinitionRepository.FirstOrDefaultAsync(x => x.Id == id); if (entity == null) { throw new BusinessException("审批定义不存在"); } return entity; } private static string NormalizeApproverType(string? type) { if (string.Equals(type, ApprovalCodes.ApproverTypeRole, StringComparison.OrdinalIgnoreCase)) { return ApprovalCodes.ApproverTypeRole; } if (string.Equals(type, ApprovalCodes.ApproverTypeUser, StringComparison.OrdinalIgnoreCase)) { return ApprovalCodes.ApproverTypeUser; } throw new BusinessException("审批人类型仅支持 User 或 Role"); } private static ApprovalDefinitionOutput MapOutput(ApprovalDefinition entity) => new() { Id = entity.Id, OperationCode = entity.OperationCode, OperationName = entity.OperationName, IsEnabled = entity.IsEnabled, ConditionFormula = entity.ConditionFormula, ApproverType = entity.ApproverType, ApproverIds = ApprovalIdHelper.SplitIds(entity.ApproverIds), ForbidSelfApprove = entity.ForbidSelfApprove, Remark = entity.Remark, CreateTime = entity.CreateTime, UpdateTime = OmsDocHelper.NullIfDefault(entity.UpdateTime) }; }