S8ExceptionService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. ModuleCode = e.ModuleCode,
  76. ResponsibleDeptId = e.ResponsibleDeptId,
  77. OccurrenceDeptId = e.OccurrenceDeptId,
  78. AssigneeId = e.AssigneeId,
  79. SlaDeadline = e.SlaDeadline,
  80. TimeoutFlag = e.TimeoutFlag,
  81. CreatedAt = e.CreatedAt,
  82. ClosedAt = e.ClosedAt,
  83. ExceptionTypeCode = e.ExceptionTypeCode,
  84. RecoveredAt = e.RecoveredAt,
  85. SourceRuleCode = e.SourceRuleCode,
  86. SourceObjectType = e.SourceObjectType,
  87. SourceObjectId = e.SourceObjectId,
  88. DedupKey = e.DedupKey,
  89. LastDetectedAt = e.LastDetectedAt,
  90. RuleType = wr.RuleType
  91. })
  92. .ToPageListAsync(q.Page, q.PageSize);
  93. foreach (var r in list)
  94. {
  95. r.StatusLabel = S8Labels.StatusLabel(r.Status);
  96. r.SeverityLabel = S8Labels.SeverityLabel(r.Severity);
  97. r.ModuleName = string.IsNullOrWhiteSpace(r.ModuleCode) ? null : S8ModuleCode.Label(r.ModuleCode!);
  98. }
  99. await FillDisplayNamesAsync(list, q.FactoryId);
  100. return (total, list);
  101. }
  102. public async Task<object> GetFilterOptionsAsync(long tenantId, long factoryId)
  103. {
  104. var scenes = await _rep.Context.Queryable<AdoS8SceneConfig>()
  105. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && x.Enabled)
  106. .OrderBy(x => x.SortNo)
  107. .Select(x => new { value = x.SceneCode, label = x.SceneName })
  108. .ToListAsync();
  109. var departments = await _deptRep.AsQueryable()
  110. .Where(x => x.FactoryRefId == factoryId)
  111. .OrderBy(x => x.Department)
  112. .Take(500)
  113. .Select(x => new { value = x.Id, label = x.Descr ?? x.Department })
  114. .ToListAsync();
  115. // S8-EXCEPTION-MODULE-DISPLAY-1:业务展示主口径切到 module_code(S1-S7)。
  116. // scenes 保留兼容期,前端筛选已切到 modules。
  117. var modules = S8ModuleCode.All
  118. .Select(code => new { value = code, label = S8ModuleCode.Label(code) })
  119. .ToList();
  120. return new
  121. {
  122. statuses = S8Labels.StatusOptions(),
  123. severities = S8Labels.SeverityOptions(),
  124. scenes,
  125. modules,
  126. departments
  127. };
  128. }
  129. public async Task<AdoS8ExceptionDetailDto?> GetDetailAsync(long id, long tenantId, long factoryId)
  130. {
  131. var rows = await _rep.Context.Queryable<AdoS8Exception>()
  132. .LeftJoin<AdoS8SceneConfig>((e, sc) =>
  133. e.TenantId == sc.TenantId && e.FactoryId == sc.FactoryId && e.SceneCode == sc.SceneCode)
  134. .LeftJoin<AdoS8WatchRule>((e, sc, wr) =>
  135. e.TenantId == wr.TenantId && e.FactoryId == wr.FactoryId && e.SourceRuleCode == wr.RuleCode)
  136. .Where((e, sc, wr) => e.Id == id && e.TenantId == tenantId && e.FactoryId == factoryId && !e.IsDeleted)
  137. .Select((e, sc, wr) => new AdoS8ExceptionDetailDto
  138. {
  139. Id = e.Id,
  140. FactoryId = e.FactoryId,
  141. ExceptionCode = e.ExceptionCode,
  142. Title = e.Title,
  143. Description = e.Description,
  144. Status = e.Status,
  145. Severity = e.Severity,
  146. PriorityScore = e.PriorityScore,
  147. PriorityLevel = e.PriorityLevel,
  148. SceneCode = e.SceneCode,
  149. SceneName = sc.SceneName,
  150. ModuleCode = e.ModuleCode,
  151. SourceType = e.SourceType,
  152. OccurrenceDeptId = e.OccurrenceDeptId,
  153. ResponsibleDeptId = e.ResponsibleDeptId,
  154. ResponsibleGroupId = e.ResponsibleGroupId,
  155. AssigneeId = e.AssigneeId,
  156. ReporterId = e.ReporterId,
  157. SlaDeadline = e.SlaDeadline,
  158. TimeoutFlag = e.TimeoutFlag,
  159. CreatedAt = e.CreatedAt,
  160. ClosedAt = e.ClosedAt,
  161. AssignedAt = e.AssignedAt,
  162. UpdatedAt = e.UpdatedAt,
  163. ActiveFlowInstanceId = e.ActiveFlowInstanceId,
  164. ActiveFlowBizType = e.ActiveFlowBizType,
  165. VerifierId = e.VerifierId,
  166. VerificationAssignedAt = e.VerificationAssignedAt,
  167. VerifiedAt = e.VerifiedAt,
  168. VerificationResult = e.VerificationResult,
  169. VerificationRemark = e.VerificationRemark,
  170. SourceRuleId = e.SourceRuleId,
  171. RelatedObjectCode = e.RelatedObjectCode,
  172. DedupKey = e.DedupKey,
  173. LastDetectedAt = e.LastDetectedAt,
  174. RecoveredAt = e.RecoveredAt,
  175. SourceRuleCode = e.SourceRuleCode,
  176. SourceObjectType = e.SourceObjectType,
  177. SourceObjectId = e.SourceObjectId,
  178. ExceptionTypeCode = e.ExceptionTypeCode,
  179. RuleType = wr.RuleType,
  180. })
  181. .Take(1)
  182. .ToListAsync();
  183. if (rows.Count == 0) return null;
  184. var d = rows[0];
  185. d.StatusLabel = S8Labels.StatusLabel(d.Status);
  186. d.SeverityLabel = S8Labels.SeverityLabel(d.Severity);
  187. d.ModuleName = string.IsNullOrWhiteSpace(d.ModuleCode) ? null : S8ModuleCode.Label(d.ModuleCode!);
  188. await FillDisplayNamesAsync(new[] { d }, factoryId);
  189. return d;
  190. }
  191. // S8-DEPT-DISPLAY-CONSISTENCY-1(P0-A-2/A-3):list 行也水合 OccurrenceDeptName;
  192. // 部门查询加 factory_ref_id 二次约束,避免跨 factory 同名 / 同 RecID 错位。
  193. private async Task FillDisplayNamesAsync(IEnumerable<AdoS8ExceptionListItemDto> rows, long factoryId)
  194. {
  195. var list = rows.ToList();
  196. if (list.Count == 0) return;
  197. var deptIds = list
  198. .Select(x => x.ResponsibleDeptId)
  199. .Concat(list.Select(x => x.OccurrenceDeptId))
  200. .Where(x => x > 0)
  201. .Distinct()
  202. .ToList();
  203. var empIds = list
  204. .Select(x => x.AssigneeId ?? 0L)
  205. .Concat(list.OfType<AdoS8ExceptionDetailDto>().Select(x => x.ReporterId ?? 0L))
  206. .Concat(list.OfType<AdoS8ExceptionDetailDto>().Select(x => x.VerifierId ?? 0L))
  207. .Where(x => x > 0)
  208. .Distinct()
  209. .ToList();
  210. var deptMap = deptIds.Count == 0
  211. ? new Dictionary<long, string>()
  212. : (await _deptRep.AsQueryable()
  213. .Where(x => deptIds.Contains(x.Id) && x.FactoryRefId == factoryId)
  214. .Select(x => new { x.Id, Name = x.Descr ?? x.Department })
  215. .ToListAsync())
  216. .ToDictionary(x => x.Id, x => x.Name);
  217. // EmployeeMaster.tenant_id 与 SysUser.TenantId 历史错位(797403760988229 ≠ 系统租户),
  218. // 走全局 multi-tenant filter 会全过滤为空 → 详情页处理人/检验人姓名显示数字 ID。
  219. // 与 S8MasterDataAdapter.GetEmployeesAsync / S8TaskFlowService.GetEmployeeSysUserIdAsync 同口径,
  220. // 局部 ClearFilter + employee.Id 主键集合作为安全边界,无跨租户泄漏。
  221. var empMap = empIds.Count == 0
  222. ? new Dictionary<long, string>()
  223. : (await _empRep.AsQueryable().ClearFilter()
  224. .Where(x => empIds.Contains(x.Id))
  225. .Select(x => new { x.Id, Name = x.Name ?? x.Employee })
  226. .ToListAsync())
  227. .ToDictionary(x => x.Id, x => x.Name);
  228. // S8-REPORTER-IDSPACE-FIX-1(P0-B-1):ReporterId 新协议 = EmployeeMaster.RecID(与 assignee/verifier 同 idspace)。
  229. // 水合优先级:EmployeeMaster.Name → fallback SysUser.RealName/Account(兼容旧数据 reporter=SysUser.Id)。
  230. // 旧注释 “ReporterId 现在记录 sysUser.Id” 已失效,由本批协议替代。
  231. var reporterUserIds = list.OfType<AdoS8ExceptionDetailDto>()
  232. .Select(x => x.ReporterId ?? 0L)
  233. .Where(x => x > 0)
  234. .Distinct()
  235. .ToList();
  236. var reporterUserMap = reporterUserIds.Count == 0
  237. ? new Dictionary<long, string>()
  238. : (await _sysUserRep.AsQueryable().ClearFilter()
  239. .Where(u => reporterUserIds.Contains(u.Id))
  240. .Select(u => new { u.Id, u.RealName, u.Account })
  241. .ToListAsync())
  242. .ToDictionary(
  243. u => u.Id,
  244. u => !string.IsNullOrWhiteSpace(u.RealName) ? u.RealName : u.Account);
  245. foreach (var row in list)
  246. {
  247. row.ResponsibleDeptName = ResolveDeptName(row.ResponsibleDeptId, deptMap);
  248. row.OccurrenceDeptName = ResolveDeptName(row.OccurrenceDeptId, deptMap);
  249. row.AssigneeName = row.AssigneeId.HasValue ? empMap.GetValueOrDefault(row.AssigneeId.Value) : null;
  250. if (row is AdoS8ExceptionDetailDto detail)
  251. {
  252. // S8-REPORTER-IDSPACE-FIX-1:empMap(EmployeeMaster.RecID)优先,reporterUserMap(SysUser.Id)兜底兼容旧数据。
  253. detail.ReporterName = detail.ReporterId.HasValue
  254. ? (empMap.GetValueOrDefault(detail.ReporterId.Value) ?? reporterUserMap.GetValueOrDefault(detail.ReporterId.Value))
  255. : null;
  256. detail.VerifierName = detail.VerifierId.HasValue ? empMap.GetValueOrDefault(detail.VerifierId.Value) : null;
  257. }
  258. }
  259. }
  260. // S8-DEPT-DISPLAY-CONSISTENCY-1(P0-A-3):dept fallback —— 0/缺失=未归属,查不到名=部门ID:{id}。
  261. private static string? ResolveDeptName(long deptId, Dictionary<long, string> deptMap)
  262. {
  263. if (deptId <= 0) return "未归属";
  264. return deptMap.TryGetValue(deptId, out var name) && !string.IsNullOrWhiteSpace(name)
  265. ? name
  266. : $"部门ID:{deptId}";
  267. }
  268. /// <summary>
  269. /// S2-EW:debug-only 软删 RelatedObjectCode 以 "TEST_G09_" 开头的异常。
  270. /// 调用方仅限 <see cref="Controllers.S8.AdoS8WatchDebugController"/>,由其 _debugEndpointEnabled 守门。
  271. /// 实现纪律:
  272. /// - 仅 SET IsDeleted=true,不动业务字段(status/closed_at/source_rule_id 等)。
  273. /// - 前缀字面量硬编码,不接受外部 prefix;防止前缀注入。
  274. /// - 不联动 timeline / decision / evidence;业务读路径以父 IsDeleted 屏蔽。
  275. /// </summary>
  276. public async Task<int> SoftDeleteTestPrefixAsync(long tenantId, long factoryId)
  277. {
  278. const string prefix = "TEST_G09_";
  279. var affected = await _rep.AsUpdateable()
  280. .SetColumns(e => new AdoS8Exception { IsDeleted = true })
  281. .Where(e => e.TenantId == tenantId
  282. && e.FactoryId == factoryId
  283. && !e.IsDeleted
  284. && e.RelatedObjectCode != null
  285. && e.RelatedObjectCode.StartsWith(prefix))
  286. .ExecuteCommandAsync();
  287. System.Diagnostics.Trace.TraceWarning(
  288. $"[S2-EW] soft-deleted {affected} TEST_G09_ exceptions, tenant={tenantId} factory={factoryId}");
  289. return affected;
  290. }
  291. }