feat: 新增银行卡检查插件及相关依赖与配置文件

This commit is contained in:
2026-10-29 14:21:30 +08:00
parent 259369953f
commit 526116af83
494 changed files with 66923 additions and 2714 deletions
+2
View File
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""XQ0002 插件 logic 层:筛选复制 + 三阶段名额调度 + WPS/Excel 重算。"""
+658
View File
@@ -0,0 +1,658 @@
# -*- coding: utf-8 -*-
"""XQ0002 插件 - HR「待增减人员」增减员导入(浏览器自动化,移植影刀版 add_sub_import v1.8.0)。
流程:访问待增减人员页面 -> 更多操作 -> 减员/增员导入 -> 上传文件 -> 下一步(格式校验)
-> 下一步(真正导入)-> 关闭;监听 getTmpDataPage.mc 捕获逐行导入结果。
插件化改造点(相对影刀版):
1. 登录态:优先底座注入 session(config.get_session())的 cookies 注入浏览器,
未注入/为空时兜底读共享 cookies 文件(hr_cookies.json);
2. 导入文件路径经 config.category_import_add_file / category_import_sub_file 实时解析
(base_dir 由 run() 注入,不依赖类别配置里的固化 folder);
3. 一次运行共用一个浏览器:先全部类别【减员】再全部类别【增员】
(替换/修改人员必须先撤旧方案再上新方案,先增员会方案冲突报错);
4. 日志统一转发 config.logger;结果 dict 返回,由 __init__.py 汇总进 summary/notes。
关键语义(与影刀版一致,勿改):
- getTmpDataPage.mc 仅在存在异常行时才返回逐行结果:全部成功时 HR 不调用结果接口,
流程完整走完(两步「下一步」+「关闭」)且监听正常、未捕获异常行 -> 按文件条数推定全部成功;
- 接口每页固定 15 条,弹窗只加载第一页:捕获首响应后按 pageNo 主动翻页拉全;
- 需导入条数从导入文件 A 列最大序号统计(模板预格式化空白行不计);
- 上传/校验/确认走 UI 控件(input[name=file] 设置路径跳过系统文件选择框)。
"""
import json
import os
import re
import time
import requests
from openpyxl import load_workbook
from ..config import logger, SESSIONS_DIR, get_session
try:
from DrissionPage import ChromiumPage, ChromiumOptions
_DRP_AVAILABLE = True
_DRP_IMPORT_ERROR = None
except ImportError as _e: # 模块可安全导入(开关关闭时不触发),使用时再报清晰错误
_DRP_AVAILABLE = False
_DRP_IMPORT_ERROR = _e
# ==================== 常量(与影刀版 add_sub_import 一致) ====================
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
# HR 系统「待增减人员」页面
ADD_SUB_URL = (
"https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic"
"#ajax&1&nworktoday-40175-13664-23874-98879&nworktoday-40175-13664"
"|/RedseaPlatform/hrRoster/7984ae1a-16ec-11ed-bea9-822ff8ed5b28/"
"getCustomCommonList.mc?menuName=待增减人员"
)
BTN_MORE = "更多操作" # 「更多操作」下拉按钮
MENU_ADD = "增员导入" # 下拉菜单:增员导入
MENU_SUB = "减员导入" # 下拉菜单:减员导入
BTN_NEXT = "下一步" # 导入弹窗「下一步」按钮(第 2/3 步)
BTN_CLOSE = "关闭" # 导入完成弹窗「关闭」按钮
WAIT_SHORT = 0.6
WAIT_MID = 2.0
WAIT_LONG = 4.0
# 接口监听:第二步「下一步」导入内容结果(getTmpDataPage.mc)
TMP_DATA_API_MARK = "getTmpDataPage.mc" # 导入内容结果接口(URL 子串过滤)
TMP_DATA_STATE_OK = "1" # 接口 state 成功值
TMP_DATA_WAIT = 8.0 # 等待导入结果接口响应的超时秒数
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"Chrome/120.0.0.0 Safari/537.36")
class LoginRequiredError(Exception):
"""HR 登录态缺失/失效(页面被重定向到登录页或无可用 cookies)。"""
class ElementNotFoundError(Exception):
"""页面元素/控件未找到(页面结构变化或加载超时)。"""
# ==================== 登录态:底座注入 session 优先,兜底共享 cookies 文件 ====================
def _cookies_from_requests_session(session):
"""从底座注入的 requests.Session 提取 37du.co 域 cookies(DrissionPage 字典格式)。"""
cookies = []
try:
jar_items = list(session.cookies)
except Exception:
return cookies
for c in jar_items:
domain = str(getattr(c, "domain", "") or "")
if "37du.co" not in domain:
continue
cookies.append({
"name": c.name, "value": c.value,
"domain": domain, "path": getattr(c, "path", None) or "/",
})
return cookies
def _cookies_from_shared_file():
"""读取共享 HR cookies 文件(37du.co 域),缺失/为空返回空列表。"""
if not os.path.isfile(SHARED_HR_COOKIE_FILE):
return []
try:
with open(SHARED_HR_COOKIE_FILE, encoding="utf-8") as f:
cookies = json.load(f) or []
except Exception as e:
logger.warning("共享 HR cookies 文件读取失败 %s:%s", SHARED_HR_COOKIE_FILE, e)
return []
return [c for c in cookies if c.get("domain") and "37du.co" in str(c["domain"])]
def _collect_browser_cookies():
"""收集浏览器登录态 cookies:底座注入 session 优先,为空兜底共享 cookies 文件。"""
cookies = []
session = get_session()
if session is not None:
cookies = _cookies_from_requests_session(session)
if cookies:
logger.info("使用底座注入 HR 会话的 cookies:%d 个", len(cookies))
if not cookies:
cookies = _cookies_from_shared_file()
if cookies:
logger.info("使用共享 cookies 文件:%d 个(%s)", len(cookies), SHARED_HR_COOKIE_FILE)
if not cookies:
raise LoginRequiredError(
"未找到可用 HR 登录态:底座未注入 HR 会话且共享 cookies 文件缺失/为空,"
"请先在插件界面完成 HR 登录后再执行导入。")
return cookies
def _build_hr_session():
"""构建可访问 HR 接口的 requests.Session(供结果接口翻页拉全)。
cookies 来源与浏览器一致(注入 session 优先,兜底共享文件);构建失败返回 None,
调用方降级为仅统计监听到的第一页(与影刀版兜底语义一致)。
"""
cookies = []
session = get_session()
if session is not None:
cookies = _cookies_from_requests_session(session)
if not cookies:
cookies = _cookies_from_shared_file()
if not cookies:
return None
s = requests.Session()
s.headers.update({
"User-Agent": USER_AGENT,
"Content-Type": "application/x-www-form-urlencoded",
})
for c in cookies:
try:
s.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
except Exception:
continue
return s
# ==================== 元素定位辅助(DrissionPage) ====================
def _create_page():
"""创建 ChromiumPage(统一配置,非无头,与影刀版一致)。"""
co = ChromiumOptions()
return ChromiumPage(co)
def _click_text(page, text, timeout=10):
"""按元素文本精确匹配并点击,找不到则抛错。"""
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
if not ele:
raise ElementNotFoundError(f"未找到元素:{text}")
ele.click()
logger.info("已点击:%s", text)
def _click_text_in(page, container, text, timeout=5):
"""在指定容器内按文本匹配并点击。"""
ele = container.ele(f'xpath:.//*[normalize-space(text())="{text}"]', timeout=timeout)
if not ele:
raise ElementNotFoundError(f"容器内未找到元素:{text}")
ele.click()
logger.info("已点击:%s", text)
def _is_displayed(ele):
"""判断元素是否可见且具有尺寸;异常时返回 False(保守不误判)。"""
if ele is None:
return False
try:
if not ele.states.is_displayed:
return False
w, h = ele.rect.size
return w > 0 and h > 0
except Exception:
return False
def _ensure_logged_in(page):
"""访问待增减人员页面;若被重定向到登录页,抛 LoginRequiredError。"""
page.get(ADD_SUB_URL)
time.sleep(WAIT_LONG)
if page.ele('@id=j_username', timeout=2):
raise LoginRequiredError(
"HR 登录态已失效(页面被重定向到登录页),请先在插件界面重新登录 HR 再执行导入。")
logger.info("已进入待增减人员页面:%s", page.url)
# ==================== 增员/减员导入页面流程 ====================
def _open_more_operations(page):
"""点击「更多操作」按钮,展开下拉菜单(幂等,已展开则跳过)。"""
menu = page.ele('css:#custom-btn-ul', timeout=2)
if menu and _is_displayed(menu):
logger.info("「更多操作」下拉已展开,跳过")
time.sleep(WAIT_SHORT)
return menu
more_btn = page.ele('css:#more-btns button.dropdown-toggle', timeout=15)
if not more_btn:
more_btn = page.ele('css:button.btn-success.dropdown-toggle', timeout=5)
if not more_btn:
_click_text(page, BTN_MORE)
else:
more_btn.click()
logger.info("已点击「更多操作」")
time.sleep(WAIT_SHORT)
menu = page.ele('css:#custom-btn-ul', timeout=5)
if not menu:
raise ElementNotFoundError("未找到「更多操作」下拉菜单(#custom-btn-ul)")
logger.info("「更多操作」下拉已展开")
return menu
def _choose_import_menu(page, menu_label):
"""在下拉菜单中选择「增员导入」或「减员导入」。"""
menu = _open_more_operations(page)
_click_text_in(page, menu, menu_label)
time.sleep(WAIT_MID)
def _upload_file(page, file_path):
"""在导入弹窗中上传指定文件(直接对 input[name=file] 设置路径,跳过系统文件选择框)。"""
if not os.path.isfile(file_path):
raise FileNotFoundError(f"导入文件不存在:{file_path}")
file_input = page.ele('css:input[name="file"]', timeout=15)
if not file_input:
raise ElementNotFoundError("未找到文件上传控件(input[name=file])")
file_input.input(file_path)
logger.info("已选择导入文件:%s", file_path)
time.sleep(WAIT_SHORT)
def _click_next(page):
"""点击导入弹窗中的「下一步」按钮(btn-success 且可见)。"""
btn = page.ele(
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-success")'
' and normalize-space(.)="下一步"]',
timeout=10,
)
if not btn or not _is_displayed(btn):
raise ElementNotFoundError("未找到可见的「下一步」按钮")
btn.click()
logger.info("已点击「下一步」")
time.sleep(WAIT_MID)
def _click_close(page):
"""点击导入完成弹窗中的「关闭」按钮。"""
btn = page.ele(
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-default")'
' and normalize-space(.)="关闭"]',
timeout=10,
)
if not btn or not _is_displayed(btn):
raise ElementNotFoundError("未找到可见的「关闭」按钮")
btn.click()
logger.info("已点击「关闭」")
time.sleep(WAIT_SHORT)
# ---------------------------------------------------------------
# 接口监听:上传表格后解析结果(getTmpDataPage.mc),捕获返回的全部异常
# ---------------------------------------------------------------
def _extract_json_response(req):
"""从监听到的请求中解析 JSON 响应;解析失败返回 None。"""
try:
return req.response.json()
except Exception:
body = getattr(req.response, "body", None)
if isinstance(body, (dict, list)):
return body
if not body:
return None
try:
return json.loads(body)
except Exception:
return None
def _merge_datas(result, resp):
"""从一次接口响应(resp)中提取并累计统计:需导入总条数、成功数、异常明细。"""
for item in resp.get("datas") or []:
item = item or {}
msg = str(item.get("imp_fixed_msg", "") or "").strip()
if not msg:
continue
result["total_count"] += 1
# 成功行返回「导入成功;」固定文案,只计数量不纳入异常
if "导入成功" in msg:
result["success_count"] += 1
continue
result["exceptions"].append({
"staff_code": str(item.get("imp_assi_staff_code_ext_table_field_base_id", "") or ""),
"staff_name": str(item.get("imp_assi_staff_name_ext_table_field_base_id", "") or ""),
"insurance_name": str(item.get("ext_insurance_name", "") or ""),
"message": msg,
})
def _fetch_remaining_pages(result, first_url, first_body, page_count, page_size=15):
"""getTmpDataPage 每页固定返回 15 条,弹窗只加载第一页:按 pageNo 主动翻页拉全。
该接口为 POST,分页参数(importId/imp_fixed_businessid/start/pageNo/pageSize)
在请求 body 中,必须复用首次请求 body 改页码后 POST(直接 GET URL 拿不到目标页)。
"""
if page_count <= 1:
return
session = _build_hr_session()
if session is None:
logger.warning("分页拉取失败(无法构建 HR 会话),仅统计弹窗第一页")
return
for page_no in range(2, page_count + 1):
start = (page_no - 1) * page_size
body = re.sub(r"pageNo=\d+", f"pageNo={page_no}", first_body or "")
body = re.sub(r"start=\d+", f"start={start}", body)
body = re.sub(r"pageSize=\d+", f"pageSize={page_size}", body)
try:
resp = session.post(first_url, data=body, timeout=15)
data = resp.json()
except Exception as e:
logger.warning("分页第 %s/%s 页拉取失败:%s", page_no, page_count, e)
continue
if str(data.get("state", "")).strip() != TMP_DATA_STATE_OK:
logger.warning("分页第 %s/%s 页返回 state=%s,跳过",
page_no, page_count, data.get("state"))
continue
logger.info("分页第 %s/%s 页返回 %s 条",
page_no, page_count, len(data.get("datas") or []))
_merge_datas(result, data)
def _capture_import_exceptions(page, timeout=TMP_DATA_WAIT):
"""监听导入结果接口(getTmpDataPage.mc),捕获全部逐行结果(监听须已开启)。
第一步「下一步」(格式校验/预览)也可能请求该接口但行内 imp_fixed_msg 为空,跳过;
仅处理携带导入结果说明的响应。捕获首响应后按 pageCount 主动翻页拉全。
Returns:
dict: {captured, state, meg, listen_ok, success_count, total_count, exceptions}
"""
result = {"captured": False, "state": "", "meg": "", "exceptions": [],
"listen_ok": True, "success_count": 0, "total_count": 0}
first_url = None
first_body = ""
page_count = 1
deadline = time.time() + timeout
last_hit = time.time()
while time.time() < deadline:
try:
remain = max(0.0, deadline - time.time())
req = page.listen.wait(timeout=min(0.5, remain))
except Exception as e:
logger.warning("监听 %s 接口异常:%s", TMP_DATA_API_MARK, e)
break
if not req:
# 已捕获过解析响应时,再确认一个间隔后结束,合并多次返回的结果
if result["captured"] and time.time() - last_hit >= 1.0:
break
continue
if not hasattr(req, "url"):
continue
if TMP_DATA_API_MARK not in (req.url or ""):
continue
resp = _extract_json_response(req)
if not isinstance(resp, dict):
continue
# 预览/校验响应行内 imp_fixed_msg 为空 -> 跳过,继续等待最终结果
if not any(str((it or {}).get("imp_fixed_msg", "") or "").strip()
for it in (resp.get("datas") or [])):
continue
result["captured"] = True
last_hit = time.time()
state = str(resp.get("state", "")).strip()
if state:
result["state"] = state
meg = str(resp.get("meg", "") or "").strip()
if meg:
result["meg"] = meg
if first_url is None:
first_url = req.url
first_body = req.request.postData or ""
try:
page_count = max(1, int(resp.get("pageCount") or 1))
except Exception:
page_count = 1
_merge_datas(result, resp)
if first_url and page_count > 1:
_fetch_remaining_pages(result, first_url, first_body, page_count)
break
return result
def _count_import_rows(file_path):
"""统计导入文件需导入条数(A 列最大序号;第 1 行标题/第 2 行表头/第 3 行示例,第 4 行起数据)。
官方模板自带大量预格式化空白行(max_row 可达数千),不能直接用 max_row 统计。
"""
try:
wb = load_workbook(file_path, read_only=True)
try:
ws = wb[wb.sheetnames[0]]
max_seq = 0
for seq in ws.iter_rows(min_row=4, max_row=ws.max_row,
max_col=1, values_only=True):
v = seq[0]
if v is None or str(v).strip() == "":
continue
try:
max_seq = max(max_seq, int(v))
except (TypeError, ValueError):
continue
return max_seq
finally:
wb.close()
except Exception as e:
logger.warning("统计导入文件条数失败 %s:%s", file_path, e)
return 0
def _import_file_path(category, menu_label):
"""按菜单解析类别导入文件路径(base_dir 运行时注入,实时拼接)。"""
if menu_label == MENU_ADD:
from ..config import category_import_add_file
return category_import_add_file(category)
from ..config import category_import_sub_file
return category_import_sub_file(category)
def _import_one(page, category, menu_label, expected_total=None):
"""对单个类别执行一次导入(选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。
自第一个「下一步」之前即开启 getTmpDataPage.mc 监听(结果接口可能在格式校验或
真正导入时触发,提前监听避免漏捕);异常仅记录上报,不中断导入流程。
Args:
expected_total: 需导入条数(由 import_all 预检传入,避免重复读文件;None 时自行统计)。
Returns:
dict: 导入结果(含 expected_total 需导入条数、exceptions 异常明细等)。
"""
file_path = _import_file_path(category, menu_label)
if not os.path.isfile(file_path):
raise FileNotFoundError(f"导入文件不存在:{file_path}")
if expected_total is None:
expected_total = _count_import_rows(file_path)
logger.info("===== 类别[%s] 开始%s,文件:%s(需导入 %d 条) =====",
category["name"], menu_label, file_path, expected_total)
_choose_import_menu(page, menu_label)
_upload_file(page, file_path)
# 第一个「下一步」前开启监听,贯穿「格式校验/预览 + 真正导入」全过程;
# 监听启动失败必须上报,否则未捕获异常会被误判为正常(假成功)
listen_ok = True
try:
page.listen.start(TMP_DATA_API_MARK)
except Exception as e:
listen_ok = False
logger.error("启动 %s 接口监听失败,无法捕获导入结果:%s", TMP_DATA_API_MARK, e)
try:
_click_next(page) # 第一步:格式校验/预览
_click_next(page) # 第二步:真正导入内容(触发结果接口)
import_result = _capture_import_exceptions(page)
import_result["listen_ok"] = listen_ok
import_result["expected_total"] = expected_total
finally:
try:
page.listen.stop()
except Exception:
pass
# 全部成功时 HR 不调用结果接口:流程完整走完 + 监听正常 + 未捕获异常行 -> 按文件条数推定全部成功
if (not import_result["captured"] and listen_ok and not import_result["exceptions"]):
import_result["assumed_all_success"] = True
import_result["success_count"] = expected_total
import_result["total_count"] = expected_total
if import_result["exceptions"]:
logger.error("类别[%s] %s:导入返回 %d 条异常:",
category["name"], menu_label, len(import_result["exceptions"]))
for exc in import_result["exceptions"]:
logger.error(" - [%s/%s] 方案[%s]:%s",
exc["staff_code"], exc["staff_name"],
exc["insurance_name"], exc["message"])
elif not listen_ok:
logger.error("类别[%s] %s:接口监听启动失败,无法确认导入结果,请人工核对",
category["name"], menu_label)
elif import_result["captured"] and import_result["state"] != TMP_DATA_STATE_OK:
logger.error("类别[%s] %s:导入接口 state=%s(meg=%s),导入可能失败",
category["name"], menu_label, import_result["state"], import_result["meg"])
elif import_result.get("assumed_all_success"):
logger.info("类别[%s] %s:全部导入成功(HR 未返回结果接口,按文件 %d 条推定),无异常",
category["name"], menu_label, expected_total)
elif not import_result["captured"]:
logger.warning("类别[%s] %s:未捕获到导入结果接口响应,无法确认导入结果",
category["name"], menu_label)
else:
logger.info("类别[%s] %s:导入成功 %s 人,无异常",
category["name"], menu_label, import_result.get("success_count", 0))
_click_close(page)
logger.info("===== 类别[%s] %s完成 =====", category["name"], menu_label)
return import_result
# ==================== 对外入口:先减员后增员,全程共用一个浏览器 ====================
def _skipped_result(category, menu, reason):
"""构造「无待导入条目」的跳过单元结果(无 error,不计流程失败)。"""
return {
"category": category["name"], "menu": menu,
"captured": False, "state": "", "meg": "", "exceptions": [],
"listen_ok": True, "expected_total": 0,
"success_count": 0, "total_count": 0,
"skipped": True, "skip_reason": reason,
}
def import_all(categories, on_progress=None):
"""对指定类别执行 HR 导入(★先全部类别【减员】再【增员】,顺序不可换)。
预检:仅「导入文件存在且实际有待导入条目」的单元才会启动浏览器执行导入;
需导入 0 条(无增员/减员变动)的单元直接跳过——本就没有需要导入的内容,
不启动浏览器、也不报"流程失败"。
Args:
categories: 类别配置列表(config.CATEGORIES 项,须为本次调度成功的类别,
只导入本次新生成的导入文件,避免误传历史文件)。
on_progress: 可选回调 on_progress(done, total),每个实际执行导入的
「类别×菜单」单元完成后调用,供 __init__.py 上报进度。
Returns:
list[dict]: 每单元结果:{category, menu, captured, state, meg, exceptions,
listen_ok, expected_total, success_count, total_count,
assumed_all_success?, error?, error_type?, skipped?}
skipped=True 表示该单元导入文件无待导入条目(需导入 0 条),未启动浏览器导入,
不视为流程失败(无 error 字段)。
Raises:
LoginRequiredError: HR 登录态缺失/失效(整个导入未开始,无部分导入风险)。
RuntimeError: DrissionPage 依赖缺失。
"""
if not _DRP_AVAILABLE:
raise RuntimeError(f"缺少 DrissionPage 依赖(python-env 未内置),无法自动导入:{_DRP_IMPORT_ERROR}")
if not categories:
logger.info("无待导入类别,跳过 HR 导入")
return []
# ---- 预检:按导入文件实际条数过滤出真正需要导入的单元(类别×菜单) ----
results = []
units = []
for c in categories:
for menu in (MENU_SUB, MENU_ADD):
label = "减员" if menu == MENU_SUB else "增员"
file_path = _import_file_path(c, menu)
if not os.path.isfile(file_path):
logger.warning("类别[%s] %s导入文件不存在,视为无需导入:%s",
c["name"], label, file_path)
results.append(_skipped_result(c, menu, "导入文件不存在"))
continue
expected_total = _count_import_rows(file_path)
if expected_total <= 0:
logger.info("类别[%s] %s导入文件无待导入条目,跳过导入:%s",
c["name"], label, file_path)
results.append(_skipped_result(c, menu, "无待导入条目"))
continue
units.append((c, menu, expected_total))
if not units:
logger.info("各类别增/减员导入文件均无待导入条目,跳过 HR 自动导入(未启动浏览器)")
return results
total_units = len(units)
done = 0
page = _create_page()
logger.info("浏览器已启动(导入全程共用)")
try:
cookies = _collect_browser_cookies()
page.set.cookies(cookies)
_ensure_logged_in(page)
for category, menu_label, expected_total in units:
try:
res = dict(_import_one(page, category, menu_label, expected_total=expected_total))
res["category"] = category["name"]
res["menu"] = menu_label
results.append(res)
except Exception as e:
logger.error("类别[%s] %s失败:%s", category["name"], menu_label, e)
results.append({
"category": category["name"], "menu": menu_label,
"captured": False, "state": "", "meg": "", "exceptions": [],
"listen_ok": True, "expected_total": 0,
"success_count": 0, "total_count": 0,
"error": str(e), "error_type": type(e).__name__,
})
done += 1
if on_progress:
try:
on_progress(done, total_units)
except Exception:
pass
return results
finally:
try:
page.quit()
except Exception:
pass
def summarize_results(results):
"""把导入结果汇总为可读文本行列表(供插件 summary 拼接)。
口径与影刀版一致:需导入条数取自导入文件(expected_total,与接口是否捕获无关);
成功/失败取接口返回的业务结果(全部成功时 HR 不返回接口,按文件条数推定成功);
流程失败(登录/元素/文件缺失)的单元不纳入条数统计,仅报失败;
跳过单元(skipped,无待导入条目)正常纳入统计(需导入 0 条),不报失败/待确认。
"""
lines = []
for menu, label in ((MENU_SUB, "减员"), (MENU_ADD, "增员")):
rs = [r for r in results if r.get("menu") == menu]
if not rs:
continue
total = sum(r.get("expected_total") or 0 for r in rs if not r.get("error"))
success = sum(r.get("success_count") or 0 for r in rs if not r.get("error"))
fail = sum(len(r.get("exceptions") or []) for r in rs if not r.get("error"))
flow_failed = [r["category"] for r in rs if r.get("error")]
unconfirmed = [r["category"] for r in rs
if not r.get("error") and not r.get("exceptions")
and not r.get("assumed_all_success") and not r.get("skipped")
and (not r.get("captured") or r.get("state") != TMP_DATA_STATE_OK)]
line = f"{label}:需导入 {total} 条,成功 {success} 条,异常 {fail} 条"
extras = []
if unconfirmed:
extras.append(f"{len(unconfirmed)} 个类别结果待人工确认({'、'.join(unconfirmed)})")
if flow_failed:
extras.append(f"流程失败({'、'.join(flow_failed)})")
if extras:
line += ";" + ";".join(extras)
lines.append(line)
return lines
+158
View File
@@ -0,0 +1,158 @@
# -*- coding: utf-8 -*-
"""XQ0002 插件 - 筛选复制(由影刀版 roster_filter.py v2.0.0 移植)。
从员工花名册按类别 include/exclude 所属单位筛选数据,复制到各自类别目标表
(各文件夹内最新的「*雇主险变更记录*.xlsx」),并剔除「入职时间 > 业务日期」的
未来入职员工;F列工号强制文本格式(否则与在参名单 B列及表内公式匹配失败)。
源表缺失或超过 TTL(15 分钟)时调用 data.roster_export_api.export_roster 自动导出,
替代影刀版对 share/roster_export.py 的懒加载;登录态经底座注入的 session。
"""
import os
import pandas as pd
from openpyxl import load_workbook
from ..config import (
logger, SHEET_BIZ, SOURCE_HEADER_MARK, EXPORT_TEMPLATE, EXPORT_STATUSES,
TARGET_HEADER_ROW, DATA_COLUMNS, CODE_COL, ID_COL, JOIN_DATE_COL, NAME_COL,
EXCLUDE_REGIONS, EXCLUDE_NAME_KEYWORDS, category_folder, employee_file,
find_latest_target, to_text, parse_join_date, ref_date, CACHE_DIR,
)
from ..data.roster_export_api import export_roster
def _read_source(employee_path):
"""读取源表(员工花名册):自动定位表头行(B 列=「所属单位」),返回 B~O 14 列切片。"""
probe = pd.read_excel(employee_path, header=None, nrows=8)
header_row = None
for idx in range(len(probe)):
if str(probe.iloc[idx, 1]).strip() == SOURCE_HEADER_MARK:
header_row = idx
break
if header_row is None:
raise ValueError(f"源表未找到表头行(B 列应为「{SOURCE_HEADER_MARK}」)")
df = pd.read_excel(employee_path, header=header_row)
if df.shape[1] < DATA_COLUMNS + 1:
raise ValueError(f"源表列数不足:{df.shape[1]}(需要 B~O 共{DATA_COLUMNS}列)")
data = df.iloc[:, 1:DATA_COLUMNS + 1].copy() # B~O 14列(「类型」列在末尾,不受影响)
# 与宏一致:以 B 列(所属单位)最后非空行为数据边界
return data[data.iloc[:, 0].notna()]
def filter_and_copy_roster(category, employee_path="", target_file=None):
"""从员工花名册按类别筛选数据,复制到该类别的雇主险变更记录表(仅复制,不校验)。
Args:
category: 类别配置(含 name/include_dept/exclude_dept)
employee_path: 源表路径,默认 {base_dir}\\员工花名册.xlsx
target_file: 目标表路径,默认取该类别文件夹内最新的「*雇主险变更记录*.xlsx」
Returns:
复制的数据行数
Raises:
FileNotFoundError: 源表或目标表不存在
ValueError: 源表列数不足 或 目标表缺少指定 Sheet
"""
category_name = category["name"]
employee_path = os.path.abspath(employee_path or employee_file())
target_file = os.path.abspath(target_file or find_latest_target(category_folder(category)))
if not os.path.exists(employee_path):
raise FileNotFoundError(f"源表不存在:{employee_path}")
if not os.path.exists(target_file):
raise FileNotFoundError(f"目标表不存在:{target_file}")
# ---------- 1. 读取源表并过滤 ----------
data = _read_source(employee_path)
dept = data.iloc[:, 0].astype(str).str.strip()
region = data.iloc[:, 1].astype(str).str.strip()
name = data.iloc[:, NAME_COL].astype(str).str.strip()
include_dept = category.get("include_dept") or []
exclude_dept = category.get("exclude_dept") or []
mask = ~region.isin(EXCLUDE_REGIONS)
if include_dept:
mask &= dept.isin(include_dept)
if exclude_dept:
mask &= ~dept.isin(exclude_dept)
for kw in EXCLUDE_NAME_KEYWORDS:
mask &= ~name.str.contains(kw, na=False)
# 入职时间 > 业务日期 的行剔除(未来才入职的员工暂不纳入,留到当天再筛选出来)
today = ref_date()
join_dates = data.iloc[:, JOIN_DATE_COL].map(parse_join_date)
future_mask = join_dates.map(lambda d: d is not None and d > today)
n_future = int(future_mask.sum())
mask &= ~future_mask
filtered = data[mask]
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除 %s,姓名剔除含 %s,剔除未来入职 %d 人)",
category_name, len(data), len(filtered),
include_dept or "全部", exclude_dept or "无", " / ".join(EXCLUDE_REGIONS),
" / ".join(EXCLUDE_NAME_KEYWORDS), n_future)
if len(filtered) == 0:
logger.warning("类别[%s] 筛选后没有数据!", category_name)
# ---------- 2. 写目标表(先覆盖写入,只清空超出新数据的旧行) ----------
wb = load_workbook(target_file)
if SHEET_BIZ not in wb.sheetnames:
raise ValueError(f"目标表缺少 Sheet:{SHEET_BIZ}")
ws = wb[SHEET_BIZ]
first_data_row = TARGET_HEADER_ROW + 1 # 第5行
# 找 B 列当前最后非空数据行(用于清空多余旧行)
old_last = first_data_row - 1
for r in range(first_data_row, ws.max_row + 1):
if ws.cell(row=r, column=2).value is not None:
old_last = r
# 写入 B~O(覆盖旧数据;F列工号 / O列证件号 强制文本格式)
rows = filtered.values.tolist()
cell = ws.cell
for i, row in enumerate(rows, start=first_data_row):
for j, val in enumerate(row, start=2):
c = cell(row=i, column=j)
# 工号/证件号为主键:18位身份证号超出浮点精度,文本化避免截断,保证公式/映射匹配
if j - 2 in (CODE_COL, ID_COL):
c.value = to_text(val)
c.number_format = "@"
else:
c.value = val
# 清空超出新数据的旧行
new_last = first_data_row + len(rows) - 1
if old_last > new_last:
for r in range(new_last + 1, old_last + 1):
for c in range(2, 2 + DATA_COLUMNS):
cell(row=r, column=c).value = None
wb.save(target_file)
logger.info("类别[%s] 已写入目标表 %s 第%d行起,共 %d 行", category_name, target_file, first_data_row, len(rows))
return len(rows)
def ensure_employee_file(employee_path="", session=None):
"""确保花名册源表可用:缺失或超过 TTL(15 分钟)时自动重新从 HR 接口导出。
新鲜度评估交给 export_roster 的 TTL 缓存:源表存在、非空且距上次导出
不超过 15 分钟时直接复用,否则重新导出覆盖(不用陈旧花名册做调度)。
Args:
employee_path: 花名册路径(留空=默认根目录/员工花名册.xlsx)
session: 底座注入的 HR 会话(导出时使用)
Returns:
源表绝对路径
"""
path = os.path.abspath(employee_path or employee_file())
export_roster(
download_dir=os.path.join(CACHE_DIR, "roster_tmp"),
output_path=path,
template_name=EXPORT_TEMPLATE,
statuses=EXPORT_STATUSES,
session=session,
)
if not os.path.exists(path):
raise FileNotFoundError(f"花名册导出完成但源表仍不存在:{path}")
return path
+559
View File
@@ -0,0 +1,559 @@
# -*- coding: utf-8 -*-
"""XQ0002 插件 - 三阶段名额调度(由影刀版 employer_insurance_schedule.py v1.3.0 移植)。
阶段0 初始化(空闲名额池 / 当前参保映射 / 待转入队列)→
阶段1 处理业务(增加投保批量 / 要替换逐行)→
阶段2 分配名额(复用空闲名额 / 全新新增);
含姓名核对修正(J列)、特殊情况槽位追踪(离职/参保减少被复用后保留占位)、
以及类别级编排 schedule_category(读取目标文件 → 各阶段 → 输出)。
文件路径/日期/常量统一来自 config 层;输出(在参名单/变更清单/备份/增减员导入)
由 report.output 负责(本模块在编排处懒加载,避免与 report 相互 import 成环)。
"""
import os
from collections import defaultdict
import pandas as pd
from ..config import (
logger, SHEET_BIZ, SHEET_IN_PARAM, DATA_START_ROW,
BIZ_COL_EMPLOYEE_ID, BIZ_COL_CATEGORY, BIZ_COL_SCHEME, BIZ_COL_HANDLE,
VALID_CATEGORIES, VALID_SCHEMES, category_target_file,
category_output_backup, category_change_sheet_name,
add_import_template, sub_import_template, to_text, today_date,
)
class DataValidationError(Exception):
"""数据校验失败异常:直接中断调度,禁止继续往后跑。"""
def scheme_with_suffix(category, scheme):
"""增员导入「保险方案名称」追加厂区后缀(如 人保-80万 -> 人保-80万-秒创)。
源数据投保方案为无后缀的人保-X万;HR 侧方案列表含厂区后缀,
生成增员导入文件时按类别追加。已带对应后缀或后缀为空时原样返回。
"""
suffix = str(category.get("scheme_suffix") or "").strip()
scheme = str(scheme or "").strip()
if suffix and scheme and not scheme.endswith("-" + suffix):
return f"{scheme}-{suffix}"
return scheme
# ============================================================
# 一、数据校验
# ============================================================
def validate_biz_data(biz_df):
"""校验花名册业务数据的合法性。
校验规则:
1. 工种类别(P列)必须为:一类/二类/三类/四类
2. 方案处理 = "增加投保" 时,投保方案(Q列)必须为:人保-20万 / 50万 / 80万
返回 errors 错误列表,每个错误含 行号/员工ID/错误类型/详情;为空表示校验通过。
"""
errors = []
for idx, row in biz_df.iterrows():
row_num = idx + 5 # 数据从第5行开始(第4行是表头)
emp_id = row[BIZ_COL_EMPLOYEE_ID]
category = row[BIZ_COL_CATEGORY]
scheme = row[BIZ_COL_SCHEME]
handle = row[BIZ_COL_HANDLE]
if pd.isna(category) or category not in VALID_CATEGORIES:
errors.append({
"行号": row_num,
"员工ID": emp_id,
"错误类型": "工种类别非法",
"详情": f"工种类别为 '{category}',允许值:{VALID_CATEGORIES}",
})
if str(handle).strip() == "增加投保":
if pd.isna(scheme) or scheme not in VALID_SCHEMES:
errors.append({
"行号": row_num,
"员工ID": emp_id,
"错误类型": "投保方案非法",
"详情": f"增加投保但投保方案为 '{scheme}',允许值:{VALID_SCHEMES}",
})
return errors
# ============================================================
# 二、阶段0:初始化(从在参名单构建状态)
# ============================================================
def initialize(in_param_df):
"""从「手动维护-在参名单」构建三个核心数据结构。
1. idle_pools: 空闲名额池 {方案名称: [{type, employee_id}, ...]}
2. employee_map: 当前参保员工映射 {证件号: 投保方案}
3. pending_queues: 待转入队列(初始为空){方案名称: [证件号, ...]}
列索引(0-based): K列(10)证件号 / M列(12)当前投保方案 / R列(17)方案处理
"""
idle_pools = defaultdict(list)
employee_map = {}
pending_queues = defaultdict(list)
IDX_EMP_ID = 10
IDX_CUR_SCHEME = 12
IDX_HANDLE = 17
for _, row in in_param_df.iterrows():
emp_id = row.iloc[IDX_EMP_ID]
if pd.isna(emp_id):
continue
handle = str(row.iloc[IDX_HANDLE]).strip()
scheme = row.iloc[IDX_CUR_SCHEME]
if handle in ["无需", "档次替换"]:
# 正常参保或待替换,都视为当前已参保
if not pd.isna(scheme) and scheme != "":
employee_map[emp_id] = scheme
elif handle == "离职减少":
if not pd.isna(scheme) and scheme != "":
idle_pools[scheme].append({"type": "离职减少", "employee_id": emp_id})
elif handle == "参保减少":
if not pd.isna(scheme) and scheme != "":
idle_pools[scheme].append({"type": "参保减少", "employee_id": emp_id})
# 其他值(如'/')忽略
# 按优先级排序(离职减少优先)
for scheme in idle_pools:
idle_pools[scheme].sort(key=lambda x: 1 if x["type"] == "离职减少" else 2)
return idle_pools, employee_map, pending_queues
# ============================================================
# 二点五、姓名核对修正(在参名单 J列 与 花名册 姓名比对)
# ============================================================
def collect_name_corrections(in_param_df, biz_df):
"""核对「手动维护-在参名单」J列姓名与花名册「姓名」是否一致,并就地修正。
以证件号(在参名单 K列 / 花名册 O列)为关联键:
- 在参名单中证件号存在、且花名册中能查到该证件号(覆盖离职减少/参保减少等全部行)
- 两者姓名不一致且花名册姓名非空 → 记录一条修正,并把 in_param_df J列改为花名册姓名,
使后续「删除记录 / 在参名单输出 / 减员导入」统一使用修正后姓名。
- 花名册查不到(如已离职)无法核对,跳过不处理。
Returns:
corrections: 修正列表,每项 {emp_id, old_name, new_name, category, scheme}
"""
biz_dict = {}
for _, row in biz_df.iterrows():
emp_id = row[BIZ_COL_EMPLOYEE_ID]
if pd.notna(emp_id):
biz_dict[emp_id] = row
corrections = []
for idx, row in in_param_df.iterrows():
emp_id = row.iloc[10]
if pd.isna(emp_id):
continue
biz_row = biz_dict.get(emp_id)
if biz_row is None:
continue # 花名册查不到,无法核对,跳过
new_name = biz_row.get("姓名")
if new_name is None or pd.isna(new_name) or str(new_name).strip() == "":
continue
new_name = str(new_name).strip()
old_name = row.iloc[9]
old_name_txt = "" if pd.isna(old_name) else str(old_name).strip()
if old_name_txt == new_name:
continue # 姓名一致,无需修正
# 就地修正 in_param_df J列(姓名),供后续统一使用
in_param_df.at[idx, in_param_df.columns[9]] = new_name
corrections.append({
"emp_id": emp_id,
"old_name": old_name_txt or "未知",
"new_name": new_name,
"category": biz_row.get(BIZ_COL_CATEGORY),
"scheme": biz_row.get(BIZ_COL_SCHEME),
})
if corrections:
logger.info("姓名核对修正:共 %d 条", len(corrections))
for c in corrections:
logger.info(" %s:%s → %s", c["emp_id"], c["old_name"], c["new_name"])
else:
logger.info("姓名核对完成:在参名单与花名册姓名全部一致")
return corrections
# ============================================================
# 三、阶段1:处理花名册业务
# ============================================================
def process_business(biz_df, idle_pools, employee_map, pending_queues):
"""遍历花名册业务数据,产生待转入队列和额外空闲名额。
业务类型:
1. 增加投保 → 批量加入待转入队列
2. 要替换 → 逐行处理:产生"档次替换迁出"名额,员工置为未参保
3. 其他 → 记录"非法事件跳过"
返回:idle_pools, employee_map, pending_queues, change_log
"""
change_log = []
now = today_date()
# ---------- 1. 增加投保(批量处理) ----------
df_add = biz_df[biz_df[BIZ_COL_HANDLE].astype(str).str.strip() == "增加投保"]
if not df_add.empty:
for scheme, group in df_add.groupby(BIZ_COL_SCHEME):
if pd.isna(scheme) or scheme == "":
for _, row in group.iterrows():
change_log.append({
"员工ID": row[BIZ_COL_EMPLOYEE_ID],
"操作": "非法事件跳过",
"详情": "投保方案为空,无法增加投保",
"时间": now,
})
continue
emp_ids = group[BIZ_COL_EMPLOYEE_ID].tolist()
pending_queues[scheme].extend(emp_ids)
for emp_id in emp_ids:
change_log.append({
"员工ID": emp_id,
"操作": "增加投保",
"详情": f"加入 {scheme} 待转入队列",
"时间": now,
})
# ---------- 2. 要替换(逐行处理,涉及状态变更) ----------
df_replace = biz_df[biz_df[BIZ_COL_HANDLE].astype(str).str.strip() == "要替换"]
for _, row in df_replace.iterrows():
emp_id = row[BIZ_COL_EMPLOYEE_ID]
target_scheme = row[BIZ_COL_SCHEME]
# 校验:员工必须当前已参保
origin_scheme = employee_map.get(emp_id)
if origin_scheme is None:
change_log.append({
"员工ID": emp_id,
"操作": "非法事件跳过",
"详情": "员工当前未参保,无法进行档次替换",
"时间": now,
})
continue
if pd.isna(target_scheme) or target_scheme == "":
change_log.append({
"员工ID": emp_id,
"操作": "非法事件跳过",
"详情": "目标方案为空",
"时间": now,
})
continue
# 产生"档次替换迁出"名额
idle_pools[origin_scheme].append({"type": "档次替换迁出", "employee_id": emp_id})
# 重新排序(离职减少 > 参保减少 > 档次替换迁出)
idle_pools[origin_scheme].sort(
key=lambda x: 1 if x["type"] == "离职减少"
else 2 if x["type"] == "参保减少"
else 3)
# 员工置为未参保
employee_map[emp_id] = None
pending_queues[target_scheme].append(emp_id)
change_log.append({
"员工ID": emp_id,
"操作": "档次替换迁出",
"详情": f"从 {origin_scheme} 迁出,进入 {target_scheme} 待转入",
"时间": now,
})
# ---------- 3. 其他未知类型 ----------
df_other = biz_df[~biz_df[BIZ_COL_HANDLE].astype(str).str.strip().isin(["增加投保", "要替换"])]
for _, row in df_other.iterrows():
change_log.append({
"员工ID": row[BIZ_COL_EMPLOYEE_ID],
"操作": "非法事件跳过",
"详情": f"未知业务类型: {row[BIZ_COL_HANDLE]}",
"时间": now,
})
return idle_pools, employee_map, pending_queues, change_log
# ============================================================
# 四、阶段2:分配名额
# ============================================================
def allocate_slots(idle_pools, employee_map, pending_queues, change_log):
"""逐个方案处理待转入队列,分配空闲名额或创建新名额。
逻辑:
1. 队列中的每个员工必须未参保
2. 有空闲名额 → 复用(记录来源)
3. 无空闲名额 → 全新新增
返回:final_records, change_log, reused_source_employees
"""
final_records = []
reused_source_employees = []
all_schemes = set(idle_pools.keys()) | set(pending_queues.keys())
now = today_date()
for scheme in all_schemes:
queue = pending_queues.get(scheme, [])
pool = idle_pools.get(scheme, [])
for emp_id in queue:
# 校验:员工必须未参保
if employee_map.get(emp_id) is not None:
change_log.append({
"员工ID": emp_id,
"操作": "非法事件跳过",
"详情": f"员工已参保 {employee_map[emp_id]},不能重复参保",
"时间": now,
})
continue
if pool:
# 复用空闲名额(取出优先级最高的)
slot = pool.pop(0)
reused_source_employees.append(slot["employee_id"])
employee_map[emp_id] = scheme
final_records.append({
"证件号": emp_id,
"投保方案": scheme,
"参保状态": "正常参保",
"名额来源": slot["type"],
"来源员工ID": slot["employee_id"],
})
change_log.append({
"员工ID": emp_id,
"操作": "复用空闲名额参保",
"详情": f"复用 {slot['type']}(来源 {slot['employee_id']}),方案 {scheme}",
"来源员工ID": slot["employee_id"],
"时间": now,
})
else:
# 全新新增
employee_map[emp_id] = scheme
final_records.append({
"证件号": emp_id,
"投保方案": scheme,
"参保状态": "正常参保",
"名额来源": "全新新增",
})
change_log.append({
"员工ID": emp_id,
"操作": "全新新增名额参保",
"详情": f"新增名额,方案 {scheme}",
"时间": now,
})
return final_records, change_log, reused_source_employees
# ============================================================
# 四点半、特殊情况槽位追踪(report 层共用)
# ============================================================
def _find_special_slots(final_records, in_param_df):
"""识别特殊情况:离职/参保减少名额被老员工复用,且该老员工释放的旧名额无人复用。
(例如 曹益娟参保减少20万→老员工胡兴复用,胡兴的X档旧名额没人用)。
此时把源员工名额改为老员工旧方案(X档)保留在参名单,变更清单补一条"增加X档",
既保证 增加>=删除 平衡,又把空闲名额放回池中供下次替换使用(避免同人两条名单)。
Returns:
special_slots: [{source_id, source_name, source_category, new_scheme}, ...]
"""
# 初始参保映射:在参名单 M列(投保方案)非空视为"原已参保"
initial_employee_map = {}
for _, row in in_param_df.iterrows():
emp_id = row.iloc[10]
if pd.isna(emp_id):
continue
orig_scheme = row.iloc[12]
if pd.notna(orig_scheme) and str(orig_scheme).strip() != "":
initial_employee_map[emp_id] = True
final_emp_ids = set(rec["证件号"] for rec in final_records)
# 槽位复用网络:来源员工ID -> 接收记录(用于链条追踪)
slot_network = {}
for _rec in final_records:
_sid = _rec.get("来源员工ID")
if _sid is not None and not pd.isna(_sid) and str(_sid).strip():
slot_network[str(_sid).strip()] = _rec
# 链条追踪:离职/参保减少释放的名额被老员工复用后,沿"来源员工ID"网络一路追踪,
# 老员工每次"删除自己旧方案"即释放一个旧名额,若该名额被下一人复用则继续,直到:
# - 接收者是全新新员工(无旧方案可删)→ 链条自然结束,增删本就平衡;
# - 末端老员工释放的旧名额无人复用 → 该旧名额即"空闲名额"(X档)。
special_slots = []
for rec in final_records:
if rec.get("名额来源") not in ("离职减少", "参保减少"):
continue
source_id = rec.get("来源员工ID")
# 源员工自身也参保则跳过,避免同一个人出现两条名单
if source_id is None or pd.isna(source_id) or source_id in final_emp_ids:
continue
source_id = str(source_id).strip()
# 沿链条追踪,找到末端"未被复用的旧方案"(空闲名额 X档)
current_owner = source_id
visited = set()
loose_end_scheme = None
while current_owner not in visited:
visited.add(current_owner)
next_rec = slot_network.get(current_owner)
if next_rec is None:
break # 链条断裂
receiver_id = str(next_rec["证件号"]).strip()
# 接收者不是原已参保老员工(全新新员工)-> 无旧方案可释放,链条自然结束
if receiver_id not in initial_employee_map:
break
# 接收者是老员工:释放自己的旧方案(X档);若该旧名额无人复用则即为空闲名额
if receiver_id not in slot_network:
row_match = in_param_df[in_param_df.iloc[:, 10] == receiver_id]
if not row_match.empty:
loose_end_scheme = row_match.iloc[0].iloc[12]
break
current_owner = receiver_id # 旧名额被复用,继续追踪下一环
if not loose_end_scheme:
continue
src_match = in_param_df[in_param_df.iloc[:, 10] == source_id]
if src_match.empty:
continue
src_row = src_match.iloc[0]
special_slots.append({
"source_id": source_id,
"source_name": src_row.iloc[9],
"source_category": src_row.iloc[11],
"new_scheme": loose_end_scheme,
})
return special_slots
# ============================================================
# 五、类别级编排(读取目标文件 → 三阶段 → 输出)
# ============================================================
def _check_import_templates():
"""前置校验增减员导入模板是否存在,任一缺失立即抛错。
模板在调度开始时校验(而非生成导入文件时才报),避免完整调度跑完后
才发现模板缺失、需要重做的浪费。
"""
missing = [
path for path in (add_import_template(), sub_import_template())
if not os.path.isfile(path)
]
if missing:
raise FileNotFoundError(
"增减员导入模板缺失,请先补充模板后再调度:\n - " + "\n - ".join(missing))
def schedule_category(category, enable_validation=True, gen_import_files=True):
"""对单个类别执行调度全流程(读取已刷新公式的目标文件,输出结果)。
Args:
category: 类别配置
enable_validation: 是否启用数据校验(校验失败抛 DataValidationError 中断)
gen_import_files: 是否生成增员/减员导入文件
前置:目标文件已完成筛选复制(roster_filter)并经 WPS/Excel 重算公式。
"""
category_name = category["name"]
target_file = category_target_file(category)
output_backup = category_output_backup(category)
change_sheet_prefix = category["change_sheet_prefix"]
change_sheet_name = category_change_sheet_name(category)
logger.info("=" * 70)
logger.info("类别[%s] 目标文件:%s", category_name, target_file)
if not os.path.exists(target_file):
raise FileNotFoundError(f"目标表不存在:{target_file},请先完成筛选复制步骤")
# 检查必需 Sheet
xl = pd.ExcelFile(target_file)
for s in (SHEET_BIZ, SHEET_IN_PARAM):
if s not in xl.sheet_names:
raise ValueError(f"目标表缺少必需 Sheet:{s}")
logger.info("文件结构检查通过。")
if gen_import_files:
_check_import_templates()
# ---------- 读取并清洗花名册数据 ----------
# O列(索引14)证件号强制 dtype=str:含空行的列会被 pandas 推断为 float64,
# 18 位身份证号读取即截断(如 ...0009 -> ...0000),导致与在参名单匹配失败
biz_df = pd.read_excel(target_file, sheet_name=SHEET_BIZ, header=3, dtype={14: str})
logger.info("原始花名册数据:%d 行", len(biz_df))
# 过滤:证件号为空 或 方案处理为 "/"
biz_df = biz_df[
biz_df[BIZ_COL_EMPLOYEE_ID].notna() &
(biz_df[BIZ_COL_HANDLE].astype(str).str.strip() != "/")
]
logger.info("清洗后花名册数据:%d 行", len(biz_df))
# ---------- 读取在参名单 ----------
# K列(索引10)证件号同样强制 dtype=str,避免 float64 截断 18 位身份证号
in_param_df = pd.read_excel(target_file, sheet_name=SHEET_IN_PARAM, header=5,
dtype={10: str})
logger.info("在参名单:%d 行", len(in_param_df))
# 主键文本化:证件号统一转文本(pandas 会把纯数字证件号读为 int64,openpyxl 落盘时
# 转浮点会截断 18 位身份证号;统一文本化后匹配/输出全部一致且不丢精度)
# 用整列赋值(允许自动升级 dtype),避免 float64 列 iloc 赋值报 LossySetitemError
biz_df = biz_df.copy()
biz_df[BIZ_COL_EMPLOYEE_ID] = biz_df[BIZ_COL_EMPLOYEE_ID].map(to_text)
in_param_df = in_param_df.copy()
_id_col = in_param_df.columns[10]
in_param_df[_id_col] = in_param_df[_id_col].map(to_text)
column_names = in_param_df.columns.tolist()
# ---------- 姓名核对修正 ----------
logger.info("核对在参名单与花名册姓名...")
name_corrections = collect_name_corrections(in_param_df, biz_df)
# ---------- 数据校验 ----------
if enable_validation:
logger.info("正在校验数据...")
errors = validate_biz_data(biz_df)
if errors:
for e in errors:
logger.error(" 行%s 员工%s:%s - %s",
e["行号"], e["员工ID"], e["错误类型"], e["详情"])
raise DataValidationError(
f"类别[{category_name}] 数据校验失败,共 {len(errors)} 个错误,已中断调度")
logger.info("数据校验通过!")
# ---------- 阶段0:初始化 ----------
logger.info("初始化状态...")
idle_pools, employee_map, pending_queues = initialize(in_param_df)
logger.info(" 空闲名额池:%d 个", sum(len(v) for v in idle_pools.values()))
logger.info(" 当前参保员工:%d 人", len(employee_map))
# ---------- 阶段1:处理业务 ----------
logger.info("处理花名册业务...")
idle_pools, employee_map, pending_queues, change_log = process_business(
biz_df, idle_pools, employee_map, pending_queues)
logger.info(" 待转入总人数:%d 人", sum(len(v) for v in pending_queues.values()))
logger.info(" 变更日志条数:%d", len(change_log))
# ---------- 阶段2:分配名额 ----------
logger.info("分配名额...")
final_records, change_log, reused_source_employees = allocate_slots(
idle_pools, employee_map, pending_queues, change_log)
logger.info(" 最终参保记录:%d 人", len(final_records))
# ---------- 阶段3+4:输出(懒加载 report,避免 import 成环) ----------
from ..report.output import output_results, export_add_sub_import
logger.info("输出结果...")
output_results(
final_records, change_log, reused_source_employees, biz_df,
in_param_df, column_names, target_file, output_backup,
change_sheet_name, change_sheet_prefix, SHEET_IN_PARAM,
name_corrections)
if gen_import_files:
logger.info("生成增员/减员导入文件...")
export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees)
logger.info("类别[%s] 调度完成!", category_name)
return final_records
+122
View File
@@ -0,0 +1,122 @@
# -*- coding: utf-8 -*-
"""XQ0002 插件 - WPS/Excel COM 后台重算 + 取消筛选工具。
替代雇主险流程中「人工打开目标文件刷新公式(Ctrl+S 保存)」环节:
openpyxl 写入数据后公式列的缓存结果会丢失,调度/导出变更清单前必须先重算落盘;
同时移除所有 sheet 的 AutoFilter,保证每次处理结束文件以无筛选状态保存,
后续人工「删除重新粘贴花名册」不再受筛选残留导致数据错位。
底层用 WPS 表格 COM(Ket.Application,专业版/企业版)打开 → 取消筛选 →
CalculateFullRebuild → Save;WPS 不可用时回退 MS Excel(Excel.Application)。
目标文件若已被用户在 WPS/Excel 中打开则复用该工作簿,不打断用户会话。
"""
import os
from ..config import logger
class ComRecalcError(RuntimeError):
"""公式重算失败(文件被占用 / 本机无 WPS 专业版或 MS Excel / COM 异常)。"""
def recalc_target(file_path):
"""对单个 xlsx 执行「取消全部筛选 → 全量重算公式 → 保存」。
目标文件已在 WPS/Excel 中打开时复用该工作簿(不关闭,保留用户会话);
由本函数自行打开的工作簿在保存后关闭;仅当实例已无其他工作簿时才退出 COM。
Args:
file_path: 目标文件绝对路径。
Raises:
ComRecalcError: 重算失败(含本机无可用 COM 引擎 / COM 异常等)。
"""
file_path = os.path.abspath(file_path)
if not os.path.isfile(file_path):
raise ComRecalcError(f"待重算文件不存在:{file_path}")
import pythoncom
import win32com.client
pythoncom.CoInitialize()
app = None
engine = ""
wb = None
already_open = False
try:
# 优先 WPS 表格 COM(Ket.Application);失败回退 MS Excel
try:
app = win32com.client.Dispatch("Ket.Application")
engine = "WPS"
except Exception:
try:
app = win32com.client.Dispatch("Excel.Application")
engine = "Excel"
except Exception as e:
raise ComRecalcError(
"本机未检测到可用的 WPS 表格 COM / MS Excel COM,无法自动重算公式。\n"
"请安装 WPS 专业版/企业版或 MS Excel 后重试,或关闭「WPS/Excel 后台重算公式」开关后人工打开文件 Ctrl+S 刷新公式。"
) from e
# 不设置 Visible=False:Dispatch 可能附着到用户已打开的实例,隐藏其窗口
app.DisplayAlerts = False # 关闭弹窗警告(finally 恢复)
try:
# 目标文件已在 WPS/Excel 中打开时复用该工作簿
for w in app.Workbooks:
try:
if os.path.normcase(str(w.FullName or "")) == os.path.normcase(file_path):
wb = w
already_open = True
break
except Exception:
continue
if wb is None:
wb = app.Workbooks.Open(file_path, UpdateLinks=2)
# 1. 取消所有 sheet 的筛选(筛选只是隐藏行,但会干扰人工维护花名册)
removed = 0
for ws in wb.Worksheets:
try:
if ws.AutoFilterMode:
ws.AutoFilterMode = False
removed += 1
except Exception:
pass
# 2. 强制完整重算全部公式(openpyxl 写入后公式列缓存丢失)
wb.Application.CalculateFullRebuild()
# 3. 把计算结果缓存写入 xlsx 磁盘
wb.Save()
logger.info("公式重算完成(%s COM):取消 %d 个 sheet 筛选%s:%s",
engine, removed,
"(复用已打开的工作簿)" if already_open else "", file_path)
finally:
try:
app.DisplayAlerts = True
except Exception:
pass
if wb is not None and not already_open:
try:
wb.Close(SaveChanges=False)
except Exception:
pass
except ComRecalcError:
raise
except Exception as e:
# 打开失败通常仍是文件被占用/锁定,给出可操作提示
raise ComRecalcError(
f"公式重算失败({engine or 'COM'}):{e}\n"
"请确认该目标文件未被 WPS/Excel 以受保护/只读视图打开(关闭后再试)。"
) from e
finally:
if app is not None:
# 仅当实例已无其他工作簿时才退出,避免关掉用户正在使用的 WPS/Excel
try:
if app.Workbooks.Count == 0:
app.Quit()
except Exception:
pass
try:
pythoncom.CoUninitialize()
except Exception:
pass