KpiDailyTargetReader.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using Admin.NET.Plugin.AiDOP.Entity;
  2. namespace Admin.NET.Plugin.AiDOP.SmartOps;
  3. public sealed class KpiDailyTargetReader : IKpiDailyTargetReader, ITransient
  4. {
  5. private static readonly string[] Tables =
  6. [
  7. "ado_s9_kpi_value_l1_day",
  8. "ado_s9_kpi_value_l2_day",
  9. "ado_s9_kpi_value_l3_day",
  10. "ado_s9_kpi_value_l4_day"
  11. ];
  12. private readonly ISqlSugarClient _db;
  13. public KpiDailyTargetReader(ISqlSugarClient db) => _db = db;
  14. public Task<decimal?> GetCurrentTargetAsync(long tenantId, long factoryId, string moduleCode, string metricCode, DateTime bizDate, CancellationToken ct = default)
  15. => QueryAsync(tenantId, factoryId, moduleCode, metricCode, bizDate, current: true, ct);
  16. public Task<decimal?> GetPriorTargetAsync(long tenantId, long factoryId, string moduleCode, string metricCode, DateTime bizDate, CancellationToken ct = default)
  17. => QueryAsync(tenantId, factoryId, moduleCode, metricCode, bizDate, current: false, ct);
  18. private async Task<decimal?> QueryAsync(
  19. long tenantId, long factoryId, string moduleCode, string metricCode, DateTime bizDate, bool current, CancellationToken ct)
  20. {
  21. foreach (var table in Tables)
  22. {
  23. var sql = current
  24. ? $"""
  25. SELECT target_value FROM {table}
  26. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND module_code=@ModuleCode
  27. AND metric_code=@MetricCode AND biz_date=@BizDate AND is_deleted=0
  28. AND target_value IS NOT NULL AND target_value > 0
  29. ORDER BY id LIMIT 1
  30. """
  31. : $"""
  32. SELECT target_value FROM {table}
  33. WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND module_code=@ModuleCode
  34. AND metric_code=@MetricCode AND biz_date<@BizDate AND is_deleted=0
  35. AND target_value IS NOT NULL AND target_value > 0
  36. ORDER BY biz_date DESC, id DESC LIMIT 1
  37. """;
  38. var val = await _db.Ado.SqlQuerySingleAsync<decimal?>(sql,
  39. new SugarParameter("@TenantId", tenantId),
  40. new SugarParameter("@FactoryId", factoryId),
  41. new SugarParameter("@ModuleCode", moduleCode),
  42. new SugarParameter("@MetricCode", metricCode),
  43. new SugarParameter("@BizDate", bizDate.Date));
  44. if (val is > 0)
  45. return val;
  46. }
  47. return null;
  48. }
  49. }