# -*- coding: utf-8 -*- """增员办理模式(sb_person_change 插件)。 自 workflows/XQ0014 import_add.py 主流程迁移:恢复缓存 → 读名单(排除已回写人员) → 取号 → 预检 → 逐单位登录政务平台导入申报 → 统一回写。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 precheck(units, accounts): """预检:核对每个单位的导入文件与账号。返回待办列表 [{unit, count, file, username, password}]。""" import os import_dir = os.path.join(config.SOURCE_DIR, config.IMPORT_DIR_NAME) tasks, errors = [], [] _log("\n========== 预检 ==========") for unit, count in units: file_path = os.path.join(import_dir, f"{config._safe_name(unit)}增员导入名单.xls") acc = accounts.get(unit) problems = [] if not os.path.isfile(file_path): problems.append(f"缺导入文件({config.IMPORT_DIR_NAME}\\{os.path.basename(file_path)})") if acc is None: problems.append("台账未匹配(检查户头名/城市=重庆/是否在用=是)") else: if not acc["username"]: problems.append("账号缺失(信用代码与平台用户名均为空)") if not acc["password"]: problems.append("密码缺失(平台密码为空)") if problems: errors.append(f"[{unit}] " + ";".join(problems)) _log(f" ✗ {unit}({count}人):{';'.join(problems)}") else: tasks.append({"unit": unit, "count": count, "file": file_path, "username": acc["username"], "password": acc["password"]}) _log(f" ✓ {unit}({count}人)账号={acc['username']}" f"({acc['username_src']})文件={os.path.basename(file_path)}") if errors: _log(f"\n预检未通过,共 {len(errors)} 个问题,请先修正后重跑:") for e in errors: _log(f" - {e}") return None _log(f"预检通过:{len(tasks)} 个单位待办理\n") return tasks def do_web_import(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, "imported": 0, "failed": [], "review": {}} try: excelfio.shot(work_tab, "01_workbench") biz_tab = webops.open_business_page(page, work_tab) excelfio.shot(biz_tab, "02_biz_upload_page") # 1) 上传导入 total, _failed_cnt = webops.upload_import(biz_tab, task['file']) res['imported'] = total # 2) 校验未通过:回写 参保失败 + 备注(详细信息) # 平账规则:弹窗「成功N人」+「校验未通过人员」= 名单人数,不平账中止防止漏人导致下次重复申报 fail_rows = webops.read_failed_rows(biz_tab) res['failed'] = [{"id": cid, "detail": d} for cid, d in fail_rows] expected = task.get('count', 0) if expected and total + len(fail_rows) != expected: raise RuntimeError( f"人数不平账:导入成功{total} + 校验未通过{len(fail_rows)} ≠ 名单{expected}人," f"中止该单位(防漏人/重复申报),请人工核对") if fail_rows: excelfio.writeback_source({cid: "参保失败" for cid, _ in fail_rows}, {cid: d for cid, d in fail_rows}) passed = total # 3) 全员未通过 → 跳过申报 if passed <= 0: _log(" 校验通过人数为 0,跳过申报") res.update(success=True, message=f"导入{total}人,全部校验未通过,已回写未申报") return res # 4) 预申报 → 正式提交 → 查询审核结论回写 webops.predeclare_and_submit(page, biz_tab) review = webops.query_review_results(page, biz_tab) res['review'] = [{"id": cid, "conclusion": c, "sn": sn} for cid, (c, sn) in review.items()] if review: excelfio.writeback_source({cid: concl for cid, (concl, _) in review.items()}, {}) res.update(success=True, message=f"导入{total}人,未通过{len(fail_rows)}人,提交{passed}人") return res except Exception as e: res["message"] = f"网页操作异常:{e}" return res def process_units(tasks, ctx): """逐参保单位:登录政务平台 → 完整网页导入申报 → 回写。 每个账号办完(无论成败)都清 cookies 关浏览器,下个账号全新开始。 回写策略:单位内累积到内存并写 JSON 缓存(防崩溃),运行结束统一回写 Excel 一次。""" results = [] n = len(tasks) for i, task in enumerate(tasks, 1): _log(f"\n========== [{i}/{n}] {task['unit']}({task['count']}人)==========") _log(f"导入文件:{task['file']}") ctx.progress(20 + int(70 * (i - 1) / max(n, 1))) try: login_res = login.ensure_login(task["username"], task["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_web_import(task) _log(f"办理结果:{web_res.get('message')}") results.append({**task, **web_res}) else: results.append({**task, "success": False, "message": login_res.get("message", "")}) finally: # 账号隔离:清 cookies + 关浏览器,再进入下一单位 login.close_session() return results def run(ctx, limit=0): """主流程:恢复缓存 → 读名单(排除已回写人员)→ 取号 → 预检 → 逐单位登录导入 → 统一回写。 返回 JSON 安全 dict。""" ctx.progress(5) recovered_ids = excelfio.load_ckpt() units = source.load_add_units(exclude_ids=recovered_ids) # 崩溃恢复:上次运行残留的回写缓存统一落盘(排除逻辑已在 load_add_units 中生效, # 即使下面回写失败,这些人也不会被当成待办重复申报) if recovered_ids: _log("\n检测到上次未回写的内容,先统一回写:") try: excelfio.flush_writeback() except Exception as e: _log(f"恢复回写失败(缓存保留,下次启动重试):{e}") if not units: return {"summary": "无待办数据", "rows": [], "notes": []} ctx.progress(15) # 文件占用预检:源名单被 Excel 打开会卡回写,提前报错 source_file, _ = excelfio.get_writeback_target() config.check_not_locked(source_file) accounts = source.load_accounts([u for u, _ in units]) tasks = precheck(units, accounts) if tasks is None: raise RuntimeError("预检未通过,详见日志(缺导入文件/台账账号),修正后重跑") if limit > 0: tasks = tasks[:limit] _log(f"分批运行:本次仅办理前 {limit} 个单位") ctx.progress(20) results = process_units(tasks, ctx) ctx.progress(92) # 运行结束:本次累积的回写内容统一写 Excel 一次(失败则 JSON 缓存保留,下次启动恢复) 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"]] _log(f"\n========== 汇总 ==========") _log(f"成功 {len(ok)} 家,失败 {len(fail)} 家") notes = [] 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(fail)}", "rows": [{k: r.get(k) for k in ('unit', 'count', 'imported', 'message')} for r in results], "notes": notes}