diff --git a/app/service/hrbp/ehr/employer_insurance/roster_filter.py b/app/service/hrbp/ehr/employer_insurance/roster_filter.py
index 80e393a..85689fa 100644
--- a/app/service/hrbp/ehr/employer_insurance/roster_filter.py
+++ b/app/service/hrbp/ehr/employer_insurance/roster_filter.py
@@ -160,13 +160,14 @@ def filter_and_copy_roster(category: dict, employee_file: str = None, target_fil
return len(rows)
-def export_roster_for_employer_insurance(download_dir: str = None) -> str:
+def export_roster_for_employer_insurance(download_dir: str = None, ttl: int = None) -> str:
"""按本场景模板「雇主险增减员导出模板」导出花名册(复用 roster_export,操作 HR 系统)。
输出位置由本场景指定:D:\\资料\\人资\\雇主险\\员工花名册.xlsx(与筛选复制的源表路径一致)。
Args:
download_dir: 浏览器下载临时目录,默认使用 roster_export 的默认目录。
+ ttl: 缓存有效期(秒),None 用 roster_export 默认(15 分钟);传 0 强制重新导出。
Returns:
合并后的花名册文件路径。
@@ -176,7 +177,7 @@ def export_roster_for_employer_insurance(download_dir: str = None) -> str:
logger.info("按本场景模板 [%s] 导出花名册(在职状态:%s),输出:%s",
ROSTER_TEMPLATE_NAME, ROSTER_EXPORT_STATUSES, output_path)
return export_roster(download_dir=download_dir, template_name=ROSTER_TEMPLATE_NAME,
- output_path=output_path, statuses=ROSTER_EXPORT_STATUSES)
+ output_path=output_path, statuses=ROSTER_EXPORT_STATUSES, ttl=ttl)
def main(category_name: str = None) -> None:
@@ -200,9 +201,10 @@ def main(category_name: str = None) -> None:
break
categories = [get_category(category_name)] if category_name else CATEGORIES
- # 源表(员工花名册)缺失才自动导出
- if "--export-roster" in args or not os.path.exists(EMPLOYEE_FILE):
- export_roster_for_employer_insurance()
+ # 源表(员工花名册)缺失才自动导出;--export-roster 为显式强制导出(ttl=0 绕过缓存)
+ force = "--export-roster" in args
+ if force or not os.path.exists(EMPLOYEE_FILE):
+ export_roster_for_employer_insurance(ttl=0 if force else None)
else:
logger.info("源表已存在:%s,跳过导出", EMPLOYEE_FILE)
diff --git a/app/service/hrbp/ehr/roster/roster_export.py b/app/service/hrbp/ehr/roster/roster_export.py
index 69f953d..849dcd5 100644
--- a/app/service/hrbp/ehr/roster/roster_export.py
+++ b/app/service/hrbp/ehr/roster/roster_export.py
@@ -82,6 +82,10 @@ DOWNLOAD_FINISH_TIMEOUT = 300 # 等待下载完成
OUTPUT_DIR = r"D:\资料\人资\员工花名册"
MERGED_NAME = "员工花名册.xlsx"
+# 花名册 TTL 缓存有效期(秒):按传入 output_path 的 mtime 判断,
+# 15 分钟内已导出过则直接复用该文件(不弹浏览器),超时才重新导出;传 ttl=0 表示总是重导。
+ROSTER_TTL_SECONDS = 15 * 60
+
# ---------------------------------------------------------------
# 1. 元素定位辅助(DrissionPage)
@@ -493,9 +497,14 @@ def _export_one_status(page, status, download_dir, template_name):
def export_roster(download_dir: str = None, template_name: str = ROSTER_TEMPLATE_NAME,
- output_path: str = None, statuses: list = None) -> str:
+ output_path: str = None, statuses: list = None,
+ ttl: int = ROSTER_TTL_SECONDS) -> str:
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
+ 带 TTL 缓存:output_path 已有且距上次导出不超过 ttl 秒时直接复用(跳过浏览器自动化),
+ 超时才重新导出。花名册版本由「模板 + 输出路径」共同隔离(各业务场景路径独立),
+ 不同模板导出到不同路径,不会互相复用。
+
Args:
download_dir: 浏览器下载临时目录,默认使用 OUTPUT_DIR。
template_name: 自定义导出模板名,可按业务场景动态传入(默认「员工基础信息」)。
@@ -503,6 +512,8 @@ def export_roster(download_dir: str = None, template_name: str = ROSTER_TEMPLATE
默认使用 OUTPUT_DIR/员工花名册.xlsx。
statuses: 需要导出的在职状态列表,默认 ["在职", "离职"];
业务场景可按需传入(如雇主险只需在职时传 ["在职"])。
+ ttl: 缓存有效期(秒),默认 ROSTER_TTL_SECONDS(15 分钟);传 0 表示总是重新导出。
+
Returns:
合并后的花名册文件路径。
@@ -515,6 +526,17 @@ def export_roster(download_dir: str = None, template_name: str = ROSTER_TEMPLATE
statuses = list(statuses) if statuses else list(PERSON_STATUSES)
download_dir = os.path.abspath(download_dir or OUTPUT_DIR)
+ output_path = os.path.abspath(output_path or os.path.join(OUTPUT_DIR, MERGED_NAME))
+ if ttl is None: # None 使用默认缓存有效期
+ ttl = ROSTER_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)
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s),下载目录:%s =====",
template_name, statuses, download_dir)
@@ -547,7 +569,7 @@ def export_roster(download_dir: str = None, template_name: str = ROSTER_TEMPLATE
time.sleep(WAIT_MID)
# 合并所有花名册文件
- merged_path = os.path.abspath(output_path or os.path.join(OUTPUT_DIR, MERGED_NAME))
+ merged_path = output_path # 已在函数开头按默认值归一化
os.makedirs(os.path.dirname(merged_path), exist_ok=True)
result = _merge_roster_files(files_with_status, merged_path)
logger.info("===== 花名册导出并合并完成:%s =====", result)
diff --git a/docs/需求单/XQ0002 雇主险增减操作/评分文档.md b/docs/需求单/XQ0002 雇主险增减操作/评分文档.md
index cca6719..3b4def8 100644
--- a/docs/需求单/XQ0002 雇主险增减操作/评分文档.md
+++ b/docs/需求单/XQ0002 雇主险增减操作/评分文档.md
@@ -16,6 +16,7 @@
### 1. 系统对接数 = 2
- HR 平台:花名册 / 在参名单数据源;
+- OA 平台:工作沟通推送;
- 本地 Excel 多文件读写(花名册、在参名单、变更清单、增减员导入模板/输出)。
### 2. 业务分支数 = 16
diff --git a/tests/ai_dd_send.py b/tests/ai_dd_send.py
new file mode 100644
index 0000000..af151c9
--- /dev/null
+++ b/tests/ai_dd_send.py
@@ -0,0 +1,166 @@
+# -*- coding: utf-8 -*-
+"""钉钉单聊推送(文本 / 文件)— 外部终端自测版,含重名处理"""
+import json
+import os
+import subprocess
+
+DWS_BIN = r"C:\Users\admin\.local\bin\dws.exe"
+
+# ↓↓↓ 配置区(测试时改这里)↓↓↓
+RECIPIENT_USER_ID = "37036359" # 接收人 userId(发文本用)
+RECIPIENT_OPEN_ID = "" # 接收人 openDingTalkId(发文件用;留空则按 RECIPIENT_NAME 查询)
+RECIPIENT_NAME = "张峻杰" # 接收人姓名(OPEN_ID 为空时用于查询,可留空)
+MESSAGE_TEXT = "测试文件推送"
+FILE_PATH = r"C:\Users\admin\Desktop\test.xlsx" # 要推送的本地文件路径;留空则只发文本
+# ↑↑↑ ↑↑↑
+
+
+class DwsError(RuntimeError):
+ """dws 命令执行失败;code 为上游 server_error_code(如 11056=会话不存在)"""
+ def __init__(self, message: str, code: str = ""):
+ super().__init__(message)
+ self.code = code
+
+
+def _extract_error_code(text: str) -> str:
+ """从 dws 错误输出里尽量提取 server_error_code"""
+ try:
+ data = json.loads(text[text.find("{"):])
+ return str(data.get("error", {}).get("server_error_code") or "")
+ except Exception:
+ return ""
+
+
+def _run_dws(cmd_list) -> dict:
+ """执行 dws 命令并返回完整 JSON(含 success/result 顶层字段)"""
+ result = subprocess.run(cmd_list, capture_output=True, text=True,
+ encoding="utf-8", errors="replace")
+ if result.returncode != 0:
+ raise DwsError(f"命令失败: {result.stderr.strip()}",
+ code=_extract_error_code(result.stderr))
+ raw = result.stdout
+ data = json.loads(raw[raw.find("{"):])
+ if not data.get("success"):
+ raise DwsError(f"命令未成功: {data}",
+ code=_extract_error_code(raw))
+ return data
+
+
+def resolve_open_id(name: str, user_id: str = "") -> str:
+ """按姓名查询 openDingTalkId;同名多人时优先用 userId 精确匹配,无 userId 才列候选"""
+ data = _run_dws([DWS_BIN, "contact", "user", "search",
+ "--query", name, "--format", "json"])
+ users = data.get("result") or []
+ if not users:
+ raise RuntimeError(f"未找到姓名为「{name}」的成员")
+
+ if len(users) == 1:
+ u = users[0]
+ print(f"👤 命中 1 人: {u['name']} | userId={u['userId']} | {u.get('title') or '无职位'}")
+ return u["openDingTalkId"]
+
+ # 同名多人:优先用 userId 精确定位(用户手上有各候选的 userId)
+ if user_id:
+ for u in users:
+ if u.get("userId") == user_id:
+ print(f"👤 按 userId 命中: {u['name']} | userId={u['userId']} | {u.get('title') or ''}")
+ return u["openDingTalkId"]
+
+ # 同名多人且无匹配 userId:批量拉详情(含部门)帮助区分,禁止默认选第一个
+ ids = ",".join(u["userId"] for u in users)
+ detail_data = _run_dws([DWS_BIN, "contact", "user", "get",
+ "--ids", ids, "--format", "json"])
+ details = detail_data.get("result") or []
+ info_map = {d["orgEmployeeModel"]["orgUserId"]: d for d in details}
+
+ hints = []
+ for u in users:
+ org_model = info_map.get(u["userId"], {}).get("orgEmployeeModel", {})
+ depts = org_model.get("depts") or []
+ dept = ",".join(x.get("deptName", "") for x in depts)
+ hints.append(
+ f" {u.get('name')} | userId={u.get('userId')} | "
+ f"部门={dept or '未知'} | 职位={org_model.get('orgTitle') or u.get('title') or '未知'}"
+ )
+ raise RuntimeError(
+ f"「{name}」有 {len(users)} 个同名,请在配置里填 RECIPIENT_OPEN_ID:\n" + "\n".join(hints)
+ )
+
+
+def get_chat_space_id(open_id: str) -> str:
+ """获取单聊会话共享空间 ID;无会话(11056 或缺字段)时返回空串"""
+ data = _run_dws([DWS_BIN, "chat", "conversation-info",
+ "--open-dingtalk-id", open_id, "--format", "json"])
+ try:
+ return data["result"]["conversationInfo"]["extension"].get("newCSpaceIdIM", "")
+ except (KeyError, TypeError, AttributeError):
+ return ""
+
+
+def upload_file(space_id: str, file_path: str) -> dict:
+ data = _run_dws([DWS_BIN, "drive", "upload",
+ "--file", file_path, "--space-id", space_id,
+ "--format", "json"])
+ return data["result"]
+
+
+def get_dentry(file_id: str, space_id: str) -> dict:
+ data = _run_dws([DWS_BIN, "drive", "info",
+ "--node", file_id, "--space-id", space_id,
+ "--format", "json"])
+ return data["result"]
+
+
+def send_text(user_id: str, text: str):
+ _run_dws([DWS_BIN, "chat", "message", "send",
+ "--user", user_id, "--text", text, "--format", "json"])
+ print(f"✅ 文本已发送: {text}")
+
+
+def send_file(open_id: str, file_path: str, user_id: str = ""):
+ # 获取会话空间 ID;无会话(11056 或返回缺字段)时 space_id 为空
+ try:
+ space_id = get_chat_space_id(open_id)
+ except DwsError as e:
+ if e.code != "11056":
+ raise
+ space_id = ""
+
+ if not space_id:
+ if not user_id:
+ raise RuntimeError("拿不到会话空间 ID 且未提供 userId,无法发文件")
+ print("ℹ️ 对方未建立会话,先发送一条文本建立会话…")
+ send_text(user_id, "建立会话")
+ space_id = get_chat_space_id(open_id)
+
+ if not space_id:
+ raise RuntimeError("建立会话后仍拿不到会话空间 ID(newCSpaceIdIM),请检查")
+
+ up = upload_file(space_id, file_path)
+ info = get_dentry(up["fileId"], up["spaceId"])
+ _run_dws([DWS_BIN, "chat", "message", "send",
+ "--open-dingtalk-id", open_id,
+ "--msg-type", "file",
+ "--dentry-id", info["dentryId"],
+ "--space-id", up["spaceId"],
+ "--file-name", info["name"],
+ "--file-type", info.get("extension", "file"),
+ "--file-path", info.get("path", "/" + info["name"]),
+ "--file-size", str(info["fileSize"]),
+ "--format", "json"])
+ print(f"✅ 文件已发送: {os.path.basename(file_path)}")
+
+
+if __name__ == "__main__":
+ open_id = RECIPIENT_OPEN_ID or (resolve_open_id(RECIPIENT_NAME, RECIPIENT_USER_ID) if RECIPIENT_NAME else "")
+
+ if open_id:
+ print(f"🔑 接收人 openDingTalkId: {open_id}") # 打印查询到的 OPEN_ID
+
+ if MESSAGE_TEXT:
+ send_text(RECIPIENT_USER_ID, MESSAGE_TEXT)
+
+ if FILE_PATH:
+ if not open_id:
+ raise RuntimeError("发文件需要 openDingTalkId:请填 RECIPIENT_OPEN_ID 或 RECIPIENT_NAME")
+ send_file(open_id, FILE_PATH, RECIPIENT_USER_ID)
diff --git a/yingdao/XQ0001 排班异常识别/shift_abnormal_check.py b/yingdao/XQ0001 排班异常识别/shift_abnormal_check.py
index df6418e..b3e3c60 100644
--- a/yingdao/XQ0001 排班异常识别/shift_abnormal_check.py
+++ b/yingdao/XQ0001 排班异常识别/shift_abnormal_check.py
@@ -3,12 +3,13 @@
@FileName: shift_abnormal_check.py
@Author: 小布丁
@CreateTime: 2026-08-27
-@Description: 排班异常识别 + OA 工作沟通推送(第三步,影刀版,单文件自包含)。
+@Description: 排班异常识别 + 钉钉单聊推送(第三步,影刀版,单文件自包含)。
读取第二步导出的《调动台账.xlsx》《预入职台账.xlsx》(表头均在 2 行),结合 HR 排班接口
判断每人排班是否异常,生成异常明细(写回一份 Excel + 输出到全局变量),并通知各店长:
- 最后一步由共享指令「OA工作沟通推送」(yingdao/share/work_communication.py)完成发送,
+ 最后一步由共享指令「37du钉钉单聊推送」(yingdao/share/dingtalk_dws_push.py)完成发送,
本脚本只负责「按异常人员工号解析对应店长 → 按店长分组 → 构造通知内容 → 写入影刀全局变量 messages」。
- 消息结构与共享指令 main(messages) 完全一致(receivers/subject/content/attachment_paths/category)。
+ 消息结构与共享指令 main(messages) 完全一致(五元组 (msg_type, name, user_id, content, file_path),
+ 此处均为 ("text", 店长姓名, 店长工号, 纯文本内容, ""))。
判断口径(与 app 版 shift_abnormal_check.py 一致):
- 调动台账:按「调动时间」近 {DAYS} 天;「现职位序列」含「职能」按「现单位」比对、
@@ -528,33 +529,49 @@ def resolve_manager(roster_df, row: dict) -> Tuple[str, str]:
# ==================== 消息构造 ====================
def _item_line(row: dict) -> str:
- """地点异常明细的一行(用于工作沟通正文 HTML)。"""
+ """地点异常明细的一行(单聊推送纯文本正文)。"""
name = row.get("姓名", "")
code = row.get("工号", "")
cat = row.get("类别", "")
day = row.get("调动/入职时间", "")
dept = row.get("现四级部门") or row.get("现单位") or ""
reason = row.get("异常原因", "")
- return "
{name}(工号 {code},{cat},{dept},{day}):{reason}".format(
- name=name, code=code, cat=cat, dept=dept, day=day, reason=reason)
+ return f"{name}(工号 {code},{cat},{dept},{day}):{reason}"
-def build_messages(rows: List[dict], roster_df) -> List[dict]:
- """按店长分组构造工作沟通消息列表,结构与共享指令 main(messages) 一致。
+def _resolve_manager_identity(df, keyword: str) -> Tuple[str, str]:
+ """把「工号 or 姓名」归一化为 (工号, 姓名)(默认处理人场景)。
+ 花名册能查到就取登记值;查不到则按形态回退:像工号当工号(姓名为空,
+ 推送会因缺姓名失败并在记录中体现),否则当姓名。
+ """
+ keyword = _to_text(keyword).strip()
+ if not keyword:
+ return "", ""
+ hit = df[df[COL_CODE].map(_to_text) == keyword]
+ if hit.empty:
+ hit = df[df[COL_NAME].map(_to_text) == keyword]
+ if not hit.empty:
+ return _to_text(hit.iloc[0][COL_CODE]), _to_text(hit.iloc[0][COL_NAME]) or ""
+ if keyword.isdigit():
+ return keyword, ""
+ return "", keyword
- 每组一条消息:{receivers:[店长工号], subject, content(HTML), attachment_paths:[], category}。
+
+def build_messages(rows: List[dict], roster_df) -> List[tuple]:
+ """按店长分组构造钉钉单聊推送消息列表,结构与共享模块 dingtalk_dws_push.main(messages) 一致。
+
+ 每组一条消息:("text", 店长姓名, 店长工号, 纯文本内容, "")。
无法解析店长的异常,若配置 DEFAULT_MANAGER 则归入默认处理人,否则仅日志记录、不推送。
"""
- messages: List[dict] = []
- groups: Dict[str, List[dict]] = {} # 店长工号 -> 异常行列表
+ messages: List[tuple] = []
+ groups: Dict[Tuple[str, str], List[dict]] = {} # (店长工号, 店长姓名) -> 异常行列表
unresolved: List[dict] = []
default_managers = [m.strip() for m in DEFAULT_MANAGER.split(",") if m.strip()]
for row in rows:
mc, mn = resolve_manager(roster_df, row)
- if mc:
- key = f"{mc}|{mn}"
- groups.setdefault(key, []).append(row)
+ if mc or mn:
+ groups.setdefault((mc or "", mn or ""), []).append(row)
else:
unresolved.append(row)
@@ -563,27 +580,19 @@ def build_messages(rows: List[dict], roster_df) -> List[dict]:
len(unresolved),
[f"{r.get('姓名')}/{r.get('工号')}" for r in unresolved])
if default_managers:
- primary_key = f"{default_managers[0]}|"
- groups.setdefault(primary_key, []).extend(unresolved)
+ key = _resolve_manager_identity(roster_df, default_managers[0])
+ groups.setdefault(key, []).extend(unresolved)
- for key, items in groups.items():
- mc, mn = key.split("|", 1)
- line_items = "".join(_item_line(r) for r in items)
- subject = f"【排班异常】你的门店有 {len(items)} 名员工排班异常,请核实处理"
+ for (mc, mn), items in groups.items():
+ line_items = "\n".join(_item_line(r) for r in items)
content = (
- f"人力资源部在近期排班核查中发现以下员工存在排班异常,请门店尽快核实处理:
"
- f"{line_items}
"
- f"({datetime.now().strftime('%Y-%m-%d %H:%M')} 由排班异常识别自动生成)
"
+ f"【排班异常】你的门店有 {len(items)} 名员工排班异常,请核实处理\n\n"
+ f"人力资源部在近期排班核查中发现以下员工存在排班异常,请门店尽快核实处理:\n"
+ f"{line_items}\n\n"
+ f"({datetime.now().strftime('%Y-%m-%d %H:%M')} 由排班异常识别自动生成)"
)
- receivers = [mc] if mc else [mn]
- messages.append({
- "receivers": receivers,
- "subject": subject,
- "content": content,
- "attachment_paths": [],
- "category": "工作安排",
- })
- logger.info("已构造店长[%s%s]消息,含 %d 条异常", mn, f"/{mc}" if mc else "", len(items))
+ messages.append(("text", mn, mc, content, ""))
+ logger.info("已构造店长[%s%s]单聊推送消息,含 %d 条异常", mn, f"/{mc}" if mc else "", len(items))
return messages
@@ -595,10 +604,11 @@ def run_shift_abnormal_check(
roster_path: str = None,
days: int = DAYS,
) -> Tuple[List[dict], List[dict]]:
- """执行排班异常识别,返回 (异常名单行列表, 工作沟通消息列表)。
+ """执行排班异常识别,返回 (异常名单行列表, 单聊推送消息列表)。
- 异常名单行列表:合并调动+预入职的异常明细(未写文件);
- - 工作沟通消息列表:按店长分组,供共享指令「OA工作沟通推送」直接发送。
+ - 单聊推送消息列表:按店长分组,五元组 ("text", 店长姓名, 店长工号, 内容, ""),
+ 供共享指令「37du钉钉单聊推送」直接发送。
脚本内部会将名单写入 SAVE_DIR 下《排班异常名单_时间戳.xlsx》便于人工留档。
"""
global DAYS
@@ -652,8 +662,8 @@ def run_shift_abnormal_check(
def main() -> None:
- """影刀入口:排班异常识别并构造工作沟通消息,写入全局变量 messages。
- 由流程拖「OA工作沟通推送」指令完成实际发送。
+ """影刀入口:排班异常识别并构造钉钉单聊推送消息,写入全局变量 messages。
+ 由流程拖「37du钉钉单聊推送」指令完成实际发送。
"""
try:
rows, messages = run_shift_abnormal_check()
@@ -662,7 +672,7 @@ def main() -> None:
logger.info("=" * 60)
logger.info("【排班异常识别完成】")
logger.info(" 异常人数:%d", len(rows))
- logger.info(" 待推送消息:%d 条(已写入全局变量 messages,请拖「OA工作沟通推送」指令发送)", len(messages))
+ logger.info(" 待推送消息:%d 条(已写入全局变量 messages,请拖「37du钉钉单聊推送」指令发送)", len(messages))
logger.info("=" * 60)
except Exception as e:
logger.error("排班异常识别失败:%s", e)
diff --git a/yingdao/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py b/yingdao/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py
index 0fc5f08..b838efc 100644
--- a/yingdao/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py
+++ b/yingdao/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py
@@ -12,9 +12,11 @@
缺失/失效时先拖入「37duHR登录」指令再运行本流程。
钉钉推送(消息生成与发送解耦,本脚本不内联发送):
- main() 将待推送 messages(元组列表 (search_keyword, text, verify_keyword))写入影刀全局变量
+ main() 将待推送 messages(元组列表 (msg_type, name, user_id, content, file_path),即
+ ("text", 姓名, 工号, 文本内容, ""))写入影刀全局变量
glv['messages'];处理条数汇总(自动确认数、推送当事人确认数)写入 glv['group_messages']
- (文本列表,每项一条),分别由流程拖「37du钉钉推送」(个人)/「37du钉钉群机器人推送」(群)指令完成发送。
+ (文本列表,每项一条),分别由流程拖「37du钉钉单聊推送」(个人,yingdao/share/dingtalk_dws_push.py)/
+ 「37du钉钉群机器人推送」(群)指令完成发送。
自动确认:仅轻微异常(迟到/早退 < 30 分钟,不分职能序列)自动调用确认接口,确认条数计入群汇总。
由 AUTO_CONFIRM_ENABLED 总开关控制(布尔值,默认 False,置 True 才执行批量确认,便于测试时关闭)。
@@ -523,10 +525,14 @@ def export_excel(data, save_dir, month_str, test_mode=False):
# ==================== 钉钉推送(总开关控制) ====================
def push_abnormal(items):
"""按「工号-姓名」分组,合并为 messages 元组列表,写入影刀全局变量 messages,
- 由流程拖「37du钉钉推送」指令发送(本脚本不内联发送,保持单文件自包含)。
- 每项为 (search_keyword, text, verify_keyword) 元组:
- search_keyword(搜索关键字)使用工号,避免同名人员误发;
- verify_keyword(会话标题校验关键字)传姓名(钉钉标题显示姓名而非工号)。
+ 由流程拖「37du钉钉单聊推送」指令(yingdao/share/dingtalk_dws_push.py)发送(本脚本不内联发送,
+ 保持单文件自包含)。
+ 每项为 (msg_type, name, user_id, content, file_path) 五元组,此处均为 ("text", 姓名, 工号, 文本, ""):
+ msg_type 消息类型,文本推送固定 "text"
+ name 接收人姓名(发文本时仅用于记录/展示)
+ user_id 接收人工号(dws 按工号发送,避免同名误发)
+ content 消息内容
+ file_path 文件地址(文本推送留空)
返回 (待推送条数, 失败数=0)。
"""
groups = {}
@@ -540,9 +546,9 @@ def push_abnormal(items):
messages = []
for (code, name), group in groups.items():
- # search_keyword 用工号避免同名误发;verify_keyword 用姓名(钉钉标题显示姓名)
- messages.append((code or name, build_notify_text(group), name))
- # 写入影刀全局变量,供流程「37du钉钉推送」指令读取(无数据也置空,避免 NameError)
+ # 消息类型固定 "text",工号用于 dws 按工号发送,姓名用于记录
+ messages.append(("text", name, code, build_notify_text(group), ""))
+ # 写入影刀全局变量,供流程「37du钉钉单聊推送」指令读取(无数据也置空,避免 NameError)
_set_glv('messages', messages)
logger.info("当事人消息已生成并写入全局变量 messages:共 %d 条(由流程推送)", len(messages))
return len(messages), 0
diff --git a/yingdao/share/dingtalk_dws_push.py b/yingdao/share/dingtalk_dws_push.py
new file mode 100644
index 0000000..d613f18
--- /dev/null
+++ b/yingdao/share/dingtalk_dws_push.py
@@ -0,0 +1,416 @@
+# -*- coding: utf-8 -*-
+"""
+@FileName: dingtalk_dws_push.py
+@Description: 钉钉单聊推送共享模块(文本 / 文件,基于 dws 命令行)。
+ 供各业务脚本 import 复用,也可作为影刀自定义指令「37du钉钉单聊推送」的模块源码。
+
+入口:
+ main(messages, record_dir='') 影刀自定义指令「37du钉钉单聊推送」调用入口。
+ 传入消息列表,每项为五元组 (消息类型, 姓名, 工号, 消息内容, 文件地址):
+ msg_type 消息类型:'text'/'文本' 或 'file'/'文件'
+ name 接收人姓名(文本/文件均按姓名解析 openDingTalkId;同名多人时按工号精确定位)
+ user_id 接收人工号(同名消歧;发文件且对方无会话时用于先建会话)
+ content 消息内容(msg_type=text 时必填)
+ file_path 文件地址(msg_type=file 时必填,本地绝对路径)
+ record_dir(可选):非空时每条结果写入 /YYYY-MM-DD/推送记录.csv,
+ 并把记录文件路径写入影刀全局变量 push_record_path,供流程处理失败名单。
+ 返回: {"success": bool, "message": str, "results": [...]}
+
+ send_message(msg_type, name, user_id, content, file_path, record_dir='') # 单条发送(内部/业务脚本复用)
+
+推送原理(DWS CLI,零第三方 Python 依赖,仅标准库):
+ - 文本:按姓名解析 openDingTalkId 后 dws chat message send --open-dingtalk-id --text <内容>
+ (dws 的 --user 只认钉钉 org userId,与工号不同,故文本/文件统一走 --open-dingtalk-id;
+ 单聊会话由首条消息自动创建,遇 11056 自动等待后重试一次,无需对方先聊过天)
+ - 文件:按姓名查 openDingTalkId → 取单聊会话共享空间 ID → 上传文件到钉盘
+ → 按 dentry 信息发文件消息;对方未建立会话(11056)时自动先发一条
+ 文本建立会话再发文件。
+
+防风控限流:
+ 每次实际发送前经滑动窗口限流(默认 50 条/分钟,见 _RATE_LIMIT),
+ 窗口已满时自动等待、不丢消息;批量推送请合理控制总量。
+
+依赖:dws.exe 命令行工具(路径见下方配置区 DWS_BIN)。
+"""
+import csv
+import json
+import os
+import subprocess
+import time
+from datetime import datetime
+
+# ==================== 配置区 ====================
+DWS_BIN = r"C:\Users\admin\.local\bin\dws.exe" # dws 命令行工具路径
+
+# ==================== 异常与工具 ====================
+class DwsError(RuntimeError):
+ """dws 命令执行失败;code 为上游 server_error_code(如 11056=会话不存在)"""
+ def __init__(self, message: str, code: str = ""):
+ super().__init__(message)
+ self.code = code
+
+
+def _extract_error_code(text: str) -> str:
+ """从 dws 错误输出里尽量提取 server_error_code"""
+ try:
+ data = json.loads(text[text.find("{"):])
+ return str(data.get("error", {}).get("server_error_code") or "")
+ except Exception:
+ return ""
+
+
+def _run_dws(cmd_list) -> dict:
+ """执行 dws 命令并返回完整 JSON(含 success/result 顶层字段)"""
+ result = subprocess.run(cmd_list, capture_output=True, text=True,
+ encoding="utf-8", errors="replace")
+ if result.returncode != 0:
+ raise DwsError(f"命令失败: {result.stderr.strip()}",
+ code=_extract_error_code(result.stderr))
+ raw = result.stdout
+ data = json.loads(raw[raw.find("{"):])
+ if not data.get("success"):
+ raise DwsError(f"命令未成功: {data}",
+ code=_extract_error_code(raw))
+ return data
+
+
+def _normalize_msg_type(msg_type: str) -> str:
+ """消息类型归一化:'文本'/'text' → 'text';'文件'/'file' → 'file'"""
+ key = str(msg_type or "").strip().lower()
+ if key in ("text", "文本", "txt", "文字"):
+ return "text"
+ if key in ("file", "文件"):
+ return "file"
+ raise ValueError(f"未知消息类型「{msg_type}」,仅支持:文本 / 文件")
+
+
+# ==================== 接口限流(防风控) ====================
+_RATE_LIMIT = 50 # 每分钟最大实际发送条数
+_RATE_WINDOW_SEC = 60 # 限流窗口(秒)
+_RATE_HISTORY = [] # 本进程内窗口内各次实际发送的时间戳(秒)
+
+
+def _rate_limit_wait():
+ """滑动窗口限流:1 分钟窗口内实际发送最多 _RATE_LIMIT 条(默认 50),
+ 避免短时间高频推送触发风控。窗口已满时阻塞等待最早一条滑出窗口后再放行,
+ 保证整批消息最终都能发出、不丢消息。在每次真正调用 dws 发送前调用并占名额。
+ """
+ now = time.time()
+ while True:
+ _RATE_HISTORY[:] = [t for t in _RATE_HISTORY if now - t < _RATE_WINDOW_SEC]
+ if len(_RATE_HISTORY) < _RATE_LIMIT:
+ break
+ sleep_sec = max(0.1, _RATE_HISTORY[0] + _RATE_WINDOW_SEC - now)
+ print(f"[WARN] 已达限流上限({_RATE_LIMIT} 条/分钟),等待 {sleep_sec:.1f} 秒后继续…")
+ time.sleep(min(sleep_sec, 1.0))
+ now = time.time()
+ _RATE_HISTORY.append(time.time())
+
+
+# ==================== 推送记录(main 传 record_dir 时自动写入,best-effort) ====================
+_RECORD_COLUMNS = ["推送时间", "工号", "姓名", "结果", "消息摘要"]
+_RECORD_SUMMARY_MAX_CHARS = 200
+_GLV_RECORD_PATH = "push_record_path" # 推送记录文件路径(影刀全局变量,供流程自行取用/发送失败名单)
+
+
+def _set_glv(name, value):
+ """写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
+ try:
+ glv[name] = value
+ except Exception:
+ pass
+
+
+def _record_csv_path(record_dir):
+ return os.path.join(record_dir, datetime.now().strftime("%Y-%m-%d"), "推送记录.csv")
+
+
+def _record_push(user_id, name, result, summary="", record_dir=""):
+ """尽力追加一条推送记录到 /YYYY-MM-DD/推送记录.csv。
+ record_dir 为空串时不记录(本模块供所有场景复用,由调用方传位置)。
+ best-effort,任何失败都不影响推送。返回记录文件路径(未记录返回空串)。
+ """
+ if not record_dir:
+ return ""
+ try:
+ path = _record_csv_path(record_dir)
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ new_file = not os.path.exists(path)
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ summary = str(summary or "").replace("\r\n", "\n").replace("\r", "\n")
+ if len(summary) > _RECORD_SUMMARY_MAX_CHARS:
+ summary = summary[:_RECORD_SUMMARY_MAX_CHARS] + "..."
+ with open(path, "a", newline="", encoding="utf-8-sig") as f:
+ writer = csv.DictWriter(f, fieldnames=_RECORD_COLUMNS)
+ if new_file:
+ writer.writeheader()
+ writer.writerow({
+ "推送时间": now,
+ "工号": user_id,
+ "姓名": name,
+ "结果": result,
+ "消息摘要": summary,
+ })
+ print(f"[INFO] 推送记录已写入:{path}({result})")
+ return path
+ except Exception as e:
+ print(f"[WARN] 推送记录写入失败(不影响推送):{e}")
+ return ""
+
+
+def _write_record_path_to_glv(record_dir):
+ """把推送记录文件路径写入影刀全局变量 push_record_path。
+ 未传 record_dir 时写空串,由流程自行读取记录文件处理失败名单。
+ """
+ path = _record_csv_path(record_dir) if record_dir else ""
+ _set_glv(_GLV_RECORD_PATH, path)
+ if path:
+ print(f"[INFO] 推送记录文件路径已写入全局变量 {_GLV_RECORD_PATH}:{path}")
+
+
+def _record_and_return(result, record_dir, name, user_id, content, file_path):
+ """记录推送结果后返回 result(best-effort,写失败不影响推送)。
+ 消息摘要:文本取内容,文件取文件名。
+ """
+ if record_dir:
+ summary = str(content or "").strip() or os.path.basename(str(file_path))
+ _record_push(user_id, name, "成功" if result.get("success") else "失败",
+ summary, record_dir=record_dir)
+ return result
+
+
+# ==================== 联系人解析 ====================
+_OPEN_ID_CACHE = {} # 按 (name, user_id) 缓存 openDingTalkId,批量推送同一个人只查一次通讯录
+
+
+def resolve_open_id(name: str, user_id: str = "") -> str:
+ """按姓名查询 openDingTalkId;同名多人时优先用工号精确匹配,无工号才列候选。
+ 查询结果按 (name, user_id) 缓存于进程内;通讯录有变动时需重启进程生效。
+ """
+ # 入口归一化:避免业务脚本直接调用时带空格(" 张三 " vs "张三")导致缓存键不一致
+ name = str(name or "").strip()
+ user_id = str(user_id or "").strip()
+
+ key = (name, user_id)
+ cached = _OPEN_ID_CACHE.get(key)
+ if cached:
+ print(f"[INFO] 命中缓存: {name} | userId={user_id}")
+ return cached
+
+ data = _run_dws([DWS_BIN, "contact", "user", "search",
+ "--query", name, "--format", "json"])
+ users = data.get("result") or []
+ if not users:
+ raise RuntimeError(f"未找到姓名为「{name}」的成员")
+
+ if len(users) == 1:
+ u = users[0]
+ print(f"[INFO] 命中 1 人: {u['name']} | userId={u['userId']} | {u.get('title') or '无职位'}")
+ _OPEN_ID_CACHE[key] = u["openDingTalkId"]
+ return u["openDingTalkId"]
+
+ # 同名多人:优先用工号精确定位(调用方手上应有候选的工号)
+ if user_id:
+ for u in users:
+ if u.get("userId") == user_id:
+ print(f"[INFO] 按工号命中: {u['name']} | userId={u['userId']} | {u.get('title') or ''}")
+ _OPEN_ID_CACHE[key] = u["openDingTalkId"]
+ return u["openDingTalkId"]
+
+ # 同名多人且无匹配工号:批量拉详情(含部门)帮助区分,禁止默认选第一个
+ ids = ",".join(u["userId"] for u in users)
+ detail_data = _run_dws([DWS_BIN, "contact", "user", "get",
+ "--ids", ids, "--format", "json"])
+ details = detail_data.get("result") or []
+ info_map = {d["orgEmployeeModel"]["orgUserId"]: d for d in details}
+
+ hints = []
+ for u in users:
+ org_model = info_map.get(u["userId"], {}).get("orgEmployeeModel", {})
+ depts = org_model.get("depts") or []
+ dept = ",".join(x.get("deptName", "") for x in depts)
+ hints.append(
+ f" {u.get('name')} | userId={u.get('userId')} | "
+ f"部门={dept or '未知'} | 职位={org_model.get('orgTitle') or u.get('title') or '未知'}"
+ )
+ raise RuntimeError(
+ f"「{name}」有 {len(users)} 个同名,请核对工号后再调用:\n" + "\n".join(hints)
+ )
+
+
+# ==================== 会话空间与文件 ====================
+def get_chat_space_id(open_id: str) -> str:
+ """获取单聊会话共享空间 ID;无会话(11056 或缺字段)时返回空串"""
+ data = _run_dws([DWS_BIN, "chat", "conversation-info",
+ "--open-dingtalk-id", open_id, "--format", "json"])
+ try:
+ return data["result"]["conversationInfo"]["extension"].get("newCSpaceIdIM", "")
+ except (KeyError, TypeError, AttributeError):
+ return ""
+
+
+def upload_file(space_id: str, file_path: str) -> dict:
+ data = _run_dws([DWS_BIN, "drive", "upload",
+ "--file", file_path, "--space-id", space_id,
+ "--format", "json"])
+ return data["result"]
+
+
+def get_dentry(file_id: str, space_id: str) -> dict:
+ data = _run_dws([DWS_BIN, "drive", "info",
+ "--node", file_id, "--space-id", space_id,
+ "--format", "json"])
+ return data["result"]
+
+
+# ==================== 发送实现 ====================
+def send_text(open_id: str, text: str):
+ """向单聊发送文本:--user 需要的是钉钉 org userId(≠工号),故统一用
+ resolve_open_id 解析出的 openDingTalkId 走 --open-dingtalk-id 发送。
+ 兜底:单聊会话由首条消息自动创建;若发送遇 11056(会话不存在),等待 1s
+ 后重试一次——11056 意味着该条未投递,重试不会造成重复发送。
+ """
+
+ def _do_send():
+ _rate_limit_wait() # 限流:每次实际发送占用一个名额
+ _run_dws([DWS_BIN, "chat", "message", "send",
+ "--open-dingtalk-id", open_id, "--text", text, "--format", "json"])
+
+ try:
+ _do_send()
+ except DwsError as e:
+ if e.code != "11056":
+ raise
+ print("[INFO] 会话不存在(11056),等待 1s 后重试一次(首条单聊消息即自动建会话)…")
+ time.sleep(1)
+ _do_send()
+ print(f"[INFO] 文本已发送: {text}")
+
+
+def send_file(open_id: str, file_path: str):
+ """发送文件到单聊:取会话空间 ID → 上传 → 发文件消息。
+ 无会话(11056 或缺字段)时 space_id 为空,自动先发一条文本建立会话再发文件。
+ """
+ try:
+ space_id = get_chat_space_id(open_id)
+ except DwsError as e:
+ if e.code != "11056":
+ raise
+ space_id = ""
+
+ if not space_id:
+ print("[INFO] 对方未建立会话,先发送一条文本建立会话…")
+ send_text(open_id, "建立会话")
+ space_id = get_chat_space_id(open_id)
+
+ if not space_id:
+ raise RuntimeError("建立会话后仍拿不到会话空间 ID(newCSpaceIdIM),请检查")
+
+ up = upload_file(space_id, file_path)
+ info = get_dentry(up["fileId"], up["spaceId"])
+ _rate_limit_wait() # 限流:文件消息占用一个名额(建会话文本已在 send_text 内计过一次)
+ _run_dws([DWS_BIN, "chat", "message", "send",
+ "--open-dingtalk-id", open_id,
+ "--msg-type", "file",
+ "--dentry-id", info["dentryId"],
+ "--space-id", up["spaceId"],
+ "--file-name", info["name"],
+ "--file-type", info.get("extension", "file"),
+ "--file-path", info.get("path", "/" + info["name"]),
+ "--file-size", str(info["fileSize"]),
+ "--format", "json"])
+ print(f"[INFO] 文件已发送: {os.path.basename(file_path)}")
+
+
+# ==================== 统一入口 ====================
+def send_message(msg_type, name, user_id, content, file_path="", record_dir=""):
+ """单条推送:按消息类型分发文本 / 文件。
+ 参数(5 个):msg_type 消息类型、name 姓名、user_id 工号、
+ content 消息内容、file_path 文件地址。
+ record_dir(可选):非空时写入 /YYYY-MM-DD/推送记录.csv。
+ 返回 {"success": bool, "message": str}。
+ """
+ name = str(name or "").strip()
+ user_id = str(user_id or "").strip()
+ try:
+ mtype = _normalize_msg_type(msg_type)
+
+ if mtype == "text":
+ if not content or not str(content).strip():
+ return _record_and_return({"success": False, "message": "文本消息内容不能为空"},
+ record_dir, name, user_id, content, file_path)
+ if not name:
+ return _record_and_return({"success": False, "message": "发送文本需要姓名(name)以解析 openDingTalkId"},
+ record_dir, name, user_id, content, file_path)
+ # --user 只认钉钉 org userId(≠工号),文本与文件统一按姓名解析 openDingTalkId 后发送
+ open_id = resolve_open_id(name, user_id)
+ print(f"[INFO] 接收人 openDingTalkId: {open_id}")
+ send_text(open_id, str(content))
+ return _record_and_return({"success": True, "message": f"已向「{name}」发送文本"},
+ record_dir, name, user_id, content, file_path)
+
+ # 文件
+ file_path = str(file_path or "").strip()
+ if not file_path or not os.path.exists(file_path):
+ return _record_and_return({"success": False, "message": f"文件不存在: {file_path}"},
+ record_dir, name, user_id, content, file_path)
+ if not name:
+ return _record_and_return({"success": False, "message": "发送文件需要姓名(name)以解析 openDingTalkId"},
+ record_dir, name, user_id, content, file_path)
+ open_id = resolve_open_id(name, user_id)
+ print(f"[INFO] 接收人 openDingTalkId: {open_id}")
+ send_file(open_id, file_path)
+ return _record_and_return({"success": True, "message": f"已向「{name}」发送文件"},
+ record_dir, name, user_id, content, file_path)
+ except Exception as e:
+ return _record_and_return({"success": False, "message": str(e)},
+ record_dir, name, user_id, content, file_path)
+
+
+def main(messages, record_dir=""):
+ """影刀自定义指令「37du钉钉单聊推送」调用入口。
+ 传入消息列表,每项为五元组 (消息类型, 姓名, 工号, 消息内容, 文件地址),
+ 缺省字段按空处理:
+ msg_type 'text'/'文本' 或 'file'/'文件'
+ name 接收人姓名
+ user_id 接收人工号
+ content 消息内容(文本类型必填)
+ file_path 文件地址(文件类型必填,可留空)
+ record_dir(可选):非空时每条结果写入 /YYYY-MM-DD/推送记录.csv,
+ 并把记录文件路径写入影刀全局变量 push_record_path,供流程自行处理失败名单。
+ 逐条发送,返回: {"success": bool, "message": str, "results": [...]}
+ """
+ results = []
+ for item in messages or []:
+ if isinstance(item, dict):
+ msg_type = item.get("msg_type") or item.get("消息类型") or ""
+ name = item.get("name") or item.get("姓名") or ""
+ user_id = item.get("user_id") or item.get("工号") or ""
+ content = item.get("content") or item.get("消息内容") or ""
+ file_path = item.get("file_path") or item.get("文件地址") or ""
+ else:
+ msg_type = item[0] if len(item) > 0 else ""
+ name = item[1] if len(item) > 1 else ""
+ user_id = item[2] if len(item) > 2 else ""
+ content = item[3] if len(item) > 3 else ""
+ file_path = item[4] if len(item) > 4 else ""
+ results.append(send_message(msg_type, name, user_id, content, file_path, record_dir))
+ ok = sum(1 for r in results if r.get("success"))
+ _write_record_path_to_glv(record_dir)
+ return {
+ "success": ok == len(results),
+ "message": f"共 {len(results)} 条,成功 {ok},失败 {len(results) - ok}",
+ "results": results,
+ }
+
+
+if __name__ == "__main__":
+ # 本地自测/接口说明:不实际发送。业务脚本请 import 后调用
+ # main([("文本", "姓名", "工号", "消息内容", ""),
+ # ("文件", "姓名", "工号", "", r"文件绝对路径")])
+ messages = [
+ {"msg_type": "text", "name": "李泽燕", "user_id": "37001979", "content": "你好,测试一条由ai推送的文本消息"},
+ # {"msg_type": "file", "name": "李泽燕", "user_id": "37001979", "file_path": r"C:\Users\admin\Desktop\test.xlsx"},
+ ]
+ result = main(messages)
+ print(result)
diff --git a/yingdao/share/dingtalk_sender.py b/yingdao/share/dingtalk_sender.py
index 63ab437..d043078 100644
--- a/yingdao/share/dingtalk_sender.py
+++ b/yingdao/share/dingtalk_sender.py
@@ -1,7 +1,13 @@
# -*- coding: utf-8 -*-
"""
+【已废弃 / DEPRECATED】
+钉钉联系人(单聊)文本推送已改由 yingdao/share/dingtalk_dws_push.py 替代
+(DWS CLI 直连:免 OCR、免 pyautogui/rapidocr 等重型依赖,带 50 条/分钟限流与推送记录,
+glv['messages'] 形状为 5 元组 (msg_type, name, user_id, content, file_path))。
+本文件保留仅作参考 / 兼容旧流程,不推荐新流程使用;新需求请用 dingtalk_dws_push.py。
+
@FileName: dingtalk_sender.py
-@Description: 钉钉联系人推送自定义指令(影刀编码版 Python 模块源码,单一真源)。
+@Description: 钉钉联系人推送自定义指令(影刀编码版 Python 模块源码,单一真源,已废弃)。
作为「37du钉钉推送」影刀自定义指令的模块源码,
供所有需要钉钉单人推送的影刀脚本/流程复用(周考勤、请假审批、加班审批、人事变动等),
避免每个脚本各自内联 OCR 视觉发送逻辑。
diff --git a/yingdao/share/roster_export.py b/yingdao/share/roster_export.py
index c30c056..183aaa0 100644
--- a/yingdao/share/roster_export.py
+++ b/yingdao/share/roster_export.py
@@ -84,6 +84,10 @@ 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 = "集团" # 组织树根节点
@@ -516,9 +520,13 @@ def _export_one_status(page, status, download_dir, template_name, leave_start=No
def export_roster(download_dir=None, output_path=None, template_name=None,
- statuses=None, leave_start=None, leave_end=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)
@@ -526,6 +534,7 @@ def export_roster(download_dir=None, output_path=None, template_name=None,
statuses: 需导出的在职状态列表,如 ["在职"] / ["离职"] / ["在职","离职"]
(默认 DEFAULT_STATUSES)
leave_start / leave_end: 离职时间范围 "YYYY-MM-DD"(离职状态时生效;缺省自动计算)
+ ttl: 缓存有效期(秒),默认 DEFAULT_TTL_SECONDS(15 分钟);传 0 表示总是重新导出
Returns:
合并后的花名册文件路径
@@ -534,6 +543,15 @@ def export_roster(download_dir=None, output_path=None, template_name=None,
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 = ""