S8ExceptionService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. public S8ExceptionService(
  15. SqlSugarRepository<AdoS8Exception> rep,
  16. SqlSugarRepository<AdoS0DepartmentMaster> deptRep,
  17. SqlSugarRepository<AdoS0EmployeeMaster> empRep,
  18. SqlSugarRepository<SysUser> sysUserRep)
  19. {
  20. _rep = rep;
  21. _deptRep = deptRep;
  22. _empRep = empRep;
  23. _sysUserRep = sysUserRep;
  24. }
  25. public async Task<(int total, List<AdoS8ExceptionListItemDto> list)> GetPagedAsync(AdoS8ExceptionQueryDto q)
  26. {
  27. (q.Page, q.PageSize) = PagingGuard.Normalize(q.Page, q.PageSize);
  28. var pendingStatuses = new[] { "NEW", "ASSIGNED", "IN_PROGRESS", "PENDING_VERIFICATION" };
  29. var includeUnclassified = q.IncludeUnclassified == true;
  30. var query = _rep.Context.Queryable<AdoS8Exception>()
  31. .LeftJoin<AdoS8SceneConfig>((e, sc) =>
  32. e.TenantId == sc.TenantId && e.FactoryId == sc.FactoryId && e.SceneCode == sc.SceneCode)
  33. .LeftJoin<AdoS8WatchRule>((e, sc, wr) =>
  34. e.TenantId == wr.TenantId && e.FactoryId == wr.FactoryId && e.SourceRuleCode == wr.RuleCode)
  35. .Where((e, sc, wr) => e.TenantId == q.TenantId && e.FactoryId == q.FactoryId && !e.IsDeleted)
  36. .WhereIF(!includeUnclassified, (e, sc, wr) => !SqlFunc.IsNullOrEmpty(e.ExceptionTypeCode))
  37. .WhereIF(!string.IsNullOrWhiteSpace(q.Status), (e, sc, wr) => e.Status == q.Status)
  38. .WhereIF(string.IsNullOrWhiteSpace(q.Status) && q.StatusBucket == "pending",
  39. (e, sc, wr) => pendingStatuses.Contains(e.Status))
  40. // S8-SEVERITY-FOLLOW-SERIOUS-STANDARDIZE-EXEC-1:legacy 兼容 — q.Severity 传 LOW/MEDIUM/HIGH/CRITICAL 时
  41. // 通过 Normalize 映射为 FOLLOW/SERIOUS 再过滤。
  42. .WhereIF(!string.IsNullOrWhiteSpace(q.Severity),
  43. (e, sc, wr) => e.Severity == S8SeverityCode.Normalize(q.Severity))
  44. .WhereIF(!string.IsNullOrWhiteSpace(q.SceneCode), (e, sc, wr) => e.SceneCode == q.SceneCode)
  45. .WhereIF(!string.IsNullOrWhiteSpace(q.ModuleCode), (e, sc, wr) => e.ModuleCode == q.ModuleCode)
  46. // S8-DASHBOARD-DATA-ALIGN-S1S7-1:看板明细表传 OnlyS1S7Modules=true 时与 KPI 口径对齐;
  47. // 异常列表页不传该参数,行为保持不变(仍可见 NULL module 的 legacy 行)。
  48. .WhereIF(q.OnlyS1S7Modules == true, (e, sc, wr) => S8ModuleCode.All.Contains(e.ModuleCode))
  49. .WhereIF(q.DeptId.HasValue, (e, sc, wr) => e.ResponsibleDeptId == q.DeptId!.Value || e.OccurrenceDeptId == q.DeptId!.Value)
  50. .WhereIF(q.TimeoutFlag.HasValue, (e, sc, wr) => e.TimeoutFlag == q.TimeoutFlag!.Value)
  51. .WhereIF(q.BeginTime.HasValue, (e, sc, wr) => e.CreatedAt >= q.BeginTime!.Value)
  52. .WhereIF(q.EndTime.HasValue, (e, sc, wr) => e.CreatedAt <= q.EndTime!.Value)
  53. .WhereIF(!string.IsNullOrWhiteSpace(q.ProcessNodeCode), (e, sc, wr) => e.ProcessNodeCode == q.ProcessNodeCode)
  54. .WhereIF(!string.IsNullOrWhiteSpace(q.RelatedObjectCode), (e, sc, wr) => e.RelatedObjectCode == q.RelatedObjectCode)
  55. .WhereIF(q.RecoveredStatus == "RECOVERED", (e, sc, wr) => e.RecoveredAt != null)
  56. .WhereIF(q.RecoveredStatus == "ACTIVE", (e, sc, wr) => e.RecoveredAt == null)
  57. .WhereIF(!string.IsNullOrWhiteSpace(q.RuleType), (e, sc, wr) => wr.RuleType == q.RuleType)
  58. .WhereIF(!string.IsNullOrWhiteSpace(q.Keyword),
  59. (e, sc, wr) => e.Title.Contains(q.Keyword!) || e.ExceptionCode.Contains(q.Keyword!));
  60. var total = await query.CountAsync();
  61. var list = await query
  62. .OrderBy((e, sc, wr) => e.CreatedAt, OrderByType.Desc)
  63. .Select((e, sc, wr) => new AdoS8ExceptionListItemDto
  64. {
  65. Id = e.Id,
  66. FactoryId = e.FactoryId,
  67. ExceptionCode = e.ExceptionCode,
  68. Title = e.Title,
  69. Status = e.Status,
  70. Severity = e.Severity,
  71. PriorityScore = e.PriorityScore,
  72. PriorityLevel = e.PriorityLevel,
  73. SceneCode = e.SceneCode,
  74. SceneName = sc.SceneName,
  75. ResponsibleDeptId = e.ResponsibleDeptId,
  76. AssigneeId = e.AssigneeId,
  77. SlaDeadline = e.SlaDeadline,
  78. TimeoutFlag = e.TimeoutFlag,
  79. CreatedAt = e.CreatedAt,
  80. ClosedAt = e.ClosedAt,
  81. ExceptionTypeCode = e.ExceptionTypeCode,
  82. RecoveredAt = e.RecoveredAt,
  83. SourceRuleCode = e.SourceRuleCode,
  84. SourceObjectType = e.SourceObjectType,
  85. SourceObjectId = e.SourceObjectId,
  86. DedupKey = e.DedupKey,
  87. LastDetectedAt = e.LastDetectedAt,
  88. RuleType = wr.RuleType
  89. })
  90. .ToPageListAsync(q.Page, q.PageSize);
  91. foreach (var r in list)
  92. {
  93. r.StatusLabel = S8Labels.StatusLabel(r.Status);
  94. r.SeverityLabel = S8Labels.SeverityLabel(r.Severity);
  95. }
  96. await FillDisplayNamesAsync(list);
  97. return (total, list);
  98. }
  99. public async Task<object> GetFilterOptionsAsync(long tenantId, long factoryId)
  100. {
  101. var scenes = await _rep.Context.Queryable<AdoS8SceneConfig>()
  102. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && x.Enabled)
  103. .OrderBy(x => x.SortNo)
  104. .Select(x => new { value = x.SceneCode, label = x.SceneName })
  105. .ToListAsync();
  106. var departments = await _deptRep.AsQueryable()
  107. .Where(x => x.FactoryRefId == factoryId)
  108. .OrderBy(x => x.Department)
  109. .Take(500)
  110. .Select(x => new { value = x.Id, label = x.Descr ?? x.Department })
  111. .ToListAsync();
  112. return new
  113. {
  114. statuses = S8Labels.StatusOptions(),
  115. severities = S8Labels.SeverityOptions(),
  116. scenes,
  117. departments
  118. };
  119. }
  120. public async Task<AdoS8ExceptionDetailDto?> GetDetailAsync(long id, long tenantId, long factoryId)
  121. {
  122. var rows = await _rep.Context.Queryable<AdoS8Exception>()
  123. .LeftJoin<AdoS8SceneConfig>((e, sc) =>
  124. e.TenantId == sc.TenantId && e.FactoryId == sc.FactoryId && e.SceneCode == sc.SceneCode)
  125. .LeftJoin<AdoS8WatchRule>((e, sc, wr) =>
  126. e.TenantId == wr.TenantId && e.FactoryId == wr.FactoryId && e.SourceRuleCode == wr.RuleCode)
  127. .Where((e, sc, wr) => e.Id == id && e.TenantId == tenantId && e.FactoryId == factoryId && !e.IsDeleted)
  128. .Select((e, sc, wr) => new AdoS8ExceptionDetailDto
  129. {
  130. Id = e.Id,
  131. FactoryId = e.FactoryId,
  132. ExceptionCode = e.ExceptionCode,
  133. Title = e.Title,
  134. Description = e.Description,
  135. Status = e.Status,
  136. Severity = e.Severity,
  137. PriorityScore = e.PriorityScore,
  138. PriorityLevel = e.PriorityLevel,
  139. SceneCode = e.SceneCode,
  140. SceneName = sc.SceneName,
  141. SourceType = e.SourceType,
  142. OccurrenceDeptId = e.OccurrenceDeptId,
  143. ResponsibleDeptId = e.ResponsibleDeptId,
  144. ResponsibleGroupId = e.ResponsibleGroupId,
  145. AssigneeId = e.AssigneeId,
  146. ReporterId = e.ReporterId,
  147. SlaDeadline = e.SlaDeadline,
  148. TimeoutFlag = e.TimeoutFlag,
  149. CreatedAt = e.CreatedAt,
  150. ClosedAt = e.ClosedAt,
  151. AssignedAt = e.AssignedAt,
  152. UpdatedAt = e.UpdatedAt,
  153. ActiveFlowInstanceId = e.ActiveFlowInstanceId,
  154. ActiveFlowBizType = e.ActiveFlowBizType,
  155. VerifierId = e.VerifierId,
  156. VerificationAssignedAt = e.VerificationAssignedAt,
  157. VerifiedAt = e.VerifiedAt,
  158. VerificationResult = e.VerificationResult,
  159. VerificationRemark = e.VerificationRemark,
  160. SourceRuleId = e.SourceRuleId,
  161. RelatedObjectCode = e.RelatedObjectCode,
  162. DedupKey = e.DedupKey,
  163. LastDetectedAt = e.LastDetectedAt,
  164. RecoveredAt = e.RecoveredAt,
  165. SourceRuleCode = e.SourceRuleCode,
  166. SourceObjectType = e.SourceObjectType,
  167. SourceObjectId = e.SourceObjectId,
  168. ExceptionTypeCode = e.ExceptionTypeCode,
  169. RuleType = wr.RuleType,
  170. })
  171. .Take(1)
  172. .ToListAsync();
  173. if (rows.Count == 0) return null;
  174. var d = rows[0];
  175. d.StatusLabel = S8Labels.StatusLabel(d.Status);
  176. d.SeverityLabel = S8Labels.SeverityLabel(d.Severity);
  177. await FillDisplayNamesAsync(new[] { d });
  178. return d;
  179. }
  180. private async Task FillDisplayNamesAsync(IEnumerable<AdoS8ExceptionListItemDto> rows)
  181. {
  182. var list = rows.ToList();
  183. if (list.Count == 0) return;
  184. var deptIds = list
  185. .Select(x => x.ResponsibleDeptId)
  186. .Concat(list.OfType<AdoS8ExceptionDetailDto>().Select(x => x.OccurrenceDeptId))
  187. .Where(x => x > 0)
  188. .Distinct()
  189. .ToList();
  190. var empIds = list
  191. .Select(x => x.AssigneeId ?? 0L)
  192. .Concat(list.OfType<AdoS8ExceptionDetailDto>().Select(x => x.ReporterId ?? 0L))
  193. .Concat(list.OfType<AdoS8ExceptionDetailDto>().Select(x => x.VerifierId ?? 0L))
  194. .Where(x => x > 0)
  195. .Distinct()
  196. .ToList();
  197. var deptMap = deptIds.Count == 0
  198. ? new Dictionary<long, string>()
  199. : (await _deptRep.AsQueryable()
  200. .Where(x => deptIds.Contains(x.Id))
  201. .Select(x => new { x.Id, Name = x.Descr ?? x.Department })
  202. .ToListAsync())
  203. .ToDictionary(x => x.Id, x => x.Name);
  204. // EmployeeMaster.tenant_id 与 SysUser.TenantId 历史错位(797403760988229 ≠ 系统租户),
  205. // 走全局 multi-tenant filter 会全过滤为空 → 详情页处理人/检验人姓名显示数字 ID。
  206. // 与 S8MasterDataAdapter.GetEmployeesAsync / S8TaskFlowService.GetEmployeeSysUserIdAsync 同口径,
  207. // 局部 ClearFilter + employee.Id 主键集合作为安全边界,无跨租户泄漏。
  208. var empMap = empIds.Count == 0
  209. ? new Dictionary<long, string>()
  210. : (await _empRep.AsQueryable().ClearFilter()
  211. .Where(x => empIds.Contains(x.Id))
  212. .Select(x => new { x.Id, Name = x.Name ?? x.Employee })
  213. .ToListAsync())
  214. .ToDictionary(x => x.Id, x => x.Name);
  215. // ReporterId 现在记录 sysUser.Id(OBS-S8-REPORT-REPORTER-NULL-001 修复后由服务端 JWT 兜底),
  216. // 与 employee.Id 不在同一命名空间,需要单独查 SysUser 取 RealName/Account;
  217. // 同时保留对历史 reporter=employee.Id 数据的兼容(empMap fallback)。
  218. var reporterUserIds = list.OfType<AdoS8ExceptionDetailDto>()
  219. .Select(x => x.ReporterId ?? 0L)
  220. .Where(x => x > 0)
  221. .Distinct()
  222. .ToList();
  223. var reporterUserMap = reporterUserIds.Count == 0
  224. ? new Dictionary<long, string>()
  225. : (await _sysUserRep.AsQueryable().ClearFilter()
  226. .Where(u => reporterUserIds.Contains(u.Id))
  227. .Select(u => new { u.Id, u.RealName, u.Account })
  228. .ToListAsync())
  229. .ToDictionary(
  230. u => u.Id,
  231. u => !string.IsNullOrWhiteSpace(u.RealName) ? u.RealName : u.Account);
  232. foreach (var row in list)
  233. {
  234. if (row is AdoS8ExceptionDetailDto detail)
  235. {
  236. detail.ResponsibleDeptName = deptMap.GetValueOrDefault(detail.ResponsibleDeptId);
  237. detail.OccurrenceDeptName = deptMap.GetValueOrDefault(detail.OccurrenceDeptId);
  238. detail.AssigneeName = detail.AssigneeId.HasValue ? empMap.GetValueOrDefault(detail.AssigneeId.Value) : null;
  239. detail.ReporterName = detail.ReporterId.HasValue
  240. ? (reporterUserMap.GetValueOrDefault(detail.ReporterId.Value) ?? empMap.GetValueOrDefault(detail.ReporterId.Value))
  241. : null;
  242. detail.VerifierName = detail.VerifierId.HasValue ? empMap.GetValueOrDefault(detail.VerifierId.Value) : null;
  243. }
  244. else
  245. {
  246. row.ResponsibleDeptName = deptMap.GetValueOrDefault(row.ResponsibleDeptId);
  247. row.AssigneeName = row.AssigneeId.HasValue ? empMap.GetValueOrDefault(row.AssigneeId.Value) : null;
  248. }
  249. }
  250. }
  251. /// <summary>
  252. /// S2-EW:debug-only 软删 RelatedObjectCode 以 "TEST_G09_" 开头的异常。
  253. /// 调用方仅限 <see cref="Controllers.S8.AdoS8WatchDebugController"/>,由其 _debugEndpointEnabled 守门。
  254. /// 实现纪律:
  255. /// - 仅 SET IsDeleted=true,不动业务字段(status/closed_at/source_rule_id 等)。
  256. /// - 前缀字面量硬编码,不接受外部 prefix;防止前缀注入。
  257. /// - 不联动 timeline / decision / evidence;业务读路径以父 IsDeleted 屏蔽。
  258. /// </summary>
  259. public async Task<int> SoftDeleteTestPrefixAsync(long tenantId, long factoryId)
  260. {
  261. const string prefix = "TEST_G09_";
  262. var affected = await _rep.AsUpdateable()
  263. .SetColumns(e => new AdoS8Exception { IsDeleted = true })
  264. .Where(e => e.TenantId == tenantId
  265. && e.FactoryId == factoryId
  266. && !e.IsDeleted
  267. && e.RelatedObjectCode != null
  268. && e.RelatedObjectCode.StartsWith(prefix))
  269. .ExecuteCommandAsync();
  270. System.Diagnostics.Trace.TraceWarning(
  271. $"[S2-EW] soft-deleted {affected} TEST_G09_ exceptions, tenant={tenantId} factory={factoryId}");
  272. return affected;
  273. }
  274. }