refactor(yingdao/雇主险): 重构业务流程步骤拆分与模块复用
1. 调整雇主险目录脚本结构,将原roster_export移出目录并改为共享模块 2. 重构roster_filter:改为复用共享导出模块,更新参数与注释 3. 新增add_sub_import脚本作为步骤3增减员导入,统一全流程调用逻辑 4. 更新README文档,修正步骤说明与文件对应关系
This commit is contained in:
@@ -16,9 +16,10 @@
|
|||||||
2. 通过函数传参调用(无命令行入口):
|
2. 通过函数传参调用(无命令行入口):
|
||||||
from app.service.hrbp.ehr.employer_insurance.add_sub_import import import_employee_change
|
from app.service.hrbp.ehr.employer_insurance.add_sub_import import import_employee_change
|
||||||
|
|
||||||
import_employee_change("增员") # 增员导入(默认文件)
|
import_employee_change("增员") # 增员导入(全部类别)
|
||||||
import_employee_change("减员") # 减员导入(默认文件)
|
import_employee_change("减员") # 减员导入(全部类别)
|
||||||
import_employee_change("增员", r"D:\\...\\xxx.xlsx") # 指定导入文件
|
import_employee_change("增员", ["三十七度"]) # 指定类别
|
||||||
|
import_employee_change("增员", None, r"D:\\...\\xxx.xlsx") # 指定导入文件
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
@@ -49,8 +50,7 @@ except ImportError:
|
|||||||
from app.service.hrbp.ehr.common.config import ADD_SUB_URL # noqa: E402
|
from app.service.hrbp.ehr.common.config import ADD_SUB_URL # noqa: E402
|
||||||
from app.service.hrbp.common.login import load_cookies # noqa: E402
|
from app.service.hrbp.common.login import load_cookies # noqa: E402
|
||||||
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||||
ADD_SUB_IMPORT_ADD_FILE,
|
CATEGORIES,
|
||||||
ADD_SUB_IMPORT_SUB_FILE,
|
|
||||||
get_category,
|
get_category,
|
||||||
category_import_add_file,
|
category_import_add_file,
|
||||||
category_import_sub_file,
|
category_import_sub_file,
|
||||||
@@ -225,38 +225,49 @@ _IMPORT_TYPE_MAP = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def _resolve_import_file(menu_label, category_name):
|
def _import_one(page, category, menu_label, file_path=None):
|
||||||
"""按类别+导入类型解析默认导入文件路径。
|
"""对单个类别执行一次导入(更多操作 -> 选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。
|
||||||
|
|
||||||
指定类别时取该类别文件夹内的导入文件;未指定类别(None)时用三十七度的默认文件。
|
Args:
|
||||||
|
page: 已登录的 ChromiumPage 实例。
|
||||||
|
category: 类别配置 dict。
|
||||||
|
menu_label: 菜单文案(增员导入/减员导入)。
|
||||||
|
file_path: 显式上传文件;不传则按类别文件夹取默认导入文件。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
FileNotFoundError: 导入文件不存在。
|
||||||
"""
|
"""
|
||||||
if category_name:
|
file_path = file_path or (
|
||||||
category = get_category(category_name)
|
category_import_add_file(category) if menu_label == MENU_ADD
|
||||||
if menu_label == MENU_ADD:
|
else category_import_sub_file(category))
|
||||||
return category_import_add_file(category)
|
if not os.path.isfile(file_path):
|
||||||
return category_import_sub_file(category)
|
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||||
return (
|
|
||||||
ADD_SUB_IMPORT_ADD_FILE if menu_label == MENU_ADD else ADD_SUB_IMPORT_SUB_FILE
|
logger.info("===== 类别[%s] 开始%s,文件:%s =====", category["name"], menu_label, file_path)
|
||||||
)
|
_choose_import_menu(page, menu_label)
|
||||||
|
_upload_file(page, file_path)
|
||||||
|
_click_next(page) # 第一步:下一步(进入解析)
|
||||||
|
_click_next(page) # 第二步:下一步(进入确认/完成)
|
||||||
|
_click_close(page) # 第三步:关闭
|
||||||
|
logger.info("===== 类别[%s] %s完成 =====", category["name"], menu_label)
|
||||||
|
|
||||||
|
|
||||||
def import_employee_change(import_type="增员", category_name=None, file_path=None):
|
def import_employee_change(import_type="增员", category_names=None, file_path=None):
|
||||||
"""执行增员/减员导入。
|
"""执行增员/减员导入(可一次传入一个或多个类别,复用同一浏览器)。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
import_type: "增员" 或 "减员"(也兼容 "增员导入"/"减员导入"),默认增员。
|
import_type: "增员" 或 "减员"(也兼容 "增员导入"/"减员导入"),默认增员。
|
||||||
category_name: 类别名(如「湖畔酒店」/「湖畔」),None 表示默认使用三十七度。
|
category_names: 类别名列表(如 ["三十七度", "湖畔酒店"]),
|
||||||
file_path: 要上传的文件路径;不传则按类别+导入类型取默认文件
|
空列表 / None 表示处理全部类别。
|
||||||
(各类别文件夹内的 商业保险增员导入.xlsx / 商业保险减员导入.xlsx;
|
file_path: 要上传的文件路径;若传入则对每个类别使用同一文件(覆盖类别解析);
|
||||||
category_name 为 None 时用三十七度的默认文件)。
|
不传则按各类别文件夹取 商业保险增员导入.xlsx / 商业保险减员导入.xlsx。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
bool: 成功返回 True。
|
bool: 全部类别均成功返回 True;任一类别失败返回 False(失败已逐类打日志,不中断)。
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValueError: import_type 非法。
|
ValueError: import_type 非法。
|
||||||
FileNotFoundError: 导入文件不存在。
|
RuntimeError: 缺少 DrissionPage 依赖。
|
||||||
RuntimeError: 缺少 DrissionPage 依赖或流程任一步骤失败时抛出。
|
|
||||||
"""
|
"""
|
||||||
setup_logging()
|
setup_logging()
|
||||||
if ChromiumPage is None:
|
if ChromiumPage is None:
|
||||||
@@ -266,11 +277,9 @@ def import_employee_change(import_type="增员", category_name=None, file_path=N
|
|||||||
raise ValueError(f"不支持的导入类型:{import_type}(应为「增员」或「减员」)")
|
raise ValueError(f"不支持的导入类型:{import_type}(应为「增员」或「减员」)")
|
||||||
menu_label = _IMPORT_TYPE_MAP[import_type]
|
menu_label = _IMPORT_TYPE_MAP[import_type]
|
||||||
|
|
||||||
file_path = file_path or _resolve_import_file(menu_label, category_name)
|
categories = [get_category(n) for n in category_names] if category_names else CATEGORIES
|
||||||
if not os.path.isfile(file_path):
|
logger.info("===== 开始%s,类别:%s =====", menu_label,
|
||||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
[c["name"] for c in categories])
|
||||||
|
|
||||||
logger.info("===== 开始%s,文件:%s =====", menu_label, file_path)
|
|
||||||
|
|
||||||
co = ChromiumOptions()
|
co = ChromiumOptions()
|
||||||
page = ChromiumPage(co)
|
page = ChromiumPage(co)
|
||||||
@@ -286,17 +295,16 @@ def import_employee_change(import_type="增员", category_name=None, file_path=N
|
|||||||
logger.warning("注入缓存 cookies 失败:%s", e)
|
logger.warning("注入缓存 cookies 失败:%s", e)
|
||||||
|
|
||||||
_ensure_logged_in(page)
|
_ensure_logged_in(page)
|
||||||
_choose_import_menu(page, menu_label)
|
|
||||||
_upload_file(page, file_path)
|
|
||||||
_click_next(page) # 第一步:下一步(进入解析)
|
|
||||||
_click_next(page) # 第二步:下一步(进入确认/完成)
|
|
||||||
_click_close(page) # 第三步:关闭
|
|
||||||
|
|
||||||
logger.info("===== %s完成 =====", menu_label)
|
ok = 0
|
||||||
return True
|
for category in categories:
|
||||||
|
try:
|
||||||
|
_import_one(page, category, menu_label, file_path)
|
||||||
|
ok += 1
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception("%s失败,详细堆栈如下:", menu_label)
|
logger.exception("类别[%s] %s失败:", category["name"], menu_label)
|
||||||
raise
|
logger.info("===== %s 全部完成(成功 %d/%d) =====", menu_label, ok, len(categories))
|
||||||
|
return ok == len(categories)
|
||||||
finally:
|
finally:
|
||||||
try:
|
try:
|
||||||
page.quit()
|
page.quit()
|
||||||
@@ -304,6 +312,25 @@ def import_employee_change(import_type="增员", category_name=None, file_path=N
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def main(category_names=None):
|
||||||
|
"""执行的入口:对指定/全部类别一次性完成增员+减员导入,返回调用方需要的结构化结果。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
category_names: 类别名列表,空/None=全部类别。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
{"success": bool, "categories": [...], "details": {"增员导入": bool, "减员导入": bool}}
|
||||||
|
"""
|
||||||
|
categories = [get_category(n)["name"] for n in category_names] if category_names \
|
||||||
|
else [c["name"] for c in CATEGORIES]
|
||||||
|
details = {}
|
||||||
|
ok_all = True
|
||||||
|
for import_type in ("增员", "减员"):
|
||||||
|
success = import_employee_change(import_type, category_names)
|
||||||
|
details[_IMPORT_TYPE_MAP[import_type]] = success
|
||||||
|
ok_all = ok_all and success
|
||||||
|
return {"success": ok_all, "categories": categories, "details": details}
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import_employee_change("增员")
|
main(category_names=["三十七度"])
|
||||||
import_employee_change("减员")
|
|
||||||
|
|||||||
+3
-3
@@ -31,9 +31,9 @@ yingdao/
|
|||||||
│ ├── bank_card_check.py # 银行卡检查
|
│ ├── bank_card_check.py # 银行卡检查
|
||||||
│ └── social_change.py # 人事变动
|
│ └── social_change.py # 人事变动
|
||||||
├── employer_insurance/ # 雇主险类业务脚本(单文件自包含)
|
├── employer_insurance/ # 雇主险类业务脚本(单文件自包含)
|
||||||
│ ├── roster_export.py # 雇主险花名册导出(内含 HR 登录,输出雇主险源表)
|
│ ├── roster_filter.py # 步骤2:筛选复制(源表缺失时复用「37du花名册导出」)
|
||||||
│ ├── roster_filter.py # 筛选复制(第二步)
|
│ ├── employer_insurance_schedule.py # 步骤2:调度(生成增员/减员导入文件)
|
||||||
│ └── employer_insurance_schedule.py # 名额调度(第三步)
|
│ └── add_sub_import.py # 步骤3:增减员导入(HR「待增减人员」页面上传)
|
||||||
└── README.md # 本文档
|
└── README.md # 本文档
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,386 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
@FileName: add_sub_import.py
|
||||||
|
@Author: 小布丁
|
||||||
|
@CreateTime: 2026-08-23
|
||||||
|
@Description: 雇主险流程「步骤3:增减员导入」(影刀版,单文件自包含)——在 HR「待增减人员」页面
|
||||||
|
执行增员/减员导入(复刻 aa.md 与 app 版 add_sub_import 的操作流程):
|
||||||
|
访问页面 -> 更多操作 -> 增员导入/减员导入 -> 上传文件 -> 下一步 -> 下一步 -> 关闭。
|
||||||
|
登录态复用「37duHR登录」写入的共享 hr_cookies.json(只读不补登)。
|
||||||
|
@Version: 1.0.0
|
||||||
|
|
||||||
|
设计说明(与 yingdao 下其它单文件版一致):
|
||||||
|
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||||
|
- 登录态复用共享 hr_cookies.json(缺失/失效引导先运行「37duHR登录」指令,不自动补登)。
|
||||||
|
- 按类别传参(category_names 列表,空/None=全部类别),导入文件取各类别文件夹内的
|
||||||
|
商业保险增员导入.xlsx / 商业保险减员导入.xlsx(由 schedule 步骤生成)。
|
||||||
|
|
||||||
|
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||||
|
pip install DrissionPage
|
||||||
|
|
||||||
|
环境变量(.env 文件或系统变量,可选):
|
||||||
|
employer_insurance_base_dir = 雇主险文件目录(默认 D:\\资料\\人资\\雇主险)
|
||||||
|
|
||||||
|
运行:直接执行本文件,按 __main__ 中的示例传参(增员/减员 + 类别列表)调用 main()
|
||||||
|
main(category_names=['三十七度']) 或 import_employee_change(import_type, category_names)
|
||||||
|
"""
|
||||||
|
|
||||||
|
# ==================== 标准库导入 ====================
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
|
||||||
|
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||||
|
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||||
|
try:
|
||||||
|
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
except ImportError as _import_err:
|
||||||
|
raise RuntimeError(
|
||||||
|
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||||
|
"请先执行安装:\n"
|
||||||
|
" pip install DrissionPage\n"
|
||||||
|
f"缺失依赖详情: {_import_err}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 日志(print 替代 logging) ====================
|
||||||
|
class _PrintLogger:
|
||||||
|
def debug(self, msg, *args, **kwargs):
|
||||||
|
print(msg % args if args else msg)
|
||||||
|
|
||||||
|
def info(self, msg, *args, **kwargs):
|
||||||
|
print(msg % args if args else msg)
|
||||||
|
|
||||||
|
def warning(self, msg, *args, **kwargs):
|
||||||
|
print(msg % args if args else msg)
|
||||||
|
|
||||||
|
def error(self, msg, *args, **kwargs):
|
||||||
|
print(msg % args if args else msg)
|
||||||
|
|
||||||
|
|
||||||
|
logger = _PrintLogger()
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 路径 & 常量配置(与 app 版 config 一致) ====================
|
||||||
|
BASE_DIR = os.getenv("employer_insurance_base_dir") or r"D:\资料\人资\雇主险"
|
||||||
|
|
||||||
|
# 共享 HR 登录态:由「37duHR登录」指令(yingdao/share/hr_login.py)写入
|
||||||
|
_APP_DATA_DIR = os.path.join(
|
||||||
|
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||||
|
'37duAutomation'
|
||||||
|
)
|
||||||
|
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||||
|
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||||
|
|
||||||
|
# ---------- HR 系统「待增减人员」页面(与 app 版 ehr/common/config 一致) ----------
|
||||||
|
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=待增减人员"
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---------- 四大类别(全流程按类别传参处理,与 app 版 config.CATEGORIES 一致) ----------
|
||||||
|
CATEGORIES = [
|
||||||
|
{"name": "三十七度", "folder": os.path.join(BASE_DIR, "三十七度")},
|
||||||
|
{"name": "水庄餐饮", "folder": os.path.join(BASE_DIR, "水庄餐饮")},
|
||||||
|
{"name": "湖畔酒店", "folder": os.path.join(BASE_DIR, "湖畔酒店")},
|
||||||
|
{"name": "秒创传媒", "folder": os.path.join(BASE_DIR, "秒创传媒")},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 类别辅助函数(全流程共用,与 app 版 config 一致) ----------
|
||||||
|
def get_category(name):
|
||||||
|
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name: 类别名
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
类别配置 dict
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: 未知名或前缀不唯一
|
||||||
|
"""
|
||||||
|
name = (name or "").strip()
|
||||||
|
for c in CATEGORIES:
|
||||||
|
if c["name"] == name:
|
||||||
|
return c
|
||||||
|
matched = [c for c in CATEGORIES if c["name"].startswith(name)]
|
||||||
|
if len(matched) == 1:
|
||||||
|
return matched[0]
|
||||||
|
raise ValueError(f"未知类别:{name},可选:{[c['name'] for c in CATEGORIES]}")
|
||||||
|
|
||||||
|
|
||||||
|
def category_import_add_file(category):
|
||||||
|
"""类别「增员导入」文件路径(放在类别文件夹内,由 schedule 步骤生成)。"""
|
||||||
|
return os.path.join(category["folder"], "商业保险增员导入.xlsx")
|
||||||
|
|
||||||
|
|
||||||
|
def category_import_sub_file(category):
|
||||||
|
"""类别「减员导入」文件路径(放在类别文件夹内,由 schedule 步骤生成)。"""
|
||||||
|
return os.path.join(category["folder"], "商业保险减员导入.xlsx")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 流程步骤文案常量(与 app 版 add_sub_import 一致) ----------
|
||||||
|
BTN_MORE = "更多操作" # 「更多操作」下拉按钮
|
||||||
|
MENU_ADD = "增员导入" # 下拉菜单:增员导入
|
||||||
|
MENU_SUB = "减员导入" # 下拉菜单:减员导入
|
||||||
|
BTN_NEXT = "下一步" # 导入弹窗「下一步」按钮(第 2/3 步)
|
||||||
|
BTN_CLOSE = "关闭" # 导入完成弹窗「关闭」按钮
|
||||||
|
|
||||||
|
# 通用等待秒数
|
||||||
|
WAIT_SHORT = 0.6
|
||||||
|
WAIT_MID = 2.0
|
||||||
|
WAIT_LONG = 4.0
|
||||||
|
|
||||||
|
|
||||||
|
class LoginRequiredError(Exception):
|
||||||
|
"""打开页面被重定向到登录页(cookies 缺失或失效)。"""
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 登录态(共享 cookies 文件) ====================
|
||||||
|
def _load_shared_hr_cookies():
|
||||||
|
"""读取共享 HR cookies 文件(由「37duHR登录」指令写入)。"""
|
||||||
|
if os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||||
|
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||||
|
cookies = json.load(f)
|
||||||
|
return cookies or None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 元素定位辅助(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 RuntimeError(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 RuntimeError(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):
|
||||||
|
"""访问待增减人员页面;若被重定向到登录页,提示先运行「37duHR登录」指令。"""
|
||||||
|
page.get(ADD_SUB_URL)
|
||||||
|
time.sleep(WAIT_LONG)
|
||||||
|
|
||||||
|
# 登录页特征:存在用户名输入框
|
||||||
|
if page.ele('@id=j_username', timeout=2):
|
||||||
|
raise LoginRequiredError(
|
||||||
|
"HR 登录态已失效/缺失。请先在影刀流程开头调用「37duHR登录」指令完成登录,"
|
||||||
|
"或本地运行: python yingdao/share/hr_login.py")
|
||||||
|
logger.info("已进入待增减人员页面:%s", page.url)
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 增员/减员导入主流程(aa.md 步骤) ====================
|
||||||
|
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-btns 容器内的 btn-success dropdown-toggle)
|
||||||
|
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 RuntimeError("未找到「更多操作」下拉菜单(#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):
|
||||||
|
"""在导入弹窗中上传指定文件。
|
||||||
|
|
||||||
|
aa.md:选择文件夹按钮(glyphicon glyphicon-folder-open)会弹出文件选择器;
|
||||||
|
这里直接用 DrissionPage 对 <input type="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 RuntimeError("未找到文件上传控件(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 RuntimeError("未找到可见的「下一步」按钮")
|
||||||
|
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 RuntimeError("未找到可见的「关闭」按钮")
|
||||||
|
btn.click()
|
||||||
|
logger.info("已点击「关闭」")
|
||||||
|
time.sleep(WAIT_SHORT)
|
||||||
|
|
||||||
|
|
||||||
|
def _import_one(page, category, menu_label, file_path=None):
|
||||||
|
"""对单个类别执行一次导入(更多操作 -> 选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。"""
|
||||||
|
file_path = file_path or (
|
||||||
|
category_import_add_file(category) if menu_label == MENU_ADD
|
||||||
|
else category_import_sub_file(category))
|
||||||
|
if not os.path.isfile(file_path):
|
||||||
|
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||||
|
|
||||||
|
logger.info("===== 类别[%s] 开始%s,文件:%s =====", category["name"], menu_label, file_path)
|
||||||
|
_choose_import_menu(page, menu_label)
|
||||||
|
_upload_file(page, file_path)
|
||||||
|
_click_next(page) # 第一步:下一步(进入解析)
|
||||||
|
_click_next(page) # 第二步:下一步(进入确认/完成)
|
||||||
|
_click_close(page) # 第三步:关闭
|
||||||
|
logger.info("===== 类别[%s] %s完成 =====", category["name"], menu_label)
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 对外入口(函数传参调用,支持多类别) ====================
|
||||||
|
# 参数兼容「增员/减员」短名 与「增员导入/减员导入」菜单全名
|
||||||
|
_IMPORT_TYPE_MAP = {
|
||||||
|
"增员": MENU_ADD,
|
||||||
|
"减员": MENU_SUB,
|
||||||
|
MENU_ADD: MENU_ADD,
|
||||||
|
MENU_SUB: MENU_SUB,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def import_employee_change(import_type="增员", category_names=None, file_path=None):
|
||||||
|
"""执行增员/减员导入(可一次传入一个或多个类别,复用同一浏览器)。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
import_type: "增员" 或 "减员"(也兼容 "增员导入"/"减员导入"),默认增员。
|
||||||
|
category_names: 类别名列表(如 ["三十七度", "湖畔酒店"]),
|
||||||
|
空列表 / None 表示处理全部类别。
|
||||||
|
file_path: 要上传的文件路径;若传入则对每个类别使用同一文件(覆盖类别解析);
|
||||||
|
不传则按类别文件夹取 schedule 步骤生成的 商业保险增员/减员导入.xlsx。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: 全部类别均成功返回 True;任一类别失败返回 False(失败已逐类打日志)。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
LoginRequiredError: 共享 HR 登录态缺失/失效,需先运行「37duHR登录」指令。
|
||||||
|
ValueError: import_type 非法。
|
||||||
|
"""
|
||||||
|
if import_type not in _IMPORT_TYPE_MAP:
|
||||||
|
raise ValueError(f"不支持的导入类型:{import_type}(应为「增员」或「减员」)")
|
||||||
|
menu_label = _IMPORT_TYPE_MAP[import_type]
|
||||||
|
|
||||||
|
categories = [get_category(n) for n in category_names] if category_names else CATEGORIES
|
||||||
|
|
||||||
|
logger.info("===== 开始%s,类别:%s =====", menu_label,
|
||||||
|
[c["name"] for c in categories])
|
||||||
|
page = _create_page()
|
||||||
|
logger.info("浏览器已启动")
|
||||||
|
try:
|
||||||
|
cookies = _load_shared_hr_cookies()
|
||||||
|
if not cookies:
|
||||||
|
raise LoginRequiredError(
|
||||||
|
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||||
|
logger.info("加载缓存 cookies:%d 个", len(cookies))
|
||||||
|
page.set.cookies(cookies)
|
||||||
|
_ensure_logged_in(page)
|
||||||
|
|
||||||
|
ok = 0
|
||||||
|
for category in categories:
|
||||||
|
try:
|
||||||
|
_import_one(page, category, menu_label, file_path)
|
||||||
|
ok += 1
|
||||||
|
except Exception:
|
||||||
|
logger.exception("类别[%s] %s失败:", category["name"], menu_label)
|
||||||
|
logger.info("===== %s 全部完成(成功 %d/%d) =====", menu_label, ok, len(categories))
|
||||||
|
return ok == len(categories)
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
page.quit()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def main(category_names=None):
|
||||||
|
"""影刀自定义指令入口「37du增减员导入」:对指定/全部类别一次性完成增员+减员导入。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
category_names: 类别名列表,空/None=全部类别。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
{"success": bool, "categories": [...], "details": {"增员导入": bool, "减员导入": bool}}
|
||||||
|
"""
|
||||||
|
load_dotenv()
|
||||||
|
categories = [get_category(n)["name"] for n in category_names] if category_names \
|
||||||
|
else [c["name"] for c in CATEGORIES]
|
||||||
|
details = {}
|
||||||
|
ok_all = True
|
||||||
|
for import_type in ("增员", "减员"):
|
||||||
|
success = import_employee_change(import_type, category_names)
|
||||||
|
details[_IMPORT_TYPE_MAP[import_type]] = success
|
||||||
|
ok_all = ok_all and success
|
||||||
|
return {"success": ok_all, "categories": categories, "details": details}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main(category_names=["三十七度"])
|
||||||
@@ -1,813 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
@FileName: roster_export.py
|
|
||||||
@Author: 小布丁
|
|
||||||
@CreateTime: 2026-08-13
|
|
||||||
@Description: 雇主险花名册导出(影刀版,单文件自包含)——HR 登录(滑块验证码) -> 花名册页
|
|
||||||
-> 在职 -> 自定义导出「雇主险增减员导出模板」-> 下载并按统一格式保存到
|
|
||||||
D:\资料\人资\雇主险\员工花名册.xlsx。作为雇主险流程第一步的输出源表。
|
|
||||||
@Version: 1.0.0
|
|
||||||
|
|
||||||
设计说明(避免维护 app/影刀两套版本,与 yingdao 下其它单文件版一致):
|
|
||||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
|
||||||
- 内含 HR 登录(滑块验证码识别),保证花名册导出所需的 hr.37du.co 登录态。
|
|
||||||
- 输出统一规范:单 sheet、只保留第2行表头(丢弃第1行标题)、「类型」列统一放最后一列
|
|
||||||
(与 app 版输出一致,供 roster_filter 等直接读取)。
|
|
||||||
|
|
||||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
|
||||||
pip install DrissionPage python-dotenv requests pandas openpyxl opencv-python numpy Pillow
|
|
||||||
|
|
||||||
环境变量(.env 文件或系统变量):
|
|
||||||
HR 登录:hr_login_username / hr_login_password(必须)
|
|
||||||
可选:
|
|
||||||
roster_template=雇主险增减员导出模板 自定义导出模板名(默认雇主险模板)
|
|
||||||
roster_statuses=在职 需导出的在职状态(逗号分隔,默认仅在职)
|
|
||||||
roster_output_path= 合并后源表保存路径(默认 D:\\资料\\人资\\雇主险\\员工花名册.xlsx)
|
|
||||||
roster_download_dir= 浏览器下载临时目录(默认 D:\\资料\\人资\\员工花名册)
|
|
||||||
|
|
||||||
运行:直接执行本文件即可导出花名册(无需命令行参数)
|
|
||||||
"""
|
|
||||||
|
|
||||||
# ==================== 标准库导入 ====================
|
|
||||||
import functools
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import random
|
|
||||||
import re
|
|
||||||
import time
|
|
||||||
|
|
||||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
|
||||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
|
||||||
try:
|
|
||||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
|
||||||
from dotenv import load_dotenv
|
|
||||||
import pandas as pd
|
|
||||||
import cv2
|
|
||||||
import numpy as np
|
|
||||||
except ImportError as _import_err:
|
|
||||||
raise RuntimeError(
|
|
||||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
|
||||||
"请先执行安装:\n"
|
|
||||||
" pip install DrissionPage python-dotenv requests pandas openpyxl opencv-python "
|
|
||||||
"numpy Pillow\n"
|
|
||||||
f"缺失依赖详情: {_import_err}"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# ==================== 日志(print 替代 logging) ====================
|
|
||||||
class _PrintLogger:
|
|
||||||
def debug(self, msg, *args, **kwargs):
|
|
||||||
print(msg % args if args else msg)
|
|
||||||
|
|
||||||
def info(self, msg, *args, **kwargs):
|
|
||||||
print(msg % args if args else msg)
|
|
||||||
|
|
||||||
def warning(self, msg, *args, **kwargs):
|
|
||||||
print(msg % args if args else msg)
|
|
||||||
|
|
||||||
def error(self, msg, *args, **kwargs):
|
|
||||||
print(msg % args if args else msg)
|
|
||||||
|
|
||||||
|
|
||||||
logger = _PrintLogger()
|
|
||||||
|
|
||||||
|
|
||||||
# ==================== 路径 & 常量配置 ====================
|
|
||||||
# 缓存统一放在 %LOCALAPPDATA%\37duAutomation\EmployerInsurance(影刀版独立子目录)
|
|
||||||
_APP_DATA_DIR = os.path.join(
|
|
||||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
|
||||||
'37duAutomation', 'EmployerInsurance'
|
|
||||||
)
|
|
||||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
|
||||||
COOKIE_FILE_HR = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
|
||||||
|
|
||||||
# ---------- HR 系统 ----------
|
|
||||||
HR_BASE_URL = "https://hr.37du.co"
|
|
||||||
HR_LOGIN_URL = f"{HR_BASE_URL}/RedseaPlatform/"
|
|
||||||
HR_SUCCESS_KEYWORD = f"{HR_BASE_URL}/RedseaPlatform/PtPortal.mc?method=classic"
|
|
||||||
|
|
||||||
# ---------- 花名册自定义导出页面(aa.md 提供,与 app 版 ehr/common/config 一致) ----------
|
|
||||||
ROSTER_URL = (
|
|
||||||
"https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic"
|
|
||||||
"#ajax&1&nworktoday-40175-24311-77128-52242&nworktoday-40175-24311"
|
|
||||||
"|/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/"
|
|
||||||
"getCustomCommonList.mc?clickFlag=true&treePermitType=permit"
|
|
||||||
"&useSealTreeData=0&menuName=%E5%91%98%E5%B7%A5%E8%8A%B1%E5%90%8D%E5%86%8C"
|
|
||||||
)
|
|
||||||
|
|
||||||
# ---------- 雇主险场景参数(可用环境变量/命令行覆盖) ----------
|
|
||||||
DEFAULT_TEMPLATE = "雇主险增减员导出模板"
|
|
||||||
DEFAULT_STATUSES = ["在职"]
|
|
||||||
DEFAULT_OUTPUT_PATH = r"D:\资料\人资\雇主险\员工花名册.xlsx"
|
|
||||||
DEFAULT_DOWNLOAD_DIR = r"D:\资料\人资\员工花名册"
|
|
||||||
|
|
||||||
# ---------- 流程步骤文案(与 app 版 roster_export 一致) ----------
|
|
||||||
TAB_ORG = "组织机构" # 左侧「组织机构」tab,切换为组织树
|
|
||||||
TREE_GROUP = "集团" # 组织树根节点
|
|
||||||
BTN_MORE = "更多操作" # 更多操作按钮
|
|
||||||
MENU_CUSTOM_EXPORT = "自定义导出"
|
|
||||||
TEMPLATE_PLACEHOLDER = "请选择模板"
|
|
||||||
BTN_CONFIRM = "确认导出"
|
|
||||||
FILTER_XPATH = 'xpath://button[contains(@class,"el-button--primary") and normalize-space(.)="筛选"]'
|
|
||||||
|
|
||||||
# ---------- 通用等待秒数 ----------
|
|
||||||
WAIT_SHORT = 0.6
|
|
||||||
WAIT_MID = 2.0
|
|
||||||
WAIT_LONG = 4.0
|
|
||||||
DOWNLOAD_FINISH_TIMEOUT = 300 # 等待下载完成
|
|
||||||
|
|
||||||
# ---------- HR 登录配置 ----------
|
|
||||||
LOGIN_BTN = "@id=login-btn"
|
|
||||||
ACCOUNT_INPUT_HR = "@id=j_username"
|
|
||||||
PASSWORD_INPUT_HR = "@id=j_password_2"
|
|
||||||
CAPTCHA_CONTAINER = ".:comImageValidate"
|
|
||||||
SLIDER_BTN = ".:v_rightBtn"
|
|
||||||
BG_IMG = ".imgBg"
|
|
||||||
SLIDER_IMG = "css:div.imgBg_3 > img"
|
|
||||||
HR_RETRY_MAX = 5
|
|
||||||
HR_TIMEOUT = 10
|
|
||||||
HR_HEADLESS = False
|
|
||||||
|
|
||||||
|
|
||||||
# ==================== 重试装饰器 ====================
|
|
||||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()):
|
|
||||||
if max_attempts < 1:
|
|
||||||
raise ValueError("max_attempts must be >= 1")
|
|
||||||
|
|
||||||
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 last_exc
|
|
||||||
return wrapper
|
|
||||||
return decorator
|
|
||||||
|
|
||||||
|
|
||||||
# ==================== Cookies 持久化 ====================
|
|
||||||
def _ensure_dir(path):
|
|
||||||
os.makedirs(path, exist_ok=True)
|
|
||||||
|
|
||||||
|
|
||||||
def save_browser_cookies(browser_page, path):
|
|
||||||
cookies = browser_page.cookies(all_domains=True)
|
|
||||||
if not cookies:
|
|
||||||
logger.warning("未获取到 Cookies,跳过保存")
|
|
||||||
return
|
|
||||||
_ensure_dir(os.path.dirname(path))
|
|
||||||
with open(path, 'w', encoding='utf-8') as f:
|
|
||||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
|
||||||
logger.info("已保存 %d 个 Cookies 到 %s", len(cookies), path)
|
|
||||||
|
|
||||||
|
|
||||||
def load_cookies(path):
|
|
||||||
if not os.path.exists(path):
|
|
||||||
return None
|
|
||||||
with open(path, encoding='utf-8') as f:
|
|
||||||
cookies = json.load(f)
|
|
||||||
return cookies or None
|
|
||||||
|
|
||||||
|
|
||||||
# ==================== HR 登录(滑块验证码) ====================
|
|
||||||
def match_slider_dual(bg_bytes, slider_bytes):
|
|
||||||
"""模板匹配滑块缺口,返回物理距离(px)。"""
|
|
||||||
bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR)
|
|
||||||
slider_color = cv2.imdecode(np.frombuffer(slider_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
|
|
||||||
if bg_img is None or slider_color is None:
|
|
||||||
raise RuntimeError("无法解码验证码图片")
|
|
||||||
|
|
||||||
bg_h, bg_w = bg_img.shape[:2]
|
|
||||||
x_offset, y_offset = 0, 0
|
|
||||||
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
|
|
||||||
alpha = slider_color[:, :, 3]
|
|
||||||
slider_rgb = slider_color[:, :, :3]
|
|
||||||
ys, xs = np.where(alpha > 0)
|
|
||||||
if len(ys) > 0:
|
|
||||||
y_min, y_max = np.min(ys), np.max(ys)
|
|
||||||
x_min, x_max = np.min(xs), np.max(xs)
|
|
||||||
slider_rgb = slider_rgb[y_min:y_max + 1, x_min:x_max + 1]
|
|
||||||
x_offset, y_offset = x_min, y_min
|
|
||||||
else:
|
|
||||||
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
|
|
||||||
|
|
||||||
s_h, s_w = slider_rgb.shape[:2]
|
|
||||||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
|
||||||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
|
||||||
bg_edges = cv2.Canny(gray_bg, 50, 150)
|
|
||||||
slider_edges = cv2.Canny(gray_slider, 50, 150)
|
|
||||||
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
|
|
||||||
|
|
||||||
candidates = []
|
|
||||||
temp_result = result.copy()
|
|
||||||
for _ in range(6):
|
|
||||||
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
|
|
||||||
if max_val < 0.03:
|
|
||||||
break
|
|
||||||
candidates.append((max_val, max_loc))
|
|
||||||
y0 = max(0, max_loc[1] - s_h // 2); y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
|
|
||||||
x0 = max(0, max_loc[0] - s_w // 2); x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
|
|
||||||
temp_result[y0:y1, x0:x1] = -2.0
|
|
||||||
|
|
||||||
if not candidates:
|
|
||||||
raise RuntimeError("无有效滑块候选")
|
|
||||||
|
|
||||||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
|
||||||
|
|
||||||
def region_whiteness(x, y, w, h):
|
|
||||||
roi = bg_img[y:y + h, x:x + w]
|
|
||||||
if roi.size == 0:
|
|
||||||
return 0.0
|
|
||||||
return float(np.all(roi > 200, axis=2).mean())
|
|
||||||
|
|
||||||
scored = []
|
|
||||||
for val, loc in candidates:
|
|
||||||
x, y = loc
|
|
||||||
if x <= s_w or x > right_limit:
|
|
||||||
continue
|
|
||||||
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
|
|
||||||
|
|
||||||
if scored:
|
|
||||||
scored.sort(key=lambda t: t[0], reverse=True)
|
|
||||||
best_val, best_loc = scored[0][1], scored[0][2]
|
|
||||||
else:
|
|
||||||
best_val, best_loc = candidates[0]
|
|
||||||
|
|
||||||
distance = best_loc[0] - x_offset
|
|
||||||
if distance < 0:
|
|
||||||
distance = 0
|
|
||||||
if distance + s_w > bg_w:
|
|
||||||
distance = bg_w - s_w
|
|
||||||
return distance
|
|
||||||
|
|
||||||
|
|
||||||
def generate_track(distance):
|
|
||||||
overshoot = random.randint(2, 6) if random.random() < 0.75 else 0
|
|
||||||
aim = distance + overshoot
|
|
||||||
steps = []
|
|
||||||
moved = 0
|
|
||||||
y = 0
|
|
||||||
while moved < aim:
|
|
||||||
remain = aim - moved
|
|
||||||
if remain > 80:
|
|
||||||
dx = min(remain, random.randint(9, 15)); dt = random.uniform(0.010, 0.022)
|
|
||||||
elif remain > 35:
|
|
||||||
dx = min(remain, random.randint(5, 9)); dt = random.uniform(0.012, 0.028)
|
|
||||||
elif remain > 12:
|
|
||||||
dx = min(remain, random.randint(2, 5)); dt = random.uniform(0.016, 0.040)
|
|
||||||
else:
|
|
||||||
dx = min(remain, random.randint(1, 3)); dt = random.uniform(0.020, 0.060)
|
|
||||||
if random.random() < 0.22:
|
|
||||||
y = max(-2, min(2, y + random.choice([-1, 1])))
|
|
||||||
else:
|
|
||||||
y = int(round(y * 0.6))
|
|
||||||
steps.append((dx, y, dt))
|
|
||||||
moved += dx
|
|
||||||
if overshoot > 0:
|
|
||||||
back = overshoot
|
|
||||||
while back > 0:
|
|
||||||
dx = -min(back, random.randint(1, 3))
|
|
||||||
steps.append((dx, random.choice([-1, 0, 1]), random.uniform(0.030, 0.080)))
|
|
||||||
back += dx
|
|
||||||
if random.random() < 0.65:
|
|
||||||
steps.extend([(0, 0, random.uniform(0.060, 0.140)),
|
|
||||||
(1, 0, random.uniform(0.020, 0.050)),
|
|
||||||
(-1, 0, random.uniform(0.020, 0.050))])
|
|
||||||
return steps
|
|
||||||
|
|
||||||
|
|
||||||
def perform_slide(page, btn, distance_css):
|
|
||||||
if distance_css <= 0:
|
|
||||||
return False
|
|
||||||
mid = btn.rect.midpoint
|
|
||||||
steps = generate_track(distance_css)
|
|
||||||
try:
|
|
||||||
page.actions.move_to((mid[0] + random.uniform(-3, 3), mid[1] + random.uniform(-2, 2)),
|
|
||||||
duration=random.uniform(0.25, 0.60))
|
|
||||||
time.sleep(random.uniform(0.18, 0.45))
|
|
||||||
page.actions.hold(on_ele=btn)
|
|
||||||
time.sleep(random.uniform(0.12, 0.28))
|
|
||||||
for dx, dy, dt in steps:
|
|
||||||
if dx == 0 and dy == 0:
|
|
||||||
time.sleep(dt)
|
|
||||||
else:
|
|
||||||
page.actions.move(offset_x=dx, offset_y=dy, duration=dt)
|
|
||||||
time.sleep(random.uniform(0.10, 0.26))
|
|
||||||
page.actions.release()
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("拖拽异常:%s", e)
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def handle_hr_captcha(page):
|
|
||||||
for retry_no in range(HR_RETRY_MAX):
|
|
||||||
logger.info("--- HR 第 %d 次尝试验证 ---", retry_no + 1)
|
|
||||||
try:
|
|
||||||
container = page.ele(CAPTCHA_CONTAINER, timeout=HR_TIMEOUT)
|
|
||||||
if not container:
|
|
||||||
continue
|
|
||||||
bg_ele = container.ele(BG_IMG) or container.ele('div[style*="background-image"]')
|
|
||||||
slider_ele = container.ele(SLIDER_IMG)
|
|
||||||
if not bg_ele or not slider_ele:
|
|
||||||
continue
|
|
||||||
if slider_ele.tag != 'img':
|
|
||||||
inner = slider_ele.ele('tag:img')
|
|
||||||
if inner:
|
|
||||||
slider_ele = inner
|
|
||||||
try:
|
|
||||||
page.run_js('arguments[0].style.display = "none"', slider_ele)
|
|
||||||
time.sleep(0.2)
|
|
||||||
bg_screenshot = bg_ele.get_screenshot(as_bytes='png')
|
|
||||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
|
||||||
time.sleep(0.2)
|
|
||||||
slider_screenshot = slider_ele.get_screenshot(as_bytes='png')
|
|
||||||
except Exception:
|
|
||||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
|
||||||
continue
|
|
||||||
|
|
||||||
distance_phys = match_slider_dual(bg_screenshot, slider_screenshot)
|
|
||||||
dpr = page.run_js('return window.devicePixelRatio') or 1
|
|
||||||
distance_css = distance_phys / dpr
|
|
||||||
logger.info("匹配距离 %dpx -> CSS %.1fpx", distance_phys, distance_css)
|
|
||||||
|
|
||||||
btn = page.ele(SLIDER_BTN)
|
|
||||||
if btn and perform_slide(page, btn, distance_css):
|
|
||||||
time.sleep(2)
|
|
||||||
if HR_SUCCESS_KEYWORD in page.url:
|
|
||||||
return True
|
|
||||||
if not page.ele(CAPTCHA_CONTAINER, timeout=1):
|
|
||||||
return True
|
|
||||||
time.sleep(2)
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("验证异常:%s", e)
|
|
||||||
time.sleep(1)
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
class LoginRequiredError(Exception):
|
|
||||||
"""登录态失效:打开页面被重定向到登录页。"""
|
|
||||||
|
|
||||||
|
|
||||||
def _create_page():
|
|
||||||
"""创建新的 ChromiumPage(统一配置)。"""
|
|
||||||
co = ChromiumOptions()
|
|
||||||
if HR_HEADLESS:
|
|
||||||
co.headless()
|
|
||||||
return ChromiumPage(co)
|
|
||||||
|
|
||||||
|
|
||||||
def hr_login(username=None, password=None):
|
|
||||||
load_dotenv()
|
|
||||||
final_username = username or os.getenv('hr_login_username')
|
|
||||||
final_password = password or os.getenv('hr_login_password')
|
|
||||||
if not final_username or not final_password:
|
|
||||||
raise RuntimeError("HR 用户名或密码未提供,请设置环境变量 hr_login_username / hr_login_password")
|
|
||||||
|
|
||||||
page = _create_page()
|
|
||||||
|
|
||||||
saved = load_cookies(COOKIE_FILE_HR)
|
|
||||||
if saved:
|
|
||||||
try:
|
|
||||||
page.set.cookies(saved)
|
|
||||||
page.get(HR_LOGIN_URL)
|
|
||||||
time.sleep(2)
|
|
||||||
if HR_SUCCESS_KEYWORD in page.url:
|
|
||||||
logger.info("已通过缓存的 HR Cookies 登录")
|
|
||||||
save_browser_cookies(page, COOKIE_FILE_HR)
|
|
||||||
page.quit()
|
|
||||||
return
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("复用 HR Cookies 失败:%s", e)
|
|
||||||
else:
|
|
||||||
page.get(HR_LOGIN_URL)
|
|
||||||
time.sleep(2)
|
|
||||||
|
|
||||||
if HR_SUCCESS_KEYWORD in page.url:
|
|
||||||
logger.info("HR 已登录")
|
|
||||||
save_browser_cookies(page, COOKIE_FILE_HR)
|
|
||||||
page.quit()
|
|
||||||
return
|
|
||||||
|
|
||||||
try:
|
|
||||||
account = page.ele(ACCOUNT_INPUT_HR)
|
|
||||||
if not account:
|
|
||||||
raise RuntimeError("找不到 HR 账号输入框")
|
|
||||||
account.clear(); account.input(final_username); time.sleep(0.5)
|
|
||||||
pwd = page.ele(PASSWORD_INPUT_HR)
|
|
||||||
if not pwd:
|
|
||||||
raise RuntimeError("找不到 HR 密码输入框")
|
|
||||||
pwd.clear(); pwd.input(final_password); time.sleep(0.5)
|
|
||||||
login_btn = page.ele(LOGIN_BTN)
|
|
||||||
if not login_btn:
|
|
||||||
raise RuntimeError("找不到登录按钮")
|
|
||||||
login_btn.click(); time.sleep(3)
|
|
||||||
|
|
||||||
if HR_SUCCESS_KEYWORD in page.url:
|
|
||||||
logger.info("HR 登录成功(无滑块)")
|
|
||||||
elif handle_hr_captcha(page):
|
|
||||||
logger.info("HR 登录成功(验证通过)")
|
|
||||||
else:
|
|
||||||
raise RuntimeError("HR 登录失败(滑块验证未通过)")
|
|
||||||
save_browser_cookies(page, COOKIE_FILE_HR)
|
|
||||||
finally:
|
|
||||||
try:
|
|
||||||
page.quit()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
# ==================== 花名册导出(浏览器自动化) ====================
|
|
||||||
def _click_text(page, text, timeout=10):
|
|
||||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
|
||||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
|
||||||
if not ele:
|
|
||||||
raise RuntimeError(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 RuntimeError(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 _inject_cookies_and_goto(page, max_retry=3):
|
|
||||||
"""注入 HR cookies 并访问花名册页,返回可用的 page。
|
|
||||||
|
|
||||||
处理两件事:
|
|
||||||
1. 断连恢复:登录函数(hr_login)登录后会自行关闭其浏览器;若与原 page 共享
|
|
||||||
同一浏览器实例,原 page 连接会断开(报「与页面的连接已断开」)。因此这里
|
|
||||||
不依赖旧 page,失败时关闭旧页面、重建新页面、重新注入 cookies 后再访问。
|
|
||||||
2. 仍需登录:cookies 不存在或失效时,访问会被重定向到登录页,此时仍会调用
|
|
||||||
hr_login() 完成登录,登录后再携带新 cookies 重新打开访问(最多重试 max_retry 次)。
|
|
||||||
"""
|
|
||||||
for attempt in range(1, max_retry + 1):
|
|
||||||
try:
|
|
||||||
cookies = load_cookies(COOKIE_FILE_HR)
|
|
||||||
logger.info("加载缓存 cookies:%d 个", len(cookies or []))
|
|
||||||
if cookies:
|
|
||||||
page.set.cookies(cookies)
|
|
||||||
page.get(ROSTER_URL)
|
|
||||||
time.sleep(WAIT_LONG)
|
|
||||||
# 登录页特征:存在用户名输入框
|
|
||||||
if page.ele('@id=j_username', timeout=2):
|
|
||||||
raise LoginRequiredError("HR 登录态已失效")
|
|
||||||
logger.info("已进入花名册页面:%s", page.url)
|
|
||||||
return page
|
|
||||||
except LoginRequiredError:
|
|
||||||
logger.info("HR 登录态已失效,执行重新登录")
|
|
||||||
hr_login()
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("访问花名册页失败(第 %d 次):%s", attempt, e)
|
|
||||||
# 关闭旧页面并重建(携带 cookies 重新打开访问)
|
|
||||||
try:
|
|
||||||
page.quit()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
page = _create_page()
|
|
||||||
raise RuntimeError(f"登录态/连接恢复失败,连续 {max_retry} 次未能进入花名册页面")
|
|
||||||
|
|
||||||
|
|
||||||
def _select_org_tree(page):
|
|
||||||
"""切换到组织树并选中「集团」。"""
|
|
||||||
# 步骤1:点击左侧「组织机构」,切换为组织树
|
|
||||||
org_tab = page.ele('css:.hrm-bd-left-title-org', timeout=15)
|
|
||||||
if org_tab:
|
|
||||||
org_tab.click()
|
|
||||||
logger.info("已点击左侧「组织机构」")
|
|
||||||
time.sleep(WAIT_MID)
|
|
||||||
else:
|
|
||||||
logger.warning("未找到「组织机构」tab,尝试直接按文本点击")
|
|
||||||
_click_text(page, TAB_ORG)
|
|
||||||
time.sleep(WAIT_MID)
|
|
||||||
|
|
||||||
# 步骤2:点击组织树根节点「集团」
|
|
||||||
group = page.ele('css:a[title="集团"]', timeout=15)
|
|
||||||
if not group:
|
|
||||||
group = page.ele(f'xpath://*[normalize-space(text())="集团"]', timeout=5)
|
|
||||||
if not group:
|
|
||||||
raise RuntimeError("组织树中未找到「集团」节点")
|
|
||||||
group.click()
|
|
||||||
logger.info("已点击组织树根节点「集团」")
|
|
||||||
time.sleep(WAIT_LONG)
|
|
||||||
|
|
||||||
|
|
||||||
def _ensure_person_status(page, status="在职"):
|
|
||||||
"""将「在职状态」筛选设置为仅选中指定状态(在职/离职)。
|
|
||||||
|
|
||||||
注意:该筛选为多选下拉(在职/离职/退休/返聘),需要取消其它已选项,
|
|
||||||
仅保留目标状态,避免导出时把多个状态混在一起。
|
|
||||||
"""
|
|
||||||
container = page.ele('css:div[component-div*="person_status"]', timeout=15)
|
|
||||||
if not container:
|
|
||||||
raise RuntimeError("未找到「在职状态」筛选控件")
|
|
||||||
select = container.ele('css:.el-select', timeout=5)
|
|
||||||
if not select:
|
|
||||||
raise RuntimeError("未找到「在职状态」下拉框")
|
|
||||||
|
|
||||||
# 打开下拉,等待可见面板出现(下拉关闭时选项仍在 DOM 但不可见,必须取可见面板内的选项)
|
|
||||||
select.click()
|
|
||||||
time.sleep(WAIT_SHORT)
|
|
||||||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=5)
|
|
||||||
if not panel:
|
|
||||||
select.click()
|
|
||||||
time.sleep(WAIT_SHORT)
|
|
||||||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=5)
|
|
||||||
if not panel:
|
|
||||||
raise RuntimeError("在职状态下拉面板未能展开")
|
|
||||||
|
|
||||||
items = panel.eles('css:li.el-select-dropdown__item')
|
|
||||||
if not items:
|
|
||||||
raise RuntimeError("在职状态下拉中没有选项")
|
|
||||||
|
|
||||||
# 文本 -> 选项元素
|
|
||||||
opt_map = {}
|
|
||||||
for it in items:
|
|
||||||
txt = (it.text or "").strip()
|
|
||||||
if txt:
|
|
||||||
opt_map[txt] = it
|
|
||||||
if status not in opt_map:
|
|
||||||
raise RuntimeError(f"在职状态下拉中不存在选项:{status}")
|
|
||||||
|
|
||||||
# 仅保留目标状态选中,其余取消选中
|
|
||||||
for txt, it in opt_map.items():
|
|
||||||
is_selected = "selected" in (it.attr('class') or "")
|
|
||||||
need = (txt == status)
|
|
||||||
if is_selected != need:
|
|
||||||
logger.info("在职状态选项「%s」%s", txt, "选中" if need else "取消选中")
|
|
||||||
it.click()
|
|
||||||
time.sleep(0.2)
|
|
||||||
|
|
||||||
# 关闭下拉(再次点击外壳切换收起)
|
|
||||||
try:
|
|
||||||
select.click()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
time.sleep(WAIT_SHORT)
|
|
||||||
logger.info("在职状态已设为仅「%s」", status)
|
|
||||||
|
|
||||||
|
|
||||||
def _open_custom_export_dialog(page):
|
|
||||||
"""点击「更多操作」->「自定义导出」,打开导出弹窗(幂等,已打开则跳过)。"""
|
|
||||||
# 若导出弹窗已打开(存在「模板」下拉),直接返回
|
|
||||||
tpl_label = page.ele(
|
|
||||||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]', timeout=2)
|
|
||||||
if tpl_label and _is_displayed(tpl_label):
|
|
||||||
logger.info("导出弹窗已打开,跳过「更多操作」")
|
|
||||||
time.sleep(WAIT_MID)
|
|
||||||
return
|
|
||||||
|
|
||||||
# 步骤3:点击「更多操作」按钮
|
|
||||||
more_btn = page.ele('css:button.btn-success.dropdown-toggle', timeout=15)
|
|
||||||
if more_btn:
|
|
||||||
more_btn.click()
|
|
||||||
else:
|
|
||||||
_click_text(page, BTN_MORE)
|
|
||||||
logger.info("已点击「更多操作」")
|
|
||||||
time.sleep(WAIT_SHORT)
|
|
||||||
|
|
||||||
# 步骤4:点击「自定义导出」
|
|
||||||
menu = page.ele('css:#custom-btn-ul', timeout=5)
|
|
||||||
if menu:
|
|
||||||
_click_text_in(page, menu, MENU_CUSTOM_EXPORT)
|
|
||||||
else:
|
|
||||||
_click_text(page, MENU_CUSTOM_EXPORT)
|
|
||||||
time.sleep(WAIT_MID)
|
|
||||||
|
|
||||||
|
|
||||||
def _select_template(page, template_name):
|
|
||||||
"""在导出弹窗中选择自定义导出模板。"""
|
|
||||||
# 步骤5:定位「模板」下拉框容器(含「模板」前置标签的 el-select)
|
|
||||||
tpl = page.ele(
|
|
||||||
'xpath://div[contains(@class,"el-input-group__prepend") and normalize-space(.)="模板"]'
|
|
||||||
'/following-sibling::div[contains(@class,"el-select")]',
|
|
||||||
timeout=15,
|
|
||||||
)
|
|
||||||
if not tpl:
|
|
||||||
raise RuntimeError("未找到「模板」下拉框")
|
|
||||||
|
|
||||||
# 确保下拉面板已展开(下拉面板会 teleport 到 body,需在页面级查找可见面板)
|
|
||||||
panel = None
|
|
||||||
for _ in range(3):
|
|
||||||
panel = page.ele('css:.el-select-dropdown:not([style*="display: none"])', timeout=2)
|
|
||||||
if panel and _is_displayed(panel):
|
|
||||||
break
|
|
||||||
tpl.click()
|
|
||||||
time.sleep(WAIT_SHORT)
|
|
||||||
if not panel:
|
|
||||||
raise RuntimeError("模板下拉面板未能展开")
|
|
||||||
|
|
||||||
# 步骤6:在可见面板中选择模板(如「雇主险增减员导出模板」)
|
|
||||||
opt = panel.ele(
|
|
||||||
f'xpath:.//li[contains(@class,"el-select-dropdown__item") and normalize-space(.)="{template_name}"]',
|
|
||||||
timeout=5,
|
|
||||||
)
|
|
||||||
if not opt:
|
|
||||||
raise RuntimeError(f"模板下拉中未找到:{template_name}")
|
|
||||||
opt.click()
|
|
||||||
logger.info("已选择模板:%s", template_name)
|
|
||||||
time.sleep(WAIT_SHORT)
|
|
||||||
|
|
||||||
|
|
||||||
def _click_confirm_export(page):
|
|
||||||
"""点击「确认导出」,触发下载。"""
|
|
||||||
btn = page.ele(f'xpath://button[contains(@class,"el-button--primary") and normalize-space(.)="{BTN_CONFIRM}"]',
|
|
||||||
timeout=10)
|
|
||||||
if not btn:
|
|
||||||
raise RuntimeError(f"未找到「{BTN_CONFIRM}」按钮")
|
|
||||||
btn.click()
|
|
||||||
logger.info("已点击「确认导出」")
|
|
||||||
time.sleep(WAIT_SHORT)
|
|
||||||
|
|
||||||
|
|
||||||
def _wait_download(page, download_dir, timeout=DOWNLOAD_FINISH_TIMEOUT):
|
|
||||||
"""等待下载文件生成并大小稳定,返回下载文件路径。
|
|
||||||
|
|
||||||
采用文件系统轮询:统计下载目录中新增的、非临时文件,当其大小两次采样一致
|
|
||||||
视为下载完成。避免依赖 DrissionPage 下载任务状态(可能卡在 100% 不结束)。
|
|
||||||
"""
|
|
||||||
logger.info("等待下载文件生成(最多 %ds)...", timeout)
|
|
||||||
before = set(os.listdir(download_dir))
|
|
||||||
deadline = time.time() + timeout
|
|
||||||
last_sizes = {}
|
|
||||||
while time.time() < deadline:
|
|
||||||
try:
|
|
||||||
files = os.listdir(download_dir)
|
|
||||||
except Exception:
|
|
||||||
files = []
|
|
||||||
for f in files:
|
|
||||||
if f in before or f.endswith(('.crdownload', '.tmp', '.part', '.download')):
|
|
||||||
continue
|
|
||||||
p = os.path.join(download_dir, f)
|
|
||||||
if not os.path.isfile(p):
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
size = os.path.getsize(p)
|
|
||||||
except Exception:
|
|
||||||
continue
|
|
||||||
if size <= 0:
|
|
||||||
continue
|
|
||||||
if last_sizes.get(p) == size:
|
|
||||||
logger.info("花名册导出文件已下载:%s(%.2f KB)", p, size / 1024.0)
|
|
||||||
return p
|
|
||||||
last_sizes[p] = size
|
|
||||||
time.sleep(1.0)
|
|
||||||
raise RuntimeError(f"等待下载文件超时({timeout}s 内未检测到稳定文件)")
|
|
||||||
|
|
||||||
|
|
||||||
# ==================== 统一格式合并(与 app 版 roster_export._merge_roster_files 一致) ====================
|
|
||||||
def _normalize_and_save(files_with_status, output_path):
|
|
||||||
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态。
|
|
||||||
|
|
||||||
统一输出格式(后续筛选复制按此规范读取):
|
|
||||||
- 只保留第2行表头,丢弃第1行标题(源表第1行为模板名标题)
|
|
||||||
- 「类型」列统一追加在最后一列,标识在职状态
|
|
||||||
- 单 sheet,表头在第1行,数据第2行起
|
|
||||||
|
|
||||||
Args:
|
|
||||||
files_with_status: [(status, file_path), ...] 列表
|
|
||||||
output_path: 合并后文件保存路径
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
合并后文件路径
|
|
||||||
"""
|
|
||||||
dfs = []
|
|
||||||
for status, path in files_with_status:
|
|
||||||
df = pd.read_excel(path, header=1) # 取第2行作表头,丢弃第1行标题
|
|
||||||
df["类型"] = status # 类型列统一追加到最后一列
|
|
||||||
dfs.append(df)
|
|
||||||
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
|
|
||||||
merged = pd.concat(dfs, ignore_index=True)
|
|
||||||
|
|
||||||
_ensure_dir(os.path.dirname(output_path))
|
|
||||||
merged.to_excel(output_path, index=False)
|
|
||||||
logger.info("合并完成,共 %d 行,已保存:%s", len(merged), output_path)
|
|
||||||
|
|
||||||
# 删除临时下载的单个文件
|
|
||||||
for _, path in files_with_status:
|
|
||||||
try:
|
|
||||||
os.remove(path)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return output_path
|
|
||||||
|
|
||||||
|
|
||||||
# ==================== 导出入口 ====================
|
|
||||||
@retry(max_attempts=3)
|
|
||||||
def _export_one_status(page, status, download_dir, template_name):
|
|
||||||
"""导出单个在职状态的花名册(设置筛选 -> 自定义导出 -> 下载),失败自动重试。"""
|
|
||||||
logger.info(">>> 开始导出在职状态:%s(模板:%s)", status, template_name)
|
|
||||||
try:
|
|
||||||
_ensure_person_status(page, status)
|
|
||||||
_open_custom_export_dialog(page)
|
|
||||||
_select_template(page, template_name)
|
|
||||||
_click_confirm_export(page)
|
|
||||||
logger.info(">>> 等待在职状态「%s」的导出文件下载", status)
|
|
||||||
path = _wait_download(page, download_dir)
|
|
||||||
logger.info(">>> 在职状态「%s」导出完成", status)
|
|
||||||
return path
|
|
||||||
except Exception:
|
|
||||||
logger.exception("导出在职状态「%s」失败,详细堆栈如下:", status)
|
|
||||||
raise
|
|
||||||
|
|
||||||
|
|
||||||
def export_roster(download_dir=None, template_name=None, output_path=None, statuses=None):
|
|
||||||
"""执行雇主险花名册自定义导出,按统一格式保存为源表。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
download_dir: 浏览器下载临时目录,默认 D:\\资料\\人资\\员工花名册
|
|
||||||
template_name: 自定义导出模板名,默认「雇主险增减员导出模板」
|
|
||||||
output_path: 合并后文件的保存路径,默认 D:\\资料\\人资\\雇主险\\员工花名册.xlsx
|
|
||||||
statuses: 需要导出的在职状态列表,默认仅 ["在职"](雇主险增减员只需在职人员)
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
合并后的花名册文件路径。
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
RuntimeError: 任何流程步骤失败或下载未检测到时抛出。
|
|
||||||
"""
|
|
||||||
download_dir = os.path.abspath(download_dir or DEFAULT_DOWNLOAD_DIR)
|
|
||||||
template_name = template_name or DEFAULT_TEMPLATE
|
|
||||||
statuses = list(statuses) if statuses else list(DEFAULT_STATUSES)
|
|
||||||
output_path = os.path.abspath(output_path or DEFAULT_OUTPUT_PATH)
|
|
||||||
_ensure_dir(download_dir)
|
|
||||||
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s),下载目录:%s =====",
|
|
||||||
template_name, statuses, download_dir)
|
|
||||||
|
|
||||||
page = _create_page()
|
|
||||||
logger.info("浏览器已启动")
|
|
||||||
try:
|
|
||||||
# 注入缓存 cookies 并进入花名册页
|
|
||||||
# (连接断开自动重建页面;cookies 失效则重新登录后再访问,见 _inject_cookies_and_goto)
|
|
||||||
page = _inject_cookies_and_goto(page)
|
|
||||||
_select_org_tree(page)
|
|
||||||
|
|
||||||
# 下载目录设置需在触发下载前完成
|
|
||||||
page.set.download_path(download_dir)
|
|
||||||
logger.info("浏览器下载目录已设置:%s", download_dir)
|
|
||||||
|
|
||||||
files_with_status = []
|
|
||||||
for status in statuses:
|
|
||||||
logger.info("===== 开始导出在职状态:%s =====", status)
|
|
||||||
path = _export_one_status(page, status, download_dir, template_name)
|
|
||||||
files_with_status.append((status, path))
|
|
||||||
time.sleep(WAIT_MID)
|
|
||||||
|
|
||||||
# 合并所有花名册文件,输出统一格式源表
|
|
||||||
result = _normalize_and_save(files_with_status, output_path)
|
|
||||||
logger.info("===== 花名册导出并合并完成:%s =====", result)
|
|
||||||
return result
|
|
||||||
finally:
|
|
||||||
try:
|
|
||||||
page.quit()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
# ==================== 主入口 ====================
|
|
||||||
def main():
|
|
||||||
load_dotenv()
|
|
||||||
try:
|
|
||||||
out = export_roster(
|
|
||||||
download_dir=os.getenv("roster_download_dir"),
|
|
||||||
template_name=os.getenv("roster_template"),
|
|
||||||
output_path=os.getenv("roster_output_path"),
|
|
||||||
statuses=[s.strip() for s in os.getenv("roster_statuses", "").split(",") if s.strip()] or None,
|
|
||||||
)
|
|
||||||
logger.info("===== 花名册导出完成:%s =====", out)
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("花名册导出失败:%s", e)
|
|
||||||
raise
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||||
- 源表读取(pandas):自动定位表头行(B 列=「所属单位」),业务列 B~O 共14列;
|
- 源表读取(pandas):自动定位表头行(B 列=「所属单位」),业务列 B~O 共14列;
|
||||||
目标表写入(openpyxl):覆盖写入 + 清空超出的旧行。
|
目标表写入(openpyxl):覆盖写入 + 清空超出的旧行。
|
||||||
- 源表缺失时默认懒加载同目录 roster_export 自动导出(开关见下方环境变量)。
|
- 源表缺失时默认懒加载共享「37du花名册导出」模块(share/roster_export.py)自动导出(开关见下方环境变量)。
|
||||||
|
|
||||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||||
pip install pandas openpyxl
|
pip install pandas openpyxl
|
||||||
@@ -23,14 +23,13 @@
|
|||||||
roster_filter_export_on_missing = true|false 源表缺失时是否自动导出(默认 true)
|
roster_filter_export_on_missing = true|false 源表缺失时是否自动导出(默认 true)
|
||||||
|
|
||||||
运行:直接执行本文件即可完成全部类别筛选复制;仅处理单个类别时以函数传参调用
|
运行:直接执行本文件即可完成全部类别筛选复制;仅处理单个类别时以函数传参调用
|
||||||
main(category_name='湖畔酒店') 或 filter_and_copy_roster(category)
|
main(category_names=['湖畔酒店']) 或 filter_and_copy_roster(category)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# ==================== 标准库导入 ====================
|
# ==================== 标准库导入 ====================
|
||||||
import numbers
|
import numbers
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import sys
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||||
@@ -188,12 +187,13 @@ def find_latest_target(folder):
|
|||||||
# 过滤规则(与 aa.md 宏一致)
|
# 过滤规则(与 aa.md 宏一致)
|
||||||
EXCLUDE_REGION = "虚拟大区" # 统一排除的一级部门(各类别均生效)
|
EXCLUDE_REGION = "虚拟大区" # 统一排除的一级部门(各类别均生效)
|
||||||
|
|
||||||
# 源表/目标表格式规范(roster_export 输出统一格式)
|
# 源表/目标表格式规范(共享「37du花名册导出」输出统一格式)
|
||||||
SOURCE_HEADER_MARK = "所属单位" # 源表表头定位标记(B列)
|
SOURCE_HEADER_MARK = "所属单位" # 源表表头定位标记(B列)
|
||||||
|
EXPORT_TEMPLATE = "雇主险增减员导出模板" # 雇主险源表使用的自定义导出模板
|
||||||
TARGET_HEADER_ROW = 4 # 目标表表头在第4行(数据第5行起)
|
TARGET_HEADER_ROW = 4 # 目标表表头在第4行(数据第5行起)
|
||||||
DATA_COLUMNS = 14 # B~O 共14列(所属单位..证件号)
|
DATA_COLUMNS = 14 # B~O 共14列(所属单位..证件号)
|
||||||
|
|
||||||
# 源表缺失时是否自动调用 roster_export 导出(默认 true)
|
# 源表缺失时是否自动调用共享导出模块(默认 true)
|
||||||
AUTO_EXPORT_ON_MISSING = os.getenv("roster_filter_export_on_missing", "true").lower() == "true"
|
AUTO_EXPORT_ON_MISSING = os.getenv("roster_filter_export_on_missing", "true").lower() == "true"
|
||||||
|
|
||||||
# F列 工号(必须文本格式,否则与「手动维护-在参名单」B列及表内公式匹配失败)
|
# F列 工号(必须文本格式,否则与「手动维护-在参名单」B列及表内公式匹配失败)
|
||||||
@@ -319,29 +319,42 @@ def filter_and_copy_roster(category: dict, employee_file: str = None, target_fil
|
|||||||
|
|
||||||
|
|
||||||
def _export_roster():
|
def _export_roster():
|
||||||
"""源表缺失时,懒加载同目录 roster_export 导出花名册到源表路径。"""
|
"""源表缺失时,懒加载共享「37du花名册导出」模块(share/roster_export.py)导出雇主险源表。
|
||||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
||||||
|
登录态复用「37duHR登录」指令写入的共享 hr_cookies.json(共享模块只读不补登)。
|
||||||
|
"""
|
||||||
|
import importlib.util
|
||||||
|
share_script = os.path.join(
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
||||||
|
"share", "roster_export.py")
|
||||||
try:
|
try:
|
||||||
from roster_export import export_roster
|
spec = importlib.util.spec_from_file_location("share_roster_export", share_script)
|
||||||
except ImportError as e:
|
mod = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(mod)
|
||||||
|
except Exception as e:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
f"源表缺失且无法加载导出模块 roster_export({e}),"
|
f"源表缺失且无法加载共享导出模块 share/roster_export.py({e}),"
|
||||||
f"请先运行 roster_export.py 导出花名册到 {EMPLOYEE_FILE}") from e
|
f"请先运行「37du花名册导出」指令导出花名册到 {EMPLOYEE_FILE}") from e
|
||||||
output = export_roster(output_path=EMPLOYEE_FILE)
|
output = mod.export_roster(
|
||||||
|
template_name=EXPORT_TEMPLATE,
|
||||||
|
statuses=["在职"],
|
||||||
|
output_path=EMPLOYEE_FILE,
|
||||||
|
)
|
||||||
logger.info("花名册导出完成:%s", output)
|
logger.info("花名册导出完成:%s", output)
|
||||||
|
|
||||||
|
|
||||||
def main(category_name: str = None) -> None:
|
def main(category_names: list[str] = None) -> None:
|
||||||
"""第二步:文件存在性校验 + 类别筛选复制(源表缺失时自动导出)。
|
"""第二步:文件存在性校验 + 类别筛选复制(源表缺失时自动导出)。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
category_name: 类别名(如「湖畔酒店」/「湖畔」),None 表示处理全部类别。
|
category_names: 类别名列表(如 ["三十七度", "湖畔酒店"]),
|
||||||
|
空列表 / None 表示处理全部类别。
|
||||||
|
|
||||||
说明:openpyxl 写入后公式列(P~W 工种类别/投保方案/方案处理)的缓存结果会丢失,
|
说明:openpyxl 写入后公式列(P~W 工种类别/投保方案/方案处理)的缓存结果会丢失,
|
||||||
需手动打开各目标文件刷新公式计算结果并保存,确认复制无误后再运行 schedule 步骤
|
需手动打开各目标文件刷新公式计算结果并保存,确认复制无误后再运行 schedule 步骤
|
||||||
(employer_insurance_schedule.py)。
|
(employer_insurance_schedule.py)。
|
||||||
"""
|
"""
|
||||||
categories = [get_category(category_name)] if category_name else CATEGORIES
|
categories = [get_category(n) for n in category_names] if category_names else CATEGORIES
|
||||||
|
|
||||||
# 源表(员工花名册)缺失才自动导出
|
# 源表(员工花名册)缺失才自动导出
|
||||||
if not os.path.exists(EMPLOYEE_FILE):
|
if not os.path.exists(EMPLOYEE_FILE):
|
||||||
@@ -378,4 +391,4 @@ def main(category_name: str = None) -> None:
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main(category_name='三十七度')
|
main(category_names=["三十七度"])
|
||||||
|
|||||||
Reference in New Issue
Block a user