feat: 新增多插件 UI 支持及运行日志集中回传功能

本次提交包含多项功能更新:
1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持
2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储
3. 新增插件分类字段支持,用于场景库分组管理
4. 优化 xq0034/0037/0048 等插件的功能及描述
5. 修复控制面响应兼容问题,支持新旧版本数据格式
6. 新增 xq0033 插件的状态存储模块,用于历史记录管理
7. 优化 CRM 登录窗口模式,支持全屏置顶
This commit is contained in:
2026-10-26 15:42:50 +08:00
parent 9fd687ada8
commit 843ff244a6
453 changed files with 243002 additions and 4493 deletions
+2
View File
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""业务逻辑层(聚合子包)。"""
+133
View File
@@ -0,0 +1,133 @@
# -*- coding: utf-8 -*-
"""目录预检:校验 base_dir(统一目录)是否满足插件各阶段需求。
用户设置资料根目录后,可先运行「目录预检」阶段确认目录结构齐备(真实布局):
- 根目录:源名单《*社保变更及增减名单*.xlsx》、员工花名册.xlsx
- 台账目录(默认根目录,可单独设置):社保户头管理台账*.xlsx(含缴费比例 sheet)
- 社保增减名单制作/模板/:增员模版.xls、减员模版.xls
- 告知书下发/模板/:三类告知书模板
(名单制作输出/、回盘打印/、告知书下发/输出/ 由各阶段运行时自动创建,不预检)
输出逐项 {名称, 是否就绪, 说明},未就绪项汇总列出,供用户补齐后重跑。
"""
import os
import re
from datetime import datetime
from .. import config
def _current_month_file(dir_path, pattern):
"""目录内匹配 pattern 且文件名月份=当月的文件(告知书数据源要求当月)。"""
if not os.path.isdir(dir_path):
return None, "目录不存在"
found = [n for n in os.listdir(dir_path)
if n.lower().endswith(".xlsx") and not n.startswith("~$")
and re.match(pattern.replace("*", ".*"), n)]
if not found:
return None, f"未找到匹配 {pattern} 的 xlsx"
now = datetime.now()
for name in found:
m = re.search(r"(20\d{2})年(\d{1,2})月", name) or re.search(r"(20\d{2})(\d{2})", name)
if m and (int(m.group(1)), int(m.group(2))) == (now.year, now.month):
return os.path.join(dir_path, name), "当月文件"
return None, f"均为历史月份:{sorted(found)[:5]}"
def _check_sheets(excel_path, required):
"""校验 xlsx 是否包含所有必需 sheet(关键字匹配)。返回 (ok, 缺失列表)。"""
try:
import pandas as pd
xl = pd.ExcelFile(excel_path)
names = [n.strip() for n in xl.sheet_names]
missing = [kw for kw in required
if not any(kw in n for n in names)]
return (not missing), missing
except Exception as e:
return False, [f"读取失败:{e}"]
def check_directory():
"""执行目录预检。返回 dict {ok, missing, checks}。
checks: [{name, ok, detail}] 逐项清单(缺失/异常项 ok=False)。
"""
base = config.get_base_dir()
ledger = config.get_ledger_dir()
checks = []
def add(name, ok, detail):
checks.append({"name": name, "ok": bool(ok), "detail": detail})
# ---- 0. 目录本身 ----
base_ok = os.path.isdir(base)
add("资料根目录", base_ok, base if base_ok else f"目录不存在:{base}")
# ---- 1. 名单制作 / 系统办理:源名单 ----
src_file = None
candidates = []
if base_ok:
candidates = [p for p in os.listdir(base)
if p.lower().endswith(".xlsx") and not p.startswith("~$")
and config.SOURCE_KEYWORD in p]
add(f"源名单(*{config.SOURCE_KEYWORD}*.xlsx)", bool(candidates),
"、".join(sorted(candidates)[:3]) or "未找到,请放入当月《社保变更及增减名单》")
if candidates:
src_file = os.path.join(base, max(
candidates, key=lambda n: os.path.getmtime(os.path.join(base, n))))
# ---- 2. 告知书数据源:当月文件 ----
if base_ok:
cur, note = _current_month_file(base, f"*{config.SOURCE_KEYWORD}*")
else:
cur, note = None, "根目录不存在"
add("源名单(当月文件,告知书用)", cur is not None, note)
# ---- 3. 源名单关键 sheet ----
if src_file:
ok, missing = _check_sheets(src_file, ["参保名单", "停保名单"])
add("源名单关键 sheet(参保名单/停保名单)", ok, "缺失:" + "、".join(missing) if missing else "齐备")
else:
add("源名单关键 sheet(参保名单/停保名单)", False, "源名单缺失,跳过校验")
# ---- 4. 名单制作:模板 + 输出目录 ----
tpl_dir = config.roster_template_dir()
add_exact = os.path.join(tpl_dir, config.TEMPLATE_ADD)
add_hit = (os.path.isfile(add_exact)
or any("增员模版" in f for f in os.listdir(tpl_dir)) if os.path.isdir(tpl_dir) else False)
add("增员模版(社保增减名单制作/模板/增员模版.xls)", add_hit,
f"{tpl_dir}\\{config.TEMPLATE_ADD}" if base_ok else "根目录不存在")
stop_exact = os.path.join(tpl_dir, config.TEMPLATE_STOP)
stop_hit = (os.path.isfile(stop_exact)
or any("减员模版" in f for f in os.listdir(tpl_dir)) if os.path.isdir(tpl_dir) else False)
add("减员模版(社保增减名单制作/模板/减员模版.xls)", stop_hit,
f"{tpl_dir}\\{config.TEMPLATE_STOP}" if base_ok else "根目录不存在")
# ---- 5. 台账(含缴费比例 sheet) ----
ledger_ok = os.path.isdir(ledger)
ledger_file = None
if ledger_ok:
cand = [p for p in os.listdir(ledger)
if p.lower().endswith(".xlsx") and "社保户头管理台账" in p and not p.startswith("~$")]
if cand:
ledger_file = os.path.join(ledger, max(cand, key=lambda n: os.path.getmtime(os.path.join(ledger, n))))
add("社保户头管理台账", ledger_file is not None,
os.path.basename(ledger_file) if ledger_file else f"未找到(目录:{ledger})")
if ledger_file:
ok, missing = _check_sheets(ledger_file, ["缴费比例"])
add("台账「缴费比例」sheet", ok, "缺失:" + "、".join(missing) if missing else "齐备")
else:
add("台账「缴费比例」sheet", False, "台账缺失,跳过校验")
# ---- 6. 告知书:花名册 + 三类模板 ----
roster = os.path.join(base, "员工花名册.xlsx")
add("员工花名册(告知书二级部门/接收人)", base_ok and os.path.isfile(roster),
roster if base_ok else "根目录不存在")
tpl_dir_notice = config.notice_template_dir()
tpl_dir_ok = os.path.isdir(tpl_dir_notice)
for key, tpl in config.NOTICE_TEMPLATES.items():
p = os.path.join(tpl_dir_notice, tpl["file"])
add(f"告知书模板[{key}](告知书下发/模板/{tpl['file']})", tpl_dir_ok and os.path.isfile(p),
p if tpl_dir_ok else f"模板目录不存在:{tpl_dir_notice}")
missing = [c for c in checks if not c["ok"]]
return {"ok": not missing, "missing": len(missing), "checks": checks}
File diff suppressed because it is too large Load Diff
+366
View File
@@ -0,0 +1,366 @@
# -*- coding: utf-8 -*-
"""OA 工作沟通推送(work_communication.py 移植,适配插件底座)。
原影刀版用 DrissionPage SessionPage + 读共享 oa_cookies.json;插件版改为:
- 登录态由底座注入(config.get_oa_session(),即 ctx.get_session("oa") 返回的
requests.Session,已带 OA cookies),不读 cookie 文件
- 请求直接用 requests.Session API(resp = session.get/post(...))
流程:解析接收人(工号/姓名 → 人员ID)→ 上传附件(getuserkey→二进制→submit绑定)→
提交工作沟通(取新建页 fdId + 通知方式随机字段 → POST method=save 保存)。
push_messages(messages) 逐条推送,返回 {success, message, doc_id, results}。
"""
import base64
import mimetypes
import os
import re
import time
import xml.etree.ElementTree as ET
from .. import config
# 附件二进制上传时的请求头(Referer 指向 OA 根地址,避免被服务端拦截)
_DEFAULT_HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"Chrome/120.0.0.0 Safari/537.36",
"Referer": f"{config.OA_BASE_URL}/",
"X-Requested-With": "XMLHttpRequest",
}
class OALoginExpiredError(Exception):
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
# ==================== 登录态(底座注入的 requests.Session) ====================
def get_oa_session():
"""取底座注入的 OA requests.Session;未登录时抛友好错误。"""
session = config.get_oa_session()
if session is None:
raise RuntimeError("未注入 OA 登录态,请先在工作台(壳子)登录 OA 系统再运行本阶段")
return session
def is_session_valid(session):
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效。"""
try:
resp = session.get(config.TODO_COUNT_URL,
params={"method": "sumTodoCount"}, timeout=10)
if resp is None or resp.status_code != 200:
return False
text = resp.text or ""
return bool(text) and text.lstrip().startswith(("{", "["))
except Exception as e:
config.log(f"OA 会话校验异常:{e}", "WARN")
return False
# ==================== 通用响应校验 ====================
def _check_response(resp, label):
"""校验响应:存在性 / 状态码 / 登录态。返回 resp。"""
if resp is None:
raise RuntimeError(f"{label}请求失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"{label}接口状态码异常: {resp.status_code}")
text = resp.text or ""
if "login.jsp" in text or "j_username" in text:
raise OALoginExpiredError(f"{label}接口返回登录页,OA 登录态已失效")
return resp
def oa_request_json(session, method, url, params, label, timeout=20, headers=None):
"""通用「发送请求 + 校验响应」:发出请求 → 校验 → 返回 JSON。"""
resp = (session.get(url, params=params, timeout=timeout, headers=headers)
if method.upper() == "GET"
else session.post(url, data=params, timeout=timeout, headers=headers))
resp = _check_response(resp, label)
text = resp.text or ""
try:
return resp.json()
except Exception:
raise RuntimeError(f"{label}接口返回非 JSON 数据(状态码 {resp.status_code}): {text[:200]}")
# ==================== 人员搜索 ====================
def search_person(session, keyword, org_type="15"):
"""按工号或姓名搜索人员,返回 (person_id, person_name);未找到返回 None。"""
params = {
"s_bean": "organizationDialogSearch",
"orgType": org_type,
"deptLimit": "",
"isExternal": "",
"key": keyword,
"s_ajax": "true",
}
resp = _check_response(session.get(config.PERSON_SEARCH_URL, params=params, timeout=20),
"人员搜索")
try:
root = ET.fromstring(resp.text)
except ET.ParseError as e:
config.log(f"人员搜索[{keyword}]响应解析失败: {e}", "WARN")
return None
matches = []
for node in root.iter("data"):
pid = node.get("id")
pname = node.get("name")
if pid and pname:
matches.append((pid, pname))
if not matches:
config.log(f"未搜索到人员: {keyword}", "WARN")
return None
for pid, pname in matches:
if keyword in (pid, pname):
config.log(f"搜索到人员: {pname} (ID: {pid})")
return (pid, pname)
if len(matches) > 1:
config.log(f"关键字[{keyword}]模糊匹配到 {len(matches)} 人,默认取第一个: {matches[0]}", "WARN")
pid, pname = matches[0]
config.log(f"搜索到人员: {pname} (ID: {pid})")
return (pid, pname)
# ==================== 附件上传 ====================
def upload_attachment(session, file_path):
"""上传单个附件,返回最终附件 ID(attid)。getuserkey → 二进制上传 → submit 绑定。"""
file_path = os.path.abspath(file_path)
if not os.path.exists(file_path):
raise FileNotFoundError(f"附件文件不存在: {file_path}")
file_name = os.path.basename(file_path)
file_size = str(os.path.getsize(file_path))
file_type = mimetypes.guess_type(file_name)[0] or "application/octet-stream"
last_modified = time.strftime(
"%a %b %d %Y %H:%M:%S GMT+0800", time.localtime(os.path.getmtime(file_path)))
fd_sign = base64.b64encode(file_name.encode("utf-8")).decode("utf-8")
fd_sign = fd_sign.replace("+", "").replace("/", "").replace("=", "")
# 1) 获取 userkey
resp1 = oa_request_json(session, "GET", config.ATT_UPLOAD_URL, {
"method": "handleAttUpload", "gettype": "getuserkey", "format": "json",
"filesize": file_size, "md5": "", "fileName": file_name,
"isSupportDirect": "false", "s_ajax": "true",
}, "附件上传-获取userkey", headers=_DEFAULT_HEADERS)
userkey = resp1.get("token", {}).get("header", {}).get("userkey")
if not userkey:
raise RuntimeError(f"获取 userkey 失败: {resp1}")
config.log(" 1. 获取 userkey 成功")
# 2) 上传二进制
uploader_url = f"{config.ATT_UPLOADER_URL}?gettype=upload&format=json&userkey={userkey}"
# 底座注入的共享会话默认带 Content-Type: application/x-www-form-urlencoded,
# 会导致 requests 在 files 上传时不再自动生成 multipart/form-data 边界头,
# 服务端(Apache Commons FileUpload)以 InvalidContentTypeException 拒绝。
# 上传前临时清除该默认头,让 requests 生成正确的 multipart 请求,随后恢复。
saved_ct = session.headers.pop("Content-Type", None)
try:
with open(file_path, "rb") as f:
files = {"file": (file_name, f, file_type)}
data2 = {"id": "WU_FILE_0", "name": file_name, "type": file_type,
"lastModifiedDate": last_modified, "size": file_size}
resp2 = _check_response(session.post(uploader_url, data=data2, files=files,
timeout=60, headers=_DEFAULT_HEADERS),
"附件上传-二进制")
finally:
if saved_ct is not None:
session.headers["Content-Type"] = saved_ct
try:
filekey = resp2.json().get("filekey")
except Exception:
filekey = None
if not filekey:
raise RuntimeError(f"二进制上传失败: {resp2.text[:200]}")
config.log(f" 2. 二进制上传成功, filekey: {filekey[:16]}...")
# 3) submit 绑定附件
resp3 = oa_request_json(session, "GET", config.ATT_UPLOAD_URL, {
"method": "handleAttUpload", "gettype": "submit", "format": "json",
"filekey": filekey, "filename": file_name, "fdKey": "attachment",
"fdModelName": config.KM_COLLABORATE_MODEL, "fdAttType": "byte",
"width": "null", "height": "null", "proportion": "true",
"fdSign": fd_sign, "s_ajax": "true",
}, "附件上传-提交绑定", headers=_DEFAULT_HEADERS)
attid = resp3.get("attid")
if str(resp3.get("status")) != "1" or not attid:
raise RuntimeError(f"提交绑定附件失败: {resp3}")
config.log(f" 3. 提交绑定成功, attid: {attid}")
return attid
# ==================== 工作沟通提交 ====================
def _encode_fd_content(content):
"""把沟通内容编码为 OA 要求的 fdContent 格式:固定前缀 + {base64(HTML)}。"""
return config.FD_CONTENT_PREFIX + "{" + \
base64.b64encode(content.encode("utf-8")).decode("utf-8") + "}"
def _get_add_page_fd_info(session):
"""打开新建工作沟通页,解析出草稿 fdId、通知方式随机字段名、当前用户 ID。"""
resp = _check_response(session.get(config.WORK_COMMUNICATION_ADD_URL, timeout=20),
"新建工作沟通-取页面")
html = resp.text or ""
m = re.search(r'name="fdId"\s+value="([^"]*)"', html)
fd_id = m.group(1) if m else ""
m2 = re.search(r'name="(__notify_type_[a-f0-9]+)"', html)
notify_field = m2.group(1) if m2 else ""
m3 = re.search(r'name="docCreatorId"\s+value="([^"]*)"', html)
creator_id = m3.group(1) if m3 else ""
if not fd_id:
raise RuntimeError("新建工作沟通页面解析失败:未找到 fdId")
config.log(f"获取新建草稿 fdId: {fd_id}, 通知方式字段: {notify_field}, "
f"页面当前用户ID: {creator_id or '无'}")
return fd_id, notify_field, creator_id
def submit_work_communication(session, receiver_ids, receiver_names, subject, content,
attachment_ids=None, creator_id=None,
category_id=config.FD_CATEGORY_DEFAULT):
"""提交工作沟通(新建),成功返回沟通文档 ID(fdId)。多值分隔符用「;」。"""
if category_id in config.FD_CATEGORY_MAP:
category_id = config.FD_CATEGORY_MAP[category_id]
elif not category_id:
category_id = config.FD_CATEGORY_DEFAULT
receiver_ids_str = ";".join(receiver_ids) if isinstance(receiver_ids, list) else receiver_ids
receiver_names_str = ";".join(receiver_names) if isinstance(receiver_names, list) else receiver_names
if isinstance(attachment_ids, list):
attachment_ids_str = ";".join(attachment_ids)
else:
attachment_ids_str = attachment_ids or ""
fd_id, notify_field, page_creator_id = _get_add_page_fd_info(session)
creator_id = creator_id or page_creator_id
if not creator_id:
raise ValueError("docCreatorId(creator_id) 必填,且无法从新建页自动提取,请显式传入")
data = {
"fdId": fd_id,
"fdNumber": "",
"participantIds": receiver_ids_str,
"participantNames": receiver_names_str,
"docSubject": subject,
"fdIsPriority": "",
"fdCategoryId": category_id,
"fdContent": _encode_fd_content(content),
"attachmentForms.attachment.fdModelId": "",
"attachmentForms.attachment.extParam": "",
"attachmentForms.attachment.fdModelName": config.KM_COLLABORATE_MODEL,
"attachmentForms.attachment.fdKey": "attachment",
"attachmentForms.attachment.fdAttType": "",
"attachmentForms.attachment.fdMulti": "",
"attachmentForms.attachment.deletedAttachmentIds": "",
"attachmentForms.attachment.attachmentIds": attachment_ids_str,
"__landray_fileattachment": "",
"fdNotifyType": "todo",
"__notify_type_placeholder": "todo",
"_fdPartnerOperating": "true",
"fdPartnerOperating": "true",
"fdIsOnlyView": "false",
"fdIsReminders": "false",
"fdRemindersDay_hidden": "",
"fdRemindersDay": "2",
"docCreatorId": creator_id,
}
if notify_field:
data[notify_field] = data.pop("__notify_type_placeholder")
else:
data.pop("__notify_type_placeholder", None)
resp = _check_response(session.post(config.KM_COLLABORATE_SAVE_URL,
params={"method": "save", "s_seq": "1"},
data=data, timeout=30),
"工作沟通提交")
text = resp.text or ""
if "您的操作已成功" in text:
config.log(f"工作沟通发送成功, 文档ID: {fd_id}")
return fd_id
raise RuntimeError(f"提交工作沟通失败: {text[:200]}")
# ==================== 一键推送入口 ====================
def _to_list(value):
"""把单个字符串或列表统一成列表。"""
if not value:
return []
return [value] if isinstance(value, str) else list(value)
def send_work_communication(receiver_keywords, subject, content,
attachment_paths=None, creator_id=None, category=None):
"""发送单条工作沟通:解析接收人 → 上传附件 → 提交。返回沟通文档 ID。"""
if not subject or not subject.strip():
raise ValueError("subject(标题) 不能为空")
if not content or not content.strip():
raise ValueError("content(内容) 不能为空")
session = get_oa_session()
if not is_session_valid(session):
raise OALoginExpiredError("OA 登录态已失效,请重新在工作台登录 OA")
# 1. 解析接收人
receiver_ids, receiver_names, unresolved = [], [], []
for kw in _to_list(receiver_keywords):
kw = str(kw).strip()
if not kw:
continue
result = search_person(session, kw)
if result:
pid, pname = result
receiver_ids.append(pid)
receiver_names.append(pname)
config.log(f"接收人[{kw}] -> {pname} (ID: {pid})")
else:
unresolved.append(kw)
if not receiver_ids:
raise RuntimeError("未解析到任何接收人,请检查传入的工号/姓名")
if unresolved:
raise RuntimeError(f"以下接收人解析失败,已中止发送: {', '.join(unresolved)}")
# 2. 上传附件(任一失败即整体失败)
attachment_ids = []
for path in _to_list(attachment_paths):
attid = upload_attachment(session, path)
attachment_ids.append(attid)
config.log(f"附件[{path}] -> attid: {attid}")
# 3. 提交沟通
return submit_work_communication(
session=session, receiver_ids=receiver_ids, receiver_names=receiver_names,
subject=subject, content=content, attachment_ids=attachment_ids or None,
creator_id=creator_id, category_id=category)
def _send_wrapped(receiver_keywords, subject, content, attachment_paths="",
creator_id="", category="工作安排"):
"""单条工作沟通推送(捕获异常,返回 result dict)。"""
try:
doc_id = send_work_communication(
receiver_keywords=receiver_keywords, subject=subject, content=content,
attachment_paths=attachment_paths or None, creator_id=creator_id or None,
category=category)
return {"success": True, "message": f"工作沟通发送成功,文档ID: {doc_id}", "doc_id": doc_id}
except Exception as e:
config.log(f"工作沟通推送失败: {e}", "ERROR")
return {"success": False, "message": f"工作沟通推送失败: {e}", "doc_id": ""}
def push_messages(messages):
"""逐条推送工作沟通(messages 结构同告知书模块产出的 OA 推送数据)。
messages 每条含 {receivers, subject, content, attachment_paths, category}。
返回 {success, message, doc_id, results}。"""
results = []
for i, msg in enumerate(messages or [], 1):
r = _send_wrapped(
receiver_keywords=msg.get("receivers", []),
subject=msg.get("subject", ""),
content=msg.get("content", ""),
attachment_paths=msg.get("attachment_paths", ""),
creator_id=msg.get("creator_id", ""),
category=msg.get("category", "工作安排"))
results.append(r)
config.log(f"[{i}/{len(messages or [])}] {r.get('message')}")
ok = sum(1 for r in results if r.get("success"))
return {
"success": ok == len(results),
"message": f"共推送 {len(results)} 条,成功 {ok} 条",
"doc_id": ",".join(r.get("doc_id", "") for r in results if r.get("doc_id")),
"results": results,
}
+285
View File
@@ -0,0 +1,285 @@
# -*- coding: utf-8 -*-
"""XQ0008 重庆社保增减员导入名单制作(generate_add.py / generate_stop.py 移植)。
- make_add_lists():按参保类型(转移参保 / 新参保)分组生成《XX增员导入名单.xls》,
分别输出到 转移参保-增员 / 新参保-增员 子目录(xlrd 读取 + xlutils 复制模板保留下拉字典);
日期规则:首次参加工作日期=本月1号、个人身份=24.工人、工伤参保时间=当日、其余参保时间=本月1号。
- make_stop_lists():按参保单位生成《XX减员导入名单.xls》到 停保-减员 子目录;
减少时间=离职日期(当月)否则=当天、减少原因=在职人员主动解除劳动合同、
五个险种减少标志=1 减少、失业原因=3 劳动者自愿辞职。
"""
import os
from datetime import datetime
from .. import config
from ..data import source_reader
# ==================== 翻译映射 ====================
def _translate_education(val):
if val is None:
return '90.其他'
try:
import pandas as pd
if pd.isna(val):
return '90.其他'
except (TypeError, ValueError):
pass
return config.EDU_MAP.get(str(val).strip(), '90.其他')
def _translate_nation(val):
if val is None:
return '99.其他'
try:
import pandas as pd
if pd.isna(val):
return '99.其他'
except (TypeError, ValueError):
pass
return config.NATION_MAP.get(str(val).strip(), '99.其他')
def _translate_residence(val):
if val is None:
return ''
try:
import pandas as pd
if pd.isna(val):
return ''
except (TypeError, ValueError):
pass
return config.RESIDENCE_MAP.get(str(val).strip(), '')
# ==================== 增员名单制作 ====================
def _write_template_add(template_file, output_path, unit_no, unit_name, records):
"""复制《增员模版.xls》写入 B1/D1 及 B4 起数据,另存为 output_path。
xlrd 读取(formatting_info 保留样式)+ xlutils.copy 复制,保留 Sheet2 下拉字典;
B1=社保号,D1=参保单位全称;数据从模板第4行起,按 TPL_COLS_ADD 顺序写入 B~U 列;
日期列以 yyyy/m/d 文本写入(工伤=当日,其余已填本月1日);多余示例行清空。
"""
import xlrd
from xlutils.copy import copy as xl_copy
rb = xlrd.open_workbook(template_file, formatting_info=True)
orig_rows = rb.sheet_by_index(0).nrows
wb = xl_copy(rb)
ws = wb.get_sheet(0) # 批量导入
ws.write(0, 1, unit_no) # B1 社保号
ws.write(0, 3, unit_name) # D1 参保单位全称
for i, rec in enumerate(records):
r = config.TPL_DATA_START_ROW - 1 + i # 0-based:模板第4行 → index 3
for c, col in enumerate(config.TPL_COLS_ADD):
val = rec.get(col)
if col in config.DATE_COLS_ADD and val is not None:
ws.write(r, c + 1, f"{val.year}/{val.month}/{val.day}")
else:
ws.write(r, c + 1, config._clean_value(val))
for r in range(config.TPL_DATA_START_ROW - 1 + len(records), orig_rows):
for c in range(1, len(config.TPL_COLS_ADD) + 1):
ws.write(r, c, "")
os.makedirs(os.path.dirname(output_path), exist_ok=True)
wb.save(output_path)
def _find_template_add():
"""定位《增员模版.xls》(社保增减名单制作/模板 下,优先精确名,其次按 *增员模版*.xls)。"""
from glob import glob
tpl_dir = config.roster_template_dir()
exact = os.path.join(tpl_dir, config.TEMPLATE_ADD)
if os.path.isfile(exact):
return exact
candidates = glob(os.path.join(tpl_dir, "*增员模版*.xls"))
if not candidates:
raise FileNotFoundError(
f"在 {tpl_dir} 下未找到《{config.TEMPLATE_ADD}》,请先准备增员导入模板。")
return max(candidates, key=os.path.getmtime)
def _add_output_dir(operation_type):
"""按参保类型取输出目录(社保增减名单制作/新参保-增员 或 转移参保-增员)。"""
sub = {"新参保": config.OUTPUT_DIR_ADD_NEW,
"转移参保": config.OUTPUT_DIR_ADD_TRANS}.get(operation_type)
if not sub:
raise ValueError(f"未知参保类型:{operation_type}(可选:{'/'.join(config.ADD_TYPES)})")
out_dir = config.roster_output_dir(sub)
os.makedirs(out_dir, exist_ok=True)
return out_dir
def process_add_members(operation_type):
"""生成增员导入名单(operation_type: '新参保' 或 '转移参保')。返回生成的份数。"""
sub, source_file, _sheet, _ = source_reader.load_records(
"add", operation_type=operation_type, status_filter="empty")
config.log(f"源表:{os.path.basename(source_file)}")
if sub.empty:
config.log(f"没有找到【{operation_type}】的数据({config.TARGET_REGION}区域,办理状态为空)")
return 0
today, first_day = datetime.now(), datetime.now().replace(day=1)
config.log(f"今日日期:{today:%Y-%m-%d};本月1日:{first_day:%Y-%m-%d}"
f"(首次参加/养老/失业/医疗/生育参保时间);工伤参保时间=当日")
template_file = _find_template_add()
output_dir = _add_output_dir(operation_type)
config.log(f"输出目录:{output_dir}")
n_files = 0
for store_name, group in sub.groupby(config.COLUMN_MAP_ADD['单位名称']):
config.log(f" 正在处理:{store_name},共 {len(group)} 人")
first_row = group.iloc[0]
unit_no = first_row[config.COLUMN_MAP_ADD['社保号']]
unit_full_name = first_row[config.COLUMN_MAP_ADD['参保单位全称']]
records = []
for _, row in group.iterrows():
rec = {
'证件号码': config._to_text(row[config.COLUMN_MAP_ADD['证件号码']]),
'姓名': row[config.COLUMN_MAP_ADD['姓名']],
'民族': _translate_nation(row[config.COLUMN_MAP_ADD['民族']]),
'首次参加工作日期': first_day,
'月基本工资额': config._clean_value(row[config.COLUMN_MAP_ADD['月基本工资额']]),
'工种': config.DEFAULT_VALUES_ADD['工种'],
'个人身份': config.DEFAULT_VALUES_ADD['个人身份'],
'户口性质': _translate_residence(row[config.COLUMN_MAP_ADD['户口性质']]),
'联系电话': config._to_text(row[config.COLUMN_MAP_ADD['联系电话']]),
'文化程度': _translate_education(row[config.COLUMN_MAP_ADD['文化程度']]),
'养老保险参保时间': first_day,
'失业保险参保时间': first_day,
'医疗保险参保时间': first_day,
'工伤保险参保时间': today,
'生育保险参保时间': first_day,
'证件类型': config.DEFAULT_VALUES_ADD['证件类型'],
'国籍': config.DEFAULT_VALUES_ADD['国籍'],
'备注': config.DEFAULT_VALUES_ADD['备注'],
'专职技能': config.DEFAULT_VALUES_ADD['专职技能'],
'技能等级': config.DEFAULT_VALUES_ADD['技能等级'],
}
records.append(rec)
output_path = os.path.join(output_dir,
f"{config._safe_name(store_name)}增员导入名单.xls")
_write_template_add(template_file, output_path, unit_no, unit_full_name, records)
config.log(f" 已生成:{output_path}")
n_files += 1
config.log(f"所有【{operation_type}】导入名单生成完成!")
return n_files
def make_add_lists():
"""增员名单制作:依次生成 转移参保 / 新参保 两类名单。返回 (总份数, 结果明细)。"""
total, detail = 0, {}
for op_type in config.ADD_TYPES:
n = process_add_members(op_type)
total += n
detail[op_type] = n
return total, detail
# ==================== 减员名单制作 ====================
def _write_template_stop(template_file, output_path, unit_no, unit_full_name, records):
"""复制《减员模版.xls》写入 B1/D1 及 B4 起数据,另存为 output_path。"""
import xlrd
from xlutils.copy import copy as xl_copy
rb = xlrd.open_workbook(template_file, formatting_info=True)
orig_rows = rb.sheet_by_index(0).nrows
wb = xl_copy(rb)
ws = wb.get_sheet(0) # 批量导入
ws.write(0, 1, unit_no) # B1 单位社保号
ws.write(0, 3, unit_full_name) # D1 单位全称
for i, rec in enumerate(records):
r = config.TPL_DATA_START_ROW - 1 + i
for c, col in enumerate(config.TPL_COLS_STOP):
val = rec.get(col)
if col in config.DATE_COLS_STOP and val is not None:
ws.write(r, c + 1, f"{val.year}/{val.month}/{val.day}")
else:
ws.write(r, c + 1, config._clean_value(val))
for r in range(config.TPL_DATA_START_ROW - 1 + len(records), orig_rows):
for c in range(1, len(config.TPL_COLS_STOP) + 1):
ws.write(r, c, "")
os.makedirs(os.path.dirname(output_path), exist_ok=True)
wb.save(output_path)
def _find_template_stop():
"""定位《减员模版.xls》(社保增减名单制作/模板 下,优先精确名,其次按 *减员模版*.xls)。"""
from glob import glob
tpl_dir = config.roster_template_dir()
exact = os.path.join(tpl_dir, config.TEMPLATE_STOP)
if os.path.isfile(exact):
return exact
candidates = glob(os.path.join(tpl_dir, "*减员模版*.xls"))
if not candidates:
raise FileNotFoundError(
f"在 {tpl_dir} 下未找到《{config.TEMPLATE_STOP}》,请先准备停保导入模板。")
return max(candidates, key=os.path.getmtime)
def _resolve_reduce_time(raw, today):
"""减少时间取值规则:离职日期为当月日期 → 减少时间=离职日期;否则=当天。"""
try:
import pandas as pd
dt = pd.to_datetime(raw, errors='coerce')
except (TypeError, ValueError):
dt = None
if dt is not None and getattr(dt, 'year', None) == today.year and dt.month == today.month:
return dt, True
return today, False
def process_stop_members():
"""生成停保导入名单。返回生成的份数。"""
sub, source_file, _sheet, _ = source_reader.load_records(
"stop", status_filter="empty")
config.log(f"源表:{os.path.basename(source_file)}")
if sub.empty:
config.log(f"没有筛选到数据(类型 ∈ {'/'.join(config.STOP_TYPES)} ∩ "
f"区域={config.TARGET_REGION} ∩ 办理停保为空)")
return 0
today = datetime.now()
config.log(f"制作日期:{today:%Y-%m-%d}")
template_file = _find_template_stop()
output_dir = config.roster_output_dir(config.OUTPUT_DIR_STOP)
os.makedirs(output_dir, exist_ok=True)
config.log(f"输出目录:{output_dir}")
n_files, n_leave_date = 0, 0
for group_key, group in sub.groupby(config.COLUMN_MAP_STOP['单位名称']):
config.log(f" 正在处理:单位【{group_key}】,共 {len(group)} 人")
first_row = group.iloc[0]
unit_no = first_row[config.COLUMN_MAP_STOP['单位社保号']]
unit_full_name = first_row[config.COLUMN_MAP_STOP['单位全称']]
records = []
for _, row in group.iterrows():
reduce_time, from_leave = _resolve_reduce_time(
row[config.STOP_LEAVE_DATE_COL], today)
if from_leave:
n_leave_date += 1
rec = {
'个人编号': config._clean_value(row[config.COLUMN_MAP_STOP['个人编号']]),
'证件号码': config._clean_value(row[config.COLUMN_MAP_STOP['证件号码']]),
'姓名': config._clean_value(row[config.COLUMN_MAP_STOP['姓名']]),
'减少时间': reduce_time,
'减少原因': config.DEFAULT_VALUES_STOP['减少原因'],
'养老保险减少标志': config.DEFAULT_VALUES_STOP['养老保险减少标志'],
'失业保险减少标志': config.DEFAULT_VALUES_STOP['失业保险减少标志'],
'医疗保险减少标志': config.DEFAULT_VALUES_STOP['医疗保险减少标志'],
'工伤保险减少标志': config.DEFAULT_VALUES_STOP['工伤保险减少标志'],
'生育保险减少标志': config.DEFAULT_VALUES_STOP['生育保险减少标志'],
'失业原因': config.DEFAULT_VALUES_STOP['失业原因'],
}
records.append(rec)
output_path = os.path.join(output_dir,
f"{config._safe_name(group_key)}减员导入名单.xls")
_write_template_stop(template_file, output_path, unit_no, unit_full_name, records)
config.log(f" 已生成:{output_path}")
n_files += 1
config.log(f"所有停保导入名单生成完成!共 {len(sub[config.COLUMN_MAP_STOP['单位名称']].unique())} 个单位")
config.log(f"减少时间取值:{n_leave_date} 人取离职日期,"
f"{len(sub) - n_leave_date} 人取当天({today:%Y-%m-%d})")
return n_files
def make_stop_lists():
"""减员名单制作。返回 (份数, 结果明细)。"""
n = process_stop_members()
return n, {"停保-减员": n}
+729
View File
@@ -0,0 +1,729 @@
# -*- coding: utf-8 -*-
"""重庆社保系统增减员办理(增员/减员系统导入)—— import_add.py / import_stop.py 移植。
统一引擎 ImportEngine(kind):
- kind='add':城保参保单位人员增加,消费《新参保-增员》/《转移参保-增员》目录
《XX增员导入名单.xls》(按参保类型分目录),回写「办理状态」列(参保失败),
审核结论回写「办理状态」
- kind='stop':城保参保单位人员减少,消费《停保-减员》目录《XX减员导入名单.xls》,
回写「办理停保」列(停保失败),审核结论回写「办理停保」
流程(每参保单位):
登录(web_login,法人用户+图形验证码)→ 进业务页 → 上传导入 → 校验未通过回写 →
预申报 → 去申报 → 全部提交 → 下一步 → 提交 → 去查看 → 明细审核结论回写 →
下个单位前清 cookies 关浏览器。回写 JSON 缓存防崩溃,运行结束统一写 Excel。
"""
import os
import re
import time
from datetime import datetime
from .. import config
from ..data import source_reader
from ..data.writeback import Writeback
from . import web_login
# ==================== 通用网页操作(增/减共用) ====================
WEB_TIMEOUT = 20 # 网页元素等待超时(秒)
def _shot(tab, name):
"""调试截图:仅调试模式开启时保存页面截图并打印当前 URL。"""
if not config.is_debug():
return
try:
from pathlib import Path
d = Path(config.CKPT_DIR) / "debug_shots"
d.mkdir(parents=True, exist_ok=True)
ts = datetime.now().strftime("%H%M%S")
tab.get_screenshot(path=str(d), name=f"{ts}_{name}.png")
config.log(f" [截图] {ts}_{name}.png url={str(tab.url)[:90]}")
except Exception as e:
config.log(f" [截图失败] {name}: {e}")
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()
config.log(f" 关闭弹窗:{t}")
hit = True
time.sleep(1.2)
except Exception:
pass
if not hit:
break
def _open_business_page(page, work_tab, business_item):
"""工作台 → 单位办事 → 业务「在线办理」。返回承载业务页的 tab。"""
before = set(page.tab_ids)
_click_any(work_tab, ['tag:button@@text()=单位办事'], '「单位办事」菜单')
time.sleep(2.5)
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()
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 _title_is_tip(m):
"""弹窗标题是否含「提示信息」。"""
try:
t = m.ele('css:.ant-modal-title', timeout=0.2)
return bool(t and '提示信息' in (t.text or ''))
except Exception:
return False
def _find_tip_modal_by_title(tab):
"""按标题「提示信息」定位弹窗:一次查询所有标题元素再上溯到 .ant-modal。"""
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:
return p
except Exception:
pass
return None
def _remove_tip_modals(tab):
"""把「提示信息」类弹窗残留节点连 wrap 一起从 DOM 移除。"""
try:
tab.run_js(
"document.querySelectorAll('.ant-modal').forEach(function(m){"
" var t = m.querySelector('.ant-modal-title');"
" var onlyX = m.querySelector('button.ant-modal-close') &&"
" m.querySelectorAll('button').length === 1;"
" if ((t && t.textContent.indexOf('提示信息') !== -1) || onlyX) {"
" var w = m.closest('.ant-modal-wrap') || m; w.remove();"
" }"
"});")
except Exception:
pass
def _close_tip_modal(tab):
"""关闭「提示信息」弹窗(减员流程特有)。未弹出返回 False。"""
m = _find_tip_modal_by_title(tab)
if m is None:
return False
x = m.ele('css:button.ant-modal-close', timeout=1)
if x:
try:
if x.states.has_rect:
x.click()
config.log(" 关闭「提示信息」弹窗")
time.sleep(0.8)
except Exception:
pass
_remove_tip_modals(tab)
return True
def _body_in_tip_modal(m):
"""modal-body 是否属于标题为「提示信息」的说明弹窗。"""
p = m
for _ in range(3):
try:
p = p.parent()
except Exception:
return False
if p is None:
return False
if _title_is_tip(p):
return True
return False
# ==================== 导入与申报(增/减共用,少量分支) ====================
def _wait_import_result(tab, timeout=90):
"""导入结果探针:等待「导入完成」成功弹窗,或捕获失败提示。
返回 ("ok", modal元素) / ("fail", 提示文本) / ("timeout", None)。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
bodies = tab.eles('css:.ant-modal-body')
# 第一遍只认「导入完成」成功标志(页面可能同时残留说明弹窗)
for m in bodies:
if '导入完成' in (m.text or ''):
return "ok", m
# 第二遍:其它任何非加载中、非「提示信息」说明弹窗的文本都视为失败提示
for m in bodies:
t = (m.text or '').strip()
if t and not any(k in t for k in ('提交中', '导入中', '加载中')) \
and not _body_in_tip_modal(m):
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 部件的就绪信号)。"""
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, close_tip, 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)
if not _wait_unit_ready(tab, timeout=40):
config.log(" 警告:40s 内单位信息未出现,本轮仍尝试导入")
time.sleep(1.0)
_shot(tab, "03_file_selected")
if close_tip:
_close_tip_modal(tab) # 点导入前再兜底清一次「提示信息」
_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
config.log(f" 导入完成:成功 {total} 人,失败 {failed} 人")
if total == 0:
# 全员未通过:不在此中止,交给上层读「校验未通过人员」回写参保失败并跳过申报
# (若此处 raise,失败人员不会落账,下次运行会重复申报)
config.log(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 "导入后未出现结果弹窗(超时)"
config.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 读表格,返回 [(证件号码, 详细信息), ...]。"""
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:
config.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)
config.log(" 警告:等待 PDF 渲染超时,继续尝试提交", "WARN")
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)
config.log(f" 下一步后未出现「提 交」按钮(第 {i + 1} 次),重试")
time.sleep(1.5)
return False
def _click_submit_add(tab, tries=3):
"""增员:点「提 交」,验证「已知晓」确认弹窗出现。"""
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:
config.log(f" 提交提示:{t[:100]}")
except Exception:
pass
time.sleep(0.5)
config.log(f" 第 {i + 1} 次提交未出现「已知晓」确认弹窗,重试")
time.sleep(1.5)
return False
def _confirm_submit_add(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
config.log(f" 第 {i + 1} 次点击已知晓后未见成功弹窗,重试")
return False
def _click_submit_stop(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=30):
return True
try:
for msg in tab.eles('css:.ant-message'):
t = (msg.text or '').strip()
if t:
config.log(f" 提交提示:{t[:100]}")
except Exception:
pass
config.log(f" 第 {i + 1} 次提交未出现「您已成功提交」弹窗,重试")
time.sleep(1.5)
return False
def _predeclare_and_submit(page, tab, kind):
"""预申报 → 去申报 → 关弹窗 → 全部提交 → 等 PDF → 下一步 → 提交 → 等成功。
kind='add' 走「已知晓」确认;kind='stop' 成功弹窗自带按钮。"""
_click_any(tab, ['tag:button@@text()=预申报'], '「预申报」按钮')
if _wait_modal(tab, '预申报成功', timeout=60) is None:
raise RuntimeError("预申报后未出现成功弹窗")
_click_any(tab, ['tag:button@@text()=去申报'], '「去申报」按钮')
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 kind == 'add':
if not _click_submit_add(tab):
_shot(tab, "09_submit_no_confirm")
raise RuntimeError("点击提交后未出现「已知晓」确认弹窗")
if not _confirm_submit_add(tab):
_shot(tab, "10_confirm_no_success")
raise RuntimeError("点击已知晓后未出现「您已成功提交」弹窗(提交可能未完成)")
else:
if not _click_submit_stop(tab):
_shot(tab, "09_submit_no_success")
raise RuntimeError("点击提交后未出现「您已成功提交」弹窗(提交可能未完成)")
_shot(tab, "11_submit_success")
config.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
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, close_tip):
"""进入申报查询列表 → (减员先关提示信息)→ 打开序号1记录「查看」→ 读审核结论。
返回 {证件号码: (审核结论, 业务流水号)}。"""
qtab = _open_query_page(page, tab)
if close_tip:
_close_tip_modal(qtab) # 去查看后会再弹一次「提示信息」,需先关闭
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
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
config.log(f" 第 {attempt + 1} 次查看未读到审核结论明细,重试")
_shot(qtab, "13_review_detail_miss")
time.sleep(1.5)
raise RuntimeError("未读取到审核结论明细表")
# ==================== 统一导入引擎 ====================
class ImportEngine:
"""按 kind(add/stop)配置的增/减员系统办理引擎。"""
def __init__(self, kind):
self.kind = kind
if kind == 'add':
self.business_item = "城保参保单位人员增加"
# 名单产出目录:按参保类型分文件夹(新参保-增员 / 转移参保-增员)
self.import_dir_names = {
"新参保": config.OUTPUT_DIR_ADD_NEW,
"转移参保": config.OUTPUT_DIR_ADD_TRANS,
}
self.file_suffix = "增员导入名单.xls"
self.fail_status = "参保失败"
self.close_tip = False
self.operation_type = config.WEB_ADD_TYPES
else:
self.business_item = "城保参保单位人员减少"
self.import_dir_names = {}
self.file_suffix = "减员导入名单.xls"
self.fail_status = "停保失败"
self.close_tip = True
self.operation_type = None
self.import_dir_name = config.OUTPUT_DIR_STOP if kind != 'add' else config.OUTPUT_DIR_ADD_NEW
self.writeback = Writeback(kind)
def _import_dir(self, op_type):
"""按参保类型取名单产出子目录(增员);减员固定「停保-减员」。"""
if self.kind == 'add':
return self.import_dir_names.get(op_type, config.OUTPUT_DIR_ADD_NEW)
return self.import_dir_name
# ---------------- 预检 ----------------
def precheck(self, units, accounts):
"""预检:核对每个(类型+单位)的导入文件与账号。返回待办列表。"""
tasks, errors = [], []
config.log("\n========== 预检 ==========")
for op_type, unit, count in units:
import_dir = config.roster_output_dir(self._import_dir(op_type))
file_path = os.path.join(import_dir, f"{config._safe_name(unit)}{self.file_suffix}")
acc = accounts.get(unit)
problems = []
if not os.path.isfile(file_path):
problems.append(f"缺导入文件({self._import_dir(op_type)}\\{os.path.basename(file_path)})")
if acc is None:
problems.append("台账未匹配(检查户头名/城市=重庆/是否在用=是)")
else:
if not acc["username"]:
problems.append("账号缺失(I列信用代码与K列平台用户名均为空)")
if not acc["password"]:
problems.append("密码缺失(L列平台密码为空)")
tag = f"{unit}({op_type or '停保'},{count}人)"
if problems:
errors.append(f"[{unit} {op_type or ''}] " + ";".join(problems))
config.log(f" ✗ {tag}:{';'.join(problems)}")
else:
tasks.append({"type": op_type, "unit": unit, "count": count, "file": file_path,
"username": acc["username"], "password": acc["password"]})
config.log(f" ✓ {tag} 账号={acc['username']}"
f"({acc['username_src']})文件={os.path.basename(file_path)}")
if errors:
config.log(f"\n预检未通过,共 {len(errors)} 个问题,请先修正后重跑:")
for e in errors:
config.log(f" - {e}")
return None
config.log(f"预检通过:{len(tasks)} 个待办理\n")
return tasks
# ---------------- 单个单位网页办理 ----------------
def do_web_import(self, task):
"""登录后的完整业务流程:进业务页 → 上传导入 → 校验回写 → 预申报提交 → 查询回写。"""
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, "imported": 0, "failed": [], "review": {}}
try:
_shot(work_tab, "01_workbench")
biz_tab = _open_business_page(page, work_tab, self.business_item)
if self.close_tip:
_close_tip_modal(biz_tab) # 减员:进业务页先关「提示信息」弹窗
_shot(biz_tab, "02_biz_upload_page")
# 1) 上传导入
total, _failed_cnt = _upload_import(biz_tab, task['file'], self.close_tip)
res['imported'] = total
# 2) 校验未通过:回写 参保失败/停保失败 + 备注(详细信息)
fail_rows = _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:
self.writeback.writeback_source(
{cid: self.fail_status for cid, _ in fail_rows},
{cid: d for cid, d in fail_rows})
passed = total
# 3) 全员未通过 → 跳过申报
if passed <= 0:
config.log(" 校验通过人数为 0,跳过申报")
res.update(success=True,
message=f"导入{total}人,全部校验未通过,已回写未申报")
return res
# 4) 预申报 → 正式提交 → 查询审核结论回写
_predeclare_and_submit(page, biz_tab, self.kind)
review = _query_review_results(page, biz_tab, self.close_tip)
res['review'] = [{"id": cid, "conclusion": c, "sn": sn}
for cid, (c, sn) in review.items()]
if review:
self.writeback.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(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.get('type') or '停保'},{task['count']}人)==========")
config.log(f"导入文件:{task['file']}")
if len(tasks) > 1:
config.progress(span_start + int((span_end - span_start) * (i - 1) / len(tasks)))
try:
login_res = web_login.ensure_login(task["username"], task["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_web_import(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)):
"""主流程:恢复缓存 → 读名单(排除已回写人员)→ 取号 → 预检 → 逐单位登录(+导入)→ 统一回写。
返回 JSON 安全 dict。"""
recovered_ids = self.writeback.load_ckpt()
units, source_file, source_sheet = source_reader.load_units(
self.kind, operation_type=self.operation_type, status_filter="empty",
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 units:
return {"success": True, "message": "无待办数据", "total": 0, "done": 0}
accounts = source_reader.load_accounts([u for _, u, _ in units])
tasks = self.precheck(units, accounts)
if tasks is None:
return {"success": False, "message": "预检未通过,详见日志",
"total": len(units), "done": 0}
limit = config.get_run_limit()
results = self.process_units(tasks[:limit], accounts, progress_span)
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"]]
config.log(f"\n========== 汇总 ==========")
config.log(f"成功 {len(ok)} 家,失败 {len(fail)} 家")
for r in fail:
config.log(f" ✗ {r['unit']}({r.get('type') or ''}):{r.get('message', '')}")
return {"success": not fail, "message": f"成功{len(ok)}/失败{len(fail)}",
"total": len(results), "done": len(ok)}
+483
View File
@@ -0,0 +1,483 @@
# -*- coding: utf-8 -*-
"""重庆人社网上服务大厅(政务平台)法人登录模块 —— XQ0014 专用(不共享登录态)。
每个参保单位一套账号(统一社会信用代码/用户名 + 密码),登录一次办一家的业务。
不做 cookies 缓存:政务平台 cookies 极易失效,缓存无意义;统一每次现场真登录
(浏览器走完整 SSO 流程 + ddddocr 识别图形验证码)。
登录流程:
1. 打开办事大厅页面 → 等待登录入口出现;
2. 点击「登录」→ 跳转新 tab 到 SSO(authcq.cqdcg.com:1443/sso/login);
3. 切换「法人用户」tab;
4. 输入账号(统一社会信用代码或政务平台用户名)+ 密码;
5. 元素截图截取图形验证码(base64 内嵌 PNG)→ ddddocr 识别 → 输入验证码;
6. 点击「登 录」→ 等待跳回办事大厅域名即成功;
7. 识别失败自动刷新验证码重试(验证码 5 次/轮 × 流程 3 轮)。
"""
import os
import time
import random
import base64
from .. import config
APPLY_URL = 'https://ggfw.rlsbj.cq.gov.cn/onlinehall/nethall/pc/cqzhrs/arrondi/ApplyOnline'
SSO_KEYWORD = 'authcq.cqdcg.com:1443/sso/login'
HOME_KEYWORD = 'ggfw.rlsbj.cq.gov.cn'
WORK_KEYWORD = 'onlineoffice/index' # 登录成功后新开的工作台 tab
RETRY_MAX = 5 # 验证码最大重试次数(每轮)
FLOW_RETRY = 3 # 整个登录流程最大轮数
TIMEOUT = 10 # 元素等待超时(秒)
HEADLESS = False
HUMAN_DELAY = (0.4, 1.2) # 操作间随机延时区间(秒),模拟人工降低脚本特征
def _captcha_debug_dir():
"""验证码调试图片目录(仅调试模式开启时落盘)。"""
return os.path.join(config.CKPT_DIR, 'debug_captcha')
# ================== 验证码识别(元素截图 + ddddocr) ==================
def _recognize_captcha(img_bytes):
"""ddddocr 识别图形验证码,返回文本。懒加载避免无关场景的导入开销。"""
import ddddocr
ocr = ddddocr.DdddOcr(show_ad=False)
return ocr.classification(img_bytes).strip()
def _dump_debug_captcha(img_bytes, text):
"""可选:落盘验证码调试图片(仅调试模式开启时),便于分析识别失败样本。"""
if not config.is_debug():
return
try:
d = _captcha_debug_dir()
os.makedirs(d, exist_ok=True)
path = os.path.join(d, f"captcha_{int(time.time() * 1000)}_{text or 'unknown'}.png")
with open(path, 'wb') as f:
f.write(img_bytes)
except Exception as e:
config.log(f"保存调试图片失败:{e}", "WARN")
def _find_input(tab, selectors):
"""按候选选择器顺序查找输入框。"""
for sel in selectors:
ele = tab.ele(sel, timeout=2)
if ele:
return ele
return None
def _find_captcha(tab):
"""定位验证码图片 + 输入框。
从验证码输入框的容器往上找(DOM 结构:div.normalCode > span包input + img.code),
避免命中页面其它 base64 图标(实测:img[src^=data:image] 会抓到 icon)。
"""
code_input = tab.ele('css:input[placeholder*="图形验证码"]', timeout=TIMEOUT)
img = None
if code_input:
holder = code_input.parent(2) # div.normalCode 容器
if holder:
img = holder.ele('tag:img', timeout=1)
if img is None:
img = tab.ele('css:.ant-tabs-tabpane-active img[src^="data:image"]', timeout=2)
return img, code_input
def _read_img_bytes(img):
"""验证码图转 bytes:优先直接解码 base64 src(像素无损、无 DPR 缩放),失败退回元素截图。"""
try:
src = img.attr('src') or ''
if 'base64,' in src:
return base64.b64decode(src.split('base64,', 1)[1])
except Exception:
pass
return img.get_screenshot(as_bytes='png')
# ================== 登录主流程 ==================
def _human_pause(a=None, b=None):
"""操作间随机延时,模拟人工节奏。"""
lo, hi = HUMAN_DELAY if (a is None or b is None) else (a, b)
time.sleep(random.uniform(lo, hi))
def _dismiss_notice(page):
"""关闭首页/工作台弹窗(「温馨提示」我知道了、授权提示同意等),避免遮挡操作。"""
candidates = [
'tag:button@@text()=我知道了',
'tag:button@@text()=知道了',
'tag:button@@text()=同意',
'tag:button@@text()=确定',
]
for _ in range(3):
btn = None
for sel in candidates:
try:
btn = page.ele(sel, timeout=1)
except Exception:
btn = None
if btn:
break
if not btn:
return
try:
btn.click()
config.log(f"已关闭弹窗(点击:{btn.text.strip()})")
time.sleep(0.5)
except Exception:
time.sleep(0.5)
def _sso_form_ready(t):
"""判断某 tab 是否已是渲染完成的 SSO 登录页:URL 在 SSO 且「法人用户」tab 已出现。
注意用 text()= 精确匹配——text(): 模糊匹配会命中包含该文字的外层容器 div。"""
try:
if SSO_KEYWORD not in t.url:
return False
return bool(t.ele('tag:div@@text()=法人用户', timeout=0.5))
except Exception:
return False
def _wait_sso_ready(tab):
"""等 SSO 登录页彻底稳定(URL 不再跳变 + 表单已渲染),再开始操作。"""
last_url = None
for _ in range(60): # 最多等 30 秒
try:
url = tab.url
except Exception:
return False
stable = (url == last_url)
last_url = url
if _sso_form_ready(tab) and stable:
break
time.sleep(0.5)
time.sleep(1.5) # 再缓冲,确保 React 渲染完成
return True
def _is_work_tab(t):
"""是否登录完成的工作台页(onlineoffice/index)。
必须 origin 前缀匹配 + 路径含 onlineoffice/index——跳转链中间页的 redirectUrl 参数也含
ggfw/onlinehall 字样,用包含匹配会误判。"""
try:
u = (t.url or '').strip()
except Exception:
return False
return u.startswith('https://' + HOME_KEYWORD) and WORK_KEYWORD in u
def _open_sso_tab(page):
"""点击首页「登录」,等待新 tab 打开、跳转链结束且登录表单渲染完成后返回。
返回 (tab, already_logged):
already_logged=False → SSO 登录页(需填表)
already_logged=True → SSO 会话有效直接跳回大厅(登录成功,无需填表)"""
_dismiss_notice(page)
login_link = page.ele('css:[class*="loginBox"] a', timeout=TIMEOUT)
if not login_link:
login_link = page.ele('tag:a@@text():登录', timeout=TIMEOUT)
if not login_link:
config.log("未找到登录入口(可能残留上一账号登录态),清除 cookies 后重试", "WARN")
try:
page.clear_cache(cookies=True)
except Exception:
try:
page.run_js("document.cookie.split(';').forEach(c=>{"
"document.cookie=c.trim().split('=')[0]+"
"'=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/'});")
except Exception:
pass
page.get(APPLY_URL)
time.sleep(2)
login_link = page.ele('css:[class*="loginBox"] a', timeout=TIMEOUT) \
or page.ele('tag:a@@text():登录', timeout=TIMEOUT)
if not login_link:
config.log("找不到登录入口(首页可能已是登录态)", "WARN")
return None, False
before_ids = set(page.tab_ids)
login_link.click()
tab = None
for _ in range(90): # 最多等 45 秒
time.sleep(0.5)
for tid in [i for i in page.tab_ids if i not in before_ids]:
try:
t = page.get_tab(tid)
except Exception:
continue
if _is_work_tab(t):
config.log(f"SSO 会话有效,已直接登录:{t.url}")
_close_extra_tabs(page, before_ids, t)
_dismiss_notice(t)
return t, True
if _sso_form_ready(t):
tab = t
break
if tab:
break
if tab is None:
if _sso_form_ready(page):
return page, False
config.log("点击登录后未检测到就绪的 SSO 登录页", "WARN")
return None, False
_close_extra_tabs(page, before_ids, tab)
return tab, False
def _close_extra_tabs(page, before_ids, keep_tab):
"""关掉一次「点登录」产生的多余新开 tab(中转页等),保持会话干净。"""
for tid in [i for i in page.tab_ids if i not in before_ids and i != keep_tab.tab_id]:
try:
page.get_tab(tid).close()
except Exception:
pass
def _try_login_once(tab, page, username, password, retry_index):
"""在 SSO tab 内完成一次填表 + 验证码 + 提交。返回 True 表示登录成功。"""
_wait_sso_ready(tab)
legal_tab = tab.ele('tag:div@@text()=法人用户', timeout=TIMEOUT)
if legal_tab:
legal_tab.click()
_human_pause(0.3, 0.8)
for _ in range(3):
active = tab.ele('css:.ant-tabs-tab-active .ant-tabs-tab-btn', timeout=2)
if active and active.text.strip() == '法人用户':
break
if legal_tab:
try:
legal_tab.click()
except Exception:
pass
time.sleep(1)
# 账号(统一社会信用代码)+ 密码
user_input = _find_input(tab, [
'css:input[placeholder*="统一社会信用代码"]',
'css:input[placeholder*="社会信用代码"]',
'css:#identifier',
])
if not user_input:
config.log("找不到账号输入框", "ERROR")
return False
user_input.clear()
user_input.input(username)
_human_pause()
pwd_input = _find_input(tab, ['css:#password', 'css:input[type="password"]'])
if not pwd_input:
config.log("找不到密码输入框", "ERROR")
return False
pwd_input.clear()
pwd_input.input(password)
_human_pause()
for attempt in range(RETRY_MAX):
config.log(f"--- 第 {retry_index}-{attempt + 1} 次验证码识别 ---")
img, code_input = _find_captcha(tab)
if not img or not code_input:
config.log("找不到验证码图片或输入框", "ERROR")
return False
img_bytes = _read_img_bytes(img)
if not img_bytes:
config.log("验证码图数据为空", "WARN")
time.sleep(1)
continue
try:
code = _recognize_captcha(img_bytes)
except Exception as e:
config.log(f"ddddocr 识别异常:{e}", "ERROR")
return False
config.log(f" 识别结果:{code!r}")
if not code:
_refresh_captcha(tab, img)
continue
code = code.upper() # 页面显示为大写,按大写提交
_dump_debug_captcha(img_bytes, code)
code_input.clear()
code_input.input(code)
_human_pause(0.3, 0.9)
btn = tab.ele('css:button[type="submit"]', timeout=TIMEOUT) \
or tab.ele('tag:button@@text():登录', timeout=TIMEOUT)
if not btn:
config.log("找不到登录提交按钮", "ERROR")
return False
_human_pause(0.2, 0.6)
btn.click()
ok, work_tab = _wait_login_result(tab, page)
if ok:
_try_login_once.work_tab = work_tab # 供 _do_login 保存会话
return True
_refresh_captcha(tab, img)
return False
def _wait_login_result(tab, page):
"""提交后轮询判定登录结果。返回 (ok, work_tab)。"""
before_ids = set(page.tab_ids)
for _ in range(30): # 最多等 15 秒
time.sleep(0.5)
for tid in [i for i in page.tab_ids if i not in before_ids]:
try:
t = page.get_tab(tid)
except Exception:
continue
if _is_work_tab(t):
config.log(f"登录成功(新开工作台 tab):{t.url}")
_close_extra_tabs(page, before_ids, t)
_dismiss_notice(t)
return True, t
try:
url = (tab.url or '').strip()
except Exception:
url = ''
if url.startswith('https://' + HOME_KEYWORD) and SSO_KEYWORD not in url and WORK_KEYWORD in url:
config.log(f"登录成功,已跳转:{url}")
_dismiss_notice(tab)
return True, tab
try:
err = tab.ele('css:.ant-message-error', timeout=0.5)
if err:
config.log(f"登录失败提示:{err.text}")
return False, None
except Exception:
pass
config.log("等待登录结果超时", "WARN")
return False, None
def _refresh_captcha(tab, img):
"""点击验证码图片刷新,校验 base64 src 是否真的变化(连续点 2 次)。"""
try:
old = img.attr('src') or ''
except Exception:
old = ''
for _ in range(2):
try:
img.click()
except Exception:
try:
img.click(by_js=True)
except Exception:
pass
for _p in range(10):
time.sleep(0.3)
try:
new = img.attr('src') or ''
except Exception:
new = old
if new and new != old:
return True
config.log("警告:验证码图片刷新后未变化", "WARN")
return False
LAST_SESSION = {'page': None, 'tab': None} # 登录成功后保留的浏览器会话(供后续网页操作使用)
def _teardown(page):
"""清 cookies/本地存储后关浏览器(账号切换彻底隔离,避免残留登录态)。"""
if page is None:
return
try:
page.clear_cache(cookies=True, local_storage=True, session_storage=True)
except Exception:
try:
page.clear_cache()
except Exception:
pass
try:
page.quit()
except Exception:
pass
def close_session():
"""清 cookies 并关闭当前保留的登录会话(每个账号业务办完后必须调用)。"""
_teardown(LAST_SESSION['page'])
LAST_SESSION['page'] = None
LAST_SESSION['tab'] = None
def _do_login(username, password):
"""打开浏览器现场完成登录(含图形验证码)。不做任何 cookies 缓存。
成功保留浏览器会话(工作台 tab 供后续导入操作),失败关闭浏览器。
返回 (ok, work_tab)。"""
from DrissionPage import ChromiumPage, ChromiumOptions
close_session() # 账号切换隔离
co = ChromiumOptions()
if HEADLESS:
co.headless()
co.auto_port(True) # 每次启动独立端口+独立临时用户目录,账号间 cookies 天然隔离
co.set_argument('--start-maximized')
co.set_pref('credentials_enable_service', False)
co.set_pref('profile.password_manager_enabled', False)
page = ChromiumPage(co)
work_tab_holder = {'tab': None}
def _finish(ok):
if ok:
LAST_SESSION['page'] = page
LAST_SESSION['tab'] = work_tab_holder['tab']
return True, work_tab_holder['tab']
_teardown(page)
return False, None
try:
page.get(APPLY_URL)
_human_pause(1.0, 2.5)
tab = None
for retry in range(FLOW_RETRY):
try:
_dismiss_notice(page)
if tab is not None:
try:
if SSO_KEYWORD not in tab.url:
tab = None
except Exception:
tab = None
if tab is None:
tab, already = _open_sso_tab(page)
if tab is None:
config.log(f"进入 SSO 登录页失败(第 {retry + 1}/{FLOW_RETRY} 轮)", "WARN")
time.sleep(2)
continue
if already:
work_tab_holder['tab'] = tab
return _finish(True)
if _try_login_once(tab, page, username, password, retry + 1):
work_tab_holder['tab'] = getattr(_try_login_once, 'work_tab', None) or tab
return _finish(True)
try:
tab.refresh()
time.sleep(2)
except Exception:
pass
except Exception as e:
config.log(f"第 {retry + 1}/{FLOW_RETRY} 轮流程异常(将重试):{e}", "WARN")
time.sleep(1)
config.log("登录失败(验证码识别未通过或流程异常)", "ERROR")
return _finish(False)
except Exception:
_teardown(page)
raise
def ensure_login(username, password):
"""以指定账号现场登录政务平台(无缓存,每次真登录)。
返回 JSON 安全 dict:{success, username, message}"""
username = (username or '').strip()
password = (password or '').strip()
if not (username and password):
return {"success": False, "username": username,
"message": "登录账号/密码缺失(台账未取到账号密码)"}
ok, _work_tab = _do_login(username, password)
if ok:
return {"success": True, "username": username, "message": "登录成功"}
return {"success": False, "username": username,
"message": "登录失败(验证码识别未通过或流程异常)"}
+661
View File
@@ -0,0 +1,661 @@
# -*- 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)}