S7MdpSyncTransformService.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. using Admin.NET.Core.Service;
  2. using Microsoft.Extensions.Logging;
  3. using System.Text.Json;
  4. namespace Admin.NET.Plugin.AiDOP.FinishedWarehouse;
  5. /// <summary>
  6. /// S7 成品仓储 — T8 KPI 数据底座与刷新转换服务。
  7. /// 路径 A:方老师 v5.4 KPI 字段对照表 J 列 SQL 原逻辑直发 T8 SQL Server(ConfigId=t8_v5)。
  8. /// 包含 KPI:S7_L1_001 订单发货周期 / S7_L1_002 订单发货满足率 / S7_L1_003 成品仓储人效。
  9. /// </summary>
  10. public class S7MdpSyncTransformService : ITransient
  11. {
  12. private readonly ISqlSugarClient _db;
  13. private readonly SysNoticeService _sysNoticeService;
  14. private readonly ILogger<S7MdpSyncTransformService> _logger;
  15. private const string JobCode = "S7_MDP_SYNC_TRANSFORM";
  16. private const string JobName = "S7 成品仓储 MDP 同步与转换";
  17. private const string T8ConfigId = "t8_v5";
  18. private const string ModuleCode = "S7";
  19. // FAILURE-NOTIFICATION-1:超级管理员 superAdmin.NET(AccountType=999)
  20. private const long NoticeReceiverUserId = 1300000000101L;
  21. private const string NoticeReceiverUserName = "超级管理员";
  22. public S7MdpSyncTransformService(
  23. ISqlSugarClient db,
  24. SysNoticeService sysNoticeService,
  25. ILogger<S7MdpSyncTransformService> logger)
  26. {
  27. _db = db;
  28. _sysNoticeService = sysNoticeService;
  29. _logger = logger;
  30. }
  31. public async Task<S7MdpSyncTransformResult> RunFullAsync(
  32. CancellationToken cancellationToken = default,
  33. string triggerType = "AUTO",
  34. S7MdpRefreshOption? option = null)
  35. {
  36. cancellationToken.ThrowIfCancellationRequested();
  37. option ??= S7MdpRefreshOption.Default();
  38. // 目标租户由 T8 账套(ztid)映射决定,替代此前写死的 1300000000001(禁止固定默认/兜底)
  39. option.TenantId = AidopSourceTenantMap.ResolveTenantId(option.SourceZtid, option.TenantId);
  40. var now = DateTime.Now;
  41. var batchId = $"S7_MDP_FULL_{now:yyyyMMddHHmmss}";
  42. var normalizedTrigger = NormalizeTriggerType(triggerType);
  43. var runLogId = await InsertTransformRunLogAsync(batchId, now, normalizedTrigger, option.TenantId);
  44. var result = new S7MdpSyncTransformResult
  45. {
  46. BatchId = batchId,
  47. RunLogId = runLogId,
  48. TriggerType = normalizedTrigger,
  49. SourceZtid = option.SourceZtid,
  50. BizDate = option.BizDate,
  51. BizMonth = option.BizMonth,
  52. MonthlyPeriodStart = option.MonthlyPeriodStart,
  53. MonthlyPeriodEnd = option.MonthlyPeriodEnd
  54. };
  55. try
  56. {
  57. result.StageRows = 0;
  58. result.StandardRows = 0;
  59. var sub25 = await BuildS7L1001OrderShipmentCycleAsync(batchId, now, option, cancellationToken);
  60. result.MergeSub("S7_L1_001", sub25);
  61. var sub26 = await BuildS7L1002OrderShipmentFulfillmentAsync(batchId, now, option, cancellationToken);
  62. result.MergeSub("S7_L1_002", sub26);
  63. var sub27 = await BuildS7L1003FinishedWarehouseEfficiencyAsync(batchId, now, option, cancellationToken);
  64. result.MergeSub("S7_L1_003", sub27);
  65. await MarkTransformRunSuccessAsync(runLogId, now, result);
  66. return result;
  67. }
  68. catch (Exception ex)
  69. {
  70. await MarkTransformRunFailedAsync(runLogId, now, ex.Message, batchId);
  71. throw;
  72. }
  73. }
  74. // ─────────────────────────────────────────────────────────────────────────
  75. /// <summary>S7_L1_001 订单发货周期 = 最晚发货日期 - 最早 FQC 报检日期(5 表 JOIN)。</summary>
  76. private async Task<KpiBuildSubResult> BuildS7L1001OrderShipmentCycleAsync(
  77. string batchId, DateTime now, S7MdpRefreshOption option, CancellationToken ct)
  78. {
  79. var sub = new KpiBuildSubResult();
  80. const string sql = @"
  81. select noid as noid,
  82. datediff(day, min(shdate), max(shtime)) as scts
  83. from (
  84. select a.noid as noid, b.code as code,
  85. IsNull(c.shdate, b.addtime) as shdate,
  86. (case when b.gdyn=1 then b.gdtime else d.shtime end) as shtime,
  87. (case when b.gdyn=1 or b.sl<=b.slzx then 1 else 0 end) as wczt
  88. from kc_dd_head a with(nolock)
  89. left join kc_dd_list b with(nolock) on a.Id=b.idid
  90. left join (
  91. select min(b.id) as id, b.lynoid as lynoid, b.code as code,
  92. max(a.shtime) as shtime, sum(b.slzx) as slzx
  93. from kc_tz_head a with(nolock)
  94. inner join kc_tz_list b with(nolock) on a.Id=b.idid
  95. where a.ztid=@ztid and a.lbs='销售出库' and a.hzyn=0 and a.zfyn=0 and a.shyn=1
  96. group by b.lynoid, b.code
  97. ) d on b.rwnoid=d.lynoid and b.code=d.code
  98. left join kc_zj_list c on a.ztid=c.ztid and c.lyid=b.id and c.zjyn=1
  99. where a.ztid=@ztid and a.lbs='销售订单' and a.zf=0 and a.shyn=1
  100. ) n
  101. group by noid
  102. having min(wczt)=1";
  103. var rows = await QueryT8Async<S7CycleRow>(sql, new[] { new SugarParameter("@ztid", option.SourceZtid) });
  104. sub.T8Rows = rows.Count;
  105. var dwdAffected = 0;
  106. var cycleList = new List<int>();
  107. foreach (var r in rows)
  108. {
  109. ct.ThrowIfCancellationRequested();
  110. if (string.IsNullOrEmpty(r.noid)) continue;
  111. if (r.scts.HasValue) cycleList.Add(r.scts.Value);
  112. dwdAffected += await _db.Ado.ExecuteCommandAsync(@"
  113. INSERT INTO dwd_t8_order_shipment_cycle
  114. (tenant_id, factory_id, biz_date, source_ztid, order_no, cycle_days, batch_id, create_time)
  115. VALUES
  116. (@TenantId, 1, @bizDate, @ztid, @orderNo, @cycleDays, @batchId, @now)
  117. ON DUPLICATE KEY UPDATE
  118. cycle_days=VALUES(cycle_days),
  119. batch_id=VALUES(batch_id), update_time=@now",
  120. new SugarParameter("@TenantId", option.TenantId),
  121. new SugarParameter("@bizDate", option.BizDate),
  122. new SugarParameter("@ztid", option.SourceZtid),
  123. new SugarParameter("@orderNo", r.noid),
  124. new SugarParameter("@cycleDays", r.scts),
  125. new SugarParameter("@batchId", batchId),
  126. new SugarParameter("@now", now));
  127. }
  128. sub.DwdRows = dwdAffected;
  129. decimal? metricValue = cycleList.Count > 0
  130. ? Math.Round((decimal)cycleList.Average(), 4)
  131. : null;
  132. sub.KpiRows = await UpsertKpiValueAsync("S7_L1_001", option.TenantId, option.BizDate, metricValue, now);
  133. sub.DenominatorStatus = cycleList.Count > 0 ? "OK" : "NO_COMPLETED_ORDER";
  134. return sub;
  135. }
  136. /// <summary>S7_L1_002 订单发货满足率 = (交期前发货行数 / 该订单总行数) × 100%。</summary>
  137. private async Task<KpiBuildSubResult> BuildS7L1002OrderShipmentFulfillmentAsync(
  138. string batchId, DateTime now, S7MdpRefreshOption option, CancellationToken ct)
  139. {
  140. var sub = new KpiBuildSubResult();
  141. const string sql = @"
  142. select noid as noid,
  143. count(noid) as total_rows,
  144. sum(wczt) as in_window_rows
  145. from (
  146. select a.noid as noid, b.rwnoid as rwnoid, b.code as code,
  147. (case when sum(d.slzx)>=b.sl then 1 else 0 end) as wczt
  148. from kc_dd_head a with(nolock)
  149. left join kc_dd_list b with(nolock) on a.Id=b.idid
  150. left join (
  151. select b.lynoid as lynoid, b.code as code,
  152. convert(varchar(10), a.shtime, 23) as shtime, b.slzx as slzx
  153. from kc_tz_head a with(nolock)
  154. inner join kc_tz_list b with(nolock) on a.Id=b.idid
  155. where a.ztid=@ztid and a.lbs='销售出库' and a.hzyn=0 and a.zfyn=0 and a.shyn=1
  156. ) d on b.rwnoid=d.lynoid and b.code=d.code and d.shtime<=b.jhdate
  157. where a.ztid=@ztid and a.lbs='销售订单' and a.zf=0 and a.shyn=1
  158. group by a.noid, b.rwnoid, b.code, b.sl
  159. ) n
  160. group by noid";
  161. var rows = await QueryT8Async<S7FulfillmentRow>(sql, new[] { new SugarParameter("@ztid", option.SourceZtid) });
  162. sub.T8Rows = rows.Count;
  163. var dwdAffected = 0;
  164. var rateList = new List<decimal>();
  165. foreach (var r in rows)
  166. {
  167. ct.ThrowIfCancellationRequested();
  168. if (string.IsNullOrEmpty(r.noid)) continue;
  169. decimal? rate = (r.total_rows > 0)
  170. ? Math.Round((decimal)r.in_window_rows / r.total_rows * 100m, 4)
  171. : null;
  172. if (rate.HasValue) rateList.Add(rate.Value);
  173. dwdAffected += await _db.Ado.ExecuteCommandAsync(@"
  174. INSERT INTO dwd_t8_order_shipment_fulfillment
  175. (tenant_id, factory_id, biz_date, source_ztid, order_no,
  176. total_rows, in_window_rows, fulfillment_rate, batch_id, create_time)
  177. VALUES
  178. (@TenantId, 1, @bizDate, @ztid, @orderNo,
  179. @total, @inWindow, @rate, @batchId, @now)
  180. ON DUPLICATE KEY UPDATE
  181. total_rows=VALUES(total_rows), in_window_rows=VALUES(in_window_rows),
  182. fulfillment_rate=VALUES(fulfillment_rate),
  183. batch_id=VALUES(batch_id), update_time=@now",
  184. new SugarParameter("@TenantId", option.TenantId),
  185. new SugarParameter("@bizDate", option.BizDate),
  186. new SugarParameter("@ztid", option.SourceZtid),
  187. new SugarParameter("@orderNo", r.noid),
  188. new SugarParameter("@total", r.total_rows),
  189. new SugarParameter("@inWindow", r.in_window_rows),
  190. new SugarParameter("@rate", rate),
  191. new SugarParameter("@batchId", batchId),
  192. new SugarParameter("@now", now));
  193. }
  194. sub.DwdRows = dwdAffected;
  195. decimal? metricValue = rateList.Count > 0
  196. ? Math.Round(rateList.Average(), 4)
  197. : null;
  198. sub.KpiRows = await UpsertKpiValueAsync("S7_L1_002", option.TenantId, option.BizDate, metricValue, now);
  199. sub.DenominatorStatus = rateList.Count > 0 ? "OK" : "NO_VALID_ORDER";
  200. return sub;
  201. }
  202. /// <summary>S7_L1_003 成品仓储人效 = SUM(slzx where lbs=销售出库) / count(gw=仓管)。</summary>
  203. private async Task<KpiBuildSubResult> BuildS7L1003FinishedWarehouseEfficiencyAsync(
  204. string batchId, DateTime now, S7MdpRefreshOption option, CancellationToken ct)
  205. {
  206. var sub = new KpiBuildSubResult();
  207. const string sqlNumer = @"
  208. select b.lynoid as lynoid, b.code as code,
  209. convert(varchar(10), a.shtime, 23) as shtime, b.slzx as slzx
  210. from kc_tz_head a with(nolock)
  211. inner join kc_tz_list b with(nolock) on a.Id=b.idid
  212. where a.ztid=@ztid and a.lbs='销售出库' and a.hzyn=0 and a.zfyn=0 and a.shyn=1
  213. and convert(varchar(10), a.shtime, 23) between @startDateText and @endDateText";
  214. const string sqlDenom = @"
  215. select count(*) as penum
  216. from sys_pelist with(nolock)
  217. where ztid=@ztid and zzzt='在职' and gw='仓管'";
  218. var pNumer = new[]
  219. {
  220. new SugarParameter("@ztid", option.SourceZtid),
  221. new SugarParameter("@startDateText", option.MonthlyPeriodStart.ToString("yyyy-MM-dd")),
  222. new SugarParameter("@endDateText", option.MonthlyPeriodEnd.ToString("yyyy-MM-dd"))
  223. };
  224. var pDenom = new[] { new SugarParameter("@ztid", option.SourceZtid) };
  225. var numerRows = await QueryT8Async<S7ShipmentDetailRow>(sqlNumer, pNumer);
  226. var denomRows = await QueryT8Async<S7PeNumRow>(sqlDenom, pDenom);
  227. sub.T8Rows = numerRows.Count + denomRows.Count;
  228. decimal? shipmentQty = numerRows.Sum(r => r.slzx ?? 0m);
  229. if (numerRows.Count == 0) shipmentQty = null;
  230. int? headcount = denomRows.FirstOrDefault()?.penum;
  231. decimal? efficiency = null;
  232. string denomStatus;
  233. if (!headcount.HasValue || headcount.Value <= 0)
  234. denomStatus = "NO_HEADCOUNT";
  235. else if (!shipmentQty.HasValue)
  236. denomStatus = "NO_NUMERATOR";
  237. else
  238. {
  239. efficiency = Math.Round(shipmentQty.Value / headcount.Value, 4);
  240. denomStatus = "OK";
  241. }
  242. sub.DenominatorStatus = denomStatus;
  243. var dwdAffected = await _db.Ado.ExecuteCommandAsync(@"
  244. INSERT INTO dwd_t8_finished_warehouse_efficiency
  245. (tenant_id, factory_id, biz_month, source_ztid, period_start, period_end,
  246. shipment_qty, warehouse_headcount, efficiency, denominator_status, batch_id, create_time)
  247. VALUES
  248. (@TenantId, 1, @bizMonth, @ztid, @periodStart, @periodEnd,
  249. @shipmentQty, @headcount, @efficiency, @denomStatus, @batchId, @now)
  250. ON DUPLICATE KEY UPDATE
  251. period_start=VALUES(period_start), period_end=VALUES(period_end),
  252. shipment_qty=VALUES(shipment_qty), warehouse_headcount=VALUES(warehouse_headcount),
  253. efficiency=VALUES(efficiency), denominator_status=VALUES(denominator_status),
  254. batch_id=VALUES(batch_id), update_time=@now",
  255. new SugarParameter("@TenantId", option.TenantId),
  256. new SugarParameter("@bizMonth", option.BizMonth),
  257. new SugarParameter("@ztid", option.SourceZtid),
  258. new SugarParameter("@periodStart", option.MonthlyPeriodStart),
  259. new SugarParameter("@periodEnd", option.MonthlyPeriodEnd),
  260. new SugarParameter("@shipmentQty", shipmentQty),
  261. new SugarParameter("@headcount", headcount),
  262. new SugarParameter("@efficiency", efficiency),
  263. new SugarParameter("@denomStatus", denomStatus),
  264. new SugarParameter("@batchId", batchId),
  265. new SugarParameter("@now", now));
  266. sub.DwdRows = dwdAffected;
  267. sub.KpiRows = await UpsertKpiValueAsync("S7_L1_003", option.TenantId, option.MonthlyPeriodEnd, efficiency, now);
  268. return sub;
  269. }
  270. // ─────────────────────────────────────────────────────────────────────────
  271. private async Task<List<T>> QueryT8Async<T>(string sql, SugarParameter[] parameters)
  272. {
  273. var t8 = _db.AsTenant().GetConnectionScope(T8ConfigId);
  274. return await t8.Ado.SqlQueryAsync<T>(sql, parameters);
  275. }
  276. private async Task<int> UpsertKpiValueAsync(string metricCode, long tenantId, DateTime bizDate, decimal? metricValue, DateTime now)
  277. {
  278. // 沿用 S3 UpsertS3KpiValueAsync 范式:先查现存行 → UPDATE;不存在 → SELECT MAX(id)+1 显式生成 id 后 INSERT。
  279. // ado_s9_kpi_value_l1_day.id 为手工分配主键(无 AUTO_INCREMENT),必须显式 set;
  280. // metric_value 允许 NULL(分母缺失不得伪装真实 0)。
  281. // FIX-2:截断时分秒(月度 KPI 入参可能为 YYYY-MM-DD 23:59:59),保证 SELECT WHERE biz_date=@BizDate 与 DB date 列匹配,避免重复 INSERT。
  282. bizDate = bizDate.Date;
  283. var existingId = await _db.Ado.GetLongAsync(
  284. "SELECT IFNULL((SELECT id FROM ado_s9_kpi_value_l1_day WHERE tenant_id=@TenantId AND factory_id=1 " +
  285. "AND module_code=@ModuleCode AND metric_code=@MetricCode AND biz_date=@BizDate AND is_deleted=0 " +
  286. "ORDER BY id LIMIT 1), 0)",
  287. new List<SugarParameter>
  288. {
  289. new("@TenantId", tenantId),
  290. new("@ModuleCode", ModuleCode),
  291. new("@MetricCode", metricCode),
  292. new("@BizDate", bizDate)
  293. });
  294. if (existingId > 0)
  295. {
  296. return await _db.Ado.ExecuteCommandAsync(
  297. "UPDATE ado_s9_kpi_value_l1_day SET metric_value=@MetricValue, calc_time=@Now, " +
  298. "update_time=@Now, is_deleted=0, is_active=1 WHERE id=@Id",
  299. new SugarParameter("@MetricValue", metricValue),
  300. new SugarParameter("@Now", now),
  301. new SugarParameter("@Id", existingId));
  302. }
  303. var nextId = await _db.Ado.GetLongAsync(
  304. "SELECT COALESCE(MAX(id), 0) + 1 FROM ado_s9_kpi_value_l1_day");
  305. return await _db.Ado.ExecuteCommandAsync(@"
  306. INSERT INTO ado_s9_kpi_value_l1_day
  307. (id, tenant_id, org_id, company_id, factory_id, status, biz_date,
  308. create_time, update_time, is_deleted, is_active,
  309. module_code, metric_code, metric_value, calc_time)
  310. VALUES
  311. (@Id, @TenantId, NULL, NULL, 1, NULL, @BizDate,
  312. @Now, @Now, 0, 1,
  313. @ModuleCode, @MetricCode, @MetricValue, @Now)",
  314. new SugarParameter("@Id", nextId),
  315. new SugarParameter("@TenantId", tenantId),
  316. new SugarParameter("@BizDate", bizDate),
  317. new SugarParameter("@Now", now),
  318. new SugarParameter("@ModuleCode", ModuleCode),
  319. new SugarParameter("@MetricCode", metricCode),
  320. new SugarParameter("@MetricValue", metricValue));
  321. }
  322. private async Task<long> InsertTransformRunLogAsync(string batchId, DateTime startedAt, string triggerType, long tenantId)
  323. {
  324. await _db.Ado.ExecuteCommandAsync(@"
  325. INSERT INTO mdp_transform_run_log
  326. (tenant_id, job_code, job_name, trigger_type, batch_id, status, start_time, stage_rows, standard_rows, dwd_rows, create_time, update_time)
  327. VALUES
  328. (@TenantId, @JobCode, @JobName, @TriggerType, @BatchId, 'RUNNING', @StartTime, 0, 0, 0, @StartTime, @StartTime)",
  329. new SugarParameter("@TenantId", tenantId),
  330. new SugarParameter("@JobCode", JobCode),
  331. new SugarParameter("@JobName", JobName),
  332. new SugarParameter("@TriggerType", triggerType),
  333. new SugarParameter("@BatchId", batchId),
  334. new SugarParameter("@StartTime", startedAt));
  335. return await _db.Ado.GetLongAsync(
  336. "SELECT id FROM mdp_transform_run_log WHERE batch_id=@BatchId ORDER BY id DESC LIMIT 1",
  337. new List<SugarParameter> { new("@BatchId", batchId) });
  338. }
  339. private async Task MarkTransformRunSuccessAsync(long runLogId, DateTime startedAt, S7MdpSyncTransformResult result)
  340. {
  341. var finishedAt = DateTime.Now;
  342. await _db.Ado.ExecuteCommandAsync(@"
  343. UPDATE mdp_transform_run_log
  344. SET status='SUCCESS', end_time=@EndTime, duration_ms=@DurationMs,
  345. stage_rows=@StageRows, standard_rows=@StandardRows, dwd_rows=@DwdRows,
  346. summary_json=@SummaryJson, update_time=CURRENT_TIMESTAMP
  347. WHERE id=@Id",
  348. new SugarParameter("@EndTime", finishedAt),
  349. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  350. new SugarParameter("@StageRows", result.StageRows),
  351. new SugarParameter("@StandardRows", result.StandardRows),
  352. new SugarParameter("@DwdRows", result.DwdRows),
  353. new SugarParameter("@SummaryJson", JsonSerializer.Serialize(new
  354. {
  355. batchId = result.BatchId,
  356. sourceZtid = result.SourceZtid,
  357. bizDate = result.BizDate.ToString("yyyy-MM-dd"),
  358. bizMonth = result.BizMonth,
  359. dwdRows = result.DwdRows,
  360. kpiRows = result.KpiRows,
  361. perKpiDwdRows = result.PerKpiDwdRows,
  362. perKpiKpiRows = result.PerKpiKpiRows,
  363. denominatorStatus = result.KpiDenominatorStatus
  364. })),
  365. new SugarParameter("@Id", runLogId));
  366. }
  367. private async Task MarkTransformRunFailedAsync(long runLogId, DateTime startedAt, string message, string batchId)
  368. {
  369. bool runLogUpdated = false;
  370. try
  371. {
  372. var finishedAt = DateTime.Now;
  373. await _db.Ado.ExecuteCommandAsync(@"
  374. UPDATE mdp_transform_run_log
  375. SET status='FAILED', end_time=@EndTime, duration_ms=@DurationMs,
  376. error_message=@ErrorMessage, update_time=CURRENT_TIMESTAMP
  377. WHERE id=@Id",
  378. new SugarParameter("@EndTime", finishedAt),
  379. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  380. new SugarParameter("@ErrorMessage", Truncate(message, 2000)),
  381. new SugarParameter("@Id", runLogId));
  382. runLogUpdated = true;
  383. }
  384. catch (Exception ex)
  385. {
  386. Console.Error.WriteLine($"[S7MdpSyncTransform] MarkTransformRunFailed write failed (runLogId={runLogId}): {ex.Message}");
  387. }
  388. // FAILURE-NOTIFICATION-1:写库 FAILED 成功后发通知给超级管理员;通知失败不影响主流程
  389. if (!runLogUpdated) return;
  390. try
  391. {
  392. await _sysNoticeService.AddNotice(new AddNoticeInput
  393. {
  394. Title = "S7 成品仓储 T8 KPI 跑批失败",
  395. Content = $"模块:S7 成品仓储\n批次ID:{batchId}\n失败时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}\n错误信息:{Truncate(message, 1000)}\n\n请查看 mdp_transform_run_log 获取完整错误与重试记录。",
  396. Type = NoticeTypeEnum.NOTICE,
  397. PublicTime = DateTime.Now,
  398. Status = NoticeStatusEnum.PUBLIC,
  399. PublicUserId = NoticeReceiverUserId,
  400. PublicUserName = NoticeReceiverUserName
  401. });
  402. }
  403. catch (Exception notifyEx)
  404. {
  405. _logger.LogError(notifyEx, "[S7MdpSyncTransform] SysNotice 发送失败 (runLogId={RunLogId}, batchId={BatchId})", runLogId, batchId);
  406. }
  407. }
  408. private static string NormalizeTriggerType(string s) =>
  409. string.IsNullOrWhiteSpace(s) ? "AUTO" : s.Trim().ToUpperInvariant();
  410. private static string Truncate(string s, int max) =>
  411. string.IsNullOrEmpty(s) ? "" : (s.Length <= max ? s : s.Substring(0, max));
  412. }
  413. // DTO ────────────────────────────────────────────────────────────────────────
  414. public sealed class S7MdpRefreshOption
  415. {
  416. public string SourceZtid { get; set; } = "pbxfxp";
  417. /// <summary>KPI 落库目标租户;0=由 SourceZtid 经 AidopSourceTenantMap 解析(禁止写死固定租户)。</summary>
  418. public long TenantId { get; set; }
  419. public DateTime BizDate { get; set; }
  420. public string BizMonth { get; set; } = "";
  421. public DateTime MonthlyPeriodStart { get; set; }
  422. public DateTime MonthlyPeriodEnd { get; set; }
  423. public static S7MdpRefreshOption Default()
  424. {
  425. var today = DateTime.Today;
  426. var yesterday = today.AddDays(-1);
  427. var lastMonth = today.AddMonths(-1);
  428. var monthStart = new DateTime(lastMonth.Year, lastMonth.Month, 1);
  429. var monthEnd = monthStart.AddMonths(1).AddDays(-1);
  430. return new S7MdpRefreshOption
  431. {
  432. SourceZtid = "pbxfxp",
  433. BizDate = yesterday,
  434. BizMonth = lastMonth.ToString("yyyy-MM"),
  435. MonthlyPeriodStart = monthStart,
  436. MonthlyPeriodEnd = monthEnd.AddDays(1).AddSeconds(-1)
  437. };
  438. }
  439. }
  440. public sealed class S7MdpSyncTransformResult
  441. {
  442. public string BatchId { get; set; } = "";
  443. public long RunLogId { get; set; }
  444. public string TriggerType { get; set; } = "AUTO";
  445. public string SourceZtid { get; set; } = "";
  446. public DateTime BizDate { get; set; }
  447. public string BizMonth { get; set; } = "";
  448. public DateTime MonthlyPeriodStart { get; set; }
  449. public DateTime MonthlyPeriodEnd { get; set; }
  450. public int StageRows { get; set; }
  451. public int StandardRows { get; set; }
  452. public int DwdRows { get; set; }
  453. public int KpiRows { get; set; }
  454. public Dictionary<string, int> PerKpiDwdRows { get; } = new();
  455. public Dictionary<string, int> PerKpiKpiRows { get; } = new();
  456. public List<string> KpiDenominatorStatus { get; } = new();
  457. public void MergeSub(string kpiCode, KpiBuildSubResult sub)
  458. {
  459. PerKpiDwdRows[kpiCode] = sub.DwdRows;
  460. PerKpiKpiRows[kpiCode] = sub.KpiRows;
  461. DwdRows += sub.DwdRows;
  462. KpiRows += sub.KpiRows;
  463. KpiDenominatorStatus.Add($"{kpiCode}:{sub.DenominatorStatus}");
  464. }
  465. }
  466. public sealed class KpiBuildSubResult
  467. {
  468. public int T8Rows { get; set; }
  469. public int DwdRows { get; set; }
  470. public int KpiRows { get; set; }
  471. public string DenominatorStatus { get; set; } = "OK";
  472. }
  473. // T8 result set 投影类型 ──────────────────────────────────────────────────────
  474. internal sealed class S7CycleRow
  475. {
  476. public string? noid { get; set; }
  477. public int? scts { get; set; }
  478. }
  479. internal sealed class S7FulfillmentRow
  480. {
  481. public string? noid { get; set; }
  482. public int total_rows { get; set; }
  483. public int in_window_rows { get; set; }
  484. }
  485. internal sealed class S7ShipmentDetailRow
  486. {
  487. public string? lynoid { get; set; }
  488. public string? code { get; set; }
  489. public string? shtime { get; set; }
  490. public decimal? slzx { get; set; }
  491. }
  492. internal sealed class S7PeNumRow
  493. {
  494. public int penum { get; set; }
  495. }