using System.Diagnostics;
using Admin.NET.Core;
using SqlSugar;
namespace Admin.NET.Plugin.AiDOP.Infrastructure;
///
/// 一次性迁移:将历史 TenantId=1 的 AiDOP 业务数据更新为框架默认租户。
/// 幂等——若已无 TenantId=1 的行则不做任何事。
///
public static class AidopTenantMigration
{
private static readonly (string Table, string TenantColumn)[] Tables =
{
("ado_smart_ops_kpi_master", "TenantId"),
("ado_smart_ops_layout_item", "TenantId"),
("ado_smart_ops_home_module", "TenantId"),
("ado_s9_kpi_value_l1_day", "tenant_id"),
("ado_s9_kpi_value_l2_day", "tenant_id"),
("ado_s9_kpi_value_l3_day", "tenant_id"),
("ado_s9_kpi_value_l4_day", "tenant_id")
};
public static void MigrateOldTenantId(ISqlSugarClient db)
{
EnsureKpiValueL4Table(db);
var target = SqlSugarConst.DefaultTenantId;
if (target == 1) return;
foreach (var (table, tenantColumn) in Tables)
{
try
{
db.Ado.ExecuteCommand(
$"UPDATE `{table}` SET `{tenantColumn}` = @target WHERE `{tenantColumn}` = 1",
new { target });
}
catch (Exception ex)
{
Trace.TraceWarning($"AidopTenantMigration [{table}]: {ex.Message}");
}
}
DropOldUniqueIndex(db);
BackfillThresholds(db);
}
public static void EnsureKpiValueL4Table(ISqlSugarClient db)
{
try
{
db.Ado.ExecuteCommand(
"CREATE TABLE IF NOT EXISTS `ado_s9_kpi_value_l4_day` LIKE `ado_s9_kpi_value_l3_day`");
}
catch (Exception ex)
{
Trace.TraceWarning($"AidopTenantMigration ensure L4 value table: {ex.Message}");
}
}
private static void BackfillThresholds(ISqlSugarClient db)
{
try
{
db.Ado.ExecuteCommand(
"UPDATE ado_smart_ops_kpi_master SET YellowThreshold=95, RedThreshold=80 " +
"WHERE YellowThreshold IS NULL AND Direction='higher_is_better'");
db.Ado.ExecuteCommand(
"UPDATE ado_smart_ops_kpi_master SET YellowThreshold=110, RedThreshold=120 " +
"WHERE YellowThreshold IS NULL AND Direction='lower_is_better'");
}
catch (Exception ex)
{
Trace.TraceWarning($"AidopTenantMigration backfill thresholds: {ex.Message}");
}
}
private static void DropOldUniqueIndex(ISqlSugarClient db)
{
try
{
var rows = db.Ado.SqlQuery(
"SHOW INDEX FROM ado_smart_ops_kpi_master WHERE Key_name = 'uk_kpi_master_code'");
if (rows != null && rows.Count > 0)
db.Ado.ExecuteCommand("ALTER TABLE ado_smart_ops_kpi_master DROP INDEX uk_kpi_master_code");
}
catch (Exception ex)
{
Trace.TraceWarning($"AidopTenantMigration drop old index: {ex.Message}");
}
}
}