-- ===========================================================================
-- 1.0.442 · verify  S5 MissedPrint 租户归属回填
--
-- 契约（AutoVersionUpdate.RunVerifyScriptIfExists）：逐条执行、取首行首列、
-- 交 IsTruthy 判定，不真即抛。故：禁止 SET @var；每条语句自包含；
-- 每条返回「通过为真」的标量（用 = 期望值 得 1/0），不得返回错误条数；
-- 一条语句一个断言；文件以最后一条 SQL 的分号结束。
-- ===========================================================================

-- 01 · 全部标签都有租户归属（写路径 + 回填共同保证）
SELECT COUNT(*) = 0
FROM MissedPrint
WHERE tenant_id IS NULL OR tenant_id = 0;

-- 02 · 归属与唯一 SET 源 scm_shd.tenant_id 零矛盾
SELECT COUNT(*) = 0
FROM MissedPrint m
JOIN (SELECT shddh, MIN(tenant_id) AS tenant_id
      FROM scm_shd
      GROUP BY shddh
      HAVING COUNT(DISTINCT tenant_id) = 1) d ON d.shddh = m.ShipperNbr
WHERE IFNULL(m.tenant_id, 0) <> d.tenant_id;

-- 03 · 与独立推导 CreateUser → SysUser.TenantId 零矛盾（交叉验证，非 SET 源）
SELECT COUNT(*) = 0
FROM MissedPrint m
JOIN (SELECT Account, MIN(TenantId) AS TenantId
      FROM SysUser
      GROUP BY Account
      HAVING COUNT(DISTINCT TenantId) = 1) u ON u.Account = m.CreateUser
WHERE IFNULL(m.tenant_id, 0) <> u.TenantId;

-- 04 · 回填基线快照（2026-09-01 实测 DRY-RUN）：合计 152
SELECT (SELECT COUNT(*) FROM MissedPrint) = 152;

-- 05 · 回填基线快照：AIDOP 租户 797403760988229 = 104
SELECT (SELECT COUNT(*) FROM MissedPrint WHERE tenant_id = 797403760988229) = 104;

-- 06 · 回填基线快照：UAT 租户 838257186181189 = 48
SELECT (SELECT COUNT(*) FROM MissedPrint WHERE tenant_id = 838257186181189) = 48;

-- 07 · 两个租户之外不得出现第三方归属
SELECT COUNT(*) = 0
FROM MissedPrint
WHERE tenant_id NOT IN (797403760988229, 838257186181189);
