103 lines
5.1 KiB
Python
103 lines
5.1 KiB
Python
#!/usr/bin/env python3
|
|
# xuchao: 9月底至1103已激活批次入抽奖池执行脚本——号段白名单过滤+事务导入+自检+COMMIT
|
|
# 用法: python3 docs/tools_import_activated_batch_20261110.py # 干跑,只算不写
|
|
# python3 docs/tools_import_activated_batch_20261110.py --execute # 执行入库(UAT=生产)
|
|
# 口径(2026-11-10 用户确认): 手机号必须为「3位白名单号段 + 4星 + 4位尾号」,不合格整行剔除并出对照表;
|
|
# 白名单号段: 130-139 | 140 141 144-149 | 150-159(除154) | 162 165 166 167 |
|
|
# 170-173 175-178 | 180-189 | 190-193 195-199 (共58段,未启用154/164/174/194等)
|
|
# 预期: 文件60,800行 → 合格58,893行入库、剔除1,907行;与池id交集必须为0;任一校验不过即中止回滚。
|
|
# 连接参数复用 12301-dscp/docs/tools/settle_recompute_check.py 的 SETTLE_ENV=uat 分支。
|
|
# 回滚(如业务要求撤批次): DELETE FROM hhrs_lottery_pool WHERE created_time >= '<本脚本输出的t0>'
|
|
# AND id BETWEEN 2852613 AND 3982068; -- 执行前先 SELECT COUNT 复核应=58893 再删
|
|
import sys, os, re
|
|
import pandas as pd
|
|
|
|
EXECUTE = '--execute' in sys.argv
|
|
XLSX = '/Users/jacobxu/Downloads/9月底至1103已激活数据.xlsx'
|
|
DOCS = os.path.dirname(os.path.abspath(__file__))
|
|
EXPECT_TOTAL, EXPECT_OK, EXPECT_REJ = 60800, 58893, 1907
|
|
|
|
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)
|
|
assert len(allowed) == 58
|
|
_pat = re.compile(r'^(\d{3})\*{4}\d{4}$')
|
|
|
|
def classify(p):
|
|
if p == '':
|
|
return '空值'
|
|
m = _pat.match(p)
|
|
if not m:
|
|
return '格式异常(非3+4星+4)'
|
|
if m.group(1) not in allowed:
|
|
return '号段不在白名单'
|
|
return '合格'
|
|
|
|
# ---- 读文件并按口径过滤 ----
|
|
df = pd.read_excel(XLSX, sheet_name='已激活明细', dtype=str).fillna('')
|
|
assert len(df) == EXPECT_TOTAL, f'明细行数 {len(df)} != 预期 {EXPECT_TOTAL}'
|
|
df['剔除原因'] = df['脱敏手机号'].map(classify)
|
|
ok = df[df['剔除原因'] == '合格'].copy()
|
|
rej = df[df['剔除原因'] != '合格'].copy()
|
|
assert len(ok) == EXPECT_OK and len(rej) == EXPECT_REJ, \
|
|
f'合格/剔除行数与确认口径不符: {len(ok)}/{len(rej)} != {EXPECT_OK}/{EXPECT_REJ}'
|
|
ids = [int(x) for x in ok['ID']]
|
|
assert len(set(ids)) == len(ids), '文件合格行 ID 存在重复'
|
|
rows = [(i, nm, ct, 0, idno, ph, 0) for i, nm, ct, idno, ph in
|
|
zip([int(x) for x in ok['ID']], ok['姓名'], ok['发卡地区'], ok['脱敏身份证'], ok['脱敏手机号'])]
|
|
rej[['ID', '姓名', '脱敏手机号', '脱敏身份证', '发卡地区', '剔除原因']].to_csv(
|
|
os.path.join(DOCS, '已激活批次_剔除对照_20261110.csv'), index=False)
|
|
print('文件行:', len(df), ' 合格:', len(ok), ' 剔除:', len(rej), '(对照表已写 docs/)')
|
|
print('剔除原因分布:', rej['剔除原因'].value_counts().to_dict())
|
|
|
|
# ---- 连库预检 ----
|
|
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 COUNT(*) c FROM hhrs_lottery_pool")
|
|
before = cur.fetchone()['c']
|
|
lo, hi = min(ids), max(ids)
|
|
cur.execute("SELECT id FROM hhrs_lottery_pool WHERE id BETWEEN %s AND %s", (lo, hi))
|
|
inter = set(ids) & {r['id'] for r in cur.fetchall()}
|
|
print(f'池现有行数: {before} 本批ID窗[{lo}..{hi}]内池行交集: {len(inter)}')
|
|
assert not inter, f'主键冲突,中止: {sorted(inter)[:10]}'
|
|
|
|
if not EXECUTE:
|
|
print('干跑通过,未写入。执行入库请加 --execute')
|
|
raise SystemExit
|
|
|
|
# ---- 事务导入 ----
|
|
cur.execute("SELECT NOW() n")
|
|
t0 = cur.fetchone()['n']
|
|
print('批次时间戳 t0 =', t0)
|
|
sql = ("INSERT INTO hhrs_lottery_pool "
|
|
"(id, member_name, county, batch_no, member_identity_no, member_phone, won) "
|
|
"VALUES (%s,%s,%s,%s,%s,%s,%s)")
|
|
for i in range(0, len(rows), 2000):
|
|
cur.executemany(sql, rows[i:i + 2000])
|
|
cur.execute("SELECT COUNT(*) c FROM hhrs_lottery_pool WHERE created_time >= %s", (t0,))
|
|
n_new = cur.fetchone()['c']
|
|
cur.execute("SELECT COUNT(*) c FROM hhrs_lottery_pool")
|
|
n_all = cur.fetchone()['c']
|
|
cur.execute("SELECT COUNT(*) c FROM hhrs_lottery_pool WHERE created_time >= %s "
|
|
"AND member_phone REGEXP '^[0-9]{3}\\\\*{4}[0-9]{4}$'", (t0,))
|
|
n_fmt = cur.fetchone()['c']
|
|
print('事务内自检: 本批行数', n_new, ' 全表行数', n_all, ' 本批手机号格式合格率', f'{n_fmt}/{n_new}')
|
|
if n_new == len(rows) and n_all == before + len(rows) and n_fmt == n_new:
|
|
conn.commit()
|
|
print('COMMIT 成功: 池', before, '->', n_all)
|
|
else:
|
|
conn.rollback()
|
|
print('自检未通过,已 ROLLBACK,未入库')
|
|
raise SystemExit(1)
|