S8MonitoringService.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. using Admin.NET.Plugin.AiDOP.Dto.S8;
  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 S8MonitoringService : ITransient
  7. {
  8. private readonly SqlSugarRepository<AdoS8Exception> _rep;
  9. private readonly SqlSugarRepository<AdoS8ExceptionType> _typeRep;
  10. // S8-OVERVIEW-DEPT-LABEL-HYDRATION-1:部门名称水合改用 AdoS0DepartmentMaster(DepartmentMaster 表,
  11. // RecID=1/2 映射真实部门),与 S8DashboardService / S8ExceptionService 主数据水合口径一致。
  12. // SysOrg 的 Id 为雪花,不与 ado_s8_exception.responsible_dept_id (1/2) 匹配,不能作部门名来源。
  13. private readonly SqlSugarRepository<AdoS0DepartmentMaster> _deptRep;
  14. public S8MonitoringService(
  15. SqlSugarRepository<AdoS8Exception> rep,
  16. SqlSugarRepository<AdoS8ExceptionType> typeRep,
  17. SqlSugarRepository<AdoS0DepartmentMaster> deptRep)
  18. {
  19. _rep = rep;
  20. _typeRep = typeRep;
  21. _deptRep = deptRep;
  22. }
  23. /// <summary>
  24. /// 9宫格数据:S1-S7 订单健康分布 + S8业务类别汇总 + S9部门汇总。
  25. /// 数据来源 ado_s8_exception 聚合;异常表为空时返回全 0(不再返回 Demo 数据)。
  26. /// </summary>
  27. public async Task<AdoS8OrderGridDto> GetOrderGridAsync(long tenantId = 1, long factoryId = 1, string? period = null)
  28. {
  29. var (periodFrom, periodTo) = S8PeriodHelper.Resolve(period);
  30. // S8-DASHBOARD-DATA-ALIGN-S1S7-1:统一统计基准 module_code IN S1-S7;
  31. // module_code IS NULL 的 legacy/demo 行不参与大屏聚合(不依赖 scene_code、不映射 legacy scene)。
  32. var events = await _rep.AsQueryable()
  33. .Where(e => e.TenantId == tenantId && e.FactoryId == factoryId && !e.IsDeleted)
  34. .Where(e => S8ModuleCode.All.Contains(e.ModuleCode))
  35. .WhereIF(periodFrom.HasValue, e => e.CreatedAt >= periodFrom!.Value)
  36. .WhereIF(periodTo.HasValue, e => e.CreatedAt < periodTo!.Value)
  37. .Select(e => new
  38. {
  39. e.ModuleCode,
  40. e.Severity,
  41. e.Status,
  42. e.TimeoutFlag,
  43. e.ExceptionTypeCode,
  44. e.SceneCode,
  45. e.ResponsibleDeptId,
  46. e.CreatedAt,
  47. e.ClosedAt
  48. })
  49. .ToListAsync();
  50. // ── Modules:按 module_code 聚合 ──
  51. var modules = S8ModuleCode.All.Select(mc =>
  52. {
  53. var rows = events.Where(e => e.ModuleCode == mc).ToList();
  54. var unclosed = rows.Where(e => e.Status != "CLOSED").ToList();
  55. // S8-SEVERITY-FOLLOW-SERIOUS-STANDARDIZE-EXEC-1:red=SERIOUS / yellow=FOLLOW;
  56. // green 不再来自异常 severity(异常表无「正常」桶),保留 0 兜底,绿色由 useS8StageConfig 兜底。
  57. var red = unclosed.Count(e => S8SeverityCode.IsSerious(e.Severity));
  58. var yellow = unclosed.Count(e => S8SeverityCode.IsFollow(e.Severity));
  59. var green = 0;
  60. var closed = rows.Count(e => e.Status == "CLOSED");
  61. var total = rows.Count;
  62. return new AdoS8ModuleOrderSummary
  63. {
  64. ModuleCode = mc,
  65. ModuleLabel = S8ModuleCode.Label(mc),
  66. Green = green,
  67. Yellow = yellow,
  68. Red = red,
  69. Total = total,
  70. Frequency = total,
  71. AvgProcessHours = AvgHours(rows.Select(r => (r.CreatedAt, r.ClosedAt))),
  72. CloseRate = total == 0 ? 0 : Math.Round(closed * 100.0 / total, 1),
  73. };
  74. }).ToList();
  75. // ── ByCategory:按异常类型的 type_code 聚合为 5 大业务类别(CategoryOf) ──
  76. var typeMap = (await _typeRep.AsQueryable()
  77. .Where(t => (t.TenantId == 0 && t.FactoryId == 0)
  78. || (t.TenantId == tenantId && t.FactoryId == factoryId))
  79. .ToListAsync())
  80. .GroupBy(t => t.TypeCode)
  81. .ToDictionary(g => g.Key, g => g.OrderByDescending(x => x.FactoryId).First());
  82. var byCategory = events
  83. .Where(e => !string.IsNullOrEmpty(e.ExceptionTypeCode) && typeMap.ContainsKey(e.ExceptionTypeCode!))
  84. .GroupBy(e => CategoryOf(typeMap[e.ExceptionTypeCode!]))
  85. .Where(g => !string.IsNullOrEmpty(g.Key))
  86. .Select(g =>
  87. {
  88. var total = g.Count();
  89. var closed = g.Count(e => e.Status == "CLOSED");
  90. return new AdoS8CategorySummary
  91. {
  92. Category = g.Key!,
  93. Total = total,
  94. AvgProcessHours = AvgHours(g.Select(e => (e.CreatedAt, e.ClosedAt))),
  95. CloseRate = total == 0 ? 0 : Math.Round(closed * 100.0 / total, 1),
  96. };
  97. })
  98. .OrderBy(c => CategoryOrder(c.Category))
  99. .ToList();
  100. // ── ByDept:按 ResponsibleDeptId 聚合,JOIN AdoS0DepartmentMaster(DepartmentMaster)取部门名称 ──
  101. // S8-OVERVIEW-DEPT-LABEL-HYDRATION-1:原使用 SysOrg 但其 Id 是雪花,与 dept_id=1/2 不匹配 → 100% fallback;
  102. // 改用 DepartmentMaster(RecID=1=质量部 / RecID=2=生产部),与 dashboard 部门口径对齐。
  103. var deptIds = events.Select(e => e.ResponsibleDeptId).Where(id => id > 0).Distinct().ToList();
  104. // S8-DEPT-DISPLAY-CONSISTENCY-1(P0-A-3):部门水合加 factory_ref_id 约束。
  105. var deptNameMap = deptIds.Count == 0
  106. ? new Dictionary<long, string>()
  107. : (await _deptRep.AsQueryable()
  108. .Where(d => deptIds.Contains(d.Id) && d.FactoryRefId == factoryId)
  109. .Select(d => new { d.Id, Name = d.Descr ?? d.Department })
  110. .ToListAsync())
  111. .ToDictionary(d => d.Id, d => d.Name ?? string.Empty);
  112. var byDept = events
  113. .Where(e => e.ResponsibleDeptId > 0)
  114. .GroupBy(e => e.ResponsibleDeptId)
  115. .Select(g =>
  116. {
  117. var total = g.Count();
  118. var closed = g.Count(e => e.Status == "CLOSED");
  119. return new AdoS8DeptSummary
  120. {
  121. DeptName = deptNameMap.TryGetValue(g.Key, out var n) && !string.IsNullOrEmpty(n) ? n : $"部门{g.Key}",
  122. Total = total,
  123. AvgProcessHours = AvgHours(g.Select(e => (e.CreatedAt, e.ClosedAt))),
  124. CloseRate = total == 0 ? 0 : Math.Round(closed * 100.0 / total, 1),
  125. };
  126. })
  127. .OrderByDescending(d => d.Total)
  128. .ToList();
  129. return new AdoS8OrderGridDto
  130. {
  131. Modules = modules,
  132. ByCategory = byCategory,
  133. ByDept = byDept,
  134. };
  135. }
  136. private static double AvgHours(IEnumerable<(DateTime createdAt, DateTime? closedAt)> items)
  137. {
  138. var closed = items.Where(x => x.closedAt.HasValue).ToList();
  139. if (closed.Count == 0) return 0;
  140. var avg = closed.Average(x => (x.closedAt!.Value - x.createdAt).TotalHours);
  141. return Math.Round(avg, 1);
  142. }
  143. /// <summary>异常类型 → 业务类别(与 Overview 页 5 张类别卡对应)。
  144. /// 优先级:配置 (AdoS8ExceptionType.MonitoringCategoryKey → KeyToLabel) → legacy hardcode fallback → string.Empty。
  145. /// 配置缺失或非法 key 时由 CategoryOfLegacy 兜底,保证演示链路不丢类别卡。</summary>
  146. private static string CategoryOf(AdoS8ExceptionType? t)
  147. {
  148. if (t is null) return string.Empty;
  149. var configured = S8MonitoringCategory.KeyToLabel(t.MonitoringCategoryKey);
  150. if (!string.IsNullOrEmpty(configured)) return configured;
  151. return CategoryOfLegacy(t.TypeCode);
  152. }
  153. /// <summary>Legacy hardcode 映射,保留现有 15 条 enabled + 7 条 deprecated 兼容分支。
  154. /// 不在此处补新映射;新 type_code 通过 monitoring_category_key 配置驱动。</summary>
  155. private static string CategoryOfLegacy(string? typeCode) => typeCode switch
  156. {
  157. // 订单评审
  158. "ORDER_CHANGE" => "订单评审",
  159. // 总装发货
  160. "DELIVERY_DELAY" => "总装发货",
  161. "PENDING_SHIPMENT" => "总装发货",
  162. // 本体生产(新基线)
  163. "EQUIP_FAULT" => "本体生产",
  164. "MFG_MATERIAL_ABNORMAL" => "本体生产",
  165. "MFG_QUALITY_ABNORMAL" => "本体生产",
  166. "PRODUCTION_MATERIAL_ABNORMAL" => "本体生产",
  167. "PRODUCTION_QUALITY_ABNORMAL" => "本体生产",
  168. "WORK_ORDER_KITTING_ABNORMAL" => "本体生产",
  169. "WORK_ORDER_ISSUE_ABNORMAL" => "本体生产",
  170. // 材料采购(新基线)
  171. "SUPPLIER_ETA_ISSUE" => "材料采购",
  172. "SUPPLIER_SHIP_ISSUE" => "材料采购",
  173. "IQC_ISSUE" => "材料采购",
  174. "WH_PUTAWAY_ISSUE" => "材料采购",
  175. "WAREHOUSE_RECEIPT_ABNORMAL" => "材料采购",
  176. // 旧 7 条 deprecated 仍保留兼容(DB 已迁移;此分支防 Overview 临时回放历史 active)
  177. "MATERIAL_SHORTAGE" => "本体生产",
  178. "QUALITY_DEFECT" => "本体生产",
  179. "DIMENSION_DEVIATION" => "本体生产",
  180. "WH_KIT_ISSUE" => "本体生产",
  181. "WH_ISSUE_OUT_ISSUE" => "本体生产",
  182. "WH_INBOUND_ISSUE" => "材料采购",
  183. _ => string.Empty,
  184. };
  185. private static int CategoryOrder(string category) => category switch
  186. {
  187. "订单评审" => 1,
  188. "产品设计" => 2,
  189. "材料采购" => 3,
  190. "本体生产" => 4,
  191. "总装发货" => 5,
  192. _ => 99,
  193. };
  194. /// <summary>
  195. /// 异常监控汇总:按 module_code 分组统计红/黄/绿/超时数。
  196. /// 供综合全景页顶部徽标和模块汇总表使用。
  197. /// </summary>
  198. public async Task<AdoS8MonitoringSummaryDto> GetSummaryAsync(AdoS8MonitoringSummaryQueryDto q)
  199. {
  200. // 显式日期范围优先;未传显式范围时尝试从 period 解析。
  201. var (periodFrom, periodTo) = (!q.BizDateFrom.HasValue && !q.BizDateTo.HasValue)
  202. ? S8PeriodHelper.Resolve(q.Period)
  203. : (q.BizDateFrom, q.BizDateTo);
  204. var effectiveFrom = q.BizDateFrom ?? periodFrom;
  205. var effectiveTo = q.BizDateTo ?? periodTo;
  206. var query = _rep.AsQueryable()
  207. .Where(e => e.TenantId == q.TenantId && e.FactoryId == q.FactoryId && !e.IsDeleted)
  208. // S8-DASHBOARD-DATA-ALIGN-S1S7-1:统一统计基准 module_code IN S1-S7。
  209. .Where(e => S8ModuleCode.All.Contains(e.ModuleCode))
  210. .WhereIF(!string.IsNullOrWhiteSpace(q.SceneCode), e => e.SceneCode == q.SceneCode)
  211. .WhereIF(!string.IsNullOrWhiteSpace(q.ModuleCode), e => e.ModuleCode == q.ModuleCode)
  212. .WhereIF(effectiveFrom.HasValue, e => e.CreatedAt >= effectiveFrom!.Value)
  213. .WhereIF(effectiveTo.HasValue, e => e.CreatedAt < effectiveTo!.Value);
  214. // 聚合到内存(数据量在可控范围内,避免复杂 GROUP BY 兼容性问题)
  215. // S8-SLA-TIMEOUT-RUNTIME-1(P3):投影 SlaDeadline 替代 TimeoutFlag,timeout 改为运行时计算。
  216. var raw = await query
  217. .Select(e => new
  218. {
  219. e.ModuleCode,
  220. e.SceneCode,
  221. e.Severity,
  222. e.SlaDeadline,
  223. e.Status
  224. })
  225. .ToListAsync();
  226. var nowForTimeout = DateTime.Now;
  227. var byModule = raw
  228. .GroupBy(e => new { mc = e.ModuleCode ?? string.Empty, sc = e.SceneCode ?? string.Empty })
  229. .Select(g => new AdoS8ModuleSummaryItem
  230. {
  231. ModuleCode = g.Key.mc,
  232. ModuleLabel = S8ModuleCode.Label(g.Key.mc),
  233. SceneCode = g.Key.sc,
  234. SceneLabel = S8SceneCode.Label(g.Key.sc),
  235. Total = g.Count(),
  236. // S8-SEVERITY-FOLLOW-SERIOUS-STANDARDIZE-EXEC-1:red=SERIOUS / yellow=FOLLOW;green=0(异常表无正常桶)。
  237. Red = g.Count(e => S8SeverityCode.IsSerious(e.Severity)),
  238. Yellow = g.Count(e => S8SeverityCode.IsFollow(e.Severity)),
  239. Green = 0,
  240. Timeout = g.Count(e => e.SlaDeadline != null && e.SlaDeadline < nowForTimeout && e.Status != "CLOSED" && e.Status != "RECOVERED")
  241. })
  242. // 按 S8ModuleCode.All 顺序排列
  243. .OrderBy(r => Array.IndexOf(S8ModuleCode.All, r.ModuleCode))
  244. .ToList();
  245. return new AdoS8MonitoringSummaryDto
  246. {
  247. Total = raw.Count,
  248. // S8-SEVERITY-FOLLOW-SERIOUS-STANDARDIZE-EXEC-1:red=SERIOUS / yellow=FOLLOW;green=0。
  249. Red = raw.Count(e => S8SeverityCode.IsSerious(e.Severity)),
  250. Yellow = raw.Count(e => S8SeverityCode.IsFollow(e.Severity)),
  251. Green = 0,
  252. Timeout = raw.Count(e => e.SlaDeadline != null && e.SlaDeadline < nowForTimeout && e.Status != "CLOSED" && e.Status != "RECOVERED"),
  253. ByModule = byModule
  254. };
  255. }
  256. /// <summary>
  257. /// S8-DELIVERY-TREND-CHART-REPLACE-DUPLICATE-SECTION-1:Delivery 页近 N 日交付异常趋势。
  258. /// 口径:module_code IN (S1,S7) AND exception_type_code IN (ORDER_CHANGE / DELIVERY_DELAY / PENDING_SHIPMENT);
  259. /// 时间字段 created_at;不排除 CLOSED;按日聚合,缺失日期补 0;days 限 1-30。
  260. /// </summary>
  261. public async Task<AdoS8DeliveryTrendDto> GetDeliveryTrendAsync(long tenantId = 1, long factoryId = 1, int days = 7)
  262. {
  263. days = Math.Clamp(days, 1, 30);
  264. var today = DateTime.Today;
  265. var from = today.AddDays(-(days - 1));
  266. var toExclusive = today.AddDays(1);
  267. var deliveryModules = new[] { "S1", "S7" };
  268. var deliveryTypes = new[] { "ORDER_CHANGE", "DELIVERY_DELAY", "PENDING_SHIPMENT" };
  269. var rows = await _rep.AsQueryable()
  270. .Where(e => e.TenantId == tenantId && e.FactoryId == factoryId && !e.IsDeleted)
  271. .Where(e => deliveryModules.Contains(e.ModuleCode))
  272. .Where(e => e.ExceptionTypeCode != null && deliveryTypes.Contains(e.ExceptionTypeCode))
  273. .Where(e => e.CreatedAt >= from && e.CreatedAt < toExclusive)
  274. .Select(e => new { e.ExceptionTypeCode, e.CreatedAt })
  275. .ToListAsync();
  276. var byDate = rows
  277. .GroupBy(r => r.CreatedAt.Date)
  278. .ToDictionary(g => g.Key, g => g.ToList());
  279. var dayList = new List<AdoS8DeliveryTrendDayDto>(days);
  280. for (var i = 0; i < days; i++)
  281. {
  282. var d = from.AddDays(i);
  283. var bucket = byDate.TryGetValue(d, out var list) ? list : new();
  284. var oc = bucket.Count(r => r.ExceptionTypeCode == "ORDER_CHANGE");
  285. var dd = bucket.Count(r => r.ExceptionTypeCode == "DELIVERY_DELAY");
  286. var ps = bucket.Count(r => r.ExceptionTypeCode == "PENDING_SHIPMENT");
  287. dayList.Add(new AdoS8DeliveryTrendDayDto
  288. {
  289. Date = d.ToString("MM/dd"),
  290. RawDate = d.ToString("yyyy-MM-dd"),
  291. OrderChange = oc,
  292. DeliveryDelay = dd,
  293. PendingShipment = ps,
  294. Total = oc + dd + ps,
  295. });
  296. }
  297. var totalSum = dayList.Sum(d => d.Total);
  298. var peak = dayList.OrderByDescending(d => d.Total).FirstOrDefault();
  299. var todayDay = dayList.Last();
  300. var yesterday = dayList.Count >= 2 ? dayList[^2] : null;
  301. double? changeRate = (yesterday is null || yesterday.Total == 0)
  302. ? (double?)null
  303. : Math.Round((todayDay.Total - yesterday.Total) * 100.0 / yesterday.Total, 1);
  304. var summary = new AdoS8DeliveryTrendSummaryDto
  305. {
  306. PeakValue = peak?.Total ?? 0,
  307. PeakDate = (peak is null || peak.Total == 0) ? null : peak.RawDate,
  308. AvgValue = Math.Round(totalSum / (double)days, 2),
  309. TodayValue = todayDay.Total,
  310. TodayChangeRate = changeRate,
  311. };
  312. return new AdoS8DeliveryTrendDto { Days = dayList, Summary = summary };
  313. }
  314. /// <summary>
  315. /// S8-PROD-SUPPLY-TREND-CHART-REPLACE-DUPLICATE-SECTION-1:Production 页近 N 日生产异常趋势。
  316. /// 口径:module_code IN (S2,S6) AND exception_type_code IN (EQUIP_FAULT / MFG_MATERIAL_ABNORMAL / MFG_QUALITY_ABNORMAL);
  317. /// 时间字段 created_at;不排除 CLOSED;按日聚合,缺失日期补 0;days 限 1-30。
  318. /// </summary>
  319. public async Task<AdoS8ProductionTrendDto> GetProductionTrendAsync(long tenantId = 1, long factoryId = 1, int days = 7)
  320. {
  321. days = Math.Clamp(days, 1, 30);
  322. var today = DateTime.Today;
  323. var from = today.AddDays(-(days - 1));
  324. var toExclusive = today.AddDays(1);
  325. var prodModules = new[] { "S2", "S6" };
  326. var prodTypes = new[] { "EQUIP_FAULT", "MFG_MATERIAL_ABNORMAL", "MFG_QUALITY_ABNORMAL" };
  327. var rows = await _rep.AsQueryable()
  328. .Where(e => e.TenantId == tenantId && e.FactoryId == factoryId && !e.IsDeleted)
  329. .Where(e => prodModules.Contains(e.ModuleCode))
  330. .Where(e => e.ExceptionTypeCode != null && prodTypes.Contains(e.ExceptionTypeCode))
  331. .Where(e => e.CreatedAt >= from && e.CreatedAt < toExclusive)
  332. .Select(e => new { e.ExceptionTypeCode, e.CreatedAt })
  333. .ToListAsync();
  334. var byDate = rows.GroupBy(r => r.CreatedAt.Date).ToDictionary(g => g.Key, g => g.ToList());
  335. var dayList = new List<AdoS8ProductionTrendDayDto>(days);
  336. for (var i = 0; i < days; i++)
  337. {
  338. var d = from.AddDays(i);
  339. var bucket = byDate.TryGetValue(d, out var list) ? list : new();
  340. var ef = bucket.Count(r => r.ExceptionTypeCode == "EQUIP_FAULT");
  341. var mf = bucket.Count(r => r.ExceptionTypeCode == "MFG_MATERIAL_ABNORMAL");
  342. var qf = bucket.Count(r => r.ExceptionTypeCode == "MFG_QUALITY_ABNORMAL");
  343. dayList.Add(new AdoS8ProductionTrendDayDto
  344. {
  345. Date = d.ToString("MM/dd"),
  346. RawDate = d.ToString("yyyy-MM-dd"),
  347. EquipmentFault = ef,
  348. MaterialFault = mf,
  349. QualityFault = qf,
  350. Total = ef + mf + qf,
  351. });
  352. }
  353. var totalSum = dayList.Sum(d => d.Total);
  354. var peak = dayList.OrderByDescending(d => d.Total).FirstOrDefault();
  355. var todayDay = dayList.Last();
  356. var yesterday = dayList.Count >= 2 ? dayList[^2] : null;
  357. double? changeRate = (yesterday is null || yesterday.Total == 0)
  358. ? (double?)null
  359. : Math.Round((todayDay.Total - yesterday.Total) * 100.0 / yesterday.Total, 1);
  360. var summary = new AdoS8DeliveryTrendSummaryDto
  361. {
  362. PeakValue = peak?.Total ?? 0,
  363. PeakDate = (peak is null || peak.Total == 0) ? null : peak.RawDate,
  364. AvgValue = Math.Round(totalSum / (double)days, 2),
  365. TodayValue = todayDay.Total,
  366. TodayChangeRate = changeRate,
  367. };
  368. return new AdoS8ProductionTrendDto { Days = dayList, Summary = summary };
  369. }
  370. /// <summary>
  371. /// S8-PROD-SUPPLY-TREND-CHART-REPLACE-DUPLICATE-SECTION-1:Supply 页近 N 日供应异常趋势。
  372. /// 口径:module_code IN (S3,S4,S5) AND exception_type_code IN 7 类(SUPPLIER_ETA_ISSUE / SUPPLIER_SHIP_ISSUE
  373. /// / WAREHOUSE_RECEIPT_ABNORMAL / IQC_ISSUE / WH_PUTAWAY_ISSUE / WORK_ORDER_KITTING_ABNORMAL / WORK_ORDER_ISSUE_ABNORMAL);
  374. /// 时间字段 created_at;不排除 CLOSED;按日聚合,缺失日期补 0;days 限 1-30。
  375. /// </summary>
  376. public async Task<AdoS8SupplyTrendDto> GetSupplyTrendAsync(long tenantId = 1, long factoryId = 1, int days = 7)
  377. {
  378. days = Math.Clamp(days, 1, 30);
  379. var today = DateTime.Today;
  380. var from = today.AddDays(-(days - 1));
  381. var toExclusive = today.AddDays(1);
  382. var supplyModules = new[] { "S3", "S4", "S5" };
  383. var supplyTypes = new[]
  384. {
  385. "SUPPLIER_ETA_ISSUE", "SUPPLIER_SHIP_ISSUE", "WAREHOUSE_RECEIPT_ABNORMAL",
  386. "IQC_ISSUE", "WH_PUTAWAY_ISSUE", "WORK_ORDER_KITTING_ABNORMAL", "WORK_ORDER_ISSUE_ABNORMAL"
  387. };
  388. var rows = await _rep.AsQueryable()
  389. .Where(e => e.TenantId == tenantId && e.FactoryId == factoryId && !e.IsDeleted)
  390. .Where(e => supplyModules.Contains(e.ModuleCode))
  391. .Where(e => e.ExceptionTypeCode != null && supplyTypes.Contains(e.ExceptionTypeCode))
  392. .Where(e => e.CreatedAt >= from && e.CreatedAt < toExclusive)
  393. .Select(e => new { e.ExceptionTypeCode, e.CreatedAt })
  394. .ToListAsync();
  395. var byDate = rows.GroupBy(r => r.CreatedAt.Date).ToDictionary(g => g.Key, g => g.ToList());
  396. var dayList = new List<AdoS8SupplyTrendDayDto>(days);
  397. for (var i = 0; i < days; i++)
  398. {
  399. var d = from.AddDays(i);
  400. var bucket = byDate.TryGetValue(d, out var list) ? list : new();
  401. var s1 = bucket.Count(r => r.ExceptionTypeCode == "SUPPLIER_ETA_ISSUE");
  402. var s2 = bucket.Count(r => r.ExceptionTypeCode == "SUPPLIER_SHIP_ISSUE");
  403. var s3 = bucket.Count(r => r.ExceptionTypeCode == "WAREHOUSE_RECEIPT_ABNORMAL");
  404. var s4 = bucket.Count(r => r.ExceptionTypeCode == "IQC_ISSUE");
  405. var s5 = bucket.Count(r => r.ExceptionTypeCode == "WH_PUTAWAY_ISSUE");
  406. var s6 = bucket.Count(r => r.ExceptionTypeCode == "WORK_ORDER_KITTING_ABNORMAL");
  407. var s7 = bucket.Count(r => r.ExceptionTypeCode == "WORK_ORDER_ISSUE_ABNORMAL");
  408. dayList.Add(new AdoS8SupplyTrendDayDto
  409. {
  410. Date = d.ToString("MM/dd"),
  411. RawDate = d.ToString("yyyy-MM-dd"),
  412. SupplierEtaIssue = s1,
  413. SupplierShipIssue = s2,
  414. WarehouseReceiptAbnormal = s3,
  415. IqcIssue = s4,
  416. WarehousePutawayIssue = s5,
  417. WorkOrderKittingAbnormal = s6,
  418. WorkOrderIssueAbnormal = s7,
  419. Total = s1 + s2 + s3 + s4 + s5 + s6 + s7,
  420. });
  421. }
  422. var totalSum = dayList.Sum(d => d.Total);
  423. var peak = dayList.OrderByDescending(d => d.Total).FirstOrDefault();
  424. var todayDay = dayList.Last();
  425. var yesterday = dayList.Count >= 2 ? dayList[^2] : null;
  426. double? changeRate = (yesterday is null || yesterday.Total == 0)
  427. ? (double?)null
  428. : Math.Round((todayDay.Total - yesterday.Total) * 100.0 / yesterday.Total, 1);
  429. var summary = new AdoS8DeliveryTrendSummaryDto
  430. {
  431. PeakValue = peak?.Total ?? 0,
  432. PeakDate = (peak is null || peak.Total == 0) ? null : peak.RawDate,
  433. AvgValue = Math.Round(totalSum / (double)days, 2),
  434. TodayValue = todayDay.Total,
  435. TodayChangeRate = changeRate,
  436. };
  437. return new AdoS8SupplyTrendDto { Days = dayList, Summary = summary };
  438. }
  439. /// <summary>
  440. /// S8-SIDEBAR-TYPE-CARD-WINDOW-TOGGLE-1:专题页右侧类型卡按 (domain, window) 统一聚合。
  441. /// 单一时间窗口下 total / open / closed / avgProcessHours / closeRate 共用同一分母。
  442. /// 公共过滤:tenant/factory + is_deleted=0 + module_code IN S1-S7 + exception_type_code IN domain 类型集 + created_at IN window。
  443. /// </summary>
  444. public async Task<AdoS8DomainTypeMetricsDto> GetDomainTypeMetricsAsync(string domain, string window, long tenantId = 1, long factoryId = 1)
  445. {
  446. var d = (domain ?? string.Empty).Trim().ToUpperInvariant();
  447. var w = (window ?? string.Empty).Trim().ToUpperInvariant();
  448. if (w != "LAST_24H" && w != "LAST_7D") w = "LAST_24H";
  449. (string key, string label, string typeCode)[] specs = d switch
  450. {
  451. "DELIVERY" => new (string, string, string)[]
  452. {
  453. ("order-change", "订单变更", "ORDER_CHANGE"),
  454. ("delivery-delay", "交期延迟", "DELIVERY_DELAY"),
  455. ("stock-pending", "入库待发", "PENDING_SHIPMENT"),
  456. },
  457. "PRODUCTION" => new (string, string, string)[]
  458. {
  459. ("equipment-fault", "设备异常", "EQUIP_FAULT"),
  460. ("material-fault", "物料异常", "MFG_MATERIAL_ABNORMAL"),
  461. ("quality-fault", "质量异常", "MFG_QUALITY_ABNORMAL"),
  462. },
  463. "SUPPLY" => new (string, string, string)[]
  464. {
  465. ("supplier-reply-delay", "供应商回复交期异常", "SUPPLIER_ETA_ISSUE"),
  466. ("supplier-ship-fault", "供应商发货异常", "SUPPLIER_SHIP_ISSUE"),
  467. ("warehouse-receipt", "仓库收货异常", "WAREHOUSE_RECEIPT_ABNORMAL"),
  468. ("iqc-inspection", "IQC 检验异常", "IQC_ISSUE"),
  469. ("warehouse-shelving", "仓库上架入库异常", "WH_PUTAWAY_ISSUE"),
  470. ("work-order-prepare", "仓库工单备料异常", "WORK_ORDER_KITTING_ABNORMAL"),
  471. ("work-order-issue", "仓库工单发料异常", "WORK_ORDER_ISSUE_ABNORMAL"),
  472. },
  473. _ => Array.Empty<(string, string, string)>(),
  474. };
  475. var typeCodes = specs.Select(s => s.typeCode).ToArray();
  476. if (typeCodes.Length == 0)
  477. {
  478. return new AdoS8DomainTypeMetricsDto { Domain = d, Window = w, Total = 0, Items = new() };
  479. }
  480. DateTime from, to;
  481. if (w == "LAST_7D")
  482. {
  483. // 与 trend 接口保持一致:[today-6, today+1)
  484. var today = DateTime.Today;
  485. from = today.AddDays(-6);
  486. to = today.AddDays(1);
  487. }
  488. else
  489. {
  490. // LAST_24H:滑动窗口 NOW()-24h ~ NOW()
  491. var now = DateTime.Now;
  492. from = now.AddHours(-24);
  493. to = now.AddMinutes(1);
  494. }
  495. var rows = await _rep.AsQueryable()
  496. .Where(e => e.TenantId == tenantId && e.FactoryId == factoryId && !e.IsDeleted)
  497. .Where(e => S8ModuleCode.All.Contains(e.ModuleCode))
  498. .Where(e => e.ExceptionTypeCode != null && typeCodes.Contains(e.ExceptionTypeCode))
  499. .Where(e => e.CreatedAt >= from && e.CreatedAt < to)
  500. .Select(e => new { e.ExceptionTypeCode, e.Status, e.CreatedAt, e.ClosedAt })
  501. .ToListAsync();
  502. var byType = rows.GroupBy(r => r.ExceptionTypeCode!).ToDictionary(g => g.Key, g => g.ToList());
  503. var items = specs.Select(s =>
  504. {
  505. var bucket = byType.TryGetValue(s.typeCode, out var list) ? list : new();
  506. var total = bucket.Count;
  507. var closedCount = bucket.Count(r => r.Status == "CLOSED");
  508. var openCount = total - closedCount;
  509. double? avgHours = null;
  510. var closedSamples = bucket.Where(r => r.ClosedAt.HasValue).ToList();
  511. if (closedSamples.Count > 0)
  512. {
  513. avgHours = Math.Round(closedSamples.Average(r => (r.ClosedAt!.Value - r.CreatedAt).TotalHours), 1);
  514. }
  515. double? closeRate = total == 0 ? null : Math.Round(closedCount * 100.0 / total, 1);
  516. return new AdoS8DomainTypeMetricItemDto
  517. {
  518. Key = s.key,
  519. Label = s.label,
  520. TypeCode = s.typeCode,
  521. Total = total,
  522. OpenCount = openCount,
  523. ClosedCount = closedCount,
  524. AvgProcessHours = avgHours,
  525. CloseRate = closeRate,
  526. };
  527. }).ToList();
  528. return new AdoS8DomainTypeMetricsDto
  529. {
  530. Domain = d,
  531. Window = w,
  532. Total = items.Sum(i => i.Total),
  533. Items = items,
  534. };
  535. }
  536. }