S8ExceptionService.cs 28 KB

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