S8DashboardService.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. namespace Admin.NET.Plugin.AiDOP.Service.S8;
  5. public class S8DashboardService : ITransient
  6. {
  7. private readonly SqlSugarRepository<AdoS8Exception> _rep;
  8. private readonly SqlSugarRepository<AdoS0DepartmentMaster> _deptRep;
  9. private readonly SqlSugarRepository<AdoS8ProcessNode> _processNodeRep;
  10. public S8DashboardService(
  11. SqlSugarRepository<AdoS8Exception> rep,
  12. SqlSugarRepository<AdoS0DepartmentMaster> deptRep,
  13. SqlSugarRepository<AdoS8ProcessNode> processNodeRep)
  14. {
  15. _rep = rep;
  16. _deptRep = deptRep;
  17. _processNodeRep = processNodeRep;
  18. }
  19. public async Task<object> GetOverviewAsync(long tenantId, long factoryId)
  20. {
  21. var q = _rep.AsQueryable().Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && !x.IsDeleted);
  22. var total = await q.CountAsync();
  23. var pending = await q.CountAsync(x => x.Status == "NEW" || x.Status == "ASSIGNED" || x.Status == "IN_PROGRESS");
  24. var inProgress = await q.CountAsync(x => x.Status == "IN_PROGRESS");
  25. var timeout = await q.CountAsync(x => x.TimeoutFlag);
  26. var closed = await q.CountAsync(x => x.Status == "CLOSED");
  27. var todayNew = await q.CountAsync(x => x.CreatedAt >= DateTime.Today);
  28. var critical = await q.CountAsync(x => x.Severity == "CRITICAL");
  29. var closureRate = total > 0 ? Math.Round(closed * 100.0 / total, 1) : 0.0;
  30. // 平均处理周期(小时),仅对已闭环且有关闭时间的记录计算
  31. var closedRows = await q
  32. .Where(x => x.Status == "CLOSED" && x.ClosedAt != null)
  33. .Select(x => new { x.CreatedAt, x.ClosedAt })
  34. .ToListAsync();
  35. var avgCycleHours = closedRows.Count > 0
  36. ? Math.Round(closedRows.Average(x => (x.ClosedAt!.Value - x.CreatedAt).TotalHours), 1)
  37. : 0.0;
  38. return new { total, pending, inProgress, timeout, closed, todayNew, critical, closureRate, avgCycleHours };
  39. }
  40. public async Task<object> GetTrendsAsync(long tenantId, long factoryId, int days)
  41. {
  42. var from = DateTime.Today.AddDays(-Math.Clamp(days, 1, 90));
  43. var rows = await _rep.AsQueryable()
  44. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && !x.IsDeleted && x.CreatedAt >= from)
  45. .Select(x => new { x.CreatedAt })
  46. .ToListAsync();
  47. return rows
  48. .GroupBy(x => x.CreatedAt.Date)
  49. .OrderBy(g => g.Key)
  50. .Select(g => new { date = g.Key.ToString("yyyy-MM-dd"), count = g.Count() })
  51. .ToList();
  52. }
  53. public async Task<object> GetDistributionsAsync(long tenantId, long factoryId)
  54. {
  55. var list = await _rep.AsQueryable()
  56. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && !x.IsDeleted)
  57. .Select(x => new
  58. {
  59. x.Status,
  60. x.SceneCode,
  61. x.Severity,
  62. x.ResponsibleDeptId,
  63. x.OccurrenceDeptId,
  64. x.ProcessNodeCode,
  65. x.RelatedObjectCode,
  66. })
  67. .ToListAsync();
  68. // 部门名称字典
  69. var allDeptIds = list.Select(x => x.ResponsibleDeptId)
  70. .Concat(list.Select(x => x.OccurrenceDeptId))
  71. .Distinct().ToList();
  72. var deptMap = await _deptRep.AsQueryable()
  73. .Where(d => allDeptIds.Contains(d.Id))
  74. .Select(d => new { d.Id, Name = d.Descr ?? d.Department })
  75. .ToListAsync();
  76. var deptDict = deptMap.ToDictionary(d => d.Id, d => d.Name ?? d.Id.ToString());
  77. // 流程节点名称字典
  78. var processNodes = await _processNodeRep.AsQueryable()
  79. .OrderBy(p => p.SortNo)
  80. .Select(p => new { p.Code, p.Name })
  81. .ToListAsync();
  82. var processDict = processNodes.ToDictionary(p => p.Code, p => p.Name);
  83. return new
  84. {
  85. byStatus = list
  86. .GroupBy(x => x.Status)
  87. .Select(g => new { key = g.Key, count = g.Count() }),
  88. byScene = list
  89. .GroupBy(x => x.SceneCode)
  90. .Select(g => new { key = g.Key, count = g.Count() }),
  91. bySeverity = list
  92. .GroupBy(x => x.Severity)
  93. .Select(g => new { key = g.Key, count = g.Count() }),
  94. byDept = list
  95. .GroupBy(x => x.ResponsibleDeptId)
  96. .Select(g => new
  97. {
  98. key = g.Key,
  99. deptName = deptDict.GetValueOrDefault(g.Key, g.Key.ToString()),
  100. count = g.Count(),
  101. }),
  102. byOccurrenceDept = list
  103. .GroupBy(x => x.OccurrenceDeptId)
  104. .Select(g => new
  105. {
  106. key = g.Key,
  107. deptName = deptDict.GetValueOrDefault(g.Key, g.Key.ToString()),
  108. count = g.Count(),
  109. }),
  110. byProcess = list
  111. .Where(x => x.ProcessNodeCode != null)
  112. .GroupBy(x => x.ProcessNodeCode!)
  113. .Select(g => new
  114. {
  115. key = g.Key,
  116. nodeName = processDict.GetValueOrDefault(g.Key, g.Key),
  117. count = g.Count(),
  118. }),
  119. byObject = list
  120. .Where(x => x.RelatedObjectCode != null)
  121. .GroupBy(x => x.RelatedObjectCode!)
  122. .OrderByDescending(g => g.Count())
  123. .Take(20)
  124. .Select(g => new { key = g.Key, count = g.Count() }),
  125. };
  126. }
  127. public async Task<object> GetDeptBacklogAsync(long tenantId, long factoryId)
  128. {
  129. var pendingStatuses = new[] { "NEW", "ASSIGNED", "IN_PROGRESS" };
  130. var list = await _rep.AsQueryable()
  131. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && !x.IsDeleted)
  132. .Select(x => new { x.ResponsibleDeptId, x.Status, x.TimeoutFlag })
  133. .ToListAsync();
  134. var deptIds = list.Select(x => x.ResponsibleDeptId).Distinct().ToList();
  135. var deptMap = await _deptRep.AsQueryable()
  136. .Where(d => deptIds.Contains(d.Id))
  137. .Select(d => new { d.Id, Name = d.Descr ?? d.Department })
  138. .ToListAsync();
  139. var deptDict = deptMap.ToDictionary(d => d.Id, d => d.Name ?? d.Id.ToString());
  140. return list
  141. .GroupBy(x => x.ResponsibleDeptId)
  142. .Select(g => new
  143. {
  144. deptId = g.Key,
  145. deptName = deptDict.GetValueOrDefault(g.Key, g.Key.ToString()),
  146. pending = g.Count(x => pendingStatuses.Contains(x.Status)),
  147. inProgress = g.Count(x => x.Status == "IN_PROGRESS"),
  148. timeout = g.Count(x => x.TimeoutFlag),
  149. total = g.Count(),
  150. })
  151. .OrderByDescending(x => x.pending)
  152. .ToList();
  153. }
  154. /// <summary>
  155. /// 按维度返回多系列日趋势数据。dim: object | process | occDept | respDept
  156. /// 返回: { dates, series: [{ name, data[] }] }
  157. /// </summary>
  158. public async Task<object> GetDimTrendsAsync(long tenantId, long factoryId, string dim, int days)
  159. {
  160. var from = DateTime.Today.AddDays(-Math.Clamp(days, 1, 90));
  161. var rows = await _rep.AsQueryable()
  162. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && !x.IsDeleted && x.CreatedAt >= from)
  163. .Select(x => new
  164. {
  165. x.CreatedAt,
  166. x.ProcessNodeCode,
  167. x.RelatedObjectCode,
  168. x.OccurrenceDeptId,
  169. x.ResponsibleDeptId,
  170. })
  171. .ToListAsync();
  172. // 生成连续日期序列
  173. var dates = Enumerable.Range(0, (DateTime.Today - from).Days + 1)
  174. .Select(i => from.AddDays(i).Date)
  175. .ToList();
  176. var dateLabels = dates.Select(d => d.ToString("yyyy-MM-dd")).ToList();
  177. // 按维度取 key 函数
  178. Func<dynamic, string> keySelector = dim switch
  179. {
  180. "process" => r => r.ProcessNodeCode ?? "未设置",
  181. "occDept" => r => r.OccurrenceDeptId.ToString(),
  182. "respDept" => r => r.ResponsibleDeptId.ToString(),
  183. _ => r => r.RelatedObjectCode ?? "未设置", // object
  184. };
  185. var grouped = rows
  186. .GroupBy(r => keySelector(r))
  187. .OrderByDescending(g => g.Count())
  188. .Take(8) // 最多取 8 个系列,避免图例过多
  189. .ToList();
  190. // 补全部门名 / 流程节点名
  191. Dictionary<string, string> nameMap = new();
  192. if (dim == "process")
  193. {
  194. var nodes = await _processNodeRep.AsQueryable().ToListAsync();
  195. nameMap = nodes.ToDictionary(n => n.Code, n => n.Name);
  196. }
  197. else if (dim is "occDept" or "respDept")
  198. {
  199. var ids = grouped.Select(g => long.TryParse(g.Key, out var id) ? id : 0).ToList();
  200. var depts = await _deptRep.AsQueryable()
  201. .Where(d => ids.Contains(d.Id))
  202. .Select(d => new { d.Id, Name = d.Descr ?? d.Department })
  203. .ToListAsync();
  204. nameMap = depts.ToDictionary(d => d.Id.ToString(), d => d.Name ?? d.Id.ToString());
  205. }
  206. var series = grouped.Select(g =>
  207. {
  208. var seriesName = nameMap.TryGetValue(g.Key, out var n) ? n : g.Key;
  209. var byDate = g.GroupBy(r => r.CreatedAt.Date).ToDictionary(x => x.Key, x => x.Count());
  210. var data = dates.Select(d => byDate.TryGetValue(d, out var c) ? c : 0).ToList();
  211. return new { name = seriesName, data };
  212. }).ToList();
  213. return new { dates = dateLabels, series };
  214. }
  215. public async Task<List<AdoS8Exception>> GetQuickExceptionsAsync(long tenantId, long factoryId, string mode)
  216. {
  217. var q = _rep.AsQueryable().Where(x => x.TenantId == tenantId && x.FactoryId == factoryId && !x.IsDeleted);
  218. var ordered = mode switch
  219. {
  220. "high-priority" => q.OrderBy(x => x.PriorityScore, OrderByType.Desc),
  221. "timeout" => q.Where(x => x.TimeoutFlag).OrderBy(x => x.SlaDeadline),
  222. _ => q.OrderBy(x => x.CreatedAt, OrderByType.Desc),
  223. };
  224. return await ordered.Take(20).ToListAsync();
  225. }
  226. }