662 lines
30 KiB
Python
662 lines
30 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""重庆社保系统增减员办理(核查-回盘)—— check_review.py / check_review_stop.py 移植。
|
||
|
||
申报提交后平台审核存在滞后,本模块对源名单中「办理状态/办理停保=待审核」的人员所在
|
||
参保单位,逐个登录重庆人社政务平台核查审核结论并下载回盘表:
|
||
|
||
统一引擎 ReviewEngine(kind):
|
||
- kind='add':增员核查,回写「办理状态」列(参保成功/参保失败);
|
||
审核通过人员的个人编号由回盘表核对得出(五项参保状态全「参保缴费」→ 备注个人编号)
|
||
- kind='stop':减员核查,回写「办理停保」列(停保成功/停保失败);
|
||
审核通过人员的个人编号/减少时间由明细接口直取(aac001/aad030),回盘表仅留档
|
||
|
||
流程(每参保单位):登录 → 进业务页(减员先关「提示信息」弹窗)→ 等单位信息 →
|
||
左侧「已申报查询」→ 读第一条状态,非「已办结」跳过 → 「查看」监听 queryYsbWs04orWs01
|
||
接口 → 页内 XHR 重放翻页取全量 → 按证件号匹配回写 → 回盘打印下载(增员核对/减员留档)。
|
||
400系统错误:先记录,全部核查完后统一清空状态回待办。
|
||
"""
|
||
import os
|
||
import re
|
||
import json
|
||
import time
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
from urllib.parse import urlparse, parse_qsl, urlencode
|
||
|
||
from .. import config
|
||
from ..data import source_reader
|
||
from ..data.writeback import Writeback
|
||
from . import web_login
|
||
from .web_import import (_shot, _click_any, _dismiss_popups,
|
||
_open_business_page, _close_tip_modal)
|
||
|
||
|
||
# ==================== 减员特有:新手引导 / 温馨提示 ====================
|
||
def _dismiss_guide(tab):
|
||
"""关闭新手引导浮层(点「跳过全部」,无则点「下一步」翻完)。"""
|
||
for _ in range(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 _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, business_item):
|
||
"""统一自愈入口:重走业务入口——打开业务页 → 关「提示信息」→ 跳新手引导 → 关残留弹窗。"""
|
||
tab = _open_business_page(page, web_login.LAST_SESSION['tab'], business_item)
|
||
_close_tip_modal(tab)
|
||
_dismiss_guide(tab)
|
||
_dismiss_popups(tab)
|
||
return tab
|
||
|
||
|
||
# ==================== 核查网页操作(增/减共用,少量分支) ====================
|
||
def _open_query_menu(tab):
|
||
"""业务页左侧菜单点「已申报查询」,等记录表(表头含 当前状态/操作)出现。"""
|
||
_dismiss_guide(tab) # 新手引导浮层会吞菜单点击
|
||
_click_any(tab, [f'tag:li@@text()={config.MENU_QUERY}', f'text={config.MENU_QUERY}'],
|
||
f'左侧菜单「{config.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"点击「{config.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。"""
|
||
before = set(page.tab_ids)
|
||
tab.listen.start(config.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:
|
||
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(config.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
|
||
config.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 接口直到返回本单位数据。
|
||
接口轮询失败但页面已出现单位名时也视为加载成功。期间弹「温馨提示」→ 返回 None
|
||
由调用方统一重走业务入口自愈。返回 data[0] / {} / None。"""
|
||
deadline = time.time() + timeout
|
||
while time.time() < deadline:
|
||
if _dismiss_warm_tip(tab):
|
||
config.log(" 单位信息接口调用失败(温馨提示),关闭后重走业务入口", "WARN")
|
||
return None
|
||
try:
|
||
raw = _fetch_via_xhr(tab, config.API_UNIT_INFO)
|
||
data = (json.loads(raw).get('data') or [None])[0]
|
||
if data and data.get('aab001'):
|
||
config.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):
|
||
config.log(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(config.MAX_PAGES):
|
||
params = base_params + [('pageIndex', json.dumps(
|
||
{"pageIndex": idx, "pageSize": config.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)
|
||
config.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(),
|
||
"pid": str(it.get('aac001') or '').strip(),
|
||
"stop_date": str(it.get('aad030') or '').strip(),
|
||
})
|
||
unit_full = ""
|
||
for it in rows:
|
||
v = str(it.get('aab004') or '').strip()
|
||
if v:
|
||
unit_full = v
|
||
break
|
||
return results, unit_full
|
||
|
||
|
||
# ==================== 结论回写 ====================
|
||
def _build_writeback(engine, 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']] = engine.pass_status
|
||
if engine.kind == 'stop':
|
||
# 减员:备注直接取接口个人编号+减少时间(不依赖回盘表核对)
|
||
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 engine.pass_status
|
||
line += f" → {engine.status_label}={engine.pass_status},备注追加:{info[:60]}"
|
||
else:
|
||
# 增员:个人编号由回盘表核对后追加(_do_huipan)
|
||
line += f" → {engine.status_label}={engine.pass_status}"
|
||
elif concl == '不通过':
|
||
if config.ERR_400_KEYWORD in opinion and config.RUN_400_CLEAR:
|
||
redo400.append({"cid": r['cid'], "name": r['name'], "unit": unit_name})
|
||
line += " → 400系统错误,已记录(结束后统一清状态回待办重新办理)"
|
||
elif config.ERR_400_KEYWORD in opinion:
|
||
# 400错误但清状态开关未开:兜底按不通过处理,避免明细被静默丢弃
|
||
status_map[r['cid']] = engine.fail_status
|
||
remark_map[r['cid']] = opinion or '400系统错误'
|
||
line += (f" → 400系统错误且清状态开关未开,{engine.status_label}={engine.fail_status},"
|
||
f"备注追加:{opinion[:60]}")
|
||
else:
|
||
status_map[r['cid']] = engine.fail_status
|
||
remark_map[r['cid']] = opinion or '审核不通过'
|
||
line += f" → {engine.status_label}={engine.fail_status},备注追加:{opinion[:60]}"
|
||
else:
|
||
line += " → 非终态结论,跳过"
|
||
logs.append(line)
|
||
return status_map, remark_map, redo400, logs
|
||
|
||
|
||
# ==================== 回盘打印下载 ====================
|
||
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 _find_huipan_btn(tab, wait):
|
||
"""找内容区可见的「回盘打印」提交按钮(只认 button/a,排除左侧菜单 li>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 = Path(config.CKPT_DIR) / "_debug"
|
||
dbg.mkdir(parents=True, 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')
|
||
config.log(f" 已保存现场:{dbg / f'huipan_{tag}_{ts}.png'}(含同名 html)")
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _download_huipan(page, biz_tab, unit, business_item, save_dir):
|
||
"""左侧菜单「回盘打印」→ 页内「回盘打印」按钮,等下载完成后重命名为规范文件名。
|
||
点「查看」后左侧菜单不可见,直接跳菜单页进入(重开业务页兜底);返回保存的文件 Path。"""
|
||
save_dir = Path(save_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=回盘打印']
|
||
btn = None
|
||
for name, goto in (("菜单页", config.MENU_PAGE_URL), ("重开业务页", "__REOPEN__")):
|
||
try:
|
||
if goto == "__REOPEN__":
|
||
biz_tab = _reopen_biz(page, business_item)
|
||
else:
|
||
config.log(f" 直跳{name}进回盘打印...")
|
||
biz_tab.get(goto)
|
||
time.sleep(2)
|
||
_dismiss_warm_tip(biz_tab)
|
||
_dismiss_guide(biz_tab)
|
||
_dismiss_popups(biz_tab)
|
||
_click_any(biz_tab, menu_sel, f'左侧菜单「回盘打印」({name})')
|
||
btn = _find_huipan_btn(biz_tab, 8)
|
||
if btn:
|
||
break
|
||
config.log(f" ({name})菜单已点但回盘打印内容未出现,换下一种方式")
|
||
except Exception as e:
|
||
config.log(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)
|
||
return target
|
||
|
||
|
||
def _verify_huipan(filepath, task_cids):
|
||
"""读回盘表(表头在第2行),按身份证号核对五项参保状态,生成备注回写内容。
|
||
同人多条记录:取参保缴费数量最多的那条。返回 (remark_map, logs)。"""
|
||
import pandas as pd
|
||
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
|
||
|
||
|
||
# ==================== 统一核查引擎 ====================
|
||
class ReviewEngine:
|
||
"""按 kind(add/stop)配置的增/减员核查回盘引擎。"""
|
||
|
||
def __init__(self, kind):
|
||
self.kind = kind
|
||
if kind == 'add':
|
||
self.business_item = "城保参保单位人员增加"
|
||
self.pass_status = "参保成功"
|
||
self.fail_status = "参保失败"
|
||
self.status_label = "办理状态"
|
||
self.operation_type = config.WEB_ADD_TYPES
|
||
else:
|
||
self.business_item = "城保参保单位人员减少"
|
||
self.pass_status = "停保成功"
|
||
self.fail_status = "停保失败"
|
||
self.status_label = config.STOP_PROCESSED_COL
|
||
self.operation_type = None
|
||
self.writeback = Writeback(kind)
|
||
# 回盘子目录:减员固定「停保-减员」;增员按参保类型分(新参保-增员 / 转移参保-增员)
|
||
self._huipan_subs = {"新参保": config.OUTPUT_DIR_ADD_NEW,
|
||
"转移参保": config.OUTPUT_DIR_ADD_TRANS}
|
||
|
||
# ---------------- 单个单位完整核查 ----------------
|
||
def do_unit_check(self, task):
|
||
"""登录后的完整核查流程。返回结果 dict(JSON 安全)。"""
|
||
page = web_login.LAST_SESSION.get('page')
|
||
work_tab = web_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:
|
||
_shot(work_tab, "c1_workbench")
|
||
biz_tab = _open_business_page(page, work_tab, self.business_item)
|
||
_close_tip_modal(biz_tab) # 减员特有;增员无该弹窗,调用无害
|
||
_dismiss_popups(biz_tab)
|
||
# 关键:必须等单位信息接口(getAab001)返回本单位,否则后续查询拿不到数据。
|
||
# 接口偶发失败会弹「温馨提示」,统一重走业务入口自愈,最多 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
|
||
config.log(f" 单位信息未加载(第 {attempt} 次),重走业务入口...")
|
||
if attempt < 3:
|
||
biz_tab = _reopen_biz(page, self.business_item)
|
||
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(biz_tab, "c2_biz_page")
|
||
|
||
table = _open_query_menu(biz_tab)
|
||
_shot(biz_tab, "c3_query_list")
|
||
status, view = _read_first_row(table)
|
||
if not status:
|
||
res.update(success=True, skipped=True, message="已申报查询无记录,跳过")
|
||
elif status != config.DONE_STATUS:
|
||
res.update(success=True, skipped=True,
|
||
message=f"第一条状态「{status}」非{config.DONE_STATUS},跳过")
|
||
else:
|
||
config.log(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(biz_tab, "c4_detail_fetched")
|
||
if not results:
|
||
res.update(success=True, message="明细接口返回 0 条,跳过")
|
||
else:
|
||
status_map, remark_map, redo400, logs = _build_writeback(
|
||
self, results, task['cids'], task['unit'])
|
||
fail_cids = {cid for cid, st in status_map.items() if st == self.fail_status}
|
||
for line in logs:
|
||
config.log(line)
|
||
if status_map or remark_map:
|
||
self.writeback.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 == self.pass_status])
|
||
n_fail = len([v for v in status_map.values() if v == self.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:
|
||
name_for_file = (unit_full or task['unit']).strip()
|
||
if unit_full and unit_full != task['unit']:
|
||
config.log(f" 使用平台单位全称命名:{unit_full}")
|
||
config.log(" 开始回盘打印下载...")
|
||
sub = (self._huipan_subs.get(task.get('type'), config.OUTPUT_DIR_ADD_NEW)
|
||
if self.kind == 'add' else config.OUTPUT_DIR_STOP)
|
||
save_dir = Path(config.replay_dir(sub))
|
||
hp_file = _download_huipan(page, biz_tab, name_for_file,
|
||
self.business_item, save_dir)
|
||
config.log(f" 回盘文件已保存:{hp_file}")
|
||
if self.kind == 'add':
|
||
self._verify_add_huipan(hp_file, task['cids'], fail_cids, res)
|
||
else:
|
||
res["huipan"] = f"回盘已下载留档:{hp_file.name}"
|
||
except Exception as e:
|
||
res["huipan"] = f"回盘打印失败:{e}"
|
||
config.log(f" 回盘打印失败:{e}")
|
||
return res
|
||
except Exception as e:
|
||
res["message"] = f"核查异常:{e}"
|
||
return res
|
||
|
||
def _verify_add_huipan(self, hp_file, task_cids, fail_cids, res):
|
||
"""增员回盘核对:五项参保状态 + 个人编号备注追加。"""
|
||
hp_remarks, hp_logs = _verify_huipan(hp_file, task_cids)
|
||
for line in hp_logs:
|
||
config.log(line)
|
||
for cid in fail_cids:
|
||
if hp_remarks.get(cid, "").strip() == "未查询到回盘记录":
|
||
hp_remarks.pop(cid)
|
||
config.log(f" 证件{cid}:审核不通过无回盘记录,跳过未查询备注")
|
||
for cid in list(hp_remarks):
|
||
old = self.writeback._pending_remark.get(cid)
|
||
if old:
|
||
hp_remarks[cid] = f"{old}\n{hp_remarks[cid]}"
|
||
if hp_remarks:
|
||
self.writeback.writeback_source({}, hp_remarks)
|
||
res["huipan"] = f"回盘已下载,核对回写 {len(hp_remarks)} 人"
|
||
|
||
# ---------------- 逐单位登录 + 核查 ----------------
|
||
def process_units(self, tasks, accounts, progress_span=(0, 100)):
|
||
"""逐参保单位:登录 → 已申报查询核查 → 回盘下载。每账号办完清 cookies 关浏览器。"""
|
||
span_start, span_end = progress_span
|
||
results = []
|
||
for i, task in enumerate(tasks, 1):
|
||
config.log(f"\n========== [{i}/{len(tasks)}] {task['unit']}"
|
||
f"({task['count']}人待审核)==========")
|
||
acc = accounts.get(task['unit'])
|
||
if len(tasks) > 1:
|
||
config.progress(span_start + int((span_end - span_start) * (i - 1) / len(tasks)))
|
||
try:
|
||
login_res = web_login.ensure_login(acc["username"], acc["password"])
|
||
except Exception as e:
|
||
login_res = {"success": False, "message": f"登录调用异常:{e}"}
|
||
config.log(f"登录结果:{login_res.get('message')}")
|
||
try:
|
||
if login_res.get("success"):
|
||
web_res = self.do_unit_check(task)
|
||
config.log(f"核查结果:{web_res.get('message')}")
|
||
results.append({**task, **web_res})
|
||
else:
|
||
results.append({**task, "success": False,
|
||
"message": login_res.get("message", "")})
|
||
finally:
|
||
web_login.close_session()
|
||
config.progress(span_end)
|
||
return results
|
||
|
||
# ---------------- 主流程 ----------------
|
||
def run(self, progress_span=(0, 100)):
|
||
"""主流程:恢复缓存 → 读待审核名单 → 取号 → 预检 → 逐单位登录核查 → 统一回写。"""
|
||
recovered_ids = self.writeback.load_ckpt()
|
||
tasks, source_file, source_sheet = source_reader.load_check_tasks(
|
||
self.kind, status_filter=config.CHECK_STATUS, exclude_ids=recovered_ids)
|
||
self.writeback.bind_source(source_file, source_sheet)
|
||
if recovered_ids:
|
||
config.log("\n检测到上次未回写的内容,先统一回写:")
|
||
try:
|
||
self.writeback.flush()
|
||
except Exception as e:
|
||
config.log(f"恢复回写失败(缓存保留,下次启动重试):{e}")
|
||
if not tasks:
|
||
return {"success": True, "message": "无待核查数据", "total": 0, "done": 0}
|
||
|
||
accounts = source_reader.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:
|
||
config.log("\n预检未通过:")
|
||
for e in errors:
|
||
config.log(f" - {e}")
|
||
return {"success": False, "message": "预检未通过,详见日志",
|
||
"total": len(tasks), "done": 0}
|
||
|
||
limit = config.get_run_limit()
|
||
todo = tasks[:limit]
|
||
results = self.process_units(todo, accounts, progress_span)
|
||
|
||
# 400系统错误:核查时只记录,全部单位核查完后统一清空状态回待办(重新走名单制作+办理)
|
||
redo_all = [p for r in results for p in (r.get("redo400") or [])]
|
||
if redo_all:
|
||
self.writeback.writeback_source({p['cid']: "" for p in redo_all}, {})
|
||
config.log(f"\n400系统错误共 {len(redo_all)} 人,已统一清空状态回待办,"
|
||
f"请重新执行名单制作后办理:")
|
||
for p in redo_all:
|
||
config.log(f" - {p['name']}({p['cid']}){p['unit']}")
|
||
try:
|
||
self.writeback.flush()
|
||
except Exception as e:
|
||
config.log(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")]
|
||
config.log(f"\n========== 汇总 ==========")
|
||
config.log(f"核查完成 {len(ok) - len(skip)} 家,跳过(未办结/无记录){len(skip)} 家,"
|
||
f"失败 {len(fail)} 家")
|
||
for r in fail:
|
||
config.log(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)}
|