S4MdpSyncTransformService.cs 50 KB

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