S6LegacyFlowAuthorityMigrationService.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. using System.Security.Cryptography;
  2. using System.Text;
  3. using System.Text.Json.Nodes;
  4. using Admin.NET.Core;
  5. using Admin.NET.Plugin.AiDOP.Entity.S6;
  6. using Admin.NET.Plugin.ApprovalFlow;
  7. using Microsoft.Extensions.Logging;
  8. namespace Admin.NET.Plugin.AiDOP.Service.S6;
  9. /// <summary>迁移结果。分项计数,运维要能看出「这次到底动了什么、什么被挡下了」。</summary>
  10. public sealed class S6FlowAuthorityMigrationResult
  11. {
  12. /// <summary>通过全部安全谓词、进入逐条处理的候选实例数。</summary>
  13. public int CandidatesSelected { get; set; }
  14. /// <summary>本次实际改写快照的实例数。</summary>
  15. public int Applied { get; set; }
  16. /// <summary>目标租户角色缺失 / 禁用 / 无同租户成员 / 角色不唯一 → 未改。</summary>
  17. public int BlockedByTargetAuthority { get; set; }
  18. /// <summary>回滚来源缺失或不唯一 → 未改。</summary>
  19. public int BlockedByRollbackSource { get; set; }
  20. /// <summary>UPDATE 影响行数 ≠ 1(期间被并发改动)→ 已回滚。</summary>
  21. public int BlockedByConcurrentModification { get; set; }
  22. }
  23. /// <summary>
  24. /// S6-LEGACY-SNAPSHOT-MIGRATION-1:把**仍在运行**的 S6 流程实例快照里冻结的
  25. /// 跨租户物理 RoleId 改写为 RoleCode,让它们能在租户本地化模型下继续流转。
  26. ///
  27. /// <para><b>问题形态</b>(已取证,非推测):<c>StartFlowCore</c> 落实例时把
  28. /// <c>ApprovalFlow.FlowJson</c> 整体冻结进 <c>FlowJsonSnapshot</c>,此后**所有推进路径
  29. /// 一律读快照、再不看定义**。因此 2026-09-14 的租户本地化迁移(把定义的 approverIds
  30. /// 从默认租户物理 RoleId 改成 RoleCode)**只对新发起的实例生效**;此前发起且仍未走完的
  31. /// 实例,快照里那个跨租户 RoleId 会被 <c>EnsureRoleAuthorityTenantScopedAsync</c>
  32. /// 直接 fail-closed 拒绝,单据永久卡死。</para>
  33. ///
  34. /// <para><b>为什么不做 runtime auto-heal</b>:引擎里「跨租户 RoleId 一律拒绝」是刚建立的
  35. /// 门禁,放宽它会同时影响**新**实例,等于把门拆掉;而运行时隐式把 A 角色当 B 角色执行,
  36. /// 会让「执行的」与「快照里展示的」永久分离,比显式改写更难解释。故本服务是
  37. /// <b>显式、一次性、可审计的数据迁移</b>,不是 resolver 兼容层。</para>
  38. ///
  39. /// <para><b>批次边界(关键)</b>:只处理 <see cref="BatchCutoff"/> 之前发起的实例。
  40. /// 该时点之后发起的实例本就会拿到 RoleCode 快照 —— 若之后仍出现跨租户 RoleId,
  41. /// 那是**新的 authority regression**,必须让它响亮地失败、被人看见,
  42. /// 绝不能被本服务静默治好。这条边界是「一次性迁移」与「长期 auto-heal」的分界线。</para>
  43. ///
  44. /// <para><b>只修坏的,不碰好的</b>:终态实例一律不动(对 runtime 已无影响,改了没用,
  45. /// 却百分之百是纯历史记录);同租户的物理 RoleId 也不动(numeric ≠ bad)。</para>
  46. /// </summary>
  47. public class S6LegacyFlowAuthorityMigrationService : ITransient
  48. {
  49. /// <summary>与 <c>FlowEngineService.TenantStrictRoleBizTypes</c> 逐字一致:只有被严格守卫的链才需要迁。</summary>
  50. internal static IReadOnlyList<string> TargetBizTypes { get; } =
  51. new List<string> { "IPQC_INSPECTION", "S6_PROCESS_INSPECTION" };
  52. /// <summary>
  53. /// 批次边界。租户本地 RoleCode 定义于 2026-09-14 发布,此后发起的实例快照本就是 RoleCode。
  54. /// 之后再出现跨租户 RoleId = 新缺陷,不属本次迁移范围,必须 fail-closed 暴露。
  55. /// </summary>
  56. private static readonly DateTime BatchCutoff = new(2026, 9, 14, 0, 0, 0, DateTimeKind.Unspecified);
  57. private const string BatchPrefix = "S6-LEGACY-SNAPSHOT-MIGRATION-1";
  58. private readonly ISqlSugarClient _db;
  59. private readonly SqlSugarRepository<AdoS6FlowAuthorityMigrationLog> _logRep;
  60. private readonly ILogger<S6LegacyFlowAuthorityMigrationService> _logger;
  61. public S6LegacyFlowAuthorityMigrationService(
  62. ISqlSugarClient db,
  63. SqlSugarRepository<AdoS6FlowAuthorityMigrationLog> logRep,
  64. ILogger<S6LegacyFlowAuthorityMigrationService> logger)
  65. {
  66. _db = db;
  67. _logRep = logRep;
  68. _logger = logger;
  69. }
  70. /// <summary>
  71. /// 选出候选(只读,不写任何东西)。Apply 与 dry-run 共用同一段谓词,
  72. /// 避免「预演看到的」和「实际改的」是两套逻辑。
  73. /// </summary>
  74. public async Task<List<S6MigrationCandidate>> SelectCandidatesAsync()
  75. {
  76. var candidates = new List<S6MigrationCandidate>();
  77. // ① 运行中 + 批次边界内。ApprovalFlowInstance 无 TenantId 列,租户后面由业务实体反查。
  78. // bizTypes / cutoff 取局部变量:SqlSugar 的表达式解析器无法把静态成员翻成 SQL 参数。
  79. var bizTypes = TargetBizTypes.ToList();
  80. var cutoff = BatchCutoff;
  81. var instances = await _db.Queryable<ApprovalFlowInstance>().ClearFilter()
  82. .Where(x => bizTypes.Contains(x.BizType)
  83. && x.Status == FlowInstanceStatusEnum.Running
  84. && x.StartTime < cutoff)
  85. .ToListAsync();
  86. foreach (var inst in instances)
  87. {
  88. // ② ACTIVE 的完整判据:不能只看 Status —— 终态实例的 CurrentNodeId 可能仍停在
  89. // N3_* 而非 end(CompleteInstance 不重写该字段),只看状态字段会误判。
  90. var hasPending = await _db.Queryable<ApprovalFlowTask>().ClearFilter()
  91. .AnyAsync(t => t.InstanceId == inst.Id && t.Status == FlowTaskStatusEnum.Pending);
  92. if (!hasPending) continue;
  93. // ③ Effective Tenant 必须由业务实体反查,禁止取登录用户租户 —— 迁移的租户判定
  94. // 绝不能复制「推进时按登录租户解析」那个既有结构缺陷。
  95. var tenantId = await ResolveEffectiveTenantAsync(inst.BizType, inst.BizId);
  96. if (tenantId is not > 0) continue;
  97. // ④ 快照里是否还存在「Role 节点 + 纯数字 token」。这同时就是幂等判据的补集:
  98. // 迁完之后本条恒为 false,第二次运行自然选不中。
  99. var refs = ParseNumericRoleRefs(inst.FlowJsonSnapshot);
  100. if (refs.Count == 0) continue;
  101. candidates.Add(new S6MigrationCandidate
  102. {
  103. Instance = inst,
  104. EffectiveTenantId = tenantId.Value,
  105. NumericRefs = refs,
  106. });
  107. }
  108. return candidates;
  109. }
  110. /// <summary>执行迁移。每个候选独立事务:留证 INSERT 与快照 UPDATE 原子提交,任一失败整条回滚。</summary>
  111. public async Task<S6FlowAuthorityMigrationResult> MigrateAsync(CancellationToken ct = default)
  112. {
  113. var result = new S6FlowAuthorityMigrationResult();
  114. var batch = $"{BatchPrefix}@{DateTime.Now:yyyyMMddHHmmss}";
  115. List<S6MigrationCandidate> candidates;
  116. try
  117. {
  118. candidates = await SelectCandidatesAsync();
  119. }
  120. catch (Exception ex)
  121. {
  122. _logger.LogError(ex, "S6 legacy flow authority migration: 候选选取失败,本次跳过");
  123. return result;
  124. }
  125. result.CandidatesSelected = candidates.Count;
  126. foreach (var c in candidates)
  127. {
  128. if (ct.IsCancellationRequested) break;
  129. await MigrateOneAsync(c, batch, result);
  130. }
  131. // 无条件记一行汇总 —— 「本次 0 候选 0 改动」本身就是要被看见的结论:
  132. // 迁移已收敛的证据,以及「未来若冒出新候选会被立刻发现」的可观测性基础。
  133. _logger.LogInformation(
  134. "S6LegacyFlowAuthorityMigration batch={Batch} selected={Selected} applied={Applied} "
  135. + "blockedTargetAuthority={BlockedTarget} blockedRollbackSource={BlockedRollback} blockedConcurrent={BlockedConcurrent}",
  136. batch, result.CandidatesSelected, result.Applied,
  137. result.BlockedByTargetAuthority, result.BlockedByRollbackSource, result.BlockedByConcurrentModification);
  138. return result;
  139. }
  140. private async Task MigrateOneAsync(S6MigrationCandidate c, string batch, S6FlowAuthorityMigrationResult result)
  141. {
  142. var inst = c.Instance;
  143. var before = inst.FlowJsonSnapshot ?? string.Empty;
  144. var beforeMd5 = Md5(before);
  145. // ── Gate 1:逐 token 解析目标角色。任一 token 映射不出来 → 整条实例不迁(禁止部分迁移,
  146. // 否则会留下半新半旧的快照,比全旧更难排查)。
  147. var mappings = new List<string>();
  148. var tokenMap = new Dictionary<string, string>(StringComparer.Ordinal);
  149. foreach (var r in c.NumericRefs)
  150. {
  151. foreach (var token in r.NumericTokens)
  152. {
  153. if (tokenMap.ContainsKey(token)) continue;
  154. var legacyRole = await _db.Queryable<SysRole>().ClearFilter()
  155. .Where(x => x.Id == long.Parse(token)).FirstAsync();
  156. if (legacyRole == null)
  157. {
  158. await BlockAsync(c, batch, beforeMd5, mappings, "BLOCKED_TARGET_AUTHORITY",
  159. $"legacy RoleId {token} 在 SysRole 中不存在", result, r => result.BlockedByTargetAuthority++);
  160. return;
  161. }
  162. // 同租户的物理 RoleId 是合法引用,不是缺陷 —— 不得因为「是数字」就改它。
  163. if (legacyRole.TenantId == c.EffectiveTenantId)
  164. {
  165. await BlockAsync(c, batch, beforeMd5, mappings, "BLOCKED_TARGET_AUTHORITY",
  166. $"RoleId {token} 属于本租户 {c.EffectiveTenantId},非跨租户引用,不在迁移范围",
  167. result, _ => result.BlockedByTargetAuthority++);
  168. return;
  169. }
  170. var code = legacyRole.Code;
  171. if (string.IsNullOrWhiteSpace(code))
  172. {
  173. await BlockAsync(c, batch, beforeMd5, mappings, "BLOCKED_TARGET_AUTHORITY",
  174. $"legacy RoleId {token} 无 Code,无法映射", result, _ => result.BlockedByTargetAuthority++);
  175. return;
  176. }
  177. // Gate 2:目标租户下该 Code 必须**恰好一个**启用角色。不得 First() 随便挑。
  178. var targets = await _db.Queryable<SysRole>().ClearFilter()
  179. .Where(x => x.TenantId == c.EffectiveTenantId && x.Code == code && x.Status == StatusEnum.Enable)
  180. .ToListAsync();
  181. if (targets.Count != 1)
  182. {
  183. await BlockAsync(c, batch, beforeMd5, mappings, "BLOCKED_TARGET_AUTHORITY",
  184. targets.Count == 0
  185. ? $"目标租户 {c.EffectiveTenantId} 下不存在启用的 {code}"
  186. : $"目标租户 {c.EffectiveTenantId} 下 {code} 有 {targets.Count} 个,AMBIGUOUS TARGET ROLE",
  187. result, _ => result.BlockedByTargetAuthority++);
  188. return;
  189. }
  190. var target = targets[0];
  191. // Gate 3:目标角色必须至少有一个**同租户**成员,否则迁完仍旧解析 0 人。
  192. var memberIds = await _db.Queryable<SysUserRole>().ClearFilter()
  193. .Where(x => x.RoleId == target.Id).Select(x => x.UserId).ToListAsync();
  194. var sameTenantMembers = memberIds.Count == 0 ? 0
  195. : await _db.Queryable<SysUser>().ClearFilter()
  196. .CountAsync(u => memberIds.Contains(u.Id) && u.TenantId == c.EffectiveTenantId);
  197. if (sameTenantMembers == 0)
  198. {
  199. await BlockAsync(c, batch, beforeMd5, mappings, "BLOCKED_TARGET_AUTHORITY",
  200. $"目标角色 {code}@{c.EffectiveTenantId}(RoleId {target.Id})无同租户成员",
  201. result, _ => result.BlockedByTargetAuthority++);
  202. return;
  203. }
  204. tokenMap[token] = code;
  205. mappings.Add($"node={r.NodeId};{token}=>{code}@{target.Id};members={sameTenantMembers}");
  206. }
  207. }
  208. // ── Gate 4:回滚来源必须唯一且与当前快照逐字节一致。ApprovalFlowVersion 全库存在
  209. // (FlowId,Version) 重复行,该表也没有唯一约束 —— 这道门禁不是形式主义。
  210. var versionRows = await _db.Queryable<ApprovalFlowVersion>().ClearFilter()
  211. .Where(v => v.FlowId == inst.FlowId && v.Version == inst.FlowVersion).ToListAsync();
  212. var usable = versionRows.Where(v => Md5(v.FlowJson ?? string.Empty) == beforeMd5).ToList();
  213. if (versionRows.Count != 1 || usable.Count != 1)
  214. {
  215. await BlockAsync(c, batch, beforeMd5, mappings, "BLOCKED_ROLLBACK_SOURCE",
  216. $"ApprovalFlowVersion(FlowId={inst.FlowId},Version={inst.FlowVersion}) 命中 {versionRows.Count} 行、"
  217. + $"其中与当前快照 MD5 一致 {usable.Count} 行;要求恰好 1/1",
  218. result, _ => result.BlockedByRollbackSource++);
  219. return;
  220. }
  221. var rollbackSource = $"ApprovalFlowVersion#{usable[0].Id}";
  222. // ── 结构化改写:只动 Role 节点的 approverIds,其余一律不碰。禁止字符串替换。
  223. var after = RewriteAuthority(before, tokenMap);
  224. if (after == null || after == before)
  225. {
  226. await BlockAsync(c, batch, beforeMd5, mappings, "BLOCKED_TARGET_AUTHORITY",
  227. "结构化改写未产生变化或解析失败", result, _ => result.BlockedByTargetAuthority++);
  228. return;
  229. }
  230. var afterMd5 = Md5(after);
  231. // ── 留证 + 改写同一事务。任一失败整条回滚:不接受「改了但没留证」,
  232. // 也不接受「留证说改了但实际没改」。
  233. var tran = await _db.AsTenant().UseTranAsync(async () =>
  234. {
  235. await _logRep.AsInsertable(new AdoS6FlowAuthorityMigrationLog
  236. {
  237. MigrationBatch = batch,
  238. InstanceId = inst.Id,
  239. BizType = inst.BizType,
  240. BizId = inst.BizId,
  241. EffectiveTenantId = c.EffectiveTenantId,
  242. BeforeSnapshot = before,
  243. AfterSnapshot = after,
  244. BeforeMd5 = beforeMd5,
  245. AfterMd5 = afterMd5,
  246. AuthorityMapping = string.Join(" | ", mappings),
  247. RollbackSource = rollbackSource,
  248. Reason = "运行中实例的快照冻结了跨租户物理 RoleId,被 TenantStrictRoleBizTypes 守卫 fail-closed;"
  249. + "改写为 RoleCode 后由引擎在本租户内重新解析",
  250. Outcome = "APPLIED",
  251. }).ExecuteCommandAsync();
  252. // 并发守卫:实例表无 version/checksum,只能用「改前 MD5 + 状态」作乐观锁。
  253. // 用裸 SQL 精确只改这一列,避免整实体 Updateable 把过期读到的其它列一并回写。
  254. var affected = await _db.Ado.ExecuteCommandAsync(
  255. """
  256. UPDATE ApprovalFlowInstance
  257. SET FlowJsonSnapshot=@after
  258. WHERE Id=@id AND Status=@running AND MD5(FlowJsonSnapshot)=@beforeMd5
  259. """,
  260. new List<SugarParameter>
  261. {
  262. new("@after", after), new("@id", inst.Id),
  263. new("@running", (int)FlowInstanceStatusEnum.Running), new("@beforeMd5", beforeMd5),
  264. });
  265. if (affected != 1)
  266. throw Oops.Oh($"CONCURRENT MODIFICATION:实例 {inst.Id} 期间被改动,affected={affected}");
  267. });
  268. if (!tran.IsSuccess)
  269. {
  270. result.BlockedByConcurrentModification++;
  271. _logger.LogWarning(tran.ErrorException,
  272. "S6LegacyFlowAuthorityMigration: 实例 {InstanceId} 迁移失败已整体回滚", inst.Id);
  273. return;
  274. }
  275. result.Applied++;
  276. _logger.LogInformation(
  277. "S6LegacyFlowAuthorityMigration APPLIED instance={InstanceId} bizType={BizType} bizId={BizId} "
  278. + "tenant={Tenant} beforeMd5={BeforeMd5} afterMd5={AfterMd5} mapping={Mapping}",
  279. inst.Id, inst.BizType, inst.BizId, c.EffectiveTenantId, beforeMd5, afterMd5, string.Join(" | ", mappings));
  280. }
  281. /// <summary>挡下的候选同样留证 —— 「为什么没迁」和「为什么迁了」一样需要能回答。</summary>
  282. private async Task BlockAsync(S6MigrationCandidate c, string batch, string beforeMd5,
  283. List<string> mappings, string outcome, string reason,
  284. S6FlowAuthorityMigrationResult result, Action<S6FlowAuthorityMigrationResult> bump)
  285. {
  286. bump(result);
  287. await _logRep.AsInsertable(new AdoS6FlowAuthorityMigrationLog
  288. {
  289. MigrationBatch = batch,
  290. InstanceId = c.Instance.Id,
  291. BizType = c.Instance.BizType,
  292. BizId = c.Instance.BizId,
  293. EffectiveTenantId = c.EffectiveTenantId,
  294. BeforeSnapshot = c.Instance.FlowJsonSnapshot,
  295. BeforeMd5 = beforeMd5,
  296. AuthorityMapping = mappings.Count == 0 ? null : string.Join(" | ", mappings),
  297. Reason = reason,
  298. Outcome = outcome,
  299. }).ExecuteCommandAsync();
  300. _logger.LogWarning("S6LegacyFlowAuthorityMigration {Outcome} instance={InstanceId} reason={Reason}",
  301. outcome, c.Instance.Id, reason);
  302. }
  303. /// <summary>
  304. /// Effective Tenant 由业务实体反查。<c>ApprovalFlowInstance</c> 自身没有 TenantId 列,
  305. /// 而推进时引擎用的是登录租户 —— 迁移绝不能沿用那条路径,否则会把租户判定建立在
  306. /// 「谁在执行迁移」而不是「这条单据属于谁」之上。
  307. /// </summary>
  308. private async Task<long?> ResolveEffectiveTenantAsync(string bizType, long bizId) => bizType switch
  309. {
  310. "S6_PROCESS_INSPECTION" => await _db.Ado.SqlQuerySingleAsync<long?>(
  311. "SELECT tenant_id FROM ado_s6_process_inspection_bill WHERE id=@id LIMIT 1",
  312. new List<SugarParameter> { new("@id", bizId) }),
  313. "IPQC_INSPECTION" => await _db.Ado.SqlQuerySingleAsync<long?>(
  314. "SELECT tenant_id FROM qms_gcjyd WHERE id=@id LIMIT 1",
  315. new List<SugarParameter> { new("@id", bizId) }),
  316. _ => null,
  317. };
  318. /// <summary>
  319. /// 解析快照中「approverType==Role 且 approverIds 含纯数字 token」的节点。
  320. ///
  321. /// <para>必须按 JSON 结构解析、结合 approverType 判断语义,<b>不能只 grep 数字</b>:
  322. /// 实测同一个 Id 既可能是合法 SysRole.Id 又是合法 SysUser.Id,而
  323. /// <c>SpecificUser</c> / <c>Department</c> 节点里的数字分别是 UserId / OrgId,
  324. /// 纯数字匹配会把它们误判成 RoleId。</para>
  325. /// </summary>
  326. internal static List<S6NumericRoleRef> ParseNumericRoleRefs(string? snapshot)
  327. {
  328. var refs = new List<S6NumericRoleRef>();
  329. if (string.IsNullOrWhiteSpace(snapshot)) return refs;
  330. JsonNode? root;
  331. try { root = JsonNode.Parse(snapshot); }
  332. catch { return refs; }
  333. if (root?["nodes"] is not JsonArray nodes) return refs;
  334. foreach (var node in nodes)
  335. {
  336. var props = node?["properties"];
  337. if (props == null) continue;
  338. if (props["approverType"]?.GetValue<string>() != nameof(ApproverTypeEnum.Role)) continue;
  339. var ids = props["approverIds"]?.GetValue<string>();
  340. if (string.IsNullOrWhiteSpace(ids)) continue;
  341. var numeric = ids.Split(',', StringSplitOptions.RemoveEmptyEntries)
  342. .Select(s => s.Trim())
  343. .Where(s => s.Length > 0 && long.TryParse(s, out var v) && v > 0)
  344. .Distinct(StringComparer.Ordinal)
  345. .ToList();
  346. if (numeric.Count == 0) continue;
  347. refs.Add(new S6NumericRoleRef
  348. {
  349. NodeId = node?["id"]?.GetValue<string>() ?? string.Empty,
  350. ApproverIds = ids,
  351. NumericTokens = numeric,
  352. });
  353. }
  354. return refs;
  355. }
  356. /// <summary>
  357. /// 结构化改写:只把 Role 节点 approverIds 里的数字 token 换成对应 RoleCode,
  358. /// 保持 token 原顺序与原数量。节点 id / 名称 / edges / 网关条件 / approverNames 一概不动。
  359. /// </summary>
  360. internal static string? RewriteAuthority(string snapshot, IReadOnlyDictionary<string, string> tokenMap)
  361. {
  362. JsonNode? root;
  363. try { root = JsonNode.Parse(snapshot); }
  364. catch { return null; }
  365. if (root?["nodes"] is not JsonArray nodes) return null;
  366. var changed = false;
  367. foreach (var node in nodes)
  368. {
  369. var props = node?["properties"];
  370. if (props == null) continue;
  371. if (props["approverType"]?.GetValue<string>() != nameof(ApproverTypeEnum.Role)) continue;
  372. var ids = props["approverIds"]?.GetValue<string>();
  373. if (string.IsNullOrWhiteSpace(ids)) continue;
  374. var tokens = ids.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList();
  375. if (tokens.Count == 0) continue;
  376. var rewritten = tokens.Select(t => tokenMap.TryGetValue(t, out var code) ? code : t).ToList();
  377. var joined = string.Join(",", rewritten);
  378. if (joined == ids) continue;
  379. props["approverIds"] = joined;
  380. changed = true;
  381. }
  382. return changed ? root!.ToJsonString() : null;
  383. }
  384. private static string Md5(string s)
  385. {
  386. var bytes = MD5.HashData(Encoding.UTF8.GetBytes(s));
  387. return Convert.ToHexString(bytes).ToLowerInvariant();
  388. }
  389. }
  390. /// <summary>候选实例 + 其反查出的租户 + 快照中待迁的数字角色引用。</summary>
  391. public sealed class S6MigrationCandidate
  392. {
  393. public ApprovalFlowInstance Instance { get; set; } = null!;
  394. public long EffectiveTenantId { get; set; }
  395. public List<S6NumericRoleRef> NumericRefs { get; set; } = new();
  396. }
  397. /// <summary>快照中一个 Role 节点里的数字角色引用。</summary>
  398. public sealed class S6NumericRoleRef
  399. {
  400. public string NodeId { get; set; } = string.Empty;
  401. public string ApproverIds { get; set; } = string.Empty;
  402. public List<string> NumericTokens { get; set; } = new();
  403. }