S7MdpSyncTransformService.cs 26 KB

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