using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Nodes;
using Admin.NET.Core;
using Admin.NET.Plugin.AiDOP.Entity.S7;
using Admin.NET.Plugin.AiDOP.FinishedWarehouse;
using Admin.NET.Plugin.ApprovalFlow;
using Microsoft.Extensions.Logging;
namespace Admin.NET.Plugin.AiDOP.Service.S7;
/// 迁移结果。分项计数,运维要能看出「这次到底动了什么、什么被挡下了」。
public sealed class S7FlowAuthorityMigrationResult
{
/// 通过全部安全谓词、进入逐条处理的候选实例数。
public int CandidatesSelected { get; set; }
/// 本次实际改写快照的实例数。
public int Applied { get; set; }
/// 目标租户角色缺失 / 禁用 / 无同租户成员 / 角色不唯一 / 目标 Code 不在允许集 → 未改。
public int BlockedByTargetAuthority { get; set; }
/// 回滚来源缺失或不唯一 → 未改。
public int BlockedByRollbackSource { get; set; }
/// 改写落在 N2/N3 之外的 JSON 路径 → 未改。
public int BlockedByChangedPath { get; set; }
/// UPDATE 影响行数 ≠ 1(期间被并发改动)→ 已回滚。
public int BlockedByConcurrentModification { get; set; }
}
///
/// S7-LEGACY-SNAPSHOT-MIGRATION-1:把**仍在运行**的 S7 成品检验流程实例快照里冻结的
/// 默认租户物理 RoleId 改写为 RoleCode,让它们在租户本地化模型下继续流转。
///
/// 问题形态(已取证,非推测):StartFlowCore 落实例时把
/// ApprovalFlow.FlowJson 整体冻结进 FlowJsonSnapshot(:128),此后
/// **所有推进路径一律读快照、再不看定义**(:180/302/366/467/515/555/1230)。因此
/// 2026-09-14 的 S7 租户本地化(定义 N2/N3 由 1329915020002/1329915020003
/// 改成 RoleCode)**只对新发起的实例生效**;此前发起且仍未走完的实例,快照里那个默认租户
/// RoleId 只能靠 9 条跨租户 SysUserRole 绑定才解析得出人 —— 那些绑定本身是待清理的缺陷。
///
/// 为什么不做 runtime auto-heal:运行时隐式把 A 角色当 B 角色执行,会让
/// 「执行的」与「快照里展示的」永久分离,比显式改写更难解释;而放宽引擎门禁会同时影响新实例。
/// 故本服务是 显式、一次性、可审计、可回滚的数据迁移,不是 resolver 兼容层。
///
/// 批次边界(关键):只处理 之前发起的实例。该时点是
/// S7 RoleCode 定义发布之前;此后发起的实例本就会拿到 RoleCode 快照 —— 若之后仍出现默认租户
/// RoleId,那是**新的 authority regression**,必须让它响亮失败被人看见,绝不能被本服务静默治好。
/// 这条边界是「一次性迁移」与「长期 auto-heal」的分界线。
///
/// 只修坏的,不碰好的:终态实例一律不动(对 runtime 已无影响,改了没用,
/// 却百分之百是纯历史记录);同租户的物理 RoleId 也不动(numeric ≠ bad);
/// N1 是 Initiator 节点,本服务只看 approverType == Role,天然不会碰它。
///
/// 与 S6 的关系:设计思想、门禁顺序、并发守卫、事务边界全部镜像已验证的
/// S6LegacyFlowAuthorityMigrationService。未复用该类本体,因为它的 TargetBizTypes
/// 与租户反查都硬绑 S6 两条链,泛化它就要改 S6 已关闭的逻辑。
///
public class S7LegacyFlowAuthorityMigrationService : ITransient
{
/// 本迁移只处理 S7 成品检验链。
internal static IReadOnlyList TargetBizTypes { get; } =
new List { FqcInspBillFlowConst.BizType };
///
/// 允许被改写的节点 —— 只有主管审核与 QE 处置两个 Role 节点。
/// N1(N1_INSPECT)是 Initiator 节点,不在此列也不该出现在改写路径里。
///
internal static IReadOnlySet MigratableNodeIds { get; } =
new HashSet(StringComparer.Ordinal)
{
FqcInspBillFlowConst.NodeSupervisor,
FqcInspBillFlowConst.NodeDisposition,
};
///
/// 允许作为改写目标的 RoleCode 白名单。目标 Code 是从 legacy 角色行的 SysRole.Code
/// 反查来的(比硬编码映射更可靠:Code 若与预期不符会被本白名单挡下,而不是静默写入意外值)。
///
internal static IReadOnlySet AllowedTargetRoleCodes { get; } =
new HashSet(StringComparer.Ordinal)
{
FqcInspBillFlowConst.RoleSupervisorCode,
FqcInspBillFlowConst.RoleQeCode,
};
///
/// 批次边界。S7 租户本地 RoleCode 定义于 2026-09-14 晚间发布(S7FQC_T*),
/// 此后发起的实例快照本就是 RoleCode。之后再出现默认租户 RoleId = 新缺陷,
/// 不属本次迁移范围,必须 fail-closed 暴露。
///
private static readonly DateTime BatchCutoff = new(2026, 9, 14, 22, 0, 0, DateTimeKind.Unspecified);
private const string BatchPrefix = "S7-LEGACY-SNAPSHOT-MIGRATION-1";
private readonly ISqlSugarClient _db;
private readonly SqlSugarRepository _logRep;
private readonly ILogger _logger;
public S7LegacyFlowAuthorityMigrationService(
ISqlSugarClient db,
SqlSugarRepository logRep,
ILogger logger)
{
_db = db;
_logRep = logRep;
_logger = logger;
}
///
/// 选出候选(**只读,不写任何表,包括迁移留证表**)。Apply 与 dry-run 共用同一段谓词,
/// 避免「预演看到的」和「实际改的」是两套逻辑。
///
public async Task> SelectCandidatesAsync()
{
var candidates = new List();
// ① 运行中 + 批次边界内。ApprovalFlowInstance 无 TenantId 列,租户后面由业务实体反查。
// bizTypes / cutoff 取局部变量:SqlSugar 的表达式解析器无法把静态成员翻成 SQL 参数。
var bizTypes = TargetBizTypes.ToList();
var cutoff = BatchCutoff;
var instances = await _db.Queryable().ClearFilter()
.Where(x => bizTypes.Contains(x.BizType)
&& x.Status == FlowInstanceStatusEnum.Running
&& x.StartTime < cutoff)
.ToListAsync();
foreach (var inst in instances)
{
// ② ACTIVE 的完整判据:不能只看 Status —— 终态实例的 CurrentNodeId 可能仍停在
// N3_* 而非 end(实测 S7 有 3 条这样的终态实例),只看状态字段会误判。
var hasPending = await _db.Queryable().ClearFilter()
.AnyAsync(t => t.InstanceId == inst.Id && t.Status == FlowTaskStatusEnum.Pending);
if (!hasPending) continue;
// ③ Business Tenant 必须由 S7 业务实体反查,禁止取登录用户租户 / 定义租户 /
// 发起人租户 / 待办人租户 —— 实测这四者在 S7 存量实例上互不相等。
var tenantId = await ResolveBusinessTenantAsync(inst.BizType, inst.BizId);
if (tenantId is not > 0) continue;
// ④ 快照里是否还存在「Role 节点 + 纯数字 token」。这同时就是幂等判据的补集:
// 迁完之后本条恒为 false,第二次运行自然选不中;上一批新建的 RoleCode 实例
// 也因此天然被排除(它们的 approverIds 是 Code,没有数字 token)。
var refs = ParseNumericRoleRefs(inst.FlowJsonSnapshot);
if (refs.Count == 0) continue;
candidates.Add(new S7MigrationCandidate
{
Instance = inst,
BusinessTenantId = tenantId.Value,
NumericRefs = refs,
});
}
return candidates;
}
/// 执行迁移。每个候选独立事务:留证 INSERT 与快照 UPDATE 原子提交,任一失败整条回滚。
public async Task MigrateAsync(CancellationToken ct = default)
{
var result = new S7FlowAuthorityMigrationResult();
var batch = $"{BatchPrefix}@{DateTime.Now:yyyyMMddHHmmss}";
List candidates;
try
{
candidates = await SelectCandidatesAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "S7 legacy flow authority migration: 候选选取失败,本次跳过");
return result;
}
result.CandidatesSelected = candidates.Count;
foreach (var c in candidates)
{
if (ct.IsCancellationRequested) break;
await MigrateOneAsync(c, batch, result);
}
// 无条件记一行汇总 —— 「本次 0 候选 0 改动」本身就是要被看见的结论:
// 迁移已收敛的证据,以及「未来若冒出新候选会被立刻发现」的可观测性基础。
_logger.LogInformation(
"S7LegacyFlowAuthorityMigration batch={Batch} selected={Selected} applied={Applied} "
+ "blockedTargetAuthority={BlockedTarget} blockedRollbackSource={BlockedRollback} "
+ "blockedChangedPath={BlockedPath} blockedConcurrent={BlockedConcurrent}",
batch, result.CandidatesSelected, result.Applied,
result.BlockedByTargetAuthority, result.BlockedByRollbackSource,
result.BlockedByChangedPath, result.BlockedByConcurrentModification);
return result;
}
///
/// 预演(**只读,不写任何表,包括迁移留证表**)。与 Apply 共用
/// 与 :预演看到的门禁结论就是 Apply 会走的那一条,不存在两套逻辑。
///
public async Task> DryRunAsync()
{
var report = new List();
foreach (var c in await SelectCandidatesAsync())
report.Add(await EvaluateAsync(c));
// 预演结论必须可观测:用服务自己的 ILogger 输出(Startup 里的 Trace 不进应用日志文件)。
_logger.LogInformation("S7MigrationDryRun candidates={Count} applicable={Ok} blocked={Blocked}",
report.Count, report.Count(x => x.CanApply), report.Count(x => !x.CanApply));
foreach (var r in report)
_logger.LogInformation(
"S7MigrationDryRun inst={Inst} tenant={Tenant} node={Node} canApply={CanApply} "
+ "beforeMd5={Before} afterMd5={After} changedNodes=[{Nodes}] paths={Paths} "
+ "mapping={Mapping} rollback={Rollback} outcome={Outcome} reason={Reason}",
r.Candidate.Instance.Id, r.Candidate.BusinessTenantId, r.Candidate.Instance.CurrentNodeId,
r.CanApply, r.BeforeMd5, r.AfterMd5, string.Join(",", r.ChangedNodeIds), r.ChangedPaths,
string.Join(" | ", r.Mappings), r.RollbackSource, r.Outcome, r.Reason);
return report;
}
private async Task MigrateOneAsync(S7MigrationCandidate c, string batch, S7FlowAuthorityMigrationResult result)
{
var e = await EvaluateAsync(c);
if (!e.CanApply)
{
await BlockAsync(c, batch, e.BeforeMd5, e.Mappings, e.ChangedPaths, e.Outcome!, e.Reason!,
result, _ =>
{
switch (e.Outcome)
{
case "BLOCKED_CHANGED_PATH": result.BlockedByChangedPath++; break;
case "BLOCKED_ROLLBACK_SOURCE": result.BlockedByRollbackSource++; break;
default: result.BlockedByTargetAuthority++; break;
}
});
return;
}
await ApplyOneAsync(c, e, batch, result);
}
///
/// 逐条跑完全部门禁并算出改写结果,**不写库**。返回「可应用的计划」或「被挡下的原因」。
/// 抽出这一层的目的:让 dry-run 与 apply 在代码上无法分叉。
///
private async Task EvaluateAsync(S7MigrationCandidate c)
{
var inst = c.Instance;
var before = inst.FlowJsonSnapshot ?? string.Empty;
var beforeMd5 = Md5(before);
// ── Gate 1:逐 token 解析目标角色。任一 token 映射不出来 → 整条实例不迁(禁止部分迁移,
// 否则会留下半新半旧的快照,比全旧更难排查)。
var mappings = new List();
var tokenMap = new Dictionary(StringComparer.Ordinal);
foreach (var r in c.NumericRefs)
{
// Gate 1a:数字引用只允许出现在 N2/N3 两个可迁节点上。出现在别处说明快照结构
// 与预期不符(例如 N1 被改成过 Role),必须停下让人看,而不是顺手改。
if (!MigratableNodeIds.Contains(r.NodeId))
{
return Blocked(c, beforeMd5, mappings, null, "BLOCKED_CHANGED_PATH",
$"节点 {r.NodeId} 含数字 Role 引用,但它不在可迁节点集 "
+ $"[{string.Join(",", MigratableNodeIds)}] 内");
}
foreach (var token in r.NumericTokens)
{
if (tokenMap.ContainsKey(token)) continue;
var legacyRole = await _db.Queryable().ClearFilter()
.Where(x => x.Id == long.Parse(token)).FirstAsync();
if (legacyRole == null)
{
return Blocked(c, beforeMd5, mappings, null, "BLOCKED_TARGET_AUTHORITY",
$"legacy RoleId {token} 在 SysRole 中不存在");
}
// 同租户的物理 RoleId 是合法引用,不是缺陷 —— 不得因为「是数字」就改它。
if (legacyRole.TenantId == c.BusinessTenantId)
{
return Blocked(c, beforeMd5, mappings, null, "BLOCKED_TARGET_AUTHORITY",
$"RoleId {token} 属于本租户 {c.BusinessTenantId},非跨租户引用,不在迁移范围");
}
var code = legacyRole.Code;
if (string.IsNullOrWhiteSpace(code))
{
return Blocked(c, beforeMd5, mappings, null, "BLOCKED_TARGET_AUTHORITY",
$"legacy RoleId {token} 无 Code,无法映射");
}
// Gate 1b:目标 Code 必须在 S7 白名单内。防止「legacy 行的 Code 不是我们以为的那个」
// 时把意外值写进快照。
if (!AllowedTargetRoleCodes.Contains(code))
{
return Blocked(c, beforeMd5, mappings, null, "BLOCKED_TARGET_AUTHORITY",
$"legacy RoleId {token} 的 Code={code} 不在 S7 允许的目标 Code 集 "
+ $"[{string.Join(",", AllowedTargetRoleCodes)}] 内");
}
// Gate 2:目标租户下该 Code 必须**恰好一个**启用角色。不得 First() 随便挑。
var targets = await _db.Queryable().ClearFilter()
.Where(x => x.TenantId == c.BusinessTenantId && x.Code == code && x.Status == StatusEnum.Enable)
.ToListAsync();
if (targets.Count != 1)
{
return Blocked(c, beforeMd5, mappings, null, "BLOCKED_TARGET_AUTHORITY",
targets.Count == 0
? $"目标租户 {c.BusinessTenantId} 下不存在启用的 {code}"
: $"目标租户 {c.BusinessTenantId} 下 {code} 有 {targets.Count} 个,AMBIGUOUS TARGET ROLE");
}
var target = targets[0];
// Gate 3:目标角色必须至少有一个**同租户**成员,否则迁完仍旧解析 0 人。
var memberIds = await _db.Queryable().ClearFilter()
.Where(x => x.RoleId == target.Id).Select(x => x.UserId).ToListAsync();
var sameTenantMembers = memberIds.Count == 0 ? 0
: await _db.Queryable().ClearFilter()
.CountAsync(u => memberIds.Contains(u.Id) && u.TenantId == c.BusinessTenantId);
if (sameTenantMembers == 0)
{
return Blocked(c, beforeMd5, mappings, null, "BLOCKED_TARGET_AUTHORITY",
$"目标角色 {code}@{c.BusinessTenantId}(RoleId {target.Id})无同租户成员");
}
tokenMap[token] = code;
mappings.Add($"node={r.NodeId};{token}=>{code}@{target.Id};members={sameTenantMembers}");
}
}
// ── Gate 4:回滚来源必须唯一且与当前快照逐字节一致。ApprovalFlowVersion 全库存在
// (FlowId,Version) 重复行、该表也没有唯一约束 —— 这道门禁不是形式主义。
// 注意:改前快照全文本身已落 before_snapshot(第一回滚来源),本门禁是第二来源校验。
var versionRows = await _db.Queryable().ClearFilter()
.Where(v => v.FlowId == inst.FlowId && v.Version == inst.FlowVersion).ToListAsync();
var usable = versionRows.Where(v => Md5(v.FlowJson ?? string.Empty) == beforeMd5).ToList();
if (versionRows.Count != 1 || usable.Count != 1)
{
return Blocked(c, beforeMd5, mappings, null, "BLOCKED_ROLLBACK_SOURCE",
$"ApprovalFlowVersion(FlowId={inst.FlowId},Version={inst.FlowVersion}) 命中 {versionRows.Count} 行、"
+ $"其中与当前快照 MD5 一致 {usable.Count} 行;要求恰好 1/1");
}
var rollbackSource = $"ApprovalFlowVersion#{usable[0].Id}";
// ── 结构化改写:只动 Role 节点的 approverIds,其余一律不碰。禁止字符串替换。
var rewrite = RewriteAuthority(before, tokenMap);
if (rewrite == null || rewrite.After == before)
{
return Blocked(c, beforeMd5, mappings, null, "BLOCKED_TARGET_AUTHORITY",
"结构化改写未产生变化或解析失败");
}
// ── Gate 5:改写路径必须全部落在 N2/N3 的 approverIds 上。这是对改写实现的独立复核,
// 不依赖 RewriteAuthority 自己的自觉(§14 精确路径门禁)。
var illegal = rewrite.ChangedNodeIds.Where(n => !MigratableNodeIds.Contains(n)).ToList();
if (illegal.Count > 0)
{
return Blocked(c, beforeMd5, mappings, rewrite.ChangedPathText, "BLOCKED_CHANGED_PATH",
$"改写路径越界:{string.Join(",", illegal)} 不在可迁节点集内");
}
var after = rewrite.After;
return new S7MigrationEvaluation
{
Candidate = c,
CanApply = true,
Before = before,
BeforeMd5 = beforeMd5,
After = after,
AfterMd5 = Md5(after),
ChangedNodeIds = rewrite.ChangedNodeIds,
ChangedPaths = rewrite.ChangedPathText,
Mappings = mappings,
RollbackSource = rollbackSource,
};
}
/// 被门禁挡下的评估结论(不写库,由调用方决定是否落留证)。
private static S7MigrationEvaluation Blocked(S7MigrationCandidate c, string beforeMd5,
List mappings, string? changedPaths, string outcome, string reason) => new()
{
Candidate = c,
CanApply = false,
Before = c.Instance.FlowJsonSnapshot ?? string.Empty,
BeforeMd5 = beforeMd5,
Mappings = mappings,
ChangedPaths = changedPaths,
Outcome = outcome,
Reason = reason,
};
///
/// 落地一条已通过全部门禁的计划:留证 INSERT 与快照 UPDATE 同一事务,任一失败整条回滚。
///
private async Task ApplyOneAsync(S7MigrationCandidate c, S7MigrationEvaluation e,
string batch, S7FlowAuthorityMigrationResult result)
{
var inst = c.Instance;
// ── 留证 + 改写同一事务。任一失败整条回滚:不接受「改了但没留证」,
// 也不接受「留证说改了但实际没改」。
var tran = await _db.AsTenant().UseTranAsync(async () =>
{
await _logRep.AsInsertable(new AdoS7FlowAuthorityMigrationLog
{
MigrationBatch = batch,
MigrationKey = $"{BatchPrefix}#{inst.Id}",
InstanceId = inst.Id,
BizType = inst.BizType,
BizId = inst.BizId,
BusinessTenantId = c.BusinessTenantId,
BeforeSnapshot = e.Before,
AfterSnapshot = e.After,
BeforeMd5 = e.BeforeMd5,
AfterMd5 = e.AfterMd5,
ChangedPaths = e.ChangedPaths,
AuthorityMapping = string.Join(" | ", e.Mappings),
RollbackSource = e.RollbackSource,
Reason = "运行中实例的快照冻结了默认租户物理 RoleId,只能靠跨租户 SysUserRole 绑定解析;"
+ "改写为 RoleCode 后由引擎在本租户内重新解析,不再依赖跨租户绑定",
AppliedBy = MigrationIdentity(),
Outcome = "APPLIED",
}).ExecuteCommandAsync();
// 并发守卫:实例表无 version/checksum,只能用「改前 MD5 + 状态」作乐观锁。
// 用裸 SQL 精确只改这一列,避免整实体 Updateable 把过期读到的其它列一并回写
// (FlowId / FlowVersion / CurrentNodeId / InitiatorId 因此天然不受影响)。
var affected = await _db.Ado.ExecuteCommandAsync(
"""
UPDATE ApprovalFlowInstance
SET FlowJsonSnapshot=@after
WHERE Id=@id AND Status=@running AND MD5(FlowJsonSnapshot)=@beforeMd5
""",
new List
{
new("@after", e.After), new("@id", inst.Id),
new("@running", (int)FlowInstanceStatusEnum.Running), new("@beforeMd5", e.BeforeMd5),
});
if (affected != 1)
throw Oops.Oh($"CONCURRENT MODIFICATION:实例 {inst.Id} 期间被改动,affected={affected}");
});
if (!tran.IsSuccess)
{
result.BlockedByConcurrentModification++;
_logger.LogWarning(tran.ErrorException,
"S7LegacyFlowAuthorityMigration: 实例 {InstanceId} 迁移失败已整体回滚", inst.Id);
return;
}
result.Applied++;
_logger.LogInformation(
"S7LegacyFlowAuthorityMigration APPLIED instance={InstanceId} bizType={BizType} bizId={BizId} "
+ "tenant={Tenant} beforeMd5={BeforeMd5} afterMd5={AfterMd5} paths={Paths} mapping={Mapping}",
inst.Id, inst.BizType, inst.BizId, c.BusinessTenantId, e.BeforeMd5, e.AfterMd5,
e.ChangedPaths, string.Join(" | ", e.Mappings));
}
/// 挡下的候选同样留证 —— 「为什么没迁」和「为什么迁了」一样需要能回答。
private async Task BlockAsync(S7MigrationCandidate c, string batch, string beforeMd5,
List mappings, string? changedPaths, string outcome, string reason,
S7FlowAuthorityMigrationResult result, Action bump)
{
bump(result);
await _logRep.AsInsertable(new AdoS7FlowAuthorityMigrationLog
{
MigrationBatch = batch,
MigrationKey = $"{BatchPrefix}#{c.Instance.Id}",
InstanceId = c.Instance.Id,
BizType = c.Instance.BizType,
BizId = c.Instance.BizId,
BusinessTenantId = c.BusinessTenantId,
BeforeSnapshot = c.Instance.FlowJsonSnapshot,
BeforeMd5 = beforeMd5,
ChangedPaths = changedPaths,
AuthorityMapping = mappings.Count == 0 ? null : string.Join(" | ", mappings),
Reason = reason,
AppliedBy = MigrationIdentity(),
Outcome = outcome,
}).ExecuteCommandAsync();
_logger.LogWarning("S7LegacyFlowAuthorityMigration {Outcome} instance={InstanceId} reason={Reason}",
outcome, c.Instance.Id, reason);
}
///
/// 迁移执行身份。本迁移以系统身份在启动期运行、没有登录用户上下文,
/// 故记录「执行体 + 主机」;不伪造 UserId。
///
private static string MigrationIdentity() => $"{BatchPrefix}@{Environment.MachineName}";
///
/// Business Tenant 由 S7 业务实体反查。ApprovalFlowInstance 自身没有 TenantId 列,
/// 而推进时引擎用的是登录租户 —— 迁移绝不能沿用那条路径,否则会把租户判定建立在
/// 「谁在执行迁移」而不是「这条单据属于谁」之上。
///
private async Task ResolveBusinessTenantAsync(string bizType, long bizId) => bizType switch
{
// BizId = qms_qcpp_inspbill.id(见 FqcInspBillFlowService 头部注释)
"S7_FQC_INSPBILL" => await _db.Ado.SqlQuerySingleAsync(
"SELECT tenant_id FROM qms_qcpp_inspbill WHERE id=@id LIMIT 1",
new List { new("@id", bizId) }),
_ => null,
};
///
/// 解析快照中「approverType==Role 且 approverIds 含纯数字 token」的节点。
///
/// 必须按 JSON 结构解析、结合 approverType 判断语义,不能只 grep 数字:
/// 同一个 Id 既可能是合法 SysRole.Id 又是合法 SysUser.Id,而
/// SpecificUser / Department 节点里的数字分别是 UserId / OrgId,
/// 纯数字匹配会把它们误判成 RoleId;Initiator 节点(S7 的 N1)则根本没有 approverIds。
///
internal static List ParseNumericRoleRefs(string? snapshot)
{
var refs = new List();
if (string.IsNullOrWhiteSpace(snapshot)) return refs;
JsonNode? root;
try { root = JsonNode.Parse(snapshot); }
catch { return refs; }
if (root?["nodes"] is not JsonArray nodes) return refs;
foreach (var node in nodes)
{
var props = node?["properties"];
if (props == null) continue;
if (props["approverType"]?.GetValue() != nameof(ApproverTypeEnum.Role)) continue;
var ids = props["approverIds"]?.GetValue();
if (string.IsNullOrWhiteSpace(ids)) continue;
var numeric = ids.Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Trim())
.Where(s => s.Length > 0 && long.TryParse(s, out var v) && v > 0)
.Distinct(StringComparer.Ordinal)
.ToList();
if (numeric.Count == 0) continue;
refs.Add(new S7NumericRoleRef
{
NodeId = node?["id"]?.GetValue() ?? string.Empty,
ApproverIds = ids,
NumericTokens = numeric,
});
}
return refs;
}
///
/// 结构化改写:只把 Role 节点 approverIds 里的数字 token 换成对应 RoleCode,
/// 保持 token 原顺序与原数量。节点 id / 名称 / approverType / approverNames /
/// edges / 网关条件一概不动;Initiator 节点不进入循环体。
/// 同时返回被改动的节点与可读路径,供调用方做独立的路径门禁复核。
///
internal static S7AuthorityRewrite? RewriteAuthority(string snapshot, IReadOnlyDictionary tokenMap)
{
JsonNode? root;
try { root = JsonNode.Parse(snapshot); }
catch { return null; }
if (root?["nodes"] is not JsonArray nodes) return null;
var changedNodes = new List();
var paths = new List();
foreach (var node in nodes)
{
var props = node?["properties"];
if (props == null) continue;
if (props["approverType"]?.GetValue() != nameof(ApproverTypeEnum.Role)) continue;
var ids = props["approverIds"]?.GetValue();
if (string.IsNullOrWhiteSpace(ids)) continue;
var tokens = ids.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList();
if (tokens.Count == 0) continue;
var rewritten = tokens.Select(t => tokenMap.TryGetValue(t, out var code) ? code : t).ToList();
var joined = string.Join(",", rewritten);
if (joined == ids) continue;
props["approverIds"] = joined;
var nodeId = node?["id"]?.GetValue() ?? string.Empty;
changedNodes.Add(nodeId);
paths.Add($"nodes[id={nodeId}].properties.approverIds: \"{ids}\" => \"{joined}\"");
}
if (changedNodes.Count == 0) return null;
return new S7AuthorityRewrite
{
After = root!.ToJsonString(),
ChangedNodeIds = changedNodes,
ChangedPathText = string.Join(" | ", paths),
};
}
private static string Md5(string s)
{
var bytes = MD5.HashData(Encoding.UTF8.GetBytes(s));
return Convert.ToHexString(bytes).ToLowerInvariant();
}
}
/// 候选实例 + 其反查出的业务租户 + 快照中待迁的数字角色引用。
public sealed class S7MigrationCandidate
{
public ApprovalFlowInstance Instance { get; set; } = null!;
public long BusinessTenantId { get; set; }
public List NumericRefs { get; set; } = new();
}
/// 快照中一个 Role 节点里的数字角色引用。
public sealed class S7NumericRoleRef
{
public string NodeId { get; set; } = string.Empty;
public string ApproverIds { get; set; } = string.Empty;
public List NumericTokens { get; set; } = new();
}
///
/// 逐条评估结论:要么是一份「可应用的计划」,要么是「被哪道门禁挡下、为什么」。
/// Dry-run 与 Apply 消费同一个对象,因此预演输出与实际改写在代码上无法分叉。
///
public sealed class S7MigrationEvaluation
{
public S7MigrationCandidate Candidate { get; set; } = null!;
public bool CanApply { get; set; }
public string Before { get; set; } = string.Empty;
public string BeforeMd5 { get; set; } = string.Empty;
/// 仅 为真时有值。
public string? After { get; set; }
public string? AfterMd5 { get; set; }
public List ChangedNodeIds { get; set; } = new();
public string? ChangedPaths { get; set; }
public List Mappings { get; set; } = new();
public string? RollbackSource { get; set; }
/// 被挡下时的 outcome 码与原因;可应用时为 null。
public string? Outcome { get; set; }
public string? Reason { get; set; }
}
/// 结构化改写结果:改后全文 + 被改动节点 + 可读路径。
public sealed class S7AuthorityRewrite
{
public string After { get; set; } = string.Empty;
public List ChangedNodeIds { get; set; } = new();
public string ChangedPathText { get; set; } = string.Empty;
}