Files
37duAutomation/workflows/XQ0001-0100/XQ0014 社保系统增减员办理/check_review.py
T
puddy a66006115a fix: 优化社保增减员回盘打印的菜单跳转逻辑并更新插件版本
优化回盘打印的菜单跳转逻辑,移除冗余的当前页尝试,调整异常处理顺序以适配页面变化;同步更新插件版本至1.0.3
2026-10-08 11:52:20 +08:00

627 lines
30 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- 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. 回盘打印:每个账号核查完都下载回盘表到 DISK_DIR
(人员增减申请回盘表_单位_下载日期.xlsx),核对养老/失业/医疗/工伤/生育
五项参保状态:全「参保缴费」→ 备注追加个人编号;否则备注追加个人编号 +
异常字段名及内容(都是追加,不覆盖)
7. 台账回写:与 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" # 已申报明细查询接口(监听 + 重放)
API_UNIT_INFO = ("https://ggfw.rlsbj.cq.gov.cn/onlinehall/declare/server/gourd/"
"cloud/ggfw/declare/query/DwCx/dwyl/getAab001") # 单位信息接口(页面加载完成标志)
MENU_PAGE_URL = ("https://ggfw.rlsbj.cq.gov.cn/onlinehall/nethall/pc/cqzhrs/"
"onlineoffice/OdCommon") # 左侧菜单页(刷新/直跳即可回到菜单)
PAGE_SIZE = 10 # 重放接口每页条数(与平台默认一致,翻页取全量)
MAX_PAGES = 50 # 重放翻页上限(防死循环)
CHECK_LIMIT = None # 每次运行最多核查的单位数(None=不限制)
RUN_400_CLEAR = True # 400系统错误:True=运行结束后统一清空办理状态回待办(重新走8号+增员)
# ---- 回盘打印下载与核对 ----
DISK_DIR = r"D:\资料\人资\重庆社保增减员办理\回盘打印" # 回盘文件根目录(按参保类型分子目录)
HUIPAN_SUBS = {"新参保": "新参保-增员", "转移参保": "转移参保-增员"} # 参保类型 → 回盘子目录
REPLAY_PREFIX = "人员增减申请回盘表" # 保存文件名:前缀_单位_日期.xlsx
INS_STATUSES = ["养老参保状态", "失业参保状态", "医疗参保状态",
"工伤参保状态", "生育参保状态"] # 需核对的三险五项状态列
INS_OK = "参保缴费" # 正常状态值
# ==================== 2. 核查任务读取 ====================
def load_check_tasks(exclude_ids=frozenset()):
"""读取源名单,筛选 办理状态=待审核 的行,按参保类型+参保单位分组。
返回 [{unit, type, count, cids(set)}](type=参保类型,回盘文件按类型分目录存放);
同时把源文件信息写回 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().isin(import_add.OPERATION_TYPES))
& (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} ∩ {'/'.join(import_add.OPERATION_TYPES)} "
f"∩ 办理状态={CHECK_STATUS})")
return []
tasks = []
sub["_unit"] = sub[import_add.UNIT_COL].astype(str).str.strip()
sub["_type"] = sub[import_add.TYPE_COL].astype(str).str.strip()
for (unit, t), g in sub.groupby(["_unit", "_type"]):
cids = {import_add._norm_id(v) for v in g['身份证号码']}
cids.discard('')
tasks.append({"unit": unit, "type": t, "count": len(cids), "cids": cids})
tasks.sort(key=lambda x: (x['unit'], x['type']))
print(f"核查范围:共 {sum(t['count'] for t in tasks)} 人 / "
f"{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 _wait_unit_loaded(tab, unit_name, timeout=40):
"""等业务页单位信息加载完成:轮询 getAab001 接口直到返回本单位数据。
该接口没返回时页面没加载出单位,后续已申报查询/回盘打印都拿不到数据。
接口轮询失败但页面已出现单位名时也视为加载成功(可能错过响应窗口)。
返回 data[0](含 aab001、aab004 平台单位全称),页面已加载但接口拿不到时返回 {},超时返回 None。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
raw = _fetch_via_xhr(tab, API_UNIT_INFO)
data = (json.loads(raw).get('data') or [None])[0]
if data and data.get('aab001'):
print(f" 单位信息已加载:{data.get('aab004')}(aab001={data.get('aab001')})")
return data
except Exception:
pass
# 接口没拿到但页面已经出现单位名 → 页面其实加载完了,不必再等
try:
if tab.ele(f'text:{unit_name}', timeout=0.5):
print(f" 页面已显示单位「{unit_name}」,视为加载完成(接口轮询未取到全称)")
return {}
except Exception:
pass
time.sleep(1)
return None
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(),
})
# 平台登记的参保单位全称(aab004),用于回盘文件命名
unit_full = ""
for it in rows:
v = str(it.get('aab004') or '').strip()
if v:
unit_full = v
break
return results, unit_full
# ==================== 4. 结论回写 ====================
def build_writeback(results, task_cids, unit_name):
"""按回写规则处理明细,返回 (status_map, remark_map, redo400_list, log_lines)。
只处理本单位「待审核」人员(证件号码精确匹配),其余仅记录日志。
400系统错误不立即清状态:先记录,运行结束后统一清空办理状态回待办再新增。"""
status_map, remark_map, redo400, 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:
# 系统错误:仅记录,运行结束后统一清空办理状态回待办重新增员
if RUN_400_CLEAR:
redo400.append({"cid": r['cid'], "name": r['name'], "unit": unit_name})
line += " → 400系统错误,已记录(结束后统一清状态回待办重新增员)"
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, redo400, logs
# ==================== 4b. 回盘打印下载与核对 ====================
def _clean_cell(v):
"""单元格值转干净字符串:浮点整数去掉 .0,其余去首尾空白。"""
if v is None:
return ""
if isinstance(v, float) and v.is_integer():
return str(int(v))
return str(v).strip()
def _download_huipan(page, biz_tab, unit, op_type):
"""左侧菜单「回盘打印」→ 页内「回盘打印」按钮,等下载完成后重命名为规范文件名。
按参保类型存入 回盘打印/<类型>-增员/ 子目录。返回保存的文件 Path。"""
save_dir = Path(DISK_DIR) / HUIPAN_SUBS.get(op_type, "新参保-增员")
save_dir.mkdir(parents=True, exist_ok=True)
target = save_dir / f"{REPLAY_PREFIX}_{unit}_{datetime.now():%Y%m%d}.xlsx"
menu_sel = ['tag:li@@text()=回盘打印', 'text=回盘打印']
try:
# 点「查看」后跳到明细详情页,左侧菜单不可见:直接跳 OdCommon 菜单页
print(" 直跳菜单页进回盘打印...")
biz_tab.get(MENU_PAGE_URL)
time.sleep(2)
import_add._click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」(菜单页)')
except Exception:
# 直跳也不行:重开业务页再点(最后兜底)
biz_tab = import_add._open_business_page(page, sb_login.LAST_SESSION['tab'])
import_add._dismiss_popups(biz_tab)
import_add._click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」(重开业务页)')
import_add._dismiss_popups(biz_tab)
# 页内「回盘打印」按钮(menu li 已处理,这里只找按钮/链接)。
# 不放 tag:span 候选:左侧菜单项是 li>span 结构,内容区未渲染时会误抓
# 菜单 span 重点一次菜单,下载不触发(减员版实测踩过的坑)
btn = None
for sel in ('tag:button@@text()=回盘打印', 'tag:a@@text()=回盘打印'):
try:
btn = biz_tab.ele(sel, timeout=2)
except Exception:
btn = None
if btn:
break
if btn is None:
raise RuntimeError("未找到页内「回盘打印」按钮")
biz_tab.set.download_path(str(save_dir))
before = {f.name for f in save_dir.iterdir() if f.is_file()}
try:
btn.click()
except Exception:
btn.click(by_js=True)
# 轮询等下载:新文件出现且大小连续2秒稳定(最多90秒)
new_file, last_size, stable = None, -1, 0
deadline = time.time() + 90
while time.time() < deadline:
time.sleep(1)
files = [f for f in save_dir.iterdir() if f.is_file() and f.name not in before
and f.suffix.lower() not in ('.crdownload', '.tmp')]
if not files:
stable, last_size = 0, -1
continue
f = max(files, key=lambda x: x.stat().st_mtime)
size = f.stat().st_size
if size > 0 and size == last_size:
stable += 1
if stable >= 2:
new_file = f
break
else:
stable = 0
last_size = size
if new_file is None:
raise RuntimeError("点击回盘打印后90秒内未检测到新下载文件")
os.replace(new_file, target) # 同名覆盖,保证文件名=回盘表_单位_日期.xlsx
return target
def _verify_huipan(filepath, task_cids):
"""读回盘表(表头在第2行),按身份证号核对五项参保状态,生成备注回写内容。
同人多条记录:取参保缴费数量最多的那条(并列取先出现的)。
返回 (remark_map, logs)。"""
df = pd.read_excel(filepath, header=1)
df.columns = [str(c).strip() for c in df.columns]
need = ['个人编号', '身份证号'] + INS_STATUSES
missing = [c for c in need if c not in df.columns]
if missing:
raise RuntimeError(f"回盘表缺少列:{missing}")
remarks, logs = {}, []
for cid in task_cids:
rows = df[df['身份证号'].map(
lambda v: import_add._id_hit(import_add._norm_id(_clean_cell(v)), [cid]))]
if rows.empty:
remarks[cid] = "未查询到回盘记录"
logs.append(f" 证件{cid}:回盘表中未找到记录 → 备注追加「未查询到回盘记录」")
continue
# 同人多条记录:取参保缴费数量最多的那条(并列取先出现的)
best_row, best_ok = None, -1
for _, row in rows.iterrows():
ok = sum(1 for c in INS_STATUSES if _clean_cell(row[c]) == INS_OK)
if ok > best_ok:
best_row, best_ok = row, ok
target = best_row
bh = _clean_cell(target['个人编号'])
if best_ok == len(INS_STATUSES):
# 五项全参保缴费 = 正常,备注只追加个人编号
remarks[cid] = f"个人编号:{bh}"
logs.append(f" 证件{cid}:五项均参保缴费,个人编号 {bh} → 备注追加")
else:
# 有不是参保缴费的:记录个人编号 + 异常字段名和对应内容
bad = [f"{c}:{_clean_cell(target[c])}"
for c in INS_STATUSES if _clean_cell(target[c]) != INS_OK]
remarks[cid] = f"个人编号:{bh};" + "、".join(bad)
logs.append(f" 证件{cid}:参保状态异常 → {';'.join(bad)}(个人编号 {bh})→ 备注追加")
return remarks, logs
def _do_huipan(page, biz_tab, task, res, unit_full="", fail_cids=()):
"""每个账号核查完都执行:下载回盘记录 + 核对参保状态 + 备注追加(含与核查备注合并)。
文件名单位优先用平台 aab004 全称,未取到(未办结跳过等)退回源名单参保单位名。
fail_cids:审核不通过(参保失败)人员,平台无其回盘记录,跳过「未查询到回盘记录」回写。"""
name_for_file = (unit_full or task['unit']).strip()
if unit_full and unit_full != task['unit']:
print(f" 使用平台单位全称命名:{unit_full}")
print(" 开始回盘打印下载...")
hp_file = _download_huipan(page, biz_tab, name_for_file, task.get('type'))
print(f" 回盘文件已保存:{hp_file}")
hp_remarks, hp_logs = _verify_huipan(hp_file, task['cids'])
for line in hp_logs:
print(line)
for cid in fail_cids:
if hp_remarks.get(cid, "").strip() == "未查询到回盘记录":
hp_remarks.pop(cid)
print(f" 证件{cid}:审核不通过无回盘记录,跳过未查询备注")
# 与核查阶段已生成的备注合并(writeback_source 按证件号覆盖,需手动拼接)
for cid in list(hp_remarks):
old = import_add._PENDING_REMARK.get(cid)
if old:
hp_remarks[cid] = f"{old}\n{hp_remarks[cid]}"
if hp_remarks:
import_add.writeback_source({}, hp_remarks)
res["huipan"] = f"回盘已下载,核对回写 {len(hp_remarks)} 人"
# ==================== 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": [], "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)
# 关键:必须等单位信息接口(getAab001)返回本单位,否则后续查询全部拿不到数据
unit_info = _wait_unit_loaded(biz_tab, task['unit'])
if unit_info is None:
# 页面没加载出单位:重开一次业务页再等
print(" 单位信息未加载,重开业务页重试...")
biz_tab = import_add._open_business_page(page, work_tab)
import_add._dismiss_popups(biz_tab)
unit_info = _wait_unit_loaded(biz_tab, task['unit'])
if unit_info is None:
res.update(success=True, skipped=True,
message="单位信息未加载(getAab001无数据),跳过")
return res
unit_full = str(unit_info.get('aab004') or '').strip() # 平台单位全称,用于回盘命名
fail_cids = set() # 审核不通过(参保失败)人员:平台无回盘记录,回盘阶段跳过其未查询备注
_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="已申报查询无记录,跳过")
elif status != DONE_STATUS:
res.update(success=True, skipped=True,
message=f"第一条状态「{status}」非{DONE_STATUS},跳过")
else:
print(f" 第一条状态:{status},点击查看读取审核结论")
url = _capture_query_url(page, biz_tab, view)
results, detail_full = _replay_query_all(biz_tab, url)
unit_full = unit_full or detail_full
_shot_c(biz_tab, "c4_detail_fetched")
if not results:
res.update(success=True, message="明细接口返回 0 条,跳过")
else:
status_map, remark_map, redo400, logs = build_writeback(
results, task['cids'], task['unit'])
fail_cids = {cid for cid, st in status_map.items() if st == FAIL_STATUS}
for line in logs:
print(line)
if status_map or remark_map:
import_add.writeback_source(status_map, remark_map)
n_match = len([r for r in results if r['cid'] in task['cids']])
n_pass = len([v for v in status_map.values() if v == PASS_STATUS])
n_fail = len([v for v in status_map.values() if v == FAIL_STATUS])
res.update(
success=True,
checked=n_match,
passed=n_pass,
failed=n_fail,
redo400=redo400,
message=(f"核查{n_match}条,通过{n_pass} 失败{n_fail} "
f"400系统错误{len(redo400)}(结束后统一清状态)"))
# 回盘打印:每个账号核查完都要下载回盘记录并核对参保状态(无论是否已办结)
try:
_do_huipan(page, biz_tab, task, res, unit_full, fail_cids)
except Exception as e:
res["huipan"] = f"回盘打印失败:{e}"
print(f" 回盘打印失败:{e}")
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)
# 400系统错误:核查时只记录,全部单位核查完后统一清空办理状态回待办(重新走8号+增员)
redo_all = [p for r in results for p in (r.get("redo400") or [])]
if redo_all:
import_add.writeback_source({p['cid']: "" for p in redo_all}, {})
print(f"\n400系统错误共 {len(redo_all)} 人,已统一清空办理状态回待办,"
f"请重新执行8号需求制作名单后增员:")
for p in redo_all:
print(f" - {p['name']}({p['cid']}){p['unit']}")
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())