S8ExceptionService.cs 14 KB

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