S6MdpSyncTransformService.cs 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  1. using Admin.NET.Core.Service;
  2. using Admin.NET.Plugin.AiDOP.DataPlatform.MdpRebuild;
  3. using Admin.NET.Plugin.AiDOP.Infrastructure;
  4. using Microsoft.Extensions.Logging;
  5. using System.Text.Json;
  6. namespace Admin.NET.Plugin.AiDOP.Manufacturing;
  7. /// <summary>
  8. /// S6 生产执行 — KPI 计算与刷新转换服务。
  9. /// 双模式:读本地中立标准层(由适配器从贴源→标准),不再直连源库。
  10. /// 计算逻辑沿用方老师 v5.4 KPI J 列口径(等价改写为 MySQL 读 std)。
  11. /// 口径归位(S6-L1-KPI-CONTRACT-RESOLUTION-1,方案 B):L1=订单级,L2=工单级。
  12. /// L1:订单制造周期/满足率/人效写 l1_day;L2:工单制造满足率/人效写 l2_day。
  13. /// 最终聚合经 KpiCalcDispatcher(LEGACY_CODE/CONFIG_SQL),数据准备(dwd)不变。
  14. /// </summary>
  15. public class S6MdpSyncTransformService : ITransient
  16. {
  17. private readonly ISqlSugarClient _db;
  18. private readonly TransformRunLogFinalizer _runLogFinalizer;
  19. private readonly SysNoticeService _sysNoticeService;
  20. private readonly ILogger<S6MdpSyncTransformService> _logger;
  21. private readonly SmartOps.KpiCalcDispatcher _kpiCalcDispatcher;
  22. private readonly SmartOps.KpiDimensionRunService _dimensionRun;
  23. private readonly SmartOps.IKpiTargetResolver _kpiTargetResolver;
  24. private readonly SmartOps.S9CompositeKpiWriter _s9Composite;
  25. private readonly SmartOps.KpiResultStatusService _kpiStatus;
  26. private readonly DataPlatform.MdpTenantStdSourceResolver _stdSource;
  27. private const string L2ValueTable = "ado_s9_kpi_value_l2_day";
  28. private const string L3ValueTable = "ado_s9_kpi_value_l3_day";
  29. private const string JobCode = "S6_MDP_SYNC_TRANSFORM";
  30. private const string JobName = "S6 生产执行 MDP 同步与转换";
  31. private const string ModuleCode = "S6";
  32. // FAILURE-NOTIFICATION-1:超级管理员 superAdmin.NET(AccountType=999)
  33. private const long NoticeReceiverUserId = 1300000000101L;
  34. private const string NoticeReceiverUserName = "超级管理员";
  35. public S6MdpSyncTransformService(
  36. ISqlSugarClient db,
  37. SysNoticeService sysNoticeService,
  38. ILogger<S6MdpSyncTransformService> logger,
  39. SmartOps.KpiCalcDispatcher kpiCalcDispatcher,
  40. SmartOps.KpiDimensionRunService dimensionRun,
  41. SmartOps.IKpiTargetResolver kpiTargetResolver,
  42. TransformRunLogFinalizer runLogFinalizer,
  43. SmartOps.S9CompositeKpiWriter s9Composite,
  44. SmartOps.KpiResultStatusService kpiStatus,
  45. DataPlatform.MdpTenantStdSourceResolver stdSource)
  46. {
  47. _db = db;
  48. _runLogFinalizer = runLogFinalizer;
  49. _sysNoticeService = sysNoticeService;
  50. _logger = logger;
  51. _kpiCalcDispatcher = kpiCalcDispatcher;
  52. _dimensionRun = dimensionRun;
  53. _kpiTargetResolver = kpiTargetResolver;
  54. _s9Composite = s9Composite;
  55. _kpiStatus = kpiStatus;
  56. _stdSource = stdSource;
  57. }
  58. private async Task<string> SourceOfAsync(long tenantId, string stdObject, CancellationToken ct)
  59. {
  60. var row = await _stdSource.GetSourceAsync(tenantId, stdObject, ct);
  61. return row?.SourceSystem ?? "";
  62. }
  63. public async Task<S6MdpSyncTransformResult> RunFullAsync(
  64. CancellationToken cancellationToken = default,
  65. string triggerType = "AUTO",
  66. S6MdpRefreshOption? option = null)
  67. {
  68. cancellationToken.ThrowIfCancellationRequested();
  69. option ??= S6MdpRefreshOption.Default();
  70. NormalizeOption(option);
  71. var now = DateTime.Now;
  72. var batchId = $"S6_MDP_FULL_{now:yyyyMMddHHmmss}";
  73. var normalizedTrigger = NormalizeTriggerType(triggerType);
  74. var runLogId = await InsertTransformRunLogAsync(batchId, now, normalizedTrigger, option);
  75. var result = new S6MdpSyncTransformResult
  76. {
  77. BatchId = batchId,
  78. RunLogId = runLogId,
  79. TriggerType = normalizedTrigger,
  80. SourceZtid = option.SourceZtid,
  81. TargetTenantId = option.TargetTenantId,
  82. TargetFactoryId = option.TargetFactoryId,
  83. BizDate = option.BizDate,
  84. BizMonth = option.BizMonth,
  85. MonthlyPeriodStart = option.MonthlyPeriodStart,
  86. MonthlyPeriodEnd = option.MonthlyPeriodEnd
  87. };
  88. try
  89. {
  90. result.StageRows = 0;
  91. result.StandardRows = 0;
  92. var currentBizDate = option.BizDate;
  93. const int backfillDays = 14;
  94. for (var dayOffset = backfillDays - 1; dayOffset >= 0; dayOffset--)
  95. {
  96. option.BizDate = currentBizDate.AddDays(-dayOffset);
  97. result.MergeSub("S6_L2_001", await BuildS6L2001WorkOrderMfgCycleAsync(
  98. batchId, now, option, normalizedTrigger, cancellationToken));
  99. result.MergeSub("S6_L2_002", await BuildS6L2002WorkOrderMfgFulfillmentAsync(
  100. batchId, now, option, normalizedTrigger, cancellationToken));
  101. result.MergeSub("S6_L2_003", await BuildS6L2003WorkOrderMfgEfficiencyAsync(
  102. batchId, now, option, normalizedTrigger, cancellationToken));
  103. result.MergeSub("S6_L2_004", await BuildS6L2004WorkOrderWipTurnoverAsync(
  104. batchId, now, option, normalizedTrigger, cancellationToken));
  105. foreach (var metricCode in new[]
  106. {
  107. "S6_L3_001", "S6_L3_002", "S6_L3_003", "S6_L3_004",
  108. "S6_L3_005", "S6_L3_006", "S6_L3_007", "S6_L3_008"
  109. })
  110. {
  111. var sub = await BuildS6ExecutionDetailKpiAsync(
  112. metricCode, batchId, now, option, normalizedTrigger, cancellationToken);
  113. result.MergeSub(metricCode, sub);
  114. }
  115. }
  116. option.BizDate = currentBizDate;
  117. var sub11 = await BuildS6L1001OrderMfgCycleAsync(batchId, now, option, normalizedTrigger, cancellationToken);
  118. result.MergeSub("S6_L1_001", sub11);
  119. var sub12 = await BuildS6L1002OrderMfgFulfillmentAsync(batchId, now, option, normalizedTrigger, cancellationToken);
  120. result.MergeSub("S6_L1_002", sub12);
  121. var sub13 = await BuildS6L1003OrderMfgEfficiencyAsync(batchId, now, option, normalizedTrigger, cancellationToken);
  122. result.MergeSub("S6_L1_003", sub13);
  123. result.KpiRows += await _s9Composite.WriteRecentAsync(
  124. option.TargetTenantId, option.TargetFactoryId, option.BizDate, cancellationToken);
  125. await MarkTransformRunSuccessAsync(runLogId, now, result);
  126. return result;
  127. }
  128. catch (Exception ex)
  129. {
  130. if (ex is ModuleRebuildCancelledException)
  131. throw;
  132. // 宿主关停不是转换失败:交给 finally 收口为 ABORTED,不污染 FAILED 语义。
  133. if (!_runLogFinalizer.IsHostStopping)
  134. await MarkTransformRunFailedAsync(runLogId, now, ex.Message, batchId);
  135. throw;
  136. }
  137. finally
  138. {
  139. await _runLogFinalizer.FinalizeIfHostStoppingAsync(runLogId, now);
  140. }
  141. }
  142. // ─────────────────────────────────────────────────────────────────────────
  143. /// <summary>工单制造周期 = 每个完成工单最晚完工时间 - 最早投产时间,再取工单平均。归位 L2:写 S6_L2_001。</summary>
  144. private async Task<KpiBuildSubResult> BuildS6L2001WorkOrderMfgCycleAsync(
  145. string batchId, DateTime now, S6MdpRefreshOption option, string triggerType, CancellationToken ct)
  146. {
  147. const string sql = @"
  148. select task_no, datediff(max(completion_time), min(start_time)) as cycle_days
  149. from (
  150. select b.order_no, b.task_no, b.item_code, b.release_time as start_time,
  151. case when b.closed_flag=1 and b.closed_time is not null then b.closed_time else max(d.completion_time) end as completion_time,
  152. case when b.closed_flag=1 or sum(ifnull(d.qty_change,0))>=b.qty_planned then 1 else 0 end as completed
  153. from mdp_std_work_order_line b
  154. left join (
  155. select ref_task_no, item_num, qty_change, ifnull(line_closed_time, approved_time) as completion_time
  156. from mdp_std_inv_trans
  157. where tenant_id=@tenantId
  158. and biz_doc_type='PROD_RECEIPT' and summary_flag=0 and void_flag=0 and approved_flag=1 AND source_system=@sourceSystem
  159. ) d on b.task_no=d.ref_task_no and b.item_code=d.item_num
  160. where b.tenant_id=@tenantId
  161. and b.doc_type='PROD_TASK' and b.void_flag=0 and b.approved_flag=1 and b.task_no is not null
  162. group by b.order_no, b.task_no, b.item_code, b.qty_planned, b.release_time, b.closed_flag, b.closed_time
  163. ) n
  164. group by task_no
  165. having min(completed)=1 and min(start_time) is not null and max(completion_time) is not null";
  166. var rows = await _db.Ado.SqlQueryAsync<S6WorkOrderCycleRow>(sql, new[]
  167. {
  168. new SugarParameter("@tenantId", option.TargetTenantId),
  169. new SugarParameter("@sourceDomain", option.SourceZtid),
  170. new SugarParameter("@sourceSystem", await SourceOfAsync(option.TargetTenantId, "INV_TRANS", ct))
  171. });
  172. var cycles = rows.Where(r => r.cycle_days.HasValue && r.cycle_days.Value >= 0)
  173. .Select(r => (decimal)r.cycle_days!.Value).ToList();
  174. decimal? value = cycles.Count > 0 ? Math.Round(cycles.Average(), 4) : null;
  175. var denom = cycles.Count > 0 ? "OK" : "NO_COMPLETED_WORK_ORDER";
  176. var dispatch = await _kpiCalcDispatcher.DispatchAsync(
  177. "S6_L2_001", ModuleCode, option.TargetTenantId, option.TargetFactoryId,
  178. option.BizDate, option.BizDate, option.BizDate, option.SourceZtid,
  179. batchId, triggerType, value, denom, ct);
  180. var sub = new KpiBuildSubResult
  181. {
  182. T8Rows = rows.Count,
  183. KpiRows = dispatch.ShouldUpsert
  184. ? await UpsertKpiValueAsync("S6_L2_001", option.BizDate, dispatch.MetricValue, now, option, L2ValueTable)
  185. : 0,
  186. DenominatorStatus = dispatch.DenominatorStatus
  187. };
  188. await RunDimensionSafelyAsync("S6_L2_001", option.BizDate, batchId, triggerType, option, dispatch.ShouldUpsert, ct);
  189. return sub;
  190. }
  191. /// <summary>工单制造满足率 = 完工窗口内累计入库 / 工单投产数量。归位 L2:写 S6_L2_002。</summary>
  192. private async Task<KpiBuildSubResult> BuildS6L2002WorkOrderMfgFulfillmentAsync(
  193. string batchId, DateTime now, S6MdpRefreshOption option, string triggerType, CancellationToken ct)
  194. {
  195. var sub = new KpiBuildSubResult();
  196. const string sql = @"
  197. select b.order_no as order_no, b.task_no as task_no, b.item_code as item_code, b.qty_planned as qty_planned, sum(d.qty_change) as qty_done
  198. from mdp_std_work_order_line b
  199. left join (
  200. select ref_task_no, item_num,
  201. date(approved_time) as approved_date, qty_change
  202. from mdp_std_inv_trans
  203. where tenant_id=@tenantId
  204. and biz_doc_type='PROD_RECEIPT' and summary_flag=0 and void_flag=0 and approved_flag=1 AND source_system=@sourceSystem
  205. ) d on b.task_no=d.ref_task_no and b.item_code=d.item_num
  206. where b.tenant_id=@tenantId
  207. and b.doc_type='PROD_TASK' and b.void_flag=0 and b.approved_flag=1 and d.approved_date<=b.plan_finish_date
  208. group by b.order_no, b.task_no, b.item_code, b.qty_planned";
  209. var rows = await _db.Ado.SqlQueryAsync<S6MfgFulfillmentRow>(sql, new[]
  210. {
  211. new SugarParameter("@tenantId", option.TargetTenantId),
  212. new SugarParameter("@sourceDomain", option.SourceZtid),
  213. new SugarParameter("@sourceSystem", await SourceOfAsync(option.TargetTenantId, "INV_TRANS", ct))
  214. });
  215. sub.T8Rows = rows.Count;
  216. var dwdAffected = 0;
  217. var rateList = new List<decimal>();
  218. foreach (var r in rows)
  219. {
  220. ct.ThrowIfCancellationRequested();
  221. if (string.IsNullOrEmpty(r.order_no)) continue;
  222. decimal? rate = (r.qty_planned.HasValue && r.qty_planned.Value > 0m && r.qty_done.HasValue)
  223. ? Math.Round(Math.Clamp(r.qty_done.Value / r.qty_planned.Value, 0m, 1m), 4)
  224. : null;
  225. if (rate.HasValue) rateList.Add(rate.Value);
  226. dwdAffected += await _db.Ado.ExecuteCommandAsync(@"
  227. INSERT INTO dwd_work_order_mfg_fulfillment
  228. (tenant_id, factory_id, biz_date, source_ztid, order_no, task_no, item_code,
  229. plan_qty, done_qty_in_window, fulfillment_rate, batch_id, create_time)
  230. VALUES
  231. (@tenantId, @factoryId, @bizDate, @sourceDomain, @orderNo, @taskNo, @itemCode,
  232. @planQty, @doneQty, @rate, @batchId, @now)
  233. ON DUPLICATE KEY UPDATE
  234. plan_qty=VALUES(plan_qty), done_qty_in_window=VALUES(done_qty_in_window),
  235. fulfillment_rate=VALUES(fulfillment_rate),
  236. batch_id=VALUES(batch_id), update_time=@now",
  237. new SugarParameter("@tenantId", option.TargetTenantId),
  238. new SugarParameter("@factoryId", option.TargetFactoryId),
  239. new SugarParameter("@bizDate", option.BizDate),
  240. new SugarParameter("@sourceDomain", option.SourceZtid),
  241. new SugarParameter("@orderNo", r.order_no),
  242. new SugarParameter("@taskNo", r.task_no ?? ""),
  243. new SugarParameter("@itemCode", r.item_code ?? ""),
  244. new SugarParameter("@planQty", r.qty_planned),
  245. new SugarParameter("@doneQty", r.qty_done),
  246. new SugarParameter("@rate", rate),
  247. new SugarParameter("@batchId", batchId),
  248. new SugarParameter("@now", now));
  249. }
  250. sub.DwdRows = dwdAffected;
  251. // 数据准备(dwd)已完成。最终聚合交分发器(日 KPI:period 复用 BizDate,SQL 按 biz_date 圈选)。
  252. decimal? legacyValue = rateList.Count > 0
  253. ? Math.Round(rateList.Average() * 100m, 4) // 百分号
  254. : null;
  255. var legacyDenom = rateList.Count > 0 ? "OK" : "NO_VALID_WORK_ORDER";
  256. var dispatch = await _kpiCalcDispatcher.DispatchAsync(
  257. "S6_L2_002", ModuleCode, option.TargetTenantId, option.TargetFactoryId,
  258. option.BizDate, option.BizDate, option.BizDate, option.SourceZtid,
  259. batchId, triggerType, legacyValue, legacyDenom, ct);
  260. sub.KpiRows = dispatch.ShouldUpsert
  261. ? await UpsertKpiValueAsync("S6_L2_002", option.BizDate, dispatch.MetricValue, now, option, L2ValueTable)
  262. : 0;
  263. sub.DenominatorStatus = dispatch.DenominatorStatus;
  264. // 调度:SUMMARY 成功/NO_DATA 后触发对应 DIMENSION 跑批(共享 BatchId;SUMMARY FAILED 不触发)。
  265. if (dispatch.ShouldUpsert)
  266. {
  267. try
  268. {
  269. await _dimensionRun.RunDimensionAsync(
  270. "S6_L2_002", ModuleCode, option.TargetTenantId, option.BizDate, batchId, triggerType, ct);
  271. }
  272. catch (Exception ex)
  273. {
  274. _logger.LogWarning(ex, "S6_L2_002 维度跑批异常(不影响汇总链路)");
  275. }
  276. }
  277. return sub;
  278. }
  279. /// <summary>工单制造人效 = 完成的 PROD_RECEIPT 行数 / PRODUCTION ACTIVE 人数。归位 L2:写 S6_L2_003。</summary>
  280. private async Task<KpiBuildSubResult> BuildS6L2003WorkOrderMfgEfficiencyAsync(
  281. string batchId, DateTime now, S6MdpRefreshOption option, string triggerType, CancellationToken ct)
  282. {
  283. var sub = new KpiBuildSubResult();
  284. const string sqlNumer = @"
  285. select case
  286. when sum(case when doc_qty is not null or line_closed_flag=1 then 1 else 0 end)=0 then null
  287. else sum(case when qty_change>0 and (qty_change>=doc_qty or line_closed_flag=1) then 1 else 0 end)
  288. end as ddnum
  289. from mdp_std_inv_trans
  290. where tenant_id=@tenantId
  291. and biz_doc_type='PROD_RECEIPT' and summary_flag=0 and void_flag=0 and approved_flag=1 AND source_system=@sourceSystem
  292. and eff_date between @startDate and @endDate";
  293. const string sqlDenom = @"
  294. select count(*) as penum
  295. from mdp_std_employee
  296. where tenant_id=@tenantId and employment_status='ACTIVE' and position_code='PRODUCTION' AND source_system=@empSource";
  297. var pNumer = new[]
  298. {
  299. new SugarParameter("@tenantId", option.TargetTenantId),
  300. new SugarParameter("@startDate", option.MonthlyPeriodStart),
  301. new SugarParameter("@endDate", option.MonthlyPeriodEnd),
  302. new SugarParameter("@sourceDomain", option.SourceZtid),
  303. new SugarParameter("@sourceSystem", await SourceOfAsync(option.TargetTenantId, "INV_TRANS", ct))
  304. };
  305. var pDenom = new[]
  306. {
  307. new SugarParameter("@tenantId", option.TargetTenantId),
  308. new SugarParameter("@sourceDomain", option.SourceZtid),
  309. new SugarParameter("@empSource", await SourceOfAsync(option.TargetTenantId, "EMPLOYEE", ct))
  310. };
  311. var numerRows = await _db.Ado.SqlQueryAsync<S6CountRow>(sqlNumer, pNumer);
  312. var denomRows = await _db.Ado.SqlQueryAsync<S6PeNumRow>(sqlDenom, pDenom);
  313. sub.T8Rows = numerRows.Count + denomRows.Count;
  314. int? doneCount = numerRows.FirstOrDefault()?.ddnum;
  315. int? headcount = denomRows.FirstOrDefault()?.penum;
  316. decimal? efficiency = null;
  317. string denomStatus;
  318. if (!headcount.HasValue || headcount.Value <= 0)
  319. denomStatus = "NO_HEADCOUNT";
  320. else if (!doneCount.HasValue)
  321. denomStatus = "NO_NUMERATOR";
  322. else
  323. {
  324. efficiency = Math.Round((decimal)doneCount.Value / headcount.Value, 4);
  325. denomStatus = "OK";
  326. }
  327. sub.DenominatorStatus = denomStatus;
  328. var dwdAffected = await _db.Ado.ExecuteCommandAsync(@"
  329. INSERT INTO dwd_work_order_mfg_efficiency
  330. (tenant_id, factory_id, biz_month, source_ztid, period_start, period_end,
  331. done_count, production_headcount, efficiency, denominator_status, batch_id, create_time)
  332. VALUES
  333. (@tenantId, @factoryId, @bizMonth, @sourceDomain, @periodStart, @periodEnd,
  334. @doneCount, @headcount, @efficiency, @denomStatus, @batchId, @now)
  335. ON DUPLICATE KEY UPDATE
  336. period_start=VALUES(period_start), period_end=VALUES(period_end),
  337. done_count=VALUES(done_count), production_headcount=VALUES(production_headcount),
  338. efficiency=VALUES(efficiency), denominator_status=VALUES(denominator_status),
  339. batch_id=VALUES(batch_id), update_time=@now",
  340. new SugarParameter("@tenantId", option.TargetTenantId),
  341. new SugarParameter("@factoryId", option.TargetFactoryId),
  342. new SugarParameter("@bizMonth", option.BizMonth),
  343. new SugarParameter("@sourceDomain", option.SourceZtid),
  344. new SugarParameter("@periodStart", option.MonthlyPeriodStart),
  345. new SugarParameter("@periodEnd", option.MonthlyPeriodEnd),
  346. new SugarParameter("@doneCount", doneCount),
  347. new SugarParameter("@headcount", headcount),
  348. new SugarParameter("@efficiency", efficiency),
  349. new SugarParameter("@denomStatus", denomStatus),
  350. new SugarParameter("@batchId", batchId),
  351. new SugarParameter("@now", now));
  352. sub.DwdRows = dwdAffected;
  353. // 月度 KPI 最终聚合交分发器;bizDate=月末、period=当月窗口;legacyValue=efficiency、legacyDenom 保留 NO_HEADCOUNT/NO_NUMERATOR。
  354. var dispatch = await _kpiCalcDispatcher.DispatchAsync(
  355. "S6_L2_003", ModuleCode, option.TargetTenantId, option.TargetFactoryId,
  356. option.MonthlyPeriodEnd, option.MonthlyPeriodStart, option.MonthlyPeriodEnd, option.SourceZtid,
  357. batchId, triggerType, efficiency, denomStatus, ct);
  358. sub.KpiRows = dispatch.ShouldUpsert
  359. ? await UpsertKpiValueAsync("S6_L2_003", option.MonthlyPeriodEnd, dispatch.MetricValue, now, option, L2ValueTable)
  360. : 0;
  361. sub.DenominatorStatus = dispatch.DenominatorStatus;
  362. // 调度:SUMMARY 成功/NO_DATA 后触发人效月度 DIMENSION 跑批(月度:@biz_date=月末派生 biz_month)。
  363. if (dispatch.ShouldUpsert)
  364. {
  365. try
  366. {
  367. await _dimensionRun.RunDimensionAsync(
  368. "S6_L2_003", ModuleCode, option.TargetTenantId, option.MonthlyPeriodEnd, batchId, triggerType, ct);
  369. }
  370. catch (Exception ex)
  371. {
  372. _logger.LogWarning(ex, "S6_L2_003 维度跑批异常(不影响汇总链路)");
  373. }
  374. }
  375. return sub;
  376. }
  377. /// <summary>工单在制周转 = 在制工单成本 / 当期工单入库成本 × 30。</summary>
  378. private Task<KpiBuildSubResult> BuildS6L2004WorkOrderWipTurnoverAsync(
  379. string batchId, DateTime now, S6MdpRefreshOption option, string triggerType, CancellationToken ct)
  380. => DispatchExecutionKpiAsync(
  381. "S6_L2_004",
  382. """
  383. SELECT ROUND(
  384. 30 * SUM(IFNULL(QtyWIP,0) * IFNULL(NULLIF(PerAmt,0),1))
  385. / NULLIF(SUM(IFNULL(QtyComplete,0) * IFNULL(NULLIF(PerAmt,0),1)),0),
  386. 4) AS MetricValue,
  387. SUM(CASE WHEN IFNULL(QtyComplete,0)>0 THEN 1 ELSE 0 END) AS RowCount
  388. FROM WorkOrdRouting
  389. WHERE tenant_id=@TenantId
  390. """,
  391. "NO_WORK_ORDER_COMPLETION",
  392. L2ValueTable,
  393. batchId, now, option, triggerType, ct);
  394. private Task<KpiBuildSubResult> BuildS6ExecutionDetailKpiAsync(
  395. string metricCode, string batchId, DateTime now, S6MdpRefreshOption option,
  396. string triggerType, CancellationToken ct)
  397. {
  398. var (sql, emptyDenom) = metricCode switch
  399. {
  400. "S6_L3_001" => (
  401. """
  402. SELECT ROUND(AVG(TIMESTAMPDIFF(MINUTE,StartDate,EndDate)/1440),4) AS MetricValue,
  403. COUNT(*) AS RowCount
  404. FROM WorkOrdRouting
  405. WHERE tenant_id=@TenantId AND StartDate IS NOT NULL AND EndDate>=StartDate
  406. """,
  407. "NO_COMPLETED_OPERATION"),
  408. "S6_L3_002" => (
  409. """
  410. SELECT ROUND(
  411. 100 * SUM(CASE WHEN EndDate IS NOT NULL AND DueDate IS NOT NULL AND EndDate<=DueDate
  412. THEN LEAST(IFNULL(QtyComplete,0),IFNULL(QtyOrded,0)) ELSE 0 END)
  413. / NULLIF(SUM(IFNULL(QtyOrded,0)),0),
  414. 4) AS MetricValue,
  415. SUM(CASE WHEN DueDate IS NOT NULL AND IFNULL(QtyOrded,0)>0 THEN 1 ELSE 0 END) AS RowCount
  416. FROM WorkOrdRouting
  417. WHERE tenant_id=@TenantId
  418. """,
  419. "NO_PLANNED_OPERATION"),
  420. "S6_L3_003" => (
  421. """
  422. SELECT ROUND(
  423. (SELECT COUNT(*) FROM WorkOrdRouting r
  424. WHERE r.tenant_id=@TenantId AND r.EndDate IS NOT NULL AND IFNULL(r.QtyComplete,0)>0)
  425. / NULLIF((
  426. SELECT COUNT(DISTINCT NULLIF(TRIM(e.Employee),''))
  427. FROM OpTransEmployee e
  428. WHERE EXISTS (
  429. SELECT 1 FROM WorkOrdRouting r2
  430. WHERE r2.tenant_id=@TenantId AND r2.WorkOrd=e.WorkOrd
  431. )
  432. ),0),
  433. 4) AS MetricValue,
  434. (SELECT COUNT(*) FROM WorkOrdRouting r
  435. WHERE r.tenant_id=@TenantId AND r.EndDate IS NOT NULL AND IFNULL(r.QtyComplete,0)>0) AS RowCount
  436. """,
  437. "NO_OPERATION_OPERATOR"),
  438. "S6_L3_004" => (
  439. """
  440. SELECT ROUND(
  441. 30 * SUM(IFNULL(QtyWIP,0) * IFNULL(NULLIF(PerAmt,0),1))
  442. / NULLIF(SUM(IFNULL(QtyComplete,0) * IFNULL(NULLIF(PerAmt,0),1)),0),
  443. 4) AS MetricValue,
  444. SUM(CASE WHEN IFNULL(QtyComplete,0)>0 THEN 1 ELSE 0 END) AS RowCount
  445. FROM WorkOrdRouting
  446. WHERE tenant_id=@TenantId
  447. """,
  448. "NO_OPERATION_COMPLETION"),
  449. "S6_L3_005" => (
  450. """
  451. SELECT ROUND(AVG(cycle_days),4) AS MetricValue, COUNT(*) AS RowCount
  452. FROM (
  453. SELECT Machine,
  454. TIMESTAMPDIFF(MINUTE,MIN(StartDate),MAX(EndDate))/1440 AS cycle_days
  455. FROM WorkOrdRouting
  456. WHERE tenant_id=@TenantId AND NULLIF(TRIM(Machine),'') IS NOT NULL
  457. AND StartDate IS NOT NULL AND EndDate>=StartDate
  458. GROUP BY Machine
  459. ) x
  460. """,
  461. "NO_COMPLETED_EQUIPMENT_TASK"),
  462. "S6_L3_006" => (
  463. """
  464. SELECT ROUND(
  465. 100 * SUM(CASE WHEN EndDate IS NOT NULL AND DueDate IS NOT NULL AND EndDate<=DueDate
  466. THEN LEAST(IFNULL(QtyComplete,0),IFNULL(QtyOrded,0)) ELSE 0 END)
  467. / NULLIF(SUM(IFNULL(QtyOrded,0)),0),
  468. 4) AS MetricValue,
  469. COUNT(DISTINCT NULLIF(TRIM(Machine),'')) AS RowCount
  470. FROM WorkOrdRouting
  471. WHERE tenant_id=@TenantId AND NULLIF(TRIM(Machine),'') IS NOT NULL
  472. """,
  473. "NO_PLANNED_EQUIPMENT_TASK"),
  474. "S6_L3_007" => (
  475. """
  476. SELECT ROUND(
  477. 100 * SUM(IFNULL(StdRunTime,0)
  478. * GREATEST(IFNULL(QtyComplete,0)-IFNULL(CumRejected,0)-IFNULL(QtyScrap,0),0))
  479. / NULLIF(SUM(IFNULL(ActRunTime,0)),0),
  480. 4) AS MetricValue,
  481. SUM(CASE WHEN IFNULL(ActRunTime,0)>0 AND IFNULL(StdRunTime,0)>0
  482. THEN 1 ELSE 0 END) AS RowCount
  483. FROM WorkOrdRouting
  484. WHERE tenant_id=@TenantId AND NULLIF(TRIM(Machine),'') IS NOT NULL
  485. """,
  486. "NO_OEE_RUNTIME"),
  487. "S6_L3_008" => (
  488. """
  489. SELECT ROUND(
  490. SUM(IFNULL(QtyWIP,0)) / NULLIF(SUM(IFNULL(QtyComplete,0)),0),
  491. 4) AS MetricValue,
  492. COUNT(DISTINCT NULLIF(TRIM(Machine),'')) AS RowCount
  493. FROM WorkOrdRouting
  494. WHERE tenant_id=@TenantId AND NULLIF(TRIM(Machine),'') IS NOT NULL
  495. """,
  496. "NO_EQUIPMENT_COMPLETION"),
  497. _ => throw new ArgumentOutOfRangeException(nameof(metricCode), metricCode, "不支持的 S6 明细指标")
  498. };
  499. return DispatchExecutionKpiAsync(
  500. metricCode, sql, emptyDenom, L3ValueTable,
  501. batchId, now, option, triggerType, ct);
  502. }
  503. private async Task<KpiBuildSubResult> DispatchExecutionKpiAsync(
  504. string metricCode, string sql, string emptyDenom, string valueTable,
  505. string batchId, DateTime now, S6MdpRefreshOption option, string triggerType, CancellationToken ct)
  506. {
  507. var row = await _db.Ado.SqlQuerySingleAsync<S6ExecutionKpiRow>(
  508. sql, new SugarParameter("@TenantId", option.TargetTenantId));
  509. var value = row?.RowCount > 0 ? row.MetricValue : null;
  510. var dispatch = await _kpiCalcDispatcher.DispatchAsync(
  511. metricCode, ModuleCode, option.TargetTenantId, option.TargetFactoryId,
  512. option.BizDate, option.BizDate, option.BizDate, option.SourceZtid,
  513. batchId, triggerType, value, value.HasValue ? "OK" : emptyDenom, ct);
  514. var sub = new KpiBuildSubResult
  515. {
  516. T8Rows = row?.RowCount ?? 0,
  517. KpiRows = dispatch.ShouldUpsert
  518. ? await UpsertKpiValueAsync(metricCode, option.BizDate, dispatch.MetricValue, now, option, valueTable)
  519. : 0,
  520. DenominatorStatus = dispatch.DenominatorStatus
  521. };
  522. await RunDimensionSafelyAsync(
  523. metricCode, option.BizDate, batchId, triggerType, option, dispatch.ShouldUpsert, ct);
  524. return sub;
  525. }
  526. /// <summary>订单制造周期 = 每个完成订单最晚完工时间 - 最早投产时间,再取订单平均。</summary>
  527. private async Task<KpiBuildSubResult> BuildS6L1001OrderMfgCycleAsync(
  528. string batchId, DateTime now, S6MdpRefreshOption option, string triggerType, CancellationToken ct)
  529. {
  530. const string sql = @"
  531. select order_no, datediff(max(completion_time), min(start_time)) as cycle_days
  532. from (
  533. select b.order_no, b.task_no, b.item_code, b.release_time as start_time,
  534. case when b.closed_flag=1 and b.closed_time is not null then b.closed_time else max(d.completion_time) end as completion_time,
  535. case when b.closed_flag=1 or sum(ifnull(d.qty_change,0))>=b.qty_planned then 1 else 0 end as completed
  536. from mdp_std_work_order_line b
  537. left join (
  538. select ref_task_no, item_num, qty_change, ifnull(line_closed_time, approved_time) as completion_time
  539. from mdp_std_inv_trans
  540. where tenant_id=@tenantId
  541. and biz_doc_type='PROD_RECEIPT' and summary_flag=0 and void_flag=0 and approved_flag=1 AND source_system=@sourceSystem
  542. ) d on b.task_no=d.ref_task_no and b.item_code=d.item_num
  543. where b.tenant_id=@tenantId
  544. and b.doc_type='PROD_TASK' and b.void_flag=0 and b.approved_flag=1 and b.order_no is not null
  545. group by b.order_no, b.task_no, b.item_code, b.qty_planned, b.release_time, b.closed_flag, b.closed_time
  546. ) n
  547. group by order_no
  548. having min(completed)=1 and min(start_time) is not null and max(completion_time) is not null";
  549. var rows = await _db.Ado.SqlQueryAsync<S6OrderCycleRow>(sql, new[]
  550. {
  551. new SugarParameter("@tenantId", option.TargetTenantId),
  552. new SugarParameter("@sourceDomain", option.SourceZtid),
  553. new SugarParameter("@sourceSystem", await SourceOfAsync(option.TargetTenantId, "INV_TRANS", ct))
  554. });
  555. var cycles = rows.Where(r => r.cycle_days.HasValue && r.cycle_days.Value >= 0)
  556. .Select(r => (decimal)r.cycle_days!.Value).ToList();
  557. decimal? value = cycles.Count > 0 ? Math.Round(cycles.Average(), 4) : null;
  558. var denom = cycles.Count > 0 ? "OK" : "NO_COMPLETED_ORDER";
  559. var dispatch = await _kpiCalcDispatcher.DispatchAsync(
  560. "S6_L1_001", ModuleCode, option.TargetTenantId, option.TargetFactoryId,
  561. option.BizDate, option.BizDate, option.BizDate, option.SourceZtid,
  562. batchId, triggerType, value, denom, ct);
  563. var sub = new KpiBuildSubResult
  564. {
  565. T8Rows = rows.Count,
  566. KpiRows = dispatch.ShouldUpsert
  567. ? await UpsertKpiValueAsync("S6_L1_001", option.BizDate, dispatch.MetricValue, now, option)
  568. : 0,
  569. DenominatorStatus = dispatch.DenominatorStatus
  570. };
  571. await RunDimensionSafelyAsync("S6_L1_001", option.BizDate, batchId, triggerType, option, dispatch.ShouldUpsert, ct);
  572. return sub;
  573. }
  574. /// <summary>订单制造满足率 = AVG(clamp(SUM(交期内完成量)/SUM(投产量), 0..1)) × 100。</summary>
  575. private async Task<KpiBuildSubResult> BuildS6L1002OrderMfgFulfillmentAsync(
  576. string batchId, DateTime now, S6MdpRefreshOption option, string triggerType, CancellationToken ct)
  577. {
  578. const string sql = @"
  579. select order_no, sum(plan_qty) as plan_qty, sum(done_qty_in_window) as done_qty_in_window
  580. from dwd_work_order_mfg_fulfillment
  581. where tenant_id=@tenantId and factory_id=@factoryId and biz_date=@bizDate and source_ztid=@sourceDomain
  582. group by order_no";
  583. var rows = await _db.Ado.SqlQueryAsync<S6OrderFulfillmentRow>(sql,
  584. new SugarParameter("@tenantId", option.TargetTenantId),
  585. new SugarParameter("@factoryId", option.TargetFactoryId),
  586. new SugarParameter("@bizDate", option.BizDate),
  587. new SugarParameter("@sourceDomain", option.SourceZtid));
  588. decimal? value = CalculateOrderFulfillmentPercent(
  589. rows.Select(r => (r.plan_qty, r.done_qty_in_window)));
  590. var denom = value.HasValue ? "OK" : "NO_VALID_ORDER";
  591. var dispatch = await _kpiCalcDispatcher.DispatchAsync(
  592. "S6_L1_002", ModuleCode, option.TargetTenantId, option.TargetFactoryId,
  593. option.BizDate, option.BizDate, option.BizDate, option.SourceZtid,
  594. batchId, triggerType, value, denom, ct);
  595. var sub = new KpiBuildSubResult
  596. {
  597. T8Rows = rows.Count,
  598. KpiRows = dispatch.ShouldUpsert
  599. ? await UpsertKpiValueAsync("S6_L1_002", option.BizDate, dispatch.MetricValue, now, option)
  600. : 0,
  601. DenominatorStatus = dispatch.DenominatorStatus
  602. };
  603. await RunDimensionSafelyAsync("S6_L1_002", option.BizDate, batchId, triggerType, option, dispatch.ShouldUpsert, ct);
  604. return sub;
  605. }
  606. internal static decimal? CalculateOrderFulfillmentPercent(
  607. IEnumerable<(decimal? PlanQty, decimal? DoneQty)> orders)
  608. {
  609. var rates = orders
  610. .Where(r => r.PlanQty.HasValue && r.PlanQty.Value > 0m && r.DoneQty.HasValue)
  611. .Select(r => Math.Clamp(r.DoneQty!.Value / r.PlanQty!.Value, 0m, 1m))
  612. .ToList();
  613. return rates.Count > 0 ? Math.Round(rates.Average() * 100m, 4) : null;
  614. }
  615. /// <summary>订单制造人效 = 统计期内完成制造的订单数 / PRODUCTION ACTIVE 人数。</summary>
  616. private async Task<KpiBuildSubResult> BuildS6L1003OrderMfgEfficiencyAsync(
  617. string batchId, DateTime now, S6MdpRefreshOption option, string triggerType, CancellationToken ct)
  618. {
  619. const string sqlNumer = @"
  620. select count(*) as ddnum
  621. from (
  622. select order_no
  623. from (
  624. select b.order_no, b.task_no, b.item_code,
  625. case when b.closed_flag=1 and b.closed_time is not null then b.closed_time else max(d.completion_time) end as completion_time,
  626. case when b.closed_flag=1 or sum(ifnull(d.qty_change,0))>=b.qty_planned then 1 else 0 end as completed
  627. from mdp_std_work_order_line b
  628. left join (
  629. select ref_task_no, item_num, qty_change, ifnull(line_closed_time, approved_time) as completion_time
  630. from mdp_std_inv_trans
  631. where tenant_id=@tenantId
  632. and biz_doc_type='PROD_RECEIPT' and summary_flag=0 and void_flag=0 and approved_flag=1 AND source_system=@sourceSystem
  633. ) d on b.task_no=d.ref_task_no and b.item_code=d.item_num
  634. where b.tenant_id=@tenantId
  635. and b.doc_type='PROD_TASK' and b.void_flag=0 and b.approved_flag=1 and b.order_no is not null
  636. group by b.order_no, b.task_no, b.item_code, b.qty_planned, b.closed_flag, b.closed_time
  637. ) order_lines
  638. group by order_no
  639. having min(completed)=1 and max(completion_time) between @startDate and @endDate
  640. ) orders_done";
  641. const string sqlDenom = @"
  642. select count(*) as penum
  643. from mdp_std_employee
  644. where tenant_id=@tenantId and employment_status='ACTIVE' and position_code='PRODUCTION' AND source_system=@empSource";
  645. var numerRows = await _db.Ado.SqlQueryAsync<S6CountRow>(sqlNumer,
  646. new SugarParameter("@tenantId", option.TargetTenantId),
  647. new SugarParameter("@startDate", option.MonthlyPeriodStart),
  648. new SugarParameter("@endDate", option.MonthlyPeriodEnd),
  649. new SugarParameter("@sourceDomain", option.SourceZtid),
  650. new SugarParameter("@sourceSystem", await SourceOfAsync(option.TargetTenantId, "INV_TRANS", ct)));
  651. var denomRows = await _db.Ado.SqlQueryAsync<S6PeNumRow>(sqlDenom,
  652. new SugarParameter("@tenantId", option.TargetTenantId),
  653. new SugarParameter("@sourceDomain", option.SourceZtid),
  654. new SugarParameter("@empSource", await SourceOfAsync(option.TargetTenantId, "EMPLOYEE", ct)));
  655. int? doneCount = numerRows.FirstOrDefault()?.ddnum;
  656. int? headcount = denomRows.FirstOrDefault()?.penum;
  657. decimal? value = null;
  658. string denom;
  659. if (!headcount.HasValue || headcount.Value <= 0)
  660. denom = "NO_HEADCOUNT";
  661. else if (!doneCount.HasValue)
  662. denom = "NO_NUMERATOR";
  663. else
  664. {
  665. value = Math.Round((decimal)doneCount.Value / headcount.Value, 4);
  666. denom = "OK";
  667. }
  668. var dispatch = await _kpiCalcDispatcher.DispatchAsync(
  669. "S6_L1_003", ModuleCode, option.TargetTenantId, option.TargetFactoryId,
  670. option.MonthlyPeriodEnd, option.MonthlyPeriodStart, option.MonthlyPeriodEnd, option.SourceZtid,
  671. batchId, triggerType, value, denom, ct);
  672. var sub = new KpiBuildSubResult
  673. {
  674. T8Rows = numerRows.Count + denomRows.Count,
  675. KpiRows = dispatch.ShouldUpsert
  676. ? await UpsertKpiValueAsync("S6_L1_003", option.MonthlyPeriodEnd, dispatch.MetricValue, now, option)
  677. : 0,
  678. DenominatorStatus = dispatch.DenominatorStatus
  679. };
  680. await RunDimensionSafelyAsync("S6_L1_003", option.MonthlyPeriodEnd, batchId, triggerType, option, dispatch.ShouldUpsert, ct);
  681. return sub;
  682. }
  683. private async Task RunDimensionSafelyAsync(
  684. string metricCode, DateTime bizDate, string batchId, string triggerType,
  685. S6MdpRefreshOption option, bool shouldRun, CancellationToken ct)
  686. {
  687. if (!shouldRun) return;
  688. try
  689. {
  690. await _dimensionRun.RunDimensionAsync(
  691. metricCode, ModuleCode, option.TargetTenantId, bizDate, batchId, triggerType, ct);
  692. }
  693. catch (Exception ex)
  694. {
  695. _logger.LogWarning(ex, "{MetricCode} 维度跑批异常(不影响汇总链路)", metricCode);
  696. }
  697. }
  698. // ─────────────────────────────────────────────────────────────────────────
  699. private async Task<int> UpsertKpiValueAsync(string metricCode, DateTime bizDate, decimal? metricValue, DateTime now, S6MdpRefreshOption option, string valueTable = "ado_s9_kpi_value_l1_day")
  700. {
  701. // 沿用 S3 UpsertS3KpiValueAsync 范式:先查现存行 → UPDATE;不存在 → SELECT MAX(id)+1 显式生成 id 后 INSERT。
  702. // 值表 id 为手工分配主键(无 AUTO_INCREMENT),必须显式 set;metric_value 允许 NULL(分母缺失不得伪装真实 0)。
  703. // valueTable:L1 KPI 写 ado_s9_kpi_value_l1_day;L2(本服务工单指标 S6_L2_002/003)写 ado_s9_kpi_value_l2_day。
  704. // 表名为受控常量(非用户输入),可安全内插;各表 id 序列独立,MAX(id) 取目标表。
  705. // FIX-2:截断时分秒(月度 KPI 入参可能为 YYYY-MM-DD 23:59:59),保证 SELECT WHERE biz_date=@BizDate 与 DB date 列匹配。
  706. bizDate = bizDate.Date;
  707. var decision = await _kpiStatus.ResolveAsync(option.TargetTenantId, metricCode, metricValue);
  708. metricValue = decision.Value;
  709. var snap = await _kpiTargetResolver.ResolveAsync(option.TargetTenantId, option.TargetFactoryId, metricCode, ModuleCode, bizDate);
  710. var existingId = await _db.Ado.GetLongAsync(
  711. $"SELECT IFNULL((SELECT id FROM {valueTable} WHERE tenant_id=@TenantId AND factory_id=@FactoryId " +
  712. "AND module_code=@ModuleCode AND metric_code=@MetricCode AND biz_date=@BizDate AND is_deleted=0 " +
  713. "ORDER BY id LIMIT 1), 0)",
  714. new List<SugarParameter>
  715. {
  716. new("@TenantId", option.TargetTenantId),
  717. new("@FactoryId", option.TargetFactoryId),
  718. new("@ModuleCode", ModuleCode),
  719. new("@MetricCode", metricCode),
  720. new("@BizDate", bizDate)
  721. });
  722. if (existingId > 0)
  723. {
  724. return await _db.Ado.ExecuteCommandAsync(
  725. $"UPDATE {valueTable} SET {SmartOps.KpiResultWrite.SetClause}metric_value=@MetricValue, target_value=@TargetValue, " +
  726. "target_config_id=@TargetConfigId, target_source=@TargetSource, target_resolved_at=@TargetResolvedAt, " +
  727. "calc_time=@Now, update_time=@Now, is_deleted=0, is_active=1 WHERE id=@Id",
  728. new SugarParameter("@MetricValue", metricValue),
  729. SmartOps.KpiResultWrite.Status(decision.Status),
  730. SmartOps.KpiResultWrite.Reason(decision.Reason),
  731. new SugarParameter("@TargetValue", SmartOps.KpiTargetSnapshotSql.ValueOrDbNull(snap)),
  732. new SugarParameter("@TargetConfigId", SmartOps.KpiTargetSnapshotSql.ConfigIdOrDbNull(snap)),
  733. new SugarParameter("@TargetSource", SmartOps.KpiTargetSnapshotSql.SourceOrDbNull(snap)),
  734. new SugarParameter("@TargetResolvedAt", snap.ResolvedAt),
  735. new SugarParameter("@Now", now),
  736. new SugarParameter("@Id", existingId));
  737. }
  738. var nextId = Yitter.IdGenerator.YitIdHelper.NextId();
  739. return await _db.Ado.ExecuteCommandAsync($@"
  740. INSERT INTO {valueTable}
  741. (id, tenant_id, org_id, company_id, factory_id, status, biz_date,
  742. create_time, update_time, is_deleted, is_active,
  743. module_code, metric_code, result_status, result_reason, metric_value, target_value, calc_time,
  744. target_config_id, target_source, target_resolved_at)
  745. VALUES
  746. (@Id, @TenantId, NULL, NULL, @FactoryId, NULL, @BizDate,
  747. @Now, @Now, 0, 1,
  748. @ModuleCode, @MetricCode, @ResultStatus, @ResultReason, @MetricValue, @TargetValue, @Now,
  749. @TargetConfigId, @TargetSource, @TargetResolvedAt)",
  750. new SugarParameter("@Id", nextId),
  751. new SugarParameter("@TenantId", option.TargetTenantId),
  752. new SugarParameter("@FactoryId", option.TargetFactoryId),
  753. new SugarParameter("@BizDate", bizDate),
  754. new SugarParameter("@Now", now),
  755. new SugarParameter("@ModuleCode", ModuleCode),
  756. new SugarParameter("@MetricCode", metricCode),
  757. SmartOps.KpiResultWrite.Status(decision.Status),
  758. SmartOps.KpiResultWrite.Reason(decision.Reason),
  759. new SugarParameter("@MetricValue", metricValue),
  760. new SugarParameter("@TargetValue", SmartOps.KpiTargetSnapshotSql.ValueOrDbNull(snap)),
  761. new SugarParameter("@TargetConfigId", SmartOps.KpiTargetSnapshotSql.ConfigIdOrDbNull(snap)),
  762. new SugarParameter("@TargetSource", SmartOps.KpiTargetSnapshotSql.SourceOrDbNull(snap)),
  763. new SugarParameter("@TargetResolvedAt", snap.ResolvedAt));
  764. }
  765. private async Task<long> InsertTransformRunLogAsync(string batchId, DateTime startedAt, string triggerType, S6MdpRefreshOption option)
  766. {
  767. await _db.Ado.ExecuteCommandAsync(@"
  768. INSERT INTO mdp_transform_run_log
  769. (tenant_id, job_code, job_name, trigger_type, batch_id, status, start_time, stage_rows, standard_rows, dwd_rows, create_time, update_time)
  770. VALUES
  771. (@TenantId, @JobCode, @JobName, @TriggerType, @BatchId, 'RUNNING', @StartTime, 0, 0, 0, @StartTime, @StartTime)",
  772. new SugarParameter("@TenantId", option.TargetTenantId),
  773. new SugarParameter("@JobCode", JobCode),
  774. new SugarParameter("@JobName", JobName),
  775. new SugarParameter("@TriggerType", triggerType),
  776. new SugarParameter("@BatchId", batchId),
  777. new SugarParameter("@StartTime", startedAt));
  778. return await _db.Ado.GetLongAsync(
  779. "SELECT id FROM mdp_transform_run_log WHERE batch_id=@BatchId ORDER BY id DESC LIMIT 1",
  780. new List<SugarParameter> { new("@BatchId", batchId) });
  781. }
  782. private async Task MarkTransformRunSuccessAsync(long runLogId, DateTime startedAt, S6MdpSyncTransformResult result)
  783. {
  784. var finishedAt = DateTime.Now;
  785. await _db.Ado.ExecuteCommandAsync(@"
  786. UPDATE mdp_transform_run_log
  787. SET status='SUCCESS', end_time=@EndTime, duration_ms=@DurationMs,
  788. stage_rows=@StageRows, standard_rows=@StandardRows, dwd_rows=@DwdRows,
  789. summary_json=@SummaryJson, update_time=CURRENT_TIMESTAMP
  790. WHERE id=@Id",
  791. new SugarParameter("@EndTime", finishedAt),
  792. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  793. new SugarParameter("@StageRows", result.StageRows),
  794. new SugarParameter("@StandardRows", result.StandardRows),
  795. new SugarParameter("@DwdRows", result.DwdRows),
  796. new SugarParameter("@SummaryJson", JsonSerializer.Serialize(new
  797. {
  798. batchId = result.BatchId,
  799. sourceZtid = result.SourceZtid,
  800. bizDate = result.BizDate.ToString("yyyy-MM-dd"),
  801. bizMonth = result.BizMonth,
  802. dwdRows = result.DwdRows,
  803. kpiRows = result.KpiRows,
  804. perKpiDwdRows = result.PerKpiDwdRows,
  805. perKpiKpiRows = result.PerKpiKpiRows,
  806. denominatorStatus = result.KpiDenominatorStatus
  807. })),
  808. new SugarParameter("@Id", runLogId));
  809. }
  810. private async Task MarkTransformRunFailedAsync(long runLogId, DateTime startedAt, string message, string batchId)
  811. {
  812. bool runLogUpdated = false;
  813. try
  814. {
  815. var finishedAt = DateTime.Now;
  816. await _db.Ado.ExecuteCommandAsync(@"
  817. UPDATE mdp_transform_run_log
  818. SET status='FAILED', end_time=@EndTime, duration_ms=@DurationMs,
  819. error_message=@ErrorMessage, update_time=CURRENT_TIMESTAMP
  820. WHERE id=@Id",
  821. new SugarParameter("@EndTime", finishedAt),
  822. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  823. new SugarParameter("@ErrorMessage", Truncate(message, 2000)),
  824. new SugarParameter("@Id", runLogId));
  825. runLogUpdated = true;
  826. }
  827. catch (Exception ex)
  828. {
  829. Console.Error.WriteLine($"[S6MdpSyncTransform] MarkTransformRunFailed write failed (runLogId={runLogId}): {ex.Message}");
  830. }
  831. // FAILURE-NOTIFICATION-1:写库 FAILED 成功后发通知给超级管理员;通知失败不影响主流程
  832. if (!runLogUpdated) return;
  833. try
  834. {
  835. await _sysNoticeService.AddNotice(new AddNoticeInput
  836. {
  837. Title = "S6 生产执行 T8 KPI 跑批失败",
  838. Content = $"模块:S6 生产执行\n批次ID:{batchId}\n失败时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}\n错误信息:{Truncate(message, 1000)}\n\n请查看 mdp_transform_run_log 获取完整错误与重试记录。",
  839. Type = NoticeTypeEnum.NOTICE,
  840. PublicTime = DateTime.Now,
  841. Status = NoticeStatusEnum.PUBLIC,
  842. PublicUserId = NoticeReceiverUserId,
  843. PublicUserName = NoticeReceiverUserName
  844. });
  845. }
  846. catch (Exception notifyEx)
  847. {
  848. _logger.LogError(notifyEx, "[S6MdpSyncTransform] SysNotice 发送失败 (runLogId={RunLogId}, batchId={BatchId})", runLogId, batchId);
  849. }
  850. }
  851. private static string NormalizeTriggerType(string s) =>
  852. string.IsNullOrWhiteSpace(s) ? "AUTO" : s.Trim().ToUpperInvariant();
  853. private static void NormalizeOption(S6MdpRefreshOption option)
  854. {
  855. var d = S6MdpRefreshOption.Default();
  856. if (option.TargetFactoryId <= 0) option.TargetFactoryId = d.TargetFactoryId;
  857. if (string.IsNullOrWhiteSpace(option.SourceZtid)) option.SourceZtid = d.SourceZtid;
  858. option.TargetTenantId = AidopSourceTenantMap.ResolveTenantId(option.SourceZtid, option.TargetTenantId);
  859. if (option.BizDate == default) option.BizDate = d.BizDate;
  860. if (string.IsNullOrWhiteSpace(option.BizMonth)) option.BizMonth = d.BizMonth;
  861. if (option.MonthlyPeriodStart == default) option.MonthlyPeriodStart = d.MonthlyPeriodStart;
  862. if (option.MonthlyPeriodEnd == default) option.MonthlyPeriodEnd = d.MonthlyPeriodEnd;
  863. }
  864. private static string Truncate(string s, int max) =>
  865. string.IsNullOrEmpty(s) ? "" : (s.Length <= max ? s : s.Substring(0, max));
  866. }
  867. // DTO ────────────────────────────────────────────────────────────────────────
  868. public sealed class S6MdpRefreshOption
  869. {
  870. public string SourceZtid { get; set; } = "pbxfxp";
  871. /// <summary>KPI/DWD 落库目标租户;≤0 时由 <see cref="AidopSourceTenantMap"/> 按 SourceZtid 解析。</summary>
  872. public long TargetTenantId { get; set; }
  873. /// <summary>KPI/DWD 落库目标工厂;默认 1。</summary>
  874. public long TargetFactoryId { get; set; } = 1L;
  875. public DateTime BizDate { get; set; }
  876. public string BizMonth { get; set; } = "";
  877. public DateTime MonthlyPeriodStart { get; set; }
  878. public DateTime MonthlyPeriodEnd { get; set; }
  879. public static S6MdpRefreshOption Default()
  880. {
  881. var today = DateTime.Today;
  882. var yesterday = today.AddDays(-1);
  883. var lastMonth = today.AddMonths(-1);
  884. var monthStart = new DateTime(lastMonth.Year, lastMonth.Month, 1);
  885. var monthEnd = monthStart.AddMonths(1).AddDays(-1);
  886. return new S6MdpRefreshOption
  887. {
  888. SourceZtid = "pbxfxp",
  889. TargetTenantId = 0,
  890. TargetFactoryId = 1L,
  891. BizDate = yesterday,
  892. BizMonth = lastMonth.ToString("yyyy-MM"),
  893. MonthlyPeriodStart = monthStart,
  894. MonthlyPeriodEnd = monthEnd.AddDays(1).AddSeconds(-1)
  895. };
  896. }
  897. }
  898. public sealed class S6MdpSyncTransformResult
  899. {
  900. public string BatchId { get; set; } = "";
  901. public long RunLogId { get; set; }
  902. public string TriggerType { get; set; } = "AUTO";
  903. public string SourceZtid { get; set; } = "";
  904. public long TargetTenantId { get; set; }
  905. public long TargetFactoryId { get; set; }
  906. public DateTime BizDate { get; set; }
  907. public string BizMonth { get; set; } = "";
  908. public DateTime MonthlyPeriodStart { get; set; }
  909. public DateTime MonthlyPeriodEnd { get; set; }
  910. public int StageRows { get; set; }
  911. public int StandardRows { get; set; }
  912. public int DwdRows { get; set; }
  913. public int KpiRows { get; set; }
  914. public Dictionary<string, int> PerKpiDwdRows { get; } = new();
  915. public Dictionary<string, int> PerKpiKpiRows { get; } = new();
  916. public List<string> KpiDenominatorStatus { get; } = new();
  917. public void MergeSub(string kpiCode, KpiBuildSubResult sub)
  918. {
  919. PerKpiDwdRows[kpiCode] = sub.DwdRows;
  920. PerKpiKpiRows[kpiCode] = sub.KpiRows;
  921. DwdRows += sub.DwdRows;
  922. KpiRows += sub.KpiRows;
  923. KpiDenominatorStatus.Add($"{kpiCode}:{sub.DenominatorStatus}");
  924. }
  925. }
  926. public sealed class KpiBuildSubResult
  927. {
  928. public int T8Rows { get; set; }
  929. public int DwdRows { get; set; }
  930. public int KpiRows { get; set; }
  931. public string DenominatorStatus { get; set; } = "OK";
  932. }
  933. // T8 result set 投影类型 ──────────────────────────────────────────────────────
  934. internal sealed class S6MfgFulfillmentRow
  935. {
  936. public string? order_no { get; set; }
  937. public string? task_no { get; set; }
  938. public string? item_code { get; set; }
  939. public decimal? qty_planned { get; set; }
  940. public decimal? qty_done { get; set; }
  941. }
  942. internal sealed class S6CountRow
  943. {
  944. public int? ddnum { get; set; }
  945. }
  946. internal sealed class S6PeNumRow
  947. {
  948. public int penum { get; set; }
  949. }
  950. internal sealed class S6OrderCycleRow
  951. {
  952. public string? order_no { get; set; }
  953. public int? cycle_days { get; set; }
  954. }
  955. internal sealed class S6WorkOrderCycleRow
  956. {
  957. public string? task_no { get; set; }
  958. public int? cycle_days { get; set; }
  959. }
  960. internal sealed class S6OrderFulfillmentRow
  961. {
  962. public string? order_no { get; set; }
  963. public decimal? plan_qty { get; set; }
  964. public decimal? done_qty_in_window { get; set; }
  965. }
  966. internal sealed class S6ExecutionKpiRow
  967. {
  968. public decimal? MetricValue { get; set; }
  969. public int RowCount { get; set; }
  970. }