S8ExceptionService.cs 14 KB

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