# -*- coding: utf-8 -*- """核查回盘模式(sb_person_change 插件)。 自 workflows/XQ0014 check_review.py 主流程迁移:恢复缓存 → 读待审核名单 → 取号 → 预检 → 逐单位登录核查审核结论 + 回盘打印下载核对 → 400系统错误统一清状态 → 统一回写。 print → config.log。 """ from . import config from . import excelio from . import login from . import source from . import webops def _log(msg): config.log(msg) 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']] = config.PASS_STATUS line += f" → 办理状态={config.PASS_STATUS}" elif concl == '不通过': if config.ERR_400_KEYWORD in opinion: # 系统错误:仅记录,运行结束后统一清空办理状态回待办重新增员 if config.RUN_400_CLEAR: redo400.append({"cid": r['cid'], "name": r['name'], "unit": unit_name}) line += " → 400系统错误,已记录(结束后统一清状态回待办重新增员)" else: status_map[r['cid']] = config.FAIL_STATUS remark_map[r['cid']] = opinion or '审核不通过' line += f" → 办理状态={config.FAIL_STATUS},备注追加:{opinion[:60]}" else: line += " → 非终态结论,跳过" logs.append(line) return status_map, remark_map, redo400, logs def do_unit_check(task): """登录后的完整核查流程。返回结果 dict(JSON 安全)。""" page = login.LAST_SESSION.get('page') work_tab = 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: excelfio.shot(work_tab, "c1_workbench") biz_tab = webops.open_business_page(page, work_tab) webops._dismiss_popups(biz_tab) # 关键:必须等单位信息接口(getAab001)返回本单位,否则后续查询全部拿不到数据 unit_info = webops.wait_unit_loaded(biz_tab, task['unit']) if unit_info is None: # 页面没加载出单位:重开一次业务页再等 _log(" 单位信息未加载,重开业务页重试...") biz_tab = webops.open_business_page(page, work_tab) webops._dismiss_popups(biz_tab) unit_info = webops.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() # 审核不通过(参保失败)人员:平台无回盘记录,回盘阶段跳过其未查询备注 excelfio.shot(biz_tab, "c2_biz_page") table = webops.open_query_menu(biz_tab) excelfio.shot(biz_tab, "c3_query_list") status, view = webops.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: _log(f" 第一条状态:{status},点击查看读取审核结论") url = webops._capture_query_url(page, biz_tab, view) results, detail_full = webops.replay_query_all(biz_tab, url) unit_full = unit_full or detail_full excelfio.shot(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 == config.FAIL_STATUS} for line in logs: _log(line) if status_map or remark_map: excelfio.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 == config.PASS_STATUS]) n_fail = len([v for v in status_map.values() if v == config.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: webops.do_huipan(page, biz_tab, task, res, unit_full, fail_cids) except Exception as e: res["huipan"] = f"回盘打印失败:{e}" _log(f" 回盘打印失败:{e}") return res except Exception as e: res["message"] = f"核查异常:{e}" return res def process_units(tasks, accounts, ctx): """逐参保单位:登录 → 已申报查询核查 → 回写。每账号办完清 cookies 关浏览器。""" results = [] n = len(tasks) for i, task in enumerate(tasks, 1): _log(f"\n========== [{i}/{n}] {task['unit']}({task['count']}人待审核)==========") ctx.progress(20 + int(70 * (i - 1) / max(n, 1))) acc = accounts.get(task['unit']) try: login_res = login.ensure_login(acc["username"], acc["password"]) except Exception as e: login_res = {"success": False, "message": f"登录调用异常:{e}"} _log(f"登录结果:{login_res.get('message')}") try: if login_res.get("success"): web_res = do_unit_check(task) _log(f"核查结果:{web_res.get('message')}") results.append({**task, **web_res}) else: results.append({**task, "success": False, "message": login_res.get("message", "")}) finally: login.close_session() return results def run(ctx, limit=0): """主流程:恢复缓存 → 读待审核名单 → 取号 → 预检 → 逐单位登录核查 → 统一回写。""" ctx.progress(5) recovered_ids = excelfio.load_ckpt() tasks = source.load_check_tasks(exclude_ids=recovered_ids) if recovered_ids: _log("\n检测到上次未回写的内容,先统一回写:") try: excelfio.flush_writeback() except Exception as e: _log(f"恢复回写失败(缓存保留,下次启动重试):{e}") if not tasks: ctx.progress(100) return {"summary": "无待核查数据", "rows": [], "notes": []} ctx.progress(15) # 文件占用预检:源名单被 Excel 打开会卡回写,提前报错 source_file, _ = excelfio.get_writeback_target() config.check_not_locked(source_file) accounts = source.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: _log("\n预检未通过:") for e in errors: _log(f" - {e}") raise RuntimeError("预检未通过,详见日志(台账未匹配/账号密码缺失),修正后重跑") todo = tasks[:limit] if limit > 0 else tasks if limit > 0: _log(f"分批运行:本次仅核查前 {limit} 个单位") ctx.progress(20) results = process_units(todo, accounts, ctx) ctx.progress(92) # 400系统错误:核查时只记录,全部单位核查完后统一清空办理状态回待办(重新走名单制作+增员) redo_all = [p for r in results for p in (r.get("redo400") or [])] notes = [] if redo_all: excelfio.writeback_source({p['cid']: "" for p in redo_all}, {}) _log(f"\n400系统错误共 {len(redo_all)} 人,已统一清空办理状态回待办," f"请重新执行名单制作后增员:") for p in redo_all: _log(f" - {p['name']}({p['cid']}){p['unit']}") notes.append(f"400系统错误:{p['name']}({p['cid']}){p['unit']} 已清状态回待办") try: excelfio.flush_writeback() except Exception as e: _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")] _log(f"\n========== 汇总 ==========") _log(f"核查完成 {len(ok) - len(skip)} 家,跳过(未办结/无记录){len(skip)} 家,失败 {len(fail)} 家") for r in fail: _log(f" ✗ {r['unit']}:{r.get('message', '')}") notes.append(f"{r['unit']}:{r.get('message', '')}") ctx.progress(100) return {"summary": f"核查回盘 完成{len(ok) - len(skip)}/跳过{len(skip)}/失败{len(fail)}", "rows": [{k: r.get(k) for k in ('unit', 'count', 'checked', 'passed', 'failed', 'huipan', 'message')} for r in results], "notes": notes}