S8ExceptionService.cs 15 KB

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