补交2026-11-18手机号专项三份工具脚本(UAT)——audit池手机与第二批文档掩码比对、refill存量515677行按新文档回刷、delete删除未中奖且无真实手机24892行;均干跑默认/--execute才写,含整行备份表可回滚,对应00cc714与b88088d两次操作

This commit is contained in:
jacobxu666
2026-11-25 11:14:44 +08:00
parent dfd26d7e4d
commit a620a5c033
3 changed files with 258 additions and 0 deletions
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
# xuchao: 只读审计——hhrs_lottery_pool.member_phone vs 《第二批年龄段25-40岁抽奖数据.xlsx》(2026-11-18 用户指令"比对手机不一致数量")
# 用法: python3 docs/tools_audit_phone_vs_doc_20261118.py # 纯只读,不写库不改文件
# 口径: 池按主键 id 关联文件 ID;池存掩码(前3+****+后4),文件明文按 11-10/11-17 既定白名单口径转掩码后比对;
# 文件手机非法/空 → 期望 NULL。分类统计不一致,并抽样展示。
import sys, os, re
import pandas as pd
SRC = os.path.expanduser('~/Downloads/第二批年龄段25-40岁抽奖数据.xlsx')
# 2026-11-18 文件为20列全量发卡明细:按位置取 col0=ID, col1=身份证, col2=姓名, col5=手机, col8=县区
F = pd.read_excel(SRC, dtype=str, usecols=[0, 1, 2, 5, 8]).fillna('')
F.columns = ['ID', '身份证', '姓名', '手机', '县区']
print('文件行数:', len(F))
assert F['ID'].astype(int).is_unique, '文件ID不唯一'
allowed = set()
allowed.update(f'13{d}' for d in range(10))
allowed.update(['140', '141', '144', '145', '146', '147', '148', '149'])
allowed.update(f'15{d}' for d in range(10) if d != 4)
allowed.update(['162', '165', '166', '167'])
allowed.update(['170', '171', '172', '173', '175', '176', '177', '178'])
allowed.update(f'18{d}' for d in range(10))
allowed.update(f'19{d}' for d in range(10) if d != 4)
def expect_mask(p):
return (p[:3] + '****' + p[7:11]) if re.fullmatch(r'\d{11}', p) and p[:3] in allowed else None
fmap = {int(i): expect_mask(p) for i, p in zip(F['ID'], F['手机'])}
n_valid = sum(1 for v in fmap.values() if v)
print(f'文件 {len(fmap)} 行: 白名单口径有效手机 {n_valid}, 期望NULL {len(fmap)-n_valid}')
os.environ['SETTLE_ENV'] = 'uat'
path = '/Users/jacobxu/Documents/Project/12301-dscp/docs/tools/settle_recompute_check.py'
src = open(path).read()
head = src.split("cur = conn.cursor(pymysql.cursors.DictCursor)", 1)[0] + "cur = conn.cursor(pymysql.cursors.DictCursor)"
ns = {'__name__': 'env'}
exec(compile(head, path, 'exec'), ns)
conn, cur = ns['conn'], ns['cur']
cur.execute("SELECT id, member_phone, created_time FROM hhrs_lottery_pool")
pool = cur.fetchall()
print('池总行数:', len(pool))
covered = [r for r in pool if r['id'] in fmap]
uncovered = len(pool) - len(covered)
print(f'文件覆盖池 {len(covered)} 行, 未覆盖(不在文件) {uncovered} 行')
cats = {'一致': 0, '掩码不同': 0, '池NULL但文件有效': 0, '池有值但文件应NULL': 0}
samples = {k: [] for k in cats if k != '一致'}
by_ct = {}
for r in covered:
exp = fmap[r['id']]
got = r['member_phone']
if got == exp:
cats['一致'] += 1
continue
if got is None and exp is not None:
k = '池NULL但文件有效'
elif got is not None and exp is None:
k = '池有值但文件应NULL'
else:
k = '掩码不同'
cats[k] += 1
if len(samples[k]) < 5:
samples[k].append((r['id'], got, exp))
for r in covered:
ct = str(r['created_time'])
by_ct.setdefault(ct, [0, 0])
by_ct[ct][1] += 1
if r['member_phone'] == fmap[r['id']]:
by_ct[ct][0] += 1
print('\n=== 比对结果(文件覆盖范围内) ===')
for k, v in cats.items():
print(f'{k}: {v}')
total_bad = sum(v for k, v in cats.items() if k != '一致')
print(f'不一致合计: {total_bad}')
print('\n按 created_time 分布(一致/总数):')
for ct, (ok, tot) in sorted(by_ct.items()):
print(f' {ct}: {ok}/{tot} (不一致 {tot-ok})')
print('\n抽样(池id, 池现值, 文件期望掩码):')
for k, ss in samples.items():
for s in ss:
print(f' [{k}] {s}')
conn.close()
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
# xuchao: 删除"未中奖且无真实手机"行(2026-11-18 用户最终口径:中奖者8000人全保留只同步手机[已一致无需动,20人NULL以文档为准];
# 未中奖且无真实手机者删除)。20个"池won=0但公示有名"的一期中奖者属中奖者,保留不改动。
# 用法: python3 docs/tools_delete_nophone_20261118.py # 干跑:核对目标量,不写
# python3 docs/tools_delete_nophone_20261118.py --execute # 整行备份+事务删除+自检+COMMIT(UAT=生产)
# 目标: created_time='2026-10-15 09:57:17' AND member_phone IS NULL AND won=0,排除20个公示中奖pool_id;
# 预期24,892行(=25,215 NULL手机 - 303已中奖 - 20公示保留)。不碰11-10批、中奖者、公示表。
# 备份: hhrs_lottery_pool_delbak_20261118(整行);回滚=INSERT INTO hhrs_lottery_pool SELECT * FROM 备份表。
import sys, os
EXECUTE = '--execute' in sys.argv
LEGACY_CT = '2026-10-15 09:57:17'
KEEP20 = [271705, 455355, 470658, 493004, 597303, 672481, 681391, 757339, 847426, 940646,
943507, 982987, 1192268, 1234479, 1264630, 1951332, 2007782, 2180844, 2197340, 2213244]
EXPECT_DEL, EXPECT_AFTER = 24892, 549678
os.environ['SETTLE_ENV'] = 'uat'
path = '/Users/jacobxu/Documents/Project/12301-dscp/docs/tools/settle_recompute_check.py'
src = open(path).read()
head = src.split("cur = conn.cursor(pymysql.cursors.DictCursor)", 1)[0] + "cur = conn.cursor(pymysql.cursors.DictCursor)"
ns = {'__name__': 'env'}
exec(compile(head, path, 'exec'), ns)
conn, cur = ns['conn'], ns['cur']
def one(sql):
cur.execute(sql)
return cur.fetchone()['c']
ph = ','.join(str(i) for i in KEEP20)
WHERE = (f"created_time='{LEGACY_CT}' AND member_phone IS NULL AND won=0 AND id NOT IN ({ph})")
n_target = one("SELECT COUNT(*) c FROM hhrs_lottery_pool WHERE " + WHERE)
# 交叉验证:目标行无任何公示引用
n_ref = one("SELECT COUNT(*) c FROM hhrs_winner w JOIN hhrs_lottery_pool p ON w.pool_id=p.id WHERE " +
WHERE.replace('created_time', 'p.created_time').replace('member_phone', 'p.member_phone')
.replace('won=0', 'p.won=0').replace('id NOT IN', 'p.id NOT IN'))
n_keep = one(f"SELECT COUNT(*) c FROM hhrs_lottery_pool WHERE id IN ({ph})")
# 既有悬空引用基线(历史遗留:一期1625+二轮3),本次不得新增
n_dang0 = one("SELECT COUNT(*) c FROM hhrs_winner w LEFT JOIN hhrs_lottery_pool p ON w.pool_id=p.id "
"WHERE w.pool_id IS NOT NULL AND p.id IS NULL")
print(f'目标 {n_target}(应{EXPECT_DEL}) | 目标行公示引用 {n_ref}(应0) | 20保留行在池 {n_keep}(应20) | 既有悬空基线 {n_dang0}')
assert n_target == EXPECT_DEL and n_ref == 0 and n_keep == 20, '预检不符,中止'
if not EXECUTE:
print('干跑通过,未写入。执行请加 --execute')
raise SystemExit
cur.execute("SHOW TABLES LIKE 'hhrs_lottery_pool_delbak_20261118'")
assert not cur.fetchall(), '备份表已存在,中止(防重复执行)'
cur.execute("CREATE TABLE hhrs_lottery_pool_delbak_20261118 AS SELECT * FROM hhrs_lottery_pool WHERE " + WHERE)
assert one("SELECT COUNT(*) c FROM hhrs_lottery_pool_delbak_20261118") == EXPECT_DEL, '备份行数不符'
print('整行备份表 hhrs_lottery_pool_delbak_20261118 已建:', EXPECT_DEL)
cur.execute("START TRANSACTION")
cur.execute("DELETE FROM hhrs_lottery_pool WHERE " + WHERE)
n_del = cur.rowcount
n_all = one("SELECT COUNT(*) c FROM hhrs_lottery_pool")
n_won = int(one("SELECT SUM(won) c FROM hhrs_lottery_pool"))
n_null = one(f"SELECT COUNT(*) c FROM hhrs_lottery_pool WHERE created_time='{LEGACY_CT}' AND member_phone IS NULL")
n_b10 = one("SELECT COUNT(*) c FROM hhrs_lottery_pool WHERE created_time>='2026-11-10 00:00:00'")
n_keep2 = one(f"SELECT COUNT(*) c FROM hhrs_lottery_pool WHERE id IN ({ph})")
n_ref2 = one("SELECT COUNT(*) c FROM hhrs_winner w LEFT JOIN hhrs_lottery_pool p ON w.pool_id=p.id "
"WHERE w.pool_id IS NOT NULL AND p.id IS NULL")
n_winpool = one("SELECT COUNT(DISTINCT w.pool_id) c FROM hhrs_winner w JOIN hhrs_lottery_pool p ON w.pool_id=p.id")
print(f'自检: 删{n_del}(应{EXPECT_DEL}) | 全池{n_all}(应{EXPECT_AFTER}) | won={n_won}(应5997) | '
f'存量NULL剩{n_null}(应323=303中奖+20保留) | 11-10批{n_b10}(应58893) | 20保留行{n_keep2}(应20) | '
f'在池中奖者{n_winpool}(应6372) | 公示悬空引用{n_ref2}(应{n_dang0}不新增)')
if (n_del, n_all, n_won, n_null, n_b10, n_keep2, n_winpool, n_ref2) == (EXPECT_DEL, EXPECT_AFTER, 5997, 323, 58893, 20, 6372, n_dang0):
conn.commit()
print('COMMIT 成功: 已删除未中奖且无真实手机行')
else:
conn.rollback()
print('自检未通过,已 ROLLBACK')
raise SystemExit(1)
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env python3
# xuchao: 存量手机回刷(2026-11-18 用户授权"存量515677行按新文档回刷")
# 用法: python3 docs/tools_refill_phone_20261118.py # 干跑:算变更量,不写
# python3 docs/tools_refill_phone_20261118.py --execute # 备份+事务回刷+全量自检+COMMIT(UAT=生产)
# 源: ~/Downloads/第二批年龄段25-40岁抽奖数据.xlsx(2026-11-18新版,20列全量发卡明细,col0=ID,col5=手机明文)
# 口径: 仅动存量(created_time='2026-10-15 09:57:17')515,677行;手机=白名单号段11位转掩码(前3+****+后4),非法/空→NULL;
# 预期变更515,673(掩码不同490,458+置NULL25,215),4行已一致不动。不碰11-10批58,893行、won、公示。
# 备份: hhrs_lottery_pool_phonebak_20261118(存量id+改前phone);回滚=按备份表整列还原。
import sys, os, re
import pandas as pd
EXECUTE = '--execute' in sys.argv
SRC = os.path.expanduser('~/Downloads/第二批年龄段25-40岁抽奖数据.xlsx')
LEGACY_CT = '2026-10-15 09:57:17'
EXPECT_LEGACY, EXPECT_CHG, EXPECT_NULL = 515677, 515673, 25215
F = pd.read_excel(SRC, dtype=str, usecols=[0, 5]).fillna('')
F.columns = ['ID', '手机']
assert F['ID'].astype(int).is_unique and len(F) == 532872, '文件ID应唯一且532,872行'
allowed = set()
allowed.update(f'13{d}' for d in range(10))
allowed.update(['140', '141', '144', '145', '146', '147', '148', '149'])
allowed.update(f'15{d}' for d in range(10) if d != 4)
allowed.update(['162', '165', '166', '167'])
allowed.update(['170', '171', '172', '173', '175', '176', '177', '178'])
allowed.update(f'18{d}' for d in range(10))
allowed.update(f'19{d}' for d in range(10) if d != 4)
def expect_mask(p):
return (p[:3] + '****' + p[7:11]) if re.fullmatch(r'\d{11}', p) and p[:3] in allowed else None
fmap = {int(i): expect_mask(p) for i, p in zip(F['ID'], F['手机'])}
os.environ['SETTLE_ENV'] = 'uat'
path = '/Users/jacobxu/Documents/Project/12301-dscp/docs/tools/settle_recompute_check.py'
src = open(path).read()
head = src.split("cur = conn.cursor(pymysql.cursors.DictCursor)", 1)[0] + "cur = conn.cursor(pymysql.cursors.DictCursor)"
ns = {'__name__': 'env'}
exec(compile(head, path, 'exec'), ns)
conn, cur = ns['conn'], ns['cur']
cur.execute("SELECT id, member_phone FROM hhrs_lottery_pool WHERE created_time=%s", (LEGACY_CT,))
legacy = {r['id']: r['member_phone'] for r in cur.fetchall()}
assert len(legacy) == EXPECT_LEGACY, f'存量 {len(legacy)} != {EXPECT_LEGACY}'
assert set(legacy) <= set(fmap), '文件未完全覆盖存量,中止'
changes = [(i, fmap[i]) for i in legacy if fmap[i] != legacy[i]]
n_null = sum(1 for _, v in changes if v is None)
print(f'存量 {len(legacy)} 行, 需变更 {len(changes)}(置NULL {n_null}), 已一致 {len(legacy)-len(changes)}')
assert len(changes) == EXPECT_CHG and n_null == EXPECT_NULL, '变更量与11-18审计不符,中止'
if not EXECUTE:
print('干跑通过,未写入。执行请加 --execute')
raise SystemExit
# ---- 备份表(DDL隐式提交,先行) ----
cur.execute("SHOW TABLES LIKE 'hhrs_lottery_pool_phonebak_20261118'")
assert not cur.fetchall(), '备份表已存在,中止(防重复执行覆盖备份)'
cur.execute(f"CREATE TABLE hhrs_lottery_pool_phonebak_20261118 AS "
f"SELECT id, member_phone FROM hhrs_lottery_pool WHERE created_time='{LEGACY_CT}'")
cur.execute("SELECT COUNT(*) c FROM hhrs_lottery_pool_phonebak_20261118")
assert cur.fetchone()['c'] == EXPECT_LEGACY, '备份行数不符'
print('备份表 hhrs_lottery_pool_phonebak_20261118 已建:', EXPECT_LEGACY)
# ---- staging 批量 UPDATE ----
cur.execute("DROP TABLE IF EXISTS hhrs_stg_phone_20261118")
cur.execute("CREATE TABLE hhrs_stg_phone_20261118 (id BIGINT PRIMARY KEY, new_phone VARCHAR(20))")
sql = "INSERT INTO hhrs_stg_phone_20261118 (id, new_phone) VALUES (%s,%s)"
for i in range(0, len(changes), 2000):
cur.executemany(sql, changes[i:i + 2000])
cur.execute("START TRANSACTION")
cur.execute("UPDATE hhrs_lottery_pool p JOIN hhrs_stg_phone_20261118 s ON p.id=s.id "
f"SET p.member_phone=s.new_phone WHERE p.created_time='{LEGACY_CT}' "
"AND NOT (p.member_phone <=> s.new_phone)")
n_upd = cur.rowcount
# ---- 事务内全量自检 ----
cur.execute("SELECT COUNT(*) c FROM hhrs_lottery_pool")
n_all = cur.fetchone()['c']
cur.execute("SELECT id, member_phone FROM hhrs_lottery_pool WHERE created_time=%s", (LEGACY_CT,))
after = {r['id']: r['member_phone'] for r in cur.fetchall()}
n_match = sum(1 for i, v in after.items() if v == fmap[i])
n_null_after = sum(1 for v in after.values() if v is None)
cur.execute("SELECT COUNT(*) c FROM hhrs_lottery_pool WHERE created_time>=%s", ('2026-11-10 00:00:00',))
n_1110 = cur.fetchone()['c']
cur.execute("SELECT SUM(won) w FROM hhrs_lottery_pool")
n_won = int(cur.fetchone()['w'])
print(f'自检: 更新{n_upd}(应{EXPECT_CHG}) | 全池{n_all}(应574570) | 存量与文档全量一致{n_match}(应{EXPECT_LEGACY}) | '
f'存量NULL{n_null_after}(应{EXPECT_NULL}) | 11-10批{n_1110}(应58893) | won={n_won}(应5997)')
if (n_upd, n_all, n_match, n_null_after, n_1110, n_won) == (EXPECT_CHG, 574570, EXPECT_LEGACY, EXPECT_NULL, 58893, 5997):
conn.commit()
print('COMMIT 成功: 存量手机已按新文档回刷')
else:
conn.rollback()
print('自检未通过,已 ROLLBACK')
raise SystemExit(1)
cur.execute("DROP TABLE hhrs_stg_phone_20261118")
print('staging 已清理;备份表保留待业务确认后清理')