S6MdpSyncTransformService.cs 50 KB

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