S7MdpSyncTransformService.cs 30 KB

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