S6MdpSyncTransformService.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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.Manufacturing;
  6. /// <summary>
  7. /// S6 生产执行 — KPI 计算与刷新转换服务。
  8. /// 双模式:读本地标准层 mdp_std_t8_kc_*(由 T8BaseInboundMdpSyncService 从 T8 贴源→标准),不再直连 T8。
  9. /// 计算逻辑沿用方老师 v5.4 KPI J 列口径(等价改写为 MySQL 读 std)。
  10. /// 口径归位(S6-L1-KPI-CONTRACT-RESOLUTION-1,方案 B):L1=订单级(待 Phase 2 实现),
  11. /// L2=工单级——本服务产出 **工单** 指标写 L2:
  12. /// 工单制造满足率→S6_L2_002(l2_day),工单制造人效→S6_L2_003(l2_day);不再写 S6_L1_001/002。
  13. /// 最终聚合经 KpiCalcDispatcher(LEGACY_CODE/CONFIG_SQL),数据准备(dwd)不变。
  14. /// </summary>
  15. public class S6MdpSyncTransformService : ITransient
  16. {
  17. private readonly ISqlSugarClient _db;
  18. private readonly SysNoticeService _sysNoticeService;
  19. private readonly ILogger<S6MdpSyncTransformService> _logger;
  20. private readonly SmartOps.KpiCalcDispatcher _kpiCalcDispatcher;
  21. private readonly SmartOps.KpiDimensionRunService _dimensionRun;
  22. private const string L2ValueTable = "ado_s9_kpi_value_l2_day";
  23. private const string JobCode = "S6_MDP_SYNC_TRANSFORM";
  24. private const string JobName = "S6 生产执行 MDP 同步与转换";
  25. private const string ModuleCode = "S6";
  26. // FAILURE-NOTIFICATION-1:超级管理员 superAdmin.NET(AccountType=999)
  27. private const long NoticeReceiverUserId = 1300000000101L;
  28. private const string NoticeReceiverUserName = "超级管理员";
  29. public S6MdpSyncTransformService(
  30. ISqlSugarClient db,
  31. SysNoticeService sysNoticeService,
  32. ILogger<S6MdpSyncTransformService> logger,
  33. SmartOps.KpiCalcDispatcher kpiCalcDispatcher,
  34. SmartOps.KpiDimensionRunService dimensionRun)
  35. {
  36. _db = db;
  37. _sysNoticeService = sysNoticeService;
  38. _logger = logger;
  39. _kpiCalcDispatcher = kpiCalcDispatcher;
  40. _dimensionRun = dimensionRun;
  41. }
  42. public async Task<S6MdpSyncTransformResult> RunFullAsync(
  43. CancellationToken cancellationToken = default,
  44. string triggerType = "AUTO",
  45. S6MdpRefreshOption? option = null)
  46. {
  47. cancellationToken.ThrowIfCancellationRequested();
  48. option ??= S6MdpRefreshOption.Default();
  49. NormalizeOption(option);
  50. var now = DateTime.Now;
  51. var batchId = $"S6_MDP_FULL_{now:yyyyMMddHHmmss}";
  52. var normalizedTrigger = NormalizeTriggerType(triggerType);
  53. var runLogId = await InsertTransformRunLogAsync(batchId, now, normalizedTrigger, option);
  54. var result = new S6MdpSyncTransformResult
  55. {
  56. BatchId = batchId,
  57. RunLogId = runLogId,
  58. TriggerType = normalizedTrigger,
  59. SourceZtid = option.SourceZtid,
  60. TargetTenantId = option.TargetTenantId,
  61. TargetFactoryId = option.TargetFactoryId,
  62. BizDate = option.BizDate,
  63. BizMonth = option.BizMonth,
  64. MonthlyPeriodStart = option.MonthlyPeriodStart,
  65. MonthlyPeriodEnd = option.MonthlyPeriodEnd
  66. };
  67. try
  68. {
  69. result.StageRows = 0;
  70. result.StandardRows = 0;
  71. // 口径归位:工单指标写 L2(S6_L2_002 满足率 / S6_L2_003 人效);L1 订单级待 Phase 2。
  72. var sub22 = await BuildS6L2002WorkOrderMfgFulfillmentAsync(batchId, now, option, normalizedTrigger, cancellationToken);
  73. result.MergeSub("S6_L2_002", sub22);
  74. var sub23 = await BuildS6L2003WorkOrderMfgEfficiencyAsync(batchId, now, option, normalizedTrigger, cancellationToken);
  75. result.MergeSub("S6_L2_003", sub23);
  76. await MarkTransformRunSuccessAsync(runLogId, now, result);
  77. return result;
  78. }
  79. catch (Exception ex)
  80. {
  81. await MarkTransformRunFailedAsync(runLogId, now, ex.Message, batchId);
  82. throw;
  83. }
  84. }
  85. // ─────────────────────────────────────────────────────────────────────────
  86. /// <summary>工单制造满足率 = 计划完工时间内累计报工 / 工单计划生产数量。归位 L2:写 S6_L2_002。</summary>
  87. private async Task<KpiBuildSubResult> BuildS6L2002WorkOrderMfgFulfillmentAsync(
  88. string batchId, DateTime now, S6MdpRefreshOption option, string triggerType, CancellationToken ct)
  89. {
  90. var sub = new KpiBuildSubResult();
  91. // 双模式:读本地标准层 mdp_std_t8_*(源 identity Id→src_id),语义等价于原直发 T8 SQL。
  92. const string sql = @"
  93. select a.noid as noid, b.rwnoid as rwnoid, b.code as code, b.sl as sl, sum(d.slzx) as slzx
  94. from mdp_std_t8_kc_dd_head a
  95. left join mdp_std_t8_kc_dd_list b on a.src_id=b.idid
  96. left join (
  97. select b.lynoid as lynoid, b.code as code,
  98. date(a.shtime) as shtime, b.slzx as slzx
  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. ) d on b.rwnoid=d.lynoid and b.code=d.code
  103. where a.ztid=@ztid and a.lbs='生产任务' and a.zf=0 and a.shyn=1 and d.shtime<=b.jhdate
  104. group by a.noid, b.rwnoid, b.code, b.sl";
  105. var rows = await _db.Ado.SqlQueryAsync<S6MfgFulfillmentRow>(sql, new[] { new SugarParameter("@ztid", option.SourceZtid) });
  106. sub.T8Rows = rows.Count;
  107. var dwdAffected = 0;
  108. var rateList = new List<decimal>();
  109. foreach (var r in rows)
  110. {
  111. ct.ThrowIfCancellationRequested();
  112. if (string.IsNullOrEmpty(r.noid)) continue;
  113. decimal? rate = (r.sl.HasValue && r.sl.Value > 0m && r.slzx.HasValue)
  114. ? Math.Round(r.slzx.Value / r.sl.Value, 4)
  115. : null;
  116. if (rate.HasValue) rateList.Add(rate.Value);
  117. dwdAffected += await _db.Ado.ExecuteCommandAsync(@"
  118. INSERT INTO dwd_t8_work_order_mfg_fulfillment
  119. (tenant_id, factory_id, biz_date, source_ztid, order_no, task_no, item_code,
  120. plan_qty, done_qty_in_window, fulfillment_rate, batch_id, create_time)
  121. VALUES
  122. (@tenantId, @factoryId, @bizDate, @ztid, @orderNo, @taskNo, @itemCode,
  123. @planQty, @doneQty, @rate, @batchId, @now)
  124. ON DUPLICATE KEY UPDATE
  125. plan_qty=VALUES(plan_qty), done_qty_in_window=VALUES(done_qty_in_window),
  126. fulfillment_rate=VALUES(fulfillment_rate),
  127. batch_id=VALUES(batch_id), update_time=@now",
  128. new SugarParameter("@tenantId", option.TargetTenantId),
  129. new SugarParameter("@factoryId", option.TargetFactoryId),
  130. new SugarParameter("@bizDate", option.BizDate),
  131. new SugarParameter("@ztid", option.SourceZtid),
  132. new SugarParameter("@orderNo", r.noid),
  133. new SugarParameter("@taskNo", r.rwnoid ?? ""),
  134. new SugarParameter("@itemCode", r.code ?? ""),
  135. new SugarParameter("@planQty", r.sl),
  136. new SugarParameter("@doneQty", r.slzx),
  137. new SugarParameter("@rate", rate),
  138. new SugarParameter("@batchId", batchId),
  139. new SugarParameter("@now", now));
  140. }
  141. sub.DwdRows = dwdAffected;
  142. // 数据准备(dwd)已完成。最终聚合交分发器(日 KPI:period 复用 BizDate,SQL 按 biz_date 圈选)。
  143. decimal? legacyValue = rateList.Count > 0
  144. ? Math.Round(rateList.Average() * 100m, 4) // 百分号
  145. : null;
  146. var legacyDenom = rateList.Count > 0 ? "OK" : "NO_VALID_WORK_ORDER";
  147. var dispatch = await _kpiCalcDispatcher.DispatchAsync(
  148. "S6_L2_002", ModuleCode, option.TargetTenantId, option.TargetFactoryId,
  149. option.BizDate, option.BizDate, option.BizDate, option.SourceZtid,
  150. batchId, triggerType, legacyValue, legacyDenom, ct);
  151. sub.KpiRows = dispatch.ShouldUpsert
  152. ? await UpsertKpiValueAsync("S6_L2_002", option.BizDate, dispatch.MetricValue, now, option, L2ValueTable)
  153. : 0;
  154. sub.DenominatorStatus = dispatch.DenominatorStatus;
  155. // 调度:SUMMARY 成功/NO_DATA 后触发对应 DIMENSION 跑批(共享 BatchId;SUMMARY FAILED 不触发)。
  156. if (dispatch.ShouldUpsert)
  157. {
  158. try
  159. {
  160. await _dimensionRun.RunDimensionAsync(
  161. "S6_L2_002", ModuleCode, option.TargetTenantId, option.BizDate, batchId, triggerType, ct);
  162. }
  163. catch (Exception ex)
  164. {
  165. _logger.LogWarning(ex, "S6_L2_002 维度跑批异常(不影响汇总链路)");
  166. }
  167. }
  168. return sub;
  169. }
  170. /// <summary>工单制造人效 = 完成制造工单数(lbs=生产入库 AND (slzx>=sl OR gdyn=1)) / count(gw=生产)。归位 L2:写 S6_L2_003。</summary>
  171. private async Task<KpiBuildSubResult> BuildS6L2003WorkOrderMfgEfficiencyAsync(
  172. string batchId, DateTime now, S6MdpRefreshOption option, string triggerType, CancellationToken ct)
  173. {
  174. var sub = new KpiBuildSubResult();
  175. const string sqlNumer = @"
  176. select count(*) as ddnum
  177. from mdp_std_t8_kc_tz_head a
  178. inner join mdp_std_t8_kc_tz_list b on a.src_id=b.idid
  179. where a.ztid=@ztid and a.lbs='生产入库' and a.hzyn=0 and a.zfyn=0 and a.shyn=1
  180. and a.date0 between @startDate and @endDate
  181. and b.slzx>0 and (b.slzx>=b.sl or b.gdyn=1)";
  182. const string sqlDenom = @"
  183. select count(*) as penum
  184. from mdp_std_t8_sys_pelist
  185. where ztid=@ztid and zzzt='在职' and gw='生产'";
  186. var pNumer = new[]
  187. {
  188. new SugarParameter("@ztid", option.SourceZtid),
  189. new SugarParameter("@startDate", option.MonthlyPeriodStart),
  190. new SugarParameter("@endDate", option.MonthlyPeriodEnd)
  191. };
  192. var pDenom = new[] { new SugarParameter("@ztid", option.SourceZtid) };
  193. var numerRows = await _db.Ado.SqlQueryAsync<S6CountRow>(sqlNumer, pNumer);
  194. var denomRows = await _db.Ado.SqlQueryAsync<S6PeNumRow>(sqlDenom, pDenom);
  195. sub.T8Rows = numerRows.Count + denomRows.Count;
  196. int? doneCount = numerRows.FirstOrDefault()?.ddnum;
  197. int? headcount = denomRows.FirstOrDefault()?.penum;
  198. decimal? efficiency = null;
  199. string denomStatus;
  200. if (!headcount.HasValue || headcount.Value <= 0)
  201. denomStatus = "NO_HEADCOUNT";
  202. else if (!doneCount.HasValue)
  203. denomStatus = "NO_NUMERATOR";
  204. else
  205. {
  206. efficiency = Math.Round((decimal)doneCount.Value / headcount.Value, 4);
  207. denomStatus = "OK";
  208. }
  209. sub.DenominatorStatus = denomStatus;
  210. var dwdAffected = await _db.Ado.ExecuteCommandAsync(@"
  211. INSERT INTO dwd_t8_work_order_mfg_efficiency
  212. (tenant_id, factory_id, biz_month, source_ztid, period_start, period_end,
  213. done_count, production_headcount, efficiency, denominator_status, batch_id, create_time)
  214. VALUES
  215. (@tenantId, @factoryId, @bizMonth, @ztid, @periodStart, @periodEnd,
  216. @doneCount, @headcount, @efficiency, @denomStatus, @batchId, @now)
  217. ON DUPLICATE KEY UPDATE
  218. period_start=VALUES(period_start), period_end=VALUES(period_end),
  219. done_count=VALUES(done_count), production_headcount=VALUES(production_headcount),
  220. efficiency=VALUES(efficiency), denominator_status=VALUES(denominator_status),
  221. batch_id=VALUES(batch_id), update_time=@now",
  222. new SugarParameter("@tenantId", option.TargetTenantId),
  223. new SugarParameter("@factoryId", option.TargetFactoryId),
  224. new SugarParameter("@bizMonth", option.BizMonth),
  225. new SugarParameter("@ztid", option.SourceZtid),
  226. new SugarParameter("@periodStart", option.MonthlyPeriodStart),
  227. new SugarParameter("@periodEnd", option.MonthlyPeriodEnd),
  228. new SugarParameter("@doneCount", doneCount),
  229. new SugarParameter("@headcount", headcount),
  230. new SugarParameter("@efficiency", efficiency),
  231. new SugarParameter("@denomStatus", denomStatus),
  232. new SugarParameter("@batchId", batchId),
  233. new SugarParameter("@now", now));
  234. sub.DwdRows = dwdAffected;
  235. // 月度 KPI 最终聚合交分发器;bizDate=月末、period=当月窗口;legacyValue=efficiency、legacyDenom 保留 NO_HEADCOUNT/NO_NUMERATOR。
  236. var dispatch = await _kpiCalcDispatcher.DispatchAsync(
  237. "S6_L2_003", ModuleCode, option.TargetTenantId, option.TargetFactoryId,
  238. option.MonthlyPeriodEnd, option.MonthlyPeriodStart, option.MonthlyPeriodEnd, option.SourceZtid,
  239. batchId, triggerType, efficiency, denomStatus, ct);
  240. sub.KpiRows = dispatch.ShouldUpsert
  241. ? await UpsertKpiValueAsync("S6_L2_003", option.MonthlyPeriodEnd, dispatch.MetricValue, now, option, L2ValueTable)
  242. : 0;
  243. sub.DenominatorStatus = dispatch.DenominatorStatus;
  244. // 调度:SUMMARY 成功/NO_DATA 后触发人效月度 DIMENSION 跑批(月度:@biz_date=月末派生 biz_month)。
  245. if (dispatch.ShouldUpsert)
  246. {
  247. try
  248. {
  249. await _dimensionRun.RunDimensionAsync(
  250. "S6_L2_003", ModuleCode, option.TargetTenantId, option.MonthlyPeriodEnd, batchId, triggerType, ct);
  251. }
  252. catch (Exception ex)
  253. {
  254. _logger.LogWarning(ex, "S6_L2_003 维度跑批异常(不影响汇总链路)");
  255. }
  256. }
  257. return sub;
  258. }
  259. // ─────────────────────────────────────────────────────────────────────────
  260. private async Task<int> UpsertKpiValueAsync(string metricCode, DateTime bizDate, decimal? metricValue, DateTime now, S6MdpRefreshOption option, string valueTable = "ado_s9_kpi_value_l1_day")
  261. {
  262. // 沿用 S3 UpsertS3KpiValueAsync 范式:先查现存行 → UPDATE;不存在 → SELECT MAX(id)+1 显式生成 id 后 INSERT。
  263. // 值表 id 为手工分配主键(无 AUTO_INCREMENT),必须显式 set;metric_value 允许 NULL(分母缺失不得伪装真实 0)。
  264. // valueTable:L1 KPI 写 ado_s9_kpi_value_l1_day;L2(本服务工单指标 S6_L2_002/003)写 ado_s9_kpi_value_l2_day。
  265. // 表名为受控常量(非用户输入),可安全内插;各表 id 序列独立,MAX(id) 取目标表。
  266. // FIX-2:截断时分秒(月度 KPI 入参可能为 YYYY-MM-DD 23:59:59),保证 SELECT WHERE biz_date=@BizDate 与 DB date 列匹配。
  267. bizDate = bizDate.Date;
  268. var existingId = await _db.Ado.GetLongAsync(
  269. $"SELECT IFNULL((SELECT id FROM {valueTable} WHERE tenant_id=@TenantId AND factory_id=@FactoryId " +
  270. "AND module_code=@ModuleCode AND metric_code=@MetricCode AND biz_date=@BizDate AND is_deleted=0 " +
  271. "ORDER BY id LIMIT 1), 0)",
  272. new List<SugarParameter>
  273. {
  274. new("@TenantId", option.TargetTenantId),
  275. new("@FactoryId", option.TargetFactoryId),
  276. new("@ModuleCode", ModuleCode),
  277. new("@MetricCode", metricCode),
  278. new("@BizDate", bizDate)
  279. });
  280. if (existingId > 0)
  281. {
  282. return await _db.Ado.ExecuteCommandAsync(
  283. $"UPDATE {valueTable} SET metric_value=@MetricValue, calc_time=@Now, " +
  284. "update_time=@Now, is_deleted=0, is_active=1 WHERE id=@Id",
  285. new SugarParameter("@MetricValue", metricValue),
  286. new SugarParameter("@Now", now),
  287. new SugarParameter("@Id", existingId));
  288. }
  289. var nextId = await _db.Ado.GetLongAsync(
  290. $"SELECT COALESCE(MAX(id), 0) + 1 FROM {valueTable}");
  291. return await _db.Ado.ExecuteCommandAsync($@"
  292. INSERT INTO {valueTable}
  293. (id, tenant_id, org_id, company_id, factory_id, status, biz_date,
  294. create_time, update_time, is_deleted, is_active,
  295. module_code, metric_code, metric_value, calc_time)
  296. VALUES
  297. (@Id, @TenantId, NULL, NULL, @FactoryId, NULL, @BizDate,
  298. @Now, @Now, 0, 1,
  299. @ModuleCode, @MetricCode, @MetricValue, @Now)",
  300. new SugarParameter("@Id", nextId),
  301. new SugarParameter("@TenantId", option.TargetTenantId),
  302. new SugarParameter("@FactoryId", option.TargetFactoryId),
  303. new SugarParameter("@BizDate", bizDate),
  304. new SugarParameter("@Now", now),
  305. new SugarParameter("@ModuleCode", ModuleCode),
  306. new SugarParameter("@MetricCode", metricCode),
  307. new SugarParameter("@MetricValue", metricValue));
  308. }
  309. private async Task<long> InsertTransformRunLogAsync(string batchId, DateTime startedAt, string triggerType, S6MdpRefreshOption option)
  310. {
  311. await _db.Ado.ExecuteCommandAsync(@"
  312. INSERT INTO mdp_transform_run_log
  313. (tenant_id, job_code, job_name, trigger_type, batch_id, status, start_time, stage_rows, standard_rows, dwd_rows, create_time, update_time)
  314. VALUES
  315. (@TenantId, @JobCode, @JobName, @TriggerType, @BatchId, 'RUNNING', @StartTime, 0, 0, 0, @StartTime, @StartTime)",
  316. new SugarParameter("@TenantId", option.TargetTenantId),
  317. new SugarParameter("@JobCode", JobCode),
  318. new SugarParameter("@JobName", JobName),
  319. new SugarParameter("@TriggerType", triggerType),
  320. new SugarParameter("@BatchId", batchId),
  321. new SugarParameter("@StartTime", startedAt));
  322. return await _db.Ado.GetLongAsync(
  323. "SELECT id FROM mdp_transform_run_log WHERE batch_id=@BatchId ORDER BY id DESC LIMIT 1",
  324. new List<SugarParameter> { new("@BatchId", batchId) });
  325. }
  326. private async Task MarkTransformRunSuccessAsync(long runLogId, DateTime startedAt, S6MdpSyncTransformResult result)
  327. {
  328. var finishedAt = DateTime.Now;
  329. await _db.Ado.ExecuteCommandAsync(@"
  330. UPDATE mdp_transform_run_log
  331. SET status='SUCCESS', end_time=@EndTime, duration_ms=@DurationMs,
  332. stage_rows=@StageRows, standard_rows=@StandardRows, dwd_rows=@DwdRows,
  333. summary_json=@SummaryJson, update_time=CURRENT_TIMESTAMP
  334. WHERE id=@Id",
  335. new SugarParameter("@EndTime", finishedAt),
  336. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  337. new SugarParameter("@StageRows", result.StageRows),
  338. new SugarParameter("@StandardRows", result.StandardRows),
  339. new SugarParameter("@DwdRows", result.DwdRows),
  340. new SugarParameter("@SummaryJson", JsonSerializer.Serialize(new
  341. {
  342. batchId = result.BatchId,
  343. sourceZtid = result.SourceZtid,
  344. bizDate = result.BizDate.ToString("yyyy-MM-dd"),
  345. bizMonth = result.BizMonth,
  346. dwdRows = result.DwdRows,
  347. kpiRows = result.KpiRows,
  348. perKpiDwdRows = result.PerKpiDwdRows,
  349. perKpiKpiRows = result.PerKpiKpiRows,
  350. denominatorStatus = result.KpiDenominatorStatus
  351. })),
  352. new SugarParameter("@Id", runLogId));
  353. }
  354. private async Task MarkTransformRunFailedAsync(long runLogId, DateTime startedAt, string message, string batchId)
  355. {
  356. bool runLogUpdated = false;
  357. try
  358. {
  359. var finishedAt = DateTime.Now;
  360. await _db.Ado.ExecuteCommandAsync(@"
  361. UPDATE mdp_transform_run_log
  362. SET status='FAILED', end_time=@EndTime, duration_ms=@DurationMs,
  363. error_message=@ErrorMessage, update_time=CURRENT_TIMESTAMP
  364. WHERE id=@Id",
  365. new SugarParameter("@EndTime", finishedAt),
  366. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  367. new SugarParameter("@ErrorMessage", Truncate(message, 2000)),
  368. new SugarParameter("@Id", runLogId));
  369. runLogUpdated = true;
  370. }
  371. catch (Exception ex)
  372. {
  373. Console.Error.WriteLine($"[S6MdpSyncTransform] MarkTransformRunFailed write failed (runLogId={runLogId}): {ex.Message}");
  374. }
  375. // FAILURE-NOTIFICATION-1:写库 FAILED 成功后发通知给超级管理员;通知失败不影响主流程
  376. if (!runLogUpdated) return;
  377. try
  378. {
  379. await _sysNoticeService.AddNotice(new AddNoticeInput
  380. {
  381. Title = "S6 生产执行 T8 KPI 跑批失败",
  382. Content = $"模块:S6 生产执行\n批次ID:{batchId}\n失败时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}\n错误信息:{Truncate(message, 1000)}\n\n请查看 mdp_transform_run_log 获取完整错误与重试记录。",
  383. Type = NoticeTypeEnum.NOTICE,
  384. PublicTime = DateTime.Now,
  385. Status = NoticeStatusEnum.PUBLIC,
  386. PublicUserId = NoticeReceiverUserId,
  387. PublicUserName = NoticeReceiverUserName
  388. });
  389. }
  390. catch (Exception notifyEx)
  391. {
  392. _logger.LogError(notifyEx, "[S6MdpSyncTransform] SysNotice 发送失败 (runLogId={RunLogId}, batchId={BatchId})", runLogId, batchId);
  393. }
  394. }
  395. private static string NormalizeTriggerType(string s) =>
  396. string.IsNullOrWhiteSpace(s) ? "AUTO" : s.Trim().ToUpperInvariant();
  397. private static void NormalizeOption(S6MdpRefreshOption option)
  398. {
  399. var d = S6MdpRefreshOption.Default();
  400. if (option.TargetFactoryId <= 0) option.TargetFactoryId = d.TargetFactoryId;
  401. if (string.IsNullOrWhiteSpace(option.SourceZtid)) option.SourceZtid = d.SourceZtid;
  402. option.TargetTenantId = AidopSourceTenantMap.ResolveTenantId(option.SourceZtid, option.TargetTenantId);
  403. if (option.BizDate == default) option.BizDate = d.BizDate;
  404. if (string.IsNullOrWhiteSpace(option.BizMonth)) option.BizMonth = d.BizMonth;
  405. if (option.MonthlyPeriodStart == default) option.MonthlyPeriodStart = d.MonthlyPeriodStart;
  406. if (option.MonthlyPeriodEnd == default) option.MonthlyPeriodEnd = d.MonthlyPeriodEnd;
  407. }
  408. private static string Truncate(string s, int max) =>
  409. string.IsNullOrEmpty(s) ? "" : (s.Length <= max ? s : s.Substring(0, max));
  410. }
  411. // DTO ────────────────────────────────────────────────────────────────────────
  412. public sealed class S6MdpRefreshOption
  413. {
  414. public string SourceZtid { get; set; } = "pbxfxp";
  415. /// <summary>KPI/DWD 落库目标租户;≤0 时由 <see cref="AidopSourceTenantMap"/> 按 SourceZtid 解析。</summary>
  416. public long TargetTenantId { get; set; }
  417. /// <summary>KPI/DWD 落库目标工厂;默认 1。</summary>
  418. public long TargetFactoryId { get; set; } = 1L;
  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 S6MdpRefreshOption 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 S6MdpRefreshOption
  431. {
  432. SourceZtid = "pbxfxp",
  433. TargetTenantId = 0,
  434. TargetFactoryId = 1L,
  435. BizDate = yesterday,
  436. BizMonth = lastMonth.ToString("yyyy-MM"),
  437. MonthlyPeriodStart = monthStart,
  438. MonthlyPeriodEnd = monthEnd.AddDays(1).AddSeconds(-1)
  439. };
  440. }
  441. }
  442. public sealed class S6MdpSyncTransformResult
  443. {
  444. public string BatchId { get; set; } = "";
  445. public long RunLogId { get; set; }
  446. public string TriggerType { get; set; } = "AUTO";
  447. public string SourceZtid { get; set; } = "";
  448. public long TargetTenantId { get; set; }
  449. public long TargetFactoryId { get; set; }
  450. public DateTime BizDate { get; set; }
  451. public string BizMonth { get; set; } = "";
  452. public DateTime MonthlyPeriodStart { get; set; }
  453. public DateTime MonthlyPeriodEnd { get; set; }
  454. public int StageRows { get; set; }
  455. public int StandardRows { get; set; }
  456. public int DwdRows { get; set; }
  457. public int KpiRows { get; set; }
  458. public Dictionary<string, int> PerKpiDwdRows { get; } = new();
  459. public Dictionary<string, int> PerKpiKpiRows { get; } = new();
  460. public List<string> KpiDenominatorStatus { get; } = new();
  461. public void MergeSub(string kpiCode, KpiBuildSubResult sub)
  462. {
  463. PerKpiDwdRows[kpiCode] = sub.DwdRows;
  464. PerKpiKpiRows[kpiCode] = sub.KpiRows;
  465. DwdRows += sub.DwdRows;
  466. KpiRows += sub.KpiRows;
  467. KpiDenominatorStatus.Add($"{kpiCode}:{sub.DenominatorStatus}");
  468. }
  469. }
  470. public sealed class KpiBuildSubResult
  471. {
  472. public int T8Rows { get; set; }
  473. public int DwdRows { get; set; }
  474. public int KpiRows { get; set; }
  475. public string DenominatorStatus { get; set; } = "OK";
  476. }
  477. // T8 result set 投影类型 ──────────────────────────────────────────────────────
  478. internal sealed class S6MfgFulfillmentRow
  479. {
  480. public string? noid { get; set; }
  481. public string? rwnoid { get; set; }
  482. public string? code { get; set; }
  483. public decimal? sl { get; set; }
  484. public decimal? slzx { get; set; }
  485. }
  486. internal sealed class S6CountRow
  487. {
  488. public int ddnum { get; set; }
  489. }
  490. internal sealed class S6PeNumRow
  491. {
  492. public int penum { get; set; }
  493. }