feat(share/): add 37du花名册导出共享指令,重构原有内联导出逻辑
1. 新增share/roster_export.py共享指令,实现标准化花名册自定义导出 2. 统一读取HR共享登录态,支持在职/离职筛选、离职时间范围、自定义模板 3. 规范输出格式:单sheet、第2行作为表头、追加「类型」列到末尾 4. 更新README文档,补充指令说明、调用方式和路径配置 5. 重构原有employer_insurance/roster_export.py为雇主险专属导出逻辑
This commit is contained in:
+21
-4
@@ -18,6 +18,7 @@ yingdao/
|
||||
├── share/ # 共享指令模块(单一真源,注册为影刀自定义指令,各自独立运行)
|
||||
│ ├── oa_login.py # 「37duOA登录」OA 登录
|
||||
│ ├── hr_login.py # 「37duHR登录」HR 登录(滑块验证码)
|
||||
│ ├── roster_export.py # 「37du花名册导出」花名册自定义导出(在职/离职+离职时间+模板名)
|
||||
│ ├── dingtalk_robot.py # 「37du钉钉群机器人推送」webhook 群推送
|
||||
│ └── dingtalk_sender.py # 「37du钉钉推送」OCR 联系人单聊 + 群消息自动路由
|
||||
├── oa/ # OA 系统业务脚本(单文件自包含)
|
||||
@@ -26,11 +27,11 @@ yingdao/
|
||||
├── hr/ # HR 系统业务脚本(单文件自包含)
|
||||
│ ├── attendance_abnormal.py # 考勤异常
|
||||
│ ├── attendance_abnormal_monthly.py # 考勤异常月度
|
||||
│ ├── absence_analysis.py # 缺勤分析
|
||||
│ ├── absence_analysis.py # 缺勤分析(读「37du花名册导出」指令输出的固定路径文件)
|
||||
│ ├── bank_card_check.py # 银行卡检查
|
||||
│ └── social_change.py # 人事变动
|
||||
├── employer_insurance/ # 雇主险类业务脚本(单文件自包含)
|
||||
│ ├── roster_export.py # 花名册导出(第一步)
|
||||
│ ├── roster_export.py # 雇主险花名册导出(内含 HR 登录,输出雇主险源表)
|
||||
│ ├── roster_filter.py # 筛选复制(第二步)
|
||||
│ └── employer_insurance_schedule.py # 名额调度(第三步)
|
||||
└── README.md # 本文档
|
||||
@@ -47,6 +48,7 @@ yingdao/
|
||||
| 共享配置 | `%LOCALAPPDATA%\37duAutomation\.env`(本地开发兼容当前工作目录 `.env`) |
|
||||
| OA 登录态 | `%LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json` |
|
||||
| HR 登录态 | `%LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json` |
|
||||
| 花名册文件(「37du花名册导出」指令输出) | `D:\资料\人资\花名册\花名册.xlsx` |
|
||||
|
||||
## 4. 共享指令模块(share/,各自独立运行)
|
||||
|
||||
@@ -65,7 +67,22 @@ yingdao/
|
||||
- 入口:`main(args)`;写 `hr_cookies.json`;流程全局变量 `login_state`
|
||||
- 依赖:`DrissionPage requests python-dotenv opencv-python numpy Pillow`
|
||||
|
||||
### 4.3 dingtalk_robot.py(「37du钉钉群机器人推送」)
|
||||
### 4.3 roster_export.py(「37du花名册导出」)
|
||||
|
||||
- 花名册自定义导出共享指令:进入花名册页 → 组织机构(集团) → 按需在职状态(在职/离职)→ 离职可设时间范围 → 更多操作 → 自定义导出 → 选模板 → 下载并按统一格式合并(单 sheet、第2行表头、「类型」列在最后一列)
|
||||
- 入口:`main(statuses, leave_start, leave_end, template, output_path, download_dir)`(关键字参数)、`export_roster(download_dir, output_path, template_name, statuses, leave_start, leave_end)`
|
||||
- `statuses`:在职状态,`"在职"` / `"离职"` / `"在职,离职"` 或 list(默认 在职+离职)
|
||||
- `leave_start` / `leave_end`:离职时间范围 `"YYYY-MM-DD"`(离职状态时生效;不传默认 上月1日到今天)
|
||||
- `template`:自定义导出模板名(默认 员工基础信息)
|
||||
- **不读环境变量**:默认值全部内置(`DEFAULT_TEMPLATE`/`DEFAULT_STATUSES`/`DEFAULT_OUTPUT_PATH`/`DEFAULT_DOWNLOAD_DIR`),便于分发共享;需要变更时直接改常量或由 `main(...)` 传参
|
||||
- 登录态直接读取「37duHR登录」写出的 `hr_cookies.json`;缺失/失效时提示先运行「37duHR登录」指令(不自动补登)
|
||||
- **返回值**:`main` 返回 `{"success", "save_path", ...}`(`save_path` 即调用方传入的 `output_path` 合并文件路径);保存路径由调用方传入,不写全局变量
|
||||
- **调用方式(不懒加载)**:影刀指令是拖拽进流程的独立单元,脚本内按文件路径 importlib 加载共享模块在运行时不可行。因此业务脚本(如 `absence_analysis`)**不 import、不懒加载**本模块,而是:
|
||||
1. 流程中先拖入「37du花名册导出」指令(在指令上配置 在职状态/离职时间/模板名),导出花名册到固定路径;
|
||||
2. 业务脚本只读取该固定路径文件(`roster_path` 参数或 `absence_roster_path` 环境变量,默认 `D:\资料\人资\花名册\花名册.xlsx`)
|
||||
- 依赖:`DrissionPage pandas openpyxl`
|
||||
|
||||
### 4.4 dingtalk_robot.py(「37du钉钉群机器人推送」)
|
||||
|
||||
- 入口:`main(text, title='消息通知', status='info', webhook='', secret='', server_name='', env='prod')`
|
||||
- `text` 必传,支持纯文本或**文本列表**(列表则逐条发送,项可为纯文本或 `{text, title?, status?}` 字典自定义标题/颜色);返回 `{"success": bool, "message": str}`
|
||||
@@ -73,7 +90,7 @@ yingdao/
|
||||
- `env='dev'` 走测试环境机器人(`DEV_WEBHOOK`/`DEV_SECRET`),默认 `prod`
|
||||
- 零第三方依赖(仅标准库)
|
||||
|
||||
### 4.4 dingtalk_sender.py(「37du钉钉推送」)
|
||||
### 4.5 dingtalk_sender.py(「37du钉钉推送」)
|
||||
|
||||
- 入口:`main(args)`,`args` 支持两种方式:
|
||||
- **方式A(批量,推荐)**:`{"messages": [{target?, text, display_name?}, ...]}` 逐条发送,返回 `{success, message, sent, failed, results}`
|
||||
|
||||
+545
-832
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,630 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: roster_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-22
|
||||
@Description: 员工花名册导出(影刀共享指令,单文件自包含)——从共享登录态读取 HR cookies,
|
||||
进入花名册页 -> 组织机构(集团) -> 按需在职状态(在职/离职)-> 离职可设时间范围
|
||||
-> 更多操作 -> 自定义导出 -> 选择模板 -> 确认导出 -> 下载并按统一格式合并保存。
|
||||
供各业务脚本(请休假异常、雇主险等)复用,替代原先各自内联的浏览器自动化代码。
|
||||
@Version: 1.0.0
|
||||
|
||||
场景定位(共享指令,影刀流程中独立运行;业务脚本也可懒加载调用):
|
||||
- 登录态统一由「37duHR登录」指令写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json;
|
||||
本指令仅读取该 cookies 文件,失效时抛出提示引导先重新登录。
|
||||
- 输出统一规范:单 sheet、只保留第2行表头(丢弃第1行标题)、「类型」列统一追加在最后一列
|
||||
(与 app 版 roster_export 输出一致,各业务场景读取端按此规范读取)。
|
||||
|
||||
运行方式:
|
||||
1. 影刀:注册为自定义指令「37du花名册导出」,main(...) 关键字传参(缺省用内置默认值,见 DEFAULT_* 常量)
|
||||
statuses 在职状态,如 "在职" / "离职" / ["在职","离职"](默认 在职+离职)
|
||||
leave_start 离职时间开始 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
leave_end 离职时间结束 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
template 自定义导出模板名(默认 员工基础信息)
|
||||
output_path 合并后保存路径(默认 D:\\资料\\人资\\花名册\\花名册.xlsx)
|
||||
download_dir 浏览器下载临时目录(默认 D:\\资料\\人资\\花名册\\download)
|
||||
2. 命令行:python roster_export.py 直接运行(__main__ 中按示例传参)
|
||||
3. 业务脚本:懒加载本模块调用 export_roster(...)
|
||||
|
||||
依赖安装(启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage requests pandas openpyxl
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(共享指令要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install DrissionPage requests pandas openpyxl\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(影刀版共享目录)
|
||||
_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')
|
||||
|
||||
# ---------- 花名册自定义导出页面(与 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"
|
||||
)
|
||||
|
||||
# ---------- 默认导出参数(内置默认值,便于分发共享;如需覆盖请直接改这里或由 main(args) 传参) ----------
|
||||
DEFAULT_TEMPLATE = "员工基础信息"
|
||||
DEFAULT_STATUSES = ["在职", "离职"]
|
||||
DEFAULT_OUTPUT_PATH = r"D:\资料\人资\花名册\花名册.xlsx"
|
||||
DEFAULT_DOWNLOAD_DIR = r"D:\资料\人资\花名册\download"
|
||||
|
||||
# ---------- 流程步骤文案(与 app 版 roster_export 一致) ----------
|
||||
TAB_ORG = "组织机构" # 左侧「组织机构」tab,切换为组织树
|
||||
TREE_GROUP = "集团" # 组织树根节点
|
||||
BTN_MORE = "更多操作" # 更多操作按钮
|
||||
MENU_CUSTOM_EXPORT = "自定义导出"
|
||||
TEMPLATE_PLACEHOLDER = "请选择模板"
|
||||
BTN_CONFIRM = "确认导出"
|
||||
LEAVE_RANGE_PLACEHOLDER = "请选择离职时间"
|
||||
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 # 等待下载完成
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
# ==================== 花名册导出(浏览器自动化,与 app 版 roster_export 一致) ====================
|
||||
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 _get_leave_range(today=None):
|
||||
"""计算离职筛选时间范围:默认上月 1 日到今天(离职时间不传时使用)。"""
|
||||
today = today or date.today()
|
||||
last_month_end = today.replace(day=1) - timedelta(days=1)
|
||||
start = last_month_end.replace(day=1)
|
||||
return start.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _inject_cookies_and_goto(page):
|
||||
"""注入共享 HR cookies 并访问花名册页,返回可用的 page。
|
||||
|
||||
登录态直接读取共享 cookies 文件(由「37duHR登录」指令写入),不自动补登;
|
||||
缺失/失效被重定向到登录页时,抛出明确提示引导先重新调用「37duHR登录」指令。
|
||||
"""
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
logger.info("加载缓存 cookies:%d 个", len(cookies))
|
||||
page.set.cookies(cookies)
|
||||
page.get(ROSTER_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
# 登录页特征:存在用户名输入框
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise LoginRequiredError(
|
||||
"HR 登录态已失效,请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
logger.info("已进入花名册页面:%s", page.url)
|
||||
return page
|
||||
|
||||
|
||||
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_more_search(page):
|
||||
"""确保「更多搜索」popover 已展开,返回是否成功。
|
||||
|
||||
通过按钮的 aria-describedby 属性找到 popover 内容元素,检查其是否可见来判断展开状态。
|
||||
按钮特征:class 含 search-more-condition-btn / el-popover__reference,外层容器 demo-search-more。
|
||||
"""
|
||||
btn = page.ele('css:button.search-more-condition-btn', timeout=3)
|
||||
if not btn:
|
||||
btn = page.ele('css:.demo-search-more .el-popover__reference', timeout=2)
|
||||
if not btn:
|
||||
btn = page.ele('xpath://button[.//span[contains(normalize-space(.),"更多搜索")]]', timeout=2)
|
||||
if not btn:
|
||||
logger.warning("未找到「更多搜索」按钮")
|
||||
return False
|
||||
|
||||
for _ in range(3):
|
||||
# 通过 aria-describedby 找到 popover 元素,检查是否可见
|
||||
popover_id = btn.attr('aria-describedby')
|
||||
if popover_id:
|
||||
popover = page.ele(f'css:#{popover_id}', timeout=2)
|
||||
if popover and _is_displayed(popover):
|
||||
logger.info("更多搜索已展开(popover #%s 可见)", popover_id)
|
||||
return True
|
||||
# 兜底:检查是否有可见的「筛选」按钮
|
||||
fb = page.ele(FILTER_XPATH, timeout=2)
|
||||
if fb and _is_displayed(fb):
|
||||
logger.info("更多搜索已展开(检测到可见的「筛选」按钮)")
|
||||
return True
|
||||
# 用 JS 直接 click() 触发 Element UI popover(纯选择器,避免传参问题)
|
||||
page.run_js(
|
||||
'var b=document.querySelector("button.search-more-condition-btn");'
|
||||
'if(b){b.click();}'
|
||||
)
|
||||
time.sleep(WAIT_MID)
|
||||
logger.warning("「更多搜索」未能展开")
|
||||
return False
|
||||
|
||||
|
||||
def _click_filter(page):
|
||||
"""点击更多搜索弹层底部的「筛选」按钮,应用离职时间等筛选条件。
|
||||
|
||||
全部在 JS 中完成:定位 popover -> 在 popover 内部找文本为「筛选」的按钮 -> 直接 .click()。
|
||||
"""
|
||||
result = page.run_js(
|
||||
'var b=document.querySelector("button.search-more-condition-btn");'
|
||||
'if(!b){return "no_btn_more";}'
|
||||
'var id=b.getAttribute("aria-describedby");'
|
||||
'if(!id){return "no_id";}'
|
||||
'var pop=document.getElementById(id);'
|
||||
'if(!pop){return "no_popover:"+id;}'
|
||||
'var btns=pop.querySelectorAll("button");'
|
||||
'for(var i=0;i<btns.length;i++){'
|
||||
' var t=(btns[i].textContent||"").replace(/\\s/g,"");'
|
||||
' if(t==="筛选"){btns[i].click();return "clicked";}'
|
||||
'}'
|
||||
'return "no_filter_btn:"+id;'
|
||||
)
|
||||
if result != "clicked":
|
||||
raise RuntimeError(f"点击「筛选」失败:{result}")
|
||||
logger.info("已点击「筛选」(JS click)")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _set_leave_date_range(page, leave_start=None, leave_end=None):
|
||||
"""设置「离职时间」筛选范围并应用。缺省日期自动计算(_get_leave_range)。"""
|
||||
if not leave_start or not leave_end:
|
||||
leave_start, leave_end = _get_leave_range()
|
||||
|
||||
if not _open_more_search(page):
|
||||
raise RuntimeError("「更多搜索」未能展开,无法设置离职时间")
|
||||
logger.info("设置离职时间范围:%s ~ %s", leave_start, leave_end)
|
||||
rng = page.ele(f'css:div.split-datetime-range[placeholder="{LEAVE_RANGE_PLACEHOLDER}"]', timeout=10)
|
||||
if not rng or not _is_displayed(rng):
|
||||
raise RuntimeError("未找到可见的「离职时间」选择器")
|
||||
start_input = rng.ele('css:input[placeholder="开始时间"]', timeout=5)
|
||||
end_input = rng.ele('css:input[placeholder="结束时间"]', timeout=5)
|
||||
if not start_input or not end_input:
|
||||
raise RuntimeError("未找到离职时间起止输入框")
|
||||
# 填入日期后按回车确认(input() 无 enter 参数,用 Actions 补回车)
|
||||
start_input.input(leave_start, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
end_input.input(leave_end, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
logger.info("离职时间已设置:%s ~ %s", leave_start, leave_end)
|
||||
|
||||
_click_filter(page)
|
||||
|
||||
|
||||
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=DEFAULT_TEMPLATE):
|
||||
"""在导出弹窗中选择自定义导出模板。"""
|
||||
# 步骤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 内未检测到稳定文件)")
|
||||
|
||||
|
||||
def _normalize_and_save(files_with_status, output_path):
|
||||
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态。
|
||||
|
||||
统一输出格式(各业务场景读取端按此规范读取):
|
||||
- 只保留第2行表头,丢弃第1行标题(源表第1行为模板名标题)
|
||||
- 「类型」列统一追加在最后一列,标识在职状态
|
||||
- 单 sheet,表头在第1行,数据第2行起
|
||||
"""
|
||||
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)
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
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
|
||||
|
||||
|
||||
def _export_one_status(page, status, download_dir, template_name, leave_start=None,
|
||||
leave_end=None, max_attempts=3):
|
||||
"""导出单个在职状态的花名册(设置筛选 -> 自定义导出 -> 下载),失败自动重试。
|
||||
|
||||
status == "离职" 时按 leave_start/leave_end 设置离职时间筛选(缺省自动计算)。
|
||||
"""
|
||||
last_exc = None
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
logger.info(">>> 开始导出在职状态:%s(模板:%s)", status, template_name)
|
||||
_ensure_person_status(page, status)
|
||||
if status == "离职":
|
||||
_set_leave_date_range(page, leave_start, leave_end)
|
||||
_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 as e:
|
||||
last_exc = e
|
||||
logger.warning("导出在职状态「%s」第 %d 次失败:%s", status, attempt, e)
|
||||
time.sleep(2.0 * attempt)
|
||||
raise last_exc
|
||||
|
||||
|
||||
def export_roster(download_dir=None, output_path=None, template_name=None,
|
||||
statuses=None, leave_start=None, leave_end=None):
|
||||
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
|
||||
|
||||
Args:
|
||||
download_dir: 浏览器下载临时目录(默认 DEFAULT_DOWNLOAD_DIR)
|
||||
output_path: 合并后保存路径(默认 DEFAULT_OUTPUT_PATH)
|
||||
template_name: 自定义导出模板名(默认 DEFAULT_TEMPLATE)
|
||||
statuses: 需导出的在职状态列表,如 ["在职"] / ["离职"] / ["在职","离职"]
|
||||
(默认 DEFAULT_STATUSES)
|
||||
leave_start / leave_end: 离职时间范围 "YYYY-MM-DD"(离职状态时生效;缺省自动计算)
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径
|
||||
"""
|
||||
download_dir = download_dir or DEFAULT_DOWNLOAD_DIR
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
template_name = template_name or DEFAULT_TEMPLATE
|
||||
statuses = list(statuses) if statuses else list(DEFAULT_STATUSES)
|
||||
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
leave_desc = ""
|
||||
if "离职" in statuses:
|
||||
ls, le = leave_start or "", leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
leave_desc = f",离职时间 {ls} ~ {le}"
|
||||
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s%s),下载目录:%s =====",
|
||||
template_name, statuses, leave_desc, download_dir)
|
||||
|
||||
page = _create_page()
|
||||
logger.info("浏览器已启动")
|
||||
try:
|
||||
# 注入共享 cookies 并进入花名册页(缺失/失效时提示先登录)
|
||||
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,
|
||||
leave_start, leave_end)
|
||||
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(statuses=None, leave_start=None, leave_end=None,
|
||||
template=None, output_path=None, download_dir=None):
|
||||
"""影刀自定义指令入口「37du花名册导出」。
|
||||
|
||||
Args(缺省用内置默认值,见 DEFAULT_* 常量):
|
||||
statuses: 在职状态,str "在职" 或 "在职,离职",或 list ["在职","离职"]
|
||||
leave_start / leave_end: 离职时间范围 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
template: 自定义导出模板名
|
||||
output_path / download_dir: 保存路径与下载目录
|
||||
|
||||
Returns:
|
||||
{"success": bool, "save_path": str, "statuses": [...], "template": str}
|
||||
save_path 即调用方传入的 output_path(合并后的花名册文件路径)。
|
||||
"""
|
||||
# 在职状态:兼容 str / list / 逗号分隔
|
||||
if isinstance(statuses, str):
|
||||
statuses = [s.strip() for s in statuses.replace(",", ",").split(",") if s.strip()]
|
||||
elif statuses:
|
||||
statuses = [str(s) for s in statuses]
|
||||
else:
|
||||
statuses = list(DEFAULT_STATUSES)
|
||||
|
||||
template = template or DEFAULT_TEMPLATE
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
download_dir = download_dir or DEFAULT_DOWNLOAD_DIR
|
||||
|
||||
try:
|
||||
save_path = export_roster(
|
||||
download_dir=download_dir, output_path=output_path,
|
||||
template_name=template, statuses=statuses,
|
||||
leave_start=leave_start, leave_end=leave_end)
|
||||
return {"success": True, "save_path": save_path, "statuses": statuses, "template": template}
|
||||
except Exception as e:
|
||||
logger.error("花名册导出失败:%s", e)
|
||||
return {"success": False, "error": str(e), "statuses": statuses, "template": template}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
statuses = ["在职", "离职"]
|
||||
leave_start = "2026-07-01"
|
||||
leave_end = "2026-08-21"
|
||||
template = "员工基础信息"
|
||||
output_path = r"D:\资料\人资\请休假异常\员工花名册.xlsx"
|
||||
main(statuses=statuses, leave_start=leave_start, leave_end=leave_end,
|
||||
template=template, output_path=output_path)
|
||||
|
||||
Reference in New Issue
Block a user