S4MdpSyncTransformService.cs 58 KB

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