feat: 新增单级可配置审批引擎与配置/待办 API
All checks were successful
Build and Deploy / deploy (push) Successful in 1m18s
All checks were successful
Build and Deploy / deploy (push) Successful in 1m18s
一期落地定义、实例、任务、事件及模拟提交通路,业务接入后续再挂 Operation Adapter。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
2984b9c885
commit
649b84c1b0
151
sql/migrate_approval_engine_20261107.sql
Normal file
151
sql/migrate_approval_engine_20261107.sql
Normal file
@ -0,0 +1,151 @@
|
||||
-- =============================================================================
|
||||
-- migrate_approval_engine_20261107.sql
|
||||
-- 单级可配置审批引擎:定义 / 实例 / 任务 / 事件
|
||||
-- 审计字段对齐 t_outbound_record(定死):
|
||||
-- IsDeleted TINYINT NOT NULL DEFAULT 0
|
||||
-- ConcurrencyStamp CHAR(36) NOT NULL DEFAULT (UUID())
|
||||
-- CreateUserId INT NOT NULL DEFAULT 0
|
||||
-- CreateTime DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
-- UpdateUserId INT NULL
|
||||
-- UpdateTime DATETIME NULL
|
||||
-- 禁止 UNIQUE KEY;业务唯一性(OperationCode)在 Application 校验。可重复执行。
|
||||
-- =============================================================================
|
||||
SET @db := DATABASE();
|
||||
|
||||
-- ---------- t_approval_definition ----------
|
||||
SET @tbl := (
|
||||
SELECT COUNT(1) FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_approval_definition'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@tbl = 0,
|
||||
'CREATE TABLE `t_approval_definition` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
|
||||
`OperationCode` VARCHAR(128) NOT NULL COMMENT ''操作编码,如 Finance.Recharge.Credit'',
|
||||
`OperationName` VARCHAR(128) NOT NULL DEFAULT '''' COMMENT ''操作显示名快照'',
|
||||
`IsEnabled` TINYINT NOT NULL DEFAULT 1 COMMENT ''是否启用:0-否,1-是'',
|
||||
`ConditionFormula` VARCHAR(2000) NULL COMMENT ''触发条件公式,空表示启用即始终需审'',
|
||||
`ApproverType` VARCHAR(16) NOT NULL DEFAULT ''User'' COMMENT ''审批人类型:User/Role'',
|
||||
`ApproverIds` VARCHAR(2000) NOT NULL DEFAULT '''' COMMENT ''候选人 ID,逗号分隔(User=Guid,Role=Guid)'',
|
||||
`ForbidSelfApprove` TINYINT NOT NULL DEFAULT 1 COMMENT ''禁止申请人自审:0-否,1-是'',
|
||||
`Remark` VARCHAR(512) NULL COMMENT ''备注'',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
|
||||
`UpdateUserId` INT NULL COMMENT ''更新人'',
|
||||
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_approval_def_op` (`OperationCode`),
|
||||
KEY `ix_approval_def_enabled` (`IsEnabled`)
|
||||
) COMMENT=''审批定义(单级,按操作编码配置)''',
|
||||
'SELECT ''t_approval_definition already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- t_approval_instance ----------
|
||||
SET @tbl := (
|
||||
SELECT COUNT(1) FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_approval_instance'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@tbl = 0,
|
||||
'CREATE TABLE `t_approval_instance` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
|
||||
`InstanceNo` VARCHAR(32) NOT NULL COMMENT ''实例单号'',
|
||||
`OperationCode` VARCHAR(128) NOT NULL COMMENT ''操作编码'',
|
||||
`BizKey` VARCHAR(128) NOT NULL COMMENT ''业务幂等键'',
|
||||
`Title` VARCHAR(256) NOT NULL DEFAULT '''' COMMENT ''摘要标题'',
|
||||
`Status` TINYINT NOT NULL DEFAULT 1 COMMENT ''1Pending/2Approved/3Rejected/4Withdrawn/5Executing/6Executed/7ExecuteFailed'',
|
||||
`ApplicantUserId` INT NOT NULL DEFAULT 0 COMMENT ''申请人 mapId'',
|
||||
`ApplicantUserGuid` CHAR(36) NOT NULL DEFAULT '''' COMMENT ''申请人 RBAC Guid'',
|
||||
`ApplicantUserName` VARCHAR(64) NULL COMMENT ''申请人显示名'',
|
||||
`PayloadJson` MEDIUMTEXT NULL COMMENT ''冻结业务载荷 JSON'',
|
||||
`PayloadHash` VARCHAR(64) NULL COMMENT ''载荷哈希'',
|
||||
`SummaryJson` VARCHAR(2000) NULL COMMENT ''展示用摘要 JSON'',
|
||||
`DefinitionSnapshot` MEDIUMTEXT NULL COMMENT ''提交时定义快照 JSON'',
|
||||
`CurrentTaskId` INT NULL COMMENT ''当前任务 Id'',
|
||||
`CompletedTime` DATETIME NULL COMMENT ''终审完成时间'',
|
||||
`ExecutedTime` DATETIME NULL COMMENT ''业务执行完成时间'',
|
||||
`ExecuteMessage` VARCHAR(1000) NULL COMMENT ''执行结果/失败信息'',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
|
||||
`UpdateUserId` INT NULL COMMENT ''更新人'',
|
||||
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_approval_inst_no` (`InstanceNo`),
|
||||
KEY `ix_approval_inst_op_biz` (`OperationCode`, `BizKey`),
|
||||
KEY `ix_approval_inst_status` (`Status`),
|
||||
KEY `ix_approval_inst_applicant` (`ApplicantUserId`)
|
||||
) COMMENT=''审批实例''',
|
||||
'SELECT ''t_approval_instance already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- t_approval_task ----------
|
||||
SET @tbl := (
|
||||
SELECT COUNT(1) FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_approval_task'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@tbl = 0,
|
||||
'CREATE TABLE `t_approval_task` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
|
||||
`InstanceId` INT NOT NULL COMMENT ''审批实例 Id'',
|
||||
`StepNo` INT NOT NULL DEFAULT 1 COMMENT ''步骤号,一期固定 1'',
|
||||
`Status` TINYINT NOT NULL DEFAULT 1 COMMENT ''1Pending/2Approved/3Rejected/4Cancelled'',
|
||||
`ApproverType` VARCHAR(16) NOT NULL DEFAULT ''User'' COMMENT ''审批人类型快照'',
|
||||
`ApproverIds` VARCHAR(2000) NOT NULL DEFAULT '''' COMMENT ''配置候选人快照'',
|
||||
`CandidateUserIds` VARCHAR(4000) NOT NULL DEFAULT '''' COMMENT ''展开后的可审用户 Guid,逗号分隔'',
|
||||
`ActionUserId` INT NULL COMMENT ''实际处理人 mapId'',
|
||||
`ActionUserGuid` CHAR(36) NULL COMMENT ''实际处理人 Guid'',
|
||||
`ActionUserName` VARCHAR(64) NULL COMMENT ''实际处理人显示名'',
|
||||
`ActionTime` DATETIME NULL COMMENT ''处理时间'',
|
||||
`Comment` VARCHAR(1000) NULL COMMENT ''审批意见'',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
|
||||
`UpdateUserId` INT NULL COMMENT ''更新人'',
|
||||
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_approval_task_inst` (`InstanceId`),
|
||||
KEY `ix_approval_task_status` (`Status`)
|
||||
) COMMENT=''审批任务(单级)''',
|
||||
'SELECT ''t_approval_task already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- t_approval_event ----------
|
||||
SET @tbl := (
|
||||
SELECT COUNT(1) FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_approval_event'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@tbl = 0,
|
||||
'CREATE TABLE `t_approval_event` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
|
||||
`InstanceId` INT NOT NULL COMMENT ''审批实例 Id'',
|
||||
`TaskId` INT NULL COMMENT ''关联任务 Id'',
|
||||
`EventType` VARCHAR(32) NOT NULL COMMENT ''Submitted/Approved/Rejected/Withdrawn/Executing/Executed/ExecuteFailed'',
|
||||
`FromStatus` TINYINT NULL COMMENT ''变更前实例状态'',
|
||||
`ToStatus` TINYINT NULL COMMENT ''变更后实例状态'',
|
||||
`OperatorUserId` INT NOT NULL DEFAULT 0 COMMENT ''操作人 mapId'',
|
||||
`OperatorUserGuid` CHAR(36) NULL COMMENT ''操作人 Guid'',
|
||||
`OperatorUserName` VARCHAR(64) NULL COMMENT ''操作人显示名'',
|
||||
`Message` VARCHAR(1000) NULL COMMENT ''事件说明/意见'',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
|
||||
`UpdateUserId` INT NULL COMMENT ''更新人'',
|
||||
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_approval_event_inst` (`InstanceId`),
|
||||
KEY `ix_approval_event_type` (`EventType`)
|
||||
) COMMENT=''审批事件(追加写)''',
|
||||
'SELECT ''t_approval_event already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
13
sql/smoke_approval_engine_checklist.md
Normal file
13
sql/smoke_approval_engine_checklist.md
Normal file
@ -0,0 +1,13 @@
|
||||
# 审批引擎一期联调清单
|
||||
|
||||
1. 在 OMS 库执行 `migrate_approval_engine_20261107.sql`。
|
||||
2. 重启 SimpleAdmin.Api(触发 `ApprovalRolePermissionSeedContributor` 合并 Admin 权限码)。
|
||||
3. 前端打开 **系统管理 → 审批配置**:
|
||||
- 新增:`System.Approval.Simulate`,审批人选**另一位用户**(若选自己请关闭「禁止自审」),启用。
|
||||
- 点击「模拟提交」,应返回 `PendingApproval` + 实例单号。
|
||||
4. 用审批人账号打开 **审批待办**:
|
||||
- 「待我审批」可见该单 → 通过 / 驳回。
|
||||
- 详情抽屉可见事件:`Submitted` → `Approved`/`Rejected` →(通过时)`Executing` → `Executed`。
|
||||
5. 申请人账号在「我发起的」可撤回 Pending 单。
|
||||
|
||||
业务接入见 `src/Oms.Application/Services/Approval/README.md`。
|
||||
257
src/Oms.Application/Dtos/Approval/ApprovalDtos.cs
Normal file
257
src/Oms.Application/Dtos/Approval/ApprovalDtos.cs
Normal file
@ -0,0 +1,257 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Oms.Domain.ApprovalAggregate.Enums;
|
||||
|
||||
namespace Oms.Application.Dtos.Approval;
|
||||
|
||||
/// <summary>审批定义列表查询。</summary>
|
||||
public class ApprovalDefinitionListInput
|
||||
{
|
||||
/// <summary>页码,从 1 开始。</summary>
|
||||
public int Page { get; set; } = 1;
|
||||
|
||||
/// <summary>每页条数。</summary>
|
||||
public int PageSize { get; set; } = 50;
|
||||
|
||||
/// <summary>关键词(操作编码/名称)。</summary>
|
||||
public string? Keyword { get; set; }
|
||||
|
||||
/// <summary>是否启用筛选。</summary>
|
||||
public bool? IsEnabled { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>审批定义保存入参。</summary>
|
||||
public class ApprovalDefinitionSaveInput
|
||||
{
|
||||
/// <summary>主键;空或 0 表示新增。</summary>
|
||||
public int? Id { get; set; }
|
||||
|
||||
/// <summary>操作编码。</summary>
|
||||
[Required]
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>是否启用。</summary>
|
||||
public bool IsEnabled { get; set; } = true;
|
||||
|
||||
/// <summary>触发条件公式;空表示始终需审。</summary>
|
||||
public string? ConditionFormula { get; set; }
|
||||
|
||||
/// <summary>审批人类型:User / Role。</summary>
|
||||
[Required]
|
||||
public string ApproverType { get; set; } = "User";
|
||||
|
||||
/// <summary>候选人 Guid 列表。</summary>
|
||||
public List<string> ApproverIds { get; set; } = [];
|
||||
|
||||
/// <summary>禁止申请人自审。</summary>
|
||||
public bool ForbidSelfApprove { get; set; } = true;
|
||||
|
||||
/// <summary>备注。</summary>
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>启停入参。</summary>
|
||||
public class ApprovalDefinitionEnableInput
|
||||
{
|
||||
/// <summary>定义主键。</summary>
|
||||
[Required]
|
||||
public int Id { get; set; }
|
||||
|
||||
/// <summary>是否启用。</summary>
|
||||
public bool IsEnabled { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>审批定义输出。</summary>
|
||||
public class ApprovalDefinitionOutput
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
public string OperationName { get; set; } = string.Empty;
|
||||
|
||||
public bool IsEnabled { get; set; }
|
||||
|
||||
public string? ConditionFormula { get; set; }
|
||||
|
||||
public string ApproverType { get; set; } = "User";
|
||||
|
||||
public List<string> ApproverIds { get; set; } = [];
|
||||
|
||||
public bool ForbidSelfApprove { get; set; }
|
||||
|
||||
public string? Remark { get; set; }
|
||||
|
||||
public DateTime CreateTime { get; set; }
|
||||
|
||||
public DateTime? UpdateTime { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>操作目录项输出。</summary>
|
||||
public class ApprovalOperationCatalogItemOutput
|
||||
{
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
public string Module { get; set; } = string.Empty;
|
||||
|
||||
public bool SupportsCondition { get; set; }
|
||||
|
||||
public string ConditionHint { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>条件试算入参。</summary>
|
||||
public class ApprovalConditionTestInput
|
||||
{
|
||||
/// <summary>操作编码。</summary>
|
||||
[Required]
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>条件公式。</summary>
|
||||
public string? ConditionFormula { get; set; }
|
||||
|
||||
/// <summary>上下文字典。</summary>
|
||||
public Dictionary<string, object?>? Context { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>条件试算结果。</summary>
|
||||
public class ApprovalConditionTestOutput
|
||||
{
|
||||
public bool Ok { get; set; }
|
||||
|
||||
public bool Matched { get; set; }
|
||||
|
||||
public string? Message { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>实例列表查询。</summary>
|
||||
public class ApprovalInstanceListInput
|
||||
{
|
||||
public int Page { get; set; } = 1;
|
||||
|
||||
public int PageSize { get; set; } = 50;
|
||||
|
||||
/// <summary>关键词(单号/标题/操作码)。</summary>
|
||||
public string? Keyword { get; set; }
|
||||
|
||||
/// <summary>状态筛选。</summary>
|
||||
public ApprovalInstanceStatus? Status { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>提交/模拟提交入参。</summary>
|
||||
public class ApprovalSubmitInput
|
||||
{
|
||||
/// <summary>操作编码。</summary>
|
||||
[Required]
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>业务幂等键;空则自动生成。</summary>
|
||||
public string? BizKey { get; set; }
|
||||
|
||||
/// <summary>标题。</summary>
|
||||
public string? Title { get; set; }
|
||||
|
||||
/// <summary>载荷 JSON 字符串或对象。</summary>
|
||||
public object? Payload { get; set; }
|
||||
|
||||
/// <summary>摘要对象。</summary>
|
||||
public object? Summary { get; set; }
|
||||
|
||||
/// <summary>条件上下文。</summary>
|
||||
public Dictionary<string, object?>? ConditionContext { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>审批动作入参。</summary>
|
||||
public class ApprovalActionInput
|
||||
{
|
||||
/// <summary>实例 Id。</summary>
|
||||
[Required]
|
||||
public int InstanceId { get; set; }
|
||||
|
||||
/// <summary>意见;驳回必填。</summary>
|
||||
public string? Comment { get; set; }
|
||||
|
||||
/// <summary>并发戳(可选)。</summary>
|
||||
public string? ConcurrencyStamp { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>实例列表/详情输出。</summary>
|
||||
public class ApprovalInstanceOutput
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public string InstanceNo { get; set; } = string.Empty;
|
||||
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
public string BizKey { get; set; } = string.Empty;
|
||||
|
||||
public string Title { get; set; } = string.Empty;
|
||||
|
||||
public ApprovalInstanceStatus Status { get; set; }
|
||||
|
||||
public string StatusName { get; set; } = string.Empty;
|
||||
|
||||
public int ApplicantUserId { get; set; }
|
||||
|
||||
public string ApplicantUserGuid { get; set; } = string.Empty;
|
||||
|
||||
public string? ApplicantUserName { get; set; }
|
||||
|
||||
public string? PayloadJson { get; set; }
|
||||
|
||||
public string? SummaryJson { get; set; }
|
||||
|
||||
public string? DefinitionSnapshot { get; set; }
|
||||
|
||||
public int? CurrentTaskId { get; set; }
|
||||
|
||||
public DateTime CreateTime { get; set; }
|
||||
|
||||
public DateTime? CompletedTime { get; set; }
|
||||
|
||||
public DateTime? ExecutedTime { get; set; }
|
||||
|
||||
public string? ExecuteMessage { get; set; }
|
||||
|
||||
public string? ConcurrencyStamp { get; set; }
|
||||
|
||||
/// <summary>当前用户是否可审批该待办。</summary>
|
||||
public bool CanApprove { get; set; }
|
||||
|
||||
/// <summary>当前用户是否可撤回。</summary>
|
||||
public bool CanWithdraw { get; set; }
|
||||
|
||||
public List<ApprovalEventOutput> Events { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>事件输出。</summary>
|
||||
public class ApprovalEventOutput
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public string EventType { get; set; } = string.Empty;
|
||||
|
||||
public ApprovalInstanceStatus? FromStatus { get; set; }
|
||||
|
||||
public ApprovalInstanceStatus? ToStatus { get; set; }
|
||||
|
||||
public string? OperatorUserName { get; set; }
|
||||
|
||||
public string? Message { get; set; }
|
||||
|
||||
public DateTime CreateTime { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>提交结果。</summary>
|
||||
public class ApprovalSubmitOutput
|
||||
{
|
||||
/// <summary>Bypass / PendingApproval。</summary>
|
||||
public string Decision { get; set; } = string.Empty;
|
||||
|
||||
public int? InstanceId { get; set; }
|
||||
|
||||
public string? InstanceNo { get; set; }
|
||||
|
||||
public string? Message { get; set; }
|
||||
}
|
||||
@ -0,0 +1,68 @@
|
||||
using Fake.Application;
|
||||
using Fake.DependencyInjection;
|
||||
using Fake.Domain.Exceptions;
|
||||
using Oms.Application.DataPerm;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 将定义中的角色/用户候选人展开为可审用户 Guid 列表。
|
||||
/// </summary>
|
||||
public class ApprovalCandidateResolver(DataPermRepository dataPermRepository) : IScopedDependency
|
||||
{
|
||||
/// <summary>
|
||||
/// 展开候选人;User 类型直接返回 Guid;Role 类型展开成员。
|
||||
/// </summary>
|
||||
public async Task<List<string>> ExpandCandidateUserIdsAsync(
|
||||
string approverType,
|
||||
string approverIds,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var ids = ApprovalIdHelper.SplitIds(approverIds);
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
throw new BusinessException("审批候选人不能为空");
|
||||
}
|
||||
|
||||
if (string.Equals(approverType, ApprovalCodes.ApproverTypeUser, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
foreach (var id in ids)
|
||||
{
|
||||
if (!Guid.TryParse(id, out _))
|
||||
{
|
||||
throw new BusinessException($"用户候选人 Id 无效:{id}");
|
||||
}
|
||||
}
|
||||
|
||||
return ids;
|
||||
}
|
||||
|
||||
if (!string.Equals(approverType, ApprovalCodes.ApproverTypeRole, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new BusinessException("审批人类型仅支持 User 或 Role");
|
||||
}
|
||||
|
||||
var userIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var roleIdText in ids)
|
||||
{
|
||||
if (!Guid.TryParse(roleIdText, out var roleId))
|
||||
{
|
||||
throw new BusinessException($"角色候选人 Id 无效:{roleIdText}");
|
||||
}
|
||||
|
||||
var members = await dataPermRepository.GetUserIdsByRoleAsync(roleId, cancellationToken);
|
||||
foreach (var uid in members)
|
||||
{
|
||||
userIds.Add(uid.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
if (userIds.Count == 0)
|
||||
{
|
||||
throw new BusinessException("所选角色下没有可审批用户");
|
||||
}
|
||||
|
||||
return userIds.ToList();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,348 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using Fake.Application;
|
||||
using Fake.DependencyInjection;
|
||||
using Fake.Domain.Exceptions;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 审批条件求值:空公式视为命中;非空需操作支持条件,并用简易比较表达式求值。
|
||||
/// 一期支持:标签 比较符 数字/字符串,以及 && || ! 与括号;与自动触发公式子集对齐。
|
||||
/// </summary>
|
||||
public class ApprovalConditionEvaluator(IEnumerable<IApprovalConditionContextFactory> factories) : IScopedDependency
|
||||
{
|
||||
private readonly Dictionary<string, IApprovalConditionContextFactory> _factories = factories
|
||||
.GroupBy(x => x.OperationCode, StringComparer.OrdinalIgnoreCase)
|
||||
.ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// 校验公式是否允许保存。
|
||||
/// </summary>
|
||||
public void EnsureFormulaAllowed(string operationCode, string? formula)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(formula))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var item = ApprovalOperationCatalog.Find(operationCode);
|
||||
if (item is { SupportsCondition: false } && !_factories.ContainsKey(operationCode))
|
||||
{
|
||||
throw new BusinessException($"操作 {operationCode} 暂不支持条件公式,请留空");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 求值是否命中需审条件。空公式返回 true。
|
||||
/// </summary>
|
||||
public bool Evaluate(
|
||||
string operationCode,
|
||||
string? formula,
|
||||
IReadOnlyDictionary<string, object?>? rawContext)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(formula))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
IReadOnlyDictionary<string, object?> context = rawContext ?? new Dictionary<string, object?>();
|
||||
if (_factories.TryGetValue(operationCode, out var factory))
|
||||
{
|
||||
context = factory.Build(rawContext);
|
||||
}
|
||||
|
||||
if (!TryEvaluate(formula, context, out var matched, out var error))
|
||||
{
|
||||
throw new BusinessException(error ?? "条件公式求值失败");
|
||||
}
|
||||
|
||||
return matched;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 试算(不抛业务异常,返回消息)。
|
||||
/// </summary>
|
||||
public (bool Ok, bool Matched, string? Message) TryTest(
|
||||
string operationCode,
|
||||
string? formula,
|
||||
IReadOnlyDictionary<string, object?>? rawContext)
|
||||
{
|
||||
try
|
||||
{
|
||||
EnsureFormulaAllowed(operationCode, formula);
|
||||
var matched = Evaluate(operationCode, formula, rawContext);
|
||||
return (true, matched, matched ? "条件命中(需审批)" : "条件未命中(可不审批)");
|
||||
}
|
||||
catch (BusinessException ex)
|
||||
{
|
||||
return (false, false, ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return (false, false, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryEvaluate(
|
||||
string expression,
|
||||
IReadOnlyDictionary<string, object?> context,
|
||||
out bool result,
|
||||
out string? error)
|
||||
{
|
||||
result = false;
|
||||
error = null;
|
||||
try
|
||||
{
|
||||
var parser = new SimpleParser(expression.Trim(), context);
|
||||
result = parser.ParseExpression();
|
||||
parser.ExpectEnd();
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class SimpleParser(string source, IReadOnlyDictionary<string, object?> context)
|
||||
{
|
||||
private int _pos;
|
||||
|
||||
public bool ParseExpression() => ParseOr();
|
||||
|
||||
public void ExpectEnd()
|
||||
{
|
||||
SkipWs();
|
||||
if (_pos < source.Length)
|
||||
{
|
||||
throw new InvalidOperationException($"条件公式存在无法解析内容:{source[_pos..]}");
|
||||
}
|
||||
}
|
||||
|
||||
private bool ParseOr()
|
||||
{
|
||||
var left = ParseAnd();
|
||||
while (MatchKeyword("||") || MatchKeyword("或"))
|
||||
{
|
||||
var right = ParseAnd();
|
||||
left = left || right;
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
private bool ParseAnd()
|
||||
{
|
||||
var left = ParseUnary();
|
||||
while (MatchKeyword("&&") || MatchKeyword("且"))
|
||||
{
|
||||
var right = ParseUnary();
|
||||
left = left && right;
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
private bool ParseUnary()
|
||||
{
|
||||
if (MatchKeyword("!") || MatchKeyword("非"))
|
||||
{
|
||||
return !ParseUnary();
|
||||
}
|
||||
|
||||
return ParsePrimary();
|
||||
}
|
||||
|
||||
private bool ParsePrimary()
|
||||
{
|
||||
SkipWs();
|
||||
if (Match('('))
|
||||
{
|
||||
var inner = ParseExpression();
|
||||
if (!Match(')'))
|
||||
{
|
||||
throw new InvalidOperationException("条件公式缺少右括号");
|
||||
}
|
||||
|
||||
return inner;
|
||||
}
|
||||
|
||||
var label = ReadLabel();
|
||||
SkipWs();
|
||||
if (MatchKeyword("有值"))
|
||||
{
|
||||
return HasValue(Resolve(label));
|
||||
}
|
||||
|
||||
if (MatchKeyword("为空"))
|
||||
{
|
||||
return !HasValue(Resolve(label));
|
||||
}
|
||||
|
||||
if (MatchKeyword("包含"))
|
||||
{
|
||||
if (!Match('('))
|
||||
{
|
||||
throw new InvalidOperationException("包含(...) 语法错误");
|
||||
}
|
||||
|
||||
var needle = ReadStringOrNumber();
|
||||
if (!Match(')'))
|
||||
{
|
||||
throw new InvalidOperationException("包含(...) 缺少右括号");
|
||||
}
|
||||
|
||||
var hay = Resolve(label)?.ToString() ?? string.Empty;
|
||||
return hay.Contains(needle, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
string op;
|
||||
if (MatchKeyword(">=")) op = ">=";
|
||||
else if (MatchKeyword("<=")) op = "<=";
|
||||
else if (MatchKeyword("!=") || MatchKeyword("<>")) op = "!=";
|
||||
else if (MatchKeyword("==") || MatchKeyword("=")) op = "==";
|
||||
else if (Match('>')) op = ">";
|
||||
else if (Match('<')) op = "<";
|
||||
else throw new InvalidOperationException($"条件公式缺少比较符:{label}");
|
||||
|
||||
var rightRaw = ReadStringOrNumber();
|
||||
return Compare(Resolve(label), op, rightRaw);
|
||||
}
|
||||
|
||||
private object? Resolve(string label)
|
||||
{
|
||||
if (context.TryGetValue(label, out var value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
var hit = context.FirstOrDefault(x =>
|
||||
string.Equals(x.Key, label, StringComparison.OrdinalIgnoreCase));
|
||||
return hit.Key == null ? null : hit.Value;
|
||||
}
|
||||
|
||||
private string ReadLabel()
|
||||
{
|
||||
SkipWs();
|
||||
var start = _pos;
|
||||
while (_pos < source.Length)
|
||||
{
|
||||
var ch = source[_pos];
|
||||
if (char.IsLetterOrDigit(ch) || ch is '_' or '.' || ch > 127)
|
||||
{
|
||||
_pos++;
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
if (_pos == start)
|
||||
{
|
||||
throw new InvalidOperationException("条件公式缺少字段名");
|
||||
}
|
||||
|
||||
return source[start.._pos];
|
||||
}
|
||||
|
||||
private string ReadStringOrNumber()
|
||||
{
|
||||
SkipWs();
|
||||
if (_pos < source.Length && (source[_pos] == '"' || source[_pos] == '\''))
|
||||
{
|
||||
var quote = source[_pos++];
|
||||
var start = _pos;
|
||||
while (_pos < source.Length && source[_pos] != quote)
|
||||
{
|
||||
_pos++;
|
||||
}
|
||||
|
||||
var text = source[start.._pos];
|
||||
if (_pos < source.Length)
|
||||
{
|
||||
_pos++;
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
var m = Regex.Match(source[_pos..], @"^[+-]?\d+(\.\d+)?");
|
||||
if (m.Success)
|
||||
{
|
||||
_pos += m.Length;
|
||||
return m.Value;
|
||||
}
|
||||
|
||||
return ReadLabel();
|
||||
}
|
||||
|
||||
private static bool HasValue(object? value) =>
|
||||
value != null && !string.IsNullOrWhiteSpace(Convert.ToString(value, CultureInfo.InvariantCulture));
|
||||
|
||||
private static bool Compare(object? left, string op, string rightText)
|
||||
{
|
||||
if (decimal.TryParse(Convert.ToString(left, CultureInfo.InvariantCulture), NumberStyles.Any, CultureInfo.InvariantCulture, out var ln)
|
||||
&& decimal.TryParse(rightText, NumberStyles.Any, CultureInfo.InvariantCulture, out var rn))
|
||||
{
|
||||
return op switch
|
||||
{
|
||||
">" => ln > rn,
|
||||
">=" => ln >= rn,
|
||||
"<" => ln < rn,
|
||||
"<=" => ln <= rn,
|
||||
"==" => ln == rn,
|
||||
"!=" => ln != rn,
|
||||
_ => false
|
||||
};
|
||||
}
|
||||
|
||||
var ls = Convert.ToString(left, CultureInfo.InvariantCulture) ?? string.Empty;
|
||||
return op switch
|
||||
{
|
||||
"==" => string.Equals(ls, rightText, StringComparison.OrdinalIgnoreCase),
|
||||
"!=" => !string.Equals(ls, rightText, StringComparison.OrdinalIgnoreCase),
|
||||
_ => throw new InvalidOperationException("非数值字段仅支持 = / !=")
|
||||
};
|
||||
}
|
||||
|
||||
private void SkipWs()
|
||||
{
|
||||
while (_pos < source.Length && char.IsWhiteSpace(source[_pos]))
|
||||
{
|
||||
_pos++;
|
||||
}
|
||||
}
|
||||
|
||||
private bool Match(char ch)
|
||||
{
|
||||
SkipWs();
|
||||
if (_pos < source.Length && source[_pos] == ch)
|
||||
{
|
||||
_pos++;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool MatchKeyword(string keyword)
|
||||
{
|
||||
SkipWs();
|
||||
if (_pos + keyword.Length > source.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!string.Equals(source.Substring(_pos, keyword.Length), keyword, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_pos += keyword.Length;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,266 @@
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// 审批定义配置 API。
|
||||
/// </summary>
|
||||
[ApiExplorerSettings(GroupName = "OMS-Approval")]
|
||||
public class ApprovalDefinitionService : ApplicationService
|
||||
{
|
||||
private IApprovalDefinitionRepository DefinitionRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IApprovalDefinitionRepository>();
|
||||
|
||||
private ApprovalPermissionGuard PermissionGuard =>
|
||||
LazyServiceProvider.GetRequiredService<ApprovalPermissionGuard>();
|
||||
|
||||
private ApprovalConditionEvaluator ConditionEvaluator =>
|
||||
LazyServiceProvider.GetRequiredService<ApprovalConditionEvaluator>();
|
||||
|
||||
private ApprovalCandidateResolver CandidateResolver =>
|
||||
LazyServiceProvider.GetRequiredService<ApprovalCandidateResolver>();
|
||||
|
||||
/// <summary>
|
||||
/// 分页查询审批定义。
|
||||
/// </summary>
|
||||
[HttpGet("/system/approval/definition/list")]
|
||||
public async Task<OmsPageResult<ApprovalDefinitionOutput>> GetListAsync(
|
||||
[FromQuery] ApprovalDefinitionListInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.DefinitionQuery);
|
||||
|
||||
var keyword = input.Keyword?.Trim();
|
||||
Expression<Func<ApprovalDefinition, bool>> 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<ApprovalDefinitionOutput>
|
||||
{
|
||||
Items = items.Select(MapOutput).ToList(),
|
||||
Total = total
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询审批定义详情。
|
||||
/// </summary>
|
||||
[HttpGet("/system/approval/definition/get")]
|
||||
public async Task<ApprovalDefinitionOutput> GetAsync([FromQuery] int id)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.DefinitionQuery);
|
||||
var entity = await GetOrThrowAsync(id);
|
||||
return MapOutput(entity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取可配置操作目录。
|
||||
/// </summary>
|
||||
[HttpGet("/system/approval/operation-catalog")]
|
||||
public async Task<List<ApprovalOperationCatalogItemOutput>> 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增或更新审批定义。同一 OperationCode 仅允许一条有效定义。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/definition/save")]
|
||||
public async Task<ApprovalDefinitionOutput> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 启用或停用审批定义。
|
||||
/// </summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除审批定义(软删)。
|
||||
/// </summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 条件公式试算。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/definition/test-condition")]
|
||||
public async Task<ApprovalConditionTestOutput> 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<ApprovalDefinition> 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)
|
||||
};
|
||||
}
|
||||
514
src/Oms.Application/Services/Approval/ApprovalEngineCore.cs
Normal file
514
src/Oms.Application/Services/Approval/ApprovalEngineCore.cs
Normal file
@ -0,0 +1,514 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Fake.Application;
|
||||
using Fake.DependencyInjection;
|
||||
using Fake.Domain.Exceptions;
|
||||
using Fake.Users;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
using Oms.Domain.ApprovalAggregate.Entities;
|
||||
using Oms.Domain.ApprovalAggregate.Enums;
|
||||
using Oms.Domain.ApprovalAggregate.Repositories;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 审批引擎核心逻辑(供 Gate 与 ApplicationService 共用)。
|
||||
/// </summary>
|
||||
public class ApprovalEngineCore(
|
||||
IApprovalDefinitionRepository definitionRepository,
|
||||
IApprovalInstanceRepository instanceRepository,
|
||||
IApprovalTaskRepository taskRepository,
|
||||
IApprovalEventRepository eventRepository,
|
||||
ApprovalConditionEvaluator conditionEvaluator,
|
||||
ApprovalCandidateResolver candidateResolver,
|
||||
ICurrentUser currentUser,
|
||||
IEnumerable<IApprovalOperationHandler> handlers) : IScopedDependency
|
||||
{
|
||||
private readonly Dictionary<string, IApprovalOperationHandler> _handlers = handlers
|
||||
.GroupBy(x => x.OperationCode, StringComparer.OrdinalIgnoreCase)
|
||||
.ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// 检查并提交或 Bypass。
|
||||
/// </summary>
|
||||
public async Task<ApprovalGateResult> CheckAndSubmitOrBypassAsync(
|
||||
ApprovalSubmitRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(request.OperationCode))
|
||||
{
|
||||
throw new BusinessException("操作编码不能为空");
|
||||
}
|
||||
|
||||
var operationCode = request.OperationCode.Trim();
|
||||
var bizKey = string.IsNullOrWhiteSpace(request.BizKey)
|
||||
? Guid.NewGuid().ToString("N")
|
||||
: request.BizKey.Trim();
|
||||
|
||||
var definition = await definitionRepository.FirstOrDefaultAsync(
|
||||
x => x.OperationCode == operationCode && x.IsEnabled);
|
||||
if (definition == null)
|
||||
{
|
||||
return new ApprovalGateResult
|
||||
{
|
||||
Decision = ApprovalGateDecision.Bypass,
|
||||
Message = "未启用审批定义,直接执行"
|
||||
};
|
||||
}
|
||||
|
||||
var matched = conditionEvaluator.Evaluate(
|
||||
operationCode,
|
||||
definition.ConditionFormula,
|
||||
request.ConditionContext);
|
||||
if (!matched)
|
||||
{
|
||||
return new ApprovalGateResult
|
||||
{
|
||||
Decision = ApprovalGateDecision.Bypass,
|
||||
Message = "条件未命中,无需审批"
|
||||
};
|
||||
}
|
||||
|
||||
var pending = await instanceRepository.FirstOrDefaultAsync(x =>
|
||||
x.OperationCode == operationCode
|
||||
&& x.BizKey == bizKey
|
||||
&& x.Status == ApprovalInstanceStatus.Pending);
|
||||
if (pending != null)
|
||||
{
|
||||
throw new BusinessException($"已存在待审批实例:{pending.InstanceNo}");
|
||||
}
|
||||
|
||||
var applicantMapId = OmsSessionHelper.ResolveMapUserId(currentUser);
|
||||
var applicantGuid = ResolveCurrentUserGuid();
|
||||
var applicantName = currentUser.UserName;
|
||||
|
||||
var candidateUserIds = await candidateResolver.ExpandCandidateUserIdsAsync(
|
||||
definition.ApproverType,
|
||||
definition.ApproverIds,
|
||||
cancellationToken);
|
||||
|
||||
if (definition.ForbidSelfApprove
|
||||
&& !string.IsNullOrWhiteSpace(applicantGuid)
|
||||
&& candidateUserIds.Contains(applicantGuid, StringComparer.OrdinalIgnoreCase)
|
||||
&& candidateUserIds.Count == 1)
|
||||
{
|
||||
throw new BusinessException("已禁止自审,且审批候选人仅含申请人本人,无法提交");
|
||||
}
|
||||
|
||||
var payloadJson = NormalizePayloadJson(request.PayloadJson);
|
||||
var instance = new ApprovalInstance
|
||||
{
|
||||
InstanceNo = await NextInstanceNoAsync(),
|
||||
OperationCode = operationCode,
|
||||
BizKey = bizKey,
|
||||
Title = string.IsNullOrWhiteSpace(request.Title)
|
||||
? (string.IsNullOrWhiteSpace(definition.OperationName) ? operationCode : definition.OperationName)
|
||||
: request.Title.Trim(),
|
||||
Status = ApprovalInstanceStatus.Pending,
|
||||
ApplicantUserId = applicantMapId,
|
||||
ApplicantUserGuid = applicantGuid,
|
||||
ApplicantUserName = applicantName,
|
||||
PayloadJson = payloadJson,
|
||||
PayloadHash = ComputeHash(payloadJson),
|
||||
SummaryJson = OmsDocHelper.SerializeJson(request.Summary),
|
||||
DefinitionSnapshot = OmsDocHelper.SerializeJson(new
|
||||
{
|
||||
definition.Id,
|
||||
definition.OperationCode,
|
||||
definition.OperationName,
|
||||
definition.ConditionFormula,
|
||||
definition.ApproverType,
|
||||
definition.ApproverIds,
|
||||
definition.ForbidSelfApprove
|
||||
})
|
||||
};
|
||||
|
||||
var saved = await instanceRepository.InsertAsync(instance);
|
||||
|
||||
var task = new ApprovalTask
|
||||
{
|
||||
InstanceId = saved.Id,
|
||||
StepNo = 1,
|
||||
Status = ApprovalTaskStatus.Pending,
|
||||
ApproverType = definition.ApproverType,
|
||||
ApproverIds = definition.ApproverIds,
|
||||
CandidateUserIds = ApprovalIdHelper.JoinIds(candidateUserIds)
|
||||
};
|
||||
var savedTask = await taskRepository.InsertAsync(task);
|
||||
|
||||
saved.CurrentTaskId = savedTask.Id;
|
||||
await instanceRepository.UpdateAsync(saved);
|
||||
|
||||
await AppendEventAsync(
|
||||
saved.Id,
|
||||
savedTask.Id,
|
||||
ApprovalCodes.EventSubmitted,
|
||||
null,
|
||||
ApprovalInstanceStatus.Pending,
|
||||
applicantMapId,
|
||||
applicantGuid,
|
||||
applicantName,
|
||||
"提交审批");
|
||||
|
||||
return new ApprovalGateResult
|
||||
{
|
||||
Decision = ApprovalGateDecision.PendingApproval,
|
||||
InstanceId = saved.Id,
|
||||
InstanceNo = saved.InstanceNo,
|
||||
Message = "已创建审批实例"
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审批通过并尝试执行业务 Handler。
|
||||
/// </summary>
|
||||
public async Task ApproveAsync(int instanceId, string? comment, string? concurrencyStamp)
|
||||
{
|
||||
var (instance, task) = await LoadPendingAsync(instanceId);
|
||||
EnsureConcurrency(instance, concurrencyStamp);
|
||||
EnsureCanAct(instance, task, isApprove: true);
|
||||
|
||||
var mapId = OmsSessionHelper.ResolveMapUserId(currentUser);
|
||||
var guid = ResolveCurrentUserGuid();
|
||||
var name = currentUser.UserName;
|
||||
var now = DateTime.Now;
|
||||
|
||||
task.Status = ApprovalTaskStatus.Approved;
|
||||
task.ActionUserId = mapId;
|
||||
task.ActionUserGuid = guid;
|
||||
task.ActionUserName = name;
|
||||
task.ActionTime = now;
|
||||
task.Comment = comment?.Trim();
|
||||
await taskRepository.UpdateAsync(task);
|
||||
|
||||
instance.Status = ApprovalInstanceStatus.Approved;
|
||||
instance.CompletedTime = now;
|
||||
await instanceRepository.UpdateAsync(instance);
|
||||
|
||||
await AppendEventAsync(
|
||||
instance.Id,
|
||||
task.Id,
|
||||
ApprovalCodes.EventApproved,
|
||||
ApprovalInstanceStatus.Pending,
|
||||
ApprovalInstanceStatus.Approved,
|
||||
mapId,
|
||||
guid,
|
||||
name,
|
||||
comment?.Trim() ?? "通过");
|
||||
|
||||
await ExecuteHandlerAsync(instance, mapId, guid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 驳回。
|
||||
/// </summary>
|
||||
public async Task RejectAsync(int instanceId, string? comment, string? concurrencyStamp)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(comment))
|
||||
{
|
||||
throw new BusinessException("驳回意见不能为空");
|
||||
}
|
||||
|
||||
var (instance, task) = await LoadPendingAsync(instanceId);
|
||||
EnsureConcurrency(instance, concurrencyStamp);
|
||||
EnsureCanAct(instance, task, isApprove: false);
|
||||
|
||||
var mapId = OmsSessionHelper.ResolveMapUserId(currentUser);
|
||||
var guid = ResolveCurrentUserGuid();
|
||||
var name = currentUser.UserName;
|
||||
var now = DateTime.Now;
|
||||
|
||||
task.Status = ApprovalTaskStatus.Rejected;
|
||||
task.ActionUserId = mapId;
|
||||
task.ActionUserGuid = guid;
|
||||
task.ActionUserName = name;
|
||||
task.ActionTime = now;
|
||||
task.Comment = comment.Trim();
|
||||
await taskRepository.UpdateAsync(task);
|
||||
|
||||
instance.Status = ApprovalInstanceStatus.Rejected;
|
||||
instance.CompletedTime = now;
|
||||
await instanceRepository.UpdateAsync(instance);
|
||||
|
||||
await AppendEventAsync(
|
||||
instance.Id,
|
||||
task.Id,
|
||||
ApprovalCodes.EventRejected,
|
||||
ApprovalInstanceStatus.Pending,
|
||||
ApprovalInstanceStatus.Rejected,
|
||||
mapId,
|
||||
guid,
|
||||
name,
|
||||
comment.Trim());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 申请人撤回。
|
||||
/// </summary>
|
||||
public async Task WithdrawAsync(int instanceId, string? comment, string? concurrencyStamp)
|
||||
{
|
||||
var (instance, task) = await LoadPendingAsync(instanceId);
|
||||
EnsureConcurrency(instance, concurrencyStamp);
|
||||
|
||||
var guid = ResolveCurrentUserGuid();
|
||||
if (!string.Equals(instance.ApplicantUserGuid, guid, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new BusinessException("仅申请人可撤回");
|
||||
}
|
||||
|
||||
var mapId = OmsSessionHelper.ResolveMapUserId(currentUser);
|
||||
var name = currentUser.UserName;
|
||||
var now = DateTime.Now;
|
||||
|
||||
task.Status = ApprovalTaskStatus.Cancelled;
|
||||
task.ActionUserId = mapId;
|
||||
task.ActionUserGuid = guid;
|
||||
task.ActionUserName = name;
|
||||
task.ActionTime = now;
|
||||
task.Comment = comment?.Trim() ?? "撤回";
|
||||
await taskRepository.UpdateAsync(task);
|
||||
|
||||
instance.Status = ApprovalInstanceStatus.Withdrawn;
|
||||
instance.CompletedTime = now;
|
||||
await instanceRepository.UpdateAsync(instance);
|
||||
|
||||
await AppendEventAsync(
|
||||
instance.Id,
|
||||
task.Id,
|
||||
ApprovalCodes.EventWithdrawn,
|
||||
ApprovalInstanceStatus.Pending,
|
||||
ApprovalInstanceStatus.Withdrawn,
|
||||
mapId,
|
||||
guid,
|
||||
name,
|
||||
comment?.Trim() ?? "撤回");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行失败后的重试。
|
||||
/// </summary>
|
||||
public async Task RetryExecuteAsync(int instanceId)
|
||||
{
|
||||
var instance = await instanceRepository.FirstOrDefaultAsync(x => x.Id == instanceId)
|
||||
?? throw new BusinessException("审批实例不存在");
|
||||
if (instance.Status is not (ApprovalInstanceStatus.Approved or ApprovalInstanceStatus.ExecuteFailed))
|
||||
{
|
||||
throw new BusinessException("仅已通过或执行失败的实例可重试执行");
|
||||
}
|
||||
|
||||
var mapId = OmsSessionHelper.ResolveMapUserId(currentUser);
|
||||
var guid = ResolveCurrentUserGuid();
|
||||
await ExecuteHandlerAsync(instance, mapId, guid);
|
||||
}
|
||||
|
||||
private async Task ExecuteHandlerAsync(ApprovalInstance instance, int operatorMapId, string operatorGuid)
|
||||
{
|
||||
instance.Status = ApprovalInstanceStatus.Executing;
|
||||
await instanceRepository.UpdateAsync(instance);
|
||||
await AppendEventAsync(
|
||||
instance.Id,
|
||||
instance.CurrentTaskId,
|
||||
ApprovalCodes.EventExecuting,
|
||||
ApprovalInstanceStatus.Approved,
|
||||
ApprovalInstanceStatus.Executing,
|
||||
operatorMapId,
|
||||
operatorGuid,
|
||||
currentUser.UserName,
|
||||
"开始执行业务");
|
||||
|
||||
try
|
||||
{
|
||||
if (_handlers.TryGetValue(instance.OperationCode, out var handler))
|
||||
{
|
||||
await handler.ExecuteAsync(new ApprovalExecutionContext
|
||||
{
|
||||
InstanceId = instance.Id,
|
||||
InstanceNo = instance.InstanceNo,
|
||||
OperationCode = instance.OperationCode,
|
||||
BizKey = instance.BizKey,
|
||||
PayloadJson = instance.PayloadJson,
|
||||
ApplicantUserId = instance.ApplicantUserId,
|
||||
ApplicantUserGuid = instance.ApplicantUserGuid,
|
||||
ApproverUserId = operatorMapId,
|
||||
ApproverUserGuid = operatorGuid
|
||||
});
|
||||
}
|
||||
|
||||
instance.Status = ApprovalInstanceStatus.Executed;
|
||||
instance.ExecutedTime = DateTime.Now;
|
||||
instance.ExecuteMessage = "执行成功";
|
||||
await instanceRepository.UpdateAsync(instance);
|
||||
await AppendEventAsync(
|
||||
instance.Id,
|
||||
instance.CurrentTaskId,
|
||||
ApprovalCodes.EventExecuted,
|
||||
ApprovalInstanceStatus.Executing,
|
||||
ApprovalInstanceStatus.Executed,
|
||||
operatorMapId,
|
||||
operatorGuid,
|
||||
currentUser.UserName,
|
||||
"执行成功");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
instance.Status = ApprovalInstanceStatus.ExecuteFailed;
|
||||
instance.ExecuteMessage = ex.Message;
|
||||
await instanceRepository.UpdateAsync(instance);
|
||||
await AppendEventAsync(
|
||||
instance.Id,
|
||||
instance.CurrentTaskId,
|
||||
ApprovalCodes.EventExecuteFailed,
|
||||
ApprovalInstanceStatus.Executing,
|
||||
ApprovalInstanceStatus.ExecuteFailed,
|
||||
operatorMapId,
|
||||
operatorGuid,
|
||||
currentUser.UserName,
|
||||
ex.Message);
|
||||
throw new BusinessException($"审批通过,但业务执行失败:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<(ApprovalInstance Instance, ApprovalTask Task)> LoadPendingAsync(int instanceId)
|
||||
{
|
||||
var instance = await instanceRepository.FirstOrDefaultAsync(x => x.Id == instanceId)
|
||||
?? throw new BusinessException("审批实例不存在");
|
||||
if (instance.Status != ApprovalInstanceStatus.Pending)
|
||||
{
|
||||
throw new BusinessException("仅待审批实例可操作");
|
||||
}
|
||||
|
||||
var taskId = instance.CurrentTaskId
|
||||
?? throw new BusinessException("审批任务不存在");
|
||||
var task = await taskRepository.FirstOrDefaultAsync(x => x.Id == taskId)
|
||||
?? throw new BusinessException("审批任务不存在");
|
||||
if (task.Status != ApprovalTaskStatus.Pending)
|
||||
{
|
||||
throw new BusinessException("审批任务已处理");
|
||||
}
|
||||
|
||||
return (instance, task);
|
||||
}
|
||||
|
||||
private void EnsureCanAct(ApprovalInstance instance, ApprovalTask task, bool isApprove)
|
||||
{
|
||||
var guid = ResolveCurrentUserGuid();
|
||||
if (string.IsNullOrWhiteSpace(guid))
|
||||
{
|
||||
throw new BusinessException("无法识别当前用户");
|
||||
}
|
||||
|
||||
var snapshot = OmsDocHelper.DeserializeJson<DefinitionSnap>(instance.DefinitionSnapshot);
|
||||
var forbidSelf = snapshot?.ForbidSelfApprove ?? true;
|
||||
if (forbidSelf && string.Equals(instance.ApplicantUserGuid, guid, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new BusinessException("禁止申请人审批自己的申请");
|
||||
}
|
||||
|
||||
if (!ApprovalIdHelper.ContainsId(task.CandidateUserIds, guid.ToString()))
|
||||
{
|
||||
throw new BusinessException("当前用户不在审批候选人中");
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureConcurrency(ApprovalInstance instance, string? concurrencyStamp)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(concurrencyStamp))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var expected = concurrencyStamp.Trim();
|
||||
var actual = instance.ConcurrencyStamp.ToString();
|
||||
if (!string.Equals(actual, expected, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new BusinessException("数据已变更,请刷新后重试");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AppendEventAsync(
|
||||
int instanceId,
|
||||
int? taskId,
|
||||
string eventType,
|
||||
ApprovalInstanceStatus? from,
|
||||
ApprovalInstanceStatus? to,
|
||||
int operatorUserId,
|
||||
string? operatorGuid,
|
||||
string? operatorName,
|
||||
string? message)
|
||||
{
|
||||
await eventRepository.InsertAsync(new ApprovalEvent
|
||||
{
|
||||
InstanceId = instanceId,
|
||||
TaskId = taskId,
|
||||
EventType = eventType,
|
||||
FromStatus = from,
|
||||
ToStatus = to,
|
||||
OperatorUserId = operatorUserId,
|
||||
OperatorUserGuid = operatorGuid,
|
||||
OperatorUserName = operatorName,
|
||||
Message = message
|
||||
});
|
||||
}
|
||||
|
||||
private async Task<string> NextInstanceNoAsync()
|
||||
{
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
var no = $"AP{DateTime.Now:yyyyMMddHHmmss}{Random.Shared.Next(100, 999)}";
|
||||
var exists = await instanceRepository.AnyAsync(x => x.InstanceNo == no);
|
||||
if (!exists)
|
||||
{
|
||||
return no;
|
||||
}
|
||||
}
|
||||
|
||||
return $"AP{Guid.NewGuid():N}"[..20];
|
||||
}
|
||||
|
||||
private string ResolveCurrentUserGuid()
|
||||
{
|
||||
if (ApprovalPermissionGuard.TryGetUserGuid(currentUser, out var guid))
|
||||
{
|
||||
return guid.ToString();
|
||||
}
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
private static string? NormalizePayloadJson(string? payloadJson)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(payloadJson))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(payloadJson);
|
||||
return JsonSerializer.Serialize(doc.RootElement);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return payloadJson;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? ComputeHash(string? payloadJson)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(payloadJson))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(payloadJson));
|
||||
return Convert.ToHexString(bytes);
|
||||
}
|
||||
|
||||
private sealed class DefinitionSnap
|
||||
{
|
||||
public bool ForbidSelfApprove { get; set; } = true;
|
||||
}
|
||||
}
|
||||
347
src/Oms.Application/Services/Approval/ApprovalEngineService.cs
Normal file
347
src/Oms.Application/Services/Approval/ApprovalEngineService.cs
Normal file
@ -0,0 +1,347 @@
|
||||
using System.Text.Json;
|
||||
using Fake.Application;
|
||||
using Fake.Domain.Exceptions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Oms.Application.Dtos.Approval;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
using Oms.Domain.ApprovalAggregate.Entities;
|
||||
using Oms.Domain.ApprovalAggregate.Enums;
|
||||
using Oms.Domain.ApprovalAggregate.Repositories;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 审批引擎 API:提交、待办、通过/驳回/撤回、详情。
|
||||
/// </summary>
|
||||
[ApiExplorerSettings(GroupName = "OMS-Approval")]
|
||||
public class ApprovalEngineService : ApplicationService
|
||||
{
|
||||
private IApprovalInstanceRepository InstanceRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IApprovalInstanceRepository>();
|
||||
|
||||
private IApprovalTaskRepository TaskRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IApprovalTaskRepository>();
|
||||
|
||||
private IApprovalEventRepository EventRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IApprovalEventRepository>();
|
||||
|
||||
private ApprovalEngineCore EngineCore =>
|
||||
LazyServiceProvider.GetRequiredService<ApprovalEngineCore>();
|
||||
|
||||
private ApprovalPermissionGuard PermissionGuard =>
|
||||
LazyServiceProvider.GetRequiredService<ApprovalPermissionGuard>();
|
||||
|
||||
/// <summary>
|
||||
/// 模拟提交审批(走 Gate;需定义管理权限)。用于一期联调。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/engine/simulate-submit")]
|
||||
public async Task<ApprovalSubmitOutput> SimulateSubmitAsync(ApprovalSubmitInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(
|
||||
CurrentUser,
|
||||
ApprovalPermissionCodes.DefinitionCreate,
|
||||
ApprovalPermissionCodes.DefinitionUpdate,
|
||||
ApprovalPermissionCodes.DefinitionEnable);
|
||||
|
||||
input.OperationCode = string.IsNullOrWhiteSpace(input.OperationCode)
|
||||
? ApprovalCodes.SimOperationCode
|
||||
: input.OperationCode.Trim();
|
||||
|
||||
return await SubmitInternalAsync(input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 提交审批(供后续业务或联调调用)。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/engine/submit")]
|
||||
public async Task<ApprovalSubmitOutput> SubmitAsync(ApprovalSubmitInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(
|
||||
CurrentUser,
|
||||
ApprovalPermissionCodes.TaskQuery,
|
||||
ApprovalPermissionCodes.DefinitionQuery);
|
||||
return await SubmitInternalAsync(input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 我的待办(待审批且当前用户在候选人中)。
|
||||
/// </summary>
|
||||
[HttpGet("/system/approval/engine/my-todo")]
|
||||
public async Task<OmsPageResult<ApprovalInstanceOutput>> GetMyTodoAsync(
|
||||
[FromQuery] ApprovalInstanceListInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.TaskQuery);
|
||||
if (!ApprovalPermissionGuard.TryGetUserGuid(CurrentUser, out var userGuid))
|
||||
{
|
||||
return new OmsPageResult<ApprovalInstanceOutput> { Items = [], Total = 0 };
|
||||
}
|
||||
|
||||
var guidText = userGuid.ToString();
|
||||
var pendingTasks = await TaskRepository.GetListAsync(x => x.Status == ApprovalTaskStatus.Pending);
|
||||
var myTaskInstanceIds = pendingTasks
|
||||
.Where(t => ApprovalIdHelper.ContainsId(t.CandidateUserIds, guidText))
|
||||
.Select(t => t.InstanceId)
|
||||
.Distinct()
|
||||
.ToHashSet();
|
||||
|
||||
if (myTaskInstanceIds.Count == 0)
|
||||
{
|
||||
return new OmsPageResult<ApprovalInstanceOutput> { Items = [], Total = 0 };
|
||||
}
|
||||
|
||||
var keyword = input.Keyword?.Trim();
|
||||
var instances = await InstanceRepository.GetListAsync(x =>
|
||||
x.Status == ApprovalInstanceStatus.Pending && myTaskInstanceIds.Contains(x.Id));
|
||||
var filtered = instances
|
||||
.Where(x => string.IsNullOrWhiteSpace(keyword)
|
||||
|| x.InstanceNo.Contains(keyword, StringComparison.OrdinalIgnoreCase)
|
||||
|| x.Title.Contains(keyword, StringComparison.OrdinalIgnoreCase)
|
||||
|| x.OperationCode.Contains(keyword, StringComparison.OrdinalIgnoreCase))
|
||||
.OrderByDescending(x => x.CreateTime)
|
||||
.ThenByDescending(x => x.Id)
|
||||
.ToList();
|
||||
|
||||
return await PageMapAsync(filtered, input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 我发起的审批。
|
||||
/// </summary>
|
||||
[HttpGet("/system/approval/engine/my-submitted")]
|
||||
public async Task<OmsPageResult<ApprovalInstanceOutput>> GetMySubmittedAsync(
|
||||
[FromQuery] ApprovalInstanceListInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.TaskQuery);
|
||||
if (!ApprovalPermissionGuard.TryGetUserGuid(CurrentUser, out var userGuid))
|
||||
{
|
||||
return new OmsPageResult<ApprovalInstanceOutput> { Items = [], Total = 0 };
|
||||
}
|
||||
|
||||
var guidText = userGuid.ToString();
|
||||
var keyword = input.Keyword?.Trim();
|
||||
var list = await InstanceRepository.GetListAsync(x => x.ApplicantUserGuid == guidText);
|
||||
var filtered = list
|
||||
.Where(x => input.Status == null || x.Status == input.Status.Value)
|
||||
.Where(x => string.IsNullOrWhiteSpace(keyword)
|
||||
|| x.InstanceNo.Contains(keyword, StringComparison.OrdinalIgnoreCase)
|
||||
|| x.Title.Contains(keyword, StringComparison.OrdinalIgnoreCase)
|
||||
|| x.OperationCode.Contains(keyword, StringComparison.OrdinalIgnoreCase))
|
||||
.OrderByDescending(x => x.CreateTime)
|
||||
.ThenByDescending(x => x.Id)
|
||||
.ToList();
|
||||
|
||||
return await PageMapAsync(filtered, input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 实例详情(含事件时间线)。
|
||||
/// </summary>
|
||||
[HttpGet("/system/approval/engine/detail")]
|
||||
public async Task<ApprovalInstanceOutput> GetDetailAsync([FromQuery] int id)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.TaskQuery);
|
||||
var instance = await InstanceRepository.FirstOrDefaultAsync(x => x.Id == id)
|
||||
?? throw new BusinessException("审批实例不存在");
|
||||
var events = await EventRepository.GetListAsync(x => x.InstanceId == id);
|
||||
var output = MapInstance(instance, events.OrderBy(x => x.Id).ToList());
|
||||
await FillActionFlagsAsync(output, instance);
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审批通过。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/engine/approve")]
|
||||
public async Task ApproveAsync(ApprovalActionInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.TaskApprove);
|
||||
await EngineCore.ApproveAsync(input.InstanceId, input.Comment, input.ConcurrencyStamp);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审批驳回。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/engine/reject")]
|
||||
public async Task RejectAsync(ApprovalActionInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.TaskReject);
|
||||
await EngineCore.RejectAsync(input.InstanceId, input.Comment, input.ConcurrencyStamp);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 申请人撤回。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/engine/withdraw")]
|
||||
public async Task WithdrawAsync(ApprovalActionInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.TaskQuery);
|
||||
await EngineCore.WithdrawAsync(input.InstanceId, input.Comment, input.ConcurrencyStamp);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 业务执行失败后重试。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/engine/retry-execute")]
|
||||
public async Task RetryExecuteAsync(IdInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(
|
||||
CurrentUser,
|
||||
ApprovalPermissionCodes.TaskApprove,
|
||||
ApprovalPermissionCodes.DefinitionEnable);
|
||||
await EngineCore.RetryExecuteAsync(input.Id);
|
||||
}
|
||||
|
||||
private async Task<ApprovalSubmitOutput> SubmitInternalAsync(ApprovalSubmitInput input)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(input.OperationCode))
|
||||
{
|
||||
throw new BusinessException("操作编码不能为空");
|
||||
}
|
||||
|
||||
var payloadJson = input.Payload switch
|
||||
{
|
||||
null => null,
|
||||
string s => s,
|
||||
JsonElement el => el.GetRawText(),
|
||||
_ => OmsDocHelper.SerializeJson(input.Payload)
|
||||
};
|
||||
|
||||
var result = await EngineCore.CheckAndSubmitOrBypassAsync(new ApprovalSubmitRequest
|
||||
{
|
||||
OperationCode = input.OperationCode.Trim(),
|
||||
BizKey = input.BizKey,
|
||||
Title = input.Title ?? string.Empty,
|
||||
PayloadJson = payloadJson,
|
||||
Summary = input.Summary,
|
||||
ConditionContext = input.ConditionContext
|
||||
});
|
||||
|
||||
return new ApprovalSubmitOutput
|
||||
{
|
||||
Decision = result.Decision.ToString(),
|
||||
InstanceId = result.InstanceId,
|
||||
InstanceNo = result.InstanceNo,
|
||||
Message = result.Message
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<OmsPageResult<ApprovalInstanceOutput>> PageMapAsync(
|
||||
List<ApprovalInstance> filtered,
|
||||
ApprovalInstanceListInput input)
|
||||
{
|
||||
var pageIndex = OmsDocHelper.NormalizePage(input.Page);
|
||||
var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize <= 0 ? 50 : input.PageSize);
|
||||
var total = filtered.Count;
|
||||
var slice = filtered
|
||||
.Skip((pageIndex - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToList();
|
||||
|
||||
var pageItems = new List<ApprovalInstanceOutput>(slice.Count);
|
||||
foreach (var x in slice)
|
||||
{
|
||||
var output = MapInstance(x, []);
|
||||
await FillActionFlagsAsync(output, x);
|
||||
pageItems.Add(output);
|
||||
}
|
||||
|
||||
return new OmsPageResult<ApprovalInstanceOutput>
|
||||
{
|
||||
Items = pageItems,
|
||||
Total = total
|
||||
};
|
||||
}
|
||||
|
||||
private async Task FillActionFlagsAsync(ApprovalInstanceOutput output, ApprovalInstance instance)
|
||||
{
|
||||
if (!ApprovalPermissionGuard.TryGetUserGuid(CurrentUser, out var guid))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var guidText = guid.ToString();
|
||||
output.CanWithdraw = instance.Status == ApprovalInstanceStatus.Pending
|
||||
&& string.Equals(instance.ApplicantUserGuid, guidText, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (instance.Status != ApprovalInstanceStatus.Pending || instance.CurrentTaskId == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var task = await TaskRepository.FirstOrDefaultAsync(x => x.Id == instance.CurrentTaskId.Value);
|
||||
if (task == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var forbidSelf = true;
|
||||
var snap = OmsDocHelper.DeserializeJson<ForbidSnap>(instance.DefinitionSnapshot);
|
||||
if (snap != null)
|
||||
{
|
||||
forbidSelf = snap.ForbidSelfApprove;
|
||||
}
|
||||
|
||||
if (forbidSelf && string.Equals(instance.ApplicantUserGuid, guidText, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
output.CanApprove = false;
|
||||
return;
|
||||
}
|
||||
|
||||
output.CanApprove = ApprovalIdHelper.ContainsId(task.CandidateUserIds, guidText);
|
||||
}
|
||||
|
||||
private static ApprovalInstanceOutput MapInstance(
|
||||
ApprovalInstance entity,
|
||||
List<ApprovalEvent> events) => new()
|
||||
{
|
||||
Id = entity.Id,
|
||||
InstanceNo = entity.InstanceNo,
|
||||
OperationCode = entity.OperationCode,
|
||||
BizKey = entity.BizKey,
|
||||
Title = entity.Title,
|
||||
Status = entity.Status,
|
||||
StatusName = StatusName(entity.Status),
|
||||
ApplicantUserId = entity.ApplicantUserId,
|
||||
ApplicantUserGuid = entity.ApplicantUserGuid,
|
||||
ApplicantUserName = entity.ApplicantUserName,
|
||||
PayloadJson = entity.PayloadJson,
|
||||
SummaryJson = entity.SummaryJson,
|
||||
DefinitionSnapshot = entity.DefinitionSnapshot,
|
||||
CurrentTaskId = entity.CurrentTaskId,
|
||||
CreateTime = entity.CreateTime,
|
||||
CompletedTime = entity.CompletedTime,
|
||||
ExecutedTime = entity.ExecutedTime,
|
||||
ExecuteMessage = entity.ExecuteMessage,
|
||||
ConcurrencyStamp = entity.ConcurrencyStamp.ToString(),
|
||||
Events = events.Select(e => new ApprovalEventOutput
|
||||
{
|
||||
Id = e.Id,
|
||||
EventType = e.EventType,
|
||||
FromStatus = e.FromStatus,
|
||||
ToStatus = e.ToStatus,
|
||||
OperatorUserName = e.OperatorUserName,
|
||||
Message = e.Message,
|
||||
CreateTime = e.CreateTime
|
||||
}).ToList()
|
||||
};
|
||||
|
||||
private static string StatusName(ApprovalInstanceStatus status) => status switch
|
||||
{
|
||||
ApprovalInstanceStatus.Pending => "待审批",
|
||||
ApprovalInstanceStatus.Approved => "已通过",
|
||||
ApprovalInstanceStatus.Rejected => "已驳回",
|
||||
ApprovalInstanceStatus.Withdrawn => "已撤回",
|
||||
ApprovalInstanceStatus.Executing => "执行中",
|
||||
ApprovalInstanceStatus.Executed => "已执行",
|
||||
ApprovalInstanceStatus.ExecuteFailed => "执行失败",
|
||||
_ => status.ToString()
|
||||
};
|
||||
|
||||
private sealed class ForbidSnap
|
||||
{
|
||||
public bool ForbidSelfApprove { get; set; } = true;
|
||||
}
|
||||
}
|
||||
16
src/Oms.Application/Services/Approval/ApprovalGate.cs
Normal file
16
src/Oms.Application/Services/Approval/ApprovalGate.cs
Normal file
@ -0,0 +1,16 @@
|
||||
using Fake.DependencyInjection;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 审批门面实现:供后续业务接入。一期也可由引擎模拟提交调用。
|
||||
/// </summary>
|
||||
public class ApprovalGate(ApprovalEngineCore engineCore) : IApprovalGate, IScopedDependency
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public Task<ApprovalGateResult> CheckAndSubmitOrBypassAsync(
|
||||
ApprovalSubmitRequest request,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
engineCore.CheckAndSubmitOrBypassAsync(request, cancellationToken);
|
||||
}
|
||||
49
src/Oms.Application/Services/Approval/ApprovalIdHelper.cs
Normal file
49
src/Oms.Application/Services/Approval/ApprovalIdHelper.cs
Normal file
@ -0,0 +1,49 @@
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 审批候选人 ID 解析辅助。
|
||||
/// </summary>
|
||||
public static class ApprovalIdHelper
|
||||
{
|
||||
private static readonly char[] Separators = [',', ';', ',', ' '];
|
||||
|
||||
/// <summary>拆分为去重后的非空片段。</summary>
|
||||
public static List<string> SplitIds(string? raw)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(raw))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return raw
|
||||
.Split(Separators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Where(x => !string.IsNullOrWhiteSpace(x))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>规范化存储(逗号分隔)。</summary>
|
||||
public static string JoinIds(IEnumerable<string>? ids)
|
||||
{
|
||||
if (ids == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return string.Join(",",
|
||||
ids.Select(x => x.Trim())
|
||||
.Where(x => !string.IsNullOrWhiteSpace(x))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>判断候选串是否包含指定 Guid。</summary>
|
||||
public static bool ContainsId(string? raw, string? id)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(id))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return SplitIds(raw).Contains(id.Trim(), StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,71 @@
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 可配置审批的操作目录(代码注册,非库表)。
|
||||
/// </summary>
|
||||
public static class ApprovalOperationCatalog
|
||||
{
|
||||
/// <summary>
|
||||
/// 目录项。
|
||||
/// </summary>
|
||||
public sealed record Item(
|
||||
string Code,
|
||||
string Name,
|
||||
string Module,
|
||||
bool SupportsCondition,
|
||||
string ConditionHint);
|
||||
|
||||
private static readonly IReadOnlyList<Item> Items =
|
||||
[
|
||||
new(
|
||||
ApprovalCodes.SimOperationCode,
|
||||
"审批引擎模拟提交",
|
||||
"System",
|
||||
SupportsCondition: false,
|
||||
ConditionHint: "一期自测用,不支持条件公式"),
|
||||
new(
|
||||
"Finance.Recharge.Credit",
|
||||
"充值入账",
|
||||
"Finance",
|
||||
SupportsCondition: false,
|
||||
ConditionHint: "业务接入后可按金额等配置条件"),
|
||||
new(
|
||||
"Marketing.Commission.Withdraw",
|
||||
"佣金提现",
|
||||
"Marketing",
|
||||
SupportsCondition: false,
|
||||
ConditionHint: "业务接入后可按金额等配置条件"),
|
||||
new(
|
||||
"Channel.SalesProduct.PublishPrice",
|
||||
"销售产品价格发布",
|
||||
"Channel",
|
||||
SupportsCondition: false,
|
||||
ConditionHint: "业务接入后可按价差等配置条件"),
|
||||
new(
|
||||
"Order.Refund.Apply",
|
||||
"订单退款",
|
||||
"Order",
|
||||
SupportsCondition: false,
|
||||
ConditionHint: "业务接入后可按退款金额等配置条件")
|
||||
];
|
||||
|
||||
/// <summary>全部目录项。</summary>
|
||||
public static IReadOnlyList<Item> All => Items;
|
||||
|
||||
/// <summary>按编码查找。</summary>
|
||||
public static Item? Find(string? operationCode)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(operationCode))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return Items.FirstOrDefault(x =>
|
||||
string.Equals(x.Code, operationCode.Trim(), StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>是否已知操作。</summary>
|
||||
public static bool IsKnown(string? operationCode) => Find(operationCode) != null;
|
||||
}
|
||||
110
src/Oms.Application/Services/Approval/ApprovalPermissionGuard.cs
Normal file
110
src/Oms.Application/Services/Approval/ApprovalPermissionGuard.cs
Normal file
@ -0,0 +1,110 @@
|
||||
using System.Security.Claims;
|
||||
using Fake.Application;
|
||||
using Fake.DependencyInjection;
|
||||
using Fake.Domain.Exceptions;
|
||||
using Fake.Rbac.Application.Services;
|
||||
using Fake.Users;
|
||||
using Oms.Application.DataPerm;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 审批服务端权限校验(Admin 放行;否则查角色权限码)。
|
||||
/// </summary>
|
||||
public class ApprovalPermissionGuard(
|
||||
DataPermRepository dataPermRepository,
|
||||
RoleService roleService) : IScopedDependency
|
||||
{
|
||||
/// <summary>
|
||||
/// 要求当前用户具备指定权限码之一(含 Admin)。
|
||||
/// </summary>
|
||||
public async Task EnsureAsync(ICurrentUser currentUser, params string[] permissionCodes)
|
||||
{
|
||||
if (permissionCodes.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (await HasAnyAsync(currentUser, permissionCodes))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
throw new BusinessException("无权限执行该审批操作");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 是否具备任一权限。
|
||||
/// </summary>
|
||||
public async Task<bool> HasAnyAsync(ICurrentUser currentUser, params string[] permissionCodes)
|
||||
{
|
||||
if (!TryGetUserGuid(currentUser, out var userId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (HasAdminRoleClaim(currentUser) || await dataPermRepository.IsAdminUserAsync(userId))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var roleIds = await dataPermRepository.GetUserRoleIdsAsync(userId);
|
||||
if (roleIds.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var wanted = permissionCodes
|
||||
.SelectMany(ExpandCandidates)
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
foreach (var roleId in roleIds)
|
||||
{
|
||||
var codes = await roleService.GetRolePermissionsAsync(roleId);
|
||||
if (codes.Any(c => !string.IsNullOrWhiteSpace(c) && wanted.Contains(c.Trim())))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>解析当前用户 Guid。</summary>
|
||||
public static bool TryGetUserGuid(ICurrentUser currentUser, out Guid userId)
|
||||
{
|
||||
userId = Guid.Empty;
|
||||
var raw = currentUser.FindClaimOrNull(ClaimTypes.NameIdentifier)?.Value
|
||||
?? currentUser.FindClaimOrNull("sub")?.Value;
|
||||
return Guid.TryParse(raw, out userId) && userId != Guid.Empty;
|
||||
}
|
||||
|
||||
private static bool HasAdminRoleClaim(ICurrentUser currentUser)
|
||||
{
|
||||
return currentUser.FindClaims(ClaimTypes.Role)
|
||||
.Concat(currentUser.FindClaims("role"))
|
||||
.Any(c => string.Equals(c.Value, "Admin", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
private static IEnumerable<string> ExpandCandidates(string code)
|
||||
{
|
||||
var c = code.Trim();
|
||||
if (string.IsNullOrWhiteSpace(c))
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
yield return c;
|
||||
var suffixes = new[] { ".Query", ".Create", ".Update", ".Delete", ".Enable", ".Approve", ".Reject" };
|
||||
foreach (var suffix in suffixes)
|
||||
{
|
||||
if (!c.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
yield return c[..^suffix.Length];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,119 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Oms.Application.Services.Approval.Contracts;
|
||||
|
||||
/// <summary>
|
||||
/// 审批提交请求(业务侧组装后交给 Gate)。
|
||||
/// </summary>
|
||||
public class ApprovalSubmitRequest
|
||||
{
|
||||
/// <summary>操作编码。</summary>
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>业务幂等键(同操作下 Pending 中不可重复)。</summary>
|
||||
public string BizKey { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>摘要标题。</summary>
|
||||
public string Title { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>冻结业务载荷 JSON。</summary>
|
||||
public string? PayloadJson { get; set; }
|
||||
|
||||
/// <summary>展示摘要对象(序列化进 SummaryJson)。</summary>
|
||||
public object? Summary { get; set; }
|
||||
|
||||
/// <summary>条件求值上下文字典(中文标签 → 值);无条件时可空。</summary>
|
||||
public IReadOnlyDictionary<string, object?>? ConditionContext { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gate 判定结果。
|
||||
/// </summary>
|
||||
public enum ApprovalGateDecision
|
||||
{
|
||||
/// <summary>无需审批,业务可立即执行。</summary>
|
||||
Bypass = 0,
|
||||
|
||||
/// <summary>已创建待审批实例。</summary>
|
||||
PendingApproval = 1
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gate 返回。
|
||||
/// </summary>
|
||||
public class ApprovalGateResult
|
||||
{
|
||||
/// <summary>判定。</summary>
|
||||
public ApprovalGateDecision Decision { get; set; }
|
||||
|
||||
/// <summary>实例 Id(PendingApproval 时有值)。</summary>
|
||||
public int? InstanceId { get; set; }
|
||||
|
||||
/// <summary>实例单号。</summary>
|
||||
public string? InstanceNo { get; set; }
|
||||
|
||||
/// <summary>说明。</summary>
|
||||
public string? Message { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审批门面:业务入口调用,判断 Bypass 或建单。
|
||||
/// </summary>
|
||||
public interface IApprovalGate
|
||||
{
|
||||
/// <summary>
|
||||
/// 检查是否需审;需审则创建实例与任务,否则 Bypass。
|
||||
/// </summary>
|
||||
Task<ApprovalGateResult> CheckAndSubmitOrBypassAsync(
|
||||
ApprovalSubmitRequest request,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 终审通过后的业务执行器(按 OperationCode 注册)。
|
||||
/// </summary>
|
||||
public interface IApprovalOperationHandler
|
||||
{
|
||||
/// <summary>支持的操作编码。</summary>
|
||||
string OperationCode { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 执行业务。成功无异常;失败抛 BusinessException 或普通 Exception,引擎记 ExecuteFailed。
|
||||
/// </summary>
|
||||
Task ExecuteAsync(ApprovalExecutionContext context, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行上下文。
|
||||
/// </summary>
|
||||
public class ApprovalExecutionContext
|
||||
{
|
||||
public int InstanceId { get; set; }
|
||||
|
||||
public string InstanceNo { get; set; } = string.Empty;
|
||||
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
public string BizKey { get; set; } = string.Empty;
|
||||
|
||||
public string? PayloadJson { get; set; }
|
||||
|
||||
public int ApplicantUserId { get; set; }
|
||||
|
||||
public string ApplicantUserGuid { get; set; } = string.Empty;
|
||||
|
||||
public int ApproverUserId { get; set; }
|
||||
|
||||
public string ApproverUserGuid { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 条件上下文工厂(按操作提供公式字段;未注册则仅允许空条件)。
|
||||
/// </summary>
|
||||
public interface IApprovalConditionContextFactory
|
||||
{
|
||||
string OperationCode { get; }
|
||||
|
||||
/// <summary>将业务上下文字典转为公式求值用标签字典。</summary>
|
||||
IReadOnlyDictionary<string, object?> Build(IReadOnlyDictionary<string, object?>? raw);
|
||||
}
|
||||
18
src/Oms.Application/Services/Approval/NoopApprovalHandler.cs
Normal file
18
src/Oms.Application/Services/Approval/NoopApprovalHandler.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using Fake.DependencyInjection;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 模拟操作的空执行器(终审通过后仅记 Executed)。
|
||||
/// </summary>
|
||||
public class NoopApprovalHandler : IApprovalOperationHandler, ITransientDependency
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string OperationCode => ApprovalCodes.SimOperationCode;
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task ExecuteAsync(ApprovalExecutionContext context, CancellationToken cancellationToken = default) =>
|
||||
Task.CompletedTask;
|
||||
}
|
||||
12
src/Oms.Application/Services/Approval/README.md
Normal file
12
src/Oms.Application/Services/Approval/README.md
Normal file
@ -0,0 +1,12 @@
|
||||
# 审批引擎(一期)
|
||||
|
||||
单级可配置审批:定义某 `OperationCode` 是否需审、谁审、可选条件;实例/任务/事件由引擎托管。
|
||||
|
||||
## 业务接入(后续)
|
||||
|
||||
1. 在操作入口组装 `ApprovalSubmitRequest`,调用 `IApprovalGate.CheckAndSubmitOrBypassAsync`。
|
||||
2. `Bypass`:业务立即执行;`PendingApproval`:业务进入自有「待审批」中间态,等待终审。
|
||||
3. 实现 `IApprovalOperationHandler`(`OperationCode` 匹配),终审通过后引擎调用 `ExecuteAsync`;Handler 内须再次校验业务状态后落账/发布。
|
||||
4. 若操作需条件公式,再实现 `IApprovalConditionContextFactory`,并将目录项 `SupportsCondition` 改为 true。
|
||||
|
||||
一期不改造充值/提现/价格发布等现有审核接口。联调可用「模拟提交」+ 操作码 `System.Approval.Simulate`。
|
||||
53
src/Oms.Domain/ApprovalAggregate/Consts/ApprovalCodes.cs
Normal file
53
src/Oms.Domain/ApprovalAggregate/Consts/ApprovalCodes.cs
Normal file
@ -0,0 +1,53 @@
|
||||
namespace Oms.Domain.ApprovalAggregate.Consts;
|
||||
|
||||
/// <summary>
|
||||
/// 审批相关常量。
|
||||
/// </summary>
|
||||
public static class ApprovalCodes
|
||||
{
|
||||
/// <summary>审批人类型:用户。</summary>
|
||||
public const string ApproverTypeUser = "User";
|
||||
|
||||
/// <summary>审批人类型:角色。</summary>
|
||||
public const string ApproverTypeRole = "Role";
|
||||
|
||||
/// <summary>事件:提交。</summary>
|
||||
public const string EventSubmitted = "Submitted";
|
||||
|
||||
/// <summary>事件:通过。</summary>
|
||||
public const string EventApproved = "Approved";
|
||||
|
||||
/// <summary>事件:驳回。</summary>
|
||||
public const string EventRejected = "Rejected";
|
||||
|
||||
/// <summary>事件:撤回。</summary>
|
||||
public const string EventWithdrawn = "Withdrawn";
|
||||
|
||||
/// <summary>事件:开始执行。</summary>
|
||||
public const string EventExecuting = "Executing";
|
||||
|
||||
/// <summary>事件:执行成功。</summary>
|
||||
public const string EventExecuted = "Executed";
|
||||
|
||||
/// <summary>事件:执行失败。</summary>
|
||||
public const string EventExecuteFailed = "ExecuteFailed";
|
||||
|
||||
/// <summary>模拟提交操作编码(引擎自测)。</summary>
|
||||
public const string SimOperationCode = "System.Approval.Simulate";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审批权限码。
|
||||
/// </summary>
|
||||
public static class ApprovalPermissionCodes
|
||||
{
|
||||
public const string DefinitionQuery = "System.ApprovalDefinition.Query";
|
||||
public const string DefinitionCreate = "System.ApprovalDefinition.Create";
|
||||
public const string DefinitionUpdate = "System.ApprovalDefinition.Update";
|
||||
public const string DefinitionDelete = "System.ApprovalDefinition.Delete";
|
||||
public const string DefinitionEnable = "System.ApprovalDefinition.Enable";
|
||||
|
||||
public const string TaskQuery = "System.ApprovalTask.Query";
|
||||
public const string TaskApprove = "System.ApprovalTask.Approve";
|
||||
public const string TaskReject = "System.ApprovalTask.Reject";
|
||||
}
|
||||
@ -0,0 +1,41 @@
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.ApprovalAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 审批定义:按操作编码配置是否需审、条件与审批人。
|
||||
/// </summary>
|
||||
[SugarTable("t_approval_definition")]
|
||||
public class ApprovalDefinition : OmsAuditedAggregateRoot
|
||||
{
|
||||
/// <summary>操作编码。</summary>
|
||||
[SugarColumn(Length = 128)]
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>操作显示名快照。</summary>
|
||||
[SugarColumn(Length = 128)]
|
||||
public string OperationName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>是否启用。</summary>
|
||||
public bool IsEnabled { get; set; } = true;
|
||||
|
||||
/// <summary>触发条件公式;空表示启用即始终需审。</summary>
|
||||
[SugarColumn(Length = 2000, IsNullable = true)]
|
||||
public string? ConditionFormula { get; set; }
|
||||
|
||||
/// <summary>审批人类型:User / Role。</summary>
|
||||
[SugarColumn(Length = 16)]
|
||||
public string ApproverType { get; set; } = "User";
|
||||
|
||||
/// <summary>候选人 ID,逗号分隔。</summary>
|
||||
[SugarColumn(Length = 2000)]
|
||||
public string ApproverIds { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>禁止申请人自审。</summary>
|
||||
public bool ForbidSelfApprove { get; set; } = true;
|
||||
|
||||
/// <summary>备注。</summary>
|
||||
[SugarColumn(Length = 512, IsNullable = true)]
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
46
src/Oms.Domain/ApprovalAggregate/Entities/ApprovalEvent.cs
Normal file
46
src/Oms.Domain/ApprovalAggregate/Entities/ApprovalEvent.cs
Normal file
@ -0,0 +1,46 @@
|
||||
using Oms.Domain.ApprovalAggregate.Enums;
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.ApprovalAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 审批事件(追加写)。
|
||||
/// </summary>
|
||||
[SugarTable("t_approval_event")]
|
||||
public class ApprovalEvent : OmsAuditedAggregateRoot
|
||||
{
|
||||
/// <summary>审批实例 Id。</summary>
|
||||
public int InstanceId { get; set; }
|
||||
|
||||
/// <summary>关联任务 Id。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public int? TaskId { get; set; }
|
||||
|
||||
/// <summary>事件类型。</summary>
|
||||
[SugarColumn(Length = 32)]
|
||||
public string EventType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>变更前实例状态。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public ApprovalInstanceStatus? FromStatus { get; set; }
|
||||
|
||||
/// <summary>变更后实例状态。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public ApprovalInstanceStatus? ToStatus { get; set; }
|
||||
|
||||
/// <summary>操作人 mapId。</summary>
|
||||
public int OperatorUserId { get; set; }
|
||||
|
||||
/// <summary>操作人 Guid。</summary>
|
||||
[SugarColumn(Length = 36, IsNullable = true)]
|
||||
public string? OperatorUserGuid { get; set; }
|
||||
|
||||
/// <summary>操作人显示名。</summary>
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? OperatorUserName { get; set; }
|
||||
|
||||
/// <summary>事件说明/意见。</summary>
|
||||
[SugarColumn(Length = 1000, IsNullable = true)]
|
||||
public string? Message { get; set; }
|
||||
}
|
||||
@ -0,0 +1,74 @@
|
||||
using Oms.Domain.ApprovalAggregate.Enums;
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.ApprovalAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 审批实例。
|
||||
/// </summary>
|
||||
[SugarTable("t_approval_instance")]
|
||||
public class ApprovalInstance : OmsAuditedAggregateRoot
|
||||
{
|
||||
/// <summary>实例单号。</summary>
|
||||
[SugarColumn(Length = 32)]
|
||||
public string InstanceNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>操作编码。</summary>
|
||||
[SugarColumn(Length = 128)]
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>业务幂等键。</summary>
|
||||
[SugarColumn(Length = 128)]
|
||||
public string BizKey { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>摘要标题。</summary>
|
||||
[SugarColumn(Length = 256)]
|
||||
public string Title { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>实例状态。</summary>
|
||||
public ApprovalInstanceStatus Status { get; set; } = ApprovalInstanceStatus.Pending;
|
||||
|
||||
/// <summary>申请人 mapId。</summary>
|
||||
public int ApplicantUserId { get; set; }
|
||||
|
||||
/// <summary>申请人 RBAC Guid。</summary>
|
||||
[SugarColumn(Length = 36)]
|
||||
public string ApplicantUserGuid { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>申请人显示名。</summary>
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? ApplicantUserName { get; set; }
|
||||
|
||||
/// <summary>冻结业务载荷。</summary>
|
||||
[SugarColumn(ColumnDataType = "mediumtext", IsNullable = true)]
|
||||
public string? PayloadJson { get; set; }
|
||||
|
||||
/// <summary>载荷哈希。</summary>
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? PayloadHash { get; set; }
|
||||
|
||||
/// <summary>展示摘要 JSON。</summary>
|
||||
[SugarColumn(Length = 2000, IsNullable = true)]
|
||||
public string? SummaryJson { get; set; }
|
||||
|
||||
/// <summary>提交时定义快照。</summary>
|
||||
[SugarColumn(ColumnDataType = "mediumtext", IsNullable = true)]
|
||||
public string? DefinitionSnapshot { get; set; }
|
||||
|
||||
/// <summary>当前任务 Id。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public int? CurrentTaskId { get; set; }
|
||||
|
||||
/// <summary>终审完成时间。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public DateTime? CompletedTime { get; set; }
|
||||
|
||||
/// <summary>业务执行完成时间。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public DateTime? ExecutedTime { get; set; }
|
||||
|
||||
/// <summary>执行结果/失败信息。</summary>
|
||||
[SugarColumn(Length = 1000, IsNullable = true)]
|
||||
public string? ExecuteMessage { get; set; }
|
||||
}
|
||||
53
src/Oms.Domain/ApprovalAggregate/Entities/ApprovalTask.cs
Normal file
53
src/Oms.Domain/ApprovalAggregate/Entities/ApprovalTask.cs
Normal file
@ -0,0 +1,53 @@
|
||||
using Oms.Domain.ApprovalAggregate.Enums;
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.ApprovalAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 审批任务(一期单级仅一条进行中任务)。
|
||||
/// </summary>
|
||||
[SugarTable("t_approval_task")]
|
||||
public class ApprovalTask : OmsAuditedAggregateRoot
|
||||
{
|
||||
/// <summary>审批实例 Id。</summary>
|
||||
public int InstanceId { get; set; }
|
||||
|
||||
/// <summary>步骤号,一期固定 1。</summary>
|
||||
public int StepNo { get; set; } = 1;
|
||||
|
||||
/// <summary>任务状态。</summary>
|
||||
public ApprovalTaskStatus Status { get; set; } = ApprovalTaskStatus.Pending;
|
||||
|
||||
/// <summary>审批人类型快照。</summary>
|
||||
[SugarColumn(Length = 16)]
|
||||
public string ApproverType { get; set; } = "User";
|
||||
|
||||
/// <summary>配置候选人快照。</summary>
|
||||
[SugarColumn(Length = 2000)]
|
||||
public string ApproverIds { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>展开后的可审用户 Guid。</summary>
|
||||
[SugarColumn(Length = 4000)]
|
||||
public string CandidateUserIds { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>实际处理人 mapId。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public int? ActionUserId { get; set; }
|
||||
|
||||
/// <summary>实际处理人 Guid。</summary>
|
||||
[SugarColumn(Length = 36, IsNullable = true)]
|
||||
public string? ActionUserGuid { get; set; }
|
||||
|
||||
/// <summary>实际处理人显示名。</summary>
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? ActionUserName { get; set; }
|
||||
|
||||
/// <summary>处理时间。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public DateTime? ActionTime { get; set; }
|
||||
|
||||
/// <summary>审批意见。</summary>
|
||||
[SugarColumn(Length = 1000, IsNullable = true)]
|
||||
public string? Comment { get; set; }
|
||||
}
|
||||
58
src/Oms.Domain/ApprovalAggregate/Enums/ApprovalEnums.cs
Normal file
58
src/Oms.Domain/ApprovalAggregate/Enums/ApprovalEnums.cs
Normal file
@ -0,0 +1,58 @@
|
||||
namespace Oms.Domain.ApprovalAggregate.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// 审批实例状态。
|
||||
/// </summary>
|
||||
public enum ApprovalInstanceStatus
|
||||
{
|
||||
/// <summary>待审批。</summary>
|
||||
Pending = 1,
|
||||
|
||||
/// <summary>已通过(待/正在执行业务)。</summary>
|
||||
Approved = 2,
|
||||
|
||||
/// <summary>已驳回。</summary>
|
||||
Rejected = 3,
|
||||
|
||||
/// <summary>已撤回。</summary>
|
||||
Withdrawn = 4,
|
||||
|
||||
/// <summary>业务执行中。</summary>
|
||||
Executing = 5,
|
||||
|
||||
/// <summary>业务已执行成功。</summary>
|
||||
Executed = 6,
|
||||
|
||||
/// <summary>业务执行失败。</summary>
|
||||
ExecuteFailed = 7
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审批任务状态。
|
||||
/// </summary>
|
||||
public enum ApprovalTaskStatus
|
||||
{
|
||||
/// <summary>待处理。</summary>
|
||||
Pending = 1,
|
||||
|
||||
/// <summary>已通过。</summary>
|
||||
Approved = 2,
|
||||
|
||||
/// <summary>已驳回。</summary>
|
||||
Rejected = 3,
|
||||
|
||||
/// <summary>已取消(撤回等)。</summary>
|
||||
Cancelled = 4
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审批人类型。
|
||||
/// </summary>
|
||||
public enum ApprovalApproverType
|
||||
{
|
||||
/// <summary>指定用户(RBAC Guid)。</summary>
|
||||
User = 1,
|
||||
|
||||
/// <summary>指定角色(RBAC Role Guid)。</summary>
|
||||
Role = 2
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
using Fake.Domain.Repositories;
|
||||
using Oms.Domain.ApprovalAggregate.Entities;
|
||||
|
||||
namespace Oms.Domain.ApprovalAggregate.Repositories;
|
||||
|
||||
public interface IApprovalDefinitionRepository : IRepository<ApprovalDefinition>
|
||||
{
|
||||
}
|
||||
|
||||
public interface IApprovalInstanceRepository : IRepository<ApprovalInstance>
|
||||
{
|
||||
}
|
||||
|
||||
public interface IApprovalTaskRepository : IRepository<ApprovalTask>
|
||||
{
|
||||
}
|
||||
|
||||
public interface IApprovalEventRepository : IRepository<ApprovalEvent>
|
||||
{
|
||||
}
|
||||
30
src/Oms.SqlSugarCore/Approval/ApprovalRepositories.cs
Normal file
30
src/Oms.SqlSugarCore/Approval/ApprovalRepositories.cs
Normal file
@ -0,0 +1,30 @@
|
||||
using Fake.DependencyInjection;
|
||||
using Oms.Domain.ApprovalAggregate.Entities;
|
||||
using Oms.Domain.ApprovalAggregate.Repositories;
|
||||
using Oms.SqlSugarCore.Repositories;
|
||||
|
||||
namespace Oms.SqlSugarCore.Approval;
|
||||
|
||||
public class ApprovalDefinitionRepository : OmsSqlSugarRepository<ApprovalDefinition>,
|
||||
IApprovalDefinitionRepository,
|
||||
IScopedDependency
|
||||
{
|
||||
}
|
||||
|
||||
public class ApprovalInstanceRepository : OmsSqlSugarRepository<ApprovalInstance>,
|
||||
IApprovalInstanceRepository,
|
||||
IScopedDependency
|
||||
{
|
||||
}
|
||||
|
||||
public class ApprovalTaskRepository : OmsSqlSugarRepository<ApprovalTask>,
|
||||
IApprovalTaskRepository,
|
||||
IScopedDependency
|
||||
{
|
||||
}
|
||||
|
||||
public class ApprovalEventRepository : OmsSqlSugarRepository<ApprovalEvent>,
|
||||
IApprovalEventRepository,
|
||||
IScopedDependency
|
||||
{
|
||||
}
|
||||
@ -0,0 +1,50 @@
|
||||
using Fake.Data.Seeding;
|
||||
using Fake.Rbac.Application.Services;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
|
||||
namespace SimpleAdmin.Api.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// 将审批权限码合并进 Admin 角色(Admin 本就全量菜单,此处便于角色管理可见/非 Admin 复用)。
|
||||
/// </summary>
|
||||
public class ApprovalRolePermissionSeedContributor(RoleService roleService) : IDataSeedContributor
|
||||
{
|
||||
public static readonly string[] Permissions =
|
||||
[
|
||||
ApprovalPermissionCodes.DefinitionQuery,
|
||||
ApprovalPermissionCodes.DefinitionCreate,
|
||||
ApprovalPermissionCodes.DefinitionUpdate,
|
||||
ApprovalPermissionCodes.DefinitionDelete,
|
||||
ApprovalPermissionCodes.DefinitionEnable,
|
||||
ApprovalPermissionCodes.TaskQuery,
|
||||
ApprovalPermissionCodes.TaskApprove,
|
||||
ApprovalPermissionCodes.TaskReject,
|
||||
"System.ApprovalDefinition",
|
||||
"System.ApprovalTask"
|
||||
];
|
||||
|
||||
public async Task SeedAsync()
|
||||
{
|
||||
var roles = await roleService.GetAllRolesAsync();
|
||||
var admin = roles.FirstOrDefault(x =>
|
||||
string.Equals(x.Code, XhsRolePermissionSeedContributor.AdminRoleCode, StringComparison.OrdinalIgnoreCase));
|
||||
if (admin == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var existing = await roleService.GetRolePermissionsAsync(admin.Id);
|
||||
var merged = existing
|
||||
.Concat(Permissions)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
|
||||
if (merged.Count == existing.Count &&
|
||||
Permissions.All(p => existing.Contains(p, StringComparer.OrdinalIgnoreCase)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await roleService.AssignPermissionsAsync(admin.Id, merged);
|
||||
}
|
||||
}
|
||||
11
tools/ApprovalSmoke/ApprovalSmoke.csproj
Normal file
11
tools/ApprovalSmoke/ApprovalSmoke.csproj
Normal file
@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Oms.Application\Oms.Application.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
25
tools/ApprovalSmoke/Program.cs
Normal file
25
tools/ApprovalSmoke/Program.cs
Normal file
@ -0,0 +1,25 @@
|
||||
using Fake.Application;
|
||||
using Oms.Application.Services.Approval;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
|
||||
// 无库烟测:ID 解析 + 条件求值(空工厂)
|
||||
var ids = ApprovalIdHelper.SplitIds("a, b; c,d");
|
||||
if (ids.Count != 4) throw new Exception($"SplitIds failed: {ids.Count}");
|
||||
if (!ApprovalIdHelper.ContainsId("a,b,c", "B")) throw new Exception("ContainsId case failed");
|
||||
|
||||
var evaluator = new ApprovalConditionEvaluator(Array.Empty<IApprovalConditionContextFactory>());
|
||||
evaluator.EnsureFormulaAllowed("System.Approval.Simulate", null);
|
||||
try
|
||||
{
|
||||
evaluator.EnsureFormulaAllowed("System.Approval.Simulate", "金额 > 1");
|
||||
throw new Exception("Simulate should reject non-empty formula");
|
||||
}
|
||||
catch (BusinessException)
|
||||
{
|
||||
// expected
|
||||
}
|
||||
|
||||
var (ok, matched, msg) = evaluator.TryTest("Finance.Recharge.Credit", null, null);
|
||||
if (!ok || !matched) throw new Exception($"empty formula should match: {msg}");
|
||||
|
||||
Console.WriteLine("ApprovalSmoke OK");
|
||||
Loading…
Reference in New Issue
Block a user