Files
37duAutomation/plugins/sb_person_change/webops.py
T
puddy 1e533dd1b3 refactor: 完成项目目录重构与代码迁移
本次提交完成了整体项目的目录梳理与代码迁移:
1.  将根级controlplane、webhost等目录的代码迁移至desktop/对应子目录,统一桌面端架构
2.  移动并整理了插件目录结构,将插件统一放入根级plugins/
3.  调整了前端项目的路径与配置,统一前后端开发构建流程
4.  清理了废弃的旧版app/目录与冗余的构建中间文件
5.  更新了.gitignore与README.md,适配新的项目结构
2026-09-14 17:46:09 +08:00

743 lines
32 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 -*-
"""政务平台网页操作层(sb_person_change 插件)。
自 workflows/XQ0014 import_add.py(增员导入申报)与 check_review.py(已申报查询核查、
回盘打印下载核对)迁移。全部 print → config.log,截图统一走 excelio.shot。
依赖登录会话:login.LAST_SESSION(每个单位登录一次,办完 close_session)。
"""
import json
import os
import re
import time
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse, parse_qsl, urlencode
import pandas as pd
from . import config
from . import excelio
from . import login
BUSINESS_ITEM = "城保参保单位人员增加" # 单位办事列表里的业务名称
WEB_TIMEOUT = 20 # 网页元素等待超时(秒)
# 核查回盘相关(check_review 同源)
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 # 重放翻页上限(防死循环)
def _log(msg):
config.log(msg)
def _shot(tab, name):
excelio.shot(tab, name)
def _click_any(tab, selectors, desc, timeout=WEB_TIMEOUT):
"""按候选选择器顺序定位并点击第一个命中元素,全部未命中抛异常。"""
last_err = None
for sel in selectors:
try:
ele = tab.ele(sel, timeout=timeout)
except Exception as e:
last_err = e
continue
if ele:
ele.click()
return ele
raise RuntimeError(f"网页操作失败:找不到{desc}({last_err})")
def _find_any(tab, selectors, desc, timeout=WEB_TIMEOUT):
"""按候选选择器顺序查找元素,全部未命中抛异常。"""
for sel in selectors:
ele = tab.ele(sel, timeout=timeout)
if ele:
return ele
raise RuntimeError(f"网页操作失败:找不到{desc}")
def _wait_modal(tab, keyword, timeout=60):
"""等待某 ant-modal 弹窗正文出现指定关键字,返回该弹窗元素;超时返回 None。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
for m in tab.eles('css:.ant-modal-body'):
if keyword in (m.text or ''):
return m
except Exception:
pass
time.sleep(0.5)
return None
def _dismiss_popups(tab, rounds=5):
"""循环关闭常见提示弹窗(我已知晓/我知道了/确定/同意),直到没有可关的。"""
texts = ["我已知晓", "我知道了", "知道了", "确 定", "确定", "同 意", "同意"]
for _ in range(rounds):
hit = False
for t in texts:
try:
btn = tab.ele(f'tag:button@@text()={t}', timeout=0.5)
except Exception:
btn = None
if btn:
try:
btn.click()
_log(f" 关闭弹窗:{t}")
hit = True
time.sleep(1.2)
except Exception:
pass
if not hit:
break
# ==================== 增员导入:业务页与上传 ====================
def open_business_page(page, work_tab):
"""工作台 → 单位办事 → 「城保参保单位人员增加」在线办理。返回承载业务页的 tab。"""
before = set(page.tab_ids)
_click_any(work_tab, ['tag:button@@text()=单位办事'], '「单位办事」菜单')
time.sleep(2.5)
# 列表项:h4 标题定位 → 上溯到 li.ant-list-item → 点其「在线办理」
h4 = _find_any(work_tab, [f'tag:h4@@text()={BUSINESS_ITEM}'], f'业务入口「{BUSINESS_ITEM}」')
li = h4
for _ in range(6):
li = li.parent()
if li is None:
break
if li.tag == 'li':
break
act = li.ele('text=在线办理', timeout=3) if li is not None else None
if act is None:
raise RuntimeError("网页操作失败:找不到「在线办理」按钮")
act.click()
# 业务页可能新开 tab 或当前页跳转:轮询识别出现上传控件(input[type=file])的页面
deadline = time.time() + 30
while time.time() < deadline:
time.sleep(1)
cand_tids = [i for i in page.tab_ids if i not in before] + [work_tab.tab_id]
for tid in cand_tids:
try:
t = page.get_tab(tid)
if t.ele('#customized_form_controls_data', timeout=0.5):
return t
except Exception:
continue
raise RuntimeError("进入在线办理页失败(未出现文件上传控件)")
def _wait_import_result(tab, timeout=90):
"""导入结果探针:等待「导入完成」成功弹窗,或捕获失败提示(modal/toast)。
返回 ("ok", modal元素) / ("fail", 提示文本) / ("timeout", None)。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
for m in tab.eles('css:.ant-modal-body'):
t = (m.text or '').strip()
if '导入完成' in t:
return "ok", m
if t and not any(k in t for k in ('提交中', '导入中', '加载中')):
return "fail", t
for msg in tab.eles('css:.ant-message'):
t = (msg.text or '').strip()
if t:
return "fail", t
except Exception:
pass
time.sleep(0.4)
return "timeout", None
def _wait_unit_ready(tab, timeout=5):
"""等参保单位信息真正显示出来(导入请求 aab001 部件的就绪信号)。
单位信息由上传文件解析而来,显示在 borderless 下拉框里:
可能先以 placeholder 形式出现,也可能直接是选中值。
必须等文本内容真正渲染出来(非空)才算就绪,仅元素挂载不算。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
for sel in tab.eles('css:.ant-select-borderless'):
for kind in ('css:.ant-select-selection-placeholder',
'css:.ant-select-selection-item'):
ele = sel.ele(kind, timeout=1)
if ele and (ele.text or '').strip():
return True
except Exception:
pass
time.sleep(0.5)
return False
def upload_import(tab, xls_path, max_rounds=3):
"""上传名单 xls 并点「导入」,带失败探针与重试:
每轮都重新选文件(重新触发页面解析单位信息),就绪后再点导入。
返回 (导入成功人数, 导入失败人数)。"""
last_err = "导入超时无响应"
for rnd in range(1, max_rounds + 1):
inp = _find_any(tab, ['#customized_form_controls_data',
'css:input[type="file"]'], '文件上传控件')
inp.input(xls_path) # DrissionPage 对 file input 直接写路径即上传
# 等单位信息出现(placeholder 或选中值),未就绪点导入会报 aab001 缺失
if not _wait_unit_ready(tab, timeout=40):
_log(" 警告:40s 内单位信息未出现,本轮仍尝试导入")
time.sleep(1.0) # 就绪后再留缓冲,避免点太快
_shot(tab, "03_file_selected")
_click_any(tab, ['tag:button@@text()=导 入', 'tag:button@@text():导入'], '「导 入」按钮')
state, payload = _wait_import_result(tab, timeout=90)
if state == "ok":
_shot(tab, "04_import_result")
text = payload.text or ''
m_ok = re.search(r'成功[::]\s*(\d+)\s*人', text)
m_fail = re.search(r'失败[::]\s*(\d+)\s*人', text)
total = int(m_ok.group(1)) if m_ok else 0
failed = int(m_fail.group(1)) if m_fail else 0
_log(f" 导入完成:成功 {total} 人,失败 {failed} 人")
if total == 0:
raise RuntimeError(f"导入完成但成功人数为 0,提示:{text.strip()[:120]}")
for t in ('确 定', '确定'):
try:
btn = tab.ele(f'tag:button@@text()={t}', timeout=2)
except Exception:
btn = None
if btn:
btn.click()
break
time.sleep(1.5)
return total, failed
# 失败/超时:记录提示,重试
last_err = payload if state == "fail" else "导入后未出现结果弹窗(超时)"
_log(f" 第 {rnd} 轮导入未成功:{str(last_err)[:120]}")
time.sleep(2 + rnd) # 失败后多等一会,避免连点触发风控
raise RuntimeError(f"导入重试 {max_rounds} 轮均失败,最后提示:{str(last_err)[:160]}")
def read_failed_rows(tab):
"""切到「校验未通过人员」tab 读表格,返回 [(证件号码, 详细信息), ...]。
按表头(含「证件号码」+「详细信息」列)定位表格,避免抓到左侧导航等其它 tab 组件的面板。"""
try:
tab_btn = tab.ele('tag:span@@text()=校验未通过人员', timeout=10)
except Exception:
tab_btn = None
if not tab_btn:
return []
tab_btn.click()
time.sleep(2)
rows = []
try:
for tb in tab.eles('tag:table'):
ths = [th.text.strip() for th in tb.eles('tag:th')]
if '证件号码' in ths and '详细信息' in ths:
i_id, i_detail = ths.index('证件号码'), ths.index('详细信息')
for tr in tb.eles('css:tbody tr'):
tds = [td.text.strip() for td in tr.eles('tag:td')]
if len(tds) > max(i_id, i_detail) and len(tds[i_id]) >= 15:
detail = tds[i_detail]
# 备注只保留冒号后的内容(去掉"校验通过业务校验失败:"这类前缀)
for sep in (':', ':'):
if sep in detail:
detail = detail.split(sep, 1)[1].strip()
break
rows.append((tds[i_id], detail))
break
except Exception as e:
_log(f" 读取校验未通过表格异常:{e}")
_shot(tab, "05_check_failed_tab")
return rows
# ==================== 增员导入:预申报与提交 ====================
def _wait_pdf_ready(tab, timeout=60):
"""等 react-pdf canvas 出现且 2 秒不变,视为 PDF 绘制完成。超时仅告警不拦截。"""
last, stable_since = None, None
deadline = time.time() + timeout
while time.time() < deadline:
try:
canvases = tab.eles('css:.react-pdf__Page__canvas')
sig = (len(canvases), canvases[0].attr('width') if canvases else None)
except Exception:
sig = None
if sig and sig[0] > 0:
if sig == last:
if stable_since and time.time() - stable_since >= 2:
return True
else:
stable_since = time.time()
last = sig
time.sleep(1)
_log(" 警告:等待 PDF 渲染超时,继续尝试提交")
return False
def _goto_submit_page(tab, tries=3):
"""点「下一步」进入提交页,验证「提 交」按钮出现;未出现则重试。"""
for i in range(tries):
_click_any(tab, ['tag:button@@text()=下一步'], '「下一步」按钮')
deadline = time.time() + 12
while time.time() < deadline:
if tab.ele('tag:button@@text()=提 交', timeout=1):
return True
time.sleep(0.5)
_log(f" 下一步后未出现「提 交」按钮(第 {i + 1} 次),重试")
time.sleep(1.5)
return False
def _click_submit(tab, tries=3):
"""点「提 交」,验证「已知晓」确认弹窗出现;第一次可能因按钮未就绪失效,重试。
期间打印页面 toast 提示,便于诊断失败原因。"""
for i in range(tries):
btn = tab.ele('tag:button@@text()=提 交', timeout=5)
if btn:
try:
btn.click()
except Exception:
pass
deadline = time.time() + 10
while time.time() < deadline:
if tab.ele('tag:button@@text()=已知晓', timeout=1):
return True
try:
for msg in tab.eles('css:.ant-message'):
t = (msg.text or '').strip()
if t:
_log(f" 提交提示:{t[:100]}")
except Exception:
pass
time.sleep(0.5)
_log(f" 第 {i + 1} 次提交未出现「已知晓」确认弹窗,重试")
time.sleep(1.5)
return False
def _confirm_submit(tab, tries=3):
"""点「已知晓」→ 等「您已成功提交」弹窗;未出现则重点已知晓。"""
for i in range(tries):
btn = tab.ele('tag:button@@text()=已知晓', timeout=5)
if btn:
try:
btn.click()
except Exception:
pass
if _wait_modal(tab, '您已成功提交', timeout=60):
return True
_log(f" 第 {i + 1} 次点击已知晓后未见成功弹窗,重试")
return False
def predeclare_and_submit(page, tab):
"""预申报 → 去申报 → 关弹窗 → 全部提交 → 等 PDF → 下一步 → 提交(带重试)→ 已知晓 → 等成功。"""
_click_any(tab, ['tag:button@@text()=预申报'], '「预申报」按钮')
if _wait_modal(tab, '预申报成功', timeout=60) is None:
raise RuntimeError("预申报后未出现成功弹窗")
_click_any(tab, ['tag:button@@text()=去申报'], '「去申报」按钮')
# 等申报页就绪:提示弹窗或「全部提交」按钮任一出现即继续(替代固定 sleep,省 ~8s 空等)
deadline = time.time() + 15
while time.time() < deadline:
try:
if tab.ele('tag:button@@text()=我已知晓', timeout=0.5) or \
tab.ele('tag:button@@text()=我知道了', timeout=0.5) or \
tab.ele('tag:button@@text()=全部提交', timeout=0.5):
break
except Exception:
pass
time.sleep(0.3)
_dismiss_popups(tab) # 系统提示「我已知晓」+ 操作说明「我知道了」
_shot(tab, "06_declare_page")
_click_any(tab, ['tag:button@@text()=全部提交'], '「全部提交」按钮')
_wait_pdf_ready(tab)
_shot(tab, "07_pdf_ready")
if not _goto_submit_page(tab):
_shot(tab, "08_no_submit_btn")
raise RuntimeError("点击下一步后未出现「提 交」按钮")
_shot(tab, "08_submit_page")
if not _click_submit(tab):
_shot(tab, "09_submit_no_confirm")
raise RuntimeError("点击提交后未出现「已知晓」确认弹窗")
if not _confirm_submit(tab):
_shot(tab, "10_confirm_no_success")
raise RuntimeError("点击已知晓后未出现「您已成功提交」弹窗(提交可能未完成)")
_shot(tab, "11_submit_success")
_log(" 提交成功")
def _collect_review_rows(tab):
"""从明细表收集审核结论:{证件号码: (审核结论, 业务流水号)}。"""
results = {}
for tr in tab.eles('css:.ant-table-tbody tr.ant-table-row'):
try:
tds = [td.text.strip() for td in tr.eles('tag:td')]
except Exception:
continue
# 明细表结构:业务流水号/业务类型/姓名/证件号码/审核结论/审核意见/操作
# 证件号码可能是 15/18 位,尾号可为 X,不能只 isdigit
cid = tds[3] if len(tds) > 3 else ''
if len(cid) in (15, 18) and cid.rstrip('Xx').isdigit():
results[cid] = (tds[4], tds[0])
return results
def _open_query_page(page, tab, timeout=25):
"""点「去查看」进入申报查询列表(可能新开 tab),返回承载列表的 tab。"""
before = set(page.tab_ids)
_click_any(tab, ['tag:button@@text()=去查看'], '「去查看」按钮')
deadline = time.time() + timeout
while time.time() < deadline:
time.sleep(1)
tids = [i for i in page.tab_ids if i not in before] + [tab.tab_id]
for tid in tids:
try:
t = page.get_tab(tid)
row = t.ele('css:.ant-table-tbody tr.ant-table-row', timeout=0.5)
if row and row.ele('tag:a@@text()=查看', timeout=0.5):
_shot(t, "12_query_list")
return t
except Exception:
continue
raise RuntimeError("点击去查看后未找到申报查询列表(含「查看」按钮的记录表)")
def query_review_results(page, tab):
"""进入申报查询列表 → 打开序号1记录的「查看」→ 读明细表审核结论。
返回 {证件号码: (审核结论, 业务流水号)}。"""
qtab = _open_query_page(page, tab)
for attempt in range(3):
row = qtab.ele('css:.ant-table-tbody tr.ant-table-row', timeout=10)
view = row.ele('tag:a@@text()=查看', timeout=3) if row else None
if view:
try:
view.click()
except Exception:
pass
# 等明细表出现(含 18 位证件号码的行)
deadline = time.time() + 12
while time.time() < deadline:
time.sleep(1)
results = _collect_review_rows(qtab)
if results:
_shot(qtab, "13_review_detail")
return results
_log(f" 第 {attempt + 1} 次查看未读到审核结论明细,重试")
_shot(qtab, "13_review_detail_miss")
time.sleep(1.5)
raise RuntimeError("未读取到审核结论明细表")
# ==================== 核查回盘:已申报查询 + 接口重放 ====================
def open_query_menu(tab):
"""业务页左侧菜单点「已申报查询」,等记录表(表头含 当前状态/操作)出现。"""
_click_any(tab, [f'tag:li@@text()={MENU_QUERY}', f'text={MENU_QUERY}'],
f'左侧菜单「{MENU_QUERY}」')
_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
_log(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'):
_log(f" 单位信息已加载:{data.get('aab004')}(aab001={data.get('aab001')})")
return data
except Exception:
pass
# 接口没拿到但页面已经出现单位名 → 页面其实加载完了,不必再等
try:
if tab.ele(f'text:{unit_name}', timeout=0.5):
_log(f" 页面已显示单位「{unit_name}」,视为加载完成(接口轮询未取到全称)")
return {}
except Exception:
pass
time.sleep(1)
return None
def replay_query_all(tab, captured_url):
"""用捕获的请求参数重放接口翻页,取全量明细行。
返回 ([{name, cid, conclusion, opinion}, ...], unit_full)。
字段取 aac003/aac002/aae110s/aae111/aab004。"""
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)
_log(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": config._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
# ==================== 核查回盘:回盘打印下载与核对 ====================
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):
"""左侧菜单「回盘打印」→ 页内「回盘打印」按钮,等下载完成后重命名为规范文件名。
返回保存的文件 Path。"""
save_dir = Path(config.HUIPAN_DIR)
save_dir.mkdir(parents=True, exist_ok=True)
target = save_dir / f"{config.REPLAY_PREFIX}_{unit}_{datetime.now():%Y%m%d}.xlsx"
menu_sel = ['tag:li@@text()=回盘打印', 'text=回盘打印']
try:
_click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」')
except Exception:
# 点「查看」后会跳到明细详情页,左侧菜单不可见:直跳 OdCommon 菜单页即可
try:
_log(" 当前页看不到左侧菜单,直跳菜单页...")
biz_tab.get(MENU_PAGE_URL)
time.sleep(2)
_click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」(菜单页)')
except Exception:
# 直跳也不行:重开业务页再点(最后兜底)
biz_tab = open_business_page(page, login.LAST_SESSION['tab'])
_dismiss_popups(biz_tab)
_click_any(biz_tab, menu_sel, '左侧菜单「回盘打印」(重开业务页)')
_dismiss_popups(biz_tab)
# 页内「回盘打印」按钮(menu li 已处理,这里只找按钮/链接/文本)
btn = None
for sel in ('tag:button@@text()=回盘打印', 'tag:a@@text()=回盘打印',
'tag:span@@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 = ['个人编号', '身份证号'] + config.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: config._id_hit(config._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 config.INS_STATUSES if _clean_cell(row[c]) == config.INS_OK)
if ok > best_ok:
best_row, best_ok = row, ok
target = best_row
bh = _clean_cell(target['个人编号'])
if best_ok == len(config.INS_STATUSES):
# 五项全参保缴费 = 正常,备注只追加个人编号
remarks[cid] = f"个人编号:{bh}"
logs.append(f" 证件{cid}:五项均参保缴费,个人编号 {bh} → 备注追加")
else:
# 有不是参保缴费的:记录个人编号 + 异常字段名和对应内容
bad = [f"{c}:{_clean_cell(target[c])}"
for c in config.INS_STATUSES if _clean_cell(target[c]) != config.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']:
_log(f" 使用平台单位全称命名:{unit_full}")
_log(" 开始回盘打印下载...")
hp_file = download_huipan(page, biz_tab, name_for_file)
_log(f" 回盘文件已保存:{hp_file}")
hp_remarks, hp_logs = verify_huipan(hp_file, task['cids'])
for line in hp_logs:
_log(line)
for cid in fail_cids:
if hp_remarks.get(cid, "").strip() == "未查询到回盘记录":
hp_remarks.pop(cid)
_log(f" 证件{cid}:审核不通过无回盘记录,跳过未查询备注")
# 与核查阶段已生成的备注合并(writeback_source 按证件号覆盖,需手动拼接)
pending_remark = excelio._PENDING_REMARK
for cid in list(hp_remarks):
old = pending_remark.get(cid)
if old:
hp_remarks[cid] = f"{old}\n{hp_remarks[cid]}"
if hp_remarks:
excelio.writeback_source({}, hp_remarks)
res["huipan"] = f"回盘已下载,核对回写 {len(hp_remarks)} 人"