S4MdpSyncTransformService.cs 50 KB

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