S6MdpSyncTransformService.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. using System.Text.Json;
  2. namespace Admin.NET.Plugin.AiDOP.Manufacturing;
  3. /// <summary>
  4. /// S6 生产执行 — T8 KPI 数据底座与刷新转换服务。
  5. /// 路径 A:方老师 v5.4 KPI 字段对照表 J 列 SQL 原逻辑直发 T8 SQL Server(ConfigId=t8_v5)。
  6. /// 包含 KPI:S6_L1_001 工单制造满足率 / S6_L1_002 工单制造人效。
  7. /// </summary>
  8. public class S6MdpSyncTransformService : ITransient
  9. {
  10. private readonly ISqlSugarClient _db;
  11. private const string JobCode = "S6_MDP_SYNC_TRANSFORM";
  12. private const string JobName = "S6 生产执行 MDP 同步与转换";
  13. private const string T8ConfigId = "t8_v5";
  14. private const string ModuleCode = "S6";
  15. public S6MdpSyncTransformService(ISqlSugarClient db)
  16. {
  17. _db = db;
  18. }
  19. public async Task<S6MdpSyncTransformResult> RunFullAsync(
  20. CancellationToken cancellationToken = default,
  21. string triggerType = "AUTO",
  22. S6MdpRefreshOption? option = null)
  23. {
  24. cancellationToken.ThrowIfCancellationRequested();
  25. option ??= S6MdpRefreshOption.Default();
  26. var now = DateTime.Now;
  27. var batchId = $"S6_MDP_FULL_{now:yyyyMMddHHmmss}";
  28. var normalizedTrigger = NormalizeTriggerType(triggerType);
  29. var runLogId = await InsertTransformRunLogAsync(batchId, now, normalizedTrigger);
  30. var result = new S6MdpSyncTransformResult
  31. {
  32. BatchId = batchId,
  33. RunLogId = runLogId,
  34. TriggerType = normalizedTrigger,
  35. SourceZtid = option.SourceZtid,
  36. BizDate = option.BizDate,
  37. BizMonth = option.BizMonth,
  38. MonthlyPeriodStart = option.MonthlyPeriodStart,
  39. MonthlyPeriodEnd = option.MonthlyPeriodEnd
  40. };
  41. try
  42. {
  43. result.StageRows = 0;
  44. result.StandardRows = 0;
  45. var sub22 = await BuildS6L1001WorkOrderMfgFulfillmentAsync(batchId, now, option, cancellationToken);
  46. result.MergeSub("S6_L1_001", sub22);
  47. var sub23 = await BuildS6L1002WorkOrderMfgEfficiencyAsync(batchId, now, option, cancellationToken);
  48. result.MergeSub("S6_L1_002", sub23);
  49. await MarkTransformRunSuccessAsync(runLogId, now, result);
  50. return result;
  51. }
  52. catch (Exception ex)
  53. {
  54. await MarkTransformRunFailedAsync(runLogId, now, ex.Message);
  55. throw;
  56. }
  57. }
  58. // ─────────────────────────────────────────────────────────────────────────
  59. /// <summary>S6_L1_001 工单制造满足率 = 计划完工时间内累计报工 / 工单计划生产数量。</summary>
  60. private async Task<KpiBuildSubResult> BuildS6L1001WorkOrderMfgFulfillmentAsync(
  61. string batchId, DateTime now, S6MdpRefreshOption option, CancellationToken ct)
  62. {
  63. var sub = new KpiBuildSubResult();
  64. const string sql = @"
  65. select a.noid as noid, b.rwnoid as rwnoid, b.code as code, b.sl as sl, sum(d.slzx) as slzx
  66. from kc_dd_head a with(nolock)
  67. left join kc_dd_list b with(nolock) on a.Id=b.idid
  68. left join (
  69. select b.lynoid as lynoid, b.code as code,
  70. convert(varchar(10), a.shtime, 23) as shtime, b.slzx as slzx
  71. from kc_tz_head a with(nolock)
  72. inner join kc_tz_list b with(nolock) on a.Id=b.idid
  73. where a.ztid=@ztid and a.lbs='生产入库' and a.hzyn=0 and a.zfyn=0 and a.shyn=1
  74. ) d on b.rwnoid=d.lynoid and b.code=d.code
  75. where a.ztid=@ztid and a.lbs='生产任务' and a.zf=0 and a.shyn=1 and d.shtime<=b.jhdate
  76. group by a.noid, b.rwnoid, b.code, b.sl";
  77. var rows = await QueryT8Async<S6MfgFulfillmentRow>(sql, new[] { new SugarParameter("@ztid", option.SourceZtid) });
  78. sub.T8Rows = rows.Count;
  79. var dwdAffected = 0;
  80. var rateList = new List<decimal>();
  81. foreach (var r in rows)
  82. {
  83. ct.ThrowIfCancellationRequested();
  84. if (string.IsNullOrEmpty(r.noid)) continue;
  85. decimal? rate = (r.sl.HasValue && r.sl.Value > 0m && r.slzx.HasValue)
  86. ? Math.Round(r.slzx.Value / r.sl.Value, 4)
  87. : null;
  88. if (rate.HasValue) rateList.Add(rate.Value);
  89. dwdAffected += await _db.Ado.ExecuteCommandAsync(@"
  90. INSERT INTO dwd_t8_work_order_mfg_fulfillment
  91. (tenant_id, factory_id, biz_date, source_ztid, order_no, task_no, item_code,
  92. plan_qty, done_qty_in_window, fulfillment_rate, batch_id, create_time)
  93. VALUES
  94. (0, 1, @bizDate, @ztid, @orderNo, @taskNo, @itemCode,
  95. @planQty, @doneQty, @rate, @batchId, @now)
  96. ON DUPLICATE KEY UPDATE
  97. plan_qty=VALUES(plan_qty), done_qty_in_window=VALUES(done_qty_in_window),
  98. fulfillment_rate=VALUES(fulfillment_rate),
  99. batch_id=VALUES(batch_id), update_time=@now",
  100. new SugarParameter("@bizDate", option.BizDate),
  101. new SugarParameter("@ztid", option.SourceZtid),
  102. new SugarParameter("@orderNo", r.noid),
  103. new SugarParameter("@taskNo", r.rwnoid ?? ""),
  104. new SugarParameter("@itemCode", r.code ?? ""),
  105. new SugarParameter("@planQty", r.sl),
  106. new SugarParameter("@doneQty", r.slzx),
  107. new SugarParameter("@rate", rate),
  108. new SugarParameter("@batchId", batchId),
  109. new SugarParameter("@now", now));
  110. }
  111. sub.DwdRows = dwdAffected;
  112. decimal? metricValue = rateList.Count > 0
  113. ? Math.Round(rateList.Average() * 100m, 4) // 百分号
  114. : null;
  115. sub.KpiRows = await UpsertKpiValueAsync("S6_L1_001", option.BizDate, metricValue, now);
  116. sub.DenominatorStatus = rateList.Count > 0 ? "OK" : "NO_VALID_WORK_ORDER";
  117. return sub;
  118. }
  119. /// <summary>S6_L1_002 工单制造人效 = 完成制造工单数(lbs=生产入库 AND (slzx>=sl OR gdyn=1)) / count(gw=生产)。</summary>
  120. private async Task<KpiBuildSubResult> BuildS6L1002WorkOrderMfgEfficiencyAsync(
  121. string batchId, DateTime now, S6MdpRefreshOption option, CancellationToken ct)
  122. {
  123. var sub = new KpiBuildSubResult();
  124. const string sqlNumer = @"
  125. select count(*) as ddnum
  126. from kc_tz_head a with(nolock)
  127. inner join kc_tz_list b with(nolock) on a.Id=b.idid
  128. where a.ztid=@ztid and a.lbs='生产入库' and a.hzyn=0 and a.zfyn=0 and a.shyn=1
  129. and a.date0 between @startDate and @endDate
  130. and b.slzx>0 and (b.slzx>=b.sl or b.gdyn=1)";
  131. const string sqlDenom = @"
  132. select count(*) as penum
  133. from sys_pelist with(nolock)
  134. where ztid=@ztid and zzzt='在职' and gw='生产'";
  135. var pNumer = new[]
  136. {
  137. new SugarParameter("@ztid", option.SourceZtid),
  138. new SugarParameter("@startDate", option.MonthlyPeriodStart),
  139. new SugarParameter("@endDate", option.MonthlyPeriodEnd)
  140. };
  141. var pDenom = new[] { new SugarParameter("@ztid", option.SourceZtid) };
  142. var numerRows = await QueryT8Async<S6CountRow>(sqlNumer, pNumer);
  143. var denomRows = await QueryT8Async<S6PeNumRow>(sqlDenom, pDenom);
  144. sub.T8Rows = numerRows.Count + denomRows.Count;
  145. int? doneCount = numerRows.FirstOrDefault()?.ddnum;
  146. int? headcount = denomRows.FirstOrDefault()?.penum;
  147. decimal? efficiency = null;
  148. string denomStatus;
  149. if (!headcount.HasValue || headcount.Value <= 0)
  150. denomStatus = "NO_HEADCOUNT";
  151. else if (!doneCount.HasValue)
  152. denomStatus = "NO_NUMERATOR";
  153. else
  154. {
  155. efficiency = Math.Round((decimal)doneCount.Value / headcount.Value, 4);
  156. denomStatus = "OK";
  157. }
  158. sub.DenominatorStatus = denomStatus;
  159. var dwdAffected = await _db.Ado.ExecuteCommandAsync(@"
  160. INSERT INTO dwd_t8_work_order_mfg_efficiency
  161. (tenant_id, factory_id, biz_month, source_ztid, period_start, period_end,
  162. done_count, production_headcount, efficiency, denominator_status, batch_id, create_time)
  163. VALUES
  164. (0, 1, @bizMonth, @ztid, @periodStart, @periodEnd,
  165. @doneCount, @headcount, @efficiency, @denomStatus, @batchId, @now)
  166. ON DUPLICATE KEY UPDATE
  167. period_start=VALUES(period_start), period_end=VALUES(period_end),
  168. done_count=VALUES(done_count), production_headcount=VALUES(production_headcount),
  169. efficiency=VALUES(efficiency), denominator_status=VALUES(denominator_status),
  170. batch_id=VALUES(batch_id), update_time=@now",
  171. new SugarParameter("@bizMonth", option.BizMonth),
  172. new SugarParameter("@ztid", option.SourceZtid),
  173. new SugarParameter("@periodStart", option.MonthlyPeriodStart),
  174. new SugarParameter("@periodEnd", option.MonthlyPeriodEnd),
  175. new SugarParameter("@doneCount", doneCount),
  176. new SugarParameter("@headcount", headcount),
  177. new SugarParameter("@efficiency", efficiency),
  178. new SugarParameter("@denomStatus", denomStatus),
  179. new SugarParameter("@batchId", batchId),
  180. new SugarParameter("@now", now));
  181. sub.DwdRows = dwdAffected;
  182. sub.KpiRows = await UpsertKpiValueAsync("S6_L1_002", option.MonthlyPeriodEnd, efficiency, now);
  183. return sub;
  184. }
  185. // ─────────────────────────────────────────────────────────────────────────
  186. private async Task<List<T>> QueryT8Async<T>(string sql, SugarParameter[] parameters)
  187. {
  188. var t8 = _db.AsTenant().GetConnectionScope(T8ConfigId);
  189. return await t8.Ado.SqlQueryAsync<T>(sql, parameters);
  190. }
  191. private async Task<int> UpsertKpiValueAsync(string metricCode, DateTime bizDate, decimal? metricValue, DateTime now)
  192. {
  193. // 沿用 S3 UpsertS3KpiValueAsync 范式:先查现存行 → UPDATE;不存在 → SELECT MAX(id)+1 显式生成 id 后 INSERT。
  194. // ado_s9_kpi_value_l1_day.id 为手工分配主键(无 AUTO_INCREMENT),必须显式 set;
  195. // metric_value 允许 NULL(分母缺失不得伪装真实 0)。
  196. // FIX-2:截断时分秒(月度 KPI 入参可能为 YYYY-MM-DD 23:59:59),保证 SELECT WHERE biz_date=@BizDate 与 DB date 列匹配,避免重复 INSERT。
  197. bizDate = bizDate.Date;
  198. var existingId = await _db.Ado.GetLongAsync(
  199. "SELECT IFNULL((SELECT id FROM ado_s9_kpi_value_l1_day WHERE tenant_id=0 AND factory_id=1 " +
  200. "AND module_code=@ModuleCode AND metric_code=@MetricCode AND biz_date=@BizDate AND is_deleted=0 " +
  201. "ORDER BY id LIMIT 1), 0)",
  202. new List<SugarParameter>
  203. {
  204. new("@ModuleCode", ModuleCode),
  205. new("@MetricCode", metricCode),
  206. new("@BizDate", bizDate)
  207. });
  208. if (existingId > 0)
  209. {
  210. return await _db.Ado.ExecuteCommandAsync(
  211. "UPDATE ado_s9_kpi_value_l1_day SET metric_value=@MetricValue, calc_time=@Now, " +
  212. "update_time=@Now, is_deleted=0, is_active=1 WHERE id=@Id",
  213. new SugarParameter("@MetricValue", metricValue),
  214. new SugarParameter("@Now", now),
  215. new SugarParameter("@Id", existingId));
  216. }
  217. var nextId = await _db.Ado.GetLongAsync(
  218. "SELECT COALESCE(MAX(id), 0) + 1 FROM ado_s9_kpi_value_l1_day");
  219. return await _db.Ado.ExecuteCommandAsync(@"
  220. INSERT INTO ado_s9_kpi_value_l1_day
  221. (id, tenant_id, org_id, company_id, factory_id, status, biz_date,
  222. create_time, update_time, is_deleted, is_active,
  223. module_code, metric_code, metric_value, calc_time)
  224. VALUES
  225. (@Id, 0, NULL, NULL, 1, NULL, @BizDate,
  226. @Now, @Now, 0, 1,
  227. @ModuleCode, @MetricCode, @MetricValue, @Now)",
  228. new SugarParameter("@Id", nextId),
  229. new SugarParameter("@BizDate", bizDate),
  230. new SugarParameter("@Now", now),
  231. new SugarParameter("@ModuleCode", ModuleCode),
  232. new SugarParameter("@MetricCode", metricCode),
  233. new SugarParameter("@MetricValue", metricValue));
  234. }
  235. private async Task<long> InsertTransformRunLogAsync(string batchId, DateTime startedAt, string triggerType)
  236. {
  237. await _db.Ado.ExecuteCommandAsync(@"
  238. INSERT INTO mdp_transform_run_log
  239. (tenant_id, job_code, job_name, trigger_type, batch_id, status, start_time, stage_rows, standard_rows, dwd_rows, create_time, update_time)
  240. VALUES
  241. (0, @JobCode, @JobName, @TriggerType, @BatchId, 'RUNNING', @StartTime, 0, 0, 0, @StartTime, @StartTime)",
  242. new SugarParameter("@JobCode", JobCode),
  243. new SugarParameter("@JobName", JobName),
  244. new SugarParameter("@TriggerType", triggerType),
  245. new SugarParameter("@BatchId", batchId),
  246. new SugarParameter("@StartTime", startedAt));
  247. return await _db.Ado.GetLongAsync(
  248. "SELECT id FROM mdp_transform_run_log WHERE batch_id=@BatchId ORDER BY id DESC LIMIT 1",
  249. new List<SugarParameter> { new("@BatchId", batchId) });
  250. }
  251. private async Task MarkTransformRunSuccessAsync(long runLogId, DateTime startedAt, S6MdpSyncTransformResult result)
  252. {
  253. var finishedAt = DateTime.Now;
  254. await _db.Ado.ExecuteCommandAsync(@"
  255. UPDATE mdp_transform_run_log
  256. SET status='SUCCESS', end_time=@EndTime, duration_ms=@DurationMs,
  257. stage_rows=@StageRows, standard_rows=@StandardRows, dwd_rows=@DwdRows,
  258. summary_json=@SummaryJson, update_time=CURRENT_TIMESTAMP
  259. WHERE id=@Id",
  260. new SugarParameter("@EndTime", finishedAt),
  261. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  262. new SugarParameter("@StageRows", result.StageRows),
  263. new SugarParameter("@StandardRows", result.StandardRows),
  264. new SugarParameter("@DwdRows", result.DwdRows),
  265. new SugarParameter("@SummaryJson", JsonSerializer.Serialize(new
  266. {
  267. batchId = result.BatchId,
  268. sourceZtid = result.SourceZtid,
  269. bizDate = result.BizDate.ToString("yyyy-MM-dd"),
  270. bizMonth = result.BizMonth,
  271. dwdRows = result.DwdRows,
  272. kpiRows = result.KpiRows,
  273. perKpiDwdRows = result.PerKpiDwdRows,
  274. perKpiKpiRows = result.PerKpiKpiRows,
  275. denominatorStatus = result.KpiDenominatorStatus
  276. })),
  277. new SugarParameter("@Id", runLogId));
  278. }
  279. private async Task MarkTransformRunFailedAsync(long runLogId, DateTime startedAt, string message)
  280. {
  281. try
  282. {
  283. var finishedAt = DateTime.Now;
  284. await _db.Ado.ExecuteCommandAsync(@"
  285. UPDATE mdp_transform_run_log
  286. SET status='FAILED', end_time=@EndTime, duration_ms=@DurationMs,
  287. error_message=@ErrorMessage, update_time=CURRENT_TIMESTAMP
  288. WHERE id=@Id",
  289. new SugarParameter("@EndTime", finishedAt),
  290. new SugarParameter("@DurationMs", (int)(finishedAt - startedAt).TotalMilliseconds),
  291. new SugarParameter("@ErrorMessage", Truncate(message, 2000)),
  292. new SugarParameter("@Id", runLogId));
  293. }
  294. catch (Exception ex)
  295. {
  296. Console.Error.WriteLine($"[S6MdpSyncTransform] MarkTransformRunFailed write failed (runLogId={runLogId}): {ex.Message}");
  297. }
  298. }
  299. private static string NormalizeTriggerType(string s) =>
  300. string.IsNullOrWhiteSpace(s) ? "AUTO" : s.Trim().ToUpperInvariant();
  301. private static string Truncate(string s, int max) =>
  302. string.IsNullOrEmpty(s) ? "" : (s.Length <= max ? s : s.Substring(0, max));
  303. }
  304. // DTO ────────────────────────────────────────────────────────────────────────
  305. public sealed class S6MdpRefreshOption
  306. {
  307. public string SourceZtid { get; set; } = "pbxfxp";
  308. public DateTime BizDate { get; set; }
  309. public string BizMonth { get; set; } = "";
  310. public DateTime MonthlyPeriodStart { get; set; }
  311. public DateTime MonthlyPeriodEnd { get; set; }
  312. public static S6MdpRefreshOption Default()
  313. {
  314. var today = DateTime.Today;
  315. var yesterday = today.AddDays(-1);
  316. var lastMonth = today.AddMonths(-1);
  317. var monthStart = new DateTime(lastMonth.Year, lastMonth.Month, 1);
  318. var monthEnd = monthStart.AddMonths(1).AddDays(-1);
  319. return new S6MdpRefreshOption
  320. {
  321. SourceZtid = "pbxfxp",
  322. BizDate = yesterday,
  323. BizMonth = lastMonth.ToString("yyyy-MM"),
  324. MonthlyPeriodStart = monthStart,
  325. MonthlyPeriodEnd = monthEnd.AddDays(1).AddSeconds(-1)
  326. };
  327. }
  328. }
  329. public sealed class S6MdpSyncTransformResult
  330. {
  331. public string BatchId { get; set; } = "";
  332. public long RunLogId { get; set; }
  333. public string TriggerType { get; set; } = "AUTO";
  334. public string SourceZtid { get; set; } = "";
  335. public DateTime BizDate { get; set; }
  336. public string BizMonth { get; set; } = "";
  337. public DateTime MonthlyPeriodStart { get; set; }
  338. public DateTime MonthlyPeriodEnd { get; set; }
  339. public int StageRows { get; set; }
  340. public int StandardRows { get; set; }
  341. public int DwdRows { get; set; }
  342. public int KpiRows { get; set; }
  343. public Dictionary<string, int> PerKpiDwdRows { get; } = new();
  344. public Dictionary<string, int> PerKpiKpiRows { get; } = new();
  345. public List<string> KpiDenominatorStatus { get; } = new();
  346. public void MergeSub(string kpiCode, KpiBuildSubResult sub)
  347. {
  348. PerKpiDwdRows[kpiCode] = sub.DwdRows;
  349. PerKpiKpiRows[kpiCode] = sub.KpiRows;
  350. DwdRows += sub.DwdRows;
  351. KpiRows += sub.KpiRows;
  352. KpiDenominatorStatus.Add($"{kpiCode}:{sub.DenominatorStatus}");
  353. }
  354. }
  355. public sealed class KpiBuildSubResult
  356. {
  357. public int T8Rows { get; set; }
  358. public int DwdRows { get; set; }
  359. public int KpiRows { get; set; }
  360. public string DenominatorStatus { get; set; } = "OK";
  361. }
  362. // T8 result set 投影类型 ──────────────────────────────────────────────────────
  363. internal sealed class S6MfgFulfillmentRow
  364. {
  365. public string? noid { get; set; }
  366. public string? rwnoid { get; set; }
  367. public string? code { get; set; }
  368. public decimal? sl { get; set; }
  369. public decimal? slzx { get; set; }
  370. }
  371. internal sealed class S6CountRow
  372. {
  373. public int ddnum { get; set; }
  374. }
  375. internal sealed class S6PeNumRow
  376. {
  377. public int penum { get; set; }
  378. }