KpiBaselineSnapshotService.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using SqlSugar;
  2. namespace Admin.NET.Plugin.AiDOP.DataPlatform.MdpRebuild;
  3. /// <summary>
  4. /// 把 L1–L3 日值抄进 <c>ado_kpi_baseline_snapshot</c>。
  5. /// 窗口与 KPI 回算一致:当日及前 13 天(<c>dayOffset = 13 … 0</c>)。
  6. /// 调用方必须自己保证这次抄的是全量重算之后的结果。
  7. /// </summary>
  8. public sealed class KpiBaselineSnapshotService : ITransient
  9. {
  10. public const int WindowDays = 14;
  11. public static readonly long[] G0TenantIds =
  12. [
  13. 797403760988229,
  14. 824585161322565,
  15. 838257186181189
  16. ];
  17. private readonly ISqlSugarClient _db;
  18. public KpiBaselineSnapshotService(ISqlSugarClient db) => _db = db;
  19. public async Task<int> TakeAsync(string snapshotCode, CancellationToken cancellationToken = default)
  20. {
  21. if (string.IsNullOrWhiteSpace(snapshotCode))
  22. throw new ArgumentException("snapshotCode 不能为空", nameof(snapshotCode));
  23. var code = snapshotCode.Trim();
  24. var tenants = string.Join(",", G0TenantIds);
  25. var written = 0;
  26. foreach (var (table, lvl) in new (string table, string lvl)[]
  27. {
  28. ("ado_s9_kpi_value_l1_day", "L1"),
  29. ("ado_s9_kpi_value_l2_day", "L2"),
  30. ("ado_s9_kpi_value_l3_day", "L3")
  31. })
  32. {
  33. written += await _db.Ado.ExecuteCommandAsync(
  34. $"""
  35. INSERT INTO ado_kpi_baseline_snapshot
  36. (snapshot_code, tenant_id, factory_id, module_code, metric_code, lvl,
  37. biz_date, metric_value, target_value, result_status)
  38. SELECT @code, tenant_id, factory_id, module_code, metric_code, @lvl,
  39. biz_date, metric_value, target_value, NULL
  40. FROM {table}
  41. WHERE is_deleted = 0
  42. AND tenant_id IN ({tenants})
  43. AND biz_date BETWEEN DATE_SUB(CURDATE(), INTERVAL {WindowDays - 1} DAY) AND CURDATE()
  44. ON DUPLICATE KEY UPDATE
  45. metric_value = VALUES(metric_value),
  46. target_value = VALUES(target_value),
  47. result_status = VALUES(result_status),
  48. taken_at = CURRENT_TIMESTAMP(3)
  49. """,
  50. new { code, lvl });
  51. cancellationToken.ThrowIfCancellationRequested();
  52. }
  53. return written;
  54. }
  55. }