- 新增停保核查脚本 check_review_stop.py - 优化社保增减员路径配置,合并台账目录 - 调整商户分组名称为综合门店 - 新增 Chrome 密码设置配置,关闭保存密码弹窗 - 优化源文件筛选规则,收紧为社保变更文件 - 新增 VC 运行库复制到构建脚本,解决 DLL 加载问题 - 升级通联数据导出插件版本至 1.0.12,更新描述
675 lines
32 KiB
Python
675 lines
32 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: check_review_stop.py
|
||
@Description: XQ0014 重庆社保系统增减员办理(核查-回盘·减员)—— 单文件自包含版
|
||
减员申报(import_stop.py)提交后,平台审核存在滞后。本脚本对源名单中
|
||
「办理停保=待审核」的人员所在参保单位,逐个登录重庆人社政务平台核查审核结论。
|
||
整体流程与 check_review.py(增员核查)一致,差异点:
|
||
|
||
1. 名单口径:sheet「YYYYMM停保名单」∩ 类型∈{停保,转移停保} ∩ 办理停保=待审核,
|
||
回写列「办理停保」(停保成功/停保失败)
|
||
2. 业务入口:城保参保单位人员减少;进业务页后有一次仅有右上角 X 按钮的
|
||
「提示信息」弹窗需先关闭(import_stop._close_tip_modal)
|
||
3. 明细接口与增员同一个(queryYsbWs04orWs01,已实测减员可用),返回行内直接带
|
||
aac001=个人编号、aad030=减少时间 → 审核通过人员的备注回写直接取接口数据
|
||
(个人编号+减少时间),无需依赖回盘表核对
|
||
4. 回盘打印:每个账号核查完仍下载回盘表到 DISK_DIR 留档(减员办结后五项参保
|
||
状态口径未定,不做状态核对回写)
|
||
|
||
流程(每个参保单位):
|
||
1. 登录(复用同目录 sb_login,法人用户 + 图形验证码)
|
||
2. 单位办事 → 城保参保单位人员减少 → 在线办理(关「提示信息」弹窗)
|
||
3. 左侧菜单点「已申报查询」→ 读表格第一条「当前状态」
|
||
非「已办结」→ 跳过该单位(审核还没走完)
|
||
4. 「已办结」→ 点「查看」,监听 queryYsbWs04orWs01 接口拿查询参数,
|
||
再用页内 XHR 重放接口翻页取全量(防分页漏数据)
|
||
5. 按 aac002 证件号码匹配本单位「待审核」人员,回写源名单「办理停保」列:
|
||
- 审核通过 → 停保成功,备注追加 个人编号/减少时间(接口直取)
|
||
- 不通过 + 400系统错误 → 先记录不动状态,全部单位核查完后统一清空办理停保
|
||
(回到待办,之后重新执行8号需求制作名单完成减员)
|
||
- 不通过 + 其它原因 → 停保失败,审核意见追加写备注(不覆盖)
|
||
6. 回盘打印:每个账号核查完下载回盘表(人员增减申请回盘表_单位_下载日期.xlsx)留档
|
||
7. 台账回写:复用 import_stop 的 JSON 缓存 + 运行结束统一回写 Excel 机制
|
||
(缓存文件 writeback_pending_stop.json,与增员互不干扰)
|
||
|
||
依赖(与 import_stop 相同):pandas openpyxl DrissionPage python-dotenv ddddocr
|
||
运行:python check_review_stop.py
|
||
"""
|
||
import os
|
||
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_stop / 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_stop # 同目录:复用停保名单/台账读取、提示弹窗关闭、回写缓存机制
|
||
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号+减员)
|
||
|
||
# ---- 回盘打印下载(仅留档,不做状态核对——减员办结后五项状态口径未定,
|
||
# 备注回写的个人编号/减少时间由明细接口直取,见 build_writeback)----
|
||
DISK_DIR = r"D:\资料\人资\重庆社保增减员办理\回盘打印\停保-减员" # 回盘文件保存目录
|
||
REPLAY_PREFIX = "人员增减申请回盘表" # 保存文件名:前缀_单位_日期.xlsx
|
||
|
||
|
||
# ==================== 2. 核查任务读取 ====================
|
||
def load_check_tasks(exclude_ids=frozenset()):
|
||
"""读取停保名单,筛选 办理停保=待审核 的行,按参保单位分组。
|
||
|
||
返回 [{unit, count, cids(set)}];同时把源文件信息写回 import_stop 全局
|
||
(flush_writeback 依赖 SOURCE_FILE_USED / SOURCE_SHEET_USED)。
|
||
exclude_ids:上次运行已回写的人员身份证号(防重复核查)。
|
||
"""
|
||
source_file = import_stop._latest_file(import_stop.SOURCE_DIR, import_stop.SOURCE_GLOB)
|
||
now = datetime.now()
|
||
xl = pd.ExcelFile(source_file)
|
||
sheet_name = import_stop._pick_sheet(xl, f"{now:%Y%m}停保名单", "停保名单",
|
||
pattern=r"(20\d{2})(1[0-2]|[1-9])停保名单")
|
||
print(f"源名单:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||
import_stop.SOURCE_FILE_USED, import_stop.SOURCE_SHEET_USED = source_file, sheet_name
|
||
|
||
df = pd.read_excel(source_file, sheet_name=sheet_name, header=2) # 表头第3行
|
||
status = df[import_stop.STATUS_COL].astype(str).str.strip()
|
||
mask = (
|
||
(df[import_stop.REGION_COL].astype(str).str.strip() == import_stop.REGION)
|
||
& (df[import_stop.TYPE_COL].astype(str).str.strip().isin(import_stop.KEEP_TYPES))
|
||
& (status == CHECK_STATUS)
|
||
)
|
||
sub = df[mask].copy()
|
||
if exclude_ids and '身份证号码' in sub.columns:
|
||
before = len(sub)
|
||
ref = [import_stop._norm_id(x) for x in exclude_ids]
|
||
sub = sub[~sub['身份证号码'].map(lambda v: import_stop._id_hit(import_stop._norm_id(v), ref))]
|
||
dropped = before - len(sub)
|
||
if dropped:
|
||
print(f" 已排除 {dropped} 行上次运行已回写的人员(防重复核查)")
|
||
if sub.empty:
|
||
print(f"没有筛选到数据({import_stop.REGION} ∩ {'/'.join(import_stop.KEEP_TYPES)} "
|
||
f"∩ 办理停保={CHECK_STATUS})")
|
||
return []
|
||
|
||
tasks = []
|
||
for unit, g in sub.groupby(sub[import_stop.UNIT_COL].astype(str).str.strip()):
|
||
cids = {import_stop._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):
|
||
"""业务页左侧菜单点「已申报查询」,等记录表(表头含 当前状态/操作)出现。"""
|
||
_dismiss_guide(tab) # 新手引导浮层会吞菜单点击
|
||
import_stop._click_any(tab, [f'tag:li@@text()={MENU_QUERY}', f'text={MENU_QUERY}'],
|
||
f'左侧菜单「{MENU_QUERY}」')
|
||
import_stop._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 _dismiss_warm_tip(tab):
|
||
"""关「温馨提示」弹窗(如:统一社会信用代码,调用单位信息接口失败!),
|
||
点页脚「关 闭」按钮。返回是否处理过。"""
|
||
try:
|
||
for t in tab.eles('css:.ant-modal-title'):
|
||
if '温馨提示' not in (t.text or ''):
|
||
continue
|
||
p = t
|
||
for _ in range(4):
|
||
p = p.parent()
|
||
if p is None:
|
||
break
|
||
cls = p.attr('class') or ''
|
||
if 'ant-modal' in cls and 'ant-modal-content' not in cls \
|
||
and 'ant-modal-header' not in cls:
|
||
btn = p.ele('css:.ant-modal-footer button', timeout=1)
|
||
if btn:
|
||
try:
|
||
btn.click()
|
||
except Exception:
|
||
btn.click(by_js=True)
|
||
time.sleep(0.6)
|
||
return True
|
||
break
|
||
except Exception:
|
||
pass
|
||
return False
|
||
|
||
|
||
def _reopen_biz(page):
|
||
"""统一自愈入口:重走业务入口(与回盘打印「重开业务页」同一操作)——
|
||
打开业务页 → 关「提示信息」弹窗 → 跳过新手引导 → 关残留弹窗。
|
||
用于单位信息接口失败等页面卡死场景,代替裸刷新。返回新 biz_tab。"""
|
||
tab = import_stop._open_business_page(page, sb_login.LAST_SESSION['tab'])
|
||
import_stop._close_tip_modal(tab)
|
||
_dismiss_guide(tab)
|
||
import_stop._dismiss_popups(tab)
|
||
return tab
|
||
|
||
|
||
def _wait_unit_loaded(tab, unit_name, timeout=40):
|
||
"""等业务页单位信息加载完成:轮询 getAab001 接口直到返回本单位数据。
|
||
该接口没返回时页面没加载出单位,后续已申报查询/回盘打印都拿不到数据。
|
||
接口轮询失败但页面已出现单位名时也视为加载成功(可能错过响应窗口)。
|
||
期间弹「温馨提示:调用单位信息接口失败」→ 关闭并立即返回 None,由调用方
|
||
统一重走业务入口(_reopen_biz)自愈。
|
||
返回 data[0](含 aab001、aab004 平台单位全称),页面已加载但接口拿不到时返回 {},超时返回 None。"""
|
||
deadline = time.time() + timeout
|
||
while time.time() < deadline:
|
||
if _dismiss_warm_tip(tab):
|
||
print(" 单位信息接口调用失败(温馨提示),关闭后重走业务入口")
|
||
return None
|
||
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):
|
||
"""用捕获的请求参数重放接口翻页,取全量明细行(与增员同一接口)。
|
||
返回 (results, unit_full);results 字段取 aac003/aac002/aae110s/aae111,
|
||
另取 aac001=个人编号、aad030=减少时间(审核通过人员备注回写用)。"""
|
||
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_stop._norm_id(it.get('aac002')),
|
||
"conclusion": str(it.get('aae110s') or '').strip(),
|
||
"opinion": str(it.get('aae111') or '').strip(),
|
||
"pid": str(it.get('aac001') or '').strip(), # 个人编号
|
||
"stop_date": str(it.get('aad030') 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
|
||
info = ";".join(x for x in (
|
||
f"个人编号:{r['pid']}" if r['pid'] else "",
|
||
f"减少时间:{r['stop_date']}" if r['stop_date'] else "") if x)
|
||
remark_map[r['cid']] = info or PASS_STATUS
|
||
line += f" → 办理停保={PASS_STATUS},备注追加:{info[:60]}"
|
||
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 _dismiss_guide(tab):
|
||
"""关闭新手引导浮层(点「跳过全部」,无则点「下一步」翻完)。
|
||
该浮层带遮罩会吞掉左侧菜单点击——实测直跳菜单页后不先跳过引导,
|
||
点「回盘打印」菜单无效,内容区一直停在预申报页。"""
|
||
for _ in range(4): # 引导最多 3~4 步,点完自然消失
|
||
hit = False
|
||
for sel in ('text=跳过全部', 'text=下一步'):
|
||
try:
|
||
e = tab.ele(sel, timeout=1)
|
||
except Exception:
|
||
e = None
|
||
if not e:
|
||
continue
|
||
try:
|
||
if e.states.has_rect:
|
||
e.click()
|
||
hit = True
|
||
time.sleep(0.6)
|
||
break
|
||
except Exception:
|
||
pass
|
||
if not hit:
|
||
return
|
||
|
||
|
||
def _find_huipan_btn(tab, wait):
|
||
"""找内容区可见的「回盘打印」提交按钮(aa.md 实测:<button type="submit">)。
|
||
只认 button/a——左侧菜单项是 li>span 结构,span 一律排除,
|
||
否则内容区未渲染时会误抓菜单 span 再点一次菜单,下载不触发。"""
|
||
deadline = time.time() + wait
|
||
while time.time() < deadline:
|
||
for sel in ('tag:button@@text()=回盘打印', 'tag:a@@text()=回盘打印'):
|
||
try:
|
||
cand = tab.ele(sel, timeout=1)
|
||
except Exception:
|
||
cand = None
|
||
if cand:
|
||
try:
|
||
if cand.states.has_rect:
|
||
return cand
|
||
except Exception:
|
||
return cand # 状态取不到时退回原行为
|
||
time.sleep(0.5)
|
||
return None
|
||
|
||
|
||
def _dump_download_debug(tab, tag):
|
||
"""回盘打印失败时自动保存现场(截图+HTML 到脚本旁 _debug/),便于对齐真实页面结构。"""
|
||
try:
|
||
dbg = _HERE / "_debug"
|
||
dbg.mkdir(exist_ok=True)
|
||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||
tab.get_screenshot(path=str(dbg), name=f"huipan_{tag}_{ts}.png")
|
||
(dbg / f"huipan_{tag}_{ts}.html").write_text(tab.html, encoding='utf-8')
|
||
print(f" 已保存现场:{dbg / f'huipan_{tag}_{ts}.png'}(含同名 html)")
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _download_huipan(page, biz_tab, unit):
|
||
"""左侧菜单「回盘打印」→ 页内「回盘打印」按钮,等下载完成后重命名为规范文件名。
|
||
返回保存的文件 Path。"""
|
||
save_dir = Path(DISK_DIR)
|
||
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=回盘打印']
|
||
# 三种进入方式逐个尝试;每次点完菜单都验证内容区按钮真的出现,
|
||
# 没出现(如被引导浮层吞了点击)视为本次无效,换下一种方式
|
||
btn = None
|
||
for name, goto in (("当前页", None), ("菜单页", MENU_PAGE_URL), ("重开业务页", "__REOPEN__")):
|
||
try:
|
||
if goto == "__REOPEN__":
|
||
biz_tab = _reopen_biz(page) # 统一自愈入口(与单位信息失败恢复一致)
|
||
elif goto:
|
||
print(f" 当前页进不去回盘打印,直跳{name}...")
|
||
biz_tab.get(goto)
|
||
time.sleep(2)
|
||
_dismiss_warm_tip(biz_tab) # 接口失败类温馨提示先关掉
|
||
_dismiss_guide(biz_tab) # 新手引导浮层会吞菜单点击,必须先跳过
|
||
import_stop._dismiss_popups(biz_tab)
|
||
import_stop._click_any(biz_tab, menu_sel, f'左侧菜单「回盘打印」({name})')
|
||
btn = _find_huipan_btn(biz_tab, 8)
|
||
if btn:
|
||
break
|
||
print(f" ({name})菜单已点但回盘打印内容未出现,换下一种方式")
|
||
except Exception as e:
|
||
print(f" ({name})方式失败:{e}")
|
||
if btn is None:
|
||
_dump_download_debug(biz_tab, 'nobutton')
|
||
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:
|
||
_dump_download_debug(biz_tab, 'nodownload')
|
||
raise RuntimeError("点击回盘打印后90秒内未检测到新下载文件(已保存现场)")
|
||
os.replace(new_file, target) # 同名覆盖,保证文件名=回盘表_单位_日期.xlsx
|
||
return target
|
||
|
||
|
||
# ==================== 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_stop._shot(work_tab, "s1_workbench")
|
||
biz_tab = import_stop._open_business_page(page, work_tab)
|
||
import_stop._close_tip_modal(biz_tab) # 减员特有:进业务页先关「提示信息」弹窗
|
||
import_stop._dismiss_popups(biz_tab)
|
||
# 关键:必须等单位信息接口(getAab001)返回本单位,否则后续查询全部拿不到数据。
|
||
# 接口偶发失败会弹「温馨提示:调用单位信息接口失败」,此时统一重走业务入口自愈
|
||
# (_reopen_biz,与回盘打印「重开业务页」同一操作),最多 3 次
|
||
unit_info = None
|
||
for attempt in range(1, 4):
|
||
unit_info = _wait_unit_loaded(biz_tab, task['unit'])
|
||
if unit_info is not None:
|
||
break
|
||
print(f" 单位信息未加载(第 {attempt} 次),重走业务入口...")
|
||
if attempt < 3:
|
||
biz_tab = _reopen_biz(page)
|
||
if unit_info is None:
|
||
res.update(success=True, skipped=True,
|
||
message="单位信息未加载(getAab001无数据),跳过")
|
||
return res
|
||
unit_full = str(unit_info.get('aab004') or '').strip() # 平台单位全称,用于回盘命名
|
||
_shot_s(biz_tab, "s2_biz_page")
|
||
|
||
table = _open_query_menu(biz_tab)
|
||
_shot_s(biz_tab, "s3_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_s(biz_tab, "s4_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'])
|
||
for line in logs:
|
||
print(line)
|
||
if status_map or remark_map:
|
||
import_stop.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)}(结束后统一清状态)"))
|
||
|
||
# 回盘打印:每个账号核查完都下载回盘表留档(无论是否已办结;
|
||
# 减员备注回写用接口个人编号/减少时间,见 build_writeback)
|
||
try:
|
||
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)
|
||
print(f" 回盘文件已保存:{hp_file}")
|
||
res["huipan"] = f"回盘已下载留档:{hp_file.name}"
|
||
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_s(tab, name):
|
||
"""核查流程调试截图(沿用 import_stop 的 DEBUG_MODE 开关,前缀 s 区分)。"""
|
||
import_stop._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_stop._load_ckpt()
|
||
tasks = load_check_tasks(exclude_ids=recovered_ids)
|
||
if recovered_ids:
|
||
print("\n检测到上次未回写的内容,先统一回写:")
|
||
try:
|
||
import_stop.flush_writeback()
|
||
except Exception as e:
|
||
print(f"恢复回写失败(缓存保留,下次启动重试):{e}")
|
||
if not tasks:
|
||
return {"success": True, "message": "无待核查数据", "total": 0, "done": 0}
|
||
|
||
accounts = import_stop.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_stop.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_stop.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())
|