S7LegacyFlowAuthorityMigrationService.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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.S7;
  6. using Admin.NET.Plugin.AiDOP.FinishedWarehouse;
  7. using Admin.NET.Plugin.ApprovalFlow;
  8. using Microsoft.Extensions.Logging;
  9. namespace Admin.NET.Plugin.AiDOP.Service.S7;
  10. /// <summary>迁移结果。分项计数,运维要能看出「这次到底动了什么、什么被挡下了」。</summary>
  11. public sealed class S7FlowAuthorityMigrationResult
  12. {
  13. /// <summary>通过全部安全谓词、进入逐条处理的候选实例数。</summary>
  14. public int CandidatesSelected { get; set; }
  15. /// <summary>本次实际改写快照的实例数。</summary>
  16. public int Applied { get; set; }
  17. /// <summary>目标租户角色缺失 / 禁用 / 无同租户成员 / 角色不唯一 / 目标 Code 不在允许集 → 未改。</summary>
  18. public int BlockedByTargetAuthority { get; set; }
  19. /// <summary>回滚来源缺失或不唯一 → 未改。</summary>
  20. public int BlockedByRollbackSource { get; set; }
  21. /// <summary>改写落在 N2/N3 之外的 JSON 路径 → 未改。</summary>
  22. public int BlockedByChangedPath { get; set; }
  23. /// <summary>UPDATE 影响行数 ≠ 1(期间被并发改动)→ 已回滚。</summary>
  24. public int BlockedByConcurrentModification { get; set; }
  25. }
  26. /// <summary>
  27. /// S7-LEGACY-SNAPSHOT-MIGRATION-1:把**仍在运行**的 S7 成品检验流程实例快照里冻结的
  28. /// 默认租户物理 RoleId 改写为 RoleCode,让它们在租户本地化模型下继续流转。
  29. ///
  30. /// <para><b>问题形态</b>(已取证,非推测):<c>StartFlowCore</c> 落实例时把
  31. /// <c>ApprovalFlow.FlowJson</c> 整体冻结进 <c>FlowJsonSnapshot</c>(<c>:128</c>),此后
  32. /// **所有推进路径一律读快照、再不看定义**(<c>:180/302/366/467/515/555/1230</c>)。因此
  33. /// 2026-09-14 的 S7 租户本地化(定义 N2/N3 由 <c>1329915020002</c>/<c>1329915020003</c>
  34. /// 改成 RoleCode)**只对新发起的实例生效**;此前发起且仍未走完的实例,快照里那个默认租户
  35. /// RoleId 只能靠 9 条跨租户 <c>SysUserRole</c> 绑定才解析得出人 —— 那些绑定本身是待清理的缺陷。</para>
  36. ///
  37. /// <para><b>为什么不做 runtime auto-heal</b>:运行时隐式把 A 角色当 B 角色执行,会让
  38. /// 「执行的」与「快照里展示的」永久分离,比显式改写更难解释;而放宽引擎门禁会同时影响新实例。
  39. /// 故本服务是 <b>显式、一次性、可审计、可回滚的数据迁移</b>,不是 resolver 兼容层。</para>
  40. ///
  41. /// <para><b>批次边界(关键)</b>:只处理 <see cref="BatchCutoff"/> 之前发起的实例。该时点是
  42. /// S7 RoleCode 定义发布之前;此后发起的实例本就会拿到 RoleCode 快照 —— 若之后仍出现默认租户
  43. /// RoleId,那是**新的 authority regression**,必须让它响亮失败被人看见,绝不能被本服务静默治好。
  44. /// 这条边界是「一次性迁移」与「长期 auto-heal」的分界线。</para>
  45. ///
  46. /// <para><b>只修坏的,不碰好的</b>:终态实例一律不动(对 runtime 已无影响,改了没用,
  47. /// 却百分之百是纯历史记录);同租户的物理 RoleId 也不动(numeric ≠ bad);
  48. /// N1 是 <c>Initiator</c> 节点,本服务只看 <c>approverType == Role</c>,天然不会碰它。</para>
  49. ///
  50. /// <para><b>与 S6 的关系</b>:设计思想、门禁顺序、并发守卫、事务边界全部镜像已验证的
  51. /// <c>S6LegacyFlowAuthorityMigrationService</c>。未复用该类本体,因为它的 <c>TargetBizTypes</c>
  52. /// 与租户反查都硬绑 S6 两条链,泛化它就要改 S6 已关闭的逻辑。</para>
  53. /// </summary>
  54. public class S7LegacyFlowAuthorityMigrationService : ITransient
  55. {
  56. /// <summary>本迁移只处理 S7 成品检验链。</summary>
  57. internal static IReadOnlyList<string> TargetBizTypes { get; } =
  58. new List<string> { FqcInspBillFlowConst.BizType };
  59. /// <summary>
  60. /// 允许被改写的节点 —— 只有主管审核与 QE 处置两个 Role 节点。
  61. /// N1(<c>N1_INSPECT</c>)是 Initiator 节点,不在此列也不该出现在改写路径里。
  62. /// </summary>
  63. internal static IReadOnlySet<string> MigratableNodeIds { get; } =
  64. new HashSet<string>(StringComparer.Ordinal)
  65. {
  66. FqcInspBillFlowConst.NodeSupervisor,
  67. FqcInspBillFlowConst.NodeDisposition,
  68. };
  69. /// <summary>
  70. /// 允许作为改写目标的 RoleCode 白名单。目标 Code 是从 legacy 角色行的 <c>SysRole.Code</c>
  71. /// 反查来的(比硬编码映射更可靠:Code 若与预期不符会被本白名单挡下,而不是静默写入意外值)。
  72. /// </summary>
  73. internal static IReadOnlySet<string> AllowedTargetRoleCodes { get; } =
  74. new HashSet<string>(StringComparer.Ordinal)
  75. {
  76. FqcInspBillFlowConst.RoleSupervisorCode,
  77. FqcInspBillFlowConst.RoleQeCode,
  78. };
  79. /// <summary>
  80. /// 批次边界。S7 租户本地 RoleCode 定义于 2026-09-14 晚间发布(<c>S7FQC_T*</c>),
  81. /// 此后发起的实例快照本就是 RoleCode。之后再出现默认租户 RoleId = 新缺陷,
  82. /// 不属本次迁移范围,必须 fail-closed 暴露。
  83. /// </summary>
  84. private static readonly DateTime BatchCutoff = new(2026, 9, 14, 22, 0, 0, DateTimeKind.Unspecified);
  85. private const string BatchPrefix = "S7-LEGACY-SNAPSHOT-MIGRATION-1";
  86. private readonly ISqlSugarClient _db;
  87. private readonly SqlSugarRepository<AdoS7FlowAuthorityMigrationLog> _logRep;
  88. private readonly ILogger<S7LegacyFlowAuthorityMigrationService> _logger;
  89. public S7LegacyFlowAuthorityMigrationService(
  90. ISqlSugarClient db,
  91. SqlSugarRepository<AdoS7FlowAuthorityMigrationLog> logRep,
  92. ILogger<S7LegacyFlowAuthorityMigrationService> logger)
  93. {
  94. _db = db;
  95. _logRep = logRep;
  96. _logger = logger;
  97. }
  98. /// <summary>
  99. /// 选出候选(**只读,不写任何表,包括迁移留证表**)。Apply 与 dry-run 共用同一段谓词,
  100. /// 避免「预演看到的」和「实际改的」是两套逻辑。
  101. /// </summary>
  102. public async Task<List<S7MigrationCandidate>> SelectCandidatesAsync()
  103. {
  104. var candidates = new List<S7MigrationCandidate>();
  105. // ① 运行中 + 批次边界内。ApprovalFlowInstance 无 TenantId 列,租户后面由业务实体反查。
  106. // bizTypes / cutoff 取局部变量:SqlSugar 的表达式解析器无法把静态成员翻成 SQL 参数。
  107. var bizTypes = TargetBizTypes.ToList();
  108. var cutoff = BatchCutoff;
  109. var instances = await _db.Queryable<ApprovalFlowInstance>().ClearFilter()
  110. .Where(x => bizTypes.Contains(x.BizType)
  111. && x.Status == FlowInstanceStatusEnum.Running
  112. && x.StartTime < cutoff)
  113. .ToListAsync();
  114. foreach (var inst in instances)
  115. {
  116. // ② ACTIVE 的完整判据:不能只看 Status —— 终态实例的 CurrentNodeId 可能仍停在
  117. // N3_* 而非 end(实测 S7 有 3 条这样的终态实例),只看状态字段会误判。
  118. var hasPending = await _db.Queryable<ApprovalFlowTask>().ClearFilter()
  119. .AnyAsync(t => t.InstanceId == inst.Id && t.Status == FlowTaskStatusEnum.Pending);
  120. if (!hasPending) continue;
  121. // ③ Business Tenant 必须由 S7 业务实体反查,禁止取登录用户租户 / 定义租户 /
  122. // 发起人租户 / 待办人租户 —— 实测这四者在 S7 存量实例上互不相等。
  123. var tenantId = await ResolveBusinessTenantAsync(inst.BizType, inst.BizId);
  124. if (tenantId is not > 0) continue;
  125. // ④ 快照里是否还存在「Role 节点 + 纯数字 token」。这同时就是幂等判据的补集:
  126. // 迁完之后本条恒为 false,第二次运行自然选不中;上一批新建的 RoleCode 实例
  127. // 也因此天然被排除(它们的 approverIds 是 Code,没有数字 token)。
  128. var refs = ParseNumericRoleRefs(inst.FlowJsonSnapshot);
  129. if (refs.Count == 0) continue;
  130. candidates.Add(new S7MigrationCandidate
  131. {
  132. Instance = inst,
  133. BusinessTenantId = tenantId.Value,
  134. NumericRefs = refs,
  135. });
  136. }
  137. return candidates;
  138. }
  139. /// <summary>执行迁移。每个候选独立事务:留证 INSERT 与快照 UPDATE 原子提交,任一失败整条回滚。</summary>
  140. public async Task<S7FlowAuthorityMigrationResult> MigrateAsync(CancellationToken ct = default)
  141. {
  142. var result = new S7FlowAuthorityMigrationResult();
  143. var batch = $"{BatchPrefix}@{DateTime.Now:yyyyMMddHHmmss}";
  144. List<S7MigrationCandidate> candidates;
  145. try
  146. {
  147. candidates = await SelectCandidatesAsync();
  148. }
  149. catch (Exception ex)
  150. {
  151. _logger.LogError(ex, "S7 legacy flow authority migration: 候选选取失败,本次跳过");
  152. return result;
  153. }
  154. result.CandidatesSelected = candidates.Count;
  155. foreach (var c in candidates)
  156. {
  157. if (ct.IsCancellationRequested) break;
  158. await MigrateOneAsync(c, batch, result);
  159. }
  160. // 无条件记一行汇总 —— 「本次 0 候选 0 改动」本身就是要被看见的结论:
  161. // 迁移已收敛的证据,以及「未来若冒出新候选会被立刻发现」的可观测性基础。
  162. _logger.LogInformation(
  163. "S7LegacyFlowAuthorityMigration batch={Batch} selected={Selected} applied={Applied} "
  164. + "blockedTargetAuthority={BlockedTarget} blockedRollbackSource={BlockedRollback} "
  165. + "blockedChangedPath={BlockedPath} blockedConcurrent={BlockedConcurrent}",
  166. batch, result.CandidatesSelected, result.Applied,
  167. result.BlockedByTargetAuthority, result.BlockedByRollbackSource,
  168. result.BlockedByChangedPath, result.BlockedByConcurrentModification);
  169. return result;
  170. }
  171. /// <summary>
  172. /// 预演(**只读,不写任何表,包括迁移留证表**)。与 Apply 共用 <see cref="SelectCandidatesAsync"/>
  173. /// 与 <see cref="EvaluateAsync"/>:预演看到的门禁结论就是 Apply 会走的那一条,不存在两套逻辑。
  174. /// </summary>
  175. public async Task<List<S7MigrationEvaluation>> DryRunAsync()
  176. {
  177. var report = new List<S7MigrationEvaluation>();
  178. foreach (var c in await SelectCandidatesAsync())
  179. report.Add(await EvaluateAsync(c));
  180. // 预演结论必须可观测:用服务自己的 ILogger 输出(Startup 里的 Trace 不进应用日志文件)。
  181. _logger.LogInformation("S7MigrationDryRun candidates={Count} applicable={Ok} blocked={Blocked}",
  182. report.Count, report.Count(x => x.CanApply), report.Count(x => !x.CanApply));
  183. foreach (var r in report)
  184. _logger.LogInformation(
  185. "S7MigrationDryRun inst={Inst} tenant={Tenant} node={Node} canApply={CanApply} "
  186. + "beforeMd5={Before} afterMd5={After} changedNodes=[{Nodes}] paths={Paths} "
  187. + "mapping={Mapping} rollback={Rollback} outcome={Outcome} reason={Reason}",
  188. r.Candidate.Instance.Id, r.Candidate.BusinessTenantId, r.Candidate.Instance.CurrentNodeId,
  189. r.CanApply, r.BeforeMd5, r.AfterMd5, string.Join(",", r.ChangedNodeIds), r.ChangedPaths,
  190. string.Join(" | ", r.Mappings), r.RollbackSource, r.Outcome, r.Reason);
  191. return report;
  192. }
  193. private async Task MigrateOneAsync(S7MigrationCandidate c, string batch, S7FlowAuthorityMigrationResult result)
  194. {
  195. var e = await EvaluateAsync(c);
  196. if (!e.CanApply)
  197. {
  198. await BlockAsync(c, batch, e.BeforeMd5, e.Mappings, e.ChangedPaths, e.Outcome!, e.Reason!,
  199. result, _ =>
  200. {
  201. switch (e.Outcome)
  202. {
  203. case "BLOCKED_CHANGED_PATH": result.BlockedByChangedPath++; break;
  204. case "BLOCKED_ROLLBACK_SOURCE": result.BlockedByRollbackSource++; break;
  205. default: result.BlockedByTargetAuthority++; break;
  206. }
  207. });
  208. return;
  209. }
  210. await ApplyOneAsync(c, e, batch, result);
  211. }
  212. /// <summary>
  213. /// 逐条跑完全部门禁并算出改写结果,**不写库**。返回「可应用的计划」或「被挡下的原因」。
  214. /// 抽出这一层的目的:让 dry-run 与 apply 在代码上无法分叉。
  215. /// </summary>
  216. private async Task<S7MigrationEvaluation> EvaluateAsync(S7MigrationCandidate c)
  217. {
  218. var inst = c.Instance;
  219. var before = inst.FlowJsonSnapshot ?? string.Empty;
  220. var beforeMd5 = Md5(before);
  221. // ── Gate 1:逐 token 解析目标角色。任一 token 映射不出来 → 整条实例不迁(禁止部分迁移,
  222. // 否则会留下半新半旧的快照,比全旧更难排查)。
  223. var mappings = new List<string>();
  224. var tokenMap = new Dictionary<string, string>(StringComparer.Ordinal);
  225. foreach (var r in c.NumericRefs)
  226. {
  227. // Gate 1a:数字引用只允许出现在 N2/N3 两个可迁节点上。出现在别处说明快照结构
  228. // 与预期不符(例如 N1 被改成过 Role),必须停下让人看,而不是顺手改。
  229. if (!MigratableNodeIds.Contains(r.NodeId))
  230. {
  231. return Blocked(c, beforeMd5, mappings, null, "BLOCKED_CHANGED_PATH",
  232. $"节点 {r.NodeId} 含数字 Role 引用,但它不在可迁节点集 "
  233. + $"[{string.Join(",", MigratableNodeIds)}] 内");
  234. }
  235. foreach (var token in r.NumericTokens)
  236. {
  237. if (tokenMap.ContainsKey(token)) continue;
  238. var legacyRole = await _db.Queryable<SysRole>().ClearFilter()
  239. .Where(x => x.Id == long.Parse(token)).FirstAsync();
  240. if (legacyRole == null)
  241. {
  242. return Blocked(c, beforeMd5, mappings, null, "BLOCKED_TARGET_AUTHORITY",
  243. $"legacy RoleId {token} 在 SysRole 中不存在");
  244. }
  245. // 同租户的物理 RoleId 是合法引用,不是缺陷 —— 不得因为「是数字」就改它。
  246. if (legacyRole.TenantId == c.BusinessTenantId)
  247. {
  248. return Blocked(c, beforeMd5, mappings, null, "BLOCKED_TARGET_AUTHORITY",
  249. $"RoleId {token} 属于本租户 {c.BusinessTenantId},非跨租户引用,不在迁移范围");
  250. }
  251. var code = legacyRole.Code;
  252. if (string.IsNullOrWhiteSpace(code))
  253. {
  254. return Blocked(c, beforeMd5, mappings, null, "BLOCKED_TARGET_AUTHORITY",
  255. $"legacy RoleId {token} 无 Code,无法映射");
  256. }
  257. // Gate 1b:目标 Code 必须在 S7 白名单内。防止「legacy 行的 Code 不是我们以为的那个」
  258. // 时把意外值写进快照。
  259. if (!AllowedTargetRoleCodes.Contains(code))
  260. {
  261. return Blocked(c, beforeMd5, mappings, null, "BLOCKED_TARGET_AUTHORITY",
  262. $"legacy RoleId {token} 的 Code={code} 不在 S7 允许的目标 Code 集 "
  263. + $"[{string.Join(",", AllowedTargetRoleCodes)}] 内");
  264. }
  265. // Gate 2:目标租户下该 Code 必须**恰好一个**启用角色。不得 First() 随便挑。
  266. var targets = await _db.Queryable<SysRole>().ClearFilter()
  267. .Where(x => x.TenantId == c.BusinessTenantId && x.Code == code && x.Status == StatusEnum.Enable)
  268. .ToListAsync();
  269. if (targets.Count != 1)
  270. {
  271. return Blocked(c, beforeMd5, mappings, null, "BLOCKED_TARGET_AUTHORITY",
  272. targets.Count == 0
  273. ? $"目标租户 {c.BusinessTenantId} 下不存在启用的 {code}"
  274. : $"目标租户 {c.BusinessTenantId} 下 {code} 有 {targets.Count} 个,AMBIGUOUS TARGET ROLE");
  275. }
  276. var target = targets[0];
  277. // Gate 3:目标角色必须至少有一个**同租户**成员,否则迁完仍旧解析 0 人。
  278. var memberIds = await _db.Queryable<SysUserRole>().ClearFilter()
  279. .Where(x => x.RoleId == target.Id).Select(x => x.UserId).ToListAsync();
  280. var sameTenantMembers = memberIds.Count == 0 ? 0
  281. : await _db.Queryable<SysUser>().ClearFilter()
  282. .CountAsync(u => memberIds.Contains(u.Id) && u.TenantId == c.BusinessTenantId);
  283. if (sameTenantMembers == 0)
  284. {
  285. return Blocked(c, beforeMd5, mappings, null, "BLOCKED_TARGET_AUTHORITY",
  286. $"目标角色 {code}@{c.BusinessTenantId}(RoleId {target.Id})无同租户成员");
  287. }
  288. tokenMap[token] = code;
  289. mappings.Add($"node={r.NodeId};{token}=>{code}@{target.Id};members={sameTenantMembers}");
  290. }
  291. }
  292. // ── Gate 4:回滚来源必须唯一且与当前快照逐字节一致。ApprovalFlowVersion 全库存在
  293. // (FlowId,Version) 重复行、该表也没有唯一约束 —— 这道门禁不是形式主义。
  294. // 注意:改前快照全文本身已落 before_snapshot(第一回滚来源),本门禁是第二来源校验。
  295. var versionRows = await _db.Queryable<ApprovalFlowVersion>().ClearFilter()
  296. .Where(v => v.FlowId == inst.FlowId && v.Version == inst.FlowVersion).ToListAsync();
  297. var usable = versionRows.Where(v => Md5(v.FlowJson ?? string.Empty) == beforeMd5).ToList();
  298. if (versionRows.Count != 1 || usable.Count != 1)
  299. {
  300. return Blocked(c, beforeMd5, mappings, null, "BLOCKED_ROLLBACK_SOURCE",
  301. $"ApprovalFlowVersion(FlowId={inst.FlowId},Version={inst.FlowVersion}) 命中 {versionRows.Count} 行、"
  302. + $"其中与当前快照 MD5 一致 {usable.Count} 行;要求恰好 1/1");
  303. }
  304. var rollbackSource = $"ApprovalFlowVersion#{usable[0].Id}";
  305. // ── 结构化改写:只动 Role 节点的 approverIds,其余一律不碰。禁止字符串替换。
  306. var rewrite = RewriteAuthority(before, tokenMap);
  307. if (rewrite == null || rewrite.After == before)
  308. {
  309. return Blocked(c, beforeMd5, mappings, null, "BLOCKED_TARGET_AUTHORITY",
  310. "结构化改写未产生变化或解析失败");
  311. }
  312. // ── Gate 5:改写路径必须全部落在 N2/N3 的 approverIds 上。这是对改写实现的独立复核,
  313. // 不依赖 RewriteAuthority 自己的自觉(§14 精确路径门禁)。
  314. var illegal = rewrite.ChangedNodeIds.Where(n => !MigratableNodeIds.Contains(n)).ToList();
  315. if (illegal.Count > 0)
  316. {
  317. return Blocked(c, beforeMd5, mappings, rewrite.ChangedPathText, "BLOCKED_CHANGED_PATH",
  318. $"改写路径越界:{string.Join(",", illegal)} 不在可迁节点集内");
  319. }
  320. var after = rewrite.After;
  321. return new S7MigrationEvaluation
  322. {
  323. Candidate = c,
  324. CanApply = true,
  325. Before = before,
  326. BeforeMd5 = beforeMd5,
  327. After = after,
  328. AfterMd5 = Md5(after),
  329. ChangedNodeIds = rewrite.ChangedNodeIds,
  330. ChangedPaths = rewrite.ChangedPathText,
  331. Mappings = mappings,
  332. RollbackSource = rollbackSource,
  333. };
  334. }
  335. /// <summary>被门禁挡下的评估结论(不写库,由调用方决定是否落留证)。</summary>
  336. private static S7MigrationEvaluation Blocked(S7MigrationCandidate c, string beforeMd5,
  337. List<string> mappings, string? changedPaths, string outcome, string reason) => new()
  338. {
  339. Candidate = c,
  340. CanApply = false,
  341. Before = c.Instance.FlowJsonSnapshot ?? string.Empty,
  342. BeforeMd5 = beforeMd5,
  343. Mappings = mappings,
  344. ChangedPaths = changedPaths,
  345. Outcome = outcome,
  346. Reason = reason,
  347. };
  348. /// <summary>
  349. /// 落地一条已通过全部门禁的计划:留证 INSERT 与快照 UPDATE 同一事务,任一失败整条回滚。
  350. /// </summary>
  351. private async Task ApplyOneAsync(S7MigrationCandidate c, S7MigrationEvaluation e,
  352. string batch, S7FlowAuthorityMigrationResult result)
  353. {
  354. var inst = c.Instance;
  355. // ── 留证 + 改写同一事务。任一失败整条回滚:不接受「改了但没留证」,
  356. // 也不接受「留证说改了但实际没改」。
  357. var tran = await _db.AsTenant().UseTranAsync(async () =>
  358. {
  359. await _logRep.AsInsertable(new AdoS7FlowAuthorityMigrationLog
  360. {
  361. MigrationBatch = batch,
  362. MigrationKey = $"{BatchPrefix}#{inst.Id}",
  363. InstanceId = inst.Id,
  364. BizType = inst.BizType,
  365. BizId = inst.BizId,
  366. BusinessTenantId = c.BusinessTenantId,
  367. BeforeSnapshot = e.Before,
  368. AfterSnapshot = e.After,
  369. BeforeMd5 = e.BeforeMd5,
  370. AfterMd5 = e.AfterMd5,
  371. ChangedPaths = e.ChangedPaths,
  372. AuthorityMapping = string.Join(" | ", e.Mappings),
  373. RollbackSource = e.RollbackSource,
  374. Reason = "运行中实例的快照冻结了默认租户物理 RoleId,只能靠跨租户 SysUserRole 绑定解析;"
  375. + "改写为 RoleCode 后由引擎在本租户内重新解析,不再依赖跨租户绑定",
  376. AppliedBy = MigrationIdentity(),
  377. Outcome = "APPLIED",
  378. }).ExecuteCommandAsync();
  379. // 并发守卫:实例表无 version/checksum,只能用「改前 MD5 + 状态」作乐观锁。
  380. // 用裸 SQL 精确只改这一列,避免整实体 Updateable 把过期读到的其它列一并回写
  381. // (FlowId / FlowVersion / CurrentNodeId / InitiatorId 因此天然不受影响)。
  382. var affected = await _db.Ado.ExecuteCommandAsync(
  383. """
  384. UPDATE ApprovalFlowInstance
  385. SET FlowJsonSnapshot=@after
  386. WHERE Id=@id AND Status=@running AND MD5(FlowJsonSnapshot)=@beforeMd5
  387. """,
  388. new List<SugarParameter>
  389. {
  390. new("@after", e.After), new("@id", inst.Id),
  391. new("@running", (int)FlowInstanceStatusEnum.Running), new("@beforeMd5", e.BeforeMd5),
  392. });
  393. if (affected != 1)
  394. throw Oops.Oh($"CONCURRENT MODIFICATION:实例 {inst.Id} 期间被改动,affected={affected}");
  395. });
  396. if (!tran.IsSuccess)
  397. {
  398. result.BlockedByConcurrentModification++;
  399. _logger.LogWarning(tran.ErrorException,
  400. "S7LegacyFlowAuthorityMigration: 实例 {InstanceId} 迁移失败已整体回滚", inst.Id);
  401. return;
  402. }
  403. result.Applied++;
  404. _logger.LogInformation(
  405. "S7LegacyFlowAuthorityMigration APPLIED instance={InstanceId} bizType={BizType} bizId={BizId} "
  406. + "tenant={Tenant} beforeMd5={BeforeMd5} afterMd5={AfterMd5} paths={Paths} mapping={Mapping}",
  407. inst.Id, inst.BizType, inst.BizId, c.BusinessTenantId, e.BeforeMd5, e.AfterMd5,
  408. e.ChangedPaths, string.Join(" | ", e.Mappings));
  409. }
  410. /// <summary>挡下的候选同样留证 —— 「为什么没迁」和「为什么迁了」一样需要能回答。</summary>
  411. private async Task BlockAsync(S7MigrationCandidate c, string batch, string beforeMd5,
  412. List<string> mappings, string? changedPaths, string outcome, string reason,
  413. S7FlowAuthorityMigrationResult result, Action<S7FlowAuthorityMigrationResult> bump)
  414. {
  415. bump(result);
  416. await _logRep.AsInsertable(new AdoS7FlowAuthorityMigrationLog
  417. {
  418. MigrationBatch = batch,
  419. MigrationKey = $"{BatchPrefix}#{c.Instance.Id}",
  420. InstanceId = c.Instance.Id,
  421. BizType = c.Instance.BizType,
  422. BizId = c.Instance.BizId,
  423. BusinessTenantId = c.BusinessTenantId,
  424. BeforeSnapshot = c.Instance.FlowJsonSnapshot,
  425. BeforeMd5 = beforeMd5,
  426. ChangedPaths = changedPaths,
  427. AuthorityMapping = mappings.Count == 0 ? null : string.Join(" | ", mappings),
  428. Reason = reason,
  429. AppliedBy = MigrationIdentity(),
  430. Outcome = outcome,
  431. }).ExecuteCommandAsync();
  432. _logger.LogWarning("S7LegacyFlowAuthorityMigration {Outcome} instance={InstanceId} reason={Reason}",
  433. outcome, c.Instance.Id, reason);
  434. }
  435. /// <summary>
  436. /// 迁移执行身份。本迁移以系统身份在启动期运行、没有登录用户上下文,
  437. /// 故记录「执行体 + 主机」;不伪造 UserId。
  438. /// </summary>
  439. private static string MigrationIdentity() => $"{BatchPrefix}@{Environment.MachineName}";
  440. /// <summary>
  441. /// Business Tenant 由 S7 业务实体反查。<c>ApprovalFlowInstance</c> 自身没有 TenantId 列,
  442. /// 而推进时引擎用的是登录租户 —— 迁移绝不能沿用那条路径,否则会把租户判定建立在
  443. /// 「谁在执行迁移」而不是「这条单据属于谁」之上。
  444. /// </summary>
  445. private async Task<long?> ResolveBusinessTenantAsync(string bizType, long bizId) => bizType switch
  446. {
  447. // BizId = qms_qcpp_inspbill.id(见 FqcInspBillFlowService 头部注释)
  448. "S7_FQC_INSPBILL" => await _db.Ado.SqlQuerySingleAsync<long?>(
  449. "SELECT tenant_id FROM qms_qcpp_inspbill WHERE id=@id LIMIT 1",
  450. new List<SugarParameter> { new("@id", bizId) }),
  451. _ => null,
  452. };
  453. /// <summary>
  454. /// 解析快照中「approverType==Role 且 approverIds 含纯数字 token」的节点。
  455. ///
  456. /// <para>必须按 JSON 结构解析、结合 approverType 判断语义,<b>不能只 grep 数字</b>:
  457. /// 同一个 Id 既可能是合法 SysRole.Id 又是合法 SysUser.Id,而
  458. /// <c>SpecificUser</c> / <c>Department</c> 节点里的数字分别是 UserId / OrgId,
  459. /// 纯数字匹配会把它们误判成 RoleId;<c>Initiator</c> 节点(S7 的 N1)则根本没有 approverIds。</para>
  460. /// </summary>
  461. internal static List<S7NumericRoleRef> ParseNumericRoleRefs(string? snapshot)
  462. {
  463. var refs = new List<S7NumericRoleRef>();
  464. if (string.IsNullOrWhiteSpace(snapshot)) return refs;
  465. JsonNode? root;
  466. try { root = JsonNode.Parse(snapshot); }
  467. catch { return refs; }
  468. if (root?["nodes"] is not JsonArray nodes) return refs;
  469. foreach (var node in nodes)
  470. {
  471. var props = node?["properties"];
  472. if (props == null) continue;
  473. if (props["approverType"]?.GetValue<string>() != nameof(ApproverTypeEnum.Role)) continue;
  474. var ids = props["approverIds"]?.GetValue<string>();
  475. if (string.IsNullOrWhiteSpace(ids)) continue;
  476. var numeric = ids.Split(',', StringSplitOptions.RemoveEmptyEntries)
  477. .Select(s => s.Trim())
  478. .Where(s => s.Length > 0 && long.TryParse(s, out var v) && v > 0)
  479. .Distinct(StringComparer.Ordinal)
  480. .ToList();
  481. if (numeric.Count == 0) continue;
  482. refs.Add(new S7NumericRoleRef
  483. {
  484. NodeId = node?["id"]?.GetValue<string>() ?? string.Empty,
  485. ApproverIds = ids,
  486. NumericTokens = numeric,
  487. });
  488. }
  489. return refs;
  490. }
  491. /// <summary>
  492. /// 结构化改写:只把 Role 节点 approverIds 里的数字 token 换成对应 RoleCode,
  493. /// 保持 token 原顺序与原数量。节点 id / 名称 / approverType / approverNames /
  494. /// edges / 网关条件一概不动;<c>Initiator</c> 节点不进入循环体。
  495. /// 同时返回被改动的节点与可读路径,供调用方做独立的路径门禁复核。
  496. /// </summary>
  497. internal static S7AuthorityRewrite? RewriteAuthority(string snapshot, IReadOnlyDictionary<string, string> tokenMap)
  498. {
  499. JsonNode? root;
  500. try { root = JsonNode.Parse(snapshot); }
  501. catch { return null; }
  502. if (root?["nodes"] is not JsonArray nodes) return null;
  503. var changedNodes = new List<string>();
  504. var paths = new List<string>();
  505. foreach (var node in nodes)
  506. {
  507. var props = node?["properties"];
  508. if (props == null) continue;
  509. if (props["approverType"]?.GetValue<string>() != nameof(ApproverTypeEnum.Role)) continue;
  510. var ids = props["approverIds"]?.GetValue<string>();
  511. if (string.IsNullOrWhiteSpace(ids)) continue;
  512. var tokens = ids.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList();
  513. if (tokens.Count == 0) continue;
  514. var rewritten = tokens.Select(t => tokenMap.TryGetValue(t, out var code) ? code : t).ToList();
  515. var joined = string.Join(",", rewritten);
  516. if (joined == ids) continue;
  517. props["approverIds"] = joined;
  518. var nodeId = node?["id"]?.GetValue<string>() ?? string.Empty;
  519. changedNodes.Add(nodeId);
  520. paths.Add($"nodes[id={nodeId}].properties.approverIds: \"{ids}\" => \"{joined}\"");
  521. }
  522. if (changedNodes.Count == 0) return null;
  523. return new S7AuthorityRewrite
  524. {
  525. After = root!.ToJsonString(),
  526. ChangedNodeIds = changedNodes,
  527. ChangedPathText = string.Join(" | ", paths),
  528. };
  529. }
  530. private static string Md5(string s)
  531. {
  532. var bytes = MD5.HashData(Encoding.UTF8.GetBytes(s));
  533. return Convert.ToHexString(bytes).ToLowerInvariant();
  534. }
  535. }
  536. /// <summary>候选实例 + 其反查出的业务租户 + 快照中待迁的数字角色引用。</summary>
  537. public sealed class S7MigrationCandidate
  538. {
  539. public ApprovalFlowInstance Instance { get; set; } = null!;
  540. public long BusinessTenantId { get; set; }
  541. public List<S7NumericRoleRef> NumericRefs { get; set; } = new();
  542. }
  543. /// <summary>快照中一个 Role 节点里的数字角色引用。</summary>
  544. public sealed class S7NumericRoleRef
  545. {
  546. public string NodeId { get; set; } = string.Empty;
  547. public string ApproverIds { get; set; } = string.Empty;
  548. public List<string> NumericTokens { get; set; } = new();
  549. }
  550. /// <summary>
  551. /// 逐条评估结论:要么是一份「可应用的计划」,要么是「被哪道门禁挡下、为什么」。
  552. /// Dry-run 与 Apply 消费同一个对象,因此预演输出与实际改写在代码上无法分叉。
  553. /// </summary>
  554. public sealed class S7MigrationEvaluation
  555. {
  556. public S7MigrationCandidate Candidate { get; set; } = null!;
  557. public bool CanApply { get; set; }
  558. public string Before { get; set; } = string.Empty;
  559. public string BeforeMd5 { get; set; } = string.Empty;
  560. /// <summary>仅 <see cref="CanApply"/> 为真时有值。</summary>
  561. public string? After { get; set; }
  562. public string? AfterMd5 { get; set; }
  563. public List<string> ChangedNodeIds { get; set; } = new();
  564. public string? ChangedPaths { get; set; }
  565. public List<string> Mappings { get; set; } = new();
  566. public string? RollbackSource { get; set; }
  567. /// <summary>被挡下时的 outcome 码与原因;可应用时为 null。</summary>
  568. public string? Outcome { get; set; }
  569. public string? Reason { get; set; }
  570. }
  571. /// <summary>结构化改写结果:改后全文 + 被改动节点 + 可读路径。</summary>
  572. public sealed class S7AuthorityRewrite
  573. {
  574. public string After { get; set; } = string.Empty;
  575. public List<string> ChangedNodeIds { get; set; } = new();
  576. public string ChangedPathText { get; set; } = string.Empty;
  577. }