-- =============================================================================
-- 批次：S5-S6-S7-T8-KPI-TENANT-WRITE-CONTRACT-1
-- 目的：幂等补齐看板读取租户（TenantId=1300000000001 / FactoryId=1）下缺失的
--      S5_L1_004「品类物料库存周转」KPI master。
-- 背景：S5/S6/S7 refresh 此前把 KPI 值硬编码写入 tenant=0；本批次改写真实看板租户。
--      看板读取租户已有 S5/S6/S7 其余 8 个 L1 master，唯独缺 S5_L1_004（仅 tenant=0 有）。
-- 模板：取自 TenantId=0 的 S5_L1_004 定义，仅改 Id/TenantId/时间戳，业务字段原样复制。
-- 幂等：目标租户已存在 S5_L1_004 时不插入（@tgt_exists 守卫 + uk_kpi_master_code_tenant 唯一键双保险）。
-- 边界：不删除、不修改 tenant=0 的 S5_L1_004；不覆盖目标租户已有的其它 8 个 master。
-- =============================================================================

SET @tgt_exists = (SELECT COUNT(*) FROM ado_smart_ops_kpi_master
                   WHERE TenantId = 1300000000001 AND MetricCode = 'S5_L1_004');
SET @new_id     = (SELECT COALESCE(MAX(Id), 0) + 1 FROM ado_smart_ops_kpi_master);

INSERT INTO ado_smart_ops_kpi_master
  (Id, MetricCode, ModuleCode, MetricLevel, ParentId, MetricName, Description, Formula,
   CalcRule, DataSource, StatFrequency, Department, DopFields, Unit, Direction,
   IsHomePage, SortNo, Remark, IsEnabled, TenantId, CreatedAt, UpdatedAt,
   YellowThreshold, RedThreshold, FormulaExpr, FormulaPreview, FormulaRefs)
SELECT
  @new_id, MetricCode, ModuleCode, MetricLevel, ParentId, MetricName, Description, Formula,
  CalcRule, DataSource, StatFrequency, Department, DopFields, Unit, Direction,
  IsHomePage, SortNo, Remark, IsEnabled,
  1300000000001 AS TenantId, NOW() AS CreatedAt, NOW() AS UpdatedAt,
  YellowThreshold, RedThreshold, FormulaExpr, FormulaPreview, FormulaRefs
FROM ado_smart_ops_kpi_master
WHERE TenantId = 0 AND ModuleCode = 'S5' AND MetricCode = 'S5_L1_004'
  AND @tgt_exists = 0;
