S5MdpSyncTransformService.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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.MaterialWarehouse;
  6. /// <summary>
  7. /// S5 物料仓储 — KPI 计算与刷新转换服务。边界:7 迁 2 留。
  8. /// 已中台化(读本地标准层 mdp_std_t8_*,由 T8BaseInboundMdpSyncService 从 T8 贴源→标准):
  9. /// S5_L1_001 物料上线周期 / S5_L1_003 物料仓储人效。
  10. /// 仍 legacy 直连 T8(QueryT8Async,ConfigId=t8_v5):
  11. /// S5_L1_002 物料上线满足率(依赖 T8 报表 Cj_Bg_Head_Rep)/ S5_L1_004 品类物料库存周转(依赖 T8 TVF Rep_总账_存货_V3)。
  12. /// 结果统一落 dwd_t8_* 与 ado_s9_kpi_value_l1_day。计算口径沿用方老师 v5.4 KPI J 列。
  13. /// </summary>
  14. public class S5MdpSyncTransformService : ITransient
  15. {
  16. private readonly ISqlSugarClient _db;
  17. private readonly SysNoticeService _sysNoticeService;
  18. private readonly ILogger<S5MdpSyncTransformService> _logger;
  19. private const string JobCode = "S5_MDP_SYNC_TRANSFORM";
  20. private const string JobName = "S5 物料仓储 MDP 同步与转换";
  21. private const string T8ConfigId = "t8_v5";
  22. private const string ModuleCode = "S5";
  23. // FAILURE-NOTIFICATION-1:超级管理员 superAdmin.NET(AccountType=999)
  24. private const long NoticeReceiverUserId = 1300000000101L;
  25. private const string NoticeReceiverUserName = "超级管理员";
  26. public S5MdpSyncTransformService(
  27. ISqlSugarClient db,
  28. SysNoticeService sysNoticeService,
  29. ILogger<S5MdpSyncTransformService> logger)
  30. {
  31. _db = db;
  32. _sysNoticeService = sysNoticeService;
  33. _logger = logger;
  34. }
  35. public async Task<S5MdpSyncTransformResult> RunFullAsync(
  36. CancellationToken cancellationToken = default,
  37. string triggerType = "AUTO",
  38. S5MdpRefreshOption? option = null)
  39. {
  40. cancellationToken.ThrowIfCancellationRequested();
  41. option ??= S5MdpRefreshOption.Default();
  42. NormalizeOption(option);
  43. var now = DateTime.Now;
  44. var batchId = $"S5_MDP_FULL_{now:yyyyMMddHHmmss}";
  45. var normalizedTrigger = NormalizeTriggerType(triggerType);
  46. var runLogId = await InsertTransformRunLogAsync(batchId, now, normalizedTrigger, option);
  47. var result = new S5MdpSyncTransformResult
  48. {
  49. BatchId = batchId,
  50. RunLogId = runLogId,
  51. TriggerType = normalizedTrigger,
  52. SourceZtid = option.SourceZtid,
  53. TargetTenantId = option.TargetTenantId,
  54. TargetFactoryId = option.TargetFactoryId,
  55. BizDate = option.BizDate,
  56. BizMonth = option.BizMonth,
  57. DailyPeriodStart = option.DailyPeriodStart,
  58. DailyPeriodEnd = option.DailyPeriodEnd,
  59. MonthlyPeriodStart = option.MonthlyPeriodStart,
  60. MonthlyPeriodEnd = option.MonthlyPeriodEnd
  61. };
  62. try
  63. {
  64. // 路径 A:直发 T8 SQL,不做 stg / std 中间层
  65. result.StageRows = 0;
  66. result.StandardRows = 0;
  67. var sub16 = await BuildS5L1001MaterialOnlineCycleAsync(batchId, now, option, cancellationToken);
  68. result.MergeSub("S5_L1_001", sub16);
  69. var sub17 = await BuildS5L1002MaterialOnlineFulfillmentAsync(batchId, now, option, cancellationToken);
  70. result.MergeSub("S5_L1_002", sub17);
  71. var sub18 = await BuildS5L1003MaterialWarehouseEfficiencyAsync(batchId, now, option, cancellationToken);
  72. result.MergeSub("S5_L1_003", sub18);
  73. var sub19 = await BuildS5L1004MaterialInventoryTurnoverAsync(batchId, now, option, cancellationToken);
  74. result.MergeSub("S5_L1_004", sub19);
  75. await MarkTransformRunSuccessAsync(runLogId, now, result);
  76. return result;
  77. }
  78. catch (Exception ex)
  79. {
  80. await MarkTransformRunFailedAsync(runLogId, now, ex.Message, batchId);
  81. throw;
  82. }
  83. }
  84. // ─────────────────────────────────────────────────────────────────────────
  85. // KPI 实现(方老师 v5.4 KPI J 列 SQL 原逻辑直发 T8)
  86. // ─────────────────────────────────────────────────────────────────────────
  87. /// <summary>S5_L1_001 物料上线周期 = 配送到产线日期(lbs=生产领料) - 收货日期(lbs=采购入库)。</summary>
  88. private async Task<KpiBuildSubResult> BuildS5L1001MaterialOnlineCycleAsync(
  89. string batchId, DateTime now, S5MdpRefreshOption option, CancellationToken ct)
  90. {
  91. var sub = new KpiBuildSubResult();
  92. // 双模式:读本地标准层 mdp_std_t8_*(源 identity Id→src_id),语义等价于原直发 T8 SQL。
  93. const string sqlOnline = @"
  94. select b.code as code, min(a.shtime) as shtime
  95. from mdp_std_t8_kc_tz_head a
  96. inner join mdp_std_t8_kc_tz_list b on a.src_id=b.idid
  97. where a.ztid=@ztid and a.lbs='生产领料' and a.hzyn=0 and a.zfyn=0 and a.shyn=1
  98. group by b.code";
  99. const string sqlReceipt = @"
  100. select b.code as code, min(a.shtime) as shtime
  101. from mdp_std_t8_kc_tz_head a
  102. inner join mdp_std_t8_kc_tz_list b on a.src_id=b.idid
  103. where a.ztid=@ztid and a.lbs='采购入库' and a.hzyn=0 and a.zfyn=0 and a.shyn=1
  104. group by b.code";
  105. var p = new[] { new SugarParameter("@ztid", option.SourceZtid) };
  106. var onlineRows = await _db.Ado.SqlQueryAsync<S5OnlineCycleRow>(sqlOnline, p);
  107. var receiptRows = await _db.Ado.SqlQueryAsync<S5OnlineCycleRow>(sqlReceipt, p);
  108. sub.T8Rows = onlineRows.Count + receiptRows.Count;
  109. var onlineByCode = onlineRows.Where(r => !string.IsNullOrEmpty(r.code))
  110. .ToDictionary(r => r.code!, r => r.shtime, StringComparer.OrdinalIgnoreCase);
  111. var receiptByCode = receiptRows.Where(r => !string.IsNullOrEmpty(r.code))
  112. .ToDictionary(r => r.code!, r => r.shtime, StringComparer.OrdinalIgnoreCase);
  113. var allCodes = new HashSet<string>(onlineByCode.Keys, StringComparer.OrdinalIgnoreCase);
  114. allCodes.UnionWith(receiptByCode.Keys);
  115. var dwdAffected = 0;
  116. var cycleDaysList = new List<int>();
  117. foreach (var code in allCodes)
  118. {
  119. ct.ThrowIfCancellationRequested();
  120. var online = onlineByCode.GetValueOrDefault(code);
  121. var receipt = receiptByCode.GetValueOrDefault(code);
  122. int? cycleDays = null;
  123. if (online.HasValue && receipt.HasValue)
  124. {
  125. cycleDays = (int)(online.Value.Date - receipt.Value.Date).TotalDays;
  126. cycleDaysList.Add(cycleDays.Value);
  127. }
  128. dwdAffected += await _db.Ado.ExecuteCommandAsync(@"
  129. INSERT INTO dwd_t8_material_online_cycle
  130. (tenant_id, factory_id, biz_date, source_ztid, item_code, online_date, receipt_date, cycle_days, batch_id, create_time)
  131. VALUES
  132. (@tenantId, @factoryId, @bizDate, @ztid, @itemCode, @online, @receipt, @cycleDays, @batchId, @now)
  133. ON DUPLICATE KEY UPDATE
  134. online_date=VALUES(online_date), receipt_date=VALUES(receipt_date),
  135. cycle_days=VALUES(cycle_days), batch_id=VALUES(batch_id), update_time=@now",
  136. new SugarParameter("@tenantId", option.TargetTenantId),
  137. new SugarParameter("@factoryId", option.TargetFactoryId),
  138. new SugarParameter("@bizDate", option.BizDate),
  139. new SugarParameter("@ztid", option.SourceZtid),
  140. new SugarParameter("@itemCode", code),
  141. new SugarParameter("@online", online),
  142. new SugarParameter("@receipt", receipt),
  143. new SugarParameter("@cycleDays", cycleDays),
  144. new SugarParameter("@batchId", batchId),
  145. new SugarParameter("@now", now));
  146. }
  147. sub.DwdRows = dwdAffected;
  148. // KPI 值:所有物料 cycle_days 的算术平均;没有任一可计算物料时写 NULL,不伪装 0
  149. decimal? metricValue = cycleDaysList.Count > 0
  150. ? (decimal)cycleDaysList.Average()
  151. : null;
  152. sub.KpiRows = await UpsertKpiValueAsync("S5_L1_001", option.BizDate, metricValue, now, option);
  153. sub.DenominatorStatus = cycleDaysList.Count > 0 ? "OK" : "NO_NUMERATOR";
  154. return sub;
  155. }
  156. /// <summary>S5_L1_002 物料上线满足率 = 开工日期前完成上线行数 / 工单物料总行数。</summary>
  157. private async Task<KpiBuildSubResult> BuildS5L1002MaterialOnlineFulfillmentAsync(
  158. string batchId, DateTime now, S5MdpRefreshOption option, CancellationToken ct)
  159. {
  160. var sub = new KpiBuildSubResult();
  161. const string sqlNumer = @"
  162. select lynoid as lynoid, count(*) as codenum
  163. from (
  164. select a.lynoid as lynoid, b.code as code
  165. from kc_tz_head a with(nolock)
  166. inner join kc_tz_list b with(nolock) on a.Id=b.idid
  167. left join (
  168. select noid as noid, min(kgdate) as kgdate
  169. from Cj_Bg_Head_Rep with(nolock)
  170. where ztid=@ztid group by noid
  171. ) c on a.lynoid=c.noid
  172. where a.ztid=@ztid and a.lbs='生产领料' and a.hzyn=0 and a.zfyn=0 and a.shyn=1 and a.shtime<=c.kgdate
  173. group by a.lynoid, b.code
  174. ) n
  175. group by lynoid";
  176. const string sqlDenom = @"
  177. select a.noid as noid, count(b.id) as listnum
  178. from kc_dd_head a with(nolock)
  179. left join kc_dd_list_cllist b with(nolock) on a.Id=b.idid
  180. where a.ztid=@ztid and a.lbs='生产任务' and a.zf=0 and a.shyn=1
  181. group by a.noid";
  182. var p = new[] { new SugarParameter("@ztid", option.SourceZtid) };
  183. var numerRows = await QueryT8Async<S5FulfillmentNumerRow>(sqlNumer, p);
  184. var denomRows = await QueryT8Async<S5FulfillmentDenomRow>(sqlDenom, p);
  185. sub.T8Rows = numerRows.Count + denomRows.Count;
  186. var numerByOrder = numerRows.Where(r => !string.IsNullOrEmpty(r.lynoid))
  187. .ToDictionary(r => r.lynoid!, r => r.codenum, StringComparer.OrdinalIgnoreCase);
  188. var dwdAffected = 0;
  189. var rateList = new List<decimal>();
  190. foreach (var d in denomRows)
  191. {
  192. ct.ThrowIfCancellationRequested();
  193. if (string.IsNullOrEmpty(d.noid)) continue;
  194. var beforeKg = numerByOrder.GetValueOrDefault(d.noid, 0);
  195. decimal? rate = d.listnum > 0
  196. ? Math.Round((decimal)beforeKg / d.listnum, 4)
  197. : null; // 分母为 0 时不伪装真实 0
  198. if (rate.HasValue) rateList.Add(rate.Value);
  199. dwdAffected += await _db.Ado.ExecuteCommandAsync(@"
  200. INSERT INTO dwd_t8_material_online_fulfillment
  201. (tenant_id, factory_id, biz_date, source_ztid, work_order_no,
  202. before_kgdate_rows, total_rows, fulfillment_rate, batch_id, create_time)
  203. VALUES
  204. (@tenantId, @factoryId, @bizDate, @ztid, @workOrderNo, @beforeKg, @total, @rate, @batchId, @now)
  205. ON DUPLICATE KEY UPDATE
  206. before_kgdate_rows=VALUES(before_kgdate_rows),
  207. total_rows=VALUES(total_rows),
  208. fulfillment_rate=VALUES(fulfillment_rate),
  209. batch_id=VALUES(batch_id), update_time=@now",
  210. new SugarParameter("@tenantId", option.TargetTenantId),
  211. new SugarParameter("@factoryId", option.TargetFactoryId),
  212. new SugarParameter("@bizDate", option.BizDate),
  213. new SugarParameter("@ztid", option.SourceZtid),
  214. new SugarParameter("@workOrderNo", d.noid),
  215. new SugarParameter("@beforeKg", beforeKg),
  216. new SugarParameter("@total", d.listnum),
  217. new SugarParameter("@rate", rate),
  218. new SugarParameter("@batchId", batchId),
  219. new SugarParameter("@now", now));
  220. }
  221. sub.DwdRows = dwdAffected;
  222. decimal? metricValue = rateList.Count > 0
  223. ? Math.Round(rateList.Average() * 100m, 4) // 百分号
  224. : null;
  225. sub.KpiRows = await UpsertKpiValueAsync("S5_L1_002", option.BizDate, metricValue, now, option);
  226. sub.DenominatorStatus = rateList.Count > 0 ? "OK" : "NO_VALID_ORDER";
  227. return sub;
  228. }
  229. /// <summary>S5_L1_003 物料仓储人效 = SUM(slzx where lbs=生产领料) / count(gw=仓管)。</summary>
  230. private async Task<KpiBuildSubResult> BuildS5L1003MaterialWarehouseEfficiencyAsync(
  231. string batchId, DateTime now, S5MdpRefreshOption option, CancellationToken ct)
  232. {
  233. var sub = new KpiBuildSubResult();
  234. const string sqlNumer = @"
  235. select sum(b.slzx) as slzx
  236. from mdp_std_t8_kc_tz_head a
  237. inner join mdp_std_t8_kc_tz_list b on a.src_id=b.idid
  238. where a.ztid=@ztid and a.lbs='生产领料' and a.hzyn=0 and a.zfyn=0 and a.shyn=1
  239. and a.shtime between @startDate and @endDate";
  240. const string sqlDenom = @"
  241. select count(*) as penum
  242. from mdp_std_t8_sys_pelist
  243. where ztid=@ztid and zzzt='在职' and gw='仓管'";
  244. var pNumer = new[]
  245. {
  246. new SugarParameter("@ztid", option.SourceZtid),
  247. new SugarParameter("@startDate", option.MonthlyPeriodStart),
  248. new SugarParameter("@endDate", option.MonthlyPeriodEnd)
  249. };
  250. var pDenom = new[] { new SugarParameter("@ztid", option.SourceZtid) };
  251. var numerRows = await _db.Ado.SqlQueryAsync<S5SumQtyRow>(sqlNumer, pNumer);
  252. var denomRows = await _db.Ado.SqlQueryAsync<S5CountRow>(sqlDenom, pDenom);
  253. sub.T8Rows = numerRows.Count + denomRows.Count;
  254. decimal? onlineQty = numerRows.FirstOrDefault()?.slzx;
  255. int? headcount = denomRows.FirstOrDefault()?.penum;
  256. // 分母 = 0 或 NULL:efficiency 写 NULL,并标记 denominator_status;不伪装真实 0
  257. decimal? efficiency = null;
  258. string denomStatus;
  259. if (!headcount.HasValue || headcount.Value <= 0)
  260. {
  261. denomStatus = "NO_HEADCOUNT";
  262. }
  263. else if (!onlineQty.HasValue)
  264. {
  265. denomStatus = "NO_NUMERATOR";
  266. }
  267. else
  268. {
  269. efficiency = Math.Round(onlineQty.Value / headcount.Value, 4);
  270. denomStatus = "OK";
  271. }
  272. sub.DenominatorStatus = denomStatus;
  273. // 月度 KPI 用 biz_month 唯一键,整月 1 行
  274. var dwdAffected = await _db.Ado.ExecuteCommandAsync(@"
  275. INSERT INTO dwd_t8_material_warehouse_efficiency
  276. (tenant_id, factory_id, biz_month, source_ztid, period_start, period_end,
  277. online_qty, warehouse_headcount, efficiency, denominator_status, batch_id, create_time)
  278. VALUES
  279. (@tenantId, @factoryId, @bizMonth, @ztid, @periodStart, @periodEnd,
  280. @onlineQty, @headcount, @efficiency, @denomStatus, @batchId, @now)
  281. ON DUPLICATE KEY UPDATE
  282. period_start=VALUES(period_start), period_end=VALUES(period_end),
  283. online_qty=VALUES(online_qty), warehouse_headcount=VALUES(warehouse_headcount),
  284. efficiency=VALUES(efficiency), denominator_status=VALUES(denominator_status),
  285. batch_id=VALUES(batch_id), update_time=@now",
  286. new SugarParameter("@tenantId", option.TargetTenantId),
  287. new SugarParameter("@factoryId", option.TargetFactoryId),
  288. new SugarParameter("@bizMonth", option.BizMonth),
  289. new SugarParameter("@ztid", option.SourceZtid),
  290. new SugarParameter("@periodStart", option.MonthlyPeriodStart),
  291. new SugarParameter("@periodEnd", option.MonthlyPeriodEnd),
  292. new SugarParameter("@onlineQty", onlineQty),
  293. new SugarParameter("@headcount", headcount),
  294. new SugarParameter("@efficiency", efficiency),
  295. new SugarParameter("@denomStatus", denomStatus),
  296. new SugarParameter("@batchId", batchId),
  297. new SugarParameter("@now", now));
  298. sub.DwdRows = dwdAffected;
  299. // 月度 KPI 入日表:用月末日作 biz_date,月内每天可由聚合 API 再分发;分母缺失时 metric_value=NULL
  300. sub.KpiRows = await UpsertKpiValueAsync("S5_L1_003", option.MonthlyPeriodEnd, efficiency, now, option);
  301. return sub;
  302. }
  303. /// <summary>S5_L1_004 品类物料库存周转 = D1/D2 × 30;D1=je3 月均库存金额,D2=je2 出库成本。</summary>
  304. private async Task<KpiBuildSubResult> BuildS5L1004MaterialInventoryTurnoverAsync(
  305. string batchId, DateTime now, S5MdpRefreshOption option, CancellationToken ct)
  306. {
  307. var sub = new KpiBuildSubResult();
  308. // TVF:Rep_总账_存货_V3(账套, '普通', '正常', 起期 YYYYMM, 止期 YYYYMM)
  309. const string sqlTvf = @"
  310. select ckcode as ckcode, ckname as ckname,
  311. code as code, cname as cname,
  312. pcode as pcode, pname as pname,
  313. je3 as je3, je2 as je2
  314. from dbo.Rep_总账_存货_V3(@ztid, N'普通', N'正常', @startYm, @endYm)";
  315. var p = new[]
  316. {
  317. new SugarParameter("@ztid", option.SourceZtid),
  318. new SugarParameter("@startYm", option.TvfPeriodStartYyyymm),
  319. new SugarParameter("@endYm", option.TvfPeriodEndYyyymm)
  320. };
  321. var tvfRows = await QueryT8Async<S5InventoryTurnoverRow>(sqlTvf, p);
  322. sub.T8Rows = tvfRows.Count;
  323. var dwdAffected = 0;
  324. var turnoverDaysList = new List<decimal>();
  325. foreach (var r in tvfRows)
  326. {
  327. ct.ThrowIfCancellationRequested();
  328. // 周转天数:D2=0 或 NULL 时 NULL,不伪装 0
  329. decimal? turnoverDays = (r.je2.HasValue && r.je2.Value > 0m && r.je3.HasValue)
  330. ? Math.Round(r.je3.Value / r.je2.Value * 30m, 4)
  331. : null;
  332. if (turnoverDays.HasValue) turnoverDaysList.Add(turnoverDays.Value);
  333. dwdAffected += await _db.Ado.ExecuteCommandAsync(@"
  334. INSERT INTO dwd_t8_material_inventory_turnover
  335. (tenant_id, factory_id, biz_month, source_ztid, period_start_yyyymm, period_end_yyyymm,
  336. warehouse_code, warehouse_name, item_code, item_name, category_code, category_name,
  337. avg_inventory_value, monthly_outbound_cost, turnover_days, batch_id, create_time)
  338. VALUES
  339. (@tenantId, @factoryId, @bizMonth, @ztid, @startYm, @endYm,
  340. @ckcode, @ckname, @itemCode, @itemName, @pcode, @pname,
  341. @je3, @je2, @turnoverDays, @batchId, @now)
  342. ON DUPLICATE KEY UPDATE
  343. warehouse_name=VALUES(warehouse_name), item_name=VALUES(item_name),
  344. category_code=VALUES(category_code), category_name=VALUES(category_name),
  345. avg_inventory_value=VALUES(avg_inventory_value),
  346. monthly_outbound_cost=VALUES(monthly_outbound_cost),
  347. turnover_days=VALUES(turnover_days),
  348. period_start_yyyymm=VALUES(period_start_yyyymm),
  349. period_end_yyyymm=VALUES(period_end_yyyymm),
  350. batch_id=VALUES(batch_id), update_time=@now",
  351. new SugarParameter("@tenantId", option.TargetTenantId),
  352. new SugarParameter("@factoryId", option.TargetFactoryId),
  353. new SugarParameter("@bizMonth", option.BizMonth),
  354. new SugarParameter("@ztid", option.SourceZtid),
  355. new SugarParameter("@startYm", option.TvfPeriodStartYyyymm),
  356. new SugarParameter("@endYm", option.TvfPeriodEndYyyymm),
  357. new SugarParameter("@ckcode", r.ckcode ?? ""),
  358. new SugarParameter("@ckname", r.ckname),
  359. new SugarParameter("@itemCode", r.code ?? ""),
  360. new SugarParameter("@itemName", r.cname),
  361. new SugarParameter("@pcode", r.pcode),
  362. new SugarParameter("@pname", r.pname),
  363. new SugarParameter("@je3", r.je3),
  364. new SugarParameter("@je2", r.je2),
  365. new SugarParameter("@turnoverDays", turnoverDays),
  366. new SugarParameter("@batchId", batchId),
  367. new SugarParameter("@now", now));
  368. }
  369. sub.DwdRows = dwdAffected;
  370. // KPI 值:所有品类周转天数算术平均;无任一可计算品类时 NULL
  371. decimal? metricValue = turnoverDaysList.Count > 0
  372. ? Math.Round(turnoverDaysList.Average(), 4)
  373. : null;
  374. sub.KpiRows = await UpsertKpiValueAsync("S5_L1_004", option.MonthlyPeriodEnd, metricValue, now, option);
  375. sub.DenominatorStatus = turnoverDaysList.Count > 0 ? "OK" : "NO_VALID_OUTBOUND_COST";
  376. return sub;
  377. }
  378. // ─────────────────────────────────────────────────────────────────────────
  379. // 跨库 / 写入 / 日志 封装
  380. // ─────────────────────────────────────────────────────────────────────────
  381. // legacy 直连 T8:仅 S5_L1_002(Cj_Bg_Head_Rep 报表)/ S5_L1_004(Rep_总账_存货_V3 TVF)仍用;
  382. // 这两类源非干净基表,暂不纳入双模式贴源,待底表摸清后单独立批。已中台化的 001/003 不再走此方法。
  383. private async Task<List<T>> QueryT8Async<T>(string sql, SugarParameter[] parameters)
  384. {
  385. var t8 = _db.AsTenant().GetConnectionScope(T8ConfigId);
  386. return await t8.Ado.SqlQueryAsync<T>(sql, parameters);
  387. }
  388. private async Task<int> UpsertKpiValueAsync(string metricCode, DateTime bizDate, decimal? metricValue, DateTime now, S5MdpRefreshOption option)
  389. {
  390. // 沿用 S3 UpsertS3KpiValueAsync 范式:先查现存行 → UPDATE;不存在 → SELECT MAX(id)+1 显式生成 id 后 INSERT。
  391. // ado_s9_kpi_value_l1_day.id 为手工分配主键(无 AUTO_INCREMENT),必须显式 set;
  392. // metric_value 允许 NULL(分母缺失不得伪装真实 0)。
  393. // FIX-2:截断时分秒(月度 KPI 入参可能为 YYYY-MM-DD 23:59:59),保证 SELECT WHERE biz_date=@BizDate 与 DB date 列匹配,避免重复 INSERT。
  394. // FIX-1:tenant_id/factory_id 取自 option,默认仍为 1300000000001/1,不破坏 Demo。
  395. bizDate = bizDate.Date;
  396. var existingId = await _db.Ado.GetLongAsync(
  397. "SELECT IFNULL((SELECT id FROM ado_s9_kpi_value_l1_day WHERE tenant_id=@TenantId AND factory_id=@FactoryId " +
  398. "AND module_code=@ModuleCode AND metric_code=@MetricCode AND biz_date=@BizDate AND is_deleted=0 " +
  399. "ORDER BY id LIMIT 1), 0)",
  400. new List<SugarParameter>
  401. {
  402. new("@TenantId", option.TargetTenantId),
  403. new("@FactoryId", option.TargetFactoryId),
  404. new("@ModuleCode", ModuleCode),
  405. new("@MetricCode", metricCode),
  406. new("@BizDate", bizDate)
  407. });
  408. if (existingId > 0)
  409. {
  410. return await _db.Ado.ExecuteCommandAsync(
  411. "UPDATE ado_s9_kpi_value_l1_day SET metric_value=@MetricValue, calc_time=@Now, " +
  412. "update_time=@Now, is_deleted=0, is_active=1 WHERE id=@Id",
  413. new SugarParameter("@MetricValue", metricValue),
  414. new SugarParameter("@Now", now),
  415. new SugarParameter("@Id", existingId));
  416. }
  417. var nextId = await _db.Ado.GetLongAsync(
  418. "SELECT COALESCE(MAX(id), 0) + 1 FROM ado_s9_kpi_value_l1_day");
  419. return await _db.Ado.ExecuteCommandAsync(@"
  420. INSERT INTO ado_s9_kpi_value_l1_day
  421. (id, tenant_id, org_id, company_id, factory_id, status, biz_date,
  422. create_time, update_time, is_deleted, is_active,
  423. module_code, metric_code, metric_value, calc_time)
  424. VALUES
  425. (@Id, @TenantId, NULL, NULL, @FactoryId, NULL, @BizDate,
  426. @Now, @Now, 0, 1,
  427. @ModuleCode, @MetricCode, @MetricValue, @Now)",
  428. new SugarParameter("@Id", nextId),
  429. new SugarParameter("@TenantId", option.TargetTenantId),
  430. new SugarParameter("@FactoryId", option.TargetFactoryId),
  431. new SugarParameter("@BizDate", bizDate),
  432. new SugarParameter("@Now", now),
  433. new SugarParameter("@ModuleCode", ModuleCode),
  434. new SugarParameter("@MetricCode", metricCode),
  435. new SugarParameter("@MetricValue", metricValue));
  436. }
  437. private async Task<long> InsertTransformRunLogAsync(string batchId, DateTime startedAt, string triggerType, S5MdpRefreshOption option)
  438. {
  439. await _db.Ado.ExecuteCommandAsync(@"
  440. INSERT INTO mdp_transform_run_log
  441. (tenant_id, job_code, job_name, trigger_type, batch_id, status, start_time, stage_rows, standard_rows, dwd_rows, create_time, update_time)
  442. VALUES
  443. (@TenantId, @JobCode, @JobName, @TriggerType, @BatchId, 'RUNNING', @StartTime, 0, 0, 0, @StartTime, @StartTime)",
  444. new SugarParameter("@TenantId", option.TargetTenantId),
  445. new SugarParameter("@JobCode", JobCode),
  446. new SugarParameter("@JobName", JobName),
  447. new SugarParameter("@TriggerType", triggerType),
  448. new SugarParameter("@BatchId", batchId),
  449. new SugarParameter("@StartTime", startedAt));
  450. return await _db.Ado.GetLongAsync(
  451. "SELECT id FROM mdp_transform_run_log WHERE batch_id=@BatchId ORDER BY id DESC LIMIT 1",
  452. new List<SugarParameter> { new("@BatchId", batchId) });
  453. }
  454. private async Task MarkTransformRunSuccessAsync(long runLogId, DateTime startedAt, S5MdpSyncTransformResult result)
  455. {
  456. var finishedAt = DateTime.Now;
  457. await _db.Ado.ExecuteCommandAsync(@"
  458. UPDATE mdp_transform_run_log
  459. SET status='SUCCESS', end_time=@EndTime, duration_ms=@DurationMs,
  460. stage_rows=@StageRows, standard_rows=@StandardRows, dwd_rows=@DwdRows,
  461. summary_json=@SummaryJson, update_time=CURRENT_TIMESTAMP
  462. WHERE id=@Id",
  463. new SugarParameter("@EndTime", finishedAt),
  464. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  465. new SugarParameter("@StageRows", result.StageRows),
  466. new SugarParameter("@StandardRows", result.StandardRows),
  467. new SugarParameter("@DwdRows", result.DwdRows),
  468. new SugarParameter("@SummaryJson", BuildRunSummaryJson(result)),
  469. new SugarParameter("@Id", runLogId));
  470. }
  471. private async Task MarkTransformRunFailedAsync(long runLogId, DateTime startedAt, string message, string batchId)
  472. {
  473. bool runLogUpdated = false;
  474. try
  475. {
  476. var finishedAt = DateTime.Now;
  477. await _db.Ado.ExecuteCommandAsync(@"
  478. UPDATE mdp_transform_run_log
  479. SET status='FAILED', end_time=@EndTime, duration_ms=@DurationMs,
  480. error_message=@ErrorMessage, update_time=CURRENT_TIMESTAMP
  481. WHERE id=@Id",
  482. new SugarParameter("@EndTime", finishedAt),
  483. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  484. new SugarParameter("@ErrorMessage", Truncate(message, 2000)),
  485. new SugarParameter("@Id", runLogId));
  486. runLogUpdated = true;
  487. }
  488. catch (Exception ex)
  489. {
  490. // 写库本身失败兜底:远端 MySQL 瞬断导致 MarkFailed 自身也连不上
  491. Console.Error.WriteLine($"[S5MdpSyncTransform] MarkTransformRunFailed write failed (runLogId={runLogId}): {ex.Message}");
  492. }
  493. // FAILURE-NOTIFICATION-1:写库 FAILED 成功后发通知给超级管理员;通知失败不影响主流程
  494. if (!runLogUpdated) return;
  495. try
  496. {
  497. await _sysNoticeService.AddNotice(new AddNoticeInput
  498. {
  499. Title = "S5 物料仓储 T8 KPI 跑批失败",
  500. Content = $"模块:S5 物料仓储\n批次ID:{batchId}\n失败时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}\n错误信息:{Truncate(message, 1000)}\n\n请查看 mdp_transform_run_log 获取完整错误与重试记录。",
  501. Type = NoticeTypeEnum.NOTICE,
  502. PublicTime = DateTime.Now,
  503. Status = NoticeStatusEnum.PUBLIC,
  504. PublicUserId = NoticeReceiverUserId,
  505. PublicUserName = NoticeReceiverUserName
  506. });
  507. }
  508. catch (Exception notifyEx)
  509. {
  510. _logger.LogError(notifyEx, "[S5MdpSyncTransform] SysNotice 发送失败 (runLogId={RunLogId}, batchId={BatchId})", runLogId, batchId);
  511. }
  512. }
  513. private static string BuildRunSummaryJson(S5MdpSyncTransformResult r)
  514. {
  515. var summary = new
  516. {
  517. batchId = r.BatchId,
  518. sourceZtid = r.SourceZtid,
  519. bizDate = r.BizDate.ToString("yyyy-MM-dd"),
  520. bizMonth = r.BizMonth,
  521. triggerType = r.TriggerType,
  522. dwdRows = r.DwdRows,
  523. kpiRows = r.KpiRows,
  524. perKpiDwdRows = r.PerKpiDwdRows,
  525. perKpiKpiRows = r.PerKpiKpiRows,
  526. denominatorStatus = r.KpiDenominatorStatus,
  527. tvfPeriod = $"{r.MonthlyPeriodStart:yyyy-MM-dd}~{r.MonthlyPeriodEnd:yyyy-MM-dd}"
  528. };
  529. return JsonSerializer.Serialize(summary);
  530. }
  531. private static string NormalizeTriggerType(string s) =>
  532. string.IsNullOrWhiteSpace(s) ? "AUTO" : s.Trim().ToUpperInvariant();
  533. private static void NormalizeOption(S5MdpRefreshOption option)
  534. {
  535. var d = S5MdpRefreshOption.Default();
  536. if (option.TargetFactoryId <= 0) option.TargetFactoryId = d.TargetFactoryId;
  537. if (string.IsNullOrWhiteSpace(option.SourceZtid)) option.SourceZtid = d.SourceZtid;
  538. // 目标租户由 T8 账套(ztid)映射决定,禁止固定默认/兜底
  539. option.TargetTenantId = AidopSourceTenantMap.ResolveTenantId(option.SourceZtid, option.TargetTenantId);
  540. if (option.BizDate == default) option.BizDate = d.BizDate;
  541. if (string.IsNullOrWhiteSpace(option.BizMonth)) option.BizMonth = d.BizMonth;
  542. if (option.DailyPeriodStart == default) option.DailyPeriodStart = d.DailyPeriodStart;
  543. if (option.DailyPeriodEnd == default) option.DailyPeriodEnd = d.DailyPeriodEnd;
  544. if (option.MonthlyPeriodStart == default) option.MonthlyPeriodStart = d.MonthlyPeriodStart;
  545. if (option.MonthlyPeriodEnd == default) option.MonthlyPeriodEnd = d.MonthlyPeriodEnd;
  546. if (string.IsNullOrWhiteSpace(option.TvfPeriodStartYyyymm)) option.TvfPeriodStartYyyymm = d.TvfPeriodStartYyyymm;
  547. if (string.IsNullOrWhiteSpace(option.TvfPeriodEndYyyymm)) option.TvfPeriodEndYyyymm = d.TvfPeriodEndYyyymm;
  548. }
  549. private static string Truncate(string s, int max) =>
  550. string.IsNullOrEmpty(s) ? "" : (s.Length <= max ? s : s.Substring(0, max));
  551. }
  552. // ─────────────────────────────────────────────────────────────────────────────
  553. // Refresh 入参与结果 DTO
  554. // ─────────────────────────────────────────────────────────────────────────────
  555. public sealed class S5MdpRefreshOption
  556. {
  557. /// <summary>T8 账套(kc_tz_head.ztid);实测当前唯一账套为 pbxfxp。</summary>
  558. public string SourceZtid { get; set; } = "pbxfxp";
  559. /// <summary>KPI/DWD 落库目标租户;≤0 时由 <see cref="AidopSourceTenantMap"/> 按 SourceZtid 解析。</summary>
  560. public long TargetTenantId { get; set; }
  561. /// <summary>KPI/DWD 落库目标工厂;默认 1。</summary>
  562. public long TargetFactoryId { get; set; } = 1L;
  563. /// <summary>日 T+1 KPI 的业务日期(默认昨天)。</summary>
  564. public DateTime BizDate { get; set; }
  565. /// <summary>月 M+1 KPI 的业务月 YYYY-MM(默认上月)。</summary>
  566. public string BizMonth { get; set; } = "";
  567. /// <summary>日 T+1 KPI 区间起(含),默认昨天 00:00。</summary>
  568. public DateTime DailyPeriodStart { get; set; }
  569. /// <summary>日 T+1 KPI 区间止(含),默认昨天 23:59:59。</summary>
  570. public DateTime DailyPeriodEnd { get; set; }
  571. /// <summary>月 M+1 KPI 区间起(含),默认上月 1 日。</summary>
  572. public DateTime MonthlyPeriodStart { get; set; }
  573. /// <summary>月 M+1 KPI 区间止(含),默认上月末日。</summary>
  574. public DateTime MonthlyPeriodEnd { get; set; }
  575. /// <summary>TVF Rep_总账_存货_V3 入参起期 YYYYMM。</summary>
  576. public string TvfPeriodStartYyyymm { get; set; } = "";
  577. /// <summary>TVF Rep_总账_存货_V3 入参止期 YYYYMM。</summary>
  578. public string TvfPeriodEndYyyymm { get; set; } = "";
  579. public static S5MdpRefreshOption Default()
  580. {
  581. var today = DateTime.Today;
  582. var yesterday = today.AddDays(-1);
  583. var lastMonth = today.AddMonths(-1);
  584. var monthStart = new DateTime(lastMonth.Year, lastMonth.Month, 1);
  585. var monthEnd = monthStart.AddMonths(1).AddDays(-1);
  586. return new S5MdpRefreshOption
  587. {
  588. SourceZtid = "pbxfxp",
  589. TargetTenantId = 0,
  590. TargetFactoryId = 1L,
  591. BizDate = yesterday,
  592. BizMonth = lastMonth.ToString("yyyy-MM"),
  593. DailyPeriodStart = yesterday,
  594. DailyPeriodEnd = yesterday.AddDays(1).AddSeconds(-1),
  595. MonthlyPeriodStart = monthStart,
  596. MonthlyPeriodEnd = monthEnd.AddDays(1).AddSeconds(-1),
  597. TvfPeriodStartYyyymm = monthStart.ToString("yyyyMM"),
  598. TvfPeriodEndYyyymm = monthEnd.ToString("yyyyMM")
  599. };
  600. }
  601. }
  602. public sealed class S5MdpSyncTransformResult
  603. {
  604. public string BatchId { get; set; } = "";
  605. public long RunLogId { get; set; }
  606. public string TriggerType { get; set; } = "AUTO";
  607. public string SourceZtid { get; set; } = "";
  608. public long TargetTenantId { get; set; }
  609. public long TargetFactoryId { get; set; }
  610. public DateTime BizDate { get; set; }
  611. public string BizMonth { get; set; } = "";
  612. public DateTime DailyPeriodStart { get; set; }
  613. public DateTime DailyPeriodEnd { 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. // ─────────────────────────────────────────────────────────────────────────────
  640. // T8 result set 投影类型(与方老师 SQL SELECT 列名严格一致;SqlSugar 映射)
  641. // ─────────────────────────────────────────────────────────────────────────────
  642. internal sealed class S5OnlineCycleRow
  643. {
  644. public string? code { get; set; }
  645. public DateTime? shtime { get; set; }
  646. }
  647. internal sealed class S5FulfillmentNumerRow
  648. {
  649. public string? lynoid { get; set; }
  650. public int codenum { get; set; }
  651. }
  652. internal sealed class S5FulfillmentDenomRow
  653. {
  654. public string? noid { get; set; }
  655. public int listnum { get; set; }
  656. }
  657. internal sealed class S5SumQtyRow
  658. {
  659. public decimal? slzx { get; set; }
  660. }
  661. internal sealed class S5CountRow
  662. {
  663. public int penum { get; set; }
  664. }
  665. internal sealed class S5InventoryTurnoverRow
  666. {
  667. public string? ckcode { get; set; }
  668. public string? ckname { get; set; }
  669. public string? code { get; set; }
  670. public string? cname { get; set; }
  671. public string? pcode { get; set; }
  672. public string? pname { get; set; }
  673. public decimal? je3 { get; set; }
  674. public decimal? je2 { get; set; }
  675. }