S6MdpSyncTransformService.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. return sub;
  245. }
  246. // ─────────────────────────────────────────────────────────────────────────
  247. private async Task<int> UpsertKpiValueAsync(string metricCode, DateTime bizDate, decimal? metricValue, DateTime now, S6MdpRefreshOption option, string valueTable = "ado_s9_kpi_value_l1_day")
  248. {
  249. // 沿用 S3 UpsertS3KpiValueAsync 范式:先查现存行 → UPDATE;不存在 → SELECT MAX(id)+1 显式生成 id 后 INSERT。
  250. // 值表 id 为手工分配主键(无 AUTO_INCREMENT),必须显式 set;metric_value 允许 NULL(分母缺失不得伪装真实 0)。
  251. // valueTable:L1 KPI 写 ado_s9_kpi_value_l1_day;L2(本服务工单指标 S6_L2_002/003)写 ado_s9_kpi_value_l2_day。
  252. // 表名为受控常量(非用户输入),可安全内插;各表 id 序列独立,MAX(id) 取目标表。
  253. // FIX-2:截断时分秒(月度 KPI 入参可能为 YYYY-MM-DD 23:59:59),保证 SELECT WHERE biz_date=@BizDate 与 DB date 列匹配。
  254. bizDate = bizDate.Date;
  255. var existingId = await _db.Ado.GetLongAsync(
  256. $"SELECT IFNULL((SELECT id FROM {valueTable} WHERE tenant_id=@TenantId AND factory_id=@FactoryId " +
  257. "AND module_code=@ModuleCode AND metric_code=@MetricCode AND biz_date=@BizDate AND is_deleted=0 " +
  258. "ORDER BY id LIMIT 1), 0)",
  259. new List<SugarParameter>
  260. {
  261. new("@TenantId", option.TargetTenantId),
  262. new("@FactoryId", option.TargetFactoryId),
  263. new("@ModuleCode", ModuleCode),
  264. new("@MetricCode", metricCode),
  265. new("@BizDate", bizDate)
  266. });
  267. if (existingId > 0)
  268. {
  269. return await _db.Ado.ExecuteCommandAsync(
  270. $"UPDATE {valueTable} SET metric_value=@MetricValue, calc_time=@Now, " +
  271. "update_time=@Now, is_deleted=0, is_active=1 WHERE id=@Id",
  272. new SugarParameter("@MetricValue", metricValue),
  273. new SugarParameter("@Now", now),
  274. new SugarParameter("@Id", existingId));
  275. }
  276. var nextId = await _db.Ado.GetLongAsync(
  277. $"SELECT COALESCE(MAX(id), 0) + 1 FROM {valueTable}");
  278. return await _db.Ado.ExecuteCommandAsync($@"
  279. INSERT INTO {valueTable}
  280. (id, tenant_id, org_id, company_id, factory_id, status, biz_date,
  281. create_time, update_time, is_deleted, is_active,
  282. module_code, metric_code, metric_value, calc_time)
  283. VALUES
  284. (@Id, @TenantId, NULL, NULL, @FactoryId, NULL, @BizDate,
  285. @Now, @Now, 0, 1,
  286. @ModuleCode, @MetricCode, @MetricValue, @Now)",
  287. new SugarParameter("@Id", nextId),
  288. new SugarParameter("@TenantId", option.TargetTenantId),
  289. new SugarParameter("@FactoryId", option.TargetFactoryId),
  290. new SugarParameter("@BizDate", bizDate),
  291. new SugarParameter("@Now", now),
  292. new SugarParameter("@ModuleCode", ModuleCode),
  293. new SugarParameter("@MetricCode", metricCode),
  294. new SugarParameter("@MetricValue", metricValue));
  295. }
  296. private async Task<long> InsertTransformRunLogAsync(string batchId, DateTime startedAt, string triggerType, S6MdpRefreshOption option)
  297. {
  298. await _db.Ado.ExecuteCommandAsync(@"
  299. INSERT INTO mdp_transform_run_log
  300. (tenant_id, job_code, job_name, trigger_type, batch_id, status, start_time, stage_rows, standard_rows, dwd_rows, create_time, update_time)
  301. VALUES
  302. (@TenantId, @JobCode, @JobName, @TriggerType, @BatchId, 'RUNNING', @StartTime, 0, 0, 0, @StartTime, @StartTime)",
  303. new SugarParameter("@TenantId", option.TargetTenantId),
  304. new SugarParameter("@JobCode", JobCode),
  305. new SugarParameter("@JobName", JobName),
  306. new SugarParameter("@TriggerType", triggerType),
  307. new SugarParameter("@BatchId", batchId),
  308. new SugarParameter("@StartTime", startedAt));
  309. return await _db.Ado.GetLongAsync(
  310. "SELECT id FROM mdp_transform_run_log WHERE batch_id=@BatchId ORDER BY id DESC LIMIT 1",
  311. new List<SugarParameter> { new("@BatchId", batchId) });
  312. }
  313. private async Task MarkTransformRunSuccessAsync(long runLogId, DateTime startedAt, S6MdpSyncTransformResult result)
  314. {
  315. var finishedAt = DateTime.Now;
  316. await _db.Ado.ExecuteCommandAsync(@"
  317. UPDATE mdp_transform_run_log
  318. SET status='SUCCESS', end_time=@EndTime, duration_ms=@DurationMs,
  319. stage_rows=@StageRows, standard_rows=@StandardRows, dwd_rows=@DwdRows,
  320. summary_json=@SummaryJson, update_time=CURRENT_TIMESTAMP
  321. WHERE id=@Id",
  322. new SugarParameter("@EndTime", finishedAt),
  323. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  324. new SugarParameter("@StageRows", result.StageRows),
  325. new SugarParameter("@StandardRows", result.StandardRows),
  326. new SugarParameter("@DwdRows", result.DwdRows),
  327. new SugarParameter("@SummaryJson", JsonSerializer.Serialize(new
  328. {
  329. batchId = result.BatchId,
  330. sourceZtid = result.SourceZtid,
  331. bizDate = result.BizDate.ToString("yyyy-MM-dd"),
  332. bizMonth = result.BizMonth,
  333. dwdRows = result.DwdRows,
  334. kpiRows = result.KpiRows,
  335. perKpiDwdRows = result.PerKpiDwdRows,
  336. perKpiKpiRows = result.PerKpiKpiRows,
  337. denominatorStatus = result.KpiDenominatorStatus
  338. })),
  339. new SugarParameter("@Id", runLogId));
  340. }
  341. private async Task MarkTransformRunFailedAsync(long runLogId, DateTime startedAt, string message, string batchId)
  342. {
  343. bool runLogUpdated = false;
  344. try
  345. {
  346. var finishedAt = DateTime.Now;
  347. await _db.Ado.ExecuteCommandAsync(@"
  348. UPDATE mdp_transform_run_log
  349. SET status='FAILED', end_time=@EndTime, duration_ms=@DurationMs,
  350. error_message=@ErrorMessage, update_time=CURRENT_TIMESTAMP
  351. WHERE id=@Id",
  352. new SugarParameter("@EndTime", finishedAt),
  353. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  354. new SugarParameter("@ErrorMessage", Truncate(message, 2000)),
  355. new SugarParameter("@Id", runLogId));
  356. runLogUpdated = true;
  357. }
  358. catch (Exception ex)
  359. {
  360. Console.Error.WriteLine($"[S6MdpSyncTransform] MarkTransformRunFailed write failed (runLogId={runLogId}): {ex.Message}");
  361. }
  362. // FAILURE-NOTIFICATION-1:写库 FAILED 成功后发通知给超级管理员;通知失败不影响主流程
  363. if (!runLogUpdated) return;
  364. try
  365. {
  366. await _sysNoticeService.AddNotice(new AddNoticeInput
  367. {
  368. Title = "S6 生产执行 T8 KPI 跑批失败",
  369. Content = $"模块:S6 生产执行\n批次ID:{batchId}\n失败时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}\n错误信息:{Truncate(message, 1000)}\n\n请查看 mdp_transform_run_log 获取完整错误与重试记录。",
  370. Type = NoticeTypeEnum.NOTICE,
  371. PublicTime = DateTime.Now,
  372. Status = NoticeStatusEnum.PUBLIC,
  373. PublicUserId = NoticeReceiverUserId,
  374. PublicUserName = NoticeReceiverUserName
  375. });
  376. }
  377. catch (Exception notifyEx)
  378. {
  379. _logger.LogError(notifyEx, "[S6MdpSyncTransform] SysNotice 发送失败 (runLogId={RunLogId}, batchId={BatchId})", runLogId, batchId);
  380. }
  381. }
  382. private static string NormalizeTriggerType(string s) =>
  383. string.IsNullOrWhiteSpace(s) ? "AUTO" : s.Trim().ToUpperInvariant();
  384. private static void NormalizeOption(S6MdpRefreshOption option)
  385. {
  386. var d = S6MdpRefreshOption.Default();
  387. if (option.TargetFactoryId <= 0) option.TargetFactoryId = d.TargetFactoryId;
  388. if (string.IsNullOrWhiteSpace(option.SourceZtid)) option.SourceZtid = d.SourceZtid;
  389. option.TargetTenantId = AidopSourceTenantMap.ResolveTenantId(option.SourceZtid, option.TargetTenantId);
  390. if (option.BizDate == default) option.BizDate = d.BizDate;
  391. if (string.IsNullOrWhiteSpace(option.BizMonth)) option.BizMonth = d.BizMonth;
  392. if (option.MonthlyPeriodStart == default) option.MonthlyPeriodStart = d.MonthlyPeriodStart;
  393. if (option.MonthlyPeriodEnd == default) option.MonthlyPeriodEnd = d.MonthlyPeriodEnd;
  394. }
  395. private static string Truncate(string s, int max) =>
  396. string.IsNullOrEmpty(s) ? "" : (s.Length <= max ? s : s.Substring(0, max));
  397. }
  398. // DTO ────────────────────────────────────────────────────────────────────────
  399. public sealed class S6MdpRefreshOption
  400. {
  401. public string SourceZtid { get; set; } = "pbxfxp";
  402. /// <summary>KPI/DWD 落库目标租户;≤0 时由 <see cref="AidopSourceTenantMap"/> 按 SourceZtid 解析。</summary>
  403. public long TargetTenantId { get; set; }
  404. /// <summary>KPI/DWD 落库目标工厂;默认 1。</summary>
  405. public long TargetFactoryId { get; set; } = 1L;
  406. public DateTime BizDate { get; set; }
  407. public string BizMonth { get; set; } = "";
  408. public DateTime MonthlyPeriodStart { get; set; }
  409. public DateTime MonthlyPeriodEnd { get; set; }
  410. public static S6MdpRefreshOption Default()
  411. {
  412. var today = DateTime.Today;
  413. var yesterday = today.AddDays(-1);
  414. var lastMonth = today.AddMonths(-1);
  415. var monthStart = new DateTime(lastMonth.Year, lastMonth.Month, 1);
  416. var monthEnd = monthStart.AddMonths(1).AddDays(-1);
  417. return new S6MdpRefreshOption
  418. {
  419. SourceZtid = "pbxfxp",
  420. TargetTenantId = 0,
  421. TargetFactoryId = 1L,
  422. BizDate = yesterday,
  423. BizMonth = lastMonth.ToString("yyyy-MM"),
  424. MonthlyPeriodStart = monthStart,
  425. MonthlyPeriodEnd = monthEnd.AddDays(1).AddSeconds(-1)
  426. };
  427. }
  428. }
  429. public sealed class S6MdpSyncTransformResult
  430. {
  431. public string BatchId { get; set; } = "";
  432. public long RunLogId { get; set; }
  433. public string TriggerType { get; set; } = "AUTO";
  434. public string SourceZtid { get; set; } = "";
  435. public long TargetTenantId { get; set; }
  436. public long TargetFactoryId { get; set; }
  437. public DateTime BizDate { get; set; }
  438. public string BizMonth { get; set; } = "";
  439. public DateTime MonthlyPeriodStart { get; set; }
  440. public DateTime MonthlyPeriodEnd { get; set; }
  441. public int StageRows { get; set; }
  442. public int StandardRows { get; set; }
  443. public int DwdRows { get; set; }
  444. public int KpiRows { get; set; }
  445. public Dictionary<string, int> PerKpiDwdRows { get; } = new();
  446. public Dictionary<string, int> PerKpiKpiRows { get; } = new();
  447. public List<string> KpiDenominatorStatus { get; } = new();
  448. public void MergeSub(string kpiCode, KpiBuildSubResult sub)
  449. {
  450. PerKpiDwdRows[kpiCode] = sub.DwdRows;
  451. PerKpiKpiRows[kpiCode] = sub.KpiRows;
  452. DwdRows += sub.DwdRows;
  453. KpiRows += sub.KpiRows;
  454. KpiDenominatorStatus.Add($"{kpiCode}:{sub.DenominatorStatus}");
  455. }
  456. }
  457. public sealed class KpiBuildSubResult
  458. {
  459. public int T8Rows { get; set; }
  460. public int DwdRows { get; set; }
  461. public int KpiRows { get; set; }
  462. public string DenominatorStatus { get; set; } = "OK";
  463. }
  464. // T8 result set 投影类型 ──────────────────────────────────────────────────────
  465. internal sealed class S6MfgFulfillmentRow
  466. {
  467. public string? noid { get; set; }
  468. public string? rwnoid { get; set; }
  469. public string? code { get; set; }
  470. public decimal? sl { get; set; }
  471. public decimal? slzx { get; set; }
  472. }
  473. internal sealed class S6CountRow
  474. {
  475. public int ddnum { get; set; }
  476. }
  477. internal sealed class S6PeNumRow
  478. {
  479. public int penum { get; set; }
  480. }