S8ExceptionService.cs 28 KB

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