S4MdpSyncTransformService.cs 55 KB

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