S4MdpSyncTransformService.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. using Admin.NET.Plugin.AiDOP.DataPlatform.Executors;
  2. using Admin.NET.Plugin.AiDOP.DataPlatform.MdpRebuild;
  3. using Admin.NET.Plugin.AiDOP.Infrastructure;
  4. using Admin.NET.Plugin.AiDOP.SmartOps;
  5. namespace Admin.NET.Plugin.AiDOP.ProcurementExecution;
  6. /// <summary>
  7. /// S4 采购执行 MDP 转换:S4 专属 STG/STD + 消费 S3 共享 DWD,写入 dwd_s4_purchase_execution / dwd_po_trans 与 S4 KPI。
  8. /// Phase2:源→stg 经统一执行器;std/DWD/KPI 仍读 stg。
  9. /// </summary>
  10. public class S4MdpSyncTransformService : ITransient
  11. {
  12. private const string JobCode = "S4_MDP_SYNC_TRANSFORM";
  13. private readonly ISqlSugarClient _db;
  14. private readonly TransformRunLogFinalizer _runLogFinalizer;
  15. private readonly MdpModuleStagingPuller _stagingPuller;
  16. private readonly IKpiTargetResolver _kpiTargetResolver;
  17. private MdpRebuildScope _runScope = null!;
  18. public S4MdpSyncTransformService(ISqlSugarClient db, MdpModuleStagingPuller stagingPuller, IKpiTargetResolver kpiTargetResolver, TransformRunLogFinalizer runLogFinalizer)
  19. {
  20. _db = db;
  21. _runLogFinalizer = runLogFinalizer;
  22. _stagingPuller = stagingPuller;
  23. _kpiTargetResolver = kpiTargetResolver;
  24. }
  25. public Task<S4MdpSyncTransformResult> RunFullAsync(CancellationToken cancellationToken = default, string triggerType = "AUTO") =>
  26. throw new InvalidOperationException("S4 全量重算必须指定租户/工厂作用域,请走 ModuleRebuildService.Enqueue");
  27. public async Task<S4MdpSyncTransformResult> RunFullAsync(
  28. MdpRebuildScope scope,
  29. CancellationToken cancellationToken = default,
  30. string triggerType = "AUTO",
  31. long? rebuildJobId = null,
  32. Func<ModuleProgressUpdate, Task>? reportProgress = null)
  33. {
  34. _ = rebuildJobId;
  35. _runScope = MdpRebuildScope.Create("S4", scope.TenantId, scope.FactoryId);
  36. cancellationToken.ThrowIfCancellationRequested();
  37. await EnsureS4TablesAsync();
  38. var now = DateTime.Now;
  39. var batchId = $"S4_MDP_FULL_{_runScope.TenantId}_{_runScope.FactoryId}_{now:yyyyMMddHHmmss}";
  40. var runLogId = await InsertTransformRunLogAsync(batchId, now, triggerType);
  41. var result = new S4MdpSyncTransformResult { BatchId = batchId, RunLogId = runLogId };
  42. try
  43. {
  44. await ReportAsync(reportProgress, new ModuleProgressUpdate(ModuleRebuildStages.Preparing, 0, 5, "准备运行环境"));
  45. await ReportAsync(reportProgress, new ModuleProgressUpdate(ModuleRebuildStages.Staging, 1, 12, "正在拉取源数据"));
  46. result.StageRows = await SyncStagingAsync(batchId, now, cancellationToken);
  47. await ReportAsync(reportProgress, new ModuleProgressUpdate(ModuleRebuildStages.Staging, 1, 35, "拉取源数据完成", result.StageRows, ModuleRebuildStages.Staging));
  48. await ReportAsync(reportProgress, new ModuleProgressUpdate(ModuleRebuildStages.Standard, 2, 40, "正在标准化数据"));
  49. result.StandardRows = await TransformStandardAsync(batchId, now, cancellationToken);
  50. await ReportAsync(reportProgress, new ModuleProgressUpdate(ModuleRebuildStages.Standard, 2, 55, "标准化数据完成", result.StandardRows, ModuleRebuildStages.Standard));
  51. await ReportAsync(reportProgress, new ModuleProgressUpdate(ModuleRebuildStages.Dwd, 3, 60, "正在生成 DWD 明细"));
  52. result.DwdRows = await BuildDwdAsync(batchId, now, cancellationToken);
  53. await ReportAsync(reportProgress, new ModuleProgressUpdate(ModuleRebuildStages.Dwd, 3, 75, "生成 DWD 明细完成", result.DwdRows, ModuleRebuildStages.Dwd));
  54. await ReportAsync(reportProgress, new ModuleProgressUpdate(ModuleRebuildStages.Kpi, 4, 80, "正在重算 KPI"));
  55. result.KpiRows = await BuildS4KpiValuesAsync(now, cancellationToken);
  56. await ReportAsync(reportProgress, new ModuleProgressUpdate(ModuleRebuildStages.Kpi, 4, 96, "重算 KPI 完成", result.KpiRows, ModuleRebuildStages.Kpi));
  57. await ReportAsync(reportProgress, new ModuleProgressUpdate(ModuleRebuildStages.Finalizing, 4, 99, "正在收尾"));
  58. await MarkTransformRunSuccessAsync(runLogId, now, result);
  59. return result;
  60. }
  61. catch (Exception ex)
  62. {
  63. // 宿主关停不是转换失败:交给 finally 收口为 ABORTED,不污染 FAILED 语义。
  64. if (!_runLogFinalizer.IsHostStopping)
  65. await MarkTransformRunFailedAsync(runLogId, now, ex.Message);
  66. throw;
  67. }
  68. finally
  69. {
  70. await _runLogFinalizer.FinalizeIfHostStoppingAsync(runLogId, now);
  71. }
  72. }
  73. private static async Task ReportAsync(Func<ModuleProgressUpdate, Task>? report, ModuleProgressUpdate update)
  74. {
  75. if (report == null) return;
  76. await report(update);
  77. }
  78. private async Task EnsureS4TablesAsync()
  79. {
  80. const string ddl = """
  81. CREATE TABLE IF NOT EXISTS mdp_stg_s4_iqc (
  82. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  83. tenant_id BIGINT NOT NULL DEFAULT 0,
  84. source_system VARCHAR(50) NOT NULL DEFAULT 'AIDOP',
  85. source_table VARCHAR(100) NOT NULL,
  86. source_row_id VARCHAR(100) NOT NULL,
  87. source_biz_key VARCHAR(200) NULL,
  88. sync_batch_id VARCHAR(100) NOT NULL,
  89. sync_time DATETIME NOT NULL,
  90. process_status VARCHAR(20) NOT NULL DEFAULT 'PENDING',
  91. process_message VARCHAR(500) NULL,
  92. raw_data JSON NOT NULL,
  93. create_time DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
  94. update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  95. UNIQUE KEY uk_mdp_stg_s4_iqc (tenant_id, source_table, source_row_id),
  96. UNIQUE KEY uk_source_key (source_system, source_table, source_biz_key)
  97. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  98. CREATE TABLE IF NOT EXISTS mdp_stg_s4_shipment LIKE mdp_stg_s4_iqc;
  99. CREATE TABLE IF NOT EXISTS mdp_stg_s4_return LIKE mdp_stg_s4_iqc;
  100. CREATE TABLE IF NOT EXISTS mdp_stg_s4_shortage LIKE mdp_stg_s4_iqc;
  101. CREATE TABLE IF NOT EXISTS mdp_std_s4_iqc (
  102. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  103. tenant_id BIGINT NOT NULL DEFAULT 0,
  104. factory_id BIGINT NULL DEFAULT 1,
  105. source_system VARCHAR(50) NOT NULL DEFAULT 'AIDOP',
  106. po_no VARCHAR(50) NULL, po_line VARCHAR(50) NULL,
  107. supplier_code VARCHAR(50) NULL, item_code VARCHAR(50) NULL,
  108. receipt_qty DECIMAL(18,6) NULL DEFAULT 0,
  109. sample_qty DECIMAL(18,6) NULL DEFAULT 0,
  110. defect_qty DECIMAL(18,6) NULL DEFAULT 0,
  111. qc_result VARCHAR(20) NULL, receipt_date DATETIME NULL,
  112. source_biz_key VARCHAR(200) NULL,
  113. sync_batch_id VARCHAR(100) NOT NULL, sync_time DATETIME NOT NULL,
  114. update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  115. UNIQUE KEY uk_std_s4_iqc (tenant_id, source_biz_key)
  116. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  117. CREATE TABLE IF NOT EXISTS mdp_std_s4_shipment (
  118. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  119. tenant_id BIGINT NOT NULL DEFAULT 0,
  120. factory_id BIGINT NULL DEFAULT 1,
  121. source_system VARCHAR(50) NOT NULL DEFAULT 'AIDOP',
  122. shipment_no VARCHAR(50) NULL, po_no VARCHAR(50) NULL, po_line VARCHAR(50) NULL,
  123. supplier_code VARCHAR(50) NULL, item_code VARCHAR(50) NULL,
  124. ship_qty DECIMAL(18,6) NULL DEFAULT 0, ship_date DATETIME NULL,
  125. source_biz_key VARCHAR(200) NULL,
  126. sync_batch_id VARCHAR(100) NOT NULL, sync_time DATETIME NOT NULL,
  127. update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  128. UNIQUE KEY uk_std_s4_shipment (tenant_id, source_biz_key)
  129. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  130. CREATE TABLE IF NOT EXISTS mdp_std_s4_return (
  131. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  132. tenant_id BIGINT NOT NULL DEFAULT 0,
  133. factory_id BIGINT NULL DEFAULT 1,
  134. source_system VARCHAR(50) NOT NULL DEFAULT 'AIDOP',
  135. po_no VARCHAR(50) NULL, po_line VARCHAR(50) NULL,
  136. supplier_code VARCHAR(50) NULL, item_code VARCHAR(50) NULL,
  137. return_qty DECIMAL(18,6) NULL DEFAULT 0,
  138. return_reason VARCHAR(200) NULL, return_status VARCHAR(50) NULL,
  139. source_biz_key VARCHAR(200) NULL,
  140. sync_batch_id VARCHAR(100) NOT NULL, sync_time DATETIME NOT NULL,
  141. update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  142. UNIQUE KEY uk_std_s4_return (tenant_id, source_biz_key)
  143. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  144. CREATE TABLE IF NOT EXISTS mdp_std_s4_shortage (
  145. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  146. tenant_id BIGINT NOT NULL DEFAULT 0,
  147. factory_id BIGINT NULL DEFAULT 1,
  148. source_system VARCHAR(50) NOT NULL DEFAULT 'AIDOP',
  149. work_order VARCHAR(100) NULL, supplier_code VARCHAR(50) NULL, item_code VARCHAR(50) NULL,
  150. shortage_qty DECIMAL(18,6) NULL DEFAULT 0, risk_level VARCHAR(20) NULL, need_date DATETIME NULL,
  151. source_biz_key VARCHAR(200) NULL,
  152. sync_batch_id VARCHAR(100) NOT NULL, sync_time DATETIME NOT NULL,
  153. update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  154. UNIQUE KEY uk_std_s4_shortage (tenant_id, source_biz_key)
  155. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  156. CREATE TABLE IF NOT EXISTS dwd_s4_purchase_execution (
  157. id BIGINT AUTO_INCREMENT PRIMARY KEY,
  158. tenant_id BIGINT NOT NULL, factory_id BIGINT NOT NULL DEFAULT 1, stat_date DATE NOT NULL,
  159. po_no VARCHAR(50) NULL, po_line VARCHAR(50) NULL,
  160. supplier_code VARCHAR(50) NULL, item_code VARCHAR(50) NULL,
  161. order_qty DECIMAL(12,3) NULL DEFAULT 0, delivery_qty DECIMAL(12,3) NULL DEFAULT 0,
  162. received_qty DECIMAL(12,3) NULL DEFAULT 0, returned_qty DECIMAL(12,3) NULL DEFAULT 0,
  163. shortage_qty DECIMAL(12,3) NULL DEFAULT 0,
  164. due_date DATE NULL, actual_arrival_date DATE NULL, risk_level VARCHAR(20) NULL,
  165. source_system VARCHAR(20) NULL DEFAULT 'AIDOP',
  166. sync_batch_id VARCHAR(100) NULL, sync_time DATETIME NULL,
  167. update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  168. UNIQUE KEY uk_dwd_s4_pe (tenant_id, stat_date, po_no, po_line, item_code),
  169. KEY idx_dwd_s4_pe_date (tenant_id, stat_date),
  170. KEY idx_dwd_s4_pe_supplier (tenant_id, supplier_code)
  171. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  172. """;
  173. foreach (var statement in ddl.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
  174. {
  175. if (statement.Length > 10)
  176. await _db.Ado.ExecuteCommandAsync(statement);
  177. }
  178. }
  179. private async Task<int> SyncStagingAsync(string batchId, DateTime now, CancellationToken cancellationToken)
  180. {
  181. _ = now;
  182. EnsureRunScope();
  183. var total = await _stagingPuller.PullEntitiesAsync(
  184. S4MdpEntityConfig.All.Select(x => x.EntityCode),
  185. batchId, _runScope.TenantId, fullRefresh: true, taskCode: "S4_MDP_INBOUND", cancellationToken,
  186. factoryId: _runScope.FactoryId, requireMatchingSourceTenant: true);
  187. total += await CountSharedStagingRowsAsync();
  188. return total;
  189. }
  190. public async Task<S4MdpSyncTransformResult> RunInboundAsync(
  191. IEnumerable<string>? entityCodes = null,
  192. long tenantId = 0,
  193. bool fullRefresh = false,
  194. CancellationToken cancellationToken = default)
  195. {
  196. cancellationToken.ThrowIfCancellationRequested();
  197. if (tenantId <= 0)
  198. throw new InvalidOperationException("S4 inbound 必须指定有效 tenantId");
  199. _runScope = MdpRebuildScope.Create("S4", tenantId, 1);
  200. await EnsureS4TablesAsync();
  201. var now = DateTime.Now;
  202. var batchId = $"S4_MDP_IN_{_runScope.TenantId}_{now:yyyyMMddHHmmss}";
  203. var runLogId = await InsertTransformRunLogAsync(batchId, now, "INBOUND");
  204. var result = new S4MdpSyncTransformResult { BatchId = batchId, RunLogId = runLogId };
  205. try
  206. {
  207. var codes = entityCodes?.ToList() ?? S4MdpEntityConfig.All.Select(x => x.EntityCode).ToList();
  208. result.StageRows = await _stagingPuller.PullEntitiesAsync(
  209. codes, batchId, tenantId, fullRefresh, "S4_MDP_INBOUND", cancellationToken,
  210. factoryId: _runScope.FactoryId);
  211. result.StageRows += await CountSharedStagingRowsAsync();
  212. result.StandardRows = await TransformStandardAsync(batchId, now, cancellationToken);
  213. result.DwdRows = await BuildDwdAsync(batchId, now, cancellationToken);
  214. result.KpiRows = await BuildS4KpiValuesAsync(now, cancellationToken);
  215. await MarkTransformRunSuccessAsync(runLogId, now, result);
  216. return result;
  217. }
  218. catch (Exception ex)
  219. {
  220. // 宿主关停不是转换失败:交给 finally 收口为 ABORTED,不污染 FAILED 语义。
  221. if (!_runLogFinalizer.IsHostStopping)
  222. await MarkTransformRunFailedAsync(runLogId, now, ex.Message);
  223. throw;
  224. }
  225. finally
  226. {
  227. await _runLogFinalizer.FinalizeIfHostStoppingAsync(runLogId, now);
  228. }
  229. }
  230. private async Task<int> CountSharedStagingRowsAsync()
  231. {
  232. try
  233. {
  234. return await _db.Ado.GetIntAsync(
  235. """
  236. SELECT IFNULL(SUM(cnt), 0) FROM (
  237. SELECT COUNT(1) AS cnt FROM mdp_stg_purchase_order
  238. UNION ALL SELECT COUNT(1) FROM mdp_stg_delivery
  239. UNION ALL SELECT COUNT(1) FROM mdp_stg_receipt
  240. ) t
  241. """);
  242. }
  243. catch
  244. {
  245. return 0;
  246. }
  247. }
  248. [Obsolete("Phase3: use MdpModuleStagingPuller / executors")]
  249. private async Task<int> SyncOneEntityAsync(S4MdpEntityConfig entity, string batchId, DateTime now)
  250. {
  251. var entityRow = await _db.Ado.SqlQuerySingleAsync<S4MdpEntityRow>(
  252. "SELECT id AS Id, entity_name AS EntityName FROM mdp_entity WHERE tenant_id=0 AND entity_code=@EntityCode LIMIT 1",
  253. new SugarParameter("@EntityCode", entity.EntityCode));
  254. if (entityRow == null)
  255. throw Oops.Oh($"未找到 MDP 实体配置:{entity.EntityCode},请先执行 1.0.154.sql 或启动迁移。");
  256. var tableExists = await _db.Ado.GetIntAsync(
  257. """
  258. SELECT COUNT(1) FROM information_schema.TABLES
  259. WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=@TableName
  260. """,
  261. new SugarParameter("@TableName", entity.SourceTable));
  262. if (tableExists == 0)
  263. {
  264. if (entity.Optional)
  265. return 0;
  266. throw Oops.Oh($"未找到 S4 源表:{entity.SourceTable}(实体 {entity.EntityCode})");
  267. }
  268. var columns = await _db.Ado.SqlQueryAsync<S4ColumnRow>(
  269. """
  270. SELECT COLUMN_NAME AS ColumnName
  271. FROM information_schema.COLUMNS
  272. WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=@TableName
  273. ORDER BY ORDINAL_POSITION
  274. """,
  275. new SugarParameter("@TableName", entity.SourceTable));
  276. if (columns.Count == 0)
  277. throw Oops.Oh($"未找到源表字段:{entity.SourceTable}");
  278. var names = columns.Select(u => u.ColumnName).ToList();
  279. var tenantExpr = names.Any(u => string.Equals(u, "tenant_id", StringComparison.OrdinalIgnoreCase))
  280. ? $"IFNULL(s.`{FindColumn(names, "tenant_id")}`,0)"
  281. : "0";
  282. var sourceRowExpr = names.Any(u => string.Equals(u, entity.SourceRowIdExpression, StringComparison.OrdinalIgnoreCase))
  283. ? $"s.`{FindColumn(names, entity.SourceRowIdExpression)}`"
  284. : entity.SourceRowIdExpression;
  285. var rawDataExpr = BuildJsonObjectExpression(names);
  286. var rowsRead = await _db.Ado.GetIntAsync($"SELECT COUNT(1) FROM `{entity.SourceTable}`");
  287. var logId = await InsertSyncLogAsync(entityRow.Id, entityRow.EntityName, batchId, rowsRead);
  288. var started = DateTime.Now;
  289. try
  290. {
  291. var affected = await _db.Ado.ExecuteCommandAsync(
  292. $"""
  293. INSERT INTO `{entity.TargetTable}`
  294. (tenant_id, source_system, source_table, source_row_id, source_biz_key, sync_batch_id, sync_time, process_status, raw_data)
  295. SELECT
  296. {tenantExpr},
  297. 'AIDOP',
  298. @SourceTable,
  299. CAST({sourceRowExpr} AS CHAR),
  300. CAST(COALESCE({entity.SourceBizKeyExpression}, CAST({sourceRowExpr} AS CHAR)) AS CHAR),
  301. @BatchId,
  302. @Now,
  303. 'PENDING',
  304. {rawDataExpr}
  305. FROM `{entity.SourceTable}` s
  306. ON DUPLICATE KEY UPDATE
  307. source_row_id=VALUES(source_row_id),
  308. sync_batch_id=VALUES(sync_batch_id),
  309. sync_time=VALUES(sync_time),
  310. process_status=VALUES(process_status),
  311. raw_data=VALUES(raw_data),
  312. update_time=CURRENT_TIMESTAMP
  313. """,
  314. new SugarParameter("@SourceTable", entity.SourceTable),
  315. new SugarParameter("@BatchId", batchId),
  316. new SugarParameter("@Now", now));
  317. await MarkSyncLogSuccessAsync(logId, started, affected);
  318. return rowsRead;
  319. }
  320. catch (Exception ex)
  321. {
  322. await MarkSyncLogFailedAsync(logId, started, ex.Message);
  323. if (entity.Optional) return 0;
  324. throw;
  325. }
  326. }
  327. private async Task<int> TransformStandardAsync(string batchId, DateTime now, CancellationToken cancellationToken)
  328. {
  329. var total = 0;
  330. foreach (var command in BuildStandardCommands(batchId, now))
  331. {
  332. cancellationToken.ThrowIfCancellationRequested();
  333. try
  334. {
  335. total += await _db.Ado.ExecuteCommandAsync(command.Sql, command.Parameters);
  336. }
  337. catch
  338. {
  339. // 标准层表可能尚未有贴源数据,跳过单条失败
  340. }
  341. }
  342. total += await CountSharedStandardRowsAsync();
  343. return total;
  344. }
  345. private async Task<int> CountSharedStandardRowsAsync()
  346. {
  347. try
  348. {
  349. return await _db.Ado.GetIntAsync(
  350. """
  351. SELECT IFNULL(SUM(cnt), 0) FROM (
  352. SELECT COUNT(1) AS cnt FROM mdp_std_purchase_order
  353. UNION ALL SELECT COUNT(1) FROM mdp_std_delivery_schedule
  354. UNION ALL SELECT COUNT(1) FROM mdp_std_delivery_result
  355. ) t
  356. """);
  357. }
  358. catch
  359. {
  360. return 0;
  361. }
  362. }
  363. private IEnumerable<S4MdpSqlCommand> BuildStandardCommands(string batchId, DateTime now)
  364. {
  365. yield return Cmd(
  366. """
  367. INSERT INTO mdp_std_s4_iqc
  368. (tenant_id, factory_id, source_system, po_no, po_line, supplier_code, item_code, receipt_qty, sample_qty, defect_qty, qc_result, receipt_date, source_biz_key, sync_batch_id, sync_time)
  369. SELECT tenant_id, COALESCE(NULLIF(factory_id,0),1), 'AIDOP',
  370. COALESCE(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.PurOrd')), JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.OrdNbr'))),
  371. CAST(COALESCE(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.OrdLine')), JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.Line'))) AS CHAR),
  372. IFNULL(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.Supp')), ''),
  373. IFNULL(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.ItemNum')), ''),
  374. COALESCE(CASE WHEN JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.QtyReceived')) REGEXP '^-?[0-9]+(\\.[0-9]+)?$' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.QtyReceived')) AS DECIMAL(18,6)) END, 0),
  375. COALESCE(CASE WHEN COALESCE(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.SampleQty')), JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.QcQty'))) REGEXP '^-?[0-9]+(\\.[0-9]+)?$' THEN CAST(COALESCE(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.SampleQty')), JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.QcQty'))) AS DECIMAL(18,6)) END, 0),
  376. COALESCE(CASE WHEN COALESCE(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.RejectQty')), JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.QtyReturn'))) REGEXP '^-?[0-9]+(\\.[0-9]+)?$' THEN CAST(COALESCE(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.RejectQty')), JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.QtyReturn'))) AS DECIMAL(18,6)) END, 0),
  377. CASE WHEN COALESCE(CASE WHEN COALESCE(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.RejectQty')), JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.QtyReturn'))) REGEXP '^-?[0-9]+(\\.[0-9]+)?$' THEN CAST(COALESCE(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.RejectQty')), JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.QtyReturn'))) AS DECIMAL(18,6)) END, 0) > 0 THEN 'FAIL' ELSE 'PASS' END,
  378. NULLIF(NULLIF(COALESCE(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.RcptDate')), JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.RctDate'))), 'null'), ''),
  379. source_biz_key, @BatchId, @Now
  380. FROM mdp_stg_s4_iqc
  381. WHERE source_table='PurOrdRctDetail'
  382. ON DUPLICATE KEY UPDATE receipt_qty=VALUES(receipt_qty), sample_qty=VALUES(sample_qty), defect_qty=VALUES(defect_qty),
  383. qc_result=VALUES(qc_result), receipt_date=VALUES(receipt_date), sync_batch_id=VALUES(sync_batch_id), sync_time=VALUES(sync_time), update_time=CURRENT_TIMESTAMP
  384. """, batchId, now);
  385. yield return Cmd(
  386. """
  387. INSERT INTO mdp_std_s4_shipment
  388. (tenant_id, factory_id, source_system, shipment_no, po_no, po_line, supplier_code, item_code, ship_qty, ship_date, source_biz_key, sync_batch_id, sync_time)
  389. SELECT tenant_id, COALESCE(NULLIF(factory_id,0),1), 'AIDOP',
  390. COALESCE(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.shddh')), source_row_id),
  391. JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.po_bill')),
  392. CAST(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.po_billline')) AS CHAR),
  393. IFNULL(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.suppliercode')), ''),
  394. IFNULL(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.itemnum')), ''),
  395. COALESCE(CASE WHEN JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.sh_delivery_quantity')) REGEXP '^-?[0-9]+(\\.[0-9]+)?$' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.sh_delivery_quantity')) AS DECIMAL(18,6)) END, 0),
  396. NULLIF(NULLIF(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.updatetime')), 'null'), ''),
  397. source_biz_key, @BatchId, @Now
  398. FROM mdp_stg_s4_shipment
  399. WHERE source_table='scm_shdzb'
  400. ON DUPLICATE KEY UPDATE ship_qty=VALUES(ship_qty), ship_date=VALUES(ship_date), sync_batch_id=VALUES(sync_batch_id), sync_time=VALUES(sync_time), update_time=CURRENT_TIMESTAMP
  401. """, batchId, now);
  402. yield return Cmd(
  403. """
  404. INSERT INTO mdp_std_s4_return
  405. (tenant_id, factory_id, source_system, po_no, po_line, supplier_code, item_code, return_qty, return_reason, return_status, source_biz_key, sync_batch_id, sync_time)
  406. SELECT tenant_id, COALESCE(NULLIF(factory_id,0),1), 'AIDOP',
  407. JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.ponumber')),
  408. CAST(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.poline')) AS CHAR),
  409. IFNULL(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.suppliercode')), ''),
  410. IFNULL(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.itemnum')), ''),
  411. COALESCE(CASE WHEN JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.returnqty')) REGEXP '^-?[0-9]+(\\.[0-9]+)?$' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.returnqty')) AS DECIMAL(18,6)) END, 0),
  412. JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.remark')),
  413. JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.status')),
  414. source_biz_key, @BatchId, @Now
  415. FROM mdp_stg_s4_return
  416. WHERE source_table='srm_polist_ds'
  417. AND COALESCE(CASE WHEN JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.returnqty')) REGEXP '^-?[0-9]+(\\.[0-9]+)?$' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.returnqty')) AS DECIMAL(18,6)) END, 0) > 0
  418. ON DUPLICATE KEY UPDATE return_qty=VALUES(return_qty), return_reason=VALUES(return_reason), return_status=VALUES(return_status),
  419. sync_batch_id=VALUES(sync_batch_id), sync_time=VALUES(sync_time), update_time=CURRENT_TIMESTAMP
  420. """, batchId, now);
  421. yield return Cmd(
  422. """
  423. INSERT INTO mdp_std_s4_shortage
  424. (tenant_id, factory_id, source_system, work_order, supplier_code, item_code, shortage_qty, risk_level, need_date, source_biz_key, sync_batch_id, sync_time)
  425. SELECT tenant_id, COALESCE(NULLIF(factory_id,0),1), 'AIDOP',
  426. JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.work_order')),
  427. IFNULL(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.supplier_code')), ''),
  428. IFNULL(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.component_item_code')), ''),
  429. COALESCE(CASE WHEN JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.shortage_qty')) REGEXP '^-?[0-9]+(\\.[0-9]+)?$' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.shortage_qty')) AS DECIMAL(18,6)) END, 0),
  430. IFNULL(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.risk_level')), 'MEDIUM'),
  431. NULLIF(NULLIF(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.expected_supply_date')), 'null'), ''),
  432. source_biz_key, @BatchId, @Now
  433. FROM mdp_stg_s4_shortage
  434. WHERE source_table='dwd_material_shortage'
  435. AND COALESCE(CASE WHEN JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.shortage_qty')) REGEXP '^-?[0-9]+(\\.[0-9]+)?$' THEN CAST(JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.shortage_qty')) AS DECIMAL(18,6)) END, 0) > 0
  436. ON DUPLICATE KEY UPDATE shortage_qty=VALUES(shortage_qty), risk_level=VALUES(risk_level), need_date=VALUES(need_date),
  437. sync_batch_id=VALUES(sync_batch_id), sync_time=VALUES(sync_time), update_time=CURRENT_TIMESTAMP
  438. """, batchId, now);
  439. }
  440. private async Task<int> BuildDwdAsync(string batchId, DateTime now, CancellationToken cancellationToken)
  441. {
  442. cancellationToken.ThrowIfCancellationRequested();
  443. var scope = RequireScope();
  444. string Scoped(string sql) => MdpSqlScope.InjectTenantFactory(sql);
  445. SugarParameter[] ScopedParameters(params SugarParameter[] parameters) =>
  446. [
  447. .. parameters,
  448. new SugarParameter("@TenantId", scope.TenantId),
  449. new SugarParameter("@FactoryId", scope.FactoryId)
  450. ];
  451. var statDate = now.Date;
  452. var total = 0;
  453. try
  454. {
  455. await _db.Ado.ExecuteCommandAsync(
  456. Scoped("DELETE FROM dwd_s4_purchase_execution WHERE stat_date=@StatDate"),
  457. ScopedParameters(new SugarParameter("@StatDate", statDate)));
  458. total += await _db.Ado.ExecuteCommandAsync(
  459. Scoped("""
  460. INSERT INTO dwd_s4_purchase_execution
  461. (tenant_id, factory_id, stat_date, po_no, po_line, supplier_code, item_code,
  462. order_qty, delivery_qty, received_qty, returned_qty, shortage_qty,
  463. due_date, actual_arrival_date, risk_level, source_system, sync_batch_id, sync_time)
  464. SELECT d.tenant_id, d.factory_id, @StatDate,
  465. d.po_no, d.po_line, IFNULL(d.supplier_code,''), IFNULL(d.item_code,''),
  466. IFNULL(d.order_qty,0), IFNULL(d.delivery_qty,0), IFNULL(d.receipt_qty,0),
  467. IFNULL(ret.return_qty,0), IFNULL(sh.shortage_qty,0),
  468. DATE(d.due_date), DATE(d.last_receipt_date),
  469. CASE WHEN d.risk_level IN ('HIGH','MEDIUM','LOW') THEN LOWER(d.risk_level)
  470. WHEN IFNULL(d.remaining_qty,0) > 0 THEN 'high'
  471. WHEN IFNULL(d.receipt_qty,0) >= IFNULL(d.order_qty,0) AND IFNULL(d.order_qty,0) > 0 THEN 'low'
  472. ELSE 'medium' END,
  473. 'AIDOP', @BatchId, @Now
  474. FROM dwd_supplier_delivery d
  475. LEFT JOIN (
  476. SELECT tenant_id, factory_id, po_no, po_line, SUM(IFNULL(return_qty,0)) AS return_qty
  477. FROM mdp_std_s4_return
  478. WHERE IFNULL(po_no,'') <> ''
  479. GROUP BY tenant_id, factory_id, po_no, po_line
  480. ) ret ON d.tenant_id=ret.tenant_id AND d.factory_id=ret.factory_id AND d.po_no=ret.po_no AND d.po_line=ret.po_line
  481. LEFT JOIN (
  482. SELECT tenant_id, factory_id, supplier_code, item_code, SUM(IFNULL(shortage_qty,0)) AS shortage_qty
  483. FROM mdp_std_s4_shortage
  484. GROUP BY tenant_id, factory_id, supplier_code, item_code
  485. ) sh ON d.tenant_id=sh.tenant_id AND d.factory_id=sh.factory_id AND IFNULL(d.supplier_code,'')=IFNULL(sh.supplier_code,'') AND IFNULL(d.item_code,'')=IFNULL(sh.item_code,'')
  486. WHERE d.stat_date=@StatDate AND IFNULL(d.po_no,'') <> ''
  487. ON DUPLICATE KEY UPDATE
  488. order_qty=VALUES(order_qty), delivery_qty=VALUES(delivery_qty), received_qty=VALUES(received_qty),
  489. returned_qty=VALUES(returned_qty), shortage_qty=VALUES(shortage_qty),
  490. due_date=VALUES(due_date), actual_arrival_date=VALUES(actual_arrival_date),
  491. risk_level=VALUES(risk_level), sync_batch_id=VALUES(sync_batch_id), sync_time=VALUES(sync_time), update_time=CURRENT_TIMESTAMP
  492. """),
  493. ScopedParameters(
  494. new SugarParameter("@StatDate", statDate),
  495. new SugarParameter("@BatchId", batchId),
  496. new SugarParameter("@Now", now)));
  497. }
  498. catch
  499. {
  500. // dwd_supplier_delivery 可能尚未由 S3 生成
  501. }
  502. try
  503. {
  504. await _db.Ado.ExecuteCommandAsync(
  505. Scoped("DELETE FROM dwd_po_trans WHERE trans_date=@StatDate"),
  506. ScopedParameters(new SugarParameter("@StatDate", statDate)));
  507. total += await _db.Ado.ExecuteCommandAsync(
  508. Scoped("""
  509. INSERT INTO dwd_po_trans
  510. (tenant_id, factory_id, po_no, po_line, supplier_code, item_code, order_qty, received_qty,
  511. returned_qty, shortage_qty, due_date, actual_arrival_date, risk_level,
  512. trans_date, source_system, sync_batch_id, sync_time)
  513. SELECT tenant_id, factory_id, po_no, po_line, supplier_code, item_code,
  514. order_qty, received_qty, returned_qty, shortage_qty,
  515. due_date, actual_arrival_date, risk_level,
  516. stat_date, source_system, sync_batch_id, sync_time
  517. FROM dwd_s4_purchase_execution
  518. WHERE stat_date=@StatDate
  519. """),
  520. ScopedParameters(new SugarParameter("@StatDate", statDate)));
  521. }
  522. catch
  523. {
  524. try
  525. {
  526. total += await _db.Ado.ExecuteCommandAsync(
  527. Scoped("""
  528. INSERT INTO dwd_po_trans
  529. (tenant_id, factory_id, po_no, supplier_code, item_code, order_qty, received_qty, trans_date, source_system, sync_time)
  530. SELECT po.tenant_id, po.factory_id, po.po_no, IFNULL(po.supplier_code,''), IFNULL(po.item_code,''),
  531. IFNULL(po.order_qty,0), IFNULL(po.received_qty,0), @StatDate, 'AIDOP', @Now
  532. FROM mdp_std_purchase_order po
  533. WHERE IFNULL(po.po_no,'') <> ''
  534. """),
  535. ScopedParameters(
  536. new SugarParameter("@StatDate", statDate),
  537. new SugarParameter("@Now", now)));
  538. }
  539. catch
  540. {
  541. // ignore
  542. }
  543. }
  544. try
  545. {
  546. total += await _db.Ado.ExecuteCommandAsync(
  547. Scoped("""
  548. INSERT INTO dwd_qc_trans
  549. (tenant_id, factory_id, item_code, supplier_code, batch_no, sample_qty, defect_qty, result, trans_date, source_system, sync_time)
  550. SELECT tenant_id, factory_id, IFNULL(item_code,''), IFNULL(supplier_code,''), source_biz_key,
  551. CAST(IFNULL(sample_qty,0) AS SIGNED), CAST(IFNULL(defect_qty,0) AS SIGNED),
  552. CASE WHEN qc_result='FAIL' THEN 'FAIL' WHEN qc_result='CONCESSION' THEN 'CONCESSION' ELSE 'PASS' END,
  553. @StatDate, 'AIDOP', @Now
  554. FROM mdp_std_s4_iqc
  555. WHERE IFNULL(item_code,'') <> ''
  556. ON DUPLICATE KEY UPDATE sample_qty=VALUES(sample_qty), defect_qty=VALUES(defect_qty), result=VALUES(result), sync_time=VALUES(sync_time)
  557. """),
  558. ScopedParameters(
  559. new SugarParameter("@StatDate", statDate),
  560. new SugarParameter("@Now", now)));
  561. }
  562. catch
  563. {
  564. // dwd_qc_trans 可能无唯一键,忽略
  565. }
  566. return total;
  567. }
  568. private async Task<int> BuildS4KpiValuesAsync(DateTime now, CancellationToken cancellationToken)
  569. {
  570. var affected = 0;
  571. for (var dayOffset = 13; dayOffset >= 0; dayOffset--)
  572. {
  573. var statDate = now.Date.AddDays(-dayOffset);
  574. var rows = await CalculateS4KpiValuesAsync(statDate);
  575. foreach (var row in rows)
  576. {
  577. cancellationToken.ThrowIfCancellationRequested();
  578. affected += await UpsertS4KpiValueAsync(row, statDate, now);
  579. }
  580. }
  581. return affected;
  582. }
  583. private async Task<List<S4KpiCalcRow>> CalculateS4KpiValuesAsync(DateTime statDate)
  584. {
  585. var scope = RequireScope();
  586. try
  587. {
  588. return await _db.Ado.SqlQueryAsync<S4KpiCalcRow>(
  589. MdpSqlScope.InjectTenantFactory(
  590. """
  591. SELECT ds.tenant_id AS TenantId, ds.factory_id AS FactoryId, 'S4_L1_001' AS MetricCode,
  592. ROUND(AVG(TIMESTAMPDIFF(DAY, ds.request_date, r.receipt_date)), 4) AS MetricValue
  593. FROM mdp_std_delivery_schedule ds
  594. JOIN (
  595. SELECT tenant_id, factory_id, po_no, po_line, item_code, MAX(receipt_date) AS receipt_date
  596. FROM (
  597. SELECT tenant_id, factory_id, po_no, po_line, item_code, receipt_date
  598. FROM mdp_std_delivery_result
  599. WHERE receipt_date IS NOT NULL
  600. UNION ALL
  601. SELECT tenant_id, factory_id, po_no, po_line, item_code, receipt_date
  602. FROM mdp_std_s4_iqc
  603. WHERE receipt_date IS NOT NULL
  604. ) receipt_events
  605. GROUP BY tenant_id, factory_id, po_no, po_line, item_code
  606. ) r ON r.tenant_id=ds.tenant_id AND r.factory_id=ds.factory_id
  607. AND r.po_no=ds.po_no AND r.po_line=ds.po_line AND r.item_code=ds.item_code
  608. WHERE ds.request_date IS NOT NULL AND r.receipt_date >= ds.request_date
  609. GROUP BY ds.tenant_id, ds.factory_id
  610. HAVING MetricValue IS NOT NULL
  611. UNION ALL
  612. SELECT tenant_id AS TenantId, factory_id AS FactoryId, 'S4_L1_002' AS MetricCode,
  613. ROUND(100 * SUM(CASE WHEN IFNULL(d.receipt_qty,0) >= IFNULL(d.order_qty,0) AND IFNULL(d.order_qty,0) > 0 THEN 1
  614. WHEN d.delivery_status='COMPLETED' THEN 1 ELSE 0 END) / NULLIF(COUNT(1), 0), 4) AS MetricValue
  615. FROM dwd_supplier_delivery d
  616. WHERE d.stat_date=@StatDate AND IFNULL(d.order_qty,0) > 0
  617. GROUP BY tenant_id, factory_id
  618. UNION ALL
  619. SELECT tenant_id AS TenantId, factory_id AS FactoryId, 'S4_L1_003' AS MetricCode,
  620. ROUND(SUM(IFNULL(d.receipt_qty,0)) / GREATEST(COUNT(DISTINCT NULLIF(d.supplier_code,'')), 1), 4) AS MetricValue
  621. FROM dwd_supplier_delivery d
  622. WHERE d.stat_date=@StatDate
  623. GROUP BY tenant_id, factory_id
  624. UNION ALL
  625. SELECT tenant_id AS TenantId, factory_id AS FactoryId, 'S4_L1_004' AS MetricCode,
  626. ROUND(AVG(CASE WHEN IFNULL(d.order_qty,0) > 0
  627. THEN (IFNULL(d.remaining_qty,0) / d.order_qty) * 30 END), 4) AS MetricValue
  628. FROM dwd_supplier_delivery d
  629. WHERE d.stat_date=@StatDate AND IFNULL(d.order_qty,0) > 0
  630. GROUP BY tenant_id, factory_id
  631. UNION ALL
  632. SELECT ds.tenant_id AS TenantId, ds.factory_id AS FactoryId, 'S4_L2_001' AS MetricCode,
  633. ROUND(AVG(TIMESTAMPDIFF(DAY, ds.request_date, r.receipt_date)), 4) AS MetricValue
  634. FROM mdp_std_delivery_schedule ds
  635. JOIN (
  636. SELECT tenant_id, factory_id, po_no, po_line, item_code, MAX(receipt_date) AS receipt_date
  637. FROM (
  638. SELECT tenant_id, factory_id, po_no, po_line, item_code, receipt_date
  639. FROM mdp_std_delivery_result
  640. WHERE receipt_date IS NOT NULL
  641. UNION ALL
  642. SELECT tenant_id, factory_id, po_no, po_line, item_code, receipt_date
  643. FROM mdp_std_s4_iqc
  644. WHERE receipt_date IS NOT NULL
  645. ) receipt_events
  646. GROUP BY tenant_id, factory_id, po_no, po_line, item_code
  647. ) r ON r.tenant_id=ds.tenant_id AND r.factory_id=ds.factory_id
  648. AND r.po_no=ds.po_no AND r.po_line=ds.po_line AND r.item_code=ds.item_code
  649. WHERE ds.request_date IS NOT NULL AND r.receipt_date >= ds.request_date
  650. GROUP BY ds.tenant_id, ds.factory_id
  651. HAVING MetricValue IS NOT NULL
  652. UNION ALL
  653. SELECT tenant_id AS TenantId, factory_id AS FactoryId, 'S4_L2_002' AS MetricCode,
  654. ROUND(100 * SUM(CASE WHEN IFNULL(d.receipt_qty,0) >= IFNULL(d.order_qty,0) AND IFNULL(d.order_qty,0) > 0 THEN 1
  655. WHEN d.delivery_status='COMPLETED' THEN 1 ELSE 0 END) / NULLIF(COUNT(1), 0), 4) AS MetricValue
  656. FROM dwd_supplier_delivery d
  657. WHERE d.stat_date=@StatDate AND IFNULL(d.order_qty,0) > 0
  658. GROUP BY tenant_id, factory_id
  659. UNION ALL
  660. SELECT tenant_id AS TenantId, factory_id AS FactoryId, 'S4_L2_003' AS MetricCode,
  661. ROUND(SUM(IFNULL(pe.received_qty,0)) / GREATEST(COUNT(DISTINCT NULLIF(pe.item_code,'')), 1), 4) AS MetricValue
  662. FROM dwd_s4_purchase_execution pe
  663. WHERE pe.stat_date=@StatDate
  664. GROUP BY tenant_id, factory_id
  665. UNION ALL
  666. SELECT tenant_id AS TenantId, factory_id AS FactoryId, 'S4_L2_004' AS MetricCode,
  667. ROUND(AVG(CASE WHEN IFNULL(pe.order_qty,0) > 0
  668. THEN ((IFNULL(pe.order_qty,0) - IFNULL(pe.received_qty,0)) / pe.order_qty) * 30 END), 4) AS MetricValue
  669. FROM dwd_s4_purchase_execution pe
  670. WHERE pe.stat_date=@StatDate AND IFNULL(pe.order_qty,0) > 0
  671. GROUP BY tenant_id, factory_id
  672. UNION ALL
  673. SELECT ds.tenant_id AS TenantId, ds.factory_id AS FactoryId, 'S4_L3_001' AS MetricCode,
  674. ROUND(AVG(TIMESTAMPDIFF(DAY, ds.request_date, r.receipt_date)), 4) AS MetricValue
  675. FROM mdp_std_delivery_schedule ds
  676. JOIN (
  677. SELECT tenant_id, factory_id, po_no, po_line, item_code, MAX(receipt_date) AS receipt_date
  678. FROM (
  679. SELECT tenant_id, factory_id, po_no, po_line, item_code, receipt_date
  680. FROM mdp_std_delivery_result
  681. WHERE receipt_date IS NOT NULL
  682. UNION ALL
  683. SELECT tenant_id, factory_id, po_no, po_line, item_code, receipt_date
  684. FROM mdp_std_s4_iqc
  685. WHERE receipt_date IS NOT NULL
  686. ) receipt_events
  687. GROUP BY tenant_id, factory_id, po_no, po_line, item_code
  688. ) r ON r.tenant_id=ds.tenant_id AND r.factory_id=ds.factory_id
  689. AND r.po_no=ds.po_no AND r.po_line=ds.po_line AND r.item_code=ds.item_code
  690. WHERE ds.request_date IS NOT NULL AND r.receipt_date >= ds.request_date
  691. AND IFNULL(ds.supplier_code,'') <> ''
  692. GROUP BY ds.tenant_id, ds.factory_id
  693. HAVING MetricValue IS NOT NULL
  694. UNION ALL
  695. SELECT tenant_id AS TenantId, factory_id AS FactoryId, 'S4_L3_002' AS MetricCode,
  696. ROUND(100 * SUM(CASE WHEN IFNULL(d.receipt_qty,0) >= IFNULL(d.order_qty,0) AND IFNULL(d.order_qty,0) > 0 THEN 1
  697. WHEN d.delivery_status='COMPLETED' THEN 1 ELSE 0 END) / NULLIF(COUNT(1), 0), 4) AS MetricValue
  698. FROM dwd_supplier_delivery d
  699. WHERE d.stat_date=@StatDate AND IFNULL(d.supplier_code,'') <> '' AND IFNULL(d.order_qty,0) > 0
  700. GROUP BY tenant_id, factory_id
  701. UNION ALL
  702. SELECT tenant_id AS TenantId, factory_id AS FactoryId, 'S4_L3_003' AS MetricCode,
  703. ROUND(COUNT(DISTINCT NULLIF(pe.supplier_code,'')) / GREATEST(COUNT(DISTINCT NULLIF(pe.po_no,'')), 1), 4) AS MetricValue
  704. FROM dwd_s4_purchase_execution pe
  705. WHERE pe.stat_date=@StatDate AND IFNULL(pe.supplier_code,'') <> ''
  706. GROUP BY tenant_id, factory_id
  707. UNION ALL
  708. SELECT tenant_id AS TenantId, factory_id AS FactoryId, 'S4_L3_004' AS MetricCode,
  709. ROUND(AVG(CASE WHEN IFNULL(pe.order_qty,0) > 0 AND IFNULL(pe.supplier_code,'') <> ''
  710. THEN ((IFNULL(pe.order_qty,0) - IFNULL(pe.received_qty,0)) / pe.order_qty) * 30 END), 4) AS MetricValue
  711. FROM dwd_s4_purchase_execution pe
  712. WHERE pe.stat_date=@StatDate AND IFNULL(pe.order_qty,0) > 0 AND IFNULL(pe.supplier_code,'') <> ''
  713. GROUP BY tenant_id, factory_id
  714. """),
  715. new SugarParameter("@StatDate", statDate),
  716. new SugarParameter("@TenantId", scope.TenantId),
  717. new SugarParameter("@FactoryId", scope.FactoryId));
  718. }
  719. catch
  720. {
  721. return new List<S4KpiCalcRow>();
  722. }
  723. }
  724. private async Task<int> UpsertS4KpiValueAsync(S4KpiCalcRow row, DateTime statDate, DateTime now)
  725. {
  726. var meta = await _db.Ado.SqlQuerySingleAsync<S4KpiMetaRow>(
  727. """
  728. SELECT MetricLevel, Direction, YellowThreshold, RedThreshold
  729. FROM ado_smart_ops_kpi_master
  730. WHERE TenantId=@TenantId AND ModuleCode='S4' AND MetricCode=@MetricCode AND IsEnabled=1
  731. LIMIT 1
  732. """,
  733. new SugarParameter("@TenantId", row.TenantId),
  734. new SugarParameter("@MetricCode", row.MetricCode));
  735. if (meta == null || row.MetricValue == null)
  736. return 0;
  737. var table = ResolveKpiValueTable(meta.MetricLevel);
  738. var current = await _db.Ado.SqlQuerySingleAsync<S4KpiValueRow>(
  739. $"""
  740. SELECT id AS Id, metric_value AS MetricValue, target_value AS TargetValue
  741. FROM {table}
  742. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND module_code='S4'
  743. AND metric_code=@MetricCode AND biz_date=@BizDate AND is_deleted=0
  744. ORDER BY id
  745. LIMIT 1
  746. """,
  747. new SugarParameter("@TenantId", row.TenantId),
  748. new SugarParameter("@FactoryId", row.FactoryId),
  749. new SugarParameter("@MetricCode", row.MetricCode),
  750. new SugarParameter("@BizDate", statDate));
  751. var prior = await _db.Ado.SqlQuerySingleAsync<S4KpiValueRow>(
  752. $"""
  753. SELECT id AS Id, metric_value AS MetricValue, target_value AS TargetValue
  754. FROM {table}
  755. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND module_code='S4'
  756. AND metric_code=@MetricCode AND biz_date<@BizDate AND is_deleted=0
  757. ORDER BY biz_date DESC, id DESC
  758. LIMIT 1
  759. """,
  760. new SugarParameter("@TenantId", row.TenantId),
  761. new SugarParameter("@FactoryId", row.FactoryId),
  762. new SugarParameter("@MetricCode", row.MetricCode),
  763. new SugarParameter("@BizDate", statDate));
  764. var actual = Math.Round(row.MetricValue.Value, 4);
  765. var snap = await _kpiTargetResolver.ResolveAsync(row.TenantId, row.FactoryId, row.MetricCode, "S4", statDate);
  766. var target = snap.TargetValue;
  767. var status = AidopS4KpiMerge.AchievementLevel(actual, target, meta.Direction, meta.YellowThreshold, meta.RedThreshold);
  768. var trend = ResolveTrendFlag(actual, prior?.MetricValue);
  769. if (current != null)
  770. {
  771. return await _db.Ado.ExecuteCommandAsync(
  772. $"""
  773. UPDATE {table}
  774. SET metric_value=@MetricValue, target_value=@TargetValue, status_color=@StatusColor, trend_flag=@TrendFlag,
  775. target_config_id=@TargetConfigId, target_source=@TargetSource, target_resolved_at=@TargetResolvedAt,
  776. is_active=1, status='ACTIVE', calc_time=@CalcTime, update_time=@CalcTime
  777. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND module_code='S4'
  778. AND metric_code=@MetricCode AND biz_date=@BizDate AND is_deleted=0
  779. """,
  780. new SugarParameter("@MetricValue", actual),
  781. new SugarParameter("@TargetValue", KpiTargetSnapshotSql.ValueOrDbNull(snap)),
  782. new SugarParameter("@StatusColor", status),
  783. new SugarParameter("@TrendFlag", trend),
  784. new SugarParameter("@TargetConfigId", KpiTargetSnapshotSql.ConfigIdOrDbNull(snap)),
  785. new SugarParameter("@TargetSource", KpiTargetSnapshotSql.SourceOrDbNull(snap)),
  786. new SugarParameter("@TargetResolvedAt", snap.ResolvedAt),
  787. new SugarParameter("@CalcTime", now),
  788. new SugarParameter("@TenantId", row.TenantId),
  789. new SugarParameter("@FactoryId", row.FactoryId),
  790. new SugarParameter("@MetricCode", row.MetricCode),
  791. new SugarParameter("@BizDate", statDate));
  792. }
  793. var nextId = Yitter.IdGenerator.YitIdHelper.NextId();
  794. return await _db.Ado.ExecuteCommandAsync(
  795. $"""
  796. INSERT INTO {table}
  797. (id, tenant_id, factory_id, status, biz_date, create_time, update_time, is_deleted, is_active,
  798. module_code, metric_code, metric_value, target_value, status_color, trend_flag, calc_time,
  799. target_config_id, target_source, target_resolved_at)
  800. VALUES
  801. (@Id, @TenantId, @FactoryId, 'ACTIVE', @BizDate, @CalcTime, @CalcTime, 0, 1,
  802. 'S4', @MetricCode, @MetricValue, @TargetValue, @StatusColor, @TrendFlag, @CalcTime,
  803. @TargetConfigId, @TargetSource, @TargetResolvedAt)
  804. """,
  805. new SugarParameter("@Id", nextId),
  806. new SugarParameter("@TenantId", row.TenantId),
  807. new SugarParameter("@FactoryId", row.FactoryId),
  808. new SugarParameter("@BizDate", statDate),
  809. new SugarParameter("@CalcTime", now),
  810. new SugarParameter("@MetricCode", row.MetricCode),
  811. new SugarParameter("@MetricValue", actual),
  812. new SugarParameter("@TargetValue", KpiTargetSnapshotSql.ValueOrDbNull(snap)),
  813. new SugarParameter("@StatusColor", status),
  814. new SugarParameter("@TrendFlag", trend),
  815. new SugarParameter("@TargetConfigId", KpiTargetSnapshotSql.ConfigIdOrDbNull(snap)),
  816. new SugarParameter("@TargetSource", KpiTargetSnapshotSql.SourceOrDbNull(snap)),
  817. new SugarParameter("@TargetResolvedAt", snap.ResolvedAt));
  818. }
  819. private async Task<long> InsertSyncLogAsync(long entityId, string entityName, string batchId, int rowsRead)
  820. {
  821. EnsureRunScope();
  822. await _db.Ado.ExecuteCommandAsync(
  823. """
  824. INSERT INTO mdp_sync_log
  825. (tenant_id, entity_id, source_code, entity_name, sync_batch_id, sync_type, trigger_type, sync_start, rows_read, status)
  826. VALUES (@TenantId, @EntityId, 'AIDOPDEV_MYSQL', @EntityName, @BatchId, 'FULL', 'AUTO', NOW(), @RowsRead, 'RUNNING')
  827. """,
  828. new SugarParameter("@TenantId", _runScope.TenantId),
  829. new SugarParameter("@EntityId", entityId),
  830. new SugarParameter("@EntityName", entityName),
  831. new SugarParameter("@BatchId", batchId),
  832. new SugarParameter("@RowsRead", rowsRead));
  833. return await _db.Ado.GetLongAsync(
  834. "SELECT id FROM mdp_sync_log WHERE sync_batch_id=@BatchId AND entity_id=@EntityId ORDER BY id DESC LIMIT 1",
  835. new List<SugarParameter> { new("@BatchId", batchId), new("@EntityId", entityId) });
  836. }
  837. private async Task MarkSyncLogSuccessAsync(long logId, DateTime started, int affected)
  838. {
  839. await _db.Ado.ExecuteCommandAsync(
  840. """
  841. UPDATE mdp_sync_log
  842. SET status='SUCCESS', sync_end=NOW(), duration_ms=@DurationMs, rows_written=@RowsWritten
  843. WHERE id=@Id
  844. """,
  845. new SugarParameter("@DurationMs", (int)(DateTime.Now - started).TotalMilliseconds),
  846. new SugarParameter("@RowsWritten", affected),
  847. new SugarParameter("@Id", logId));
  848. }
  849. private async Task MarkSyncLogFailedAsync(long logId, DateTime started, string message)
  850. {
  851. await _db.Ado.ExecuteCommandAsync(
  852. """
  853. UPDATE mdp_sync_log
  854. SET status='FAILED', sync_end=NOW(), duration_ms=@DurationMs, error_message=@ErrorMessage
  855. WHERE id=@Id
  856. """,
  857. new SugarParameter("@DurationMs", (int)(DateTime.Now - started).TotalMilliseconds),
  858. new SugarParameter("@ErrorMessage", Truncate(message, 2000)),
  859. new SugarParameter("@Id", logId));
  860. }
  861. private async Task<long> InsertTransformRunLogAsync(string batchId, DateTime startedAt, string triggerType)
  862. {
  863. await _db.Ado.ExecuteCommandAsync(
  864. """
  865. INSERT INTO mdp_transform_run_log
  866. (tenant_id, job_code, job_name, trigger_type, batch_id, status, start_time)
  867. VALUES (@TenantId, @JobCode, 'S4 MDP同步与标准化转换', @TriggerType, @BatchId, 'RUNNING', @StartTime)
  868. """,
  869. new SugarParameter("@TenantId", RequireScope().TenantId),
  870. new SugarParameter("@JobCode", JobCode),
  871. new SugarParameter("@TriggerType", NormalizeTriggerType(triggerType)),
  872. new SugarParameter("@BatchId", batchId),
  873. new SugarParameter("@StartTime", startedAt));
  874. return await _db.Ado.GetLongAsync(
  875. "SELECT id FROM mdp_transform_run_log WHERE batch_id=@BatchId ORDER BY id DESC LIMIT 1",
  876. new List<SugarParameter> { new("@BatchId", batchId) });
  877. }
  878. private async Task MarkTransformRunSuccessAsync(long runLogId, DateTime startedAt, S4MdpSyncTransformResult result)
  879. {
  880. var finishedAt = DateTime.Now;
  881. await _db.Ado.ExecuteCommandAsync(
  882. """
  883. UPDATE mdp_transform_run_log
  884. SET status='SUCCESS', end_time=@EndTime, duration_ms=@DurationMs,
  885. stage_rows=@StageRows, standard_rows=@StandardRows, dwd_rows=@DwdRows,
  886. summary_json=@SummaryJson, update_time=CURRENT_TIMESTAMP
  887. WHERE id=@Id
  888. """,
  889. new SugarParameter("@EndTime", finishedAt),
  890. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  891. new SugarParameter("@StageRows", result.StageRows),
  892. new SugarParameter("@StandardRows", result.StandardRows),
  893. new SugarParameter("@DwdRows", result.DwdRows),
  894. new SugarParameter("@SummaryJson", BuildRunSummaryJson(result)),
  895. new SugarParameter("@Id", runLogId));
  896. }
  897. private async Task MarkTransformRunFailedAsync(long runLogId, DateTime startedAt, string message)
  898. {
  899. try
  900. {
  901. var finishedAt = DateTime.Now;
  902. await _db.Ado.ExecuteCommandAsync(
  903. """
  904. UPDATE mdp_transform_run_log
  905. SET status='FAILED', end_time=@EndTime, duration_ms=@DurationMs,
  906. error_message=@ErrorMessage, update_time=CURRENT_TIMESTAMP
  907. WHERE id=@Id
  908. """,
  909. new SugarParameter("@EndTime", finishedAt),
  910. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  911. new SugarParameter("@ErrorMessage", Truncate(message, 2000)),
  912. new SugarParameter("@Id", runLogId));
  913. }
  914. catch (Exception ex)
  915. {
  916. Console.Error.WriteLine($"[S4MdpSyncTransform] MarkTransformRunFailed write failed (runLogId={runLogId}): {ex.Message}");
  917. }
  918. }
  919. private S4MdpSqlCommand Cmd(string sql, string batchId, DateTime now)
  920. {
  921. var scope = RequireScope();
  922. return new S4MdpSqlCommand(MdpSqlScope.InjectTenantFactory(sql), new[]
  923. {
  924. new SugarParameter("@BatchId", batchId),
  925. new SugarParameter("@Now", now),
  926. new SugarParameter("@StatDate", now.Date),
  927. new SugarParameter("@TenantId", scope.TenantId),
  928. new SugarParameter("@FactoryId", scope.FactoryId)
  929. });
  930. }
  931. private MdpRebuildScope RequireScope()
  932. {
  933. EnsureRunScope();
  934. return _runScope;
  935. }
  936. private void EnsureRunScope()
  937. {
  938. if (_runScope == null)
  939. throw new InvalidOperationException("S4 全量重算必须指定有效 tenantId/factoryId");
  940. }
  941. private static string BuildJsonObjectExpression(IEnumerable<string> columns)
  942. {
  943. var parts = columns.SelectMany(c => new[] { $"'{c.Replace("'", "''")}'", $"s.`{c}`" });
  944. return $"JSON_OBJECT({string.Join(",", parts)})";
  945. }
  946. private static string FindColumn(IEnumerable<string> columns, string expected) =>
  947. columns.First(u => string.Equals(u, expected, StringComparison.OrdinalIgnoreCase));
  948. private static string BuildRunSummaryJson(S4MdpSyncTransformResult result) =>
  949. $$"""{"batchId":"{{result.BatchId}}","stageRows":{{result.StageRows}},"standardRows":{{result.StandardRows}},"dwdRows":{{result.DwdRows}},"kpiRows":{{result.KpiRows}}}""";
  950. private static string ResolveKpiValueTable(int metricLevel) => metricLevel switch
  951. {
  952. 1 => "ado_s9_kpi_value_l1_day",
  953. 2 => "ado_s9_kpi_value_l2_day",
  954. 3 => "ado_s9_kpi_value_l3_day",
  955. 4 => "ado_s9_kpi_value_l4_day",
  956. _ => "ado_s9_kpi_value_l2_day"
  957. };
  958. private static decimal DefaultS4Target(string metricCode) => LegacyKpiCodeTargets.GetOrZero(metricCode);
  959. private static string ResolveKpiStatus(decimal actual, decimal target, string? direction, decimal? yellowThreshold, decimal? redThreshold)
  960. {
  961. if (target <= 0) return "gray";
  962. var ratio = actual / target * 100m;
  963. if (string.Equals(direction, "lower_is_better", StringComparison.OrdinalIgnoreCase))
  964. {
  965. if (actual <= target) return "green";
  966. if (ratio <= (yellowThreshold ?? 110m)) return "yellow";
  967. return ratio >= (redThreshold ?? 120m) ? "red" : "yellow";
  968. }
  969. if (actual >= target) return "green";
  970. if (ratio >= (yellowThreshold ?? 95m)) return "yellow";
  971. return ratio <= (redThreshold ?? 80m) ? "red" : "yellow";
  972. }
  973. private static string ResolveTrendFlag(decimal actual, decimal? previous)
  974. {
  975. if (previous == null) return "flat";
  976. if (actual > previous.Value) return "up";
  977. if (actual < previous.Value) return "down";
  978. return "flat";
  979. }
  980. private static string NormalizeTriggerType(string? triggerType)
  981. => string.IsNullOrWhiteSpace(triggerType) ? "AUTO" : triggerType.Trim().ToUpperInvariant();
  982. private static string Truncate(string? raw, int maxLength)
  983. {
  984. if (string.IsNullOrEmpty(raw)) return string.Empty;
  985. return raw.Length <= maxLength ? raw : raw[..maxLength];
  986. }
  987. private sealed class S4ColumnRow
  988. {
  989. public string ColumnName { get; set; } = string.Empty;
  990. }
  991. private sealed class S4MdpEntityRow
  992. {
  993. public long Id { get; set; }
  994. public string EntityName { get; set; } = string.Empty;
  995. }
  996. private sealed class S4KpiCalcRow
  997. {
  998. public long TenantId { get; set; }
  999. public long FactoryId { get; set; }
  1000. public string MetricCode { get; set; } = string.Empty;
  1001. public decimal? MetricValue { get; set; }
  1002. }
  1003. private sealed class S4KpiMetaRow
  1004. {
  1005. public int MetricLevel { get; set; }
  1006. public string Direction { get; set; } = "higher_is_better";
  1007. public decimal? YellowThreshold { get; set; }
  1008. public decimal? RedThreshold { get; set; }
  1009. }
  1010. private sealed class S4KpiValueRow
  1011. {
  1012. public long Id { get; set; }
  1013. public decimal? MetricValue { get; set; }
  1014. public decimal? TargetValue { get; set; }
  1015. }
  1016. }
  1017. public sealed class S4MdpSyncTransformResult
  1018. {
  1019. public long RunLogId { get; set; }
  1020. public string BatchId { get; set; } = string.Empty;
  1021. public int StageRows { get; set; }
  1022. public int StandardRows { get; set; }
  1023. public int DwdRows { get; set; }
  1024. public int KpiRows { get; set; }
  1025. }
  1026. internal sealed record S4MdpSqlCommand(string Sql, SugarParameter[] Parameters);
  1027. internal sealed record S4MdpEntityConfig(
  1028. string EntityCode,
  1029. string SourceTable,
  1030. string TargetTable,
  1031. string SourceRowIdExpression,
  1032. string SourceBizKeyExpression,
  1033. bool Optional = false)
  1034. {
  1035. public static readonly IReadOnlyList<S4MdpEntityConfig> All = new List<S4MdpEntityConfig>
  1036. {
  1037. new("S4_IQC_RECEIPT", "PurOrdRctDetail", "mdp_stg_s4_iqc", "RecID", "CONCAT(IFNULL(s.`Domain`,''), ':', IFNULL(s.`Receiver`,''), ':', IFNULL(s.`Line`,''))"),
  1038. new("S4_SHIPMENT_EXEC", "scm_shdzb", "mdp_stg_s4_shipment", "id", "CONCAT(IFNULL(s.`glid`,''), ':', IFNULL(s.`id`,''))"),
  1039. new("S4_RETURN_EXEC", "srm_polist_ds", "mdp_stg_s4_return", "Id", "s.`dsnum`"),
  1040. new("S4_SHORTAGE_EXEC", "dwd_material_shortage", "mdp_stg_s4_shortage", "id", "CONCAT(IFNULL(s.`work_order`,''), ':', IFNULL(s.`component_item_code`,''))", Optional: true)
  1041. };
  1042. }