feat(xq0002): 新增钉钉群通知推送功能,优化雇主险增减操作流程

This commit is contained in:
2026-10-05 09:42:56 +08:00
parent 26d4125798
commit 41bcb44e34
83 changed files with 11419 additions and 180 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}
+815
View File
@@ -0,0 +1,815 @@
# -*- coding: utf-8 -*-
"""告知书制作与下发(XQ0015/XQ0016 notice_mail_merge.py 移植,统一目录版)。
与名单制作/系统办理共用同一 base_dir 根目录:
- 数据源:{base_dir}/*社保变更及增减名单*.xlsx(当前月文件;参保名单 sheet / 变更-* sheet)
- 模板:{base_dir}/告知书下发/模板/员工参与社会保险告知书模板.docx、
{base_dir}/告知书下发/模板/参保异常告知模板.docx、{base_dir}/告知书下发/模板/社保转移告知模板.docx
- 花名册:{base_dir}/员工花名册.xlsx(二级部门解析 + OA 接收人查找)
- 输出:{base_dir}/告知书下发/输出/YYYYMM/<告知书类型>/ 下 docx + pdf,并按(二级部门,参保单位)分组合并
三类告知书:
- 员工参与社会保险告知书(办理状态=已参 & 参保类型=新参保 & 参保告知空)
- 参保异常告知书(办理状态=参保失败 & 参保类型=新参保 & 参保告知空)
- 社保转移告知书(变更-* sheet 中 是否变更=是)
OA 工作沟通推送数据:build_work_communication_data 构造后落盘到
{输出}/YYYYMM/oa_messages.json;真实 OA 推送由 __init__ 阶段(启用推送开关时)调 oa_push 完成。
"""
import os
import re
import time
import shutil
import random
import functools
import subprocess
from copy import deepcopy
from datetime import datetime
from .. import config
logger = config.logger
# ==================== 重试装饰器(全局重试3次,AGENTS.md) ====================
class RetryExhaustedError(Exception):
pass
def retry(max_attempts: int = 3, no_retry_on: tuple = ()):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
last_exc = None
for attempt in range(1, max_attempts + 1):
try:
return func(*args, **kwargs)
except no_retry_on:
raise
except Exception as e:
last_exc = e
if attempt >= max_attempts:
logger.error("%s 连续 %d 次尝试失败: %s", func.__name__, max_attempts, e)
break
delay = 1.0 * (2.0 ** (attempt - 1)) * random.uniform(0.5, 1.5)
logger.warning("%s 第 %d 次失败: %s,%.2f 秒后重试", func.__name__, attempt, e, delay)
time.sleep(delay)
raise RetryExhaustedError(
f"{func.__name__} failed after {max_attempts} attempts, last error: {last_exc}"
) from last_exc
return wrapper
return decorator
# ==================== 路径(统一目录 = base_dir) ====================
def _base_dir():
return config.get_base_dir()
def _output_root():
return config.notice_output_root()
def _roster_path():
return os.path.join(_base_dir(), "员工花名册.xlsx")
def _template_path(rule_name):
rel = config.NOTICE_TEMPLATES[rule_name]["file"]
return os.path.join(config.notice_template_dir(), rel)
def _find_current_month_excel(dir_path):
"""在目录内查找文件名月份=当月的源名单 xlsx(历史月份/缺失均报错)。"""
if not os.path.isdir(dir_path):
raise FileNotFoundError(f"目录不存在:{dir_path}")
now = datetime.now()
current_ym = (now.year, now.month)
kw = config.SOURCE_KEYWORD
found = [n for n in os.listdir(dir_path)
if kw in n and n.lower().endswith(".xlsx") and not n.startswith("~$")]
if not found:
raise FileNotFoundError(f"目录 {dir_path} 下未找到包含「{kw}」的 xlsx 文件")
current = sorted(
(n for n in found if _extract_ym(n) == current_ym),
key=lambda n: os.path.getmtime(os.path.join(dir_path, n)))
if not current:
raise FileNotFoundError(
f"目录 {dir_path} 下包含「{kw}」的文件均非当前月份 "
f"{now.year}年{now.month}月:{found}")
return os.path.join(dir_path, current[-1])
# ==================== 基础工具 ====================
def _fmt_num(value) -> str:
"""金额格式化:509 -> '509';467.42 -> '467.42';#N/A 等错误值返回 ''。"""
if value is None:
return ""
s = str(value).strip()
if s in ("", "#N/A", "#REF!", "#VALUE!", "NA", "None"):
return ""
try:
f = float(value)
except (TypeError, ValueError):
return s
if f == int(f):
return str(int(f))
return ("%.2f" % f).rstrip("0").rstrip(".")
def _match_rule(rec: dict, status: str, ins_type: str) -> bool:
"""按模板规则 + 参保告知为空 判断记录是否命中。"""
if str(rec.get("办理状态") or "").strip() != status:
return False
if str(rec.get("参保类型") or "").strip() != ins_type:
return False
return not str(rec.get("参保告知") or "").strip()
def _extract_ym(filename: str):
"""从文件名解析 (年, 月);支持 '202609' 与 '2026年9月' 两种格式;失败返回 None。"""
m = re.search(r"(20\d{2})年(\d{1,2})月", filename)
if m:
return (int(m.group(1)), int(m.group(2)))
m = re.search(r"(20\d{2})(\d{2})", filename)
if m:
return (int(m.group(1)), int(m.group(2)))
return None
def _read_insurance_records(excel_path: str) -> list:
"""读取「参保名单」sheet,返回人员记录列表(dict,key=表头字段名)。"""
import openpyxl
wb = openpyxl.load_workbook(excel_path, read_only=True, data_only=True)
try:
sheet = None
for ws in wb.worksheets:
if config.SHEET_KEY_ADD in ws.title:
sheet = ws
break
if sheet is None:
raise ValueError(f"工作簿 {excel_path} 中未找到包含「{config.SHEET_KEY_ADD}」的 sheet")
header = [c.value for c in next(sheet.iter_rows(
min_row=config.NOTICE_HEADER_ROW, max_row=config.NOTICE_HEADER_ROW,
max_col=config.NOTICE_MAIN_COLS))]
col_names = {i: str(h).strip() for i, h in enumerate(header) if h}
if "姓名" not in col_names.values() or "办理状态" not in col_names.values():
raise ValueError(f"「{sheet.title}」第{config.NOTICE_HEADER_ROW}行未解析到标准表头")
records = []
for row in sheet.iter_rows(min_row=config.NOTICE_HEADER_ROW + 1,
max_row=sheet.max_row, max_col=config.NOTICE_MAIN_COLS):
values = [c.value for c in row]
if all(v is None for v in values):
continue
rec = {name: values[i] for i, name in col_names.items() if i < len(values)}
if rec.get("姓名") is not None:
records.append(rec)
return records
finally:
wb.close()
def _build_placeholders(rec: dict, ym: tuple) -> dict:
"""根据记录与目标月份计算占位符替换值。"""
y, m = ym
next_y, next_m = (y, m + 1) if m < 12 else (y + 1, 1)
today = datetime.now()
fee_txt = _fmt_num(rec.get("费用"))
try:
fee_num = float(rec.get("费用"))
once_txt = _fmt_num(fee_num * 2)
except (TypeError, ValueError):
once_txt = ""
return {
"{{姓名}}": str(rec.get("姓名") or ""),
"{{四级部门}}": str(rec.get("四级部门") or ""),
"{{参保单位全称}}": str(rec.get("参保单位全称") or ""),
"{{区域}}": str(rec.get("区域") or ""),
"{{费用}}": fee_txt,
"{{备注}}": str(rec.get("备注") or ""),
"{{一次性扣款}}": once_txt,
"{{当前月}}": f"{m}",
"{{下月}}": f"{next_m}",
"{{当月15日}}": f"{m}月15日",
"{{制作日年份}}": str(today.year),
"{{制作日月份}}": str(today.month),
"{{制作日天}}": str(today.day),
}
# ==================== Word 占位符替换 ====================
def _replace_in_paragraph(p, mapping: dict) -> None:
runs = p.runs
if not runs:
return
full = "".join(r.text for r in runs)
if not any(k in full for k in mapping):
return
for r in runs:
t = r.text
for k, v in mapping.items():
if k in t:
t = t.replace(k, v)
r.text = t
for k, v in mapping.items():
if k in full and not any(k in r.text for r in runs):
for i in range(len(runs)):
rt = runs[i].text
if k in rt:
continue
start = None
for L in range(min(len(rt), len(k)), 0, -1):
if rt[-L:] == k[:L]:
start = len(rt) - L
break
if start is None:
continue
acc = rt
j = i
while k not in acc and j + 1 < len(runs):
j += 1
acc += runs[j].text
if k in acc:
runs[i].text = acc.replace(k, v)
for x in range(i + 1, j + 1):
runs[x].text = ""
break
def _fill_doc(template_path: str, mapping: dict):
"""读取模板并替换占位符,返回内存中的 Document 对象(不保存)。"""
from docx import Document
if not os.path.exists(template_path):
raise FileNotFoundError(f"模板不存在:{template_path}")
doc = Document(template_path)
norm = dict(config.LEGACY_PLACEHOLDERS)
norm.update(mapping)
for para in doc.paragraphs:
_replace_in_paragraph(para, norm)
for tbl in doc.tables:
for row in tbl.rows:
for cell in row.cells:
for para in cell.paragraphs:
_replace_in_paragraph(para, norm)
return doc
def _leftover_placeholders(doc) -> set:
"""统计文档(含表格)中残留的 {{...}} 占位符。"""
leftover = set()
for para in doc.paragraphs:
leftover.update(re.findall(r"\{\{.*?\}\}", para.text))
for tbl in doc.tables:
for row in tbl.rows:
for cell in row.cells:
for para in cell.paragraphs:
leftover.update(re.findall(r"\{\{.*?\}\}", para.text))
return leftover
def _merge_notice_docs(docs):
"""把多份已填充的告知书 Document 合并为一份(每份之间插入分页符)。"""
from docx.enum.text import WD_BREAK
from docx.oxml.ns import qn
base = docs[0]
body = base.element.body
sect_pr = body.find(qn("w:sectPr"))
for d in docs[1:]:
p = base.add_paragraph()
p.add_run().add_break(WD_BREAK.PAGE)
for child in list(d.element.body):
if child.tag == qn("w:sectPr"):
continue
if sect_pr is not None:
sect_pr.addprevious(deepcopy(child))
else:
body.append(deepcopy(child))
return base
def _safe_filename(name: str) -> str:
"""过滤 Windows 文件名非法字符。"""
for ch in '\\/:*?"<>|':
name = name.replace(ch, "_")
return name.strip() or "未命名"
# ==================== PDF 转换(优先 WPS COM,失败回退 kwpsconvert 命令行) ====================
def _find_kwpsconvert() -> str:
"""定位 WPS 自带转换器 kwpsconvert.exe。"""
env = os.getenv("wps_kwpsconvert")
if env and os.path.isfile(env):
return env
bases = [
os.path.join(os.environ.get("LOCALAPPDATA", ""), "Kingsoft", "WPS Office"),
os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), "Kingsoft", "WPS Office"),
os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "Kingsoft", "WPS Office"),
]
for base in bases:
if not base or not os.path.isdir(base):
continue
for ver_dir in os.listdir(base):
cand = os.path.join(base, ver_dir, "office6", "kwpsconvert.exe")
if os.path.isfile(cand):
return cand
exe = shutil.which("kwpsconvert")
return exe or ""
def _publish_via_kwpsconvert(src_docx: str, target_pdf: str) -> None:
"""用 WPS 命令行 kwpsconvert.exe word2pdf 把 docx 转 PDF(兼容 32 位 WPS)。"""
exe = _find_kwpsconvert()
if not exe:
raise RuntimeError("未找到 kwpsconvert.exe(WPS 命令行转换器),可设置环境变量 wps_kwpsconvert 指定路径")
src_docx = os.path.abspath(src_docx)
target_pdf = os.path.abspath(target_pdf)
os.makedirs(os.path.dirname(target_pdf), exist_ok=True)
if os.path.exists(target_pdf):
os.remove(target_pdf)
cmd = [exe, "word2pdf", src_docx, "-o", target_pdf]
kwargs = {}
if os.name == "nt":
kwargs["creationflags"] = 0x08000000 # CREATE_NO_WINDOW
proc = subprocess.run(cmd, capture_output=True, timeout=300, **kwargs)
if proc.returncode != 0:
err = (proc.stderr or proc.stdout or b"").decode("gbk", errors="ignore").strip()
raise RuntimeError(f"kwpsconvert 转换失败(exit={proc.returncode}): {err or target_pdf}")
if not os.path.exists(target_pdf):
raise RuntimeError(f"kwpsconvert 转换后未生成 PDF:{target_pdf}")
logger.info("kwpsconvert 转换成功:%s", os.path.basename(target_pdf))
@retry(max_attempts=3)
def _publish_via_wps(src_docx: str, target_docx: str, target_pdf: str) -> None:
"""导出 target_pdf:优先 WPS 文字 COM(Kwps.Application),失败自动回退 kwpsconvert。"""
import win32com.client
os.makedirs(os.path.dirname(target_docx), exist_ok=True)
src_docx = os.path.abspath(src_docx)
target_docx = os.path.abspath(target_docx)
target_pdf = os.path.abspath(target_pdf)
try:
app = None
try:
app = win32com.client.Dispatch("Kwps.Application")
app.Visible = False
try:
app.DisplayAlerts = 0
except Exception:
pass
doc = app.Documents.Open(src_docx)
try:
try:
doc.SaveAs2(target_docx, 12) # 12 = wdFormatXMLDocument
except Exception:
doc.SaveAs(target_docx, 12)
doc.ExportAsFixedFormat(target_pdf, 17) # 17 = wdFormatPDF
finally:
doc.Close(False)
finally:
if app is not None:
try:
app.Quit()
except Exception:
pass
except Exception as e:
logger.warning("WPS COM 转换失败(%s),自动回退 kwpsconvert 命令行", e)
_publish_via_kwpsconvert(src_docx, target_pdf)
# ==================== 花名册与接收人解析 ====================
def _norm_code(value):
"""工号统一转文本:浮点整数去掉小数部分。"""
if value is None:
return None
try:
f = float(value)
if f.is_integer():
return str(int(f))
except (TypeError, ValueError):
pass
s = str(value).strip()
return s or None
def _read_roster_map(roster_path: str) -> dict:
"""读取花名册,返回 {工号: {姓名, 二级部门, 四级部门, 岗位}}。"""
import openpyxl
if not os.path.exists(roster_path):
raise FileNotFoundError(f"花名册文件不存在:{roster_path}")
wb = openpyxl.load_workbook(roster_path, read_only=True, data_only=True)
try:
ws = wb.active
col_idx, header_row = {}, None
for row in ws.iter_rows():
if header_row is None:
names = {str(c.value).strip(): i for i, c in enumerate(row) if c.value is not None}
if "工号" in names:
col_idx, header_row = names, row[0].row
break
if header_row is None:
raise ValueError(f"花名册未找到表头行(缺少「工号」字段):{roster_path}")
need = ("工号", "姓名", "二级部门", "四级部门", "岗位")
missing = [c for c in need if c not in col_idx]
if missing:
raise ValueError(f"花名册缺少必需列:{missing}")
def _cell(vals, key):
i = col_idx[key]
return vals[i] if i < len(vals) else None
result = {}
for row in ws.iter_rows(min_row=header_row + 1):
vals = [c.value for c in row]
code = _norm_code(_cell(vals, "工号"))
if not code:
continue
result[code] = {
"姓名": str(_cell(vals, "姓名") or ""),
"二级部门": str(_cell(vals, "二级部门") or ""),
"四级部门": str(_cell(vals, "四级部门") or ""),
"岗位": str(_cell(vals, "岗位") or ""),
}
return result
finally:
wb.close()
def _fill_dept4(rec: dict, roster_map: dict) -> str:
"""四级部门:源数据缺失时查花名册(按37工号),仍缺失 fallback 二级部门。"""
dept4 = str(rec.get("四级部门") or "").strip()
if dept4:
return dept4
code = _norm_code(rec.get("37工号"))
if code and roster_map and code in roster_map:
dept4 = str(roster_map[code].get("四级部门") or "").strip()
if dept4:
return dept4
return str(rec.get("二级部门") or "").strip() or "未知"
def _read_transfer_records(excel_path: str, roster_map: dict = None) -> list:
"""读取社保转移数据(变更-职能及干部/变更-门店 sheet,是否变更=是)。"""
import openpyxl
roster_map = roster_map or {}
wb = openpyxl.load_workbook(excel_path, read_only=True, data_only=True)
try:
records = []
for ws in wb.worksheets:
if not any(kw in ws.title for kw in config.TRANSFER_SHEET_GENERATE):
continue
col_idx, header_row = None, None
for row in ws.iter_rows():
if header_row is None:
names = {str(c.value).strip(): i for i, c in enumerate(row) if c.value is not None}
if "37工号" in names and config.TRANSFER_CHANGE_COL in names:
col_idx, header_row = names, row[0].row
break
if header_row is None:
continue
def _cell(vals, key):
i = col_idx.get(key)
return vals[i] if i is not None and i < len(vals) else None
for row in ws.iter_rows(min_row=header_row + 1):
vals = [c.value for c in row]
if all(v is None for v in vals):
continue
if str(_cell(vals, config.TRANSFER_CHANGE_COL) or "").strip() != config.TRANSFER_CHANGE_VALUE:
continue
rec = {}
for src, std in config.TRANSFER_COL_MAP.items():
if src in col_idx:
rec[std] = _cell(vals, src)
for key in ("姓名", "二级部门", "四级部门", "37工号", "备注"):
if key in col_idx:
rec[key] = _cell(vals, key)
full_key = "全称" if "全称" in col_idx else "参保单位全称"
if full_key in col_idx:
rec["参保单位全称"] = _cell(vals, full_key)
if "转移参保单位" in col_idx:
rec["转移参保单位"] = _cell(vals, "转移参保单位")
if rec.get("姓名") is None:
continue
rec["_source"] = ws.title
rec["四级部门"] = _fill_dept4(rec, roster_map)
if not rec.get("工号") and rec.get("37工号") is not None:
rec["工号"] = rec["37工号"]
records.append(rec)
return records
finally:
wb.close()
def _ins_org_of(rec: dict) -> str:
"""取记录参保单位标识:优先「参保单位」简称,其次全称/当前参保单位。"""
for key in ("参保单位", "参保单位全称", "当前参保单位"):
v = str(rec.get(key) or "").strip()
if v:
return v
return ""
def _trans_org_of(rec: dict) -> str:
"""取记录转移参保单位(告知书文件名第二段用)。"""
v = str(rec.get("转移参保单位") or "").strip()
return v or _ins_org_of(rec)
def _resolve_dept2(rec: dict, all_records: list, roster_map: dict):
"""解析记录的正确二级部门(经营中心),优先数据源内参保单位聚合,兜底记录自身/花名册反查。"""
ins = _ins_org_of(rec)
if not ins:
return None
dept2s = {str(r.get("二级部门") or "").strip()
for r in all_records if _ins_org_of(r) == ins}
dept2s.discard("")
if len(dept2s) == 1:
return dept2s.pop()
own = str(rec.get("二级部门") or "").strip()
if own:
return own
dept2s = {str(it.get("二级部门") or "").strip()
for it in roster_map.values()
if str(it.get("四级部门") or "").strip() == ins}
dept2s.discard("")
if len(dept2s) == 1:
return dept2s.pop()
return None
def _find_store_manager_in_map(roster_map: dict, code: str):
"""查店长(同四级部门岗位含「店长」,按行序取第一个)。"""
info = roster_map.get(code)
if not info or not info["四级部门"]:
return None
for c, it in roster_map.items():
if it["四级部门"] == info["四级部门"] and "店长" in it["岗位"]:
return c
return None
def _find_hr_personnel_in_map(roster_map: dict, code: str, dept2: str = None) -> list:
"""查人事/推送人:二级部门命中 DEPT2_PUSH_OVERRIDE 直接返回;其次石桥铺会馆固定;再兜底岗位含人事。"""
info = roster_map.get(code)
if not info:
return []
dept2 = dept2 or info["二级部门"]
if dept2 in config.DEPT2_PUSH_OVERRIDE:
return list(config.DEPT2_PUSH_OVERRIDE[dept2])
if dept2 in config.DEPT2_HR_OVERRIDE:
return list(config.DEPT2_HR_OVERRIDE[dept2])
if "经营中心" not in dept2:
return []
return [c for c, it in roster_map.items()
if it["二级部门"] == dept2 and "人事" in it["岗位"]]
def _resolve_receivers(roster_map: dict, codes: list, dept2_map: dict = None) -> list:
"""为员工工号列表解析接收人(店长+人事),按出现顺序去重。"""
dept2_map = dept2_map or {}
receivers = []
for code in codes:
mgr = _find_store_manager_in_map(roster_map, code)
if mgr and mgr not in receivers:
receivers.append(mgr)
for hr in _find_hr_personnel_in_map(roster_map, code, dept2_map.get(code)):
if hr and hr not in receivers:
receivers.append(hr)
return receivers
# ==================== OA 推送数据构造 ====================
def _collect_rule_pdfs(month_dir: str, rule_folder: str) -> list:
"""收集该类型输出目录下全部告知书 PDF 附件路径。"""
folder = os.path.join(month_dir, rule_folder)
if not os.path.isdir(folder):
return []
return [os.path.join(folder, f) for f in sorted(os.listdir(folder))
if f.lower().endswith(".pdf")]
def _text_to_html(text: str) -> str:
"""多行纯文本转 HTML(@@R 前缀=右对齐落款)。"""
parts = []
for ln in str(text).splitlines():
ln = ln.strip()
if not ln:
continue
if ln.startswith("@@R"):
parts.append(f'<p style="text-align:right">{ln[3:]}</p>')
else:
parts.append(f'<p style="text-indent:2em">{ln}</p>')
return "".join(parts)
def _highlight_text(text: str, highlights: tuple, m: int = None) -> str:
"""给文案关键词加颜色高亮(keyword 支持 {m} 月份占位符)。"""
for keyword, color in highlights:
kw = keyword.format(m=m) if m is not None else keyword
text = text.replace(kw, f'<span style="color:{color}">{kw}</span>')
return text
def build_work_communication_data(branch: str, output_dir: str = None, ym: tuple = None,
roster_path: str = None) -> list:
"""按分支构造 OA 工作沟通推送数据(附件=该类型输出目录下全部告知书 PDF;
接收人=店长+人事并统一追加抄送人)。返回 messages 列表,并落盘 oa_messages.json。"""
import json as _json
if branch not in config.NOTICE_BRANCHES:
raise ValueError(f"未知分支:{branch},可选 {list(config.NOTICE_BRANCHES)}")
output_dir = output_dir or _output_root()
ym = ym or (datetime.now().year, datetime.now().month)
y, m = ym
month_dir = os.path.join(output_dir, f"{y}{m:02d}")
roster_path = roster_path or _roster_path()
logger.info("构造 OA 工作沟通数据:分支=%s(%d-%02d)", branch, y, m)
excel_path = _find_current_month_excel(_base_dir())
try:
roster_map = _read_roster_map(roster_path)
except Exception as e:
logger.warning("花名册读取失败,二级部门解析/接收人查找将受限:%s", e)
roster_map = {}
logger.info("花名册共 %d 人:%s", len(roster_map), roster_path)
matched_by_rule = {}
if branch == "转移参保":
transfer_records = _read_transfer_records(excel_path, roster_map)
matched_by_rule["社保转移"] = [
r for r in transfer_records if config.TRANSFER_SHEET_PUSH in str(r.get("_source") or "")]
logger.info("[社保转移] 命中 %d 人", len(matched_by_rule["社保转移"]))
all_records = transfer_records
rule_keys = ("社保转移",)
else:
records = _read_insurance_records(excel_path)
all_records = records
rule_keys = ("新参保", "参保异常")
for rule_name in rule_keys:
rule = config.NOTICE_TEMPLATES[rule_name]
matched_by_rule[rule_name] = [
r for r in records if _match_rule(r, rule["status"], rule["type"])]
logger.info("[%s] 命中 %d 人", rule_name, len(matched_by_rule[rule_name]))
messages = []
for tpl in config.NOTICE_OA_MESSAGE_TEMPLATES:
if not any(rn in rule_keys for rn in tpl["rule_keys"]):
continue
matched_recs = []
for rn in tpl["rule_keys"]:
matched_recs.extend(matched_by_rule.get(rn, []))
attachment_paths = []
for rn in tpl["rule_keys"]:
attachment_paths.extend(_collect_rule_pdfs(month_dir, config.NOTICE_TEMPLATES[rn]["folder"]))
attachment_paths = sorted(attachment_paths,
key=lambda p: (os.path.basename(p).split("_", 1)[0], os.path.basename(p)))
if not attachment_paths:
logger.warning("[%s] 未收集到告知书 PDF(请先执行告知书生成),跳过该推送", tpl["key"])
continue
dept2_by_code, codes = {}, []
for r in matched_recs:
c = _norm_code(r.get("工号"))
if not c:
logger.warning("员工「%s」无工号,跳过接收人解析", r.get("姓名"))
continue
d2 = _resolve_dept2(r, all_records, roster_map)
if not d2:
logger.error("员工「%s」无法解析二级部门(参保单位=%s),不推送该员工",
r.get("姓名"), _ins_org_of(r))
continue
dept2_by_code[c] = d2
codes.append(c)
if not codes:
logger.warning("[%s] 命中员工均无法解析二级部门,跳过该推送", tpl["key"])
continue
receivers = _resolve_receivers(roster_map, codes, dept2_by_code)
if config.get_notice_test_mode():
receivers = list(config.NOTICE_OA_TEST_RECEIVERS)
logger.info("[测试模式] [%s] 接收人覆盖为测试接收人:%s", tpl["key"], receivers)
if config.CC_RECEIVER_ID not in receivers:
receivers.append(config.CC_RECEIVER_ID)
if not receivers:
logger.warning("[%s] 未解析到任何接收人(店长/人事),跳过该推送", tpl["key"])
continue
push_date = datetime.today().strftime("%Y年%m月%d日")
content = _highlight_text(
tpl["content"].format(y=y, m=m, push_date=push_date),
config.NOTICE_OA_HIGHLIGHTS.get(tpl["key"], ()), m=m)
messages.append({
"subject": tpl["subject"].format(y=y, m=m),
"content": _text_to_html(content),
"attachment_paths": attachment_paths,
"receivers": receivers,
"category": tpl["category"],
})
logger.info("[%s] 附件 %d 份,接收人 %d 人:%s",
tpl["key"], len(attachment_paths), len(receivers), ", ".join(receivers))
# 落盘推送数据(真实推送由 __init__ 阶段按开关调 oa_push)
try:
os.makedirs(month_dir, exist_ok=True)
json_path = os.path.join(month_dir, "oa_messages.json")
with open(json_path, "w", encoding="utf-8") as f:
_json.dump(messages, f, ensure_ascii=False, indent=1)
logger.info("OA 推送数据已落盘:%s(%d 条)", json_path, len(messages))
except Exception as e:
logger.warning("OA 推送数据落盘失败(不影响告知书生成):%s", e)
return messages
# ==================== 主流程:告知书生成 ====================
def generate_notices(branch: str, output_dir: str = None, ym: tuple = None,
roster_path: str = None) -> dict:
"""按分支生成告知书(Word + PDF)。返回 {模板名: [输出文件路径, ...]}。"""
if branch not in config.NOTICE_BRANCHES:
raise ValueError(f"未知分支:{branch},可选 {list(config.NOTICE_BRANCHES)}")
output_dir = output_dir or _output_root()
ym = ym or (datetime.now().year, datetime.now().month)
y, m = ym
month_dir = os.path.join(output_dir, f"{y}{m:02d}")
excel_path = _find_current_month_excel(_base_dir())
logger.info("读取名单:%s(目标年月 %d-%02d)", excel_path, y, m)
try:
roster_map = _read_roster_map(roster_path or _roster_path())
except Exception as e:
logger.warning("花名册读取失败,二级部门解析将受限:%s", e)
roster_map = {}
if branch == "转移参保":
transfer_records = _read_transfer_records(excel_path, roster_map)
logger.info("社保转移命中 %d 人:%s", len(transfer_records), excel_path)
records, all_records = [], transfer_records
rule_keys = ("社保转移",)
else:
records = _read_insurance_records(excel_path)
logger.info("「参保名单」共 %d 条记录", len(records))
all_records, rule_keys = records, ("新参保", "参保异常")
results = {}
for rule_name in rule_keys:
rule = config.NOTICE_TEMPLATES[rule_name]
tpl_path = _template_path(rule_name)
if not os.path.exists(tpl_path):
raise FileNotFoundError(f"模板不存在:{tpl_path}")
matched = (transfer_records if rule_name == "社保转移"
else [r for r in records if _match_rule(r, rule["status"], rule["type"])])
if not matched:
logger.info("[%s] 无命中人员,跳过", rule_name)
results[rule_name] = []
continue
out_folder = os.path.join(month_dir, rule["folder"])
os.makedirs(out_folder, exist_ok=True)
files = []
logger.info("=" * 70)
logger.info("[%s] 命中 %d 人", rule_name, len(matched))
groups = {}
for rec in matched:
dept2 = _resolve_dept2(rec, all_records, roster_map)
if not dept2:
logger.error("员工「%s」无法解析二级部门(参保单位=%s),跳过生成",
rec.get("姓名"), _ins_org_of(rec))
continue
rec["二级部门"] = dept2
key = (dept2, _trans_org_of(rec))
groups.setdefault(key, []).append(rec)
for (dept2, ins_org), recs in groups.items():
docs = [_fill_doc(tpl_path, _build_placeholders(r, ym)) for r in recs]
doc = _merge_notice_docs(docs) if len(docs) > 1 else docs[0]
base_name = _safe_filename(f"{dept2}_{ins_org}_{rule['folder']}")
docx_path = os.path.join(out_folder, base_name + ".docx")
pdf_path = docx_path[:-5] + ".pdf"
doc.save(docx_path)
leftover = _leftover_placeholders(doc)
if leftover:
logger.warning("[%s] %s 模板存在未替换占位符:%s", rule_name, base_name, sorted(leftover))
_publish_via_wps(docx_path, docx_path, pdf_path)
logger.info("已生成:%s(%d 人)", os.path.basename(docx_path), len(recs))
files.append(docx_path)
results[rule_name] = files
logger.info("=" * 70)
logger.info("全部完成,输出目录:%s", month_dir)
return results
def make_notices():
"""告知书制作阶段入口:按配置分支生成告知书 + 构造 OA 推送数据落盘 JSON。
返回 dict {branch_run, files: {branch: {rule: [files]}}, total,
messages, messages_count}。
"""
branch_cfg = config.get_notice_branch()
branches = list(config.NOTICE_BRANCHES) if branch_cfg == "all" else [branch_cfg]
results = {}
all_messages = []
for branch in branches:
logger.info("===== 告知书分支:%s =====", branch)
files = generate_notices(branch)
results[branch] = files
try:
msgs = build_work_communication_data(branch)
all_messages.extend(msgs)
except Exception as e:
logger.warning("分支[%s] OA 推送数据构造失败(不影响告知书生成):%s", branch, e)
total = sum(len(fs) for v in results.values() for fs in v.values())
return {"branch_run": branches, "files": results, "total": total,
"messages": all_messages, "messages_count": len(all_messages)}
+357
View File
@@ -0,0 +1,357 @@
# -*- 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}"
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),
"附件上传-二进制")
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}
+713
View File
@@ -0,0 +1,713 @@
# -*- 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 RuntimeError(f"导入完成但成功人数为 0,提示:{text.strip()[:120]}")
for t in ('确 定', '确定'):
try:
btn = tab.ele(f'tag:button@@text()={t}', timeout=2)
except Exception:
btn = None
if btn:
btn.click()
break
time.sleep(1.5)
return total, failed
last_err = payload if state == "fail" else "导入后未出现结果弹窗(超时)"
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_name = config.OUTPUT_DIR_ADD_NEW
self.file_suffix = "增员导入名单.xls"
self.fail_status = "参保失败"
self.close_tip = False
self.operation_type = config.WEB_ADD_TYPE
else:
self.business_item = "城保参保单位人员减少"
self.import_dir_name = config.OUTPUT_DIR_STOP
self.file_suffix = "减员导入名单.xls"
self.fail_status = "停保失败"
self.close_tip = True
self.operation_type = None
self.writeback = Writeback(kind)
# ---------------- 预检 ----------------
def precheck(self, units, accounts):
"""预检:核对每个单位的导入文件与账号。返回待办列表。"""
import_dir = config.roster_output_dir(self.import_dir_name)
tasks, errors = [], []
config.log("\n========== 预检 ==========")
for unit, count in units:
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_name}\\{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列平台密码为空)")
if problems:
errors.append(f"[{unit}] " + ";".join(problems))
config.log(f" ✗ {unit}({count}人):{';'.join(problems)}")
else:
tasks.append({"unit": unit, "count": count, "file": file_path,
"username": acc["username"], "password": acc["password"]})
config.log(f" ✓ {unit}({count}人)账号={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']}({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('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": "登录失败(验证码识别未通过或流程异常)"}
+658
View File
@@ -0,0 +1,658 @@
# -*- 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 (("当前页", None), ("菜单页", config.MENU_PAGE_URL), ("重开业务页", "__REOPEN__")):
try:
if goto == "__REOPEN__":
biz_tab = _reopen_biz(page, business_item)
elif goto:
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_TYPE
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_sub = (config.OUTPUT_DIR_ADD_NEW if kind == 'add'
else config.OUTPUT_DIR_STOP)
# ---------------- 单个单位完整核查 ----------------
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(" 开始回盘打印下载...")
save_dir = Path(config.replay_dir(self._huipan_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)}