S8ExceptionService.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. using Admin.NET.Plugin.AiDOP.Dto.S8;
  2. using Admin.NET.Plugin.AiDOP.Entity.S0.Manufacturing;
  3. using Admin.NET.Plugin.AiDOP.Entity.S0.Warehouse;
  4. using Admin.NET.Plugin.AiDOP.Entity.S8;
  5. using Admin.NET.Plugin.AiDOP.Infrastructure;
  6. using Admin.NET.Plugin.AiDOP.Const.S8;
  7. using Admin.NET.Plugin.AiDOP.Infrastructure.S8;
  8. namespace Admin.NET.Plugin.AiDOP.Service.S8;
  9. public class S8ExceptionService : ITransient
  10. {
  11. private readonly SqlSugarRepository<AdoS8Exception> _rep;
  12. private readonly SqlSugarRepository<AdoS0DepartmentMaster> _deptRep;
  13. private readonly IS8UserScopeValidator _userScope;
  14. private readonly IS8ExceptionActionAuthorizer _actionAuthorizer;
  15. private readonly IS8RuleHandlerPoolReader _handlerPool;
  16. private readonly UserManager _userManager;
  17. private readonly S8ImpactMetricsService _impactMetricsService;
  18. // S8-DEMO-IMPACT-SORT-NOTICE-1:影响排序的候选集合上限。
  19. // 超过此阈值时降级为 CreatedAt DESC 走 DB 分页,避免全量取 → 内存排序在生产规模下退化。
  20. private const int ImpactSortCandidateCap = 2000;
  21. // S8-EXCEPTION-DEPT-NAME-HYDRATION-MASTERDATA-FACTORY-FIX-1:未归属部门 codename(与 S8ManualReportService 同协议常量值)。
  22. private const string UnassignedDepartmentCode = "D-UNASSIGNED";
  23. public S8ExceptionService(
  24. SqlSugarRepository<AdoS8Exception> rep,
  25. SqlSugarRepository<AdoS0DepartmentMaster> deptRep,
  26. IS8UserScopeValidator userScope,
  27. IS8ExceptionActionAuthorizer actionAuthorizer,
  28. IS8RuleHandlerPoolReader handlerPool,
  29. UserManager userManager,
  30. S8ImpactMetricsService impactMetricsService)
  31. {
  32. _rep = rep;
  33. _deptRep = deptRep;
  34. _userScope = userScope;
  35. _actionAuthorizer = actionAuthorizer;
  36. _handlerPool = handlerPool;
  37. _userManager = userManager;
  38. _impactMetricsService = impactMetricsService;
  39. }
  40. /// <summary>
  41. /// 解析当前账号的异常可见范围。
  42. ///
  43. /// <para>返回 null = <b>不加限制</b>(持有 <c>EXCEPTION_VIEW_ALL</c>,或没有登录上下文
  44. /// 的内部调用如看板聚合 / 后台作业)。返回值 = (我负责的规则编码集合, 我的账号 Id)。</para>
  45. ///
  46. /// <para><b>超管不受限</b>:与 <c>S8ExceptionActionAttribute</c> 同口径,
  47. /// 避免出现"平台放行、S8 拦截"的不一致。</para>
  48. /// </summary>
  49. private async Task<(List<string> RuleCodes, long UserId)?> ResolveVisibilityScopeAsync(long tenantId)
  50. {
  51. if (_userManager.SuperAdmin) return null;
  52. var userId = _userManager.UserId;
  53. // 无登录上下文(看板聚合 / 后台作业)不做人员可见性收敛 ——
  54. // 那些调用方本来就不是"某个人在看列表",加上限制只会让统计数字凭空少掉。
  55. if (userId <= 0 || tenantId <= 0) return null;
  56. var allowed = await _actionAuthorizer.GetAllowedActionsAsync(tenantId, userId);
  57. if (allowed.Contains(S8ExceptionActionCode.ViewAll)) return null;
  58. var ruleCodes = (await _handlerPool.GetRuleCodesForUserAsync(tenantId, userId)).ToList();
  59. return (ruleCodes, userId);
  60. }
  61. public async Task<(int total, List<AdoS8ExceptionListItemDto> list)> GetPagedAsync(AdoS8ExceptionQueryDto q)
  62. {
  63. (q.Page, q.PageSize) = PagingGuard.Normalize(q.Page, q.PageSize);
  64. var pendingStatuses = new[] { "NEW", "ASSIGNED", "IN_PROGRESS", "PENDING_VERIFICATION" };
  65. var includeUnclassified = q.IncludeUnclassified == true;
  66. // S8-SLA-TIMEOUT-RUNTIME-1(P3):方法入口取一次 now,供 q.TimeoutFlag 筛选 + 投影写 TimeoutFlag 共用,避免分页前后不一致。
  67. var timeoutNow = DateTime.Now;
  68. var query = _rep.Context.Queryable<AdoS8Exception>()
  69. // S8-TENANT-ONLY-BATCH6:join 键去掉 factory_id。
  70. // 不去掉是**必然断链**:本批之后异常 factory_id 恒为 0,而库里的 scene_config
  71. // 全部是 factory_id ≠ 0 的租户行(实测 29 行,无一为 0),
  72. // 带 factory 的 join 一条也匹配不上 —— 场景名与规则名会整列变空,且不报错。
  73. .LeftJoin<AdoS8SceneConfig>((e, sc) =>
  74. e.TenantId == sc.TenantId && e.SceneCode == sc.SceneCode)
  75. .LeftJoin<AdoS8WatchRule>((e, sc, wr) =>
  76. e.TenantId == wr.TenantId && e.SourceRuleCode == wr.RuleCode)
  77. .Where((e, sc, wr) => e.TenantId == q.TenantId && !e.IsDeleted)
  78. // S8-EXCEPTION-FIRST-VIEW-CLOSURE-1(CC-1):默认列表的「已分类」口径同时要求 stage_code 非空。
  79. // stage_code 是 Monitoring 聚合键(GetSummaryAsync 按 S8ModuleCode.All 过滤),为空即「未归入任何业务域」,
  80. // 与 exception_type_code 为空同属未分类。所有建单入口(S8ManualReportService 的手工/watch/hit 三分支)
  81. // 都会写 stage_code,故本条只影响历史遗留行;下钻仍可用 includeUnclassified=true 查看全量。
  82. .WhereIF(!includeUnclassified, (e, sc, wr) =>
  83. !SqlFunc.IsNullOrEmpty(e.ExceptionTypeCode) && !SqlFunc.IsNullOrEmpty(e.StageCode))
  84. .WhereIF(!string.IsNullOrWhiteSpace(q.Status), (e, sc, wr) => e.Status == q.Status)
  85. .WhereIF(string.IsNullOrWhiteSpace(q.Status) && q.StatusBucket == "pending",
  86. (e, sc, wr) => pendingStatuses.Contains(e.Status))
  87. // S8-SEVERITY-FOLLOW-SERIOUS-STANDARDIZE-EXEC-1:legacy 兼容 — q.Severity 传 LOW/MEDIUM/HIGH/CRITICAL 时
  88. // 通过 Normalize 映射为 FOLLOW/SERIOUS 再过滤。
  89. .WhereIF(!string.IsNullOrWhiteSpace(q.Severity),
  90. (e, sc, wr) => e.Severity == S8SeverityCode.Normalize(q.Severity))
  91. .WhereIF(!string.IsNullOrWhiteSpace(q.SceneCode), (e, sc, wr) => e.SceneCode == q.SceneCode)
  92. .WhereIF(!string.IsNullOrWhiteSpace(q.ModuleCode), (e, sc, wr) => e.ModuleCode == q.ModuleCode)
  93. // S8-DASHBOARD-DATA-ALIGN-S1S7-1:看板明细表传 OnlyS1S7Modules=true 时与 KPI 口径对齐;
  94. // 异常列表页不传该参数,行为保持不变(仍可见 NULL module 的 legacy 行)。
  95. .WhereIF(q.OnlyS1S7Modules == true, (e, sc, wr) => S8ModuleCode.All.Contains(e.ModuleCode))
  96. .WhereIF(q.DeptId.HasValue, (e, sc, wr) => e.ResponsibleDeptId == q.DeptId!.Value || e.OccurrenceDeptId == q.DeptId!.Value)
  97. // S8-SLA-TIMEOUT-RUNTIME-1(P3):q.TimeoutFlag 由 timeout_flag 字段筛选切到 sla_deadline + status 在线计算。
  98. // q.TimeoutFlag=true → 当前超时;q.TimeoutFlag=false → 未当前超时(含未配 SLA / 已关闭 / 已恢复)。
  99. .WhereIF(q.TimeoutFlag == true, (e, sc, wr) => e.SlaDeadline != null && e.SlaDeadline < timeoutNow && e.Status != "CLOSED" && e.Status != "RECOVERED")
  100. .WhereIF(q.TimeoutFlag == false, (e, sc, wr) => !(e.SlaDeadline != null && e.SlaDeadline < timeoutNow && e.Status != "CLOSED" && e.Status != "RECOVERED"))
  101. .WhereIF(q.BeginTime.HasValue, (e, sc, wr) => e.CreatedAt >= q.BeginTime!.Value)
  102. .WhereIF(q.EndTime.HasValue, (e, sc, wr) => e.CreatedAt <= q.EndTime!.Value)
  103. .WhereIF(!string.IsNullOrWhiteSpace(q.ProcessNodeCode), (e, sc, wr) => e.ProcessNodeCode == q.ProcessNodeCode)
  104. .WhereIF(!string.IsNullOrWhiteSpace(q.RelatedObjectCode), (e, sc, wr) => e.RelatedObjectCode == q.RelatedObjectCode)
  105. .WhereIF(!string.IsNullOrWhiteSpace(q.OrderFlowCode), (e, sc, wr) => e.OrderFlowCode == q.OrderFlowCode)
  106. .WhereIF(!string.IsNullOrWhiteSpace(q.StageCode), (e, sc, wr) => e.StageCode == q.StageCode)
  107. .WhereIF(!string.IsNullOrWhiteSpace(q.RuleMechanism), (e, sc, wr) => e.RuleMechanism == q.RuleMechanism)
  108. .WhereIF(q.RecoveredStatus == "RECOVERED", (e, sc, wr) => e.RecoveredAt != null)
  109. .WhereIF(q.RecoveredStatus == "ACTIVE", (e, sc, wr) => e.RecoveredAt == null)
  110. .WhereIF(!string.IsNullOrWhiteSpace(q.RuleType), (e, sc, wr) => wr.RuleType == q.RuleType)
  111. .WhereIF(!string.IsNullOrWhiteSpace(q.Keyword),
  112. (e, sc, wr) => e.Title.Contains(q.Keyword!) || e.ExceptionCode.Contains(q.Keyword!));
  113. // ── S8-HANDLER-POOL-1:可见性收敛 ──
  114. //
  115. // View 与 View All 是两件事:前者是"能进这个页面",后者是"能看别人负责的单子"。
  116. // 没有 EXCEPTION_VIEW_ALL 的账号只看得到:① 自己负责的规则产出的异常;
  117. // ② 人工提报(无来源规则,不归属任何责任池);③ 与自己直接相关的单子
  118. // (处理人 / 检验人 / 提报人是本人)——最后一条是必要的:单据可能在他认领之后
  119. // 被移出责任池,若不保留这一支,他会看不见自己手上正在处理的单子。
  120. //
  121. // 这是 EXCEPTION_VIEW_ALL 的**唯一真实消费方**。P1-B 建立该配置位时它还没有消费方,
  122. // 在此闭环。
  123. var visibilityScope = await ResolveVisibilityScopeAsync(q.TenantId);
  124. if (visibilityScope != null)
  125. {
  126. var (myRuleCodes, myUserId) = visibilityScope.Value;
  127. query = query.Where((e, sc, wr) =>
  128. SqlFunc.IsNullOrEmpty(e.SourceRuleCode)
  129. || myRuleCodes.Contains(e.SourceRuleCode)
  130. || e.AssigneeUserId == myUserId
  131. || e.VerifierUserId == myUserId
  132. || e.ReporterUserId == myUserId);
  133. }
  134. var total = await query.CountAsync();
  135. // S8-DEMO-IMPACT-SORT-NOTICE-1:候选集合 <= ImpactSortCandidateCap 时走"全量取 → 内存填影响 → 排序 → 分页",
  136. // 支持 impactScore / repeatCount30d / cumulativeLossHours30d 等运行期字段排序;超过则降级 DB 分页 createdAt DESC。
  137. var useImpactSort = total > 0 && total <= ImpactSortCandidateCap;
  138. List<AdoS8ExceptionListItemDto> list;
  139. if (useImpactSort)
  140. {
  141. // 先按 query 命中集合一次性取候选,order 仅 createdAt DESC 用于稳定性,后续内存覆写排序。
  142. var candidates = await query
  143. .OrderBy((e, sc, wr) => e.CreatedAt, OrderByType.Desc)
  144. .Take(ImpactSortCandidateCap)
  145. .Select((e, sc, wr) => new AdoS8ExceptionListItemDto
  146. {
  147. Id = e.Id,
  148. FactoryId = e.FactoryId,
  149. ExceptionCode = e.ExceptionCode,
  150. Title = e.Title,
  151. Status = e.Status,
  152. Severity = e.Severity,
  153. PriorityScore = e.PriorityScore,
  154. PriorityLevel = e.PriorityLevel,
  155. SceneCode = e.SceneCode,
  156. SceneName = sc.SceneName,
  157. ModuleCode = e.ModuleCode,
  158. ResponsibleDeptId = e.ResponsibleDeptId,
  159. OccurrenceDeptId = e.OccurrenceDeptId,
  160. AssigneeUserId = e.AssigneeUserId,
  161. SlaDeadline = e.SlaDeadline,
  162. TimeoutFlag = e.SlaDeadline != null && e.SlaDeadline < timeoutNow && e.Status != "CLOSED" && e.Status != "RECOVERED",
  163. CreatedAt = e.CreatedAt,
  164. ClosedAt = e.ClosedAt,
  165. ExceptionTypeCode = e.ExceptionTypeCode,
  166. RecoveredAt = e.RecoveredAt,
  167. SourceRuleCode = e.SourceRuleCode,
  168. SourceObjectType = e.SourceObjectType,
  169. SourceObjectId = e.SourceObjectId,
  170. DedupKey = e.DedupKey,
  171. LastDetectedAt = e.LastDetectedAt,
  172. RuleType = wr.RuleType,
  173. RelatedObjectCode = e.RelatedObjectCode,
  174. OrderFlowCode = e.OrderFlowCode,
  175. StageCode = e.StageCode,
  176. RuleMechanism = e.RuleMechanism,
  177. })
  178. .ToListAsync();
  179. // DTO 后处理:损失时间 / 是否超时关闭 / 标签。
  180. foreach (var r in candidates)
  181. {
  182. r.StatusLabel = S8Labels.StatusLabel(r.Status);
  183. r.SeverityLabel = S8Labels.SeverityLabel(r.Severity);
  184. r.ModuleName = string.IsNullOrWhiteSpace(r.ModuleCode) ? null : S8ModuleCode.Label(r.ModuleCode!);
  185. var (lossHours, isOverdueClosed) = ComputeClosureMetrics(r.CreatedAt, r.ClosedAt, r.SlaDeadline);
  186. r.LossHours = lossHours;
  187. r.IsOverdueClosed = isOverdueClosed;
  188. }
  189. // 影响统计批量填充(30 天窗口聚合一次性 GROUP BY,O(n) 回填,无 N+1)。
  190. var impactRows = candidates
  191. .Select(r => new ExceptionImpactRow
  192. {
  193. Id = r.Id,
  194. ExceptionTypeCode = r.ExceptionTypeCode,
  195. Severity = r.Severity,
  196. CreatedAt = r.CreatedAt,
  197. ClosedAt = r.ClosedAt,
  198. TimeoutFlag = r.TimeoutFlag,
  199. })
  200. .ToList();
  201. await _impactMetricsService.FillBatchAsync(q.TenantId, impactRows);
  202. var impactById = impactRows.ToDictionary(x => x.Id);
  203. foreach (var r in candidates)
  204. {
  205. if (!impactById.TryGetValue(r.Id, out var snap)) continue;
  206. r.RepeatCount30d = snap.RepeatCount30d;
  207. r.CumulativeLossHours30d = snap.CumulativeLossHours30d;
  208. r.ImpactScore = snap.ImpactScore;
  209. r.SuggestedAttentionLevel = snap.SuggestedAttentionLevel;
  210. r.SuggestedAttentionLabel = snap.SuggestedAttentionLabel;
  211. r.ImpactReason = snap.ImpactReason;
  212. }
  213. // 内存排序(白名单,非白名单回退 createdAt DESC)。
  214. var sorted = ApplyImpactSort(candidates, q.SortField, q.SortOrder);
  215. // 内存分页。
  216. list = sorted
  217. .Skip((q.Page - 1) * q.PageSize)
  218. .Take(q.PageSize)
  219. .ToList();
  220. }
  221. else
  222. {
  223. // 降级路径:候选 > ImpactSortCandidateCap,DB 分页 createdAt DESC,不填充影响字段(前端展示 0/null)。
  224. list = await query
  225. .OrderBy((e, sc, wr) => e.CreatedAt, OrderByType.Desc)
  226. .Select((e, sc, wr) => new AdoS8ExceptionListItemDto
  227. {
  228. Id = e.Id,
  229. FactoryId = e.FactoryId,
  230. ExceptionCode = e.ExceptionCode,
  231. Title = e.Title,
  232. Status = e.Status,
  233. Severity = e.Severity,
  234. PriorityScore = e.PriorityScore,
  235. PriorityLevel = e.PriorityLevel,
  236. SceneCode = e.SceneCode,
  237. SceneName = sc.SceneName,
  238. ModuleCode = e.ModuleCode,
  239. ResponsibleDeptId = e.ResponsibleDeptId,
  240. OccurrenceDeptId = e.OccurrenceDeptId,
  241. AssigneeUserId = e.AssigneeUserId,
  242. SlaDeadline = e.SlaDeadline,
  243. TimeoutFlag = e.SlaDeadline != null && e.SlaDeadline < timeoutNow && e.Status != "CLOSED" && e.Status != "RECOVERED",
  244. CreatedAt = e.CreatedAt,
  245. ClosedAt = e.ClosedAt,
  246. ExceptionTypeCode = e.ExceptionTypeCode,
  247. RecoveredAt = e.RecoveredAt,
  248. SourceRuleCode = e.SourceRuleCode,
  249. SourceObjectType = e.SourceObjectType,
  250. SourceObjectId = e.SourceObjectId,
  251. DedupKey = e.DedupKey,
  252. LastDetectedAt = e.LastDetectedAt,
  253. RuleType = wr.RuleType,
  254. RelatedObjectCode = e.RelatedObjectCode,
  255. OrderFlowCode = e.OrderFlowCode,
  256. StageCode = e.StageCode,
  257. RuleMechanism = e.RuleMechanism,
  258. })
  259. .ToPageListAsync(q.Page, q.PageSize);
  260. foreach (var r in list)
  261. {
  262. r.StatusLabel = S8Labels.StatusLabel(r.Status);
  263. r.SeverityLabel = S8Labels.SeverityLabel(r.Severity);
  264. r.ModuleName = string.IsNullOrWhiteSpace(r.ModuleCode) ? null : S8ModuleCode.Label(r.ModuleCode!);
  265. var (lossHours, isOverdueClosed) = ComputeClosureMetrics(r.CreatedAt, r.ClosedAt, r.SlaDeadline);
  266. r.LossHours = lossHours;
  267. r.IsOverdueClosed = isOverdueClosed;
  268. }
  269. }
  270. await FillDisplayNamesAsync(list, q.TenantId);
  271. return (total, list);
  272. }
  273. // S8-DEMO-IMPACT-SORT-NOTICE-1:白名单排序;severity 自定义键(SERIOUS=2 / FOLLOW=1 / 其他=0)。
  274. // sortField 空或非白名单 → createdAt DESC;sortOrder 非 asc/desc → desc。
  275. private static List<AdoS8ExceptionListItemDto> ApplyImpactSort(
  276. List<AdoS8ExceptionListItemDto> rows, string? sortField, string? sortOrder)
  277. {
  278. var asc = string.Equals(sortOrder, "asc", StringComparison.OrdinalIgnoreCase);
  279. var key = (sortField ?? string.Empty).Trim();
  280. return key switch
  281. {
  282. "impactScore" => asc
  283. ? rows.OrderBy(r => r.ImpactScore).ThenByDescending(r => r.CreatedAt).ToList()
  284. : rows.OrderByDescending(r => r.ImpactScore).ThenByDescending(r => r.CreatedAt).ToList(),
  285. "repeatCount30d" => asc
  286. ? rows.OrderBy(r => r.RepeatCount30d).ThenByDescending(r => r.CreatedAt).ToList()
  287. : rows.OrderByDescending(r => r.RepeatCount30d).ThenByDescending(r => r.CreatedAt).ToList(),
  288. "cumulativeLossHours30d" => asc
  289. ? rows.OrderBy(r => r.CumulativeLossHours30d).ThenByDescending(r => r.CreatedAt).ToList()
  290. : rows.OrderByDescending(r => r.CumulativeLossHours30d).ThenByDescending(r => r.CreatedAt).ToList(),
  291. "severity" => asc
  292. ? rows.OrderBy(r => SeveritySortKey(r.Severity)).ThenByDescending(r => r.CreatedAt).ToList()
  293. : rows.OrderByDescending(r => SeveritySortKey(r.Severity)).ThenByDescending(r => r.CreatedAt).ToList(),
  294. "priorityScore" => asc
  295. ? rows.OrderBy(r => r.PriorityScore).ThenByDescending(r => r.CreatedAt).ToList()
  296. : rows.OrderByDescending(r => r.PriorityScore).ThenByDescending(r => r.CreatedAt).ToList(),
  297. "createdAt" => asc
  298. ? rows.OrderBy(r => r.CreatedAt).ToList()
  299. : rows.OrderByDescending(r => r.CreatedAt).ToList(),
  300. _ => rows.OrderByDescending(r => r.CreatedAt).ToList(),
  301. };
  302. }
  303. private static int SeveritySortKey(string severity) => severity switch
  304. {
  305. "SERIOUS" => 2,
  306. "FOLLOW" => 1,
  307. _ => 0,
  308. };
  309. public async Task<object> GetFilterOptionsAsync(long tenantId)
  310. {
  311. var scenes = await _rep.Context.Queryable<AdoS8SceneConfig>()
  312. .Where(x => x.TenantId == tenantId && x.Enabled)
  313. .OrderBy(x => x.SortNo)
  314. .Select(x => new { value = x.SceneCode, label = x.SceneName })
  315. .ToListAsync();
  316. var departments = await _deptRep.AsQueryable()
  317. .Where(x => x.TenantId == tenantId)
  318. .OrderBy(x => x.Department)
  319. .Take(500)
  320. .Select(x => new { value = x.Id, label = x.Descr ?? x.Department })
  321. .ToListAsync();
  322. // S8-EXCEPTION-MODULE-DISPLAY-1:业务展示主口径切到 module_code(S1-S7)。
  323. // scenes 保留兼容期,前端筛选已切到 modules。
  324. var modules = S8ModuleCode.All
  325. .Select(code => new { value = code, label = S8ModuleCode.Label(code) })
  326. .ToList();
  327. return new
  328. {
  329. statuses = S8Labels.StatusOptions(),
  330. severities = S8Labels.SeverityOptions(),
  331. scenes,
  332. modules,
  333. departments
  334. };
  335. }
  336. public async Task<AdoS8ExceptionDetailDto?> GetDetailAsync(long id, long tenantId)
  337. {
  338. // S8-SLA-TIMEOUT-RUNTIME-1(P3):详情 TimeoutFlag 与 list 同口径,运行时计算。
  339. var timeoutNow = DateTime.Now;
  340. var rows = await _rep.Context.Queryable<AdoS8Exception>()
  341. .LeftJoin<AdoS8SceneConfig>((e, sc) =>
  342. e.TenantId == sc.TenantId && e.SceneCode == sc.SceneCode)
  343. .LeftJoin<AdoS8WatchRule>((e, sc, wr) =>
  344. e.TenantId == wr.TenantId && e.SourceRuleCode == wr.RuleCode)
  345. .Where((e, sc, wr) => e.Id == id && e.TenantId == tenantId && !e.IsDeleted)
  346. .Select((e, sc, wr) => new AdoS8ExceptionDetailDto
  347. {
  348. Id = e.Id,
  349. FactoryId = e.FactoryId,
  350. ExceptionCode = e.ExceptionCode,
  351. Title = e.Title,
  352. Description = e.Description,
  353. Status = e.Status,
  354. Severity = e.Severity,
  355. PriorityScore = e.PriorityScore,
  356. PriorityLevel = e.PriorityLevel,
  357. SceneCode = e.SceneCode,
  358. SceneName = sc.SceneName,
  359. ModuleCode = e.ModuleCode,
  360. SourceType = e.SourceType,
  361. OccurrenceDeptId = e.OccurrenceDeptId,
  362. ResponsibleDeptId = e.ResponsibleDeptId,
  363. ResponsibleGroupId = e.ResponsibleGroupId,
  364. AssigneeUserId = e.AssigneeUserId,
  365. ReporterUserId = e.ReporterUserId,
  366. SlaDeadline = e.SlaDeadline,
  367. // S8-SLA-TIMEOUT-RUNTIME-1(P3):详情展示 TimeoutFlag = 在线计算。
  368. TimeoutFlag = e.SlaDeadline != null && e.SlaDeadline < timeoutNow && e.Status != "CLOSED" && e.Status != "RECOVERED",
  369. CreatedAt = e.CreatedAt,
  370. ClosedAt = e.ClosedAt,
  371. AssignedAt = e.AssignedAt,
  372. UpdatedAt = e.UpdatedAt,
  373. ActiveFlowInstanceId = e.ActiveFlowInstanceId,
  374. ActiveFlowBizType = e.ActiveFlowBizType,
  375. VerifierUserId = e.VerifierUserId,
  376. VerificationAssignedAt = e.VerificationAssignedAt,
  377. VerifiedAt = e.VerifiedAt,
  378. VerificationResult = e.VerificationResult,
  379. VerificationRemark = e.VerificationRemark,
  380. SourceRuleId = e.SourceRuleId,
  381. RelatedObjectCode = e.RelatedObjectCode,
  382. DedupKey = e.DedupKey,
  383. LastDetectedAt = e.LastDetectedAt,
  384. RecoveredAt = e.RecoveredAt,
  385. SourceRuleCode = e.SourceRuleCode,
  386. SourceObjectType = e.SourceObjectType,
  387. SourceObjectId = e.SourceObjectId,
  388. ExceptionTypeCode = e.ExceptionTypeCode,
  389. RuleType = wr.RuleType,
  390. OrderFlowCode = e.OrderFlowCode,
  391. StageCode = e.StageCode,
  392. RuleMechanism = e.RuleMechanism,
  393. })
  394. .Take(1)
  395. .ToListAsync();
  396. if (rows.Count == 0) return null;
  397. var d = rows[0];
  398. d.StatusLabel = S8Labels.StatusLabel(d.Status);
  399. d.SeverityLabel = S8Labels.SeverityLabel(d.Severity);
  400. d.ModuleName = string.IsNullOrWhiteSpace(d.ModuleCode) ? null : S8ModuleCode.Label(d.ModuleCode!);
  401. // S8-DEMO-CORE-FIELD-COMPLETE-1:详情与列表同口径,DTO 后处理计算损失时间 / 是否超时关闭。
  402. var (lossHours, isOverdueClosed) = ComputeClosureMetrics(d.CreatedAt, d.ClosedAt, d.SlaDeadline);
  403. d.LossHours = lossHours;
  404. d.IsOverdueClosed = isOverdueClosed;
  405. await FillDisplayNamesAsync(new[] { d }, tenantId);
  406. return d;
  407. }
  408. // S8-DEMO-CORE-FIELD-COMPLETE-1:损失时间(小时,1 位小数)+ 是否超时关闭(冻结判定)。
  409. // 未关闭 → LossHours=null;未关闭或无 SLA → IsOverdueClosed=null。与运行时 TimeoutFlag 不复用。
  410. private static (decimal? lossHours, bool? isOverdueClosed) ComputeClosureMetrics(
  411. DateTime createdAt, DateTime? closedAt, DateTime? slaDeadline)
  412. {
  413. decimal? lossHours = closedAt == null
  414. ? (decimal?)null
  415. : Math.Round((decimal)(closedAt.Value - createdAt).TotalHours, 1);
  416. bool? isOverdueClosed = (closedAt == null || slaDeadline == null)
  417. ? (bool?)null
  418. : closedAt.Value > slaDeadline.Value;
  419. return (lossHours, isOverdueClosed);
  420. }
  421. // S8-DEPT-DISPLAY-CONSISTENCY-1(P0-A-2/A-3):list 行也水合 OccurrenceDeptName;
  422. // 部门查询加租户二次约束,避免跨租户同名 / 同 RecID 错位。
  423. private async Task FillDisplayNamesAsync(IEnumerable<AdoS8ExceptionListItemDto> rows, long tenantId)
  424. {
  425. var list = rows.ToList();
  426. if (list.Count == 0) return;
  427. var deptIds = list
  428. .Select(x => x.ResponsibleDeptId)
  429. .Concat(list.Select(x => x.OccurrenceDeptId))
  430. .Where(x => x > 0)
  431. .Distinct()
  432. .ToList();
  433. // S8-DEPARTMENT-LOOKUP-CLOSURE-1(B-1):部门水合曾用**全局单值配置** S8MasterData.DepartmentFactoryRefId
  434. // 解析主数据 factory,在多租户下必然只能服务一个租户;已废除,改用当前请求的 trusted 边界。
  435. //
  436. // S8-TENANT-ONLY-BATCH6:该 trusted 边界由 factoryId 收敛为 **tenantId**。
  437. // B-1 当时的理由是「各 S8 运营租户的 DepartmentMaster.factory_ref_id 均等于其运营 factoryId
  438. // (每租户 factory 唯一)」—— 真库复查证明这个前提今天已不成立:
  439. // factory_ref_id = 1000 同时属于 824585161322565 与 797403760988229 两个租户,
  440. // 按 factory 水合会把另一租户的 210 个部门当作可用名称来源。tenant_id 才是唯一正确的边界。
  441. var deptMap = deptIds.Count == 0
  442. ? new Dictionary<long, string>()
  443. : (await _deptRep.AsQueryable().ClearFilter()
  444. .Where(x => deptIds.Contains(x.Id) && x.TenantId == tenantId)
  445. .Select(x => new { x.Id, Name = x.Descr ?? x.Department })
  446. .ToListAsync())
  447. .ToDictionary(x => x.Id, x => x.Name);
  448. // S8-SYSUSER-ONLY-1:处理人 / 检验人 / 提报人现在同为 SysUser.Id,一次水合三个字段。
  449. //
  450. // 原实现要查两张表:EmployeeMaster(assignee/verifier,且 ClearFilter 无租户谓词)
  451. // 与 SysUser(reporter 的兼容兜底),并按"empMap 优先、userMap 兜底"合并 ——
  452. // 那正是同一列曾经装过两套 ID 的证据。现在只有一个 ID 空间、一次查询、一个租户边界。
  453. var personIds = list
  454. .SelectMany(x => new[]
  455. {
  456. x.AssigneeUserId ?? 0L,
  457. (x as AdoS8ExceptionDetailDto)?.VerifierUserId ?? 0L,
  458. (x as AdoS8ExceptionDetailDto)?.ReporterUserId ?? 0L
  459. })
  460. .Where(x => x > 0)
  461. .Distinct()
  462. .ToList();
  463. // 判据与认领 / 转派 / 复检完全同源(见 S8UserScopeValidator):租户内 + 启用。
  464. // 停用账号解析不出名字 → 回落 UnresolvedLookupLabel,与部门的处理一致。
  465. var personMap = await _userScope.ResolveDisplayAsync(tenantId, personIds);
  466. foreach (var row in list)
  467. {
  468. row.ResponsibleDeptName = ResolveDeptName(row.ResponsibleDeptId, deptMap);
  469. row.OccurrenceDeptName = ResolveDeptName(row.OccurrenceDeptId, deptMap);
  470. row.AssigneeName = ResolvePersonName(row.AssigneeUserId, personMap);
  471. if (row is AdoS8ExceptionDetailDto detail)
  472. {
  473. detail.ReporterName = ResolvePersonName(detail.ReporterUserId, personMap);
  474. detail.VerifierName = ResolvePersonName(detail.VerifierUserId, personMap);
  475. }
  476. }
  477. }
  478. /// <summary>
  479. /// 人员名水合。空 = 未指派(返回 null,前端按"未指派"展示);
  480. /// 有值但解析不到 = 账号已停用或已被移出本租户 → 与部门同口径回落业务可读文案,
  481. /// <b>绝不回落成裸数字 ID</b>(那对业务用户没有任何意义)。
  482. /// </summary>
  483. private static string? ResolvePersonName(long? userId, IReadOnlyDictionary<long, S8OperatorUser> map)
  484. {
  485. if (userId is not > 0) return null;
  486. return map.TryGetValue(userId.Value, out var u) ? u.DisplayName : UnresolvedLookupLabel;
  487. }
  488. // S8-DEPT-DISPLAY-CONSISTENCY-1(P0-A-3):dept fallback —— 0/缺失=未归属。
  489. // S8-EXCEPTION-FIRST-VIEW-CLOSURE-1(CC-2):解析不到主数据时不再回落「部门ID:{id}」——
  490. // 裸内部 ID 对业务用户无意义,且只可能出现在 FK 悬空的历史行上,统一显示为业务可读文案。
  491. internal const string UnresolvedLookupLabel = "历史数据 / 未配置";
  492. private static string? ResolveDeptName(long deptId, Dictionary<long, string> deptMap)
  493. {
  494. if (deptId <= 0) return "未归属";
  495. return deptMap.TryGetValue(deptId, out var name) && !string.IsNullOrWhiteSpace(name)
  496. ? name
  497. : UnresolvedLookupLabel;
  498. }
  499. // S8-DEPARTMENT-LOOKUP-CLOSURE-1(B-1):原 ResolveMasterDataDepartmentFactoryRefIdAsync 已移除。
  500. // 它把全局单值配置 S8MasterData.DepartmentFactoryRefId 作为部门主数据 factory,在多租户下不安全
  501. // (实测导致跨租户读取 + 其余租户全部解析失败)。
  502. // S8-TENANT-ONLY-BATCH6:显示路径的边界进一步收敛为 trusted tenantId(factory 横跨租户,不可作边界)。
  503. /// <summary>
  504. /// S2-EW:debug-only 软删 RelatedObjectCode 以 "TEST_G09_" 开头的异常。
  505. /// 调用方仅限 <see cref="Controllers.S8.AdoS8WatchDebugController"/>,由其 _debugEndpointEnabled 守门。
  506. /// 实现纪律:
  507. /// - 仅 SET IsDeleted=true,不动业务字段(status/closed_at/source_rule_id 等)。
  508. /// - 前缀字面量硬编码,不接受外部 prefix;防止前缀注入。
  509. /// - 不联动 timeline / decision / evidence;业务读路径以父 IsDeleted 屏蔽。
  510. /// </summary>
  511. public async Task<int> SoftDeleteTestPrefixAsync(long tenantId)
  512. {
  513. const string prefix = "TEST_G09_";
  514. var affected = await _rep.AsUpdateable()
  515. .SetColumns(e => new AdoS8Exception { IsDeleted = true })
  516. .Where(e => e.TenantId == tenantId
  517. && !e.IsDeleted
  518. && e.RelatedObjectCode != null
  519. && e.RelatedObjectCode.StartsWith(prefix))
  520. .ExecuteCommandAsync();
  521. System.Diagnostics.Trace.TraceWarning(
  522. $"[S2-EW] soft-deleted {affected} TEST_G09_ exceptions, tenant={tenantId}");
  523. return affected;
  524. }
  525. }