S8DashboardService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. using Admin.NET.Plugin.AiDOP.Entity.S0.Manufacturing;
  2. using Admin.NET.Plugin.AiDOP.Entity.S0.Warehouse;
  3. using Admin.NET.Plugin.AiDOP.Entity.S8;
  4. using Admin.NET.Plugin.AiDOP.Infrastructure.S8;
  5. namespace Admin.NET.Plugin.AiDOP.Service.S8;
  6. public class S8DashboardService : ITransient
  7. {
  8. // S8-DASHBOARD-BYOBJECT-NULL-BUCKET-1:byObject / dim-trends(object) 维度统一 NULL 归桶口径。
  9. // related_object_code 为 NULL/空白 → 归入"未关联",避免主图空数据误导。
  10. private const string UnlinkedObjectLabel = "未关联";
  11. private static string NormalizeRelatedObjectCode(string? relatedObjectCode) =>
  12. string.IsNullOrWhiteSpace(relatedObjectCode)
  13. ? UnlinkedObjectLabel
  14. : relatedObjectCode!.Trim();
  15. private readonly SqlSugarRepository<AdoS8Exception> _rep;
  16. private readonly SqlSugarRepository<AdoS0DepartmentMaster> _deptRep;
  17. private readonly SqlSugarRepository<AdoS8ProcessNode> _processNodeRep;
  18. public S8DashboardService(
  19. SqlSugarRepository<AdoS8Exception> rep,
  20. SqlSugarRepository<AdoS0DepartmentMaster> deptRep,
  21. SqlSugarRepository<AdoS8ProcessNode> processNodeRep)
  22. {
  23. _rep = rep;
  24. _deptRep = deptRep;
  25. _processNodeRep = processNodeRep;
  26. }
  27. public async Task<object> GetOverviewAsync(long tenantId, long factoryId, DateTime? beginTime = null, DateTime? endTime = null, string? severity = null)
  28. {
  29. // 看板顶部的"开始/结束日期"通过 beginTime/endTime 透传,与列表的 beginTime/endTime 同语义。
  30. // BUG-12:补 severity 过滤,与异常列表 API 的 severity 口径一致(精确匹配 LOW/MEDIUM/HIGH/CRITICAL)。
  31. // BUG-22:REJECTED 状态归入 pending 桶,避免从总数视角"消失";与列表 statusBucket="pending" 同步对齐。
  32. // S8-DASHBOARD-DATA-ALIGN-S1S7-1:统一只统计 module_code IN S1-S7;NULL module 的 legacy 行不参与看板 KPI。
  33. var q = _rep.AsQueryable()
  34. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && !x.IsDeleted)
  35. .Where(x => S8ModuleCode.All.Contains(x.ModuleCode))
  36. .WhereIF(beginTime.HasValue, x => x.CreatedAt >= beginTime!.Value)
  37. .WhereIF(endTime.HasValue, x => x.CreatedAt <= endTime!.Value)
  38. .WhereIF(!string.IsNullOrWhiteSpace(severity), x => x.Severity == severity);
  39. var total = await q.CountAsync();
  40. var pending = await q.CountAsync(x => x.Status == "NEW" || x.Status == "ASSIGNED" || x.Status == "IN_PROGRESS" || x.Status == "PENDING_VERIFICATION" || x.Status == "REJECTED");
  41. var inProgress = await q.CountAsync(x => x.Status == "IN_PROGRESS");
  42. // S8-SLA-TIMEOUT-RUNTIME-1(P3):当前超时改为运行时计算 = sla_deadline IS NOT NULL AND sla_deadline < now AND status NOT IN ('CLOSED','RECOVERED')。
  43. // timeout_flag 已降级 legacy;本批不清理历史 timeout_flag。
  44. var nowForTimeout = DateTime.Now;
  45. var timeout = await q.CountAsync(x => x.SlaDeadline != null && x.SlaDeadline < nowForTimeout && x.Status != "CLOSED" && x.Status != "RECOVERED");
  46. var closed = await q.CountAsync(x => x.Status == "CLOSED");
  47. var todayNew = await q.CountAsync(x => x.CreatedAt >= DateTime.Today);
  48. // S8-SEVERITY-FOLLOW-SERIOUS-STANDARDIZE-EXEC-1:critical 字段名保留以维持外部 KPI;语义切为「严重」(SERIOUS)。
  49. var seriousList = await q.Select(x => x.Severity).ToListAsync();
  50. var critical = seriousList.Count(s => S8SeverityCode.IsSerious(s));
  51. var closureRate = total > 0 ? Math.Round(closed * 100.0 / total, 1) : 0.0;
  52. // 平均处理周期(小时),仅对已闭环且有关闭时间的记录计算
  53. var closedRows = await q
  54. .Where(x => x.Status == "CLOSED" && x.ClosedAt != null)
  55. .Select(x => new { x.CreatedAt, x.ClosedAt })
  56. .ToListAsync();
  57. var avgCycleHours = closedRows.Count > 0
  58. ? Math.Round(closedRows.Average(x => (x.ClosedAt!.Value - x.CreatedAt).TotalHours), 1)
  59. : 0.0;
  60. return new { total, pending, inProgress, timeout, closed, todayNew, critical, closureRate, avgCycleHours };
  61. }
  62. public async Task<object> GetTrendsAsync(long tenantId, long factoryId, int days)
  63. {
  64. var from = DateTime.Today.AddDays(-Math.Clamp(days, 1, 90));
  65. var rows = await _rep.AsQueryable()
  66. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && !x.IsDeleted && x.CreatedAt >= from)
  67. .Where(x => S8ModuleCode.All.Contains(x.ModuleCode))
  68. .Select(x => new { x.CreatedAt })
  69. .ToListAsync();
  70. return rows
  71. .GroupBy(x => x.CreatedAt.Date)
  72. .OrderBy(g => g.Key)
  73. .Select(g => new { date = g.Key.ToString("yyyy-MM-dd"), count = g.Count() })
  74. .ToList();
  75. }
  76. public async Task<object> GetDistributionsAsync(long tenantId, long factoryId)
  77. {
  78. var list = await _rep.AsQueryable()
  79. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && !x.IsDeleted)
  80. .Where(x => S8ModuleCode.All.Contains(x.ModuleCode))
  81. .Select(x => new
  82. {
  83. x.Status,
  84. x.SceneCode,
  85. x.Severity,
  86. x.ResponsibleDeptId,
  87. x.OccurrenceDeptId,
  88. // S8-PROCESS-NODE-MODULE-CODE-ALIGNMENT-EXEC-1:byProcess 改用 module_code 聚合。
  89. x.ModuleCode,
  90. x.RelatedObjectCode,
  91. })
  92. .ToListAsync();
  93. // 部门名称字典
  94. var allDeptIds = list.Select(x => x.ResponsibleDeptId)
  95. .Concat(list.Select(x => x.OccurrenceDeptId))
  96. .Distinct().ToList();
  97. // S8-DEPT-DISPLAY-CONSISTENCY-1(P0-A-3):部门水合加 factory_ref_id 约束,避免跨 factory 同 RecID 错位。
  98. var deptMap = await _deptRep.AsQueryable()
  99. .Where(d => allDeptIds.Contains(d.Id) && d.FactoryRefId == factoryId)
  100. .Select(d => new { d.Id, Name = d.Descr ?? d.Department })
  101. .ToListAsync();
  102. var deptDict = deptMap.ToDictionary(d => d.Id, d => d.Name ?? d.Id.ToString());
  103. // 流程节点名称字典
  104. var processNodes = await _processNodeRep.AsQueryable()
  105. .OrderBy(p => p.SortNo)
  106. .Select(p => new { p.Code, p.Name })
  107. .ToListAsync();
  108. var processDict = processNodes.ToDictionary(p => p.Code, p => p.Name);
  109. return new
  110. {
  111. byStatus = list
  112. .GroupBy(x => x.Status)
  113. .Select(g => new { key = g.Key, count = g.Count() }),
  114. // S8-DASHBOARD-BYSCENE-RESERVE-CLEAR-1:byScene 不再生成。
  115. // 业务展示主口径已切到 module_code(byProcess),保留 scene_code 仅用于建单/规则唯一性/配置 CRUD/历史追溯。
  116. // 字段保留以维持响应结构兼容;前端无消费方。
  117. byScene = Array.Empty<object>(),
  118. // S8-SEVERITY-FOLLOW-SERIOUS-STANDARDIZE-EXEC-1:bySeverity 归一为 FOLLOW/SERIOUS 两桶。
  119. bySeverity = list
  120. .GroupBy(x => S8SeverityCode.Normalize(x.Severity))
  121. .Select(g => new { key = g.Key, count = g.Count() }),
  122. byDept = list
  123. .GroupBy(x => x.ResponsibleDeptId)
  124. .Select(g => new
  125. {
  126. key = g.Key,
  127. deptName = deptDict.GetValueOrDefault(g.Key, g.Key.ToString()),
  128. count = g.Count(),
  129. }),
  130. byOccurrenceDept = list
  131. .GroupBy(x => x.OccurrenceDeptId)
  132. .Select(g => new
  133. {
  134. key = g.Key,
  135. deptName = deptDict.GetValueOrDefault(g.Key, g.Key.ToString()),
  136. count = g.Count(),
  137. }),
  138. // S8-PROCESS-NODE-MODULE-CODE-ALIGNMENT-EXEC-1:当前阶段「流程环节」按 module_code 聚合
  139. // (process_node_code 已挂起,留给未来更细流程节点)。
  140. // module_code 已经过 S1-S7 过滤(见 line 87 Where(S8ModuleCode.All.Contains(...))),无需再 NULL 兜底。
  141. // S8-SEVERITY-FOLLOW-SERIOUS-STANDARDIZE-EXEC-1:byProcess 增加 followCount/seriousCount 两段,
  142. // 供前端「流程环节」黄红堆叠柱使用;count = follow + serious。排序按 S1-S7 自然字典序固定。
  143. byProcess = list
  144. .GroupBy(x => x.ModuleCode)
  145. .Select(g => new
  146. {
  147. key = g.Key,
  148. nodeName = processDict.GetValueOrDefault(g.Key, g.Key),
  149. count = g.Count(),
  150. followCount = g.Count(x => S8SeverityCode.IsFollow(x.Severity)),
  151. seriousCount = g.Count(x => S8SeverityCode.IsSerious(x.Severity)),
  152. })
  153. .OrderBy(r => r.key),
  154. byObject = list
  155. // S8-DASHBOARD-BYOBJECT-NULL-BUCKET-1:不再过滤 NULL,与 dim-trends 口径统一;
  156. // related_object_code 为空时归入"未关联"桶。
  157. .GroupBy(x => NormalizeRelatedObjectCode(x.RelatedObjectCode))
  158. .OrderByDescending(g => g.Count())
  159. .Take(20)
  160. .Select(g => new { key = g.Key, count = g.Count() }),
  161. };
  162. }
  163. public async Task<object> GetDeptBacklogAsync(long tenantId, long factoryId)
  164. {
  165. var pendingStatuses = new[] { "NEW", "ASSIGNED", "IN_PROGRESS" };
  166. // S8-SLA-TIMEOUT-RUNTIME-1(P3):投影 SlaDeadline 替代 TimeoutFlag;timeout 由内存计算(与 GetSummaryAsync 一致 now)。
  167. var list = await _rep.AsQueryable()
  168. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && !x.IsDeleted)
  169. .Where(x => S8ModuleCode.All.Contains(x.ModuleCode))
  170. .Select(x => new { x.ResponsibleDeptId, x.Status, x.SlaDeadline })
  171. .ToListAsync();
  172. var nowForTimeout = DateTime.Now;
  173. var deptIds = list.Select(x => x.ResponsibleDeptId).Distinct().ToList();
  174. // S8-DEPT-DISPLAY-CONSISTENCY-1(P0-A-3):部门水合加 factory_ref_id 约束。
  175. var deptMap = await _deptRep.AsQueryable()
  176. .Where(d => deptIds.Contains(d.Id) && d.FactoryRefId == factoryId)
  177. .Select(d => new { d.Id, Name = d.Descr ?? d.Department })
  178. .ToListAsync();
  179. var deptDict = deptMap.ToDictionary(d => d.Id, d => d.Name ?? d.Id.ToString());
  180. return list
  181. .GroupBy(x => x.ResponsibleDeptId)
  182. .Select(g => new
  183. {
  184. deptId = g.Key,
  185. deptName = deptDict.GetValueOrDefault(g.Key, g.Key.ToString()),
  186. pending = g.Count(x => pendingStatuses.Contains(x.Status)),
  187. inProgress = g.Count(x => x.Status == "IN_PROGRESS"),
  188. // S8-SLA-TIMEOUT-RUNTIME-1:当前超时 = sla_deadline 在 now 之前 AND 未 CLOSED/RECOVERED。
  189. timeout = g.Count(x => x.SlaDeadline != null && x.SlaDeadline < nowForTimeout && x.Status != "CLOSED" && x.Status != "RECOVERED"),
  190. total = g.Count(),
  191. })
  192. .OrderByDescending(x => x.pending)
  193. .ToList();
  194. }
  195. /// <summary>
  196. /// 按维度返回多系列日趋势数据。dim: object | process | occDept | respDept
  197. /// 返回: { dates, series: [{ name, data[] }] }
  198. /// </summary>
  199. public async Task<object> GetDimTrendsAsync(long tenantId, long factoryId, string dim, int days)
  200. {
  201. var from = DateTime.Today.AddDays(-Math.Clamp(days, 1, 90));
  202. var rows = await _rep.AsQueryable()
  203. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && !x.IsDeleted && x.CreatedAt >= from)
  204. .Where(x => S8ModuleCode.All.Contains(x.ModuleCode))
  205. .Select(x => new
  206. {
  207. x.CreatedAt,
  208. // S8-PROCESS-NODE-MODULE-CODE-ALIGNMENT-EXEC-1:dim=process 改用 module_code 聚合。
  209. x.ModuleCode,
  210. x.RelatedObjectCode,
  211. x.OccurrenceDeptId,
  212. x.ResponsibleDeptId,
  213. })
  214. .ToListAsync();
  215. // 生成连续日期序列
  216. var dates = Enumerable.Range(0, (DateTime.Today - from).Days + 1)
  217. .Select(i => from.AddDays(i).Date)
  218. .ToList();
  219. var dateLabels = dates.Select(d => d.ToString("yyyy-MM-dd")).ToList();
  220. // 按维度取 key 函数
  221. // S8-DASHBOARD-BYOBJECT-NULL-BUCKET-1:object 维度 NULL/空白统一归入"未关联",与 byObject 口径一致;
  222. // process 维度沿用历史"未设置"作为兜底(理论不会命中:上方 Where 已限定 module_code IN S1-S7)。
  223. // S8-PROCESS-NODE-MODULE-CODE-ALIGNMENT-EXEC-1:process 改用 module_code(process_node_code 挂起)。
  224. Func<dynamic, string> keySelector = dim switch
  225. {
  226. "process" => r => r.ModuleCode ?? "未设置",
  227. "occDept" => r => r.OccurrenceDeptId.ToString(),
  228. "respDept" => r => r.ResponsibleDeptId.ToString(),
  229. _ => r => NormalizeRelatedObjectCode((string?)r.RelatedObjectCode), // object
  230. };
  231. var grouped = rows
  232. .GroupBy(r => keySelector(r))
  233. .OrderByDescending(g => g.Count())
  234. .Take(8) // 最多取 8 个系列,避免图例过多
  235. .ToList();
  236. // 补全部门名 / 流程节点名
  237. Dictionary<string, string> nameMap = new();
  238. if (dim == "process")
  239. {
  240. var nodes = await _processNodeRep.AsQueryable().ToListAsync();
  241. nameMap = nodes.ToDictionary(n => n.Code, n => n.Name);
  242. }
  243. else if (dim is "occDept" or "respDept")
  244. {
  245. var ids = grouped.Select(g => long.TryParse(g.Key, out var id) ? id : 0).ToList();
  246. // S8-DEPT-DISPLAY-CONSISTENCY-1-FOLLOWUP-1(P0-A-3 收尾):部门水合加 factory_ref_id 约束,
  247. // 与 GetDistributionsAsync / GetDeptBacklogAsync 同口径,避免跨 factory 同名/同 RecID 错位。
  248. var depts = await _deptRep.AsQueryable()
  249. .Where(d => ids.Contains(d.Id) && d.FactoryRefId == factoryId)
  250. .Select(d => new { d.Id, Name = d.Descr ?? d.Department })
  251. .ToListAsync();
  252. nameMap = depts.ToDictionary(d => d.Id.ToString(), d => d.Name ?? d.Id.ToString());
  253. }
  254. var series = grouped.Select(g =>
  255. {
  256. var seriesName = nameMap.TryGetValue(g.Key, out var n) ? n : g.Key;
  257. var byDate = g.GroupBy(r => r.CreatedAt.Date).ToDictionary(x => x.Key, x => x.Count());
  258. var data = dates.Select(d => byDate.TryGetValue(d, out var c) ? c : 0).ToList();
  259. return new { name = seriesName, data };
  260. }).ToList();
  261. return new { dates = dateLabels, series };
  262. }
  263. public async Task<List<AdoS8Exception>> GetQuickExceptionsAsync(long tenantId, long factoryId, string mode)
  264. {
  265. var q = _rep.AsQueryable()
  266. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && !x.IsDeleted)
  267. .Where(x => S8ModuleCode.All.Contains(x.ModuleCode));
  268. // S8-SLA-TIMEOUT-RUNTIME-1(P3):timeout 模式按 sla_deadline 在线计算筛 + 升序。
  269. var nowForTimeout = DateTime.Now;
  270. var ordered = mode switch
  271. {
  272. "high-priority" => q.OrderBy(x => x.PriorityScore, OrderByType.Desc),
  273. "timeout" => q.Where(x => x.SlaDeadline != null && x.SlaDeadline < nowForTimeout && x.Status != "CLOSED" && x.Status != "RECOVERED").OrderBy(x => x.SlaDeadline),
  274. _ => q.OrderBy(x => x.CreatedAt, OrderByType.Desc),
  275. };
  276. return await ordered.Take(20).ToListAsync();
  277. }
  278. }