S8OrderFlowService.cs 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584
  1. using System.Text.Json;
  2. using Admin.NET.Plugin.AiDOP.Dto.S8.OrderFlow;
  3. using Admin.NET.Plugin.AiDOP.Entity.S8;
  4. using Admin.NET.Plugin.AiDOP.Entity.S8.OrderFlow;
  5. namespace Admin.NET.Plugin.AiDOP.Service.S8.OrderFlow;
  6. /// <summary>
  7. /// ORDER-FLOW-S8-INTEGRATED-DOMAIN-RESET-1 t3b:S8 订单执行链路只读 service skeleton。
  8. /// 仅 GetOrders / GetOrder / GetChain 三个方法;procurement-pivot / aggregate / related-exceptions 延后切片。
  9. /// 任何业务真值(订单总数 / 平均时长 / YY 真值矩阵等)只能来自 DB,本文件零硬编码。
  10. /// 异常计数:从 ado_s8_exception 实时聚合(SourceObjectType=SALES_ORDER + RelatedObjectCode in order_codes + IsDeleted=0)。
  11. /// </summary>
  12. public class S8OrderFlowService : ITransient
  13. {
  14. private const string ExceptionSourceObjectType = "SALES_ORDER";
  15. private const string ScopeBaselinePpt = "BASELINE_PPT";
  16. private const string ScopeCurrentFiltered = "CURRENT_FILTERED";
  17. private const string BaselineSnapshotCode = "CHAIN_AGGREGATE_BASELINE";
  18. private const string PivotTotalCode = "TOTAL";
  19. // ORDER-CHAIN-FINAL-ASSEMBLY-DEPT-COLLAB-MVP-1:异常类型 → 末端协同对象 映射常量。
  20. // 这些 type_code 均来自 ado_s8_exception_type seed 中 enabled=true、monitoring_category_key=FINAL_ASSEMBLY_DELIVERY 的子集;
  21. // 不新增异常类型、不依赖业务执行表。空数组对象(如 ASSEMBLY_COMPLETION / 包装材料准备)在前端展示 "--"。
  22. private const string FinalAssemblyObjectGoodsHandover = "GOODS_HANDOVER";
  23. private const string FinalAssemblyObjectShipmentConfirmation = "SHIPMENT_CONFIRMATION";
  24. private const string FinalAssemblyObjectShippingPlan = "SHIPPING_PLAN";
  25. private static readonly string[] GoodsHandoverExceptionTypes = { "PENDING_SHIPMENT" };
  26. private static readonly string[] ShipmentConfirmationExceptionTypes =
  27. {
  28. "DELIVERY_DELAY", "SHIPMENT_ABNORMAL", "DELIVERY_DELAY_WARNING", "FINISHED_GOODS_PENDING_SHIPMENT",
  29. };
  30. private static readonly string[] ShippingPlanExceptionTypes = { "FINISHED_GOODS_PENDING_SHIPMENT" };
  31. private static readonly JsonSerializerOptions JsonOpts = new()
  32. {
  33. PropertyNameCaseInsensitive = true,
  34. };
  35. private readonly SqlSugarRepository<AdoS8OrderFlowOrder> _orderRep;
  36. private readonly SqlSugarRepository<AdoS8OrderFlowStage> _stageRep;
  37. private readonly SqlSugarRepository<AdoS8OrderFlowSubstep> _substepRep;
  38. private readonly SqlSugarRepository<AdoS8OrderFlowSubstepUnit> _unitRep;
  39. private readonly SqlSugarRepository<AdoS8OrderFlowSnapshot> _snapshotRep;
  40. private readonly SqlSugarRepository<AdoS8OrderFlowProcurementPivot> _pivotRep;
  41. private readonly SqlSugarRepository<AdoS8Exception> _exceptionRep;
  42. private readonly SqlSugarRepository<AdoS8OrderFlowProductDesignDrawing> _pddRep;
  43. // S8-ORDER-CHAIN-BODY-PRODUCTION-ORDER-LEVEL-SEED-FIX-1:本体生产 3 表 repository。
  44. private readonly SqlSugarRepository<AdoS8OrderFlowManufacturingProcess> _mfgProcessRep;
  45. private readonly SqlSugarRepository<AdoS8OrderFlowManufacturingLossFactor> _mfgLossRep;
  46. private readonly SqlSugarRepository<AdoS8OrderFlowManufacturingOperator> _mfgOperatorRep;
  47. // S8-ORDER-CHAIN-ASSEMBLY-DELIVERY-DATA-LINEAGE-AUDIT-1:总装发货 2 表 repository。
  48. private readonly SqlSugarRepository<AdoS8OrderFlowFinalAssemblyGate> _faGateRep;
  49. private readonly SqlSugarRepository<AdoS8OrderFlowFinalAssemblyParallel> _faParallelRep;
  50. public S8OrderFlowService(
  51. SqlSugarRepository<AdoS8OrderFlowOrder> orderRep,
  52. SqlSugarRepository<AdoS8OrderFlowStage> stageRep,
  53. SqlSugarRepository<AdoS8OrderFlowSubstep> substepRep,
  54. SqlSugarRepository<AdoS8OrderFlowSubstepUnit> unitRep,
  55. SqlSugarRepository<AdoS8OrderFlowSnapshot> snapshotRep,
  56. SqlSugarRepository<AdoS8OrderFlowProcurementPivot> pivotRep,
  57. SqlSugarRepository<AdoS8Exception> exceptionRep,
  58. SqlSugarRepository<AdoS8OrderFlowProductDesignDrawing> pddRep,
  59. SqlSugarRepository<AdoS8OrderFlowManufacturingProcess> mfgProcessRep,
  60. SqlSugarRepository<AdoS8OrderFlowManufacturingLossFactor> mfgLossRep,
  61. SqlSugarRepository<AdoS8OrderFlowManufacturingOperator> mfgOperatorRep,
  62. SqlSugarRepository<AdoS8OrderFlowFinalAssemblyGate> faGateRep,
  63. SqlSugarRepository<AdoS8OrderFlowFinalAssemblyParallel> faParallelRep)
  64. {
  65. _orderRep = orderRep;
  66. _stageRep = stageRep;
  67. _substepRep = substepRep;
  68. _unitRep = unitRep;
  69. _snapshotRep = snapshotRep;
  70. _pivotRep = pivotRep;
  71. _exceptionRep = exceptionRep;
  72. _pddRep = pddRep;
  73. _mfgProcessRep = mfgProcessRep;
  74. _mfgLossRep = mfgLossRep;
  75. _mfgOperatorRep = mfgOperatorRep;
  76. _faGateRep = faGateRep;
  77. _faParallelRep = faParallelRep;
  78. }
  79. /// <summary>订单档案列表(无分页)。当前 baseline 20 单。</summary>
  80. public async Task<List<AdoS8OrderFlowOrderListItemDto>> GetOrdersAsync(AdoS8OrderFlowOrderQueryDto query)
  81. {
  82. var tenantId = query.TenantId ?? 1;
  83. var factoryId = query.FactoryId ?? 1;
  84. var orders = await _orderRep.AsQueryable()
  85. .Where(o => o.TenantId == tenantId && o.FactoryId == factoryId && !o.IsDeleted)
  86. .WhereIF(!string.IsNullOrWhiteSpace(query.Keyword),
  87. o => o.OrderCode.Contains(query.Keyword!)
  88. || o.ProductName.Contains(query.Keyword!)
  89. || o.CustomerName.Contains(query.Keyword!))
  90. .WhereIF(!string.IsNullOrWhiteSpace(query.CurrentFlowCode),
  91. o => o.CurrentOrderFlowCode == query.CurrentFlowCode!)
  92. .WhereIF(!string.IsNullOrWhiteSpace(query.CustomerCode),
  93. o => o.CustomerCode == query.CustomerCode!)
  94. .WhereIF(!string.IsNullOrWhiteSpace(query.ProductLine),
  95. o => o.ProductLine == query.ProductLine!)
  96. .WhereIF(!string.IsNullOrWhiteSpace(query.Region),
  97. o => o.Region == query.Region!)
  98. .WhereIF(!string.IsNullOrWhiteSpace(query.WorkflowStatus),
  99. o => o.WorkflowStatus == query.WorkflowStatus!)
  100. .WhereIF(!string.IsNullOrWhiteSpace(query.ScenarioCode),
  101. o => o.ScenarioCode == query.ScenarioCode!)
  102. .OrderBy(o => o.OrderCode)
  103. .ToListAsync();
  104. if (orders.Count == 0) return new List<AdoS8OrderFlowOrderListItemDto>();
  105. var orderCodes = orders.Select(o => o.OrderCode).Distinct().ToList();
  106. var orderIds = orders.Select(o => o.Id).ToList();
  107. var currentStages = await _stageRep.AsQueryable()
  108. .Where(s => s.TenantId == tenantId && s.FactoryId == factoryId && !s.IsDeleted)
  109. .Where(s => orderIds.Contains(s.OrderId))
  110. .ToListAsync();
  111. var currentStageMap = currentStages
  112. .GroupBy(s => s.OrderId)
  113. .ToDictionary(g => g.Key, g => g.ToList());
  114. var exceptionCounts = await MapExceptionCountsAsync(tenantId, factoryId, orderCodes);
  115. return orders.Select(o => MapOrderListItem(o, currentStageMap.GetValueOrDefault(o.Id), exceptionCounts)).ToList();
  116. }
  117. /// <summary>单订单详情(不含 substep/unit)。</summary>
  118. public async Task<AdoS8OrderFlowOrderDetailDto?> GetOrderAsync(string orderCode, long tenantId = 1, long factoryId = 1)
  119. {
  120. if (string.IsNullOrWhiteSpace(orderCode)) return null;
  121. var order = await _orderRep.AsQueryable()
  122. .Where(o => o.TenantId == tenantId && o.FactoryId == factoryId
  123. && !o.IsDeleted && o.OrderCode == orderCode)
  124. .FirstAsync();
  125. if (order == null) return null;
  126. var stages = await _stageRep.AsQueryable()
  127. .Where(s => s.TenantId == tenantId && s.FactoryId == factoryId
  128. && !s.IsDeleted && s.OrderId == order.Id)
  129. .OrderBy(s => s.SortNo)
  130. .ToListAsync();
  131. var exceptionCounts = await MapExceptionCountsAsync(tenantId, factoryId, new List<string> { orderCode });
  132. var listItem = MapOrderListItem(order, stages, exceptionCounts);
  133. return BuildDetail(listItem, stages, substepsByFlow: null, unitsBySubstepId: null);
  134. }
  135. /// <summary>订单链路视图:详情 + lifecycle + L2 substeps + L3 units。procurementPivot 留到 t3c。</summary>
  136. public async Task<AdoS8OrderFlowChainDto?> GetChainAsync(string orderCode, long tenantId = 1, long factoryId = 1)
  137. {
  138. if (string.IsNullOrWhiteSpace(orderCode)) return null;
  139. var order = await _orderRep.AsQueryable()
  140. .Where(o => o.TenantId == tenantId && o.FactoryId == factoryId
  141. && !o.IsDeleted && o.OrderCode == orderCode)
  142. .FirstAsync();
  143. if (order == null) return null;
  144. var stages = await _stageRep.AsQueryable()
  145. .Where(s => s.TenantId == tenantId && s.FactoryId == factoryId
  146. && !s.IsDeleted && s.OrderId == order.Id)
  147. .OrderBy(s => s.SortNo)
  148. .ToListAsync();
  149. var substeps = await _substepRep.AsQueryable()
  150. .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId
  151. && !x.IsDeleted && x.OrderId == order.Id)
  152. .OrderBy(x => x.SortNo)
  153. .ToListAsync();
  154. var substepsByFlow = substeps
  155. .GroupBy(x => x.OrderFlowCode)
  156. .ToDictionary(g => g.Key, g => g.ToList());
  157. var substepIds = substeps.Select(x => x.Id).ToList();
  158. var units = substepIds.Count == 0
  159. ? new List<AdoS8OrderFlowSubstepUnit>()
  160. : await _unitRep.AsQueryable()
  161. .Where(u => u.TenantId == tenantId && u.FactoryId == factoryId
  162. && !u.IsDeleted && substepIds.Contains(u.SubstepId))
  163. .OrderBy(u => u.SortNo)
  164. .ToListAsync();
  165. var unitsBySubstepId = units
  166. .GroupBy(u => u.SubstepId)
  167. .ToDictionary(g => g.Key, g => g.ToList());
  168. var exceptionCounts = await MapExceptionCountsAsync(tenantId, factoryId, new List<string> { orderCode });
  169. var listItem = MapOrderListItem(order, stages, exceptionCounts);
  170. var detail = BuildDetail(listItem, stages, substepsByFlow, unitsBySubstepId);
  171. return new AdoS8OrderFlowChainDto
  172. {
  173. Order = detail,
  174. ProcurementPivot = null, // t3c 切片接入
  175. };
  176. }
  177. // ─────────────── private mappers ───────────────
  178. /// <summary>从 ado_s8_exception 实时聚合每个 order_code 的异常计数 + 状态。</summary>
  179. private async Task<Dictionary<string, (int Count, string Status)>> MapExceptionCountsAsync(
  180. long tenantId, long factoryId, List<string> orderCodes)
  181. {
  182. var result = orderCodes.ToDictionary(c => c, _ => (Count: 0, Status: string.Empty));
  183. if (orderCodes.Count == 0) return result;
  184. var rows = await _exceptionRep.AsQueryable()
  185. .Where(e => e.TenantId == tenantId && e.FactoryId == factoryId && !e.IsDeleted)
  186. .Where(e => e.SourceObjectType == ExceptionSourceObjectType)
  187. .Where(e => orderCodes.Contains(e.RelatedObjectCode!))
  188. .Select(e => new { e.RelatedObjectCode, e.Severity })
  189. .ToListAsync();
  190. foreach (var grp in rows.Where(r => !string.IsNullOrEmpty(r.RelatedObjectCode))
  191. .GroupBy(r => r.RelatedObjectCode!))
  192. {
  193. var items = grp.ToList();
  194. var status = items.Any(x => string.Equals(x.Severity, "SERIOUS", StringComparison.OrdinalIgnoreCase))
  195. ? "SERIOUS"
  196. : (items.Count > 0 ? "FOLLOW" : string.Empty);
  197. result[grp.Key] = (items.Count, status);
  198. }
  199. return result;
  200. }
  201. private static AdoS8OrderFlowOrderListItemDto MapOrderListItem(
  202. AdoS8OrderFlowOrder o,
  203. List<AdoS8OrderFlowStage>? lifecycle,
  204. Dictionary<string, (int Count, string Status)> exceptionCounts)
  205. {
  206. var current = lifecycle?.FirstOrDefault(s => s.OrderFlowCode == o.CurrentOrderFlowCode);
  207. var counts = exceptionCounts.TryGetValue(o.OrderCode, out var c) ? c : (Count: 0, Status: string.Empty);
  208. return new AdoS8OrderFlowOrderListItemDto
  209. {
  210. OrderCode = o.OrderCode,
  211. ProductName = o.ProductName,
  212. ProductLine = o.ProductLine,
  213. CustomerCode = o.CustomerCode,
  214. CustomerName = o.CustomerName,
  215. CustomerType = o.CustomerType,
  216. Region = o.Region,
  217. Priority = o.Priority,
  218. WorkflowStatus = o.WorkflowStatus,
  219. CurrentOrderFlowCode = o.CurrentOrderFlowCode,
  220. CurrentOrderFlowName = OrderFlowConstants.ResolveName(o.CurrentOrderFlowCode),
  221. CurrentStatus = current?.Status ?? string.Empty,
  222. ReleaseAt = o.ReleaseAt,
  223. TargetCycleDays = o.TargetCycleDays,
  224. ActualCycleDays = o.ActualCycleDays,
  225. CurrentCycleDays = current?.ActualDays,
  226. NodeVarianceDays = current?.NodeVarianceDays,
  227. CumulativeVarianceDays = current?.CumulativeVarianceDays,
  228. ExceptionCount = counts.Count,
  229. ExceptionStatus = counts.Status,
  230. ResponseMinutes = o.ResponseMinutes,
  231. ProcessingMinutes = o.ProcessingMinutes,
  232. TotalLossMinutes = o.TotalLossMinutes,
  233. ScenarioCode = o.ScenarioCode,
  234. DataSource = o.DataSource,
  235. };
  236. }
  237. private static AdoS8OrderFlowOrderDetailDto BuildDetail(
  238. AdoS8OrderFlowOrderListItemDto listItem,
  239. List<AdoS8OrderFlowStage> stages,
  240. Dictionary<string, List<AdoS8OrderFlowSubstep>>? substepsByFlow,
  241. Dictionary<long, List<AdoS8OrderFlowSubstepUnit>>? unitsBySubstepId)
  242. {
  243. var detail = new AdoS8OrderFlowOrderDetailDto
  244. {
  245. OrderCode = listItem.OrderCode,
  246. ProductName = listItem.ProductName,
  247. ProductLine = listItem.ProductLine,
  248. CustomerCode = listItem.CustomerCode,
  249. CustomerName = listItem.CustomerName,
  250. CustomerType = listItem.CustomerType,
  251. Region = listItem.Region,
  252. Priority = listItem.Priority,
  253. WorkflowStatus = listItem.WorkflowStatus,
  254. CurrentOrderFlowCode = listItem.CurrentOrderFlowCode,
  255. CurrentOrderFlowName = listItem.CurrentOrderFlowName,
  256. CurrentStatus = listItem.CurrentStatus,
  257. ReleaseAt = listItem.ReleaseAt,
  258. TargetCycleDays = listItem.TargetCycleDays,
  259. ActualCycleDays = listItem.ActualCycleDays,
  260. CurrentCycleDays = listItem.CurrentCycleDays,
  261. NodeVarianceDays = listItem.NodeVarianceDays,
  262. CumulativeVarianceDays = listItem.CumulativeVarianceDays,
  263. ExceptionCount = listItem.ExceptionCount,
  264. ExceptionStatus = listItem.ExceptionStatus,
  265. ResponseMinutes = listItem.ResponseMinutes,
  266. ProcessingMinutes = listItem.ProcessingMinutes,
  267. TotalLossMinutes = listItem.TotalLossMinutes,
  268. ScenarioCode = listItem.ScenarioCode,
  269. DataSource = listItem.DataSource,
  270. Lifecycle = stages.Select(s => MapStage(s, substepsByFlow, unitsBySubstepId)).ToList(),
  271. };
  272. return detail;
  273. }
  274. private static AdoS8OrderFlowStageDto MapStage(
  275. AdoS8OrderFlowStage s,
  276. Dictionary<string, List<AdoS8OrderFlowSubstep>>? substepsByFlow,
  277. Dictionary<long, List<AdoS8OrderFlowSubstepUnit>>? unitsBySubstepId)
  278. {
  279. var substeps = substepsByFlow != null && substepsByFlow.TryGetValue(s.OrderFlowCode, out var list)
  280. ? list.Select(x => MapSubstep(x, unitsBySubstepId)).ToList()
  281. : new List<AdoS8OrderFlowSubstepDto>();
  282. return new AdoS8OrderFlowStageDto
  283. {
  284. OrderFlowCode = s.OrderFlowCode,
  285. OrderFlowName = string.IsNullOrEmpty(s.OrderFlowName)
  286. ? OrderFlowConstants.ResolveName(s.OrderFlowCode)
  287. : s.OrderFlowName,
  288. OwnerDept = s.OwnerDept,
  289. SortNo = s.SortNo,
  290. PlannedDays = s.PlannedDays,
  291. ActualDays = s.ActualDays,
  292. TargetAt = s.TargetAt,
  293. ActualStartAt = s.ActualStartAt,
  294. ActualEndAt = s.ActualEndAt,
  295. Status = s.Status,
  296. NodeVarianceDays = s.NodeVarianceDays,
  297. CumulativeVarianceDays = s.CumulativeVarianceDays,
  298. Substeps = substeps,
  299. };
  300. }
  301. private static AdoS8OrderFlowSubstepDto MapSubstep(
  302. AdoS8OrderFlowSubstep x,
  303. Dictionary<long, List<AdoS8OrderFlowSubstepUnit>>? unitsBySubstepId)
  304. {
  305. var units = unitsBySubstepId != null && unitsBySubstepId.TryGetValue(x.Id, out var list)
  306. ? list.Select(MapUnit).ToList()
  307. : new List<AdoS8OrderFlowSubstepUnitDto>();
  308. return new AdoS8OrderFlowSubstepDto
  309. {
  310. SubstepCode = x.SubstepCode,
  311. SubstepName = x.SubstepName,
  312. PiHours = x.PiHours,
  313. ActualHours = x.ActualHours,
  314. Status = x.Status,
  315. SortNo = x.SortNo,
  316. Units = units,
  317. };
  318. }
  319. private static AdoS8OrderFlowSubstepUnitDto MapUnit(AdoS8OrderFlowSubstepUnit u)
  320. => new()
  321. {
  322. UnitCode = u.UnitCode,
  323. UnitName = u.UnitName,
  324. PiHours = u.PiHours,
  325. ActualHours = u.ActualHours,
  326. Status = u.Status,
  327. SortNo = u.SortNo,
  328. };
  329. // ──────────────────────────────────────────────────────────────────────
  330. // t3c:Aggregate + ProcurementPivot
  331. // ──────────────────────────────────────────────────────────────────────
  332. /// <summary>
  333. /// 链路聚合视图:
  334. /// scope=BASELINE_PPT → 只读 ado_s8_order_flow_snapshot.stage_snapshots_json
  335. /// scope=CURRENT_FILTERED → 从 order + stage 实时聚合
  336. /// snapshot 缺失时返回空骨架(不做 fallback 硬编码)。
  337. /// </summary>
  338. public async Task<AdoS8OrderFlowAggregateDto> GetAggregateAsync(AdoS8OrderFlowAggregateQueryDto query)
  339. {
  340. var tenantId = query.TenantId ?? 1;
  341. var factoryId = query.FactoryId ?? 1;
  342. var scope = string.IsNullOrWhiteSpace(query.Scope) ? ScopeBaselinePpt : query.Scope;
  343. if (string.Equals(scope, ScopeBaselinePpt, StringComparison.OrdinalIgnoreCase))
  344. return await BuildBaselineAggregateAsync(tenantId, factoryId, scope);
  345. if (string.Equals(scope, ScopeCurrentFiltered, StringComparison.OrdinalIgnoreCase))
  346. return await BuildCurrentAggregateAsync(tenantId, factoryId, scope, query.OrderCodes);
  347. return EmptyAggregate(scope);
  348. }
  349. private async Task<AdoS8OrderFlowAggregateDto> BuildBaselineAggregateAsync(long tenantId, long factoryId, string scope)
  350. {
  351. var snapshot = await _snapshotRep.AsQueryable()
  352. .Where(s => s.TenantId == tenantId && s.FactoryId == factoryId && !s.IsDeleted)
  353. .Where(s => s.ScopeCode == ScopeBaselinePpt && s.SnapshotCode == BaselineSnapshotCode)
  354. .FirstAsync();
  355. if (snapshot == null) return EmptyAggregate(scope);
  356. var stages = ParseStageSnapshots(snapshot.StageSnapshotsJson);
  357. var collab = await BuildFinalAssemblyCollabSummaryAsync(tenantId, factoryId, orderCodes: null);
  358. return new AdoS8OrderFlowAggregateDto
  359. {
  360. Scope = scope,
  361. TotalOrders = snapshot.TotalOrders,
  362. TotalCustomers = snapshot.TotalCustomers,
  363. AvgResponseMinutes = snapshot.AvgResponseMinutes,
  364. AvgProcessingMinutes = snapshot.AvgProcessingMinutes,
  365. AvgLossMinutes = snapshot.AvgLossMinutes,
  366. StageAggregates = ReorderByCanonical(stages),
  367. FinalAssemblyCollabSummary = collab,
  368. };
  369. }
  370. private async Task<AdoS8OrderFlowAggregateDto> BuildCurrentAggregateAsync(
  371. long tenantId, long factoryId, string scope, List<string>? orderCodes)
  372. {
  373. var orders = await _orderRep.AsQueryable()
  374. .Where(o => o.TenantId == tenantId && o.FactoryId == factoryId && !o.IsDeleted)
  375. .WhereIF(orderCodes != null && orderCodes.Count > 0, o => orderCodes!.Contains(o.OrderCode))
  376. .ToListAsync();
  377. if (orders.Count == 0) return EmptyAggregate(scope);
  378. var orderIds = orders.Select(o => o.Id).ToList();
  379. var stages = await _stageRep.AsQueryable()
  380. .Where(s => s.TenantId == tenantId && s.FactoryId == factoryId && !s.IsDeleted)
  381. .Where(s => orderIds.Contains(s.OrderId))
  382. .ToListAsync();
  383. var responseList = orders.Where(o => o.ResponseMinutes.HasValue).Select(o => (decimal)o.ResponseMinutes!.Value).ToList();
  384. var processingList = orders.Where(o => o.ProcessingMinutes.HasValue).Select(o => (decimal)o.ProcessingMinutes!.Value).ToList();
  385. var lossList = orders.Where(o => o.TotalLossMinutes.HasValue).Select(o => (decimal)o.TotalLossMinutes!.Value).ToList();
  386. var stagesByFlow = stages.GroupBy(s => s.OrderFlowCode).ToDictionary(g => g.Key, g => g.ToList());
  387. var stageAggregates = new List<AdoS8OrderFlowStageAggregateDto>();
  388. foreach (var code in OrderFlowConstants.All)
  389. {
  390. stagesByFlow.TryGetValue(code, out var rows);
  391. stageAggregates.Add(BuildStageAggregateFromRows(code, rows ?? new List<AdoS8OrderFlowStage>()));
  392. }
  393. var collab = await BuildFinalAssemblyCollabSummaryAsync(tenantId, factoryId, orderCodes);
  394. return new AdoS8OrderFlowAggregateDto
  395. {
  396. Scope = scope,
  397. TotalOrders = orders.Count,
  398. TotalCustomers = orders.Select(o => o.CustomerCode).Where(c => !string.IsNullOrEmpty(c)).Distinct().Count(),
  399. AvgResponseMinutes = AvgOrZero(responseList),
  400. AvgProcessingMinutes = AvgOrZero(processingList),
  401. AvgLossMinutes = AvgOrZero(lossList),
  402. StageAggregates = stageAggregates,
  403. FinalAssemblyCollabSummary = collab,
  404. };
  405. }
  406. // ORDER-CHAIN-FINAL-ASSEMBLY-DEPT-COLLAB-MVP-1:FINAL_ASSEMBLY_DELIVERY 末端协同派生。
  407. // 仅查 ado_s8_exception 现有数据;只覆盖有真实映射的 2 个主门禁 + 1 个并行准备,其它 6 个对象前端展示 "--"。
  408. // 不读取 S0|S4 业务表;不新增表 / seed / 异常类型。
  409. private async Task<AdoS8FinalAssemblyCollabSummaryDto> BuildFinalAssemblyCollabSummaryAsync(
  410. long tenantId, long factoryId, List<string>? orderCodes)
  411. {
  412. var allTypes = GoodsHandoverExceptionTypes
  413. .Concat(ShipmentConfirmationExceptionTypes)
  414. .Concat(ShippingPlanExceptionTypes)
  415. .Distinct()
  416. .ToList();
  417. var rows = await _exceptionRep.AsQueryable()
  418. .Where(e => e.TenantId == tenantId && e.FactoryId == factoryId && !e.IsDeleted)
  419. .Where(e => e.SourceObjectType == ExceptionSourceObjectType)
  420. .Where(e => e.ExceptionTypeCode != null && allTypes.Contains(e.ExceptionTypeCode!))
  421. .WhereIF(orderCodes != null && orderCodes.Count > 0,
  422. e => e.RelatedObjectCode != null && orderCodes!.Contains(e.RelatedObjectCode!))
  423. .Select(e => new ExceptionAttribution
  424. {
  425. ExceptionTypeCode = e.ExceptionTypeCode,
  426. RelatedObjectCode = e.RelatedObjectCode,
  427. Title = e.Title,
  428. Severity = e.Severity,
  429. CreatedAt = e.CreatedAt,
  430. })
  431. .ToListAsync();
  432. return new AdoS8FinalAssemblyCollabSummaryDto
  433. {
  434. Gates = new Dictionary<string, AdoS8FinalAssemblyObjectStatDto>
  435. {
  436. [FinalAssemblyObjectGoodsHandover] = BuildObjectStat(rows, GoodsHandoverExceptionTypes, isGate: true),
  437. [FinalAssemblyObjectShipmentConfirmation] = BuildObjectStat(rows, ShipmentConfirmationExceptionTypes, isGate: true),
  438. },
  439. Parallels = new Dictionary<string, AdoS8FinalAssemblyObjectStatDto>
  440. {
  441. [FinalAssemblyObjectShippingPlan] = BuildObjectStat(rows, ShippingPlanExceptionTypes, isGate: false),
  442. },
  443. };
  444. }
  445. private static AdoS8FinalAssemblyObjectStatDto BuildObjectStat(
  446. List<ExceptionAttribution> rows, string[] candidateTypes, bool isGate)
  447. {
  448. var subset = rows.Where(r => r.ExceptionTypeCode != null && candidateTypes.Contains(r.ExceptionTypeCode!)).ToList();
  449. var count = subset
  450. .Where(r => !string.IsNullOrEmpty(r.RelatedObjectCode))
  451. .Select(r => r.RelatedObjectCode!)
  452. .Distinct()
  453. .Count();
  454. var top = subset
  455. .OrderByDescending(r => string.Equals(r.Severity, "SERIOUS", StringComparison.OrdinalIgnoreCase) ? 1 : 0)
  456. .ThenByDescending(r => r.CreatedAt)
  457. .FirstOrDefault();
  458. return new AdoS8FinalAssemblyObjectStatDto
  459. {
  460. ImpactedOrderCount = isGate ? count : (int?)null,
  461. RiskOrderCount = isGate ? (int?)null : count,
  462. TopRiskTitle = top?.Title,
  463. TopRiskSeverity = top?.Severity,
  464. };
  465. }
  466. private sealed class ExceptionAttribution
  467. {
  468. public string? ExceptionTypeCode { get; set; }
  469. public string? RelatedObjectCode { get; set; }
  470. public string? Title { get; set; }
  471. public string? Severity { get; set; }
  472. public DateTime CreatedAt { get; set; }
  473. }
  474. private static AdoS8OrderFlowStageAggregateDto BuildStageAggregateFromRows(string flowCode, List<AdoS8OrderFlowStage> rows)
  475. {
  476. var dto = new AdoS8OrderFlowStageAggregateDto
  477. {
  478. OrderFlowCode = flowCode,
  479. OrderFlowName = OrderFlowConstants.ResolveName(flowCode),
  480. };
  481. if (rows.Count == 0) return dto;
  482. var plannedList = rows.Select(r => r.PlannedDays).ToList();
  483. var actualList = rows.Where(r => r.ActualDays.HasValue && !string.Equals(r.Status, "pending", StringComparison.OrdinalIgnoreCase))
  484. .Select(r => r.ActualDays!.Value).ToList();
  485. var green = rows.Count(r => string.Equals(r.Status, "green", StringComparison.OrdinalIgnoreCase));
  486. var yellow = rows.Count(r => string.Equals(r.Status, "yellow", StringComparison.OrdinalIgnoreCase));
  487. var red = rows.Count(r => string.Equals(r.Status, "red", StringComparison.OrdinalIgnoreCase));
  488. var pending = rows.Count(r => string.Equals(r.Status, "pending", StringComparison.OrdinalIgnoreCase));
  489. var total = rows.Count;
  490. dto.KpiAvgDays = AvgOrZero(plannedList);
  491. dto.ActualAvgDays = AvgOrZero(actualList);
  492. dto.Green = green;
  493. dto.Yellow = yellow;
  494. dto.Red = red;
  495. dto.Pending = pending;
  496. // 整数百分比;total 不含 0 因为上面已 short-circuit。 percent 因子 100 是公式系数,非业务真值。
  497. dto.OnTimeRate = total > 0 ? (int)Math.Round(green * 100.0 / total) : 0;
  498. return dto;
  499. }
  500. private static List<AdoS8OrderFlowStageAggregateDto> ParseStageSnapshots(string? json)
  501. {
  502. if (string.IsNullOrWhiteSpace(json)) return new List<AdoS8OrderFlowStageAggregateDto>();
  503. try
  504. {
  505. var parsed = JsonSerializer.Deserialize<List<AdoS8OrderFlowStageAggregateDto>>(json, JsonOpts);
  506. return parsed ?? new List<AdoS8OrderFlowStageAggregateDto>();
  507. }
  508. catch (JsonException)
  509. {
  510. return new List<AdoS8OrderFlowStageAggregateDto>();
  511. }
  512. }
  513. /// <summary>按 OrderFlowConstants.All 重排;缺失 code 补空骨架;多余 code 追加在尾部以避免静默丢数据。</summary>
  514. private static List<AdoS8OrderFlowStageAggregateDto> ReorderByCanonical(List<AdoS8OrderFlowStageAggregateDto> input)
  515. {
  516. var byCode = input.Where(x => !string.IsNullOrEmpty(x.OrderFlowCode))
  517. .GroupBy(x => x.OrderFlowCode)
  518. .ToDictionary(g => g.Key, g => g.First());
  519. var ordered = new List<AdoS8OrderFlowStageAggregateDto>();
  520. foreach (var code in OrderFlowConstants.All)
  521. {
  522. if (byCode.TryGetValue(code, out var hit))
  523. {
  524. if (string.IsNullOrEmpty(hit.OrderFlowName))
  525. hit.OrderFlowName = OrderFlowConstants.ResolveName(code);
  526. ordered.Add(hit);
  527. byCode.Remove(code);
  528. }
  529. else
  530. {
  531. ordered.Add(new AdoS8OrderFlowStageAggregateDto
  532. {
  533. OrderFlowCode = code,
  534. OrderFlowName = OrderFlowConstants.ResolveName(code),
  535. });
  536. }
  537. }
  538. ordered.AddRange(byCode.Values);
  539. return ordered;
  540. }
  541. private static AdoS8OrderFlowAggregateDto EmptyAggregate(string scope)
  542. {
  543. var stages = OrderFlowConstants.All
  544. .Select(code => new AdoS8OrderFlowStageAggregateDto
  545. {
  546. OrderFlowCode = code,
  547. OrderFlowName = OrderFlowConstants.ResolveName(code),
  548. })
  549. .ToList();
  550. return new AdoS8OrderFlowAggregateDto { Scope = scope, StageAggregates = stages };
  551. }
  552. private static decimal AvgOrZero(List<decimal> values)
  553. => values.Count == 0 ? 0m : values.Average();
  554. /// <summary>
  555. /// 采购透视视图:
  556. /// scope=BASELINE_PPT → 读 ado_s8_order_flow_procurement_pivot baseline 行(order_id IS NULL)。
  557. /// scope=CURRENT_FILTERED → 读订单级行(order_id IS NOT NULL)并按 orderCodes 过滤后聚合:
  558. /// cycle_days 简单平均;impact_count 求和(语义:多订单合计影响台次);
  559. /// kit_rate 简单平均;status 按聚合后 cycle_days 三档阈值重判
  560. /// (与 baseline seed 一致:≤15 green / ≤20 yellow / &gt;20 red)。
  561. /// 其它 scope → 返回空骨架并回显 scope。
  562. /// orderCodes 为空时返回空骨架,不静默 fallback baseline(避免 baseline 泄漏到单订单态)。
  563. /// data_source 优先级:IMPORT / AGG &gt; SEED;同一 (order_code, material, supplier, spec) 上
  564. /// 若 IMPORT/AGG 行存在,只采用 IMPORT/AGG;SEED 仅作过渡兜底,便于真实数据源接入后无缝替换。
  565. /// status 来源:baseline 直接读 row.Status;CURRENT_FILTERED 聚合后按阈值重判(运行期重新分类,
  566. /// 不修改 seed 行)。cycle_days 保持 decimal(6,3) 不截断。
  567. /// </summary>
  568. public async Task<AdoS8OrderFlowProcurementPivotDto> GetProcurementPivotAsync(AdoS8OrderFlowProcurementPivotQueryDto query)
  569. {
  570. var tenantId = query.TenantId ?? 1;
  571. var factoryId = query.FactoryId ?? 1;
  572. var scope = string.IsNullOrWhiteSpace(query.Scope) ? ScopeBaselinePpt : query.Scope;
  573. if (string.Equals(scope, ScopeBaselinePpt, StringComparison.OrdinalIgnoreCase))
  574. {
  575. var baselineRows = await _pivotRep.AsQueryable()
  576. .Where(p => p.TenantId == tenantId && p.FactoryId == factoryId && !p.IsDeleted)
  577. .Where(p => p.OrderId == null) // baseline 行
  578. .ToListAsync();
  579. return BuildPivot(scope, baselineRows);
  580. }
  581. if (string.Equals(scope, ScopeCurrentFiltered, StringComparison.OrdinalIgnoreCase))
  582. {
  583. // 与产品设计 drawings API 一致:orderCodes 由 CSV 解析(trim / 去空 / Distinct)。
  584. var orderCodes = ParseOrderCodesCsv(query.OrderCodes);
  585. if (orderCodes.Count == 0)
  586. return new AdoS8OrderFlowProcurementPivotDto { Scope = scope };
  587. var orderLevelRows = await _pivotRep.AsQueryable()
  588. .Where(p => p.TenantId == tenantId && p.FactoryId == factoryId && !p.IsDeleted)
  589. .Where(p => p.OrderId != null && p.OrderCode != null)
  590. .Where(p => orderCodes.Contains(p.OrderCode!))
  591. .ToListAsync();
  592. if (orderLevelRows.Count == 0)
  593. return new AdoS8OrderFlowProcurementPivotDto { Scope = scope };
  594. var preferred = SelectPreferredDataSourceRows(orderLevelRows);
  595. var aggregated = AggregateOrderLevelRows(preferred);
  596. return BuildPivot(scope, aggregated);
  597. }
  598. return new AdoS8OrderFlowProcurementPivotDto { Scope = scope };
  599. }
  600. /// <summary>
  601. /// data_source 优先级:同一 (order_code, material, supplier, spec) 同时存在 IMPORT/AGG 与 SEED 时,
  602. /// 只保留 IMPORT/AGG 行;SEED 仅在 IMPORT/AGG 缺失时作为兜底。便于真实数据源接入后无缝替换 SEED。
  603. /// </summary>
  604. private static List<AdoS8OrderFlowProcurementPivot> SelectPreferredDataSourceRows(
  605. List<AdoS8OrderFlowProcurementPivot> rows)
  606. {
  607. var grouped = rows.GroupBy(r => (r.OrderCode, r.MaterialCode, r.SupplierCode, r.SpecCode));
  608. var result = new List<AdoS8OrderFlowProcurementPivot>(rows.Count);
  609. foreach (var g in grouped)
  610. {
  611. var preferred = g.FirstOrDefault(r =>
  612. string.Equals(r.DataSource, "IMPORT", StringComparison.OrdinalIgnoreCase) ||
  613. string.Equals(r.DataSource, "AGG", StringComparison.OrdinalIgnoreCase));
  614. result.Add(preferred ?? g.First());
  615. }
  616. return result;
  617. }
  618. /// <summary>
  619. /// 多订单聚合:按 (material, supplier, spec) 分组后简单平均;单订单时分组内只 1 行,聚合等于原值。
  620. /// cycle_days 平均;impact_count 求和;kit_rate 平均;status 按聚合后 cycle_days 阈值重判。
  621. /// 不补造缺位单元;聚合产物为非持久化 Pivot 对象供 BuildPivot 复用。
  622. /// </summary>
  623. private static List<AdoS8OrderFlowProcurementPivot> AggregateOrderLevelRows(
  624. List<AdoS8OrderFlowProcurementPivot> rows)
  625. {
  626. return rows
  627. .GroupBy(r => (r.MaterialCode, r.SupplierCode, r.SpecCode))
  628. .Select(g =>
  629. {
  630. var cycle = decimal.Round(g.Average(r => r.CycleDays), 3);
  631. var impactRows = g.Where(r => r.ImpactCount.HasValue).ToList();
  632. int? impactSum = impactRows.Count == 0 ? null : impactRows.Sum(r => r.ImpactCount!.Value);
  633. var kitRows = g.Where(r => r.KitRate.HasValue).ToList();
  634. decimal? kitAvg = kitRows.Count == 0
  635. ? null
  636. : decimal.Round(kitRows.Average(r => r.KitRate!.Value), 4);
  637. return new AdoS8OrderFlowProcurementPivot
  638. {
  639. Id = 0,
  640. OrderId = null,
  641. OrderCode = null,
  642. MaterialCode = g.Key.MaterialCode,
  643. SupplierCode = g.Key.SupplierCode,
  644. SpecCode = g.Key.SpecCode,
  645. CycleDays = cycle,
  646. Status = ClassifyAggregatedStatus(cycle),
  647. ImpactCount = impactSum,
  648. KitRate = kitAvg,
  649. ScenarioCode = string.Empty,
  650. DataSource = string.Empty,
  651. TenantId = 0,
  652. FactoryId = 0,
  653. IsDeleted = false,
  654. };
  655. })
  656. .ToList();
  657. }
  658. private static string ClassifyAggregatedStatus(decimal cycleDays)
  659. {
  660. if (cycleDays <= 15.0m) return "green";
  661. if (cycleDays <= 20.0m) return "yellow";
  662. return "red";
  663. }
  664. private static AdoS8OrderFlowProcurementPivotDto BuildPivot(string scope, List<AdoS8OrderFlowProcurementPivot> rows)
  665. {
  666. var result = new AdoS8OrderFlowProcurementPivotDto { Scope = scope };
  667. if (rows.Count == 0) return result;
  668. var byMaterial = rows.GroupBy(r => r.MaterialCode)
  669. .ToDictionary(g => g.Key, g => g.ToList());
  670. foreach (var (material, list) in byMaterial.OrderBy(kv => kv.Key, StringComparer.Ordinal))
  671. {
  672. // KeyMaterials:取 (supplier=TOTAL, spec=TOTAL) 单元作为该 material 的概览
  673. var grand = list.FirstOrDefault(r => r.SupplierCode == PivotTotalCode && r.SpecCode == PivotTotalCode);
  674. if (grand != null)
  675. {
  676. result.KeyMaterials.Add(new AdoS8OrderFlowKeyMaterialDto
  677. {
  678. MaterialCode = material,
  679. AvgCycleDays = grand.CycleDays,
  680. CycleStatus = grand.Status,
  681. ImpactCount = grand.ImpactCount,
  682. KitRate = grand.KitRate,
  683. ResultStatus = grand.Status,
  684. });
  685. }
  686. // SupplierBreakdown:spec=TOTAL 的所有 supplier 行(含 supplier=TOTAL)
  687. foreach (var row in list.Where(r => r.SpecCode == PivotTotalCode)
  688. .OrderBy(r => r.SupplierCode == PivotTotalCode ? 1 : 0)
  689. .ThenBy(r => r.SupplierCode, StringComparer.Ordinal))
  690. {
  691. result.SupplierBreakdown.Add(new AdoS8OrderFlowSupplierBreakdownDto
  692. {
  693. MaterialCode = material,
  694. SupplierCode = row.SupplierCode,
  695. AvgCycleDays = row.CycleDays,
  696. Status = row.Status,
  697. });
  698. }
  699. // SpecBreakdown:supplier=TOTAL 的所有 spec 行(含 spec=TOTAL)
  700. foreach (var row in list.Where(r => r.SupplierCode == PivotTotalCode)
  701. .OrderBy(r => r.SpecCode == PivotTotalCode ? 1 : 0)
  702. .ThenBy(r => r.SpecCode, StringComparer.Ordinal))
  703. {
  704. result.SpecBreakdown.Add(new AdoS8OrderFlowSpecBreakdownDto
  705. {
  706. MaterialCode = material,
  707. SpecCode = row.SpecCode,
  708. AvgCycleDays = row.CycleDays,
  709. Status = row.Status,
  710. });
  711. }
  712. // MatrixByMaterial:每个 supplier 一行,cells keyed by spec_code(保留全部 cycle_days 精度)
  713. var matrix = list.GroupBy(r => r.SupplierCode)
  714. .OrderBy(g => g.Key == PivotTotalCode ? 1 : 0)
  715. .ThenBy(g => g.Key, StringComparer.Ordinal)
  716. .Select(g => new AdoS8OrderFlowProcurementMatrixRowDto
  717. {
  718. SupplierCode = g.Key,
  719. Cells = g.ToDictionary(
  720. r => r.SpecCode,
  721. r => new AdoS8OrderFlowProcurementMatrixCellDto
  722. {
  723. CycleDays = r.CycleDays,
  724. Status = r.Status,
  725. }),
  726. })
  727. .ToList();
  728. result.MatrixByMaterial[material] = matrix;
  729. }
  730. return result;
  731. }
  732. // ──────────────────────────────────────────────────────────────────────
  733. // S8-ORDER-CHAIN-PRODUCT-DESIGN-DRAWING-PERSIST-1:产品设计图号粒度聚合。
  734. // 单一数据源 = ado_s8_order_flow_product_design_drawing 表;
  735. // 台数 / 占比 / 加权达成率 全部由 product_quantity 字段驱动;
  736. // 平均设计周期 = actual_days 算术平均(非 quantity 加权);
  737. // summary.categories 固定返回 STANDARD / NON_STANDARD / TOTAL 三档;
  738. // drawings 按 productType 过滤;未达标优先 + actualDays 降序 + orderCode/drawingNo 升序。
  739. // ──────────────────────────────────────────────────────────────────────
  740. private const string ProductDesignTypeStandard = "STANDARD";
  741. private const string ProductDesignTypeNonStandard = "NON_STANDARD";
  742. private const string ProductDesignTypeTotal = "TOTAL";
  743. private const decimal ProductDesignStageKpiDays = 3m;
  744. // S8-ORDER-CHAIN-PRODUCT-DESIGN-PPT-STATIC-AND-SINGLE-ORDER-ALIGN-1:
  745. // 非标产品 KPI 与常规产品同阶段标准 3 天;非标 actual_days 超 3 时记 red/未达标。
  746. private const decimal ProductDesignNonStandardKpiDays = 3m;
  747. public async Task<AdoS8OrderFlowProductDesignDrawingsDto> GetProductDesignDrawingsAsync(
  748. AdoS8OrderFlowProductDesignDrawingsQueryDto query)
  749. {
  750. var tenantId = query.TenantId ?? 1;
  751. var factoryId = query.FactoryId ?? 1;
  752. var orderCodes = ParseOrderCodesCsv(query.OrderCodes);
  753. var productTypeFilter = NormalizeProductDesignType(query.ProductType);
  754. var scope = orderCodes.Count == 0 ? ScopeBaselinePpt : ScopeCurrentFiltered;
  755. var rows = await _pddRep.AsQueryable()
  756. .Where(d => d.TenantId == tenantId && d.FactoryId == factoryId && !d.IsDeleted)
  757. .WhereIF(orderCodes.Count > 0, d => orderCodes.Contains(d.OrderCode))
  758. .ToListAsync();
  759. // summary 始终基于命中订单范围的全分类汇总(不受 productType 过滤影响),让前端可同时渲染三档汇总。
  760. var summary = BuildProductDesignSummary(rows);
  761. var drawingItems = rows.AsEnumerable();
  762. if (productTypeFilter != null)
  763. drawingItems = drawingItems.Where(d => d.ProductType == productTypeFilter);
  764. var orderedDrawings = drawingItems
  765. .OrderBy(d => d.IsAchieved)
  766. .ThenByDescending(d => d.ActualDays ?? decimal.MinValue)
  767. .ThenBy(d => d.OrderCode, StringComparer.Ordinal)
  768. .ThenBy(d => d.DrawingNo, StringComparer.Ordinal)
  769. .Select(MapProductDesignDrawingItem)
  770. .ToList();
  771. return new AdoS8OrderFlowProductDesignDrawingsDto
  772. {
  773. Scope = scope,
  774. Filter = new AdoS8OrderFlowProductDesignFilterDto
  775. {
  776. OrderCodes = orderCodes,
  777. ProductType = productTypeFilter,
  778. },
  779. Summary = summary,
  780. Drawings = orderedDrawings,
  781. };
  782. }
  783. private static List<string> ParseOrderCodesCsv(string? raw)
  784. {
  785. if (string.IsNullOrWhiteSpace(raw)) return new List<string>();
  786. return raw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
  787. .Where(s => !string.IsNullOrWhiteSpace(s))
  788. .Distinct(StringComparer.Ordinal)
  789. .ToList();
  790. }
  791. private static string? NormalizeProductDesignType(string? raw)
  792. {
  793. if (string.IsNullOrWhiteSpace(raw)) return null;
  794. var s = raw.Trim().ToUpperInvariant();
  795. return s == ProductDesignTypeStandard || s == ProductDesignTypeNonStandard ? s : null;
  796. }
  797. private static AdoS8OrderFlowProductDesignSummaryDto BuildProductDesignSummary(
  798. List<AdoS8OrderFlowProductDesignDrawing> rows)
  799. {
  800. var stdRows = rows.Where(r => r.ProductType == ProductDesignTypeStandard).ToList();
  801. var nonStdRows = rows.Where(r => r.ProductType == ProductDesignTypeNonStandard).ToList();
  802. var grandTotalQty = rows.Sum(r => r.ProductQuantity);
  803. return new AdoS8OrderFlowProductDesignSummaryDto
  804. {
  805. Overall = BuildProductDesignOverall(rows),
  806. Categories = new List<AdoS8OrderFlowProductDesignCategorySummaryDto>
  807. {
  808. BuildProductDesignCategory(ProductDesignTypeStandard, "常规产品", ProductDesignStageKpiDays, stdRows, grandTotalQty),
  809. BuildProductDesignCategory(ProductDesignTypeNonStandard, "非标产品", ProductDesignNonStandardKpiDays, nonStdRows, grandTotalQty),
  810. BuildProductDesignCategory(ProductDesignTypeTotal, "合计", ProductDesignStageKpiDays, rows, grandTotalQty),
  811. },
  812. };
  813. }
  814. private static AdoS8OrderFlowProductDesignOverallSummaryDto BuildProductDesignOverall(
  815. List<AdoS8OrderFlowProductDesignDrawing> rows)
  816. {
  817. var totalQty = rows.Sum(r => r.ProductQuantity);
  818. var achievedQty = rows.Where(r => r.IsAchieved).Sum(r => r.ProductQuantity);
  819. var actualDays = rows.Where(r => r.ActualDays.HasValue).Select(r => r.ActualDays!.Value).ToList();
  820. return new AdoS8OrderFlowProductDesignOverallSummaryDto
  821. {
  822. DrawingCount = rows.Select(r => r.DrawingNo).Distinct(StringComparer.Ordinal).Count(),
  823. TotalQuantity = totalQty,
  824. KpiDays = ProductDesignStageKpiDays,
  825. AvgActualDays = actualDays.Count == 0 ? 0m : actualDays.Average(),
  826. AchievementRate = totalQty == 0 ? 0m : (decimal)achievedQty / totalQty,
  827. };
  828. }
  829. private static AdoS8OrderFlowProductDesignCategorySummaryDto BuildProductDesignCategory(
  830. string productType,
  831. string name,
  832. decimal kpiDays,
  833. List<AdoS8OrderFlowProductDesignDrawing> rows,
  834. int grandTotalQty)
  835. {
  836. var totalQty = rows.Sum(r => r.ProductQuantity);
  837. var achievedQty = rows.Where(r => r.IsAchieved).Sum(r => r.ProductQuantity);
  838. var actualDays = rows.Where(r => r.ActualDays.HasValue).Select(r => r.ActualDays!.Value).ToList();
  839. var rate = totalQty == 0 ? 0m : (decimal)achievedQty / totalQty;
  840. // S8-ORDER-CHAIN-PRODUCT-DESIGN-20ORDER-GENERATION-CONSISTENCY-AUDIT-1:
  841. // STANDARD / NON_STANDARD / TOTAL 三档统一返回真实指标,不再用 null 掩盖。
  842. // - KpiDays:始终返回常量 KPI=3,方便前端展示阈值。
  843. // - AvgActualDays:actualDays 简单平均(pending 行已经被 HasValue 过滤)。TOTAL 平均 == 父 stage.actual_days(守恒)。
  844. // - AchievementRate:以 product_quantity 加权达成率(与 Overall 一致),保留业务台数权重直觉。
  845. // - Status:达成率 ≥0.95 green / ≥0.80 yellow / 否则 red;无完工行(all pending)时返回空串。
  846. return new AdoS8OrderFlowProductDesignCategorySummaryDto
  847. {
  848. ProductType = productType,
  849. Name = name,
  850. DrawingCount = rows.Select(r => r.DrawingNo).Distinct(StringComparer.Ordinal).Count(),
  851. TotalQuantity = totalQty,
  852. Ratio = grandTotalQty == 0 ? 0m : (decimal)totalQty / grandTotalQty,
  853. KpiDays = kpiDays,
  854. AvgActualDays = actualDays.Count == 0 ? (decimal?)null : actualDays.Average(),
  855. AchievementRate = rate,
  856. Status = actualDays.Count == 0
  857. ? string.Empty
  858. : ClassifyProductDesignCategoryStatus(rate, totalQty),
  859. };
  860. }
  861. /// <summary>达标率 ≥ 0.95 绿 / ≥ 0.80 黄 / 否则 红;无数据返回空串以表达未取数而非状态判定。</summary>
  862. private static string ClassifyProductDesignCategoryStatus(decimal achievementRate, int totalQty)
  863. {
  864. if (totalQty == 0) return string.Empty;
  865. if (achievementRate >= 0.95m) return "green";
  866. if (achievementRate >= 0.80m) return "yellow";
  867. return "red";
  868. }
  869. private static AdoS8OrderFlowProductDesignDrawingItemDto MapProductDesignDrawingItem(
  870. AdoS8OrderFlowProductDesignDrawing d)
  871. => new()
  872. {
  873. OrderCode = d.OrderCode,
  874. DrawingNo = d.DrawingNo,
  875. ProductType = d.ProductType,
  876. ResponsiblePerson = d.ResponsiblePerson,
  877. PlannedStartDate = d.PlannedStartDate,
  878. PlannedEndDate = d.PlannedEndDate,
  879. ActualStartDate = d.ActualStartDate,
  880. ActualEndDate = d.ActualEndDate,
  881. KpiDays = d.KpiDays,
  882. ActualDays = d.ActualDays,
  883. IsAchieved = d.IsAchieved,
  884. Status = d.Status,
  885. ProductQuantity = d.ProductQuantity,
  886. };
  887. // ──────────────────────────────────────────────────────────────────────
  888. // S8-ORDER-CHAIN-BODY-PRODUCTION-ORDER-LEVEL-SEED-FIX-1:本体生产透视。
  889. // 单一数据源 = ado_s8_order_flow_manufacturing_{process,loss_factor,operator} 三表。
  890. // BASELINE_PPT 读 (order_id IS NULL) baseline 行;CURRENT_FILTERED 读订单级行(order_id IS NOT NULL),
  891. // 按 IMPORT/AGG > SEED 优先级去重后,按业务口径聚合:
  892. // process actual_days:AVG(多订单按行平均)
  893. // process plan_qty:SUM(多订单累计计划台次)
  894. // process achievement_rate:AVG(多订单平均达成率),TOTAL 行特殊处理见 BuildManufacturingProcessAggregated。
  895. // process cycle_status / achievement_status:聚合后按阈值重判(与 baseline 同口径,运行期不修改 seed 行)。
  896. // loss factor count:SUM;ratio_pct / loss_hours:AVG。
  897. // operator avg_hours:AVG;status:取首单的 status(baseline 每操作员固定,AVG 后语义不变)。
  898. // orderCodes 为空时返回空骨架(不静默 fallback baseline,避免 baseline 泄漏到单订单态)。
  899. // status 阈值与 seed 同步:cycle_status (≤pi green / ≤pi*1.2 yellow / 否则 red),
  900. // achievement_status (≥0.95 green / ≥0.80 yellow / 否则 red)。
  901. // ──────────────────────────────────────────────────────────────────────
  902. private const string ManufacturingProcessTotalCode = "TOTAL";
  903. // S8-...-FIX-1R:order-level TOTAL.achievement_rate / achievement_status 锚定 fixture,
  904. // 与 baseline TOTAL(0.90 / yellow)保持一致,不再用 plan_qty 加权计算(避免 65% red 与 90% yellow 冲突)。
  905. // SEED 过渡口径;真实 IMPORT/AGG 接入后由真实生产达成数据替换。
  906. private const decimal ManufacturingTotalAchievementRate = 0.9000m;
  907. private const string ManufacturingTotalAchievementStatus = "yellow";
  908. public async Task<AdoS8OrderFlowManufacturingPivotDto> GetManufacturingPivotAsync(
  909. AdoS8OrderFlowManufacturingPivotQueryDto query)
  910. {
  911. var tenantId = query.TenantId ?? 1;
  912. var factoryId = query.FactoryId ?? 1;
  913. var scope = string.IsNullOrWhiteSpace(query.Scope) ? ScopeBaselinePpt : query.Scope;
  914. if (string.Equals(scope, ScopeBaselinePpt, StringComparison.OrdinalIgnoreCase))
  915. {
  916. var processRows = await _mfgProcessRep.AsQueryable()
  917. .Where(p => p.TenantId == tenantId && p.FactoryId == factoryId && !p.IsDeleted)
  918. .Where(p => p.OrderId == null)
  919. .ToListAsync();
  920. var lossRows = await _mfgLossRep.AsQueryable()
  921. .Where(p => p.TenantId == tenantId && p.FactoryId == factoryId && !p.IsDeleted)
  922. .Where(p => p.OrderId == null)
  923. .ToListAsync();
  924. var operatorRows = await _mfgOperatorRep.AsQueryable()
  925. .Where(p => p.TenantId == tenantId && p.FactoryId == factoryId && !p.IsDeleted)
  926. .Where(p => p.OrderId == null)
  927. .ToListAsync();
  928. return BuildManufacturingPivotFromBaseline(scope, processRows, lossRows, operatorRows);
  929. }
  930. if (string.Equals(scope, ScopeCurrentFiltered, StringComparison.OrdinalIgnoreCase))
  931. {
  932. var orderCodes = ParseOrderCodesCsv(query.OrderCodes);
  933. if (orderCodes.Count == 0)
  934. return new AdoS8OrderFlowManufacturingPivotDto { Scope = scope };
  935. var processRows = await _mfgProcessRep.AsQueryable()
  936. .Where(p => p.TenantId == tenantId && p.FactoryId == factoryId && !p.IsDeleted)
  937. .Where(p => p.OrderId != null && p.OrderCode != null)
  938. .Where(p => orderCodes.Contains(p.OrderCode!))
  939. .ToListAsync();
  940. var lossRows = await _mfgLossRep.AsQueryable()
  941. .Where(p => p.TenantId == tenantId && p.FactoryId == factoryId && !p.IsDeleted)
  942. .Where(p => p.OrderId != null && p.OrderCode != null)
  943. .Where(p => orderCodes.Contains(p.OrderCode!))
  944. .ToListAsync();
  945. var operatorRows = await _mfgOperatorRep.AsQueryable()
  946. .Where(p => p.TenantId == tenantId && p.FactoryId == factoryId && !p.IsDeleted)
  947. .Where(p => p.OrderId != null && p.OrderCode != null)
  948. .Where(p => orderCodes.Contains(p.OrderCode!))
  949. .ToListAsync();
  950. if (processRows.Count == 0 && lossRows.Count == 0 && operatorRows.Count == 0)
  951. return new AdoS8OrderFlowManufacturingPivotDto { Scope = scope };
  952. // IMPORT/AGG > SEED 去重:同 (order_code, process_code/factor_code/operator_code) 上 IMPORT/AGG 优先。
  953. var preferredProcess = SelectPreferredMfgProcess(processRows);
  954. var preferredLoss = SelectPreferredMfgLossFactor(lossRows);
  955. var preferredOperator = SelectPreferredMfgOperator(operatorRows);
  956. return new AdoS8OrderFlowManufacturingPivotDto
  957. {
  958. Scope = scope,
  959. Processes = BuildManufacturingProcessAggregated(preferredProcess),
  960. LossFactors = BuildManufacturingLossFactorAggregated(preferredLoss),
  961. Operators = BuildManufacturingOperatorAggregated(preferredOperator),
  962. };
  963. }
  964. return new AdoS8OrderFlowManufacturingPivotDto { Scope = scope };
  965. }
  966. private static AdoS8OrderFlowManufacturingPivotDto BuildManufacturingPivotFromBaseline(
  967. string scope,
  968. List<AdoS8OrderFlowManufacturingProcess> processRows,
  969. List<AdoS8OrderFlowManufacturingLossFactor> lossRows,
  970. List<AdoS8OrderFlowManufacturingOperator> operatorRows)
  971. {
  972. var processes = processRows
  973. .OrderBy(r => r.SortNo)
  974. .Select(r => new AdoS8OrderFlowManufacturingProcessDto
  975. {
  976. ProcessCode = r.ProcessCode,
  977. ProcessName = r.ProcessName,
  978. PiDays = r.PiDays,
  979. ActualDays = r.ActualDays,
  980. CycleStatus = r.CycleStatus,
  981. PlanQty = r.PlanQty,
  982. AchievementRate = r.AchievementRate,
  983. AchievementStatus = r.AchievementStatus,
  984. SortNo = r.SortNo,
  985. })
  986. .ToList();
  987. var losses = lossRows
  988. .OrderBy(r => r.SortNo)
  989. .Select(r => new AdoS8OrderFlowManufacturingLossFactorDto
  990. {
  991. FactorCode = r.FactorCode,
  992. FactorName = r.FactorName,
  993. CountValue = r.CountValue,
  994. RatioPct = r.RatioPct,
  995. LossHours = r.LossHours,
  996. SortNo = r.SortNo,
  997. })
  998. .ToList();
  999. var operators = operatorRows
  1000. .OrderBy(r => r.SortNo)
  1001. .Select(r => new AdoS8OrderFlowManufacturingOperatorDto
  1002. {
  1003. OperatorCode = r.OperatorCode,
  1004. OperatorName = r.OperatorName,
  1005. AvgHours = r.AvgHours,
  1006. Status = r.Status,
  1007. SortNo = r.SortNo,
  1008. })
  1009. .ToList();
  1010. return new AdoS8OrderFlowManufacturingPivotDto
  1011. {
  1012. Scope = scope,
  1013. Processes = processes,
  1014. LossFactors = losses,
  1015. Operators = operators,
  1016. };
  1017. }
  1018. private static List<AdoS8OrderFlowManufacturingProcess> SelectPreferredMfgProcess(
  1019. List<AdoS8OrderFlowManufacturingProcess> rows)
  1020. {
  1021. var grouped = rows.GroupBy(r => (r.OrderCode, r.ProcessCode));
  1022. var result = new List<AdoS8OrderFlowManufacturingProcess>(rows.Count);
  1023. foreach (var g in grouped)
  1024. {
  1025. var preferred = g.FirstOrDefault(r =>
  1026. string.Equals(r.DataSource, "IMPORT", StringComparison.OrdinalIgnoreCase) ||
  1027. string.Equals(r.DataSource, "AGG", StringComparison.OrdinalIgnoreCase));
  1028. result.Add(preferred ?? g.First());
  1029. }
  1030. return result;
  1031. }
  1032. private static List<AdoS8OrderFlowManufacturingLossFactor> SelectPreferredMfgLossFactor(
  1033. List<AdoS8OrderFlowManufacturingLossFactor> rows)
  1034. {
  1035. var grouped = rows.GroupBy(r => (r.OrderCode, r.FactorCode));
  1036. var result = new List<AdoS8OrderFlowManufacturingLossFactor>(rows.Count);
  1037. foreach (var g in grouped)
  1038. {
  1039. var preferred = g.FirstOrDefault(r =>
  1040. string.Equals(r.DataSource, "IMPORT", StringComparison.OrdinalIgnoreCase) ||
  1041. string.Equals(r.DataSource, "AGG", StringComparison.OrdinalIgnoreCase));
  1042. result.Add(preferred ?? g.First());
  1043. }
  1044. return result;
  1045. }
  1046. private static List<AdoS8OrderFlowManufacturingOperator> SelectPreferredMfgOperator(
  1047. List<AdoS8OrderFlowManufacturingOperator> rows)
  1048. {
  1049. var grouped = rows.GroupBy(r => (r.OrderCode, r.OperatorCode));
  1050. var result = new List<AdoS8OrderFlowManufacturingOperator>(rows.Count);
  1051. foreach (var g in grouped)
  1052. {
  1053. var preferred = g.FirstOrDefault(r =>
  1054. string.Equals(r.DataSource, "IMPORT", StringComparison.OrdinalIgnoreCase) ||
  1055. string.Equals(r.DataSource, "AGG", StringComparison.OrdinalIgnoreCase));
  1056. result.Add(preferred ?? g.First());
  1057. }
  1058. return result;
  1059. }
  1060. /// <summary>
  1061. /// 多订单工序聚合:
  1062. /// 非 TOTAL 行:actual_days = AVG;plan_qty = SUM;achievement_rate = AVG(保留 4 位小数);
  1063. /// cycle_status 按聚合 actual vs pi 重判;achievement_status 按聚合 rate 重判。
  1064. /// TOTAL 行:pi=6(取 baseline 常量);actual = AVG(与 4 工序 AVG 之和守恒,差异为 rounding 容差);
  1065. /// plan_qty = NULL;
  1066. /// S8-...-FIX-1R:achievement_rate / achievement_status 锚定 fixture(0.90 / yellow),
  1067. /// 不再做 plan_qty 加权计算(避免与 baseline TOTAL 视觉冲突);
  1068. /// cycle_status 按聚合 actual vs pi 重判。
  1069. /// </summary>
  1070. private static List<AdoS8OrderFlowManufacturingProcessDto> BuildManufacturingProcessAggregated(
  1071. List<AdoS8OrderFlowManufacturingProcess> rows)
  1072. {
  1073. var grouped = rows
  1074. .GroupBy(r => r.ProcessCode)
  1075. .ToDictionary(g => g.Key, g => g.ToList());
  1076. // S8-...-FIX-1R:TOTAL 行 rate / status 锚定 fixture,不再做 4 工序 plan_qty 加权计算,
  1077. // 不需要维护中间 aggregatedRates 字典。
  1078. var processDtos = new List<AdoS8OrderFlowManufacturingProcessDto>();
  1079. foreach (var kv in grouped.OrderBy(g => g.Value.First().SortNo))
  1080. {
  1081. var code = kv.Key;
  1082. var list = kv.Value;
  1083. var sample = list[0];
  1084. var isTotal = string.Equals(code, ManufacturingProcessTotalCode, StringComparison.OrdinalIgnoreCase);
  1085. var actualAvg = decimal.Round(list.Average(r => r.ActualDays), 3);
  1086. var pi = sample.PiDays;
  1087. decimal? aggregatedRate;
  1088. int? planQtySum;
  1089. string achStatus;
  1090. if (isTotal)
  1091. {
  1092. // S8-...-FIX-1R:TOTAL 行 rate / status 锚定 fixture(0.90 / yellow),
  1093. // 不再做 plan_qty 加权计算;非 TOTAL 行的 plan_qty 仍保留供 UI 显示,但不参与 TOTAL.rate。
  1094. planQtySum = null;
  1095. aggregatedRate = ManufacturingTotalAchievementRate;
  1096. achStatus = ManufacturingTotalAchievementStatus;
  1097. }
  1098. else
  1099. {
  1100. planQtySum = list.Where(r => r.PlanQty.HasValue).Sum(r => r.PlanQty!.Value);
  1101. var rateRows = list.Where(r => r.AchievementRate.HasValue).ToList();
  1102. aggregatedRate = rateRows.Count == 0
  1103. ? null
  1104. : decimal.Round(rateRows.Average(r => r.AchievementRate!.Value), 4);
  1105. achStatus = aggregatedRate.HasValue
  1106. ? ClassifyMfgAchievementStatus(aggregatedRate.Value)
  1107. : string.Empty;
  1108. }
  1109. var cycleStatus = ClassifyMfgCycleStatus(actualAvg, pi);
  1110. processDtos.Add(new AdoS8OrderFlowManufacturingProcessDto
  1111. {
  1112. ProcessCode = sample.ProcessCode,
  1113. ProcessName = sample.ProcessName,
  1114. PiDays = pi,
  1115. ActualDays = actualAvg,
  1116. CycleStatus = cycleStatus,
  1117. PlanQty = planQtySum,
  1118. AchievementRate = aggregatedRate,
  1119. AchievementStatus = achStatus,
  1120. SortNo = sample.SortNo,
  1121. });
  1122. }
  1123. return processDtos;
  1124. }
  1125. private static List<AdoS8OrderFlowManufacturingLossFactorDto> BuildManufacturingLossFactorAggregated(
  1126. List<AdoS8OrderFlowManufacturingLossFactor> rows)
  1127. {
  1128. return rows
  1129. .GroupBy(r => r.FactorCode)
  1130. .OrderBy(g => g.First().SortNo)
  1131. .Select(g =>
  1132. {
  1133. var sample = g.First();
  1134. var countList = g.Where(r => r.CountValue.HasValue).ToList();
  1135. var ratioList = g.Where(r => r.RatioPct.HasValue).ToList();
  1136. var hoursList = g.Where(r => r.LossHours.HasValue).ToList();
  1137. return new AdoS8OrderFlowManufacturingLossFactorDto
  1138. {
  1139. FactorCode = sample.FactorCode,
  1140. FactorName = sample.FactorName,
  1141. CountValue = countList.Count == 0 ? null : countList.Sum(r => r.CountValue!.Value),
  1142. RatioPct = ratioList.Count == 0
  1143. ? null
  1144. : decimal.Round(ratioList.Average(r => r.RatioPct!.Value), 2),
  1145. LossHours = hoursList.Count == 0
  1146. ? null
  1147. : decimal.Round(hoursList.Average(r => r.LossHours!.Value), 2),
  1148. SortNo = sample.SortNo,
  1149. };
  1150. })
  1151. .ToList();
  1152. }
  1153. private static List<AdoS8OrderFlowManufacturingOperatorDto> BuildManufacturingOperatorAggregated(
  1154. List<AdoS8OrderFlowManufacturingOperator> rows)
  1155. {
  1156. return rows
  1157. .GroupBy(r => r.OperatorCode)
  1158. .OrderBy(g => g.First().SortNo)
  1159. .Select(g =>
  1160. {
  1161. var sample = g.First();
  1162. return new AdoS8OrderFlowManufacturingOperatorDto
  1163. {
  1164. OperatorCode = sample.OperatorCode,
  1165. OperatorName = sample.OperatorName,
  1166. AvgHours = decimal.Round(g.Average(r => r.AvgHours), 2),
  1167. // 每操作员 baseline status 固化,多订单聚合时各订单值一致;取首单不引入歧义。
  1168. Status = sample.Status,
  1169. SortNo = sample.SortNo,
  1170. };
  1171. })
  1172. .ToList();
  1173. }
  1174. private static string ClassifyMfgCycleStatus(decimal actual, decimal pi)
  1175. {
  1176. if (actual <= pi) return "green";
  1177. if (actual <= pi * 1.2m) return "yellow";
  1178. return "red";
  1179. }
  1180. private static string ClassifyMfgAchievementStatus(decimal rate)
  1181. {
  1182. if (rate >= 0.95m) return "green";
  1183. if (rate >= 0.80m) return "yellow";
  1184. return "red";
  1185. }
  1186. // ────────────────────────────────────────────────────────────
  1187. // 总装发货透视 — S8-ORDER-CHAIN-ASSEMBLY-DELIVERY-DATA-LINEAGE-AUDIT-1
  1188. //
  1189. // 与 aggregate.finalAssemblyCollabSummary(exception 派生)通道独立:
  1190. // - 本 API 提供门禁 KPI / 实际 / 偏差 / 齐套率(来自专属 pivot 表)。
  1191. // - 现有 BuildFinalAssemblyCollabSummaryAsync 保留,作为 collabSummary 补充。
  1192. // 数据源优先级:IMPORT > AGG > SEED(同 (order_code, gate_code/prep_code) 上去重)。
  1193. // 多订单聚合规则:
  1194. // - planned_offset_days:取首单值(baseline 固定 0.6/1.2/1.8/2.4/3.0,不随订单变)。
  1195. // - actual_offset_days:AVG。
  1196. // - variance_days:AVG(等于 avg_actual - planned,因 planned 固定)。
  1197. // - status:聚合后按 variance 重判(同 seed 阈值)。
  1198. // - impacted_order_count / risk_order_count:SUM。
  1199. // - top_risk_type / top_risk_label:稳定取首条 status != green 的样本(按 sort_no / order_code 升序)。
  1200. // - parallel kitting_rate:AVG(保留 4 位小数);status 按聚合 kitting_rate 重判。
  1201. // - orderCodes 为空 → 返回空骨架,不静默 fallback baseline;
  1202. // - 全 pending → 自然空骨架(SEED 不包含 pending 行)。
  1203. // ────────────────────────────────────────────────────────────
  1204. public async Task<AdoS8FinalAssemblyPivotDto> GetFinalAssemblyPivotAsync(
  1205. AdoS8FinalAssemblyPivotQueryDto query)
  1206. {
  1207. var tenantId = query.TenantId ?? 1;
  1208. var factoryId = query.FactoryId ?? 1;
  1209. var scope = string.IsNullOrWhiteSpace(query.Scope) ? ScopeBaselinePpt : query.Scope;
  1210. if (string.Equals(scope, ScopeBaselinePpt, StringComparison.OrdinalIgnoreCase))
  1211. {
  1212. var gateRows = await _faGateRep.AsQueryable()
  1213. .Where(g => g.TenantId == tenantId && g.FactoryId == factoryId && !g.IsDeleted)
  1214. .Where(g => g.OrderId == null)
  1215. .ToListAsync();
  1216. var parallelRows = await _faParallelRep.AsQueryable()
  1217. .Where(p => p.TenantId == tenantId && p.FactoryId == factoryId && !p.IsDeleted)
  1218. .Where(p => p.OrderId == null)
  1219. .ToListAsync();
  1220. return BuildFinalAssemblyPivotFromBaseline(scope, gateRows, parallelRows);
  1221. }
  1222. if (string.Equals(scope, ScopeCurrentFiltered, StringComparison.OrdinalIgnoreCase))
  1223. {
  1224. var orderCodes = ParseOrderCodesCsv(query.OrderCodes);
  1225. if (orderCodes.Count == 0)
  1226. return new AdoS8FinalAssemblyPivotDto { Scope = scope };
  1227. var gateRows = await _faGateRep.AsQueryable()
  1228. .Where(g => g.TenantId == tenantId && g.FactoryId == factoryId && !g.IsDeleted)
  1229. .Where(g => g.OrderId != null && g.OrderCode != null)
  1230. .Where(g => orderCodes.Contains(g.OrderCode!))
  1231. .ToListAsync();
  1232. var parallelRows = await _faParallelRep.AsQueryable()
  1233. .Where(p => p.TenantId == tenantId && p.FactoryId == factoryId && !p.IsDeleted)
  1234. .Where(p => p.OrderId != null && p.OrderCode != null)
  1235. .Where(p => orderCodes.Contains(p.OrderCode!))
  1236. .ToListAsync();
  1237. if (gateRows.Count == 0 && parallelRows.Count == 0)
  1238. return new AdoS8FinalAssemblyPivotDto { Scope = scope };
  1239. var preferredGates = SelectPreferredFaGate(gateRows);
  1240. var preferredParallels = SelectPreferredFaParallel(parallelRows);
  1241. return new AdoS8FinalAssemblyPivotDto
  1242. {
  1243. Scope = scope,
  1244. Gates = BuildFaGateAggregated(preferredGates),
  1245. ParallelPreps = BuildFaParallelAggregated(preferredParallels),
  1246. };
  1247. }
  1248. return new AdoS8FinalAssemblyPivotDto { Scope = scope };
  1249. }
  1250. private static AdoS8FinalAssemblyPivotDto BuildFinalAssemblyPivotFromBaseline(
  1251. string scope,
  1252. List<AdoS8OrderFlowFinalAssemblyGate> gateRows,
  1253. List<AdoS8OrderFlowFinalAssemblyParallel> parallelRows)
  1254. {
  1255. var gates = gateRows
  1256. .OrderBy(g => g.SortNo)
  1257. .Select(g => new AdoS8FinalAssemblyGateDto
  1258. {
  1259. GateCode = g.GateCode,
  1260. GateName = g.GateName,
  1261. PlannedOffsetDays = g.PlannedOffsetDays,
  1262. ActualOffsetDays = g.ActualOffsetDays,
  1263. VarianceDays = g.VarianceDays,
  1264. Status = g.Status,
  1265. ImpactedOrderCount = g.ImpactedOrderCount,
  1266. RiskOrderCount = g.RiskOrderCount,
  1267. TopRiskType = g.TopRiskType,
  1268. TopRiskLabel = g.TopRiskLabel,
  1269. OwnerSideText = g.OwnerSideText,
  1270. SortNo = g.SortNo,
  1271. })
  1272. .ToList();
  1273. var parallels = parallelRows
  1274. .OrderBy(p => p.SortNo)
  1275. .Select(p => new AdoS8FinalAssemblyParallelDto
  1276. {
  1277. PrepCode = p.PrepCode,
  1278. PrepName = p.PrepName,
  1279. KittingRate = p.KittingRate,
  1280. Status = p.Status,
  1281. ImpactedOrderCount = p.ImpactedOrderCount,
  1282. RiskOrderCount = p.RiskOrderCount,
  1283. TopRiskType = p.TopRiskType,
  1284. TopRiskLabel = p.TopRiskLabel,
  1285. OwnerSideText = p.OwnerSideText,
  1286. SortNo = p.SortNo,
  1287. })
  1288. .ToList();
  1289. return new AdoS8FinalAssemblyPivotDto
  1290. {
  1291. Scope = scope,
  1292. Gates = gates,
  1293. ParallelPreps = parallels,
  1294. };
  1295. }
  1296. private static List<AdoS8OrderFlowFinalAssemblyGate> SelectPreferredFaGate(
  1297. List<AdoS8OrderFlowFinalAssemblyGate> rows)
  1298. {
  1299. var grouped = rows.GroupBy(r => (r.OrderCode, r.GateCode));
  1300. var result = new List<AdoS8OrderFlowFinalAssemblyGate>(rows.Count);
  1301. foreach (var g in grouped)
  1302. {
  1303. var preferred = g.FirstOrDefault(r =>
  1304. string.Equals(r.DataSource, "IMPORT", StringComparison.OrdinalIgnoreCase) ||
  1305. string.Equals(r.DataSource, "AGG", StringComparison.OrdinalIgnoreCase));
  1306. result.Add(preferred ?? g.First());
  1307. }
  1308. return result;
  1309. }
  1310. private static List<AdoS8OrderFlowFinalAssemblyParallel> SelectPreferredFaParallel(
  1311. List<AdoS8OrderFlowFinalAssemblyParallel> rows)
  1312. {
  1313. var grouped = rows.GroupBy(r => (r.OrderCode, r.PrepCode));
  1314. var result = new List<AdoS8OrderFlowFinalAssemblyParallel>(rows.Count);
  1315. foreach (var g in grouped)
  1316. {
  1317. var preferred = g.FirstOrDefault(r =>
  1318. string.Equals(r.DataSource, "IMPORT", StringComparison.OrdinalIgnoreCase) ||
  1319. string.Equals(r.DataSource, "AGG", StringComparison.OrdinalIgnoreCase));
  1320. result.Add(preferred ?? g.First());
  1321. }
  1322. return result;
  1323. }
  1324. private static List<AdoS8FinalAssemblyGateDto> BuildFaGateAggregated(
  1325. List<AdoS8OrderFlowFinalAssemblyGate> rows)
  1326. {
  1327. return rows
  1328. .GroupBy(r => r.GateCode)
  1329. .OrderBy(g => g.First().SortNo)
  1330. .Select(g =>
  1331. {
  1332. var sample = g.First();
  1333. var actualList = g.Where(r => r.ActualOffsetDays.HasValue).ToList();
  1334. var varianceList = g.Where(r => r.VarianceDays.HasValue).ToList();
  1335. decimal? actualAvg = actualList.Count == 0
  1336. ? null
  1337. : decimal.Round(actualList.Average(r => r.ActualOffsetDays!.Value), 3);
  1338. decimal? varianceAvg = varianceList.Count == 0
  1339. ? null
  1340. : decimal.Round(varianceList.Average(r => r.VarianceDays!.Value), 3);
  1341. var aggregatedStatus = varianceAvg.HasValue
  1342. ? ClassifyFaGateStatus(varianceAvg.Value)
  1343. : sample.Status;
  1344. var impactedSum = g.Sum(r => r.ImpactedOrderCount ?? 0);
  1345. var riskSum = g.Sum(r => r.RiskOrderCount ?? 0);
  1346. // 稳定取首条非 green 行的 top_risk_type / label(按 order_code 升序保证确定性)。
  1347. var riskSample = g
  1348. .Where(r => !string.Equals(r.Status, "green", StringComparison.OrdinalIgnoreCase)
  1349. && r.TopRiskType != null)
  1350. .OrderBy(r => r.OrderCode, StringComparer.Ordinal)
  1351. .FirstOrDefault();
  1352. return new AdoS8FinalAssemblyGateDto
  1353. {
  1354. GateCode = sample.GateCode,
  1355. GateName = sample.GateName,
  1356. PlannedOffsetDays = sample.PlannedOffsetDays,
  1357. ActualOffsetDays = actualAvg,
  1358. VarianceDays = varianceAvg,
  1359. Status = aggregatedStatus,
  1360. ImpactedOrderCount = impactedSum,
  1361. RiskOrderCount = riskSum,
  1362. TopRiskType = riskSample?.TopRiskType,
  1363. TopRiskLabel = riskSample?.TopRiskLabel,
  1364. OwnerSideText = sample.OwnerSideText,
  1365. SortNo = sample.SortNo,
  1366. };
  1367. })
  1368. .ToList();
  1369. }
  1370. private static List<AdoS8FinalAssemblyParallelDto> BuildFaParallelAggregated(
  1371. List<AdoS8OrderFlowFinalAssemblyParallel> rows)
  1372. {
  1373. return rows
  1374. .GroupBy(r => r.PrepCode)
  1375. .OrderBy(g => g.First().SortNo)
  1376. .Select(g =>
  1377. {
  1378. var sample = g.First();
  1379. var rateList = g.Where(r => r.KittingRate.HasValue).ToList();
  1380. decimal? kittingAvg = rateList.Count == 0
  1381. ? null
  1382. : decimal.Round(rateList.Average(r => r.KittingRate!.Value), 4);
  1383. var aggregatedStatus = kittingAvg.HasValue
  1384. ? ClassifyFaParallelStatus(kittingAvg.Value)
  1385. : sample.Status;
  1386. var impactedSum = g.Sum(r => r.ImpactedOrderCount ?? 0);
  1387. var riskSum = g.Sum(r => r.RiskOrderCount ?? 0);
  1388. var riskSample = g
  1389. .Where(r => !string.Equals(r.Status, "green", StringComparison.OrdinalIgnoreCase)
  1390. && r.TopRiskType != null)
  1391. .OrderBy(r => r.OrderCode, StringComparer.Ordinal)
  1392. .FirstOrDefault();
  1393. return new AdoS8FinalAssemblyParallelDto
  1394. {
  1395. PrepCode = sample.PrepCode,
  1396. PrepName = sample.PrepName,
  1397. KittingRate = kittingAvg,
  1398. Status = aggregatedStatus,
  1399. ImpactedOrderCount = impactedSum,
  1400. RiskOrderCount = riskSum,
  1401. TopRiskType = riskSample?.TopRiskType,
  1402. TopRiskLabel = riskSample?.TopRiskLabel,
  1403. OwnerSideText = sample.OwnerSideText,
  1404. SortNo = sample.SortNo,
  1405. };
  1406. })
  1407. .ToList();
  1408. }
  1409. /// <summary>gate status:variance ≤ 0 green / ≤ 0.3 yellow / 否则 red(与 seed 同口径)。</summary>
  1410. private static string ClassifyFaGateStatus(decimal variance)
  1411. {
  1412. if (variance <= 0m) return "green";
  1413. if (variance <= 0.3m) return "yellow";
  1414. return "red";
  1415. }
  1416. /// <summary>parallel status:kitting_rate ≥ 0.95 green / ≥ 0.85 yellow / 否则 red(与 seed 同口径)。</summary>
  1417. private static string ClassifyFaParallelStatus(decimal kittingRate)
  1418. {
  1419. if (kittingRate >= 0.95m) return "green";
  1420. if (kittingRate >= 0.85m) return "yellow";
  1421. return "red";
  1422. }
  1423. }