S5MdpSyncTransformService.cs 36 KB

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