S8MonitoringService.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  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.Entity.S8.OrderFlow;
  5. using Admin.NET.Plugin.AiDOP.Infrastructure.S8;
  6. namespace Admin.NET.Plugin.AiDOP.Service.S8;
  7. public class S8MonitoringService : ITransient
  8. {
  9. private readonly SqlSugarRepository<AdoS8Exception> _rep;
  10. private readonly SqlSugarRepository<AdoS8ExceptionType> _typeRep;
  11. // S8-OVERVIEW-DEPT-LABEL-HYDRATION-1:部门名称水合改用 AdoS0DepartmentMaster(DepartmentMaster 表,
  12. // RecID=1/2 映射真实部门),与 S8DashboardService / S8ExceptionService 主数据水合口径一致。
  13. // SysOrg 的 Id 为雪花,不与 ado_s8_exception.responsible_dept_id (1/2) 匹配,不能作部门名来源。
  14. private readonly SqlSugarRepository<AdoS0DepartmentMaster> _deptRep;
  15. // TASK-012-S9-QDC-RATIO-MIGRATION-2:result KPI summary 读取 RATIO 指标字典
  16. private readonly SqlSugarRepository<AdoS8MonitorMetric> _metricRep;
  17. // S9-RESULT-KPI-DEMO-BASELINE-AND-ORDER-FLOW-CALC-1:ORDER_FLOW_CYCLE_RATIO 半真实计算依赖订单链路阶段表
  18. private readonly SqlSugarRepository<AdoS8OrderFlowStage> _orderFlowStageRep;
  19. public S8MonitoringService(
  20. SqlSugarRepository<AdoS8Exception> rep,
  21. SqlSugarRepository<AdoS8ExceptionType> typeRep,
  22. SqlSugarRepository<AdoS0DepartmentMaster> deptRep,
  23. SqlSugarRepository<AdoS8MonitorMetric> metricRep,
  24. SqlSugarRepository<AdoS8OrderFlowStage> orderFlowStageRep)
  25. {
  26. _rep = rep;
  27. _typeRep = typeRep;
  28. _deptRep = deptRep;
  29. _metricRep = metricRep;
  30. _orderFlowStageRep = orderFlowStageRep;
  31. }
  32. /// <summary>
  33. /// 9宫格数据:S1-S7 订单健康分布 + S8业务类别汇总 + S9部门汇总。
  34. /// 数据来源 ado_s8_exception 聚合;异常表为空时返回全 0(不再返回 Demo 数据)。
  35. /// </summary>
  36. public async Task<AdoS8OrderGridDto> GetOrderGridAsync(long tenantId = 1, long factoryId = 1, string? period = null)
  37. {
  38. var (periodFrom, periodTo) = S8PeriodHelper.Resolve(period);
  39. // TASK-002-RESET-DIMENSION-MODEL-DEV-4A:聚合源切到 stage_code(DEV-2A 已与 module_code 对齐);
  40. // DTO 字段名保持 ModuleCode 以兼容前端,仅来源字段改为 StageCode。
  41. var events = await _rep.AsQueryable()
  42. .Where(e => e.TenantId == tenantId && e.FactoryId == factoryId && !e.IsDeleted)
  43. .Where(e => S8ModuleCode.All.Contains(e.StageCode))
  44. .WhereIF(periodFrom.HasValue, e => e.CreatedAt >= periodFrom!.Value)
  45. .WhereIF(periodTo.HasValue, e => e.CreatedAt < periodTo!.Value)
  46. .Select(e => new
  47. {
  48. ModuleCode = e.StageCode,
  49. e.Severity,
  50. e.Status,
  51. e.TimeoutFlag,
  52. e.ExceptionTypeCode,
  53. e.SceneCode,
  54. e.ResponsibleDeptId,
  55. e.CreatedAt,
  56. e.ClosedAt
  57. })
  58. .ToListAsync();
  59. // ── Modules:按 module_code 聚合 ──
  60. var modules = S8ModuleCode.All.Select(mc =>
  61. {
  62. var rows = events.Where(e => e.ModuleCode == mc).ToList();
  63. var unclosed = rows.Where(e => e.Status != "CLOSED").ToList();
  64. // S8-SEVERITY-FOLLOW-SERIOUS-STANDARDIZE-EXEC-1:red=SERIOUS / yellow=FOLLOW;
  65. // green 不再来自异常 severity(异常表无「正常」桶),保留 0 兜底,绿色由 useS8StageConfig 兜底。
  66. var red = unclosed.Count(e => S8SeverityCode.IsSerious(e.Severity));
  67. var yellow = unclosed.Count(e => S8SeverityCode.IsFollow(e.Severity));
  68. var green = 0;
  69. var closed = rows.Count(e => e.Status == "CLOSED");
  70. var total = rows.Count;
  71. return new AdoS8ModuleOrderSummary
  72. {
  73. ModuleCode = mc,
  74. ModuleLabel = S8ModuleCode.Label(mc),
  75. Green = green,
  76. Yellow = yellow,
  77. Red = red,
  78. Total = total,
  79. Frequency = total,
  80. AvgProcessHours = AvgHours(rows.Select(r => (r.CreatedAt, r.ClosedAt))),
  81. CloseRate = total == 0 ? 0 : Math.Round(closed * 100.0 / total, 1),
  82. };
  83. }).ToList();
  84. // ── ByCategory:按异常类型的 type_code 聚合为 5 大业务类别(CategoryOf) ──
  85. var typeMap = (await _typeRep.AsQueryable()
  86. .Where(t => (t.TenantId == 0 && t.FactoryId == 0)
  87. || (t.TenantId == tenantId && t.FactoryId == factoryId))
  88. .ToListAsync())
  89. .GroupBy(t => t.TypeCode)
  90. .ToDictionary(g => g.Key, g => g.OrderByDescending(x => x.FactoryId).First());
  91. var byCategory = events
  92. .Where(e => !string.IsNullOrEmpty(e.ExceptionTypeCode) && typeMap.ContainsKey(e.ExceptionTypeCode!))
  93. .GroupBy(e => CategoryOf(typeMap[e.ExceptionTypeCode!]))
  94. .Where(g => !string.IsNullOrEmpty(g.Key))
  95. .Select(g =>
  96. {
  97. var total = g.Count();
  98. var closed = g.Count(e => e.Status == "CLOSED");
  99. return new AdoS8CategorySummary
  100. {
  101. Category = g.Key!,
  102. Total = total,
  103. AvgProcessHours = AvgHours(g.Select(e => (e.CreatedAt, e.ClosedAt))),
  104. CloseRate = total == 0 ? 0 : Math.Round(closed * 100.0 / total, 1),
  105. };
  106. })
  107. .OrderBy(c => CategoryOrder(c.Category))
  108. .ToList();
  109. // ── ByDept:按 ResponsibleDeptId 聚合,JOIN AdoS0DepartmentMaster(DepartmentMaster)取部门名称 ──
  110. // S8-OVERVIEW-DEPT-LABEL-HYDRATION-1:原使用 SysOrg 但其 Id 是雪花,与 dept_id=1/2 不匹配 → 100% fallback;
  111. // 改用 DepartmentMaster(RecID=1=质量部 / RecID=2=生产部),与 dashboard 部门口径对齐。
  112. var deptIds = events.Select(e => e.ResponsibleDeptId).Where(id => id > 0).Distinct().ToList();
  113. // S8-DEPT-DISPLAY-CONSISTENCY-1(P0-A-3):部门水合加 factory_ref_id 约束。
  114. var deptNameMap = deptIds.Count == 0
  115. ? new Dictionary<long, string>()
  116. : (await _deptRep.AsQueryable()
  117. .Where(d => deptIds.Contains(d.Id) && d.FactoryRefId == factoryId)
  118. .Select(d => new { d.Id, Name = d.Descr ?? d.Department })
  119. .ToListAsync())
  120. .ToDictionary(d => d.Id, d => d.Name ?? string.Empty);
  121. var byDept = events
  122. .Where(e => e.ResponsibleDeptId > 0)
  123. .GroupBy(e => e.ResponsibleDeptId)
  124. .Select(g =>
  125. {
  126. var total = g.Count();
  127. var closed = g.Count(e => e.Status == "CLOSED");
  128. return new AdoS8DeptSummary
  129. {
  130. DeptName = deptNameMap.TryGetValue(g.Key, out var n) && !string.IsNullOrEmpty(n) ? n : $"部门{g.Key}",
  131. Total = total,
  132. AvgProcessHours = AvgHours(g.Select(e => (e.CreatedAt, e.ClosedAt))),
  133. CloseRate = total == 0 ? 0 : Math.Round(closed * 100.0 / total, 1),
  134. };
  135. })
  136. .OrderByDescending(d => d.Total)
  137. .ToList();
  138. return new AdoS8OrderGridDto
  139. {
  140. Modules = modules,
  141. ByCategory = byCategory,
  142. ByDept = byDept,
  143. };
  144. }
  145. private static double AvgHours(IEnumerable<(DateTime createdAt, DateTime? closedAt)> items)
  146. {
  147. var closed = items.Where(x => x.closedAt.HasValue).ToList();
  148. if (closed.Count == 0) return 0;
  149. var avg = closed.Average(x => (x.closedAt!.Value - x.createdAt).TotalHours);
  150. return Math.Round(avg, 1);
  151. }
  152. /// <summary>异常类型 → 业务类别(与 Overview 页 5 张类别卡对应)。
  153. /// 优先级:配置 (AdoS8ExceptionType.MonitoringCategoryKey → KeyToLabel) → legacy hardcode fallback → string.Empty。
  154. /// 配置缺失或非法 key 时由 CategoryOfLegacy 兜底,保证演示链路不丢类别卡。</summary>
  155. private static string CategoryOf(AdoS8ExceptionType? t)
  156. {
  157. if (t is null) return string.Empty;
  158. var configured = S8MonitoringCategory.KeyToLabel(t.MonitoringCategoryKey);
  159. if (!string.IsNullOrEmpty(configured)) return configured;
  160. return CategoryOfLegacy(t.TypeCode);
  161. }
  162. /// <summary>Legacy hardcode 映射,保留现有 15 条 enabled + 7 条 deprecated 兼容分支。
  163. /// 不在此处补新映射;新 type_code 通过 monitoring_category_key 配置驱动。</summary>
  164. private static string CategoryOfLegacy(string? typeCode) => typeCode switch
  165. {
  166. // 订单评审
  167. "ORDER_CHANGE" => "订单评审",
  168. // 总装发货
  169. "DELIVERY_DELAY" => "总装发货",
  170. "PENDING_SHIPMENT" => "总装发货",
  171. // 本体生产(新基线)
  172. "EQUIP_FAULT" => "本体生产",
  173. "MFG_MATERIAL_ABNORMAL" => "本体生产",
  174. "MFG_QUALITY_ABNORMAL" => "本体生产",
  175. "PRODUCTION_MATERIAL_ABNORMAL" => "本体生产",
  176. "PRODUCTION_QUALITY_ABNORMAL" => "本体生产",
  177. "WORK_ORDER_KITTING_ABNORMAL" => "本体生产",
  178. "WORK_ORDER_ISSUE_ABNORMAL" => "本体生产",
  179. // 材料采购(新基线)
  180. "SUPPLIER_ETA_ISSUE" => "材料采购",
  181. "SUPPLIER_SHIP_ISSUE" => "材料采购",
  182. "IQC_ISSUE" => "材料采购",
  183. "WH_PUTAWAY_ISSUE" => "材料采购",
  184. "WAREHOUSE_RECEIPT_ABNORMAL" => "材料采购",
  185. // 旧 7 条 deprecated 仍保留兼容(DB 已迁移;此分支防 Overview 临时回放历史 active)
  186. "MATERIAL_SHORTAGE" => "本体生产",
  187. "QUALITY_DEFECT" => "本体生产",
  188. "DIMENSION_DEVIATION" => "本体生产",
  189. "WH_KIT_ISSUE" => "本体生产",
  190. "WH_ISSUE_OUT_ISSUE" => "本体生产",
  191. "WH_INBOUND_ISSUE" => "材料采购",
  192. _ => string.Empty,
  193. };
  194. private static int CategoryOrder(string category) => category switch
  195. {
  196. "订单评审" => 1,
  197. "产品设计" => 2,
  198. "材料采购" => 3,
  199. "本体生产" => 4,
  200. "总装发货" => 5,
  201. _ => 99,
  202. };
  203. // ── QDC 常量映射(不建表,后端常量驱动) ──────────────────────────────────────
  204. private static readonly (string Code, string Title, string[] Types, string? Remark)[] QdcGroups =
  205. {
  206. ("QUALITY", "质量异常", new[] { "PURCHASE_QUALITY_ABNORMAL", "MFG_QUALITY_ABNORMAL", "PRODUCTION_QUALITY_ABNORMAL" }, null),
  207. ("DELIVERY", "交付异常", new[] { "ORDER_DELIVERY_DELAY_WARNING", "SUPPLIER_DELIVERY_DELAY_WARNING", "ORDER_CHANGE", "DELIVERY_DELAY", "PENDING_SHIPMENT" }, null),
  208. ("INVENTORY", "库存异常", new[] { "MATERIAL_STOCK_ABNORMAL", "INVENTORY_TURNOVER_ABNORMAL", "INVENTORY_AMOUNT_LEVEL_ABNORMAL" }, null),
  209. ("COST", "成本异常", Array.Empty<string>(), "待定义成本异常口径"),
  210. };
  211. /// <summary>
  212. /// S9 QDC 四主线运营聚合:质量 / 交付 / 成本 / 库存。
  213. /// 成本异常当前无 enabled exception_type,返回空桶。
  214. /// 及时关闭率依赖 sla_deadline,无 SLA 数据时返回 null。
  215. /// </summary>
  216. public async Task<AdoS8QdcSummaryDto> GetQdcSummaryAsync(long tenantId = 1, long factoryId = 1, string? period = null)
  217. {
  218. var (periodFrom, periodTo) = S8PeriodHelper.Resolve(period);
  219. var events = await _rep.AsQueryable()
  220. .Where(e => e.TenantId == tenantId && e.FactoryId == factoryId && !e.IsDeleted)
  221. .WhereIF(periodFrom.HasValue, e => e.CreatedAt >= periodFrom!.Value)
  222. .WhereIF(periodTo.HasValue, e => e.CreatedAt < periodTo!.Value)
  223. .Select(e => new
  224. {
  225. e.ExceptionTypeCode,
  226. e.Status,
  227. e.CreatedAt,
  228. e.ClosedAt,
  229. e.SlaDeadline,
  230. })
  231. .ToListAsync();
  232. var items = new List<AdoS8QdcSummaryItemDto>();
  233. foreach (var (code, title, types, remark) in QdcGroups)
  234. {
  235. if (types.Length == 0)
  236. {
  237. items.Add(new AdoS8QdcSummaryItemDto { Code = code, Title = title, Total = 0, Remark = remark });
  238. continue;
  239. }
  240. var rows = events
  241. .Where(e => e.ExceptionTypeCode != null && types.Contains(e.ExceptionTypeCode))
  242. .ToList();
  243. var total = rows.Count;
  244. var closedRows = rows.Where(e => e.Status == "CLOSED" && e.ClosedAt.HasValue).ToList();
  245. double? avgHours = closedRows.Count == 0
  246. ? null
  247. : Math.Round(closedRows.Average(e => (e.ClosedAt!.Value - e.CreatedAt).TotalHours), 1);
  248. double? closeRate = total == 0
  249. ? null
  250. : Math.Round(closedRows.Count * 100.0 / total, 1);
  251. double? onTimeCloseRate = null;
  252. if (closedRows.Count > 0)
  253. {
  254. var closedWithSla = closedRows.Where(e => e.SlaDeadline.HasValue).ToList();
  255. if (closedWithSla.Count > 0)
  256. onTimeCloseRate = Math.Round(
  257. closedWithSla.Count(e => e.ClosedAt!.Value <= e.SlaDeadline!.Value) * 100.0 / closedRows.Count, 1);
  258. }
  259. items.Add(new AdoS8QdcSummaryItemDto
  260. {
  261. Code = code,
  262. Title = title,
  263. Total = total,
  264. AvgProcessHours = avgHours,
  265. OnTimeCloseRate = onTimeCloseRate,
  266. CloseRate = closeRate,
  267. Remark = remark,
  268. });
  269. }
  270. return new AdoS8QdcSummaryDto { Items = items };
  271. }
  272. /// <summary>
  273. /// 异常监控汇总:按 module_code 分组统计红/黄/绿/超时数。
  274. /// 供综合全景页顶部徽标和模块汇总表使用。
  275. /// </summary>
  276. public async Task<AdoS8MonitoringSummaryDto> GetSummaryAsync(AdoS8MonitoringSummaryQueryDto q)
  277. {
  278. // 显式日期范围优先;未传显式范围时尝试从 period 解析。
  279. var (periodFrom, periodTo) = (!q.BizDateFrom.HasValue && !q.BizDateTo.HasValue)
  280. ? S8PeriodHelper.Resolve(q.Period)
  281. : (q.BizDateFrom, q.BizDateTo);
  282. var effectiveFrom = q.BizDateFrom ?? periodFrom;
  283. var effectiveTo = q.BizDateTo ?? periodTo;
  284. // 前端三专题页传入逗号分隔模块码("S1,S7" / "S2,S6" / "S3,S4,S5"),按 IN 过滤;空值/单值保持原语义。
  285. var moduleCodes = (q.ModuleCode ?? string.Empty)
  286. .Split(',', StringSplitOptions.RemoveEmptyEntries)
  287. .Select(s => s.Trim())
  288. .Where(s => s.Length > 0)
  289. .Distinct()
  290. .ToList();
  291. var query = _rep.AsQueryable()
  292. .Where(e => e.TenantId == q.TenantId && e.FactoryId == q.FactoryId && !e.IsDeleted)
  293. // TASK-002-RESET-DIMENSION-MODEL-DEV-4A:聚合源 module_code → stage_code。
  294. .Where(e => S8ModuleCode.All.Contains(e.StageCode))
  295. .WhereIF(!string.IsNullOrWhiteSpace(q.SceneCode), e => e.SceneCode == q.SceneCode)
  296. .WhereIF(moduleCodes.Count > 0, e => moduleCodes.Contains(e.StageCode))
  297. .WhereIF(effectiveFrom.HasValue, e => e.CreatedAt >= effectiveFrom!.Value)
  298. .WhereIF(effectiveTo.HasValue, e => e.CreatedAt < effectiveTo!.Value);
  299. // 聚合到内存(数据量在可控范围内,避免复杂 GROUP BY 兼容性问题)
  300. // S8-SLA-TIMEOUT-RUNTIME-1(P3):投影 SlaDeadline 替代 TimeoutFlag,timeout 改为运行时计算。
  301. var raw = await query
  302. .Select(e => new
  303. {
  304. ModuleCode = e.StageCode,
  305. e.SceneCode,
  306. e.Severity,
  307. e.SlaDeadline,
  308. e.Status
  309. })
  310. .ToListAsync();
  311. var nowForTimeout = DateTime.Now;
  312. // S8-OVERVIEW-STAGE-CARD-LIFECYCLE-COPY-AND-METRIC-FIX-1:超时口径 = SlaDeadline < now AND status NOT IN (CLOSED, RECOVERED)。
  313. // 按 severity 拆桶用于 stage card 「严重 N / 延误 M」「关注 N / 延误 M」展示。
  314. bool IsTimeout(DateTime? sla, string? status) =>
  315. sla != null && sla < nowForTimeout && status != "CLOSED" && status != "RECOVERED";
  316. var byModule = raw
  317. .GroupBy(e => new { mc = e.ModuleCode ?? string.Empty, sc = e.SceneCode ?? string.Empty })
  318. .Select(g => new AdoS8ModuleSummaryItem
  319. {
  320. ModuleCode = g.Key.mc,
  321. ModuleLabel = S8ModuleCode.Label(g.Key.mc),
  322. SceneCode = g.Key.sc,
  323. SceneLabel = S8SceneCode.Label(g.Key.sc),
  324. Total = g.Count(),
  325. // S8-SEVERITY-FOLLOW-SERIOUS-STANDARDIZE-EXEC-1:red=SERIOUS / yellow=FOLLOW;green=0(异常表无正常桶)。
  326. Red = g.Count(e => S8SeverityCode.IsSerious(e.Severity)),
  327. Yellow = g.Count(e => S8SeverityCode.IsFollow(e.Severity)),
  328. Green = 0,
  329. Timeout = g.Count(e => IsTimeout(e.SlaDeadline, e.Status)),
  330. SeriousTimeout = g.Count(e => S8SeverityCode.IsSerious(e.Severity) && IsTimeout(e.SlaDeadline, e.Status)),
  331. FollowTimeout = g.Count(e => S8SeverityCode.IsFollow(e.Severity) && IsTimeout(e.SlaDeadline, e.Status)),
  332. })
  333. // 按 S8ModuleCode.All 顺序排列
  334. .OrderBy(r => Array.IndexOf(S8ModuleCode.All, r.ModuleCode))
  335. .ToList();
  336. return new AdoS8MonitoringSummaryDto
  337. {
  338. Total = raw.Count,
  339. // S8-SEVERITY-FOLLOW-SERIOUS-STANDARDIZE-EXEC-1:red=SERIOUS / yellow=FOLLOW;green=0。
  340. Red = raw.Count(e => S8SeverityCode.IsSerious(e.Severity)),
  341. Yellow = raw.Count(e => S8SeverityCode.IsFollow(e.Severity)),
  342. Green = 0,
  343. Timeout = raw.Count(e => IsTimeout(e.SlaDeadline, e.Status)),
  344. SeriousTimeout = raw.Count(e => S8SeverityCode.IsSerious(e.Severity) && IsTimeout(e.SlaDeadline, e.Status)),
  345. FollowTimeout = raw.Count(e => S8SeverityCode.IsFollow(e.Severity) && IsTimeout(e.SlaDeadline, e.Status)),
  346. ByModule = byModule
  347. };
  348. }
  349. /// <summary>
  350. /// S8-DELIVERY-PAGE-TYPE-PRUNE-AND-TREND-ALIGN-1:Delivery 页近 N 日交付异常趋势。
  351. /// 口径:module_code IN (S1,S7) AND exception_type_code IN (ORDER_DUE_DATE_DELAY / DELIVERY_DELAY_WARNING);
  352. /// 时间字段 created_at;不排除 CLOSED;按日聚合,缺失日期补 0;days 限 1-30;
  353. /// Total = OrderDueDateDelay + DeliveryDelayWarning(避免历史 bucket.Count 含未承载类型导致 total 与图线不一致)。
  354. /// </summary>
  355. public async Task<AdoS8DeliveryTrendDto> GetDeliveryTrendAsync(long tenantId = 1, long factoryId = 1, int days = 7, string? period = null)
  356. {
  357. DateTime from, toExclusive;
  358. int effectiveDays;
  359. var (periodFrom, periodTo) = S8PeriodHelper.Resolve(period);
  360. if (periodFrom.HasValue && periodTo.HasValue)
  361. {
  362. from = periodFrom.Value;
  363. toExclusive = periodTo.Value;
  364. effectiveDays = Math.Max(1, Math.Min(90, (int)(toExclusive - from).TotalDays));
  365. }
  366. else
  367. {
  368. effectiveDays = Math.Clamp(days, 1, 30);
  369. var today = DateTime.Today;
  370. from = today.AddDays(-(effectiveDays - 1));
  371. toExclusive = today.AddDays(1);
  372. }
  373. var deliveryModules = new[] { "S1", "S7" };
  374. var deliveryTypes = new[] { "ORDER_DUE_DATE_DELAY", "DELIVERY_DELAY_WARNING" };
  375. var rows = await _rep.AsQueryable()
  376. .Where(e => e.TenantId == tenantId && e.FactoryId == factoryId && !e.IsDeleted)
  377. .Where(e => deliveryModules.Contains(e.StageCode))
  378. .Where(e => e.ExceptionTypeCode != null && deliveryTypes.Contains(e.ExceptionTypeCode))
  379. .Where(e => e.CreatedAt >= from && e.CreatedAt < toExclusive)
  380. .Select(e => new { e.ExceptionTypeCode, e.CreatedAt })
  381. .ToListAsync();
  382. var byDate = rows
  383. .GroupBy(r => r.CreatedAt.Date)
  384. .ToDictionary(g => g.Key, g => g.ToList());
  385. var dayList = new List<AdoS8DeliveryTrendDayDto>(effectiveDays);
  386. for (var i = 0; i < effectiveDays; i++)
  387. {
  388. var d = from.AddDays(i);
  389. var bucket = byDate.TryGetValue(d, out var list) ? list : new();
  390. var orderDueDateDelay = bucket.Count(r => r.ExceptionTypeCode == "ORDER_DUE_DATE_DELAY");
  391. var deliveryDelayWarning = bucket.Count(r => r.ExceptionTypeCode == "DELIVERY_DELAY_WARNING");
  392. dayList.Add(new AdoS8DeliveryTrendDayDto
  393. {
  394. Date = d.ToString("MM/dd"),
  395. RawDate = d.ToString("yyyy-MM-dd"),
  396. OrderDueDateDelay = orderDueDateDelay,
  397. DeliveryDelayWarning = deliveryDelayWarning,
  398. Total = orderDueDateDelay + deliveryDelayWarning,
  399. });
  400. }
  401. var totalSum = dayList.Sum(d => d.Total);
  402. var peak = dayList.OrderByDescending(d => d.Total).FirstOrDefault();
  403. var todayDay = dayList.Last();
  404. var yesterday = dayList.Count >= 2 ? dayList[^2] : null;
  405. double? changeRate = (yesterday is null || yesterday.Total == 0)
  406. ? (double?)null
  407. : Math.Round((todayDay.Total - yesterday.Total) * 100.0 / yesterday.Total, 1);
  408. var summary = new AdoS8DeliveryTrendSummaryDto
  409. {
  410. PeakValue = peak?.Total ?? 0,
  411. PeakDate = (peak is null || peak.Total == 0) ? null : peak.RawDate,
  412. AvgValue = Math.Round(totalSum / (double)effectiveDays, 2),
  413. TodayValue = todayDay.Total,
  414. TodayChangeRate = changeRate,
  415. };
  416. return new AdoS8DeliveryTrendDto { Days = dayList, Summary = summary };
  417. }
  418. /// <summary>
  419. /// S8-PROD-SUPPLY-TREND-CHART-REPLACE-DUPLICATE-SECTION-1:Production 页近 N 日生产异常趋势。
  420. /// 口径:module_code IN (S2,S6) AND exception_type_code IN (EQUIP_FAULT / MFG_MATERIAL_ABNORMAL / MFG_QUALITY_ABNORMAL);
  421. /// 时间字段 created_at;不排除 CLOSED;按日聚合,缺失日期补 0;days 限 1-30。
  422. /// </summary>
  423. public async Task<AdoS8ProductionTrendDto> GetProductionTrendAsync(long tenantId = 1, long factoryId = 1, int days = 7, string? period = null)
  424. {
  425. DateTime from, toExclusive;
  426. int effectiveDays;
  427. var (periodFrom, periodTo) = S8PeriodHelper.Resolve(period);
  428. if (periodFrom.HasValue && periodTo.HasValue)
  429. {
  430. from = periodFrom.Value;
  431. toExclusive = periodTo.Value;
  432. effectiveDays = Math.Max(1, Math.Min(90, (int)(toExclusive - from).TotalDays));
  433. }
  434. else
  435. {
  436. effectiveDays = Math.Clamp(days, 1, 30);
  437. var today = DateTime.Today;
  438. from = today.AddDays(-(effectiveDays - 1));
  439. toExclusive = today.AddDays(1);
  440. }
  441. var prodModules = new[] { "S2", "S6" };
  442. var prodTypes = new[]
  443. {
  444. "EQUIP_FAULT", "MFG_MATERIAL_ABNORMAL", "MFG_QUALITY_ABNORMAL",
  445. "BODY_PRODUCTION_DELAY_WARNING"
  446. };
  447. var rows = await _rep.AsQueryable()
  448. .Where(e => e.TenantId == tenantId && e.FactoryId == factoryId && !e.IsDeleted)
  449. .Where(e => prodModules.Contains(e.StageCode))
  450. .Where(e => e.ExceptionTypeCode != null && prodTypes.Contains(e.ExceptionTypeCode))
  451. .Where(e => e.CreatedAt >= from && e.CreatedAt < toExclusive)
  452. .Select(e => new { e.ExceptionTypeCode, e.CreatedAt })
  453. .ToListAsync();
  454. var byDate = rows.GroupBy(r => r.CreatedAt.Date).ToDictionary(g => g.Key, g => g.ToList());
  455. var dayList = new List<AdoS8ProductionTrendDayDto>(effectiveDays);
  456. for (var i = 0; i < effectiveDays; i++)
  457. {
  458. var d = from.AddDays(i);
  459. var bucket = byDate.TryGetValue(d, out var list) ? list : new();
  460. var ef = bucket.Count(r => r.ExceptionTypeCode == "EQUIP_FAULT");
  461. var mf = bucket.Count(r => r.ExceptionTypeCode == "MFG_MATERIAL_ABNORMAL");
  462. var qf = bucket.Count(r => r.ExceptionTypeCode == "MFG_QUALITY_ABNORMAL");
  463. dayList.Add(new AdoS8ProductionTrendDayDto
  464. {
  465. Date = d.ToString("MM/dd"),
  466. RawDate = d.ToString("yyyy-MM-dd"),
  467. EquipmentFault = ef,
  468. MaterialFault = mf,
  469. QualityFault = qf,
  470. Total = bucket.Count,
  471. });
  472. }
  473. var totalSum = dayList.Sum(d => d.Total);
  474. var peak = dayList.OrderByDescending(d => d.Total).FirstOrDefault();
  475. var todayDay = dayList.Last();
  476. var yesterday = dayList.Count >= 2 ? dayList[^2] : null;
  477. double? changeRate = (yesterday is null || yesterday.Total == 0)
  478. ? (double?)null
  479. : Math.Round((todayDay.Total - yesterday.Total) * 100.0 / yesterday.Total, 1);
  480. var summary = new AdoS8DeliveryTrendSummaryDto
  481. {
  482. PeakValue = peak?.Total ?? 0,
  483. PeakDate = (peak is null || peak.Total == 0) ? null : peak.RawDate,
  484. AvgValue = Math.Round(totalSum / (double)effectiveDays, 2),
  485. TodayValue = todayDay.Total,
  486. TodayChangeRate = changeRate,
  487. };
  488. return new AdoS8ProductionTrendDto { Days = dayList, Summary = summary };
  489. }
  490. /// <summary>
  491. /// S8-PROD-SUPPLY-TREND-CHART-REPLACE-DUPLICATE-SECTION-1:Supply 页近 N 日供应异常趋势。
  492. /// 口径:module_code IN (S3,S4,S5) AND exception_type_code IN 7 类(SUPPLIER_ETA_ISSUE / SUPPLIER_SHIP_ISSUE
  493. /// / WAREHOUSE_RECEIPT_ABNORMAL / IQC_ISSUE / WH_PUTAWAY_ISSUE / WORK_ORDER_KITTING_ABNORMAL / WORK_ORDER_ISSUE_ABNORMAL);
  494. /// 时间字段 created_at;不排除 CLOSED;按日聚合,缺失日期补 0;days 限 1-30。
  495. /// </summary>
  496. public async Task<AdoS8SupplyTrendDto> GetSupplyTrendAsync(long tenantId = 1, long factoryId = 1, int days = 7, string? period = null)
  497. {
  498. DateTime from, toExclusive;
  499. int effectiveDays;
  500. var (periodFrom, periodTo) = S8PeriodHelper.Resolve(period);
  501. if (periodFrom.HasValue && periodTo.HasValue)
  502. {
  503. from = periodFrom.Value;
  504. toExclusive = periodTo.Value;
  505. effectiveDays = Math.Max(1, Math.Min(90, (int)(toExclusive - from).TotalDays));
  506. }
  507. else
  508. {
  509. effectiveDays = Math.Clamp(days, 1, 30);
  510. var today = DateTime.Today;
  511. from = today.AddDays(-(effectiveDays - 1));
  512. toExclusive = today.AddDays(1);
  513. }
  514. var supplyModules = new[] { "S3", "S4", "S5" };
  515. var supplyTypes = new[]
  516. {
  517. "SUPPLIER_ETA_ISSUE", "SUPPLIER_SHIP_ISSUE", "WAREHOUSE_RECEIPT_ABNORMAL",
  518. "IQC_ISSUE", "WH_PUTAWAY_ISSUE", "WORK_ORDER_KITTING_ABNORMAL", "WORK_ORDER_ISSUE_ABNORMAL",
  519. "PURCHASE_EXECUTION_DELAY"
  520. };
  521. var rows = await _rep.AsQueryable()
  522. .Where(e => e.TenantId == tenantId && e.FactoryId == factoryId && !e.IsDeleted)
  523. .Where(e => supplyModules.Contains(e.StageCode))
  524. .Where(e => e.ExceptionTypeCode != null && supplyTypes.Contains(e.ExceptionTypeCode))
  525. .Where(e => e.CreatedAt >= from && e.CreatedAt < toExclusive)
  526. .Select(e => new { e.ExceptionTypeCode, e.CreatedAt })
  527. .ToListAsync();
  528. var byDate = rows.GroupBy(r => r.CreatedAt.Date).ToDictionary(g => g.Key, g => g.ToList());
  529. var dayList = new List<AdoS8SupplyTrendDayDto>(effectiveDays);
  530. for (var i = 0; i < effectiveDays; i++)
  531. {
  532. var d = from.AddDays(i);
  533. var bucket = byDate.TryGetValue(d, out var list) ? list : new();
  534. var s1 = bucket.Count(r => r.ExceptionTypeCode == "SUPPLIER_ETA_ISSUE");
  535. var s2 = bucket.Count(r => r.ExceptionTypeCode == "SUPPLIER_SHIP_ISSUE");
  536. var s3 = bucket.Count(r => r.ExceptionTypeCode == "WAREHOUSE_RECEIPT_ABNORMAL");
  537. var s4 = bucket.Count(r => r.ExceptionTypeCode == "IQC_ISSUE");
  538. var s5 = bucket.Count(r => r.ExceptionTypeCode == "WH_PUTAWAY_ISSUE");
  539. var s6 = bucket.Count(r => r.ExceptionTypeCode == "WORK_ORDER_KITTING_ABNORMAL");
  540. var s7 = bucket.Count(r => r.ExceptionTypeCode == "WORK_ORDER_ISSUE_ABNORMAL");
  541. dayList.Add(new AdoS8SupplyTrendDayDto
  542. {
  543. Date = d.ToString("MM/dd"),
  544. RawDate = d.ToString("yyyy-MM-dd"),
  545. SupplierEtaIssue = s1,
  546. SupplierShipIssue = s2,
  547. WarehouseReceiptAbnormal = s3,
  548. IqcIssue = s4,
  549. WarehousePutawayIssue = s5,
  550. WorkOrderKittingAbnormal = s6,
  551. WorkOrderIssueAbnormal = s7,
  552. Total = bucket.Count,
  553. });
  554. }
  555. var totalSum = dayList.Sum(d => d.Total);
  556. var peak = dayList.OrderByDescending(d => d.Total).FirstOrDefault();
  557. var todayDay = dayList.Last();
  558. var yesterday = dayList.Count >= 2 ? dayList[^2] : null;
  559. double? changeRate = (yesterday is null || yesterday.Total == 0)
  560. ? (double?)null
  561. : Math.Round((todayDay.Total - yesterday.Total) * 100.0 / yesterday.Total, 1);
  562. var summary = new AdoS8DeliveryTrendSummaryDto
  563. {
  564. PeakValue = peak?.Total ?? 0,
  565. PeakDate = (peak is null || peak.Total == 0) ? null : peak.RawDate,
  566. AvgValue = Math.Round(totalSum / (double)effectiveDays, 2),
  567. TodayValue = todayDay.Total,
  568. TodayChangeRate = changeRate,
  569. };
  570. return new AdoS8SupplyTrendDto { Days = dayList, Summary = summary };
  571. }
  572. /// <summary>
  573. /// S8-SIDEBAR-TYPE-CARD-WINDOW-TOGGLE-1:专题页右侧类型卡按 (domain, window) 统一聚合。
  574. /// 单一时间窗口下 total / open / closed / avgProcessHours / closeRate 共用同一分母。
  575. /// 公共过滤:tenant/factory + is_deleted=0 + module_code IN S1-S7 + exception_type_code IN domain 类型集 + created_at IN window。
  576. /// </summary>
  577. public async Task<AdoS8DomainTypeMetricsDto> GetDomainTypeMetricsAsync(string domain, string window, long tenantId = 1, long factoryId = 1, string? period = null)
  578. {
  579. var d = (domain ?? string.Empty).Trim().ToUpperInvariant();
  580. var w = (window ?? string.Empty).Trim().ToUpperInvariant();
  581. if (w != "LAST_24H" && w != "LAST_7D") w = "LAST_24H";
  582. (string key, string label, string typeCode)[] specs = d switch
  583. {
  584. // S8-DELIVERY-PAGE-TYPE-PRUNE-AND-TREND-ALIGN-1:Delivery 页类型卡收敛为 2 类;
  585. // 显示名「总装发货延期」仅作大屏展示,不改 ado_s8_exception_type.type_name。
  586. "DELIVERY" => new (string, string, string)[]
  587. {
  588. ("order-due-date-delay", "订单交期延期", "ORDER_DUE_DATE_DELAY"),
  589. ("delivery-delay-warning", "总装发货延期", "DELIVERY_DELAY_WARNING"),
  590. },
  591. "PRODUCTION" => new (string, string, string)[]
  592. {
  593. ("equipment-fault", "设备异常", "EQUIP_FAULT"),
  594. ("material-fault", "物料异常", "MFG_MATERIAL_ABNORMAL"),
  595. ("quality-fault", "质量异常", "MFG_QUALITY_ABNORMAL"),
  596. ("body-production-delay-warning", "本体生产延期预警", "BODY_PRODUCTION_DELAY_WARNING"),
  597. },
  598. "SUPPLY" => new (string, string, string)[]
  599. {
  600. ("supplier-reply-delay", "供应商回复交期异常", "SUPPLIER_ETA_ISSUE"),
  601. ("supplier-ship-fault", "供应商发货异常", "SUPPLIER_SHIP_ISSUE"),
  602. ("warehouse-receipt", "仓库收货异常", "WAREHOUSE_RECEIPT_ABNORMAL"),
  603. ("iqc-inspection", "IQC 检验异常", "IQC_ISSUE"),
  604. ("warehouse-shelving", "仓库上架入库异常", "WH_PUTAWAY_ISSUE"),
  605. ("work-order-prepare", "仓库工单备料异常", "WORK_ORDER_KITTING_ABNORMAL"),
  606. ("work-order-issue", "仓库工单发料异常", "WORK_ORDER_ISSUE_ABNORMAL"),
  607. ("purchase-execution-delay", "采购执行延期", "PURCHASE_EXECUTION_DELAY"),
  608. },
  609. _ => Array.Empty<(string, string, string)>(),
  610. };
  611. var typeCodes = specs.Select(s => s.typeCode).ToArray();
  612. if (typeCodes.Length == 0)
  613. {
  614. return new AdoS8DomainTypeMetricsDto { Domain = d, Window = w, Total = 0, Items = new() };
  615. }
  616. DateTime from, to;
  617. var (periodFrom, periodTo) = S8PeriodHelper.Resolve(period);
  618. if (periodFrom.HasValue && periodTo.HasValue)
  619. {
  620. from = periodFrom.Value;
  621. to = periodTo.Value;
  622. }
  623. else if (w == "LAST_7D")
  624. {
  625. // 与 trend 接口保持一致:[today-6, today+1)
  626. var today = DateTime.Today;
  627. from = today.AddDays(-6);
  628. to = today.AddDays(1);
  629. }
  630. else
  631. {
  632. // LAST_24H:滑动窗口 NOW()-24h ~ NOW()
  633. var now = DateTime.Now;
  634. from = now.AddHours(-24);
  635. to = now.AddMinutes(1);
  636. }
  637. var rows = await _rep.AsQueryable()
  638. .Where(e => e.TenantId == tenantId && e.FactoryId == factoryId && !e.IsDeleted)
  639. .Where(e => S8ModuleCode.All.Contains(e.StageCode))
  640. .Where(e => e.ExceptionTypeCode != null && typeCodes.Contains(e.ExceptionTypeCode))
  641. .Where(e => e.CreatedAt >= from && e.CreatedAt < to)
  642. .Select(e => new { e.ExceptionTypeCode, e.Status, e.CreatedAt, e.ClosedAt })
  643. .ToListAsync();
  644. var byType = rows.GroupBy(r => r.ExceptionTypeCode!).ToDictionary(g => g.Key, g => g.ToList());
  645. var items = specs.Select(s =>
  646. {
  647. var bucket = byType.TryGetValue(s.typeCode, out var list) ? list : new();
  648. var total = bucket.Count;
  649. var closedCount = bucket.Count(r => r.Status == "CLOSED");
  650. var openCount = total - closedCount;
  651. double? avgHours = null;
  652. var closedSamples = bucket.Where(r => r.ClosedAt.HasValue).ToList();
  653. if (closedSamples.Count > 0)
  654. {
  655. avgHours = Math.Round(closedSamples.Average(r => (r.ClosedAt!.Value - r.CreatedAt).TotalHours), 1);
  656. }
  657. double? closeRate = total == 0 ? null : Math.Round(closedCount * 100.0 / total, 1);
  658. return new AdoS8DomainTypeMetricItemDto
  659. {
  660. Key = s.key,
  661. Label = s.label,
  662. TypeCode = s.typeCode,
  663. Total = total,
  664. OpenCount = openCount,
  665. ClosedCount = closedCount,
  666. AvgProcessHours = avgHours,
  667. CloseRate = closeRate,
  668. };
  669. }).ToList();
  670. return new AdoS8DomainTypeMetricsDto
  671. {
  672. Domain = d,
  673. Window = w,
  674. Total = items.Sum(i => i.Total),
  675. Items = items,
  676. };
  677. }
  678. /// <summary>
  679. /// S9-RESULT-KPI-DEMO-BASELINE-AND-ORDER-FLOW-CALC-1:A+B 混合方案。
  680. /// 4 个 KPI(ORDER_DELIVERY_RATE/PO_DELIVERY_RATE/IQC_PASS_RATE/WO_COMPLETION_RATE)→ DEMO_BASELINE 演示基线;
  681. /// 1 个 KPI(ORDER_FLOW_CYCLE_RATIO)→ ORDER_FLOW_CALC 基于 ado_s8_order_flow_stage 半真实计算;
  682. /// 不写 DB / 不接 period / 不启用 watch_rule。
  683. /// 来源:ado_s8_monitor_metric WHERE mechanism='RATIO' AND is_result_kpi=1(保留字典顺序与 metricName)。
  684. /// </summary>
  685. public async Task<AdoS8ResultKpiSummaryDto> GetResultKpiSummaryAsync(long tenantId, long factoryId)
  686. {
  687. var rows = await _metricRep.AsQueryable()
  688. .Where(x => x.Mechanism == "RATIO" && x.IsResultKpi
  689. && ((x.TenantId == 0 && x.FactoryId == 0)
  690. || (x.TenantId == tenantId && x.FactoryId == factoryId)))
  691. .ToListAsync();
  692. var resolved = rows
  693. .GroupBy(x => x.MetricCode)
  694. .Select(g => g.OrderByDescending(x => x.FactoryId).ThenByDescending(x => x.TenantId).First())
  695. .OrderBy(x => x.SortNo)
  696. .ThenBy(x => x.MetricCode)
  697. .ToList();
  698. var items = new List<AdoS8ResultKpiItemDto>(resolved.Count);
  699. foreach (var m in resolved)
  700. {
  701. var unit = string.IsNullOrWhiteSpace(m.Unit) ? "%" : m.Unit!;
  702. if (_demoBaselineMap.TryGetValue(m.MetricCode, out var baseline))
  703. {
  704. items.Add(new AdoS8ResultKpiItemDto
  705. {
  706. MetricCode = m.MetricCode,
  707. MetricName = m.MetricName,
  708. ObjectCode = m.ObjectCode,
  709. Unit = unit,
  710. CurrentValue = baseline.CurrentValue,
  711. TargetRatio = baseline.TargetRatio,
  712. DictionaryEnabled = true,
  713. Remark = baseline.Remark,
  714. Source = "DEMO_BASELINE",
  715. });
  716. }
  717. else if (m.MetricCode == "ORDER_FLOW_CYCLE_RATIO")
  718. {
  719. var (cv, source) = await ComputeOrderFlowCycleRatioAsync(tenantId, factoryId);
  720. items.Add(new AdoS8ResultKpiItemDto
  721. {
  722. MetricCode = m.MetricCode,
  723. MetricName = m.MetricName,
  724. ObjectCode = m.ObjectCode,
  725. Unit = unit,
  726. CurrentValue = cv,
  727. TargetRatio = 90.0m,
  728. DictionaryEnabled = true,
  729. Remark = "基于已完成订单链路阶段 actual_days/planned_days 计算,pending 阶段暂不纳入",
  730. Source = source,
  731. });
  732. }
  733. else
  734. {
  735. items.Add(new AdoS8ResultKpiItemDto
  736. {
  737. MetricCode = m.MetricCode,
  738. MetricName = m.MetricName,
  739. ObjectCode = m.ObjectCode,
  740. Unit = unit,
  741. CurrentValue = null,
  742. TargetRatio = m.DefaultTargetRatio,
  743. DictionaryEnabled = false,
  744. Remark = m.Remark,
  745. Source = "PENDING_REAL",
  746. });
  747. }
  748. }
  749. return new AdoS8ResultKpiSummaryDto
  750. {
  751. Items = items,
  752. Source = "MIXED_BASELINE",
  753. };
  754. }
  755. private static readonly Dictionary<string, (decimal CurrentValue, decimal TargetRatio, string Remark)> _demoBaselineMap = new()
  756. {
  757. ["ORDER_DELIVERY_RATE"] = (92.0m, 95.0m, "演示基线,待真实订单交付口径接入"),
  758. ["PO_DELIVERY_RATE"] = (88.0m, 95.0m, "演示基线,待采购到货真实表接入"),
  759. ["IQC_PASS_RATE"] = (96.0m, 98.0m, "演示基线,待 IQC 检验真实表接入"),
  760. ["WO_COMPLETION_RATE"] = (90.0m, 95.0m, "演示基线,待工单完工真实表接入"),
  761. };
  762. /// <summary>
  763. /// 候选 A:actual_days IS NOT NULL 的已完成阶段中 actual_days <= planned_days 的占比。
  764. /// pending 阶段不纳入 denominator;不依赖 status 字段;按 tenant/factory 过滤。
  765. /// </summary>
  766. private async Task<(decimal? CurrentValue, string Source)> ComputeOrderFlowCycleRatioAsync(long tenantId, long factoryId)
  767. {
  768. try
  769. {
  770. var stages = await _orderFlowStageRep.AsQueryable()
  771. .Where(x => !x.IsDeleted && x.TenantId == tenantId && x.FactoryId == factoryId
  772. && x.ActualDays != null)
  773. .Select(x => new { x.ActualDays, x.PlannedDays })
  774. .ToListAsync();
  775. var denominator = stages.Count;
  776. if (denominator == 0) return (null, "ORDER_FLOW_CALC_EMPTY");
  777. var numerator = stages.Count(s => s.ActualDays!.Value <= s.PlannedDays);
  778. var value = Math.Round(numerator * 100m / denominator, 1);
  779. return (value, "ORDER_FLOW_CALC");
  780. }
  781. catch
  782. {
  783. return (null, "ORDER_FLOW_CALC_EMPTY");
  784. }
  785. }
  786. }