S5MdpSyncTransformService.cs 33 KB

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