S7MdpSyncTransformService.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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.FinishedWarehouse;
  6. /// <summary>
  7. /// S7 成品仓储 — KPI 计算与刷新转换服务。
  8. /// 双模式:读本地标准层 mdp_std_t8_kc_*(由 T8BaseInboundMdpSyncService 从 T8 贴源→标准),不再直连 T8。
  9. /// 计算逻辑沿用方老师 v5.4 KPI J 列口径(等价改写为 MySQL 读 std)。
  10. /// 包含 KPI:S7_L1_001 订单发货周期 / S7_L1_002 订单发货满足率 / S7_L1_003 成品仓储人效。
  11. /// </summary>
  12. public class S7MdpSyncTransformService : ITransient
  13. {
  14. private readonly ISqlSugarClient _db;
  15. private readonly SysNoticeService _sysNoticeService;
  16. private readonly ILogger<S7MdpSyncTransformService> _logger;
  17. private readonly SmartOps.KpiCalcDispatcher _kpiCalcDispatcher;
  18. private readonly SmartOps.KpiDimensionRunService _dimensionRun;
  19. private readonly SmartOps.IKpiTargetResolver _kpiTargetResolver;
  20. private const string JobCode = "S7_MDP_SYNC_TRANSFORM";
  21. private const string JobName = "S7 成品仓储 MDP 同步与转换";
  22. private const string ModuleCode = "S7";
  23. // FAILURE-NOTIFICATION-1:超级管理员 superAdmin.NET(AccountType=999)
  24. private const long NoticeReceiverUserId = 1300000000101L;
  25. private const string NoticeReceiverUserName = "超级管理员";
  26. public S7MdpSyncTransformService(
  27. ISqlSugarClient db,
  28. SysNoticeService sysNoticeService,
  29. ILogger<S7MdpSyncTransformService> logger,
  30. SmartOps.KpiCalcDispatcher kpiCalcDispatcher,
  31. SmartOps.KpiDimensionRunService dimensionRun,
  32. SmartOps.IKpiTargetResolver kpiTargetResolver)
  33. {
  34. _db = db;
  35. _sysNoticeService = sysNoticeService;
  36. _logger = logger;
  37. _kpiCalcDispatcher = kpiCalcDispatcher;
  38. _dimensionRun = dimensionRun;
  39. _kpiTargetResolver = kpiTargetResolver;
  40. }
  41. public async Task<S7MdpSyncTransformResult> RunFullAsync(
  42. CancellationToken cancellationToken = default,
  43. string triggerType = "AUTO",
  44. S7MdpRefreshOption? option = null)
  45. {
  46. cancellationToken.ThrowIfCancellationRequested();
  47. option ??= S7MdpRefreshOption.Default();
  48. NormalizeOption(option);
  49. var now = DateTime.Now;
  50. var batchId = $"S7_MDP_FULL_{now:yyyyMMddHHmmss}";
  51. var normalizedTrigger = NormalizeTriggerType(triggerType);
  52. var runLogId = await InsertTransformRunLogAsync(batchId, now, normalizedTrigger, option);
  53. var result = new S7MdpSyncTransformResult
  54. {
  55. BatchId = batchId,
  56. RunLogId = runLogId,
  57. TriggerType = normalizedTrigger,
  58. SourceZtid = option.SourceZtid,
  59. TargetTenantId = option.TargetTenantId,
  60. TargetFactoryId = option.TargetFactoryId,
  61. BizDate = option.BizDate,
  62. BizMonth = option.BizMonth,
  63. MonthlyPeriodStart = option.MonthlyPeriodStart,
  64. MonthlyPeriodEnd = option.MonthlyPeriodEnd
  65. };
  66. try
  67. {
  68. result.StageRows = 0;
  69. result.StandardRows = 0;
  70. var sub25 = await BuildS7L1001OrderShipmentCycleAsync(batchId, now, option, normalizedTrigger, cancellationToken);
  71. result.MergeSub("S7_L1_001", sub25);
  72. var sub26 = await BuildS7L1002OrderShipmentFulfillmentAsync(batchId, now, option, normalizedTrigger, cancellationToken);
  73. result.MergeSub("S7_L1_002", sub26);
  74. var sub27 = await BuildS7L1003FinishedWarehouseEfficiencyAsync(batchId, now, option, normalizedTrigger, cancellationToken);
  75. result.MergeSub("S7_L1_003", sub27);
  76. await MarkTransformRunSuccessAsync(runLogId, now, result);
  77. return result;
  78. }
  79. catch (Exception ex)
  80. {
  81. await MarkTransformRunFailedAsync(runLogId, now, ex.Message, batchId);
  82. throw;
  83. }
  84. }
  85. // ─────────────────────────────────────────────────────────────────────────
  86. /// <summary>S7_L1_001 订单发货周期 = 最晚发货日期 - 最早 FQC 报检日期(5 表 JOIN)。</summary>
  87. private async Task<KpiBuildSubResult> BuildS7L1001OrderShipmentCycleAsync(
  88. string batchId, DateTime now, S7MdpRefreshOption option, string triggerType, CancellationToken ct)
  89. {
  90. var sub = new KpiBuildSubResult();
  91. // 双模式:读本地标准层 mdp_std_t8_*(源 identity Id→src_id);datediff(day,a,b)→DATEDIFF(b,a),IsNull→IFNULL。
  92. const string sql = @"
  93. select noid as noid,
  94. datediff(max(shtime), min(shdate)) as scts
  95. from (
  96. select a.noid as noid, b.code as code,
  97. ifnull(c.shdate, b.addtime) as shdate,
  98. (case when b.gdyn=1 then b.gdtime else d.shtime end) as shtime,
  99. (case when b.gdyn=1 or b.sl<=b.slzx then 1 else 0 end) as wczt
  100. from mdp_std_t8_kc_dd_head a
  101. left join mdp_std_t8_kc_dd_list b on a.src_id=b.idid
  102. left join (
  103. select min(b.src_id) as id, b.lynoid as lynoid, b.code as code,
  104. max(a.shtime) as shtime, sum(b.slzx) as slzx
  105. from mdp_std_t8_kc_tz_head a
  106. inner join mdp_std_t8_kc_tz_list b on a.src_id=b.idid
  107. where a.ztid=@ztid and a.lbs='销售出库' and a.hzyn=0 and a.zfyn=0 and a.shyn=1
  108. group by b.lynoid, b.code
  109. ) d on b.rwnoid=d.lynoid and b.code=d.code
  110. left join mdp_std_t8_kc_zj_list c on a.ztid=c.ztid and c.lyid=b.src_id and c.zjyn=1
  111. where a.ztid=@ztid and a.lbs='销售订单' and a.zf=0 and a.shyn=1
  112. ) n
  113. group by noid
  114. having min(wczt)=1";
  115. var rows = await _db.Ado.SqlQueryAsync<S7CycleRow>(sql, new[] { new SugarParameter("@ztid", option.SourceZtid) });
  116. sub.T8Rows = rows.Count;
  117. var dwdAffected = 0;
  118. var cycleList = new List<int>();
  119. foreach (var r in rows)
  120. {
  121. ct.ThrowIfCancellationRequested();
  122. if (string.IsNullOrEmpty(r.noid)) continue;
  123. if (r.scts.HasValue) cycleList.Add(r.scts.Value);
  124. dwdAffected += await _db.Ado.ExecuteCommandAsync(@"
  125. INSERT INTO dwd_t8_order_shipment_cycle
  126. (tenant_id, factory_id, biz_date, source_ztid, order_no, cycle_days, batch_id, create_time)
  127. VALUES
  128. (@tenantId, @factoryId, @bizDate, @ztid, @orderNo, @cycleDays, @batchId, @now)
  129. ON DUPLICATE KEY UPDATE
  130. cycle_days=VALUES(cycle_days),
  131. batch_id=VALUES(batch_id), update_time=@now",
  132. new SugarParameter("@tenantId", option.TargetTenantId),
  133. new SugarParameter("@factoryId", option.TargetFactoryId),
  134. new SugarParameter("@bizDate", option.BizDate),
  135. new SugarParameter("@ztid", option.SourceZtid),
  136. new SugarParameter("@orderNo", r.noid),
  137. new SugarParameter("@cycleDays", r.scts),
  138. new SugarParameter("@batchId", batchId),
  139. new SugarParameter("@now", now));
  140. }
  141. sub.DwdRows = dwdAffected;
  142. // 数据准备(dwd 逐单 cycle_days)已完成。最终聚合交分发器(日 KPI:period 复用 BizDate,SQL 按 biz_date 圈选)。
  143. decimal? legacyValue = cycleList.Count > 0
  144. ? Math.Round((decimal)cycleList.Average(), 4)
  145. : null;
  146. var legacyDenom = cycleList.Count > 0 ? "OK" : "NO_COMPLETED_ORDER";
  147. var dispatch = await _kpiCalcDispatcher.DispatchAsync(
  148. "S7_L1_001", ModuleCode, option.TargetTenantId, option.TargetFactoryId,
  149. option.BizDate, option.BizDate, option.BizDate, option.SourceZtid,
  150. batchId, triggerType, legacyValue, legacyDenom, ct);
  151. sub.KpiRows = dispatch.ShouldUpsert
  152. ? await UpsertKpiValueAsync("S7_L1_001", option.BizDate, dispatch.MetricValue, now, option)
  153. : 0;
  154. sub.DenominatorStatus = dispatch.DenominatorStatus;
  155. // 调度:SUMMARY 成功/NO_DATA 后触发对应 DIMENSION 跑批(共享 BatchId;SUMMARY FAILED 不触发)。
  156. // 维度失败不影响汇总链路(内部已落 dimension_run_log)。
  157. if (dispatch.ShouldUpsert)
  158. {
  159. try
  160. {
  161. await _dimensionRun.RunDimensionAsync(
  162. "S7_L1_001", ModuleCode, option.TargetTenantId, option.BizDate, batchId, triggerType, ct);
  163. }
  164. catch (Exception ex)
  165. {
  166. _logger.LogWarning(ex, "S7_L1_001 维度跑批异常(不影响汇总链路)");
  167. }
  168. }
  169. return sub;
  170. }
  171. /// <summary>S7_L1_002 订单发货满足率 = (交期前发货行数 / 该订单总行数) × 100%。</summary>
  172. private async Task<KpiBuildSubResult> BuildS7L1002OrderShipmentFulfillmentAsync(
  173. string batchId, DateTime now, S7MdpRefreshOption option, string triggerType, CancellationToken ct)
  174. {
  175. var sub = new KpiBuildSubResult();
  176. // 双模式:读标准层;convert(varchar(10),shtime,23)→date(shtime)。
  177. const string sql = @"
  178. select noid as noid,
  179. count(noid) as total_rows,
  180. sum(wczt) as in_window_rows
  181. from (
  182. select a.noid as noid, b.rwnoid as rwnoid, b.code as code,
  183. (case when sum(d.slzx)>=b.sl then 1 else 0 end) as wczt
  184. from mdp_std_t8_kc_dd_head a
  185. left join mdp_std_t8_kc_dd_list b on a.src_id=b.idid
  186. left join (
  187. select b.lynoid as lynoid, b.code as code,
  188. date(a.shtime) as shtime, b.slzx as slzx
  189. from mdp_std_t8_kc_tz_head a
  190. inner join mdp_std_t8_kc_tz_list b on a.src_id=b.idid
  191. where a.ztid=@ztid and a.lbs='销售出库' and a.hzyn=0 and a.zfyn=0 and a.shyn=1
  192. ) d on b.rwnoid=d.lynoid and b.code=d.code and d.shtime<=b.jhdate
  193. where a.ztid=@ztid and a.lbs='销售订单' and a.zf=0 and a.shyn=1
  194. group by a.noid, b.rwnoid, b.code, b.sl
  195. ) n
  196. group by noid";
  197. var rows = await _db.Ado.SqlQueryAsync<S7FulfillmentRow>(sql, new[] { new SugarParameter("@ztid", option.SourceZtid) });
  198. sub.T8Rows = rows.Count;
  199. var dwdAffected = 0;
  200. var rateList = new List<decimal>();
  201. foreach (var r in rows)
  202. {
  203. ct.ThrowIfCancellationRequested();
  204. if (string.IsNullOrEmpty(r.noid)) continue;
  205. decimal? rate = (r.total_rows > 0)
  206. ? Math.Round((decimal)r.in_window_rows / r.total_rows * 100m, 4)
  207. : null;
  208. if (rate.HasValue) rateList.Add(rate.Value);
  209. dwdAffected += await _db.Ado.ExecuteCommandAsync(@"
  210. INSERT INTO dwd_t8_order_shipment_fulfillment
  211. (tenant_id, factory_id, biz_date, source_ztid, order_no,
  212. total_rows, in_window_rows, fulfillment_rate, batch_id, create_time)
  213. VALUES
  214. (@tenantId, @factoryId, @bizDate, @ztid, @orderNo,
  215. @total, @inWindow, @rate, @batchId, @now)
  216. ON DUPLICATE KEY UPDATE
  217. total_rows=VALUES(total_rows), in_window_rows=VALUES(in_window_rows),
  218. fulfillment_rate=VALUES(fulfillment_rate),
  219. batch_id=VALUES(batch_id), update_time=@now",
  220. new SugarParameter("@tenantId", option.TargetTenantId),
  221. new SugarParameter("@factoryId", option.TargetFactoryId),
  222. new SugarParameter("@bizDate", option.BizDate),
  223. new SugarParameter("@ztid", option.SourceZtid),
  224. new SugarParameter("@orderNo", r.noid),
  225. new SugarParameter("@total", r.total_rows),
  226. new SugarParameter("@inWindow", r.in_window_rows),
  227. new SugarParameter("@rate", rate),
  228. new SugarParameter("@batchId", batchId),
  229. new SugarParameter("@now", now));
  230. }
  231. sub.DwdRows = dwdAffected;
  232. // 数据准备(dwd 逐单 fulfillment_rate,已 ×100)已完成。最终聚合交分发器(CONFIG_SQL 直接 AVG 该列不再 ×100)。
  233. decimal? legacyValue = rateList.Count > 0
  234. ? Math.Round(rateList.Average(), 4)
  235. : null;
  236. var legacyDenom = rateList.Count > 0 ? "OK" : "NO_VALID_ORDER";
  237. var dispatch = await _kpiCalcDispatcher.DispatchAsync(
  238. "S7_L1_002", ModuleCode, option.TargetTenantId, option.TargetFactoryId,
  239. option.BizDate, option.BizDate, option.BizDate, option.SourceZtid,
  240. batchId, triggerType, legacyValue, legacyDenom, ct);
  241. sub.KpiRows = dispatch.ShouldUpsert
  242. ? await UpsertKpiValueAsync("S7_L1_002", option.BizDate, dispatch.MetricValue, now, option)
  243. : 0;
  244. sub.DenominatorStatus = dispatch.DenominatorStatus;
  245. // 调度:SUMMARY 成功/NO_DATA 后触发对应 DIMENSION 跑批(共享 BatchId;SUMMARY FAILED 不触发)。
  246. if (dispatch.ShouldUpsert)
  247. {
  248. try
  249. {
  250. await _dimensionRun.RunDimensionAsync(
  251. "S7_L1_002", ModuleCode, option.TargetTenantId, option.BizDate, batchId, triggerType, ct);
  252. }
  253. catch (Exception ex)
  254. {
  255. _logger.LogWarning(ex, "S7_L1_002 维度跑批异常(不影响汇总链路)");
  256. }
  257. }
  258. return sub;
  259. }
  260. /// <summary>S7_L1_003 成品仓储人效 = SUM(slzx where lbs=销售出库) / count(gw=仓管)。</summary>
  261. private async Task<KpiBuildSubResult> BuildS7L1003FinishedWarehouseEfficiencyAsync(
  262. string batchId, DateTime now, S7MdpRefreshOption option, string triggerType, CancellationToken ct)
  263. {
  264. var sub = new KpiBuildSubResult();
  265. const string sqlNumer = @"
  266. select b.lynoid as lynoid, b.code as code,
  267. date(a.shtime) as shtime, b.slzx as slzx
  268. from mdp_std_t8_kc_tz_head a
  269. inner join mdp_std_t8_kc_tz_list b on a.src_id=b.idid
  270. where a.ztid=@ztid and a.lbs='销售出库' and a.hzyn=0 and a.zfyn=0 and a.shyn=1
  271. and date(a.shtime) between @startDateText and @endDateText";
  272. const string sqlDenom = @"
  273. select count(*) as penum
  274. from mdp_std_t8_sys_pelist
  275. where ztid=@ztid and zzzt='在职' and gw='仓管'";
  276. var pNumer = new[]
  277. {
  278. new SugarParameter("@ztid", option.SourceZtid),
  279. new SugarParameter("@startDateText", option.MonthlyPeriodStart.ToString("yyyy-MM-dd")),
  280. new SugarParameter("@endDateText", option.MonthlyPeriodEnd.ToString("yyyy-MM-dd"))
  281. };
  282. var pDenom = new[] { new SugarParameter("@ztid", option.SourceZtid) };
  283. var numerRows = await _db.Ado.SqlQueryAsync<S7ShipmentDetailRow>(sqlNumer, pNumer);
  284. var denomRows = await _db.Ado.SqlQueryAsync<S7PeNumRow>(sqlDenom, pDenom);
  285. sub.T8Rows = numerRows.Count + denomRows.Count;
  286. decimal? shipmentQty = numerRows.Sum(r => r.slzx ?? 0m);
  287. if (numerRows.Count == 0) shipmentQty = null;
  288. int? headcount = denomRows.FirstOrDefault()?.penum;
  289. decimal? efficiency = null;
  290. string denomStatus;
  291. if (!headcount.HasValue || headcount.Value <= 0)
  292. denomStatus = "NO_HEADCOUNT";
  293. else if (!shipmentQty.HasValue)
  294. denomStatus = "NO_NUMERATOR";
  295. else
  296. {
  297. efficiency = Math.Round(shipmentQty.Value / headcount.Value, 4);
  298. denomStatus = "OK";
  299. }
  300. sub.DenominatorStatus = denomStatus;
  301. var dwdAffected = await _db.Ado.ExecuteCommandAsync(@"
  302. INSERT INTO dwd_t8_finished_warehouse_efficiency
  303. (tenant_id, factory_id, biz_month, source_ztid, period_start, period_end,
  304. shipment_qty, warehouse_headcount, efficiency, denominator_status, batch_id, create_time)
  305. VALUES
  306. (@tenantId, @factoryId, @bizMonth, @ztid, @periodStart, @periodEnd,
  307. @shipmentQty, @headcount, @efficiency, @denomStatus, @batchId, @now)
  308. ON DUPLICATE KEY UPDATE
  309. period_start=VALUES(period_start), period_end=VALUES(period_end),
  310. shipment_qty=VALUES(shipment_qty), warehouse_headcount=VALUES(warehouse_headcount),
  311. efficiency=VALUES(efficiency), denominator_status=VALUES(denominator_status),
  312. batch_id=VALUES(batch_id), update_time=@now",
  313. new SugarParameter("@tenantId", option.TargetTenantId),
  314. new SugarParameter("@factoryId", option.TargetFactoryId),
  315. new SugarParameter("@bizMonth", option.BizMonth),
  316. new SugarParameter("@ztid", option.SourceZtid),
  317. new SugarParameter("@periodStart", option.MonthlyPeriodStart),
  318. new SugarParameter("@periodEnd", option.MonthlyPeriodEnd),
  319. new SugarParameter("@shipmentQty", shipmentQty),
  320. new SugarParameter("@headcount", headcount),
  321. new SugarParameter("@efficiency", efficiency),
  322. new SugarParameter("@denomStatus", denomStatus),
  323. new SugarParameter("@batchId", batchId),
  324. new SugarParameter("@now", now));
  325. sub.DwdRows = dwdAffected;
  326. // 月度 KPI 最终聚合交分发器;bizDate=月末、period=当月窗口;
  327. // legacyValue=efficiency、legacyDenom 保留 NO_HEADCOUNT/NO_NUMERATOR(CONFIG_SQL 下塌缩为 NO_DATA)。
  328. var dispatch = await _kpiCalcDispatcher.DispatchAsync(
  329. "S7_L1_003", ModuleCode, option.TargetTenantId, option.TargetFactoryId,
  330. option.MonthlyPeriodEnd, option.MonthlyPeriodStart, option.MonthlyPeriodEnd, option.SourceZtid,
  331. batchId, triggerType, efficiency, denomStatus, ct);
  332. sub.KpiRows = dispatch.ShouldUpsert
  333. ? await UpsertKpiValueAsync("S7_L1_003", option.MonthlyPeriodEnd, dispatch.MetricValue, now, option)
  334. : 0;
  335. sub.DenominatorStatus = dispatch.DenominatorStatus;
  336. // 调度:SUMMARY 成功/NO_DATA 后触发人效月度 DIMENSION 跑批(月度:@biz_date=月末派生 biz_month)。
  337. if (dispatch.ShouldUpsert)
  338. {
  339. try
  340. {
  341. await _dimensionRun.RunDimensionAsync(
  342. "S7_L1_003", ModuleCode, option.TargetTenantId, option.MonthlyPeriodEnd, batchId, triggerType, ct);
  343. }
  344. catch (Exception ex)
  345. {
  346. _logger.LogWarning(ex, "S7_L1_003 维度跑批异常(不影响汇总链路)");
  347. }
  348. }
  349. return sub;
  350. }
  351. // ─────────────────────────────────────────────────────────────────────────
  352. private async Task<int> UpsertKpiValueAsync(string metricCode, DateTime bizDate, decimal? metricValue, DateTime now, S7MdpRefreshOption option)
  353. {
  354. // 沿用 S3 UpsertS3KpiValueAsync 范式:先查现存行 → UPDATE;不存在 → SELECT MAX(id)+1 显式生成 id 后 INSERT。
  355. // ado_s9_kpi_value_l1_day.id 为手工分配主键(无 AUTO_INCREMENT),必须显式 set;
  356. // metric_value 允许 NULL(分母缺失不得伪装真实 0)。
  357. // FIX-2:截断时分秒(月度 KPI 入参可能为 YYYY-MM-DD 23:59:59),保证 SELECT WHERE biz_date=@BizDate 与 DB date 列匹配,避免重复 INSERT。
  358. // FIX-1:tenant_id/factory_id 取自 option,默认仍为 1300000000001/1,不破坏 Demo。
  359. bizDate = bizDate.Date;
  360. var snap = await _kpiTargetResolver.ResolveAsync(option.TargetTenantId, option.TargetFactoryId, metricCode, ModuleCode, bizDate);
  361. var existingId = await _db.Ado.GetLongAsync(
  362. "SELECT IFNULL((SELECT id FROM ado_s9_kpi_value_l1_day WHERE tenant_id=@TenantId AND factory_id=@FactoryId " +
  363. "AND module_code=@ModuleCode AND metric_code=@MetricCode AND biz_date=@BizDate AND is_deleted=0 " +
  364. "ORDER BY id LIMIT 1), 0)",
  365. new List<SugarParameter>
  366. {
  367. new("@TenantId", option.TargetTenantId),
  368. new("@FactoryId", option.TargetFactoryId),
  369. new("@ModuleCode", ModuleCode),
  370. new("@MetricCode", metricCode),
  371. new("@BizDate", bizDate)
  372. });
  373. if (existingId > 0)
  374. {
  375. return await _db.Ado.ExecuteCommandAsync(
  376. "UPDATE ado_s9_kpi_value_l1_day SET metric_value=@MetricValue, target_value=@TargetValue, " +
  377. "target_config_id=@TargetConfigId, target_source=@TargetSource, target_resolved_at=@TargetResolvedAt, " +
  378. "calc_time=@Now, update_time=@Now, is_deleted=0, is_active=1 WHERE id=@Id",
  379. new SugarParameter("@MetricValue", metricValue),
  380. new SugarParameter("@TargetValue", SmartOps.KpiTargetSnapshotSql.ValueOrDbNull(snap)),
  381. new SugarParameter("@TargetConfigId", SmartOps.KpiTargetSnapshotSql.ConfigIdOrDbNull(snap)),
  382. new SugarParameter("@TargetSource", SmartOps.KpiTargetSnapshotSql.SourceOrDbNull(snap)),
  383. new SugarParameter("@TargetResolvedAt", snap.ResolvedAt),
  384. new SugarParameter("@Now", now),
  385. new SugarParameter("@Id", existingId));
  386. }
  387. var nextId = await _db.Ado.GetLongAsync(
  388. "SELECT COALESCE(MAX(id), 0) + 1 FROM ado_s9_kpi_value_l1_day");
  389. return await _db.Ado.ExecuteCommandAsync(@"
  390. INSERT INTO ado_s9_kpi_value_l1_day
  391. (id, tenant_id, org_id, company_id, factory_id, status, biz_date,
  392. create_time, update_time, is_deleted, is_active,
  393. module_code, metric_code, metric_value, target_value, calc_time,
  394. target_config_id, target_source, target_resolved_at)
  395. VALUES
  396. (@Id, @TenantId, NULL, NULL, @FactoryId, NULL, @BizDate,
  397. @Now, @Now, 0, 1,
  398. @ModuleCode, @MetricCode, @MetricValue, @TargetValue, @Now,
  399. @TargetConfigId, @TargetSource, @TargetResolvedAt)",
  400. new SugarParameter("@Id", nextId),
  401. new SugarParameter("@TenantId", option.TargetTenantId),
  402. new SugarParameter("@FactoryId", option.TargetFactoryId),
  403. new SugarParameter("@BizDate", bizDate),
  404. new SugarParameter("@Now", now),
  405. new SugarParameter("@ModuleCode", ModuleCode),
  406. new SugarParameter("@MetricCode", metricCode),
  407. new SugarParameter("@MetricValue", metricValue),
  408. new SugarParameter("@TargetValue", SmartOps.KpiTargetSnapshotSql.ValueOrDbNull(snap)),
  409. new SugarParameter("@TargetConfigId", SmartOps.KpiTargetSnapshotSql.ConfigIdOrDbNull(snap)),
  410. new SugarParameter("@TargetSource", SmartOps.KpiTargetSnapshotSql.SourceOrDbNull(snap)),
  411. new SugarParameter("@TargetResolvedAt", snap.ResolvedAt));
  412. }
  413. private async Task<long> InsertTransformRunLogAsync(string batchId, DateTime startedAt, string triggerType, S7MdpRefreshOption option)
  414. {
  415. await _db.Ado.ExecuteCommandAsync(@"
  416. INSERT INTO mdp_transform_run_log
  417. (tenant_id, job_code, job_name, trigger_type, batch_id, status, start_time, stage_rows, standard_rows, dwd_rows, create_time, update_time)
  418. VALUES
  419. (@TenantId, @JobCode, @JobName, @TriggerType, @BatchId, 'RUNNING', @StartTime, 0, 0, 0, @StartTime, @StartTime)",
  420. new SugarParameter("@TenantId", option.TargetTenantId),
  421. new SugarParameter("@JobCode", JobCode),
  422. new SugarParameter("@JobName", JobName),
  423. new SugarParameter("@TriggerType", triggerType),
  424. new SugarParameter("@BatchId", batchId),
  425. new SugarParameter("@StartTime", startedAt));
  426. return await _db.Ado.GetLongAsync(
  427. "SELECT id FROM mdp_transform_run_log WHERE batch_id=@BatchId ORDER BY id DESC LIMIT 1",
  428. new List<SugarParameter> { new("@BatchId", batchId) });
  429. }
  430. private async Task MarkTransformRunSuccessAsync(long runLogId, DateTime startedAt, S7MdpSyncTransformResult result)
  431. {
  432. var finishedAt = DateTime.Now;
  433. await _db.Ado.ExecuteCommandAsync(@"
  434. UPDATE mdp_transform_run_log
  435. SET status='SUCCESS', end_time=@EndTime, duration_ms=@DurationMs,
  436. stage_rows=@StageRows, standard_rows=@StandardRows, dwd_rows=@DwdRows,
  437. summary_json=@SummaryJson, update_time=CURRENT_TIMESTAMP
  438. WHERE id=@Id",
  439. new SugarParameter("@EndTime", finishedAt),
  440. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  441. new SugarParameter("@StageRows", result.StageRows),
  442. new SugarParameter("@StandardRows", result.StandardRows),
  443. new SugarParameter("@DwdRows", result.DwdRows),
  444. new SugarParameter("@SummaryJson", JsonSerializer.Serialize(new
  445. {
  446. batchId = result.BatchId,
  447. sourceZtid = result.SourceZtid,
  448. bizDate = result.BizDate.ToString("yyyy-MM-dd"),
  449. bizMonth = result.BizMonth,
  450. dwdRows = result.DwdRows,
  451. kpiRows = result.KpiRows,
  452. perKpiDwdRows = result.PerKpiDwdRows,
  453. perKpiKpiRows = result.PerKpiKpiRows,
  454. denominatorStatus = result.KpiDenominatorStatus
  455. })),
  456. new SugarParameter("@Id", runLogId));
  457. }
  458. private async Task MarkTransformRunFailedAsync(long runLogId, DateTime startedAt, string message, string batchId)
  459. {
  460. bool runLogUpdated = false;
  461. try
  462. {
  463. var finishedAt = DateTime.Now;
  464. await _db.Ado.ExecuteCommandAsync(@"
  465. UPDATE mdp_transform_run_log
  466. SET status='FAILED', end_time=@EndTime, duration_ms=@DurationMs,
  467. error_message=@ErrorMessage, update_time=CURRENT_TIMESTAMP
  468. WHERE id=@Id",
  469. new SugarParameter("@EndTime", finishedAt),
  470. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  471. new SugarParameter("@ErrorMessage", Truncate(message, 2000)),
  472. new SugarParameter("@Id", runLogId));
  473. runLogUpdated = true;
  474. }
  475. catch (Exception ex)
  476. {
  477. Console.Error.WriteLine($"[S7MdpSyncTransform] MarkTransformRunFailed write failed (runLogId={runLogId}): {ex.Message}");
  478. }
  479. // FAILURE-NOTIFICATION-1:写库 FAILED 成功后发通知给超级管理员;通知失败不影响主流程
  480. if (!runLogUpdated) return;
  481. try
  482. {
  483. await _sysNoticeService.AddNotice(new AddNoticeInput
  484. {
  485. Title = "S7 成品仓储 T8 KPI 跑批失败",
  486. Content = $"模块:S7 成品仓储\n批次ID:{batchId}\n失败时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}\n错误信息:{Truncate(message, 1000)}\n\n请查看 mdp_transform_run_log 获取完整错误与重试记录。",
  487. Type = NoticeTypeEnum.NOTICE,
  488. PublicTime = DateTime.Now,
  489. Status = NoticeStatusEnum.PUBLIC,
  490. PublicUserId = NoticeReceiverUserId,
  491. PublicUserName = NoticeReceiverUserName
  492. });
  493. }
  494. catch (Exception notifyEx)
  495. {
  496. _logger.LogError(notifyEx, "[S7MdpSyncTransform] SysNotice 发送失败 (runLogId={RunLogId}, batchId={BatchId})", runLogId, batchId);
  497. }
  498. }
  499. private static string NormalizeTriggerType(string s) =>
  500. string.IsNullOrWhiteSpace(s) ? "AUTO" : s.Trim().ToUpperInvariant();
  501. private static void NormalizeOption(S7MdpRefreshOption option)
  502. {
  503. var d = S7MdpRefreshOption.Default();
  504. if (option.TargetFactoryId <= 0) option.TargetFactoryId = d.TargetFactoryId;
  505. if (string.IsNullOrWhiteSpace(option.SourceZtid)) option.SourceZtid = d.SourceZtid;
  506. option.TargetTenantId = AidopSourceTenantMap.ResolveTenantId(option.SourceZtid, option.TargetTenantId);
  507. if (option.BizDate == default) option.BizDate = d.BizDate;
  508. if (string.IsNullOrWhiteSpace(option.BizMonth)) option.BizMonth = d.BizMonth;
  509. if (option.MonthlyPeriodStart == default) option.MonthlyPeriodStart = d.MonthlyPeriodStart;
  510. if (option.MonthlyPeriodEnd == default) option.MonthlyPeriodEnd = d.MonthlyPeriodEnd;
  511. }
  512. private static string Truncate(string s, int max) =>
  513. string.IsNullOrEmpty(s) ? "" : (s.Length <= max ? s : s.Substring(0, max));
  514. }
  515. // DTO ────────────────────────────────────────────────────────────────────────
  516. public sealed class S7MdpRefreshOption
  517. {
  518. public string SourceZtid { get; set; } = "pbxfxp";
  519. /// <summary>KPI/DWD 落库目标租户;≤0 时由 <see cref="AidopSourceTenantMap"/> 按 SourceZtid 解析。</summary>
  520. public long TargetTenantId { get; set; }
  521. /// <summary>KPI/DWD 落库目标工厂;默认 1。</summary>
  522. public long TargetFactoryId { get; set; } = 1L;
  523. public DateTime BizDate { get; set; }
  524. public string BizMonth { get; set; } = "";
  525. public DateTime MonthlyPeriodStart { get; set; }
  526. public DateTime MonthlyPeriodEnd { get; set; }
  527. public static S7MdpRefreshOption Default()
  528. {
  529. var today = DateTime.Today;
  530. var yesterday = today.AddDays(-1);
  531. var lastMonth = today.AddMonths(-1);
  532. var monthStart = new DateTime(lastMonth.Year, lastMonth.Month, 1);
  533. var monthEnd = monthStart.AddMonths(1).AddDays(-1);
  534. return new S7MdpRefreshOption
  535. {
  536. SourceZtid = "pbxfxp",
  537. TargetTenantId = 0,
  538. TargetFactoryId = 1L,
  539. BizDate = yesterday,
  540. BizMonth = lastMonth.ToString("yyyy-MM"),
  541. MonthlyPeriodStart = monthStart,
  542. MonthlyPeriodEnd = monthEnd.AddDays(1).AddSeconds(-1)
  543. };
  544. }
  545. }
  546. public sealed class S7MdpSyncTransformResult
  547. {
  548. public string BatchId { get; set; } = "";
  549. public long RunLogId { get; set; }
  550. public string TriggerType { get; set; } = "AUTO";
  551. public string SourceZtid { get; set; } = "";
  552. public long TargetTenantId { get; set; }
  553. public long TargetFactoryId { get; set; }
  554. public DateTime BizDate { get; set; }
  555. public string BizMonth { get; set; } = "";
  556. public DateTime MonthlyPeriodStart { get; set; }
  557. public DateTime MonthlyPeriodEnd { get; set; }
  558. public int StageRows { get; set; }
  559. public int StandardRows { get; set; }
  560. public int DwdRows { get; set; }
  561. public int KpiRows { get; set; }
  562. public Dictionary<string, int> PerKpiDwdRows { get; } = new();
  563. public Dictionary<string, int> PerKpiKpiRows { get; } = new();
  564. public List<string> KpiDenominatorStatus { get; } = new();
  565. public void MergeSub(string kpiCode, KpiBuildSubResult sub)
  566. {
  567. PerKpiDwdRows[kpiCode] = sub.DwdRows;
  568. PerKpiKpiRows[kpiCode] = sub.KpiRows;
  569. DwdRows += sub.DwdRows;
  570. KpiRows += sub.KpiRows;
  571. KpiDenominatorStatus.Add($"{kpiCode}:{sub.DenominatorStatus}");
  572. }
  573. }
  574. public sealed class KpiBuildSubResult
  575. {
  576. public int T8Rows { get; set; }
  577. public int DwdRows { get; set; }
  578. public int KpiRows { get; set; }
  579. public string DenominatorStatus { get; set; } = "OK";
  580. }
  581. // T8 result set 投影类型 ──────────────────────────────────────────────────────
  582. internal sealed class S7CycleRow
  583. {
  584. public string? noid { get; set; }
  585. public int? scts { get; set; }
  586. }
  587. internal sealed class S7FulfillmentRow
  588. {
  589. public string? noid { get; set; }
  590. public int total_rows { get; set; }
  591. public int in_window_rows { get; set; }
  592. }
  593. internal sealed class S7ShipmentDetailRow
  594. {
  595. public string? lynoid { get; set; }
  596. public string? code { get; set; }
  597. public string? shtime { get; set; }
  598. public decimal? slzx { get; set; }
  599. }
  600. internal sealed class S7PeNumRow
  601. {
  602. public int penum { get; set; }
  603. }