S7MdpSyncTransformService.cs 34 KB

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