feat(XQ0014): 实现社保增减员全流程与配套工具
新增: - 社保增减员主流程import_add.py - 审核结果核查脚本check_review.py - 专用登录模块sb_login.py - 验证码/SSO调试探针 - 完整测试记录文档 修复: - XQ0002过滤规则新增虚拟大区排除 - 启用XQ0002数据校验开关
This commit is contained in:
@@ -0,0 +1,394 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: check_review.py
|
||||
@Description: XQ0014 重庆社保系统增减员办理(核查-回盘)—— 单文件自包含版
|
||||
增员申报(import_add.py)提交后,平台审核存在滞后。本脚本对源名单中
|
||||
「办理状态=待审核」的人员所在参保单位,逐个登录重庆人社政务平台核查审核结论:
|
||||
|
||||
流程(每个参保单位):
|
||||
1. 登录(复用同目录 sb_login,法人用户 + 图形验证码)
|
||||
2. 单位办事 → 城保参保单位人员增加 → 在线办理(与增员同一入口)
|
||||
3. 左侧菜单点「已申报查询」→ 读表格第一条「当前状态」
|
||||
非「已办结」→ 跳过该单位(审核还没走完)
|
||||
4. 「已办结」→ 点「查看」,监听 queryYsbWs04orWs01 接口拿查询参数
|
||||
(asl001/aaa121/aab001),再用页内 XHR 重放接口翻页取全量(防分页漏数据)
|
||||
5. 按 aac002 证件号码匹配本单位「待审核」人员,回写源名单:
|
||||
- 审核通过 → 办理状态 = 参保成功
|
||||
- 不通过 + 400系统错误 → 办理状态 = 空(回到待办,重新执行8号需求制作名单后再次增员)
|
||||
- 不通过 + 其它原因 → 办理状态 = 参保失败,审核意见追加写备注(不覆盖)
|
||||
6. 台账回写:与 import_add 同一套 JSON 缓存 + 运行结束统一回写 Excel 机制
|
||||
|
||||
依赖(与 import_add 相同):pandas openpyxl DrissionPage python-dotenv ddddocr
|
||||
运行:python check_review.py
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse, parse_qsl, urlencode
|
||||
|
||||
# ---- 单文件运行支持:本目录加入 sys.path,复用同目录 import_add / sb_login ----
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
if str(_HERE) not in sys.path:
|
||||
sys.path.insert(0, str(_HERE))
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动。\n请先执行安装:\n pip install pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}")
|
||||
|
||||
import import_add # 同目录:复用名单/台账读取、登录后页面导航、回写缓存机制
|
||||
import sb_login
|
||||
|
||||
# ==================== 1. 配置 ====================
|
||||
CHECK_STATUS = "待审核" # 核查范围:办理状态为该值的人员
|
||||
DONE_STATUS = "已办结" # 已申报查询里第一条的该状态才继续查看
|
||||
PASS_STATUS = "参保成功" # 审核通过 → 办理状态
|
||||
FAIL_STATUS = "参保失败" # 审核不通过(非系统错误)→ 办理状态
|
||||
ERR_400_KEYWORD = "status 400" # aae111 含该关键字 = 系统错误,需重新增员
|
||||
MENU_QUERY = "已申报查询" # 业务页左侧菜单
|
||||
API_KEYWORD = "queryYsbWs04orWs01" # 已申报明细查询接口(监听 + 重放)
|
||||
PAGE_SIZE = 10 # 重放接口每页条数(与平台默认一致,翻页取全量)
|
||||
MAX_PAGES = 50 # 重放翻页上限(防死循环)
|
||||
CHECK_LIMIT = None # 每次运行最多核查的单位数(None=不限制)
|
||||
RUN_400_CLEAR = True # 400系统错误:True=清空办理状态回到待办(重新走8号+增员)
|
||||
|
||||
|
||||
# ==================== 2. 核查任务读取 ====================
|
||||
def load_check_tasks(exclude_ids=frozenset()):
|
||||
"""读取源名单,筛选 办理状态=待审核 的行,按参保单位分组。
|
||||
|
||||
返回 [{unit, count, cids(set)}];同时把源文件信息写回 import_add 全局
|
||||
(flush_writeback 依赖 SOURCE_FILE_USED / SOURCE_SHEET_USED)。
|
||||
exclude_ids:上次运行已回写的人员身份证号(防重复核查)。
|
||||
"""
|
||||
source_file = import_add._latest_file(import_add.SOURCE_DIR, import_add.SOURCE_GLOB)
|
||||
now = datetime.now()
|
||||
xl = pd.ExcelFile(source_file)
|
||||
sheet_name = import_add._pick_sheet(xl, f"{now:%Y%m}参保名单", "参保名单")
|
||||
print(f"源名单:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||||
import_add.SOURCE_FILE_USED, import_add.SOURCE_SHEET_USED = source_file, sheet_name
|
||||
|
||||
df = pd.read_excel(source_file, sheet_name=sheet_name, header=2) # 表头第3行
|
||||
status = df[import_add.STATUS_COL].astype(str).str.strip()
|
||||
mask = (
|
||||
(df[import_add.REGION_COL].astype(str).str.strip() == import_add.REGION)
|
||||
& (df[import_add.TYPE_COL].astype(str).str.strip() == import_add.OPERATION_TYPE)
|
||||
& (status == CHECK_STATUS)
|
||||
)
|
||||
sub = df[mask].copy()
|
||||
if exclude_ids and '身份证号码' in sub.columns:
|
||||
before = len(sub)
|
||||
ref = [import_add._norm_id(x) for x in exclude_ids]
|
||||
sub = sub[~sub['身份证号码'].map(lambda v: import_add._id_hit(import_add._norm_id(v), ref))]
|
||||
dropped = before - len(sub)
|
||||
if dropped:
|
||||
print(f" 已排除 {dropped} 行上次运行已回写的人员(防重复核查)")
|
||||
if sub.empty:
|
||||
print(f"没有筛选到数据({import_add.REGION} ∩ {import_add.OPERATION_TYPE} ∩ 办理状态={CHECK_STATUS})")
|
||||
return []
|
||||
|
||||
tasks = []
|
||||
for unit, g in sub.groupby(sub[import_add.UNIT_COL].astype(str).str.strip()):
|
||||
cids = {import_add._norm_id(v) for v in g['身份证号码']}
|
||||
cids.discard('')
|
||||
tasks.append({"unit": unit, "count": len(cids), "cids": cids})
|
||||
tasks.sort(key=lambda t: t['unit'])
|
||||
print(f"核查范围:共 {sum(t['count'] for t in tasks)} 人 / {len(tasks)} 个参保单位(办理状态={CHECK_STATUS})")
|
||||
return tasks
|
||||
|
||||
|
||||
# ==================== 3. 网页操作 ====================
|
||||
def _open_query_menu(tab):
|
||||
"""业务页左侧菜单点「已申报查询」,等记录表(表头含 当前状态/操作)出现。"""
|
||||
import_add._click_any(tab, [f'tag:li@@text()={MENU_QUERY}', f'text={MENU_QUERY}'],
|
||||
f'左侧菜单「{MENU_QUERY}」')
|
||||
import_add._dismiss_popups(tab)
|
||||
deadline = time.time() + 15
|
||||
while time.time() < deadline:
|
||||
for tb in tab.eles('tag:table'):
|
||||
try:
|
||||
ths = [th.text.strip() for th in tb.eles('tag:th')]
|
||||
except Exception:
|
||||
continue
|
||||
if '当前状态' in ths and '操作' in ths:
|
||||
return tb
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError(f"点击「{MENU_QUERY}」后未出现申报记录表")
|
||||
|
||||
|
||||
def _read_first_row(table):
|
||||
"""读申报记录表第一条:返回 (当前状态, 查看按钮元素)。无记录返回 (None, None)。"""
|
||||
row = table.ele('css:tbody tr.ant-table-row', timeout=3) \
|
||||
or table.ele('css:tbody tr', timeout=1)
|
||||
if row is None:
|
||||
return None, None
|
||||
ths = [th.text.strip() for th in table.eles('tag:th')]
|
||||
i_status = ths.index('当前状态')
|
||||
tds = [td.text.strip() for td in row.eles('tag:td')]
|
||||
status = tds[i_status] if len(tds) > i_status else ''
|
||||
view = None
|
||||
for sel in ('tag:a@@text()=查看', 'tag:span@@text()=查看', 'text=查看'):
|
||||
try:
|
||||
view = row.ele(sel, timeout=1)
|
||||
except Exception:
|
||||
view = None
|
||||
if view:
|
||||
break
|
||||
return status, view
|
||||
|
||||
|
||||
def _capture_query_url(page, tab, view):
|
||||
"""点「查看」并监听明细查询接口,返回请求 URL。
|
||||
明细可能在当前 tab 打开也可能新开 tab:两个方向都轮询监听。"""
|
||||
before = set(page.tab_ids)
|
||||
tab.listen.start(API_KEYWORD)
|
||||
new_tabs = []
|
||||
packet = None
|
||||
try:
|
||||
try:
|
||||
view.click()
|
||||
except Exception:
|
||||
view.click(by_js=True)
|
||||
deadline = time.time() + 25
|
||||
while time.time() < deadline and packet is None:
|
||||
# 新开 tab 也挂上监听(明细页可能新 tab 加载接口)
|
||||
for tid in [i for i in page.tab_ids if i not in before and i not in new_tabs]:
|
||||
new_tabs.append(tid)
|
||||
try:
|
||||
page.get_tab(tid).listen.start(API_KEYWORD)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
packet = tab.listen.wait(count=1, timeout=2)
|
||||
except Exception:
|
||||
packet = None
|
||||
if packet is None:
|
||||
for tid in new_tabs:
|
||||
try:
|
||||
packet = page.get_tab(tid).listen.wait(count=1, timeout=0.5)
|
||||
except Exception:
|
||||
packet = None
|
||||
if packet:
|
||||
break
|
||||
finally:
|
||||
for t in [tab] + [page.get_tab(tid) for tid in new_tabs if tid in page.tab_ids]:
|
||||
try:
|
||||
t.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
if not packet:
|
||||
raise RuntimeError("点击查看后未监听到明细查询接口(queryYsbWs04orWs01)")
|
||||
url = packet.request.url
|
||||
print(f" 已捕获明细接口:{url[:100]}...")
|
||||
return url
|
||||
|
||||
|
||||
def _fetch_via_xhr(tab, url):
|
||||
"""页内同步 XHR GET(自带登录态 cookies),返回响应文本。"""
|
||||
js = ("const xhr=new XMLHttpRequest();"
|
||||
"xhr.open('GET',arguments[0],false);"
|
||||
"xhr.setRequestHeader('Accept','application/json, text/javascript');"
|
||||
"xhr.send();return xhr.responseText;")
|
||||
return tab.run_js(js, url)
|
||||
|
||||
|
||||
def _replay_query_all(tab, captured_url):
|
||||
"""用捕获的请求参数重放接口翻页,取全量明细行。
|
||||
返回 [{name, cid, conclusion, opinion}, ...](字段取 aac003/aac002/aae110s/aae111)。"""
|
||||
parsed = urlparse(captured_url)
|
||||
base_params = [(k, v) for k, v in parse_qsl(parsed.query, keep_blank_values=True)
|
||||
if k != 'pageIndex']
|
||||
root = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
|
||||
rows, total = [], None
|
||||
for idx in range(MAX_PAGES):
|
||||
params = base_params + [('pageIndex', json.dumps(
|
||||
{"pageIndex": idx, "pageSize": PAGE_SIZE}, separators=(',', ':')))]
|
||||
full = f"{root}?{urlencode(params)}"
|
||||
raw = _fetch_via_xhr(tab, full)
|
||||
if not raw:
|
||||
raise RuntimeError(f"接口重放第 {idx + 1} 页返回空")
|
||||
payload = json.loads(raw)
|
||||
data = payload.get('data') or {}
|
||||
items = data.get('data') or []
|
||||
if total is None:
|
||||
total = data.get('total')
|
||||
rows.extend(items)
|
||||
print(f" 接口重放第 {idx + 1} 页:取到 {len(items)} 条(累计 {len(rows)}/{total})")
|
||||
if not items or (total is not None and len(rows) >= total):
|
||||
break
|
||||
results = []
|
||||
for it in rows:
|
||||
results.append({
|
||||
"name": str(it.get('aac003') or '').strip(),
|
||||
"cid": import_add._norm_id(it.get('aac002')),
|
||||
"conclusion": str(it.get('aae110s') or '').strip(),
|
||||
"opinion": str(it.get('aae111') or '').strip(),
|
||||
})
|
||||
return results
|
||||
|
||||
|
||||
# ==================== 4. 结论回写 ====================
|
||||
def build_writeback(results, task_cids):
|
||||
"""按回写规则处理明细,返回 (status_map, remark_map, log_lines)。
|
||||
只处理本单位「待审核」人员(证件号码精确匹配),其余仅记录日志。"""
|
||||
status_map, remark_map, logs = {}, {}, []
|
||||
for r in results:
|
||||
if not r['cid'] or r['cid'] not in task_cids:
|
||||
continue
|
||||
concl, opinion = r['conclusion'], r['opinion']
|
||||
line = f" {r['name']}({r['cid']}):{concl}"
|
||||
if concl == '审核通过':
|
||||
status_map[r['cid']] = PASS_STATUS
|
||||
line += f" → 办理状态={PASS_STATUS}"
|
||||
elif concl == '不通过':
|
||||
if ERR_400_KEYWORD in opinion:
|
||||
# 系统错误:清空办理状态回到待办,重新执行8号需求制作名单后再次增员
|
||||
if RUN_400_CLEAR:
|
||||
status_map[r['cid']] = ""
|
||||
line += " → 400系统错误,办理状态已清空(重新走8号+增员)"
|
||||
else:
|
||||
status_map[r['cid']] = FAIL_STATUS
|
||||
remark_map[r['cid']] = opinion or '审核不通过'
|
||||
line += f" → 办理状态={FAIL_STATUS},备注追加:{opinion[:60]}"
|
||||
else:
|
||||
line += " → 非终态结论,跳过"
|
||||
logs.append(line)
|
||||
return status_map, remark_map, logs
|
||||
|
||||
|
||||
# ==================== 5. 单个单位完整核查 ====================
|
||||
def do_unit_check(task):
|
||||
"""登录后的完整核查流程。返回结果 dict(JSON 安全)。"""
|
||||
page = sb_login.LAST_SESSION.get('page')
|
||||
work_tab = sb_login.LAST_SESSION.get('tab')
|
||||
if page is None or work_tab is None:
|
||||
return {"success": False, "message": "无有效登录会话"}
|
||||
|
||||
res = {"success": False, "checked": 0, "passed": 0, "failed": 0,
|
||||
"redo400": 0, "skipped": False}
|
||||
try:
|
||||
import_add._shot(work_tab, "c1_workbench")
|
||||
biz_tab = import_add._open_business_page(page, work_tab)
|
||||
import_add._dismiss_popups(biz_tab)
|
||||
_shot_c(biz_tab, "c2_biz_page")
|
||||
|
||||
table = _open_query_menu(biz_tab)
|
||||
_shot_c(biz_tab, "c3_query_list")
|
||||
status, view = _read_first_row(table)
|
||||
if not status:
|
||||
res.update(success=True, skipped=True, message="已申报查询无记录,跳过")
|
||||
return res
|
||||
if status != DONE_STATUS:
|
||||
res.update(success=True, skipped=True, message=f"第一条状态「{status}」非{DONE_STATUS},跳过")
|
||||
return res
|
||||
print(f" 第一条状态:{status},点击查看读取审核结论")
|
||||
|
||||
url = _capture_query_url(page, biz_tab, view)
|
||||
results = _replay_query_all(biz_tab, url)
|
||||
_shot_c(biz_tab, "c4_detail_fetched")
|
||||
if not results:
|
||||
res.update(success=True, message="明细接口返回 0 条,跳过")
|
||||
return res
|
||||
|
||||
status_map, remark_map, logs = build_writeback(results, task['cids'])
|
||||
for line in logs:
|
||||
print(line)
|
||||
if status_map or remark_map:
|
||||
import_add.writeback_source(status_map, remark_map)
|
||||
res.update(
|
||||
success=True,
|
||||
checked=len([r for r in results if r['cid'] in task['cids']]),
|
||||
passed=len([v for v in status_map.values() if v == PASS_STATUS]),
|
||||
failed=len([v for v in status_map.values() if v == FAIL_STATUS]),
|
||||
redo400=len([v for v in status_map.values() if v == ""]),
|
||||
message=(f"核查{len(results)}条,回写 {len(status_map or remark_map)} 人"
|
||||
f"(通过{res['passed']} 失败{res['failed']} 400重办{res['redo400']})"))
|
||||
return res
|
||||
except Exception as e:
|
||||
res["message"] = f"核查异常:{e}"
|
||||
return res
|
||||
|
||||
|
||||
def _shot_c(tab, name):
|
||||
"""核查流程调试截图(沿用 import_add 的 DEBUG_MODE 开关,前缀 c 区分)。"""
|
||||
import_add._shot(tab, name)
|
||||
|
||||
|
||||
# ==================== 6. 逐单位登录 + 核查 ====================
|
||||
def process_units(tasks, accounts):
|
||||
"""逐参保单位:登录 → 已申报查询核查 → 回写。每账号办完清 cookies 关浏览器。"""
|
||||
results = []
|
||||
for i, task in enumerate(tasks, 1):
|
||||
print(f"\n========== [{i}/{len(tasks)}] {task['unit']}({task['count']}人待审核)==========")
|
||||
acc = accounts.get(task['unit'])
|
||||
try:
|
||||
login_res = sb_login.main({"username": acc["username"], "password": acc["password"]})
|
||||
except Exception as e:
|
||||
login_res = {"success": False, "message": f"登录调用异常:{e}"}
|
||||
print(f"登录结果:{login_res.get('message')}")
|
||||
try:
|
||||
if login_res.get("success"):
|
||||
web_res = do_unit_check(task)
|
||||
print(f"核查结果:{web_res.get('message')}")
|
||||
results.append({**task, **web_res})
|
||||
else:
|
||||
results.append({**task, "success": False, "message": login_res.get("message", "")})
|
||||
finally:
|
||||
sb_login.close_session()
|
||||
return results
|
||||
|
||||
|
||||
# ==================== 7. 主流程 ====================
|
||||
def run():
|
||||
"""主流程:恢复缓存 → 读待审核名单 → 取号 → 预检 → 逐单位登录核查 → 统一回写。"""
|
||||
recovered_ids = import_add._load_ckpt()
|
||||
tasks = load_check_tasks(exclude_ids=recovered_ids)
|
||||
if recovered_ids:
|
||||
print("\n检测到上次未回写的内容,先统一回写:")
|
||||
try:
|
||||
import_add.flush_writeback()
|
||||
except Exception as e:
|
||||
print(f"恢复回写失败(缓存保留,下次启动重试):{e}")
|
||||
if not tasks:
|
||||
return {"success": True, "message": "无待核查数据", "total": 0, "done": 0}
|
||||
|
||||
accounts = import_add.load_accounts([t['unit'] for t in tasks])
|
||||
# 预检:账号齐备才继续(与增员一致的严格预检)
|
||||
errors = []
|
||||
for t in tasks:
|
||||
acc = accounts.get(t['unit'])
|
||||
if acc is None:
|
||||
errors.append(f"[{t['unit']}] 台账未匹配")
|
||||
elif not acc['username'] or not acc['password']:
|
||||
errors.append(f"[{t['unit']}] 账号或密码缺失")
|
||||
if errors:
|
||||
print("\n预检未通过:")
|
||||
for e in errors:
|
||||
print(f" - {e}")
|
||||
return {"success": False, "message": "预检未通过,详见日志", "total": len(tasks), "done": 0}
|
||||
|
||||
todo = tasks[:CHECK_LIMIT]
|
||||
results = process_units(todo, accounts)
|
||||
try:
|
||||
import_add.flush_writeback()
|
||||
except Exception as e:
|
||||
print(f"回写失败:{e}")
|
||||
ok = [r for r in results if r["success"]]
|
||||
fail = [r for r in results if not r["success"]]
|
||||
skip = [r for r in ok if r.get("skipped")]
|
||||
print(f"\n========== 汇总 ==========")
|
||||
print(f"核查完成 {len(ok) - len(skip)} 家,跳过(未办结/无记录){len(skip)} 家,失败 {len(fail)} 家")
|
||||
for r in fail:
|
||||
print(f" ✗ {r['unit']}:{r.get('message', '')}")
|
||||
return {"success": not fail, "message": f"完成{len(ok) - len(skip)}/跳过{len(skip)}/失败{len(fail)}",
|
||||
"total": len(results), "done": len(ok) - len(skip)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(run())
|
||||
Reference in New Issue
Block a user