新增内容包括: 1. 7个业务需求占位文档目录与README 2. 共享OA登录、钉钉机器人推送工具模块 3. 雇主险变更清单导出脚本 4. 考勤月报封存检查两个检查脚本 5. 重庆社保停保导入名单生成脚本
642 lines
27 KiB
Python
642 lines
27 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@FileName: roster_export.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-08-22
|
||
@Description: 员工花名册导出(影刀共享指令,单文件自包含)——从共享登录态读取 HR cookies,
|
||
进入花名册页 -> 按需在职状态(在职/离职,离职可设时间范围)-> 自定义导出
|
||
-> 选择模板 -> 下载并按统一格式合并保存。供请休假异常、雇主险等业务脚本复用。
|
||
@Version: 1.0.0
|
||
|
||
运行方式:
|
||
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"
|
||
|
||
# 花名册 TTL 缓存有效期(秒):按传入 output_path 的 mtime 判断,
|
||
# 15 分钟内已导出过则直接复用该文件(不弹浏览器),超时才重新导出;传 ttl=0 表示总是重导。
|
||
DEFAULT_TTL_SECONDS = 15 * 60
|
||
|
||
# ---------- 流程步骤文案(与 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, ttl=DEFAULT_TTL_SECONDS):
|
||
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
|
||
|
||
带 TTL 缓存:output_path 已有且距上次导出不超过 ttl 秒时直接复用(跳过浏览器自动化),
|
||
超时才重新导出。花名册版本由「模板 + 输出路径」共同隔离(各业务场景路径独立),
|
||
不同模板导出到不同路径,不会互相复用。
|
||
|
||
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"(离职状态时生效;缺省自动计算)
|
||
ttl: 缓存有效期(秒),默认 DEFAULT_TTL_SECONDS(15 分钟);传 0 表示总是重新导出
|
||
|
||
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)
|
||
if ttl is None: # None 使用默认缓存有效期
|
||
ttl = DEFAULT_TTL_SECONDS
|
||
|
||
# TTL 缓存:输出路径已有、非空且距上次导出不超过 ttl 秒时直接复用,跳过浏览器导出
|
||
if ttl > 0 and os.path.exists(output_path) \
|
||
and os.path.getsize(output_path) > 0 \
|
||
and time.time() - os.path.getmtime(output_path) <= ttl:
|
||
logger.info("花名册缓存命中(%.0f 分钟内已导出,直接复用):%s", ttl / 60.0, output_path)
|
||
return output_path
|
||
|
||
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 = ""
|
||
leave_end = ""
|
||
template = "员工基础信息"
|
||
output_path = r"D:\资料\人资\排班异常识别\员工花名册.xlsx"
|
||
main(statuses=statuses, leave_start=leave_start, leave_end=leave_end,
|
||
template=template, output_path=output_path)
|
||
|