feat: 新增多个业务需求脚本与共享模块
新增内容包括: 1. 7个业务需求占位文档目录与README 2. 共享OA登录、钉钉机器人推送工具模块 3. 雇主险变更清单导出脚本 4. 考勤月报封存检查两个检查脚本 5. 重庆社保停保导入名单生成脚本
This commit is contained in:
@@ -0,0 +1,342 @@
|
||||
# 影刀脚本开发指南(yingdao/)
|
||||
|
||||
本文档沉淀 `yingdao/` 目录下影刀(Yingdao)RPA 脚本的统一编写方式:共享指令模块、业务脚本写法、以及各模块之间的通信约定。后续新增/拆解影刀脚本时以此为准。
|
||||
|
||||
## 1. 体系总览
|
||||
|
||||
影刀体系采用 **「共享指令模块 + 单文件业务脚本」** 架构:
|
||||
|
||||
- 公共能力(登录、钉钉推送)抽成**独立指令模块**,放在 `share/` 目录,在影刀中注册为自定义指令,单一真源;
|
||||
- 每个业务流程是一个**单文件 Python 脚本**(如请假、加班、考勤异常、排班异常识别),按业务需求单编号放在 `XQ00xx/` 目录(与 `docs/需求单/XQ00xx` 一一对应,便于按需求单检索与交付);
|
||||
- **单文件自包含是硬性原则**:业务脚本与共享指令模块各自独立运行,业务脚本**不 import 任何共享指令模块、不做 sys.path 注入、不做目录向上查找**;
|
||||
- 模块之间通过**文件(共享登录态)+ 影刀全局变量(消息/路径)** 弱耦合通信,做到「登录一次、全局复用、消息生成与发送解耦」。
|
||||
|
||||
## 2. 目录结构
|
||||
|
||||
```
|
||||
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 联系人单聊推送
|
||||
│ └── work_communication.py # 「OA工作沟通推送」工作沟通推送(入口 send_work_communication / main)
|
||||
├── XQ0001 排班异常识别/
|
||||
│ ├── transfer_roster_export.py # 步骤2-调动:调动台账自定义导出(排班异常识别导出模板)
|
||||
│ ├── pre_entry_roster_export.py # 步骤2-预入职:预入职台账自定义导出(同上模板)
|
||||
│ └── shift_abnormal_check.py # 步骤3:读两台账+排班接口识别人 → 按店长分组构造工作沟通消息
|
||||
├── XQ0002 雇主险增减操作/
|
||||
│ ├── roster_filter.py # 步骤2:筛选复制(源表缺失时复用「37du花名册导出」)
|
||||
│ ├── export_change_sheet.py # 变更表导出
|
||||
│ ├── employer_insurance_schedule.py # 步骤2:调度(生成增员/减员导入文件)
|
||||
│ └── add_sub_import.py # 步骤3:增减员导入(HR「待增减人员」页面上传)
|
||||
├── XQ0003 EHR系统请假流程审核/
|
||||
│ └── leave_approval.py # 请假审批 —— 自包含范例
|
||||
├── XQ0004 EHR系统加班流程审核/
|
||||
│ └── overtime_approval.py # 加班审批
|
||||
├── XQ0005 银行卡检查/
|
||||
│ └── bank_card_check.py # 银行卡检查
|
||||
├── XQ0006 EHR系统周考勤异常处理/
|
||||
│ └── attendance_abnormal.py # 周考勤异常
|
||||
├── XQ0007 OA系统社保增减名单梳理/
|
||||
│ └── social_change.py # 社保增减名单核对
|
||||
├── XQ0008 重庆社保增减员导入名单制作/
|
||||
│ └── 说明.md # *占位,需求未实现*
|
||||
├── XQ0009 门店上月请休假异常人员名单梳理/
|
||||
│ └── absence_analysis.py # 缺勤分析(读「37du花名册导出」指令输出的固定路径文件)
|
||||
├── XQ0010 EHR系统月考勤异常处理/
|
||||
│ └── attendance_abnormal_monthly.py # 月考勤异常
|
||||
├── XQ0011 考勤月报封存检查/
|
||||
│ └── 说明.md # *占位,需求未实现*
|
||||
├── XQ0012 EHR预支及支付报酬自动发起ERP付款申请/
|
||||
│ └── 说明.md # *占位,需求未实现*
|
||||
├── XQ0013 社保费用申报导出并汇总/
|
||||
│ └── 说明.md # *占位,需求未实现*
|
||||
├── XQ0014 社保系统增减员办理/
|
||||
│ └── 说明.md # *占位,需求未实现*
|
||||
├── XQ0015 参保成功及异常告知书制作与下发/
|
||||
│ └── notice_mail_merge.py # 参保/停保名单 → 按模板批量生成告知书 Word+PDF(另覆盖 XQ0016 社保转移告知书)
|
||||
├── XQ0016 社保转移告知书制作与下发/
|
||||
│ └── 说明.md # *已由 XQ0015/notice_mail_merge.py 覆盖,无需独立脚本*
|
||||
├── XQ0017 入职人事手续办理/
|
||||
│ └── 说明.md # *占位,需求未实现*
|
||||
├── XQ0018 调动人事手续跟进/
|
||||
│ └── 说明.md # *占位,需求未实现*
|
||||
├── XQ0019 离职人事手续跟进与检查/
|
||||
│ └── 说明.md # *占位,需求未实现*
|
||||
├── XQ0020 EHR系统离职电子签流程审核/
|
||||
│ └── resign_e_sign_approval.py # 离职电子签审批
|
||||
└── README.md # 本文档
|
||||
```
|
||||
|
||||
## 目录规则
|
||||
|
||||
- **编号对齐**:影刀 `yingdao/XQ00xx <流程名称>/` 与 `docs/需求单/XQ00xx <流程名称>/` **一一对应**,目录名含需求名称,命名与 `docs/需求单.md` 完全一致,无需对照即可识别。
|
||||
- **实现状态**:
|
||||
- 已实现:脚本直接放入 `XQ00xx/`,多步骤拆分多个单文件(每个文件独立,不互相 `import`);
|
||||
- 未实现:目录已创建,仅放 `说明.md`(记录关联文档+编写提示),后续开发直接把 `.py` 放入即可;
|
||||
- 已覆盖:一个脚本覆盖多个需求单(如 `XQ0015/notice_mail_merge.py` 同时做 XQ0015 + XQ0016),被覆盖的目录保留占位 `说明.md` 说明覆盖关系,不重复放代码;
|
||||
- **共享指令**:`share/` 目录独立顶层,所有流程以**影刀指令方式**引用,不做 Python `import`,单一真源。
|
||||
- **单文件原则**:业务脚本必须单文件自包含,依赖声明/核心逻辑/异常处理/入口全部内聚,不拆分冗余子模块。
|
||||
|
||||
## 3. 共享路径与约定(与 app 版统一,见 app/common/app_paths.py)
|
||||
|
||||
所有模块统一使用固定路径,**禁止各自散落配置**:
|
||||
|
||||
| 用途 | 路径 |
|
||||
|---|---|
|
||||
| 共享配置 | `%LOCALAPPDATA%\37duAutomation\.env`(本地开发兼容当前工作目录 `.env`) |
|
||||
| OA 登录态 | `%LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json` |
|
||||
| HR 登录态 | `%LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json` |
|
||||
| 花名册文件(「37du花名册导出」指令输出) | `D:\资料\人资\花名册\花名册.xlsx` |
|
||||
|
||||
## 4. 共享指令模块(share/,各自独立运行)
|
||||
|
||||
### 4.1 oa_login.py(「37duOA登录」)
|
||||
|
||||
- 环境变量:`oa_login_url`、`oa_target_url_keyword`、`oa_login_username`、`oa_login_password`、`oa_validate_url`(可选)
|
||||
- 会话校验接口(默认):`sysNotifyTodo.do?method=sumTodoCount`,cookies 有效时返回 JSON、失效时被重定向返回 HTML
|
||||
- 入口:`main(args)`、`ensure_login(force=False)`、`_load_shared_env()`
|
||||
- 写 `oa_cookies.json`;流程全局变量 `login_state`
|
||||
- 依赖:`DrissionPage requests python-dotenv`
|
||||
|
||||
### 4.2 hr_login.py(「37duHR登录」)
|
||||
|
||||
- 环境变量:`hr_login_url`、`hr_target_url_keyword`、`hr_login_username`、`hr_login_password`、`hr_validate_url`(可选)、`hr_captcha_debug_dir`(可选)
|
||||
- 滑块验证码登录;会话校验接口(默认):`PtUsers.mc?method=getCurUserInfo`
|
||||
- 入口:`main(args)`;写 `hr_cookies.json`;流程全局变量 `login_state`
|
||||
- 依赖:`DrissionPage requests python-dotenv opencv-python numpy Pillow`
|
||||
|
||||
### 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}`
|
||||
- HMAC-SHA256 加签 + Base64 + URL 编码,HTTP webhook 推送 Markdown;默认 webhook/secret 内联
|
||||
- `env='dev'` 走测试环境机器人(`DEV_WEBHOOK`/`DEV_SECRET`),默认 `prod`
|
||||
- 零第三方依赖(仅标准库)
|
||||
|
||||
### 4.5 dingtalk_sender.py(「37du钉钉推送」)
|
||||
|
||||
- 入口:`main(messages, record_dir="")`,直接传列表,每项为 `(search_keyword, text, verify_keyword)` 元组(`verify_keyword` 可省略):
|
||||
- `search_keyword`:联系人搜索关键字(支持工号,避免同名误选)
|
||||
- `text`:消息内容
|
||||
- `verify_keyword`:会话标题校验关键字(可选,钉钉标题显示姓名,用工号搜索时传姓名)
|
||||
- `record_dir`(可选):推送记录保存目录,非空时每次推送写入 `<record_dir>/YYYY-MM-DD/推送记录.csv`
|
||||
(列=推送时间, 工号, 姓名, 结果, 消息摘要);空串=不记录。按场景传入,不写死
|
||||
- 失败名单:推送结束后把推送记录文件路径写入影刀全局变量 `push_record_path`
|
||||
(形如 `<record_dir>/YYYY-MM-DD/推送记录.csv`,未传 `record_dir` 时为空串),
|
||||
流程自行读取该记录文件,筛出「结果=失败」的行做后续处理(如拖「37du钉钉群机器人推送」指令发群及时通知)
|
||||
- 仅推送联系人(单聊);群消息改用 `dingtalk_robot.py`(「37du钉钉群机器人推送」指令)推送
|
||||
- 返回 `{"success": bool, "message": str, "results": [...]}`
|
||||
- OCR 视觉方案:查找钉钉窗口 → 多策略激活前台 → Ctrl+Shift+F 搜索联系人 → OCR 定位输入框 → 粘贴 → 回车
|
||||
- 依赖:`pyautogui pywin32 pyperclip psutil Pillow numpy rapidocr`(使用 rapidocr 3.x)
|
||||
|
||||
### 4.6 work_communication.py(「OA工作沟通推送」)
|
||||
|
||||
- 独立模块(`yingdao/share/`,对应 app 版 `app/service/hrbp/oa/common/` + `oa_api/work_communication.py`),单文件自包含,不 import 共享模块
|
||||
- OA 工作沟通一键推送:搜索接收人(工号/姓名)→ 上传附件 → 提交工作沟通,返回沟通文档 ID(fdId)
|
||||
- 入口:`send_work_communication(receiver_keywords, subject, content, attachment_paths, creator_id, category)`(一键推送)、
|
||||
`main(messages)`(影刀指令入口,逐条循环发送;`messages` 结构同 `oa_work_communications` 全局变量)
|
||||
- 接收人支持多个(工号/姓名),附件支持多个(任一失败整体失败,不发送部分数据)
|
||||
- 登录态直接读取「37duOA登录」写出的 `oa_cookies.json`;缺失/失效时提示先运行登录指令(不补登)
|
||||
- 依赖:`DrissionPage requests`
|
||||
|
||||
### 4.7 notice_mail_merge.py(「告知书制作与下发」)
|
||||
|
||||
- 独立模块(`yingdao/XQ0015 参保成功及异常告知书制作与下发/`,对应 app 版 `app/service/hrbp/oa/social_notice/`),单文件自包含,不 import 共享模块
|
||||
- 读取 `D:\资料\人资\告知书制作与下发` 下包含「参保与停保名单」的 xlsx(表头第 3 行,主表字段到「费用」列为止 49 列),筛选「参保名单」sheet
|
||||
- 按三类模板规则逐人生成 Word 告知书并转 PDF(WPS 文字 COM):
|
||||
- 员工参与社会保险告知书(办理状态=已参 & 参保类型=新参保)
|
||||
- 参保异常告知书(办理状态=参保失败 & 参保类型=新参保)
|
||||
- 社保转移告知书(办理状态=已参 & 参保类型=转移参保)
|
||||
- 公共过滤:人员类型不含「职能」、二级部门包含「经营中心」或「石桥铺会馆」、办理时间为当月
|
||||
- 入口:`main()`(生成当月全部 + 构造 OA 工作沟通数据)、`generate_notices(excel_path, output_dir, ym)`(函数传参)、`build_work_communication_data(excel_path, output_dir, ym, roster_path)`(数据构造)
|
||||
- 输出:按(二级部门,四级部门)分组合并,同一部门+类型的所有员工合并为一份;
|
||||
文件名 = `二级部门_四级部门_告知书类型.docx/pdf`,同一部门内多人逐页排列
|
||||
- 环境变量:`notice_base_dir`(默认 `D:\资料\人资\告知书制作与下发`)、`notice_output_dir`(默认 `{notice_base_dir}\输出`)
|
||||
- 输出目录写入影刀全局变量 `notice_output_dir`;异常时写 `notice_error`
|
||||
- **OA 工作沟通数据构造**:根据命中员工工号查询店长/人事(花名册 `{notice_base_dir}\员工花名册.xlsx`,石桥铺会馆人事固定 37001302 梁敏),构造 2 条推送数据:
|
||||
1. 员工参与社会保险 + 参保异常合并一条;
|
||||
2. 社保转移单独一条;
|
||||
每条含 `subject/content(HTML)/attachment_paths(仅PDF)/receivers(店长+人事工号去重)/category`,
|
||||
正文月份按名单年月动态替换,关键词(告知书名、期限日期)自动标红;写入影刀全局变量 `oa_work_communications`(列表),供「OA工作沟通推送」指令逐条循环发送(`yingdao/share/work_communication.py`)
|
||||
- 占位符仅允许纯变量(如 `{{姓名}}`、`{{下月}}`、`{{一次性扣款}}`),脚本自动兼容旧写法(`{{当前月+1}}`/`{{费用*2}}`)
|
||||
- 依赖:`openpyxl python-docx pywin32`
|
||||
|
||||
## 5. 模块通信(弱耦合:文件 + 全局变量)
|
||||
|
||||
### 5.1 登录态通信(文件级,登录一次全局复用)
|
||||
|
||||
```
|
||||
「37duOA登录」指令(独立运行) ──写──▶ %LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json
|
||||
▲
|
||||
│ 只读文件,不 import、不补登
|
||||
▼
|
||||
业务脚本(XQ00xx 下的单文件)──读── 构建 SessionPage / ChromiumPage
|
||||
```
|
||||
|
||||
业务脚本侧的标准写法(**单文件自包含,不做路径查找、不 import 共享模块**):
|
||||
|
||||
1. **读共享 cookies 文件**:
|
||||
|
||||
```python
|
||||
def _load_shared_oa_cookies():
|
||||
"""读取共享 OA 登录 cookies(由「37duOA登录」指令写入)。"""
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
return json.load(f) or None
|
||||
```
|
||||
|
||||
2. **缺失/失效时直接友好提示先运行登录指令**(不在脚本内补登、不抛堆栈,用 SystemExit):
|
||||
|
||||
```python
|
||||
def _ensure_oa_cookies(force=False):
|
||||
"""确保存在有效登录态文件;缺失/失效时提示先运行「37duOA登录」指令。"""
|
||||
if not force and _load_shared_oa_cookies():
|
||||
return True
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
raise SystemExit(
|
||||
"未找到 OA 登录态文件(oa_cookies.json)。\n"
|
||||
"请先在影刀流程开头拖入「37duOA登录」指令完成登录,"
|
||||
"或本地运行: python yingdao/share/oa_login.py\n"
|
||||
"登录完成后再运行本流程。")
|
||||
raise SystemExit(
|
||||
"OA 登录态已失效(oa_cookies.json 已过期)。\n"
|
||||
"请先重新运行「37duOA登录」指令完成登录,"
|
||||
"或本地运行: python yingdao/share/oa_login.py\n"
|
||||
"重新登录后再运行本流程。")
|
||||
```
|
||||
|
||||
3. **会话有效性校验**(轻量接口,返回 JSON 视为有效、HTML 视为失效):
|
||||
|
||||
```python
|
||||
def is_session_valid(session, subject="请假"):
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
```
|
||||
|
||||
### 5.2 消息/路径通信(全局变量级,生成与发送解耦)
|
||||
|
||||
业务脚本只负责**生成消息文本**,不内联发送;通过写影刀全局变量把结果交给流程,由推送指令发送:
|
||||
|
||||
```python
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
```
|
||||
|
||||
各脚本的全局变量约定:
|
||||
|
||||
| 脚本 | 全局变量 | 值类型 | 消费方 |
|
||||
|---|---|---|---|
|
||||
| 请假审批 `XQ0003/leave_approval` | `messages` | **文本列表**(按结果类型逐条:通过/校验不通过/人工复核/失败 各一条) | 「37du钉钉群机器人推送」指令 |
|
||||
| 加班审批 `XQ0004/overtime_approval` | `messages` | **文本列表**(按结果类型逐条:通过/校验不通过/人工复核/超期/失败 各一条) | 「37du钉钉群机器人推送」指令 |
|
||||
| 周考勤异常 `XQ0006/attendance_abnormal` | `messages` | 元组列表 `[(search_keyword, text, verify_keyword), ...]` | 「37du钉钉推送」指令 |
|
||||
| 月考勤异常 `XQ0010/attendance_abnormal_monthly` | `attendance_check_save_path` | 文件路径 | 流程后续处理 |
|
||||
| 缺勤分析 `XQ0009/absence_analysis` | `absence_save_path` | 文件路径 | 流程后续处理 |
|
||||
| 雇主险增减员导入 `XQ0002/add_sub_import` | `messages` | **块格式分组列表** `[{title, blocks, status}]`(有异常:异常明细 error;无异常:完成提示 success) | 「37du钉钉群机器人推送」指令 |
|
||||
| 告知书制作与下发 `XQ0015/notice_mail_merge` | `notice_output_dir` | 告知书输出目录路径(当月目录) | 流程后续处理 |
|
||||
| 告知书制作与下发 `XQ0015/notice_mail_merge` | `oa_work_communications` | **工作沟通推送数据列表**(每条含 subject/content/attachment_paths/receivers/category) | 「OA工作沟通推送」指令逐条循环发送 |
|
||||
| 排班异常识别 `XQ0001/shift_abnormal_check` | `messages` | **工作沟通推送数据列表**(按店长分组,每条含 receivers(店长工号)/subject/content/category) | 「OA工作沟通推送」指令逐条循环发送 |
|
||||
| 排班异常识别 `XQ0001/shift_abnormal_check` | `shift_abnormal_rows` | 异常名单行列表(留档/后续处理) | 流程后续处理 |
|
||||
| 登录指令(oa/hr) | `login_state` | 布尔 | 流程判断是否继续 |
|
||||
|
||||
### 5.3 消息推送完整链路(请假脚本范例)
|
||||
|
||||
```
|
||||
main(push_type="group", target=None)
|
||||
│
|
||||
├─ group(默认):_set_glv("messages", 纯文本) ──▶ 流程拖「37du钉钉群机器人推送」指令
|
||||
│
|
||||
└─ person:main() 返回 [{target, text}, ...] ──▶ 流程拖「37du钉钉推送」指令走 OCR 单聊
|
||||
```
|
||||
|
||||
- **group 模式**:`messages` 全局变量是文本列表(每项一条,按结果类型分组),直接交给群机器人指令逐条发送
|
||||
- **person 模式**:需要单聊目标时,用 `main()` 的返回值(含 `target` 的字典列表)交给钉钉推送指令
|
||||
|
||||
### 5.4 按需启动浏览器(请假脚本范例)
|
||||
|
||||
所有**纯接口操作**(查待办、拉表单、会话校验)只用 `SessionPage`,不启动浏览器;仅当**确实有单据**时才启动 `ChromiumPage`(SSO 跳转解析、真实审批点击、结果弹窗):
|
||||
|
||||
```
|
||||
build_session(纯 SessionPage,不开浏览器)
|
||||
└─ 拉待办列表
|
||||
├─ 无单据 → 直接生成「暂无待审批的XX单据」消息返回(全程不闪浏览器)
|
||||
└─ 有单据 → build_browser(ChromiumPage)→ SSO 解析 / 审批 / 弹窗
|
||||
```
|
||||
|
||||
## 6. 业务脚本统一写法(单文件自包含模板)
|
||||
|
||||
推荐按以下骨架编写(参考 `XQ0003/leave_approval.py`):
|
||||
|
||||
```python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: xxx.py
|
||||
@Description: 业务说明;单文件自包含,不 import 共享指令模块,只读 cookies 文件、只写全局变量。
|
||||
...(文件头:约定、环境变量、全局变量、依赖、入口)
|
||||
"""
|
||||
|
||||
# 0) 全局变量兜底 + logger
|
||||
# 1) _set_glv(name, value) 写全局变量(try/except 容错)
|
||||
# 2) 常量:共享路径、接口 URL、开关、默认保存目录
|
||||
# 3) 登录态:_load_shared_cookies / _ensure_cookies(缺失只报错提示,不补登)
|
||||
# 4) 会话:build_session(纯 SessionPage)/ build_browser(有单据才 ChromiumPage)
|
||||
# 5) 数据层:get_documents / get_xxx_detail(只用 SessionPage)
|
||||
# 6) 业务层:validate_doc / generate_report(纯逻辑)
|
||||
# 7) 流程编排:run_flow(subject, validate_doc, generate_report, push_type="group", target=None)
|
||||
# - build_session 拉待办 → 无单据直接生成提示消息返回
|
||||
# - 有单据才 build_browser → SSO 解析 → 校验 → 审批 → 报告
|
||||
# 8) 入口:main(push_type="group", target=None) 返回消息,并 _set_glv 写全局变量
|
||||
```
|
||||
|
||||
## 7. 影刀集成步骤(新建指令时)
|
||||
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码(如 `oa_login`)→ 添加 Python 模块;
|
||||
2. 把 `yingdao/share/` 下对应文件内容粘贴进指令的 Python 模块(或直接以该文件为模块源码);
|
||||
3. 增加流程参数(如 `force`、`params`、`text`);
|
||||
4. 保存并「发版」→ 在需要登录/推送的应用中「获取指令」并安装;
|
||||
5. 在每个应用流程开头拖入登录指令,业务脚本执行后读全局变量,再拖入推送指令。
|
||||
|
||||
## 8. 代码编写要点
|
||||
|
||||
- **单文件自包含**:业务脚本不得 import 共享指令模块、不得做 sys.path 注入或向上目录查找;共享模块各自独立运行
|
||||
- **先加载 .env 再读环境变量**:登录指令内 `_load_shared_env()` 必须在读取环境变量前调用
|
||||
- **返回 JSON 安全 dict**:指令入口统一 `{"success": bool, "message": str}`
|
||||
- **logger 兜底**:`_PrintLogger` 简易实现,避免依赖第三方日志
|
||||
- **cookies 缺失只提示不补登**:业务脚本内不调用登录模块,缺失/失效时报错并提示先运行登录指令
|
||||
- **消息生成与发送解耦**:业务脚本只产出文本/列表写全局变量,发送一律由推送指令完成
|
||||
|
||||
## 9. 依赖清单
|
||||
|
||||
| 用途 | pip 包 |
|
||||
|---|---|
|
||||
| OA/HR 登录、浏览器自动化 | `DrissionPage requests python-dotenv` |
|
||||
| HR 滑块验证码 | 另加 `opencv-python numpy Pillow` |
|
||||
| OCR 钉钉单聊推送 | `pyautogui pywin32 pyperclip psutil Pillow numpy rapidocr`(须用 rapidocr 3.x,勿用 rapidocr-onnxruntime,避免与 numpy 2.x 冲突) |
|
||||
| 钉钉群机器人推送 | 无(仅标准库) |
|
||||
| 告知书制作与下发 | `openpyxl python-docx pywin32` |
|
||||
@@ -0,0 +1,467 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: pre_entry_roster_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-27
|
||||
@Description: 预入职台账自定义导出(排班异常识别 步骤2-预入职,影刀版,单文件自包含)。
|
||||
复用「37duHR登录」指令写入的共享 cookies,通过 DrissionPage 浏览器自动化操作:
|
||||
进入预入职台账页 -> 组织机构(集团) -> 点击「已入职」-> 更多搜索
|
||||
-> 输入预入职日期(近30天)-> 筛选 -> 自定义导出 -> 选择模板「排班异常识别导出」
|
||||
-> 确认导出,接收下载文件重命名为《预入职台账.xlsx》(表头在第 2 行)。
|
||||
与调动台账导出(transfer_roster_export.py)流程基本一致,仅页面地址、tab 文案、
|
||||
日期占位符、文件名不同。
|
||||
@Version: 1.0.0
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage
|
||||
|
||||
登录(共享登录态,本脚本仅读取共享 cookies 文件,不 import 任何共享模块):
|
||||
「37duHR登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json;
|
||||
缺失/失效时先拖入「37duHR登录」指令完成登录,再运行本流程。
|
||||
|
||||
运行:直接执行本文件即可(会弹出浏览器窗口,请勿关闭)。
|
||||
输出目录默认 D:\\资料\\人资\\排班异常识别,可用环境变量 pre_entry_output_dir 覆盖。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import traceback
|
||||
from datetime import date, timedelta
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:必须预先装齐,不懒加载) ====================
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install DrissionPage\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置(与 app 版统一) ====================
|
||||
_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')
|
||||
# HR 登录态:由「37duHR登录」共享指令写入
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# 预入职台账页地址 & 导出模板(与 app/service/hrbp/ehr/common/config.py 一致)
|
||||
PRE_ENTRY_ROSTER_URL = ("https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-01818-07406&nworktoday-40175-24311|/RedseaPlatform/hrRoster/10fe9cd6-b094-11ea-b588-14187743d052/getCustomCommonList.mc?clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=%E9%A2%84%E5%85%A5%E8%81%8C%E5%8F%B0%E8%B4%A6")
|
||||
TEMPLATE_SHIFT_ABNORMAL = "排班异常识别导出"
|
||||
|
||||
# 流程步骤所用文案常量(aa.md 提供)
|
||||
TAB_ORG = "组织机构" # 左侧「组织机构」tab
|
||||
TREE_GROUP = "集团" # 组织树根节点
|
||||
TAB_ONBOARDED = "已入职" # 预入职台账「已入职」tab(只导已入职人员)
|
||||
MENU_CUSTOM_EXPORT = "自定义导出"
|
||||
BTN_CONFIRM = "确认导出"
|
||||
BTN_MORE_SEARCH = "更多搜索"
|
||||
PRE_ENTRY_RANGE_PLACEHOLDER = "请选择预入职日期"
|
||||
|
||||
# 通用等待秒数
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
DOWNLOAD_FINISH_TIMEOUT = 300 # 等待下载完成
|
||||
RETRY_TIMES = 3 # 单次导出失败重试次数(AGENTS.md:最大重试3次)
|
||||
|
||||
# 输出目录 & 文件名
|
||||
OUTPUT_DIR = os.getenv("pre_entry_output_dir") or r"D:\资料\人资\排班异常识别"
|
||||
SAVE_NAME = "预入职台账.xlsx"
|
||||
|
||||
|
||||
# ==================== 日志(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)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _load_shared_hr_cookies():
|
||||
"""读取共享 HR cookies(由「37duHR登录」指令写入)。"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
return json.load(f) or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
"""确保存在有效的 HR 登录态;缺失时提示先运行「37duHR登录」指令。"""
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令完成登录,"
|
||||
"或本地先运行 python yingdao/share/hr_login.py")
|
||||
|
||||
|
||||
# ==================== 预入职日期范围(近30天) ====================
|
||||
def get_pre_entry_range(today: date = None, days: int = 30) -> tuple:
|
||||
"""计算预入职日期筛选范围,返回 (开始日期, 结束日期)。"""
|
||||
today = today or date.today()
|
||||
start = today - timedelta(days=days - 1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 元素定位辅助(DrissionPage) ====================
|
||||
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 _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 _find_more_search_button(page):
|
||||
"""定位当前活跃 tab 的「更多搜索」按钮(仅取可见的那个,避免展开错 tab)。"""
|
||||
btns = page.eles('css:button.search-more-condition-btn', timeout=3)
|
||||
if not btns:
|
||||
btns = page.eles('css:.demo-search-more .el-popover__reference', timeout=2)
|
||||
if not btns:
|
||||
btn = page.ele('xpath://button[.//span[contains(normalize-space(.),"更多搜索")]]', timeout=2)
|
||||
return btn if _is_displayed(btn) else None
|
||||
for b in btns:
|
||||
if _is_displayed(b):
|
||||
return b
|
||||
logger.warning("未找到可见的「更多搜索」按钮(DOM 中共 %d 个)", len(btns))
|
||||
return None
|
||||
|
||||
|
||||
def _open_more_search(page):
|
||||
"""展开当前活跃 tab 的「更多搜索」popover,返回其内容元素;失败返回 None。"""
|
||||
btn = _find_more_search_button(page)
|
||||
if not btn:
|
||||
return None
|
||||
for _ in range(3):
|
||||
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 popover
|
||||
try:
|
||||
btn.run_js('this.click();')
|
||||
except Exception:
|
||||
btn.click()
|
||||
time.sleep(WAIT_MID)
|
||||
logger.warning("「更多搜索」未能展开")
|
||||
return None
|
||||
|
||||
|
||||
def _click_filter(page, popover):
|
||||
"""点击活跃 tab「更多搜索」弹层底部的「筛选」按钮(限定在弹出容器内)。"""
|
||||
result = popover.run_js(
|
||||
'var btns=this.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";'
|
||||
)
|
||||
if result != "clicked":
|
||||
raise RuntimeError(f"点击「筛选」失败:{result}")
|
||||
logger.info("已点击「筛选」(JS click)")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _find_visible_range_input(page, placeholder):
|
||||
"""在页面级查找可见的预入职日期选择器(页面宽/窄布局不同,取可见的第一个)。"""
|
||||
rngs = page.eles(f'css:div.split-datetime-range[placeholder="{placeholder}"]', timeout=3)
|
||||
for r in rngs:
|
||||
if _is_displayed(r):
|
||||
return r
|
||||
return None
|
||||
|
||||
|
||||
def _fill_range(page, rng, start, end):
|
||||
"""填入日期范围并回车确认。"""
|
||||
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("未找到预入职日期起止输入框")
|
||||
start_input.input(start, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
end_input.input(end, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
logger.info("预入职日期已设置:%s ~ %s", start, end)
|
||||
|
||||
|
||||
def _set_pre_entry_date_range(page, start=None, end=None):
|
||||
"""设置「预入职日期」筛选范围(近30天)并应用筛选。"""
|
||||
if not start or not end:
|
||||
start, end = get_pre_entry_range()
|
||||
logger.info("设置预入职日期范围:%s ~ %s", start, end)
|
||||
popover = _open_more_search(page)
|
||||
if not popover:
|
||||
raise RuntimeError("「更多搜索」未能展开,无法设置预入职日期")
|
||||
rng = _find_visible_range_input(page, PRE_ENTRY_RANGE_PLACEHOLDER)
|
||||
if not rng:
|
||||
rng = popover.ele(
|
||||
f'css:div.split-datetime-range[placeholder="{PRE_ENTRY_RANGE_PLACEHOLDER}"]', timeout=5)
|
||||
if not rng or not _is_displayed(rng):
|
||||
raise RuntimeError("未找到可见的「预入职日期」选择器")
|
||||
_fill_range(page, rng, start, end)
|
||||
_click_filter(page, popover)
|
||||
|
||||
|
||||
# ==================== 打开台账页并确保登录态 ====================
|
||||
def _ensure_logged_in(page):
|
||||
"""访问预入职台账页面;若被重定向到登录页则提示先完成「37duHR登录」。"""
|
||||
page.get(PRE_ENTRY_ROSTER_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise RuntimeError(
|
||||
"HR 登录态已失效。\n"
|
||||
"请先重新运行「37duHR登录」指令,或本地执行 python yingdao/share/hr_login.py\n"
|
||||
"重新登录后再运行本流程。")
|
||||
logger.info("已进入预入职台账页面:%s", page.url)
|
||||
|
||||
|
||||
# ==================== 预入职台账导出主流程(aa.md 步骤) ====================
|
||||
def _select_org_tree(page):
|
||||
"""切换到组织树并选中「集团」。"""
|
||||
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)
|
||||
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 _click_onboarded_tab(page):
|
||||
"""点击「已入职」tab,只保留已入职的预入职人员。"""
|
||||
tab = page.ele(f'xpath://div[contains(@class,"tab-info")]//*[normalize-space(.)="{TAB_ONBOARDED}"]',
|
||||
timeout=10)
|
||||
if not tab:
|
||||
_click_text(page, TAB_ONBOARDED)
|
||||
return
|
||||
tab.click()
|
||||
logger.info("已点击「%s」tab", TAB_ONBOARDED)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
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
|
||||
btn = page.ele('xpath://button[normalize-space(.)="自定义导出"]', timeout=15)
|
||||
if not btn:
|
||||
btn = page.ele('xpath://*[contains(@class,"btn") and normalize-space(.)="自定义导出"]', timeout=5)
|
||||
if not btn:
|
||||
raise RuntimeError("未找到「自定义导出」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「自定义导出」")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _select_template(page, template_name=TEMPLATE_SHIFT_ABNORMAL):
|
||||
"""选择导出模板「排班异常识别导出」。"""
|
||||
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("未找到「模板」下拉框")
|
||||
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("模板下拉面板未能展开")
|
||||
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(download_dir, before, timeout=DOWNLOAD_FINISH_TIMEOUT):
|
||||
"""等待下载文件生成并大小稳定,返回下载文件路径。"""
|
||||
logger.info("等待下载文件生成(最多 %ds)...", timeout)
|
||||
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.startswith('~$'):
|
||||
continue
|
||||
if 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 内未检测到稳定文件)")
|
||||
|
||||
|
||||
# ==================== 单次导出(带重试,AGENTS.md:最大3次) ====================
|
||||
def _export_one(page, download_dir, template_name, start=None, end=None):
|
||||
"""执行单次预入职台账导出(筛选 -> 自定义导出 -> 下载),失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(1, RETRY_TIMES + 1):
|
||||
logger.info(">>> 预入职台账导出 第 %d/%d 次(模板:%s)", attempt, RETRY_TIMES, template_name)
|
||||
try:
|
||||
_set_pre_entry_date_range(page, start, end)
|
||||
_open_custom_export_dialog(page)
|
||||
_select_template(page, template_name)
|
||||
# 触发下载前捕获目录快照,避免下载过快时真实文件被误判为已存在而漏检
|
||||
before = set(os.listdir(download_dir))
|
||||
_click_confirm_export(page)
|
||||
path = _wait_download(download_dir, before)
|
||||
logger.info(">>> 预入职台账导出完成")
|
||||
return path
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
logger.exception("预入职台账导出失败(第 %d 次),尝试重试:", attempt)
|
||||
time.sleep(WAIT_MID)
|
||||
raise RuntimeError(f"预入职台账导出连续失败:{last_err}")
|
||||
|
||||
|
||||
# ==================== 对外入口 ====================
|
||||
def export_pre_entry_roster(download_dir: str = None, template_name: str = TEMPLATE_SHIFT_ABNORMAL,
|
||||
output_path: str = None, start: str = None, end: str = None) -> str:
|
||||
"""执行预入职台账自定义导出(预入职日期近30天),返回下载后的 xlsx 文件路径。"""
|
||||
download_dir = os.path.abspath(download_dir or OUTPUT_DIR)
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
if not start or not end:
|
||||
start, end = get_pre_entry_range()
|
||||
logger.info("===== 开始预入职台账导出(模板:%s,日期:%s ~ %s),下载目录:%s =====",
|
||||
template_name, start, end, download_dir)
|
||||
|
||||
page = ChromiumPage(ChromiumOptions())
|
||||
logger.info("浏览器已启动")
|
||||
try:
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
logger.info("加载共享 cookies:%d 个", len(cookies or []))
|
||||
if cookies:
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
except Exception as e:
|
||||
logger.warning("注入共享 cookies 失败:%s", e)
|
||||
|
||||
_ensure_logged_in(page)
|
||||
_select_org_tree(page)
|
||||
_click_onboarded_tab(page)
|
||||
page.set.download_path(download_dir)
|
||||
logger.info("浏览器下载目录已设置:%s", download_dir)
|
||||
|
||||
path = _export_one(page, download_dir, template_name, start, end)
|
||||
|
||||
if output_path:
|
||||
output_path = os.path.abspath(output_path)
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
shutil.move(path, output_path)
|
||||
path = output_path
|
||||
elif path.endswith('.xlsx'):
|
||||
renamed = os.path.join(download_dir, SAVE_NAME)
|
||||
if os.path.abspath(path) != os.path.abspath(renamed):
|
||||
shutil.move(path, renamed)
|
||||
path = renamed
|
||||
|
||||
logger.info("===== 预入职台账导出完成:%s =====", path)
|
||||
return path
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
"""影刀入口:导出预入职台账。缺依赖/未登录会先行报错退出。"""
|
||||
try:
|
||||
out = export_pre_entry_roster()
|
||||
logger.info("===== 预入职台账导出完成:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("预入职台账导出失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,900 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: shift_abnormal_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-27
|
||||
@Description: 排班异常识别 + 钉钉单聊推送 + 汇总群聊推送(第三步,影刀版,单文件自包含)。
|
||||
读取第二步导出的《调动台账.xlsx》《预入职台账.xlsx》(表头均在 2 行),结合 HR 排班接口
|
||||
判断每人排班是否异常,生成异常明细(写回一份 Excel + 输出到全局变量),并通知各店长:
|
||||
最后一步由共享指令「37du钉钉推送」(yingdao/share/dingtalk_dws_push.py)完成发送,
|
||||
本脚本只负责「按异常人员工号解析对应店长 → 按店长分组 → 构造通知内容 → 写入影刀全局变量 messages」。
|
||||
单聊消息结构与共享指令 main(messages) 完全一致(五元组 (msg_type, name, user_id, content, file_path),
|
||||
此处均为 ("text", 店长姓名, 店长工号, 纯文本内容, ""))。
|
||||
|
||||
汇总群聊推送(识别出异常后追加):
|
||||
将《排班异常名单_时间戳.xlsx》汇总表格 + 汇总文案推送到指定群聊(默认「金色印象人行条线沟通工作群」,
|
||||
可用环境变量 shift_abnormal_push_group 覆盖;shift_abnormal_push_at_all="1" 时 @所有人)。
|
||||
文案:【今日门店HR系统排班异常提示】今日提示日期{核查窗口起始日}至{核查窗口截止日},
|
||||
具体提示名单详见表格,已单独钉钉信息提示对应店长。
|
||||
群聊消息以 dict(含 group 键)追加到全局变量 messages,共享指令 main(messages) 自动识别为群聊
|
||||
并发送文本+附件 Excel,无需单独配置推送通道。
|
||||
|
||||
判断口径(与 app 版 shift_abnormal_check.py 一致):
|
||||
- 调动台账:按「调动时间」近 {DAYS} 天;「现职位序列」含「职能」按「现单位」比对、
|
||||
其余按「现四级部门」比对;用 rf_s_kq_work_date_query 接口按比对部门查出该部门
|
||||
全部排班集合,当日排班({日期}_team_name)属于该集合才正常(接口查不到集合时兜底
|
||||
原「完整排班名包含部门名」判断),否则为排班异常(无排班 / 排班未更新);
|
||||
- 预入职台账:按「操作时间」近 {DAYS} 天;查询「预入职日期」当日完整排班名,有即正常,否则异常。
|
||||
|
||||
不推送过滤(不纳入异常、不推送):
|
||||
- 「现职位序列」命中 经营系管理序列 / 职能系专业序列 / 门店技师序列 的,直接剔除;
|
||||
- 花名册查不到工号的按离职处理剔除(调动+预入职均生效)。
|
||||
|
||||
店长解析(花名册):
|
||||
- 所有异常行已通过「离职过滤」保证工号在花名册内(未入册者已被剔除,含预入职);
|
||||
- 按异常人员「工号」查其「四级部门」,再找该部门内岗位含「店长」的人;
|
||||
- 仍解析不到的异常,若配置 shift_abnormal_default_manager 则归入默认处理人,否则仅记录不推送。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests pandas openpyxl
|
||||
|
||||
登录(共享登录态,本脚本仅读取 cookies 文件,不 import 任何共享模块):
|
||||
「37duHR登录」指令写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json;
|
||||
缺失/失效时先拖入「37duHR登录」指令再运行本流程。
|
||||
|
||||
花名册(店长解析数据源):
|
||||
默认 D:\\资料\\人资\\排班异常识别\\员工花名册.xlsx,可用环境变量 shift_abnormal_roster_path 覆盖;
|
||||
需含列:工号 / 姓名 / 四级部门 / 岗位。缺失时提示先运行「37du花名册导出」并准备好该文件
|
||||
(模板需含上述列,如「员工基础信息」含岗位、四级部门)。
|
||||
|
||||
环境变量(可选):
|
||||
shift_abnormal_save_dir 输出目录,默认 D:\\资料\\人资\\排班异常识别
|
||||
transfer_ledger / preentry_ledger 调动/预入职台账路径(默认同输出目录下的固定文件名)
|
||||
shift_abnormal_roster_path 花名册路径(默认 %shift_abnormal_save_dir%\\员工花名册.xlsx)
|
||||
shift_abnormal_default_manager 无法解析店长时归入的默认处理人 工号or姓名(可多个用英文逗号分隔)
|
||||
shift_abnormal_push_group 汇总群推送目标群(群全称,默认「金色印象人行条线沟通工作群」)
|
||||
shift_abnormal_push_at_all "1" 时汇总群推送 @所有人(需确认群权限,默认不 @)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import traceback
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先装齐,不懒加载) ====================
|
||||
try:
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install 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)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置(与 app 版统一) ====================
|
||||
_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')
|
||||
# HR 登录态:由「37duHR登录」共享指令写入
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
SHIFT_URL = "https://hr.37du.co/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
# 按部门查询排班集合(aa.md 提供):org_name=部门名,返回该部门全部排班
|
||||
# (data.list 记录含 work_date_name 排班名、org_name 部门名,逐条记录 = 一个排班)
|
||||
WORK_DATE_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_work_date_query/redApiExec.mc"
|
||||
# 集团根组织 struId(aa.md 提供,与考勤统计报表共用)
|
||||
COMPANY_STRU_ID = "596bae33-50e9-11ec-b526-822ff8ed5b28"
|
||||
WORK_DATE_PAGE_SIZE = 50
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# 输出目录 & 第二步导出的台账文件名(表头均在第 2 行)
|
||||
SAVE_DIR = os.getenv("shift_abnormal_save_dir") or r"D:\资料\人资\排班异常识别"
|
||||
TRANSFER_FILE = os.getenv("transfer_ledger") or os.path.join(SAVE_DIR, "调动台账.xlsx")
|
||||
PREENTRY_FILE = os.getenv("preentry_ledger") or os.path.join(SAVE_DIR, "预入职台账.xlsx")
|
||||
|
||||
# 筛选窗口:近 N 天(含当天)
|
||||
DAYS = 9
|
||||
# 每 N 次查询校验一次登录态(避免会话过期后逐人触发重登)
|
||||
SESSION_REVALIDATE_EVERY = 30
|
||||
|
||||
# 店长解析:花名册路径 & 关键字段
|
||||
ROSTER_PATH = os.getenv("shift_abnormal_roster_path") or os.path.join(SAVE_DIR, "员工花名册.xlsx")
|
||||
COL_NAME = "姓名"
|
||||
COL_CODE = "工号"
|
||||
COL_DEPT4 = "四级部门"
|
||||
COL_POSITION = "岗位"
|
||||
MANAGER_KEYWORD = "店长"
|
||||
|
||||
# 现职位序列命中以下序列的异常不推送(不纳入异常、不推送)
|
||||
EXCLUDE_SEQ_KEYWORDS = ("经营系管理序列", "职能系专业序列", "门店技师序列")
|
||||
|
||||
# 无法解析店长时归入默认处理人(多个英文逗号分隔则轮流分配;空则不归并、仅记录不推送)
|
||||
DEFAULT_MANAGER = os.getenv("shift_abnormal_default_manager", "")
|
||||
|
||||
# 汇总群聊推送:目标群名(群全称,按群名精确匹配)& 是否 @所有人("1" 时开启)
|
||||
PUSH_GROUP_ENV = "shift_abnormal_push_group"
|
||||
PUSH_AT_ALL_ENV = "shift_abnormal_push_at_all"
|
||||
DEFAULT_PUSH_GROUP = "金色印象人行条线沟通工作群" # 默认汇总推送群(与 XQ0009 固定推送群一致)
|
||||
|
||||
# 异常名单导出列
|
||||
COLUMNS = [
|
||||
"序号", "姓名", "工号", "类别", "原单位", "原上级部门", "现单位", "现职位序列",
|
||||
"现上级部门", "现四级部门", "调动/入职时间", "操作时间", "当日排班", "异常原因",
|
||||
]
|
||||
|
||||
|
||||
# ==================== HR 登录态(共享 cookies) ====================
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def _load_shared_hr_cookies():
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
return json.load(f) or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python yingdao/share/hr_login.py")
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
"""用共享 hr_cookies.json 构建 requests.Session(过滤 hr.37du.co 域)。"""
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;失效抛 HRSessionExpiredError。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _relogin_get_user_id():
|
||||
"""登录态失效后:重建会话 → 重新获取 userId。"""
|
||||
_ensure_hr_cookies()
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
return session, _clean(info.get("userId"))
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
# ==================== 排班接口(内联自 app 版 hr_api/shift.py) ====================
|
||||
def fetch_shift_page(session, user_id, base_code, begin_date, end_date,
|
||||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页排班数据。datas 记录含 {日期}_team_name 完整排班名,休息日可靠判定用 bc_name==休息。"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_count_SelectBanci",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"staff_ids": "",
|
||||
"person_status": "1,4",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"post_level": "",
|
||||
"identity": "",
|
||||
"showType": "1",
|
||||
"dateType": "1",
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"bc_date": begin_date,
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SHIFT_URL, params, "排班")
|
||||
|
||||
|
||||
def fetch_all_shift(session, user_id, base_code, begin_date, end_date):
|
||||
"""分页抓取指定工号、日期范围内全部排班数据;登录态失效自动补登后续抓。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_shift_page(session, user_id, base_code, begin_date, end_date,
|
||||
"cq37du", page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("排班 HR 登录态过期,自动补登录后续抓")
|
||||
session, user_id = _relogin_get_user_id()
|
||||
data = fetch_shift_page(session, user_id, base_code, begin_date, end_date,
|
||||
"cq37du", page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("排班第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("排班无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("排班已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_work_date_page(session, org_name, page_no=1, page_size=WORK_DATE_PAGE_SIZE):
|
||||
"""请求单页「某部门排班集合」。data.list 记录含 work_date_name(排班名)、org_name(部门名)。"""
|
||||
params = {
|
||||
"stru_tree_code": "cq37du",
|
||||
"struId": COMPANY_STRU_ID,
|
||||
"containLower": "",
|
||||
"work_date_name": "",
|
||||
"paiban_type": "",
|
||||
"holiday_plan_name": "",
|
||||
"org_name": org_name,
|
||||
"work_status": "1",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "create_time",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", WORK_DATE_QUERY_URL, params, "部门排班")
|
||||
|
||||
|
||||
def fetch_all_work_date(session, org_name):
|
||||
"""分页抓取某部门的全部排班名列表(work_date_name)。登录态失效自动补登后续抓。"""
|
||||
names = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_work_date_page(session, org_name, page_no)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("部门排班 HR 登录态过期,自动补登录后续抓")
|
||||
session = _relogin_get_user_id()[0]
|
||||
data = fetch_work_date_page(session, org_name, page_no)
|
||||
if not data.get("success"):
|
||||
logger.error("部门排班第 %d 页请求失败:%s", page_no, data.get("message") or data.get("meg"))
|
||||
break
|
||||
data_block = data.get("data", {}) or {}
|
||||
page_list = data_block.get("list", []) or []
|
||||
if not page_list:
|
||||
logger.info("部门排班无更多数据")
|
||||
break
|
||||
for rec in page_list:
|
||||
name = _clean(rec.get("work_date_name"))
|
||||
if name:
|
||||
names.append(name)
|
||||
total_page = data_block.get("pageCount", 0)
|
||||
logger.info("部门排班已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(names))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return names
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
"""转字符串并去掉常见杂质:None、浮点 .0 尾缀、pandas 空占位(nan/native等)。"""
|
||||
if v is None:
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _seq_excluded(seq: str) -> bool:
|
||||
"""现职位序列命中剔除序列(经营系管理序列/职能系专业序列/门店技师序列)返回 True。"""
|
||||
seq = _clean(seq)
|
||||
return any(kw in seq for kw in EXCLUDE_SEQ_KEYWORDS)
|
||||
|
||||
|
||||
def _shift_name(s: str) -> str:
|
||||
"""归一化排班名:兼容 {日期}_team_name 可能带 "YYYY-MM-DD_" 前缀,去掉前缀便于与接口 work_date_name 比对。"""
|
||||
s = _clean(s)
|
||||
if len(s) > 11 and s[4] == "-" and s[7] == "-" and s[10] == "_":
|
||||
return s[11:]
|
||||
return s
|
||||
|
||||
|
||||
def _date_part(v) -> str:
|
||||
"""取日期字符串前 10 位(兼容 "YYYY-MM-DD HH:MM:SS")。"""
|
||||
return _clean(v)[:10]
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
"""解析日期字符串为 date,失败返回 None。"""
|
||||
s = _date_part(v)
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _recent_window(end: date = None, days: int = DAYS) -> Tuple[date, date]:
|
||||
"""返回近 N 天的 (开始日期, 结束日期),含当天。"""
|
||||
end = end or date.today()
|
||||
begin = end - timedelta(days=days - 1)
|
||||
return begin, end
|
||||
|
||||
|
||||
def _load_ledger(path: str) -> "pd.DataFrame":
|
||||
"""读取第二步导出的台账,表头在第 2 行(header=1)。"""
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到台账文件:{path}\n请先运行第二步导出(调动台账 / 预入职台账)后再执行本模块。")
|
||||
df = pd.read_excel(path, header=1, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
logger.info("已读取台账:%s,共 %d 行", path, len(df))
|
||||
return df
|
||||
|
||||
|
||||
def _ensure_user_id(session, user_id: Optional[str]) -> Tuple[object, str]:
|
||||
"""获取有效 user_id 与会话。传入 None 时实时取;已有则直接复用。"""
|
||||
if user_id:
|
||||
return session, user_id
|
||||
info = fetch_cur_user_info(session)
|
||||
new_uid = _clean(info.get("userId"))
|
||||
if not new_uid:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId:{info}")
|
||||
return session, new_uid
|
||||
|
||||
|
||||
# ==================== 排班查询器(带缓存) ====================
|
||||
class _ShiftFetcher:
|
||||
"""按 (工号, 日期) 缓存当日完整排班名,复用同一会话,定期校验登录态。"""
|
||||
|
||||
def __init__(self, session, user_id: str):
|
||||
self.session = session
|
||||
self.user_id = user_id
|
||||
self.cache: Dict[Tuple[str, date], str] = {}
|
||||
self.calls = 0
|
||||
|
||||
def fetch(self, code: str, day: date) -> str:
|
||||
"""返回某工号某日的完整排班名({日期}_team_name);无排班则返回空串。"""
|
||||
key = (code, day)
|
||||
if key not in self.cache:
|
||||
self.calls += 1
|
||||
if self.calls % SESSION_REVALIDATE_EVERY == 1:
|
||||
self.session, uid = _ensure_user_id(self.session, None)
|
||||
self.user_id = uid
|
||||
self.cache[key] = self._query(code, day)
|
||||
time.sleep(0.2)
|
||||
return self.cache[key]
|
||||
|
||||
def _query(self, code: str, day: date) -> str:
|
||||
day_str = day.strftime("%Y-%m-%d")
|
||||
rows = fetch_all_shift(self.session, self.user_id, code, day_str, day_str)
|
||||
for rec in rows:
|
||||
return _clean(rec.get(f"{day_str}_team_name"))
|
||||
return ""
|
||||
|
||||
|
||||
class _DeptShiftFetcher:
|
||||
"""按部门名缓存该部门的排班名集合(work_date_name),复用同一会话,定期校验登录态。
|
||||
|
||||
同一部门可能配置多个排班(技师岗/服务岗/管理岗…),通过 rf_s_kq_work_date_query
|
||||
接口按部门查出全部排班名,用于判断员工当日排班是否属于该部门。
|
||||
"""
|
||||
|
||||
def __init__(self, session):
|
||||
self.session = session
|
||||
self.cache: Dict[str, set] = {}
|
||||
self.calls = 0
|
||||
|
||||
def fetch(self, dept_name: str) -> set:
|
||||
"""返回某部门的排班名集合;部门名为空或查不到返回空集合。"""
|
||||
dept_name = _clean(dept_name)
|
||||
if not dept_name:
|
||||
return set()
|
||||
if dept_name not in self.cache:
|
||||
# 定期重新校验登录态,避免绑定过期会话
|
||||
self.calls += 1
|
||||
if self.calls % SESSION_REVALIDATE_EVERY == 1:
|
||||
self.session, _ = _ensure_user_id(self.session, None)
|
||||
self.cache[dept_name] = {_shift_name(n) for n in fetch_all_work_date(self.session, dept_name)}
|
||||
time.sleep(0.2)
|
||||
return self.cache[dept_name]
|
||||
|
||||
|
||||
def _shift_belongs(dept_fetcher: "_DeptShiftFetcher", dept_name: str, shift: str) -> bool:
|
||||
"""判断某排班是否属于某部门。
|
||||
|
||||
优先用新接口(rf_s_kq_work_date_query)按部门查出排班集合做成员判断;
|
||||
接口查不到集合(如「现单位」无直属排班)时兜底原「完整排班名包含部门名」判断。
|
||||
"""
|
||||
dept_name = _clean(dept_name)
|
||||
shift_norm = _shift_name(shift)
|
||||
if not dept_name or not shift_norm:
|
||||
return False
|
||||
dept_shifts = dept_fetcher.fetch(dept_name)
|
||||
if dept_shifts:
|
||||
return shift_norm in dept_shifts
|
||||
return dept_name in shift
|
||||
|
||||
|
||||
# ==================== 异常判定(与 app 版一致) ====================
|
||||
def _check_transfer_row(fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", r, begin: date, end: date):
|
||||
"""对单行调动记录判定,返回名单行 dict;属正常则返回 None。"""
|
||||
code = _clean(r.get("工号"))
|
||||
day = _parse_date(r.get("调动时间"))
|
||||
if not code or not day:
|
||||
return None
|
||||
if not (begin <= day <= end):
|
||||
return None
|
||||
|
||||
seq = _clean(r.get("现职位序列"))
|
||||
if _seq_excluded(seq):
|
||||
return None
|
||||
if "职能" in seq:
|
||||
target_field, target_name = "现单位", _clean(r.get("现单位"))
|
||||
else:
|
||||
target_field, target_name = "现四级部门", _clean(r.get("现四级部门"))
|
||||
|
||||
shift = fetcher.fetch(code, day)
|
||||
if not shift:
|
||||
reason, present = "调动时间无排班", ""
|
||||
elif target_name and not _shift_belongs(dept_fetcher, target_name, shift):
|
||||
reason, present = f"排班未更新为{target_field}({target_name})", shift
|
||||
else:
|
||||
return None # 当日有排班且排班属于所需部门 → 正常
|
||||
|
||||
return {
|
||||
"序号": 0,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"工号": code,
|
||||
"类别": "调动",
|
||||
"原单位": _clean(r.get("原单位")),
|
||||
"原上级部门": _clean(r.get("原上级部门")),
|
||||
"现单位": _clean(r.get("现单位")),
|
||||
"现职位序列": seq,
|
||||
"现上级部门": _clean(r.get("现上级部门")),
|
||||
"现四级部门": _clean(r.get("现四级部门")),
|
||||
"调动/入职时间": day.strftime("%Y-%m-%d"),
|
||||
"操作时间": _date_part(r.get("操作时间")),
|
||||
"当日排班": present,
|
||||
"异常原因": reason,
|
||||
}
|
||||
|
||||
|
||||
def _check_preentry_row(fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", r, begin: date, end: date):
|
||||
"""对单行预入职记录判定,返回名单行 dict;有排班信息则返回 None。"""
|
||||
code = _clean(r.get("工号"))
|
||||
op_day = _parse_date(r.get("操作时间")) # 筛选字段:操作时间
|
||||
if not code or not op_day:
|
||||
return None
|
||||
if not (begin <= op_day <= end):
|
||||
return None
|
||||
if _seq_excluded(r.get("职位序列")):
|
||||
return None
|
||||
|
||||
pj_day = _parse_date(r.get("预入职日期")) # 排班检查日期:预入职日期
|
||||
if not pj_day:
|
||||
return None
|
||||
|
||||
shift = fetcher.fetch(code, pj_day)
|
||||
if shift:
|
||||
return None # 有排班信息即可 → 正常
|
||||
|
||||
return {
|
||||
"序号": 0,
|
||||
"姓名": _clean(r.get("姓名")),
|
||||
"工号": code,
|
||||
"类别": "入职",
|
||||
"原单位": "",
|
||||
"原上级部门": "",
|
||||
"现单位": _clean(r.get("入职单位")),
|
||||
"现职位序列": _clean(r.get("职位序列")),
|
||||
"现上级部门": "",
|
||||
"现四级部门": "",
|
||||
"调动/入职时间": pj_day.strftime("%Y-%m-%d"),
|
||||
"操作时间": op_day.strftime("%Y-%m-%d"),
|
||||
"当日排班": "",
|
||||
"异常原因": "预入职日期无排班",
|
||||
}
|
||||
|
||||
|
||||
def _collect_rows(ledger_path: str, check_row, fetcher: "_ShiftFetcher", dept_fetcher: "_DeptShiftFetcher", end: date,
|
||||
days: int = DAYS) -> List[dict]:
|
||||
"""通用判定流程:读台账 → 逐行判定,返回异常行列表。"""
|
||||
df = _load_ledger(ledger_path)
|
||||
begin, end_date = _recent_window(end, days)
|
||||
logger.info("筛选范围:%s ~ %s(近 %d 天)", begin, end_date, days)
|
||||
rows = []
|
||||
for _, r in df.iterrows():
|
||||
row = check_row(fetcher, dept_fetcher, r, begin, end_date)
|
||||
if row:
|
||||
rows.append(row)
|
||||
logger.info("台账 %s 排班异常人数:%d", os.path.basename(ledger_path), len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 店长解析(花名册) ====================
|
||||
def _to_text(v):
|
||||
"""将工号等主键值统一转为文本(浮点/整型转 str),避免文本/数字混存匹配失败。"""
|
||||
if v is None:
|
||||
return ""
|
||||
try:
|
||||
if pd.isna(v):
|
||||
return ""
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return _clean(v)
|
||||
|
||||
|
||||
def _read_roster(roster_path: str) -> "pd.DataFrame":
|
||||
"""读取花名册并定位表头行(含「工号」列的行),返回列名为字段名的 DataFrame。
|
||||
|
||||
需含列:工号 / 姓名 / 四级部门 / 岗位。
|
||||
"""
|
||||
path = os.path.abspath(roster_path)
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到花名册:{path}\n"
|
||||
f"请先运行「37du花名册导出」指令导出到该路径,或设置环境变量 shift_abnormal_roster_path。")
|
||||
probe = pd.read_excel(path, header=None, nrows=10)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if (probe.iloc[idx].astype(str).str.strip() == COL_CODE).any():
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"花名册未找到表头行(缺少「{COL_CODE}」字段):{path}")
|
||||
df = pd.read_excel(path, header=header_row)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
required = (COL_CODE, COL_NAME, COL_DEPT4, COL_POSITION)
|
||||
missing = [c for c in required if c not in df.columns]
|
||||
if missing:
|
||||
raise ValueError(f"花名册缺少必需列:{missing}({path})")
|
||||
return df
|
||||
|
||||
|
||||
def _find_manager_by_code(df, code):
|
||||
"""按异常人员工号解析店长:查其四级部门 → 部门内岗位含「店长」的人。
|
||||
|
||||
返回 (manager_code, manager_name);找不到返回 (None, None)。
|
||||
"""
|
||||
code = _to_text(code)
|
||||
if not code:
|
||||
return None, None
|
||||
row = df[df[COL_CODE].map(_to_text) == code]
|
||||
if row.empty:
|
||||
logger.warning("花名册中无该工号:%s", code)
|
||||
return None, None
|
||||
dept4 = _to_text(row.iloc[0][COL_DEPT4])
|
||||
if not dept4:
|
||||
logger.warning("员工(工号 %s)无四级部门,无法解析店长", code)
|
||||
return None, None
|
||||
return _find_manager_by_dept(df, dept4)
|
||||
|
||||
|
||||
def _find_manager_by_dept(df, dept_name, label=""):
|
||||
"""按部门名解析店长:花名册中该部门内岗位含「店长」的人,命中多个取第一个。
|
||||
|
||||
返回 (manager_code, manager_name);找不到返回 (None, None)。
|
||||
"""
|
||||
dept_name = _clean(dept_name)
|
||||
if not dept_name:
|
||||
return None, None
|
||||
dept_col = df[COL_DEPT4].map(_to_text)
|
||||
candidates = df[(dept_col == dept_name) & (df[COL_POSITION].astype(str).str.contains(MANAGER_KEYWORD, na=False))]
|
||||
if candidates.empty:
|
||||
logger.warning("%s未在花名册「%s」部门找到店长", label, dept_name)
|
||||
return None, None
|
||||
first = candidates.iloc[0]
|
||||
return _to_text(first[COL_CODE]), _to_text(first[COL_NAME]) or ""
|
||||
|
||||
|
||||
def resolve_manager(roster_df, row: dict) -> Tuple[str, str]:
|
||||
"""解析某条异常名单行对应的店长:工号已保证在花名册(离职过滤已剔除未入册者),
|
||||
直接按工号查其四级部门 → 部门内岗位含「店长」的人;找不到返回 (None, None)。"""
|
||||
return _find_manager_by_code(roster_df, row.get("工号", ""))
|
||||
|
||||
|
||||
# ==================== 消息构造 ====================
|
||||
def _item_line(row: dict) -> str:
|
||||
"""异常明细一行(钉钉 markdown 纯文本,<br> 做单行换行),按异常原因区分文案:
|
||||
|
||||
- 调动-无排班:门店员工{姓名}({工号})至{调动时间}日调入本店超期未排班,请核实处理;
|
||||
- 调动-排班未更新:门店员工{姓名}({工号})至{调动时间}日调入本店排班未更新,请核实处理;
|
||||
- 新入职:门店员工{姓名}({工号})自{预入职日期}日入职本店超期未排班,请核实处理。
|
||||
"""
|
||||
name = row.get("姓名", "")
|
||||
code = row.get("工号", "")
|
||||
day = row.get("调动/入职时间", "")
|
||||
if row.get("类别") == "调动":
|
||||
if "排班未更新" in _clean(row.get("异常原因")):
|
||||
return f"门店员工{name}({code})至{day}日调入本店排班未更新,请核实处理"
|
||||
return f"门店员工{name}({code})至{day}日调入本店超期未排班,请核实处理"
|
||||
return f"门店员工{name}({code})自{day}日入职本店超期未排班,请核实处理"
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _find_dept4_by_manager(df, mc: str, mn: str) -> str:
|
||||
"""按店长工号/姓名在花名册查询其四级部门(门店名),查不到返回空串。
|
||||
|
||||
问候语里的门店名以花名册为准,不使用异常表里的 现四级部门/现单位 字段。
|
||||
"""
|
||||
if mc:
|
||||
hit = df[df[COL_CODE].map(_to_text) == mc]
|
||||
elif mn:
|
||||
hit = df[df[COL_NAME].map(_to_text) == mn]
|
||||
else:
|
||||
return ""
|
||||
if hit.empty:
|
||||
return ""
|
||||
return _to_text(hit.iloc[0][COL_DEPT4])
|
||||
|
||||
|
||||
def build_messages(rows: List[dict], roster_df) -> List[tuple]:
|
||||
"""按店长分组构造钉钉单聊推送消息列表,结构与共享模块 dingtalk_dws_push.main(messages) 一致。
|
||||
|
||||
每组一条消息:("text", 店长姓名, 店长工号, 纯文本内容, "")。
|
||||
无法解析店长的异常,若配置 DEFAULT_MANAGER 则归入默认处理人(多个用英文逗号分隔,
|
||||
轮流分配),否则仅日志记录、不推送。
|
||||
"""
|
||||
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 or mn:
|
||||
groups.setdefault((mc or "", mn or ""), []).append(row)
|
||||
else:
|
||||
unresolved.append(row)
|
||||
|
||||
if unresolved:
|
||||
logger.warning("有 %d 条异常无法解析店长:%s",
|
||||
len(unresolved),
|
||||
[f"{r.get('姓名')}/{r.get('工号')}" for r in unresolved])
|
||||
if default_managers:
|
||||
# 配置多个默认处理人(英文逗号分隔)时,无法解析店长的异常轮流分配,不遗漏
|
||||
for i, row in enumerate(unresolved):
|
||||
mgr = default_managers[i % len(default_managers)]
|
||||
key = _resolve_manager_identity(roster_df, mgr)
|
||||
groups.setdefault(key, []).append(row)
|
||||
|
||||
for (mc, mn), items in groups.items():
|
||||
dept = _find_dept4_by_manager(roster_df, mc, mn) # 门店名以花名册店长四级部门为准
|
||||
line_items = "<br>".join(_item_line(r) for r in items)
|
||||
content = (
|
||||
f"【排班异常提醒】<br>"
|
||||
f"{dept}店长您好,人力资源部在近期排班核查中发现您的门店有 {len(items)} 名员工排班异常<br>"
|
||||
f"{line_items}<br>"
|
||||
f"如有疑问请联系经营中心人行"
|
||||
)
|
||||
messages.append(("text", mn, mc, content, ""))
|
||||
logger.info("已构造店长[%s%s]单聊推送消息,含 %d 条异常", mn, f"/{mc}" if mc else "", len(items))
|
||||
|
||||
return messages
|
||||
|
||||
|
||||
def _build_group_push_message(save_path: str, begin: date, end: date) -> Optional[dict]:
|
||||
"""构造群聊汇总推送消息(汇总文案 + 名单表格附件)。
|
||||
|
||||
识别出排班异常后调用:把《排班异常名单_时间戳.xlsx》及汇总文案打包成一条群聊消息
|
||||
(dict 含 group 键,共享指令「37du钉钉推送」main(messages) 自动识别为群聊并发送文本+附件),
|
||||
目标群默认 DEFAULT_PUSH_GROUP(金色印象人行条线沟通工作群),可用环境变量
|
||||
shift_abnormal_push_group 覆盖;shift_abnormal_push_at_all="1" 时 @所有人(需群权限)。
|
||||
|
||||
Args:
|
||||
save_path: 排班异常名单 Excel 绝对路径
|
||||
begin: 核查窗口开始日期(近 DAYS 天,含)
|
||||
end: 核查窗口结束日期(当天)
|
||||
|
||||
Returns:
|
||||
群聊推送消息 dict;文件不存在时返回 None(流程指令收到空则不发送)。
|
||||
"""
|
||||
if not save_path or not os.path.exists(save_path):
|
||||
logger.warning("排班异常名单文件不存在,跳过群聊汇总推送消息构造:%s", save_path)
|
||||
return None
|
||||
group = (os.getenv(PUSH_GROUP_ENV, "") or DEFAULT_PUSH_GROUP).strip()
|
||||
at_all = (os.getenv(PUSH_AT_ALL_ENV) or "0").strip().lower() in ("1", "true", "yes", "y")
|
||||
text = (
|
||||
f"【今日门店HR系统排班异常提示】今日提示日期{begin}至{end},"
|
||||
f"具体提示名单详见表格,已单独钉钉信息提示对应店长"
|
||||
)
|
||||
if at_all:
|
||||
text += "\n<@all>" # @所有人 需在内容中含占位符 <@all>(与共享模块约定一致)
|
||||
return {
|
||||
"group": group,
|
||||
"content": text,
|
||||
"file_path": save_path,
|
||||
"title": "",
|
||||
"at_all": at_all,
|
||||
"at_open_ids": "",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def run_shift_abnormal_check(
|
||||
transfer_path: str = None,
|
||||
preentry_path: str = None,
|
||||
roster_path: str = None,
|
||||
days: int = DAYS,
|
||||
) -> Tuple[List[dict], List[dict]]:
|
||||
"""执行排班异常识别,返回 (异常名单行列表, 推送消息列表)。
|
||||
|
||||
- 异常名单行列表:合并调动+预入职的异常明细(未写文件);
|
||||
- 推送消息列表:单聊消息按店长分组(五元组 ("text", 店长姓名, 店长工号, 内容, "")),
|
||||
识别出异常时末尾追加一条群聊汇总推送 dict(含 group 键,自动识别为群聊,文案+名单表格附件),
|
||||
统一由共享指令「37du钉钉推送」main(messages) 发送(单聊/群聊按消息结构自动识别)。
|
||||
脚本内部会将名单写入 SAVE_DIR 下《排班异常名单_时间戳.xlsx》便于人工留档。
|
||||
"""
|
||||
transfer_path = transfer_path or TRANSFER_FILE
|
||||
preentry_path = preentry_path or PREENTRY_FILE
|
||||
roster_path = roster_path or ROSTER_PATH
|
||||
# 前置校验:花名册必须存在,避免台账读取与 HR 排班接口调用跑完后才发现缺失
|
||||
if not os.path.exists(roster_path):
|
||||
raise RuntimeError(
|
||||
f"未找到花名册:{roster_path}\n"
|
||||
"请先运行「37du花名册导出」指令导出到该路径,或设置环境变量 shift_abnormal_roster_path。")
|
||||
roster_df = _read_roster(roster_path) # 早读花名册:用于离职判定(工号查不到=离职剔除)
|
||||
roster_codes = set(_to_text(c) for c in roster_df[COL_CODE])
|
||||
end = date.today()
|
||||
begin, end_window = _recent_window(end, days) # 核查窗口(近 DAYS 天,含当天),用于汇总文案日期
|
||||
|
||||
rows: List[dict] = []
|
||||
fetcher = None
|
||||
if os.path.exists(transfer_path) or os.path.exists(preentry_path):
|
||||
session = build_hr_session()
|
||||
session, user_id = _ensure_user_id(session, None)
|
||||
fetcher = _ShiftFetcher(session, user_id)
|
||||
dept_fetcher = _DeptShiftFetcher(session)
|
||||
else:
|
||||
raise RuntimeError(
|
||||
"调动台账、预入职台账均不存在,请先运行第二步导出后再执行本模块。\n"
|
||||
f"(调动:{transfer_path},预入职:{preentry_path})")
|
||||
|
||||
if os.path.exists(transfer_path):
|
||||
rows.extend(_collect_rows(transfer_path, _check_transfer_row, fetcher, dept_fetcher, end, days))
|
||||
else:
|
||||
logger.warning("跳过调动台账:文件不存在 %s", transfer_path)
|
||||
|
||||
if os.path.exists(preentry_path):
|
||||
rows.extend(_collect_rows(preentry_path, _check_preentry_row, fetcher, dept_fetcher, end, days))
|
||||
else:
|
||||
logger.warning("跳过预入职台账:文件不存在 %s", preentry_path)
|
||||
|
||||
# 离职过滤:花名册查不到工号的按离职处理,不纳入异常、不推送(调动+预入职均生效)
|
||||
if rows:
|
||||
resigned = [r for r in rows if _to_text(r.get("工号")) not in roster_codes]
|
||||
if resigned:
|
||||
logger.warning("花名册查不到工号,按离职剔除 %d 人:%s",
|
||||
len(resigned), [f"{r.get('姓名')}/{r.get('工号')}" for r in resigned])
|
||||
rows = [r for r in rows if _to_text(r.get("工号")) in roster_codes]
|
||||
|
||||
if not rows:
|
||||
logger.info("未识别到排班异常,无需推送。")
|
||||
messages = []
|
||||
else:
|
||||
# 补序号
|
||||
rows.sort(key=lambda x: (x.get("类别", ""), x.get("姓名", ""), x.get("工号", "")))
|
||||
for idx, item in enumerate(rows, 1):
|
||||
item["序号"] = idx
|
||||
# 导出名单留档
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.join(SAVE_DIR, f"排班异常名单_{ts}.xlsx")
|
||||
pd.DataFrame(rows, columns=COLUMNS).to_excel(save_path, index=False)
|
||||
logger.info("排班异常名单(共 %d 人)已保存:%s", len(rows), save_path)
|
||||
|
||||
# 解析店长并构造单聊推送消息
|
||||
messages = build_messages(rows, roster_df)
|
||||
|
||||
# 汇总群聊推送:汇总文案 + 名单表格附件(dict 含 group 键,共享指令自动识别为群聊)
|
||||
group_msg = _build_group_push_message(save_path, begin, end_window)
|
||||
if group_msg:
|
||||
messages.append(group_msg)
|
||||
logger.info("已构造群聊汇总推送消息(群「%s」,含名单表格附件)", group_msg.get("group"))
|
||||
|
||||
return rows, messages
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""影刀入口:排班异常识别并构造钉钉推送消息(单聊按店长 + 汇总群聊),写入全局变量 messages。
|
||||
由流程拖「37du钉钉推送」指令完成实际发送(单聊/群聊按消息结构自动识别)。
|
||||
"""
|
||||
try:
|
||||
rows, messages = run_shift_abnormal_check()
|
||||
_set_glv("shift_abnormal_rows", rows)
|
||||
_set_glv("messages", messages)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【排班异常识别完成】")
|
||||
logger.info(" 异常人数:%d", len(rows))
|
||||
logger.info(" 待推送消息:%d 条(含单聊+汇总群聊,已写入全局变量 messages,请拖「37du钉钉推送」指令发送)", len(messages))
|
||||
logger.info("=" * 60)
|
||||
except Exception as e:
|
||||
logger.error("排班异常识别失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,467 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: transfer_roster_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-27
|
||||
@Description: 调动台账自定义导出(排班异常识别 步骤2-调动,影刀版,单文件自包含)。
|
||||
复用「37duHR登录」指令写入的共享 cookies,通过 DrissionPage 浏览器自动化操作:
|
||||
进入调动台账页 -> 组织机构(集团) -> 点击「调动已生效」-> 更多搜索
|
||||
-> 输入调动时间(近30天)-> 筛选 -> 自定义导出 -> 选择模板「排班异常识别导出」
|
||||
-> 确认导出,接收下载文件重命名为《调动台账.xlsx》(表头在第 2 行)。
|
||||
与预入职台账导出(pre_entry_roster_export.py)流程基本一致,仅页面地址、tab 文案、
|
||||
日期占位符、文件名不同。
|
||||
@Version: 1.0.0
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage
|
||||
|
||||
登录(共享登录态,本脚本仅读取共享 cookies 文件,不 import 任何共享模块):
|
||||
「37duHR登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json;
|
||||
缺失/失效时先拖入「37duHR登录」指令完成登录,再运行本流程。
|
||||
|
||||
运行:直接执行本文件即可(会弹出浏览器窗口,请勿关闭)。
|
||||
输出目录默认 D:\\资料\\人资\\排班异常识别,可用环境变量 transfer_output_dir 覆盖。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import traceback
|
||||
from datetime import date, timedelta
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:必须预先装齐,不懒加载) ====================
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install DrissionPage\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置(与 app 版统一) ====================
|
||||
_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')
|
||||
# HR 登录态:由「37duHR登录」共享指令写入
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# 调动台账页地址 & 导出模板(与 app/service/hrbp/ehr/common/config.py 一致)
|
||||
TRANSFER_ROSTER_URL = ("https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-01818-39687&nworktoday-40175-24311|/RedseaPlatform/hrRoster/1123d951-b094-11ea-b588-14187743d052/getCustomCommonList.mc?clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=%E8%B0%83%E5%8A%A8%E5%8F%B0%E8%B4%A6")
|
||||
TEMPLATE_SHIFT_ABNORMAL = "排班异常识别导出"
|
||||
|
||||
# 流程步骤所用文案常量(aa.md 提供)
|
||||
TAB_ORG = "组织机构" # 左侧「组织机构」tab
|
||||
TREE_GROUP = "集团" # 组织树根节点
|
||||
TAB_TRANSFER_EFFECTIVE = "调动已生效" # 只导已生效调动
|
||||
MENU_CUSTOM_EXPORT = "自定义导出"
|
||||
BTN_CONFIRM = "确认导出"
|
||||
BTN_MORE_SEARCH = "更多搜索"
|
||||
TRANSFER_RANGE_PLACEHOLDER = "请选择调动时间"
|
||||
|
||||
# 通用等待秒数
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
DOWNLOAD_FINISH_TIMEOUT = 300 # 等待下载完成
|
||||
RETRY_TIMES = 3 # 单次导出失败重试次数(AGENTS.md:最大重试3次)
|
||||
|
||||
# 输出目录 & 文件名
|
||||
OUTPUT_DIR = os.getenv("transfer_output_dir") or r"D:\资料\人资\排班异常识别"
|
||||
SAVE_NAME = "调动台账.xlsx"
|
||||
|
||||
|
||||
# ==================== 日志(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)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _load_shared_hr_cookies():
|
||||
"""读取共享 HR cookies(由「37duHR登录」指令写入)。"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
return json.load(f) or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
"""确保存在有效的 HR 登录态;缺失时提示先运行「37duHR登录」指令。"""
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令完成登录,"
|
||||
"或本地先运行 python yingdao/share/hr_login.py")
|
||||
|
||||
|
||||
# ==================== 调动日期范围(近30天) ====================
|
||||
def get_transfer_range(today: date = None, days: int = 30) -> tuple:
|
||||
"""计算调动日期筛选范围,返回 (开始日期, 结束日期)。"""
|
||||
today = today or date.today()
|
||||
start = today - timedelta(days=days - 1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 元素定位辅助(DrissionPage) ====================
|
||||
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 _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 _find_more_search_button(page):
|
||||
"""定位当前活跃 tab 的「更多搜索」按钮(仅取可见的那个,避免展开错 tab)。"""
|
||||
btns = page.eles('css:button.search-more-condition-btn', timeout=3)
|
||||
if not btns:
|
||||
btns = page.eles('css:.demo-search-more .el-popover__reference', timeout=2)
|
||||
if not btns:
|
||||
btn = page.ele('xpath://button[.//span[contains(normalize-space(.),"更多搜索")]]', timeout=2)
|
||||
return btn if _is_displayed(btn) else None
|
||||
for b in btns:
|
||||
if _is_displayed(b):
|
||||
return b
|
||||
logger.warning("未找到可见的「更多搜索」按钮(DOM 中共 %d 个)", len(btns))
|
||||
return None
|
||||
|
||||
|
||||
def _open_more_search(page):
|
||||
"""展开当前活跃 tab 的「更多搜索」popover,返回其内容元素;失败返回 None。"""
|
||||
btn = _find_more_search_button(page)
|
||||
if not btn:
|
||||
return None
|
||||
for _ in range(3):
|
||||
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 popover
|
||||
try:
|
||||
btn.run_js('this.click();')
|
||||
except Exception:
|
||||
btn.click()
|
||||
time.sleep(WAIT_MID)
|
||||
logger.warning("「更多搜索」未能展开")
|
||||
return None
|
||||
|
||||
|
||||
def _click_filter(page, popover):
|
||||
"""点击活跃 tab「更多搜索」弹层底部的「筛选」按钮(限定在弹出容器内)。"""
|
||||
result = popover.run_js(
|
||||
'var btns=this.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";'
|
||||
)
|
||||
if result != "clicked":
|
||||
raise RuntimeError(f"点击「筛选」失败:{result}")
|
||||
logger.info("已点击「筛选」(JS click)")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _find_visible_range_input(page, placeholder):
|
||||
"""在页面级查找可见的调动时间选择器(页面宽/窄布局不同,取可见的第一个)。"""
|
||||
rngs = page.eles(f'css:div.split-datetime-range[placeholder="{placeholder}"]', timeout=3)
|
||||
for r in rngs:
|
||||
if _is_displayed(r):
|
||||
return r
|
||||
return None
|
||||
|
||||
|
||||
def _fill_range(page, rng, start, end):
|
||||
"""填入日期范围并回车确认。"""
|
||||
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("未找到调动时间起止输入框")
|
||||
start_input.input(start, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
end_input.input(end, clear=True)
|
||||
page.actions.key_down('enter').key_up('enter')
|
||||
time.sleep(WAIT_SHORT)
|
||||
logger.info("调动时间已设置:%s ~ %s", start, end)
|
||||
|
||||
|
||||
def _set_transfer_date_range(page, start=None, end=None):
|
||||
"""设置「调动时间」筛选范围(近30天)并应用筛选。"""
|
||||
if not start or not end:
|
||||
start, end = get_transfer_range()
|
||||
logger.info("设置调动时间范围:%s ~ %s", start, end)
|
||||
popover = _open_more_search(page)
|
||||
if not popover:
|
||||
raise RuntimeError("「更多搜索」未能展开,无法设置调动时间")
|
||||
rng = _find_visible_range_input(page, TRANSFER_RANGE_PLACEHOLDER)
|
||||
if not rng:
|
||||
rng = popover.ele(
|
||||
f'css:div.split-datetime-range[placeholder="{TRANSFER_RANGE_PLACEHOLDER}"]', timeout=5)
|
||||
if not rng or not _is_displayed(rng):
|
||||
raise RuntimeError("未找到可见的「调动时间」选择器")
|
||||
_fill_range(page, rng, start, end)
|
||||
_click_filter(page, popover)
|
||||
|
||||
|
||||
# ==================== 打开台账页并确保登录态 ====================
|
||||
def _ensure_logged_in(page):
|
||||
"""访问调动台账页面;若被重定向到登录页则提示先完成「37duHR登录」。"""
|
||||
page.get(TRANSFER_ROSTER_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise RuntimeError(
|
||||
"HR 登录态已失效。\n"
|
||||
"请先重新运行「37duHR登录」指令,或本地执行 python yingdao/share/hr_login.py\n"
|
||||
"重新登录后再运行本流程。")
|
||||
logger.info("已进入调动台账页面:%s", page.url)
|
||||
|
||||
|
||||
# ==================== 调动台账导出主流程(aa.md 步骤) ====================
|
||||
def _select_org_tree(page):
|
||||
"""切换到组织树并选中「集团」。"""
|
||||
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)
|
||||
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 _click_transfer_tab(page):
|
||||
"""点击「调动已生效」tab,只保留已生效的调动记录。"""
|
||||
tab = page.ele(f'xpath://div[contains(@class,"tab-info")]//*[normalize-space(.)="{TAB_TRANSFER_EFFECTIVE}"]',
|
||||
timeout=10)
|
||||
if not tab:
|
||||
_click_text(page, TAB_TRANSFER_EFFECTIVE)
|
||||
return
|
||||
tab.click()
|
||||
logger.info("已点击「%s」tab", TAB_TRANSFER_EFFECTIVE)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
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
|
||||
btn = page.ele('xpath://button[normalize-space(.)="自定义导出"]', timeout=15)
|
||||
if not btn:
|
||||
btn = page.ele('xpath://*[contains(@class,"btn") and normalize-space(.)="自定义导出"]', timeout=5)
|
||||
if not btn:
|
||||
raise RuntimeError("未找到「自定义导出」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「自定义导出」")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _select_template(page, template_name=TEMPLATE_SHIFT_ABNORMAL):
|
||||
"""选择导出模板「排班异常识别导出」。"""
|
||||
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("未找到「模板」下拉框")
|
||||
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("模板下拉面板未能展开")
|
||||
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(download_dir, before, timeout=DOWNLOAD_FINISH_TIMEOUT):
|
||||
"""等待下载文件生成并大小稳定,返回下载文件路径。"""
|
||||
logger.info("等待下载文件生成(最多 %ds)...", timeout)
|
||||
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.startswith('~$'):
|
||||
continue
|
||||
if 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 内未检测到稳定文件)")
|
||||
|
||||
|
||||
# ==================== 单次导出(带重试,AGENTS.md:最大3次) ====================
|
||||
def _export_one(page, download_dir, template_name, start=None, end=None):
|
||||
"""执行单次调动台账导出(筛选 -> 自定义导出 -> 下载),失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(1, RETRY_TIMES + 1):
|
||||
logger.info(">>> 调动台账导出 第 %d/%d 次(模板:%s)", attempt, RETRY_TIMES, template_name)
|
||||
try:
|
||||
_set_transfer_date_range(page, start, end)
|
||||
_open_custom_export_dialog(page)
|
||||
_select_template(page, template_name)
|
||||
# 触发下载前捕获目录快照,避免下载过快时真实文件被误判为已存在而漏检
|
||||
before = set(os.listdir(download_dir))
|
||||
_click_confirm_export(page)
|
||||
path = _wait_download(download_dir, before)
|
||||
logger.info(">>> 调动台账导出完成")
|
||||
return path
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
logger.exception("调动台账导出失败(第 %d 次),尝试重试:", attempt)
|
||||
time.sleep(WAIT_MID)
|
||||
raise RuntimeError(f"调动台账导出连续失败:{last_err}")
|
||||
|
||||
|
||||
# ==================== 对外入口 ====================
|
||||
def export_transfer_roster(download_dir: str = None, template_name: str = TEMPLATE_SHIFT_ABNORMAL,
|
||||
output_path: str = None, start: str = None, end: str = None) -> str:
|
||||
"""执行调动台账自定义导出(调动时间近30天),返回下载后的 xlsx 文件路径。"""
|
||||
download_dir = os.path.abspath(download_dir or OUTPUT_DIR)
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
if not start or not end:
|
||||
start, end = get_transfer_range()
|
||||
logger.info("===== 开始调动台账导出(模板:%s,日期:%s ~ %s),下载目录:%s =====",
|
||||
template_name, start, end, download_dir)
|
||||
|
||||
page = ChromiumPage(ChromiumOptions())
|
||||
logger.info("浏览器已启动")
|
||||
try:
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
logger.info("加载共享 cookies:%d 个", len(cookies or []))
|
||||
if cookies:
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
except Exception as e:
|
||||
logger.warning("注入共享 cookies 失败:%s", e)
|
||||
|
||||
_ensure_logged_in(page)
|
||||
_select_org_tree(page)
|
||||
_click_transfer_tab(page)
|
||||
page.set.download_path(download_dir)
|
||||
logger.info("浏览器下载目录已设置:%s", download_dir)
|
||||
|
||||
path = _export_one(page, download_dir, template_name, start, end)
|
||||
|
||||
if output_path:
|
||||
output_path = os.path.abspath(output_path)
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
shutil.move(path, output_path)
|
||||
path = output_path
|
||||
elif path.endswith('.xlsx'):
|
||||
renamed = os.path.join(download_dir, SAVE_NAME)
|
||||
if os.path.abspath(path) != os.path.abspath(renamed):
|
||||
shutil.move(path, renamed)
|
||||
path = renamed
|
||||
|
||||
logger.info("===== 调动台账导出完成:%s =====", path)
|
||||
return path
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
"""影刀入口:导出调动台账。缺依赖/未登录会先行报错退出。"""
|
||||
try:
|
||||
out = export_transfer_roster()
|
||||
logger.info("===== 调动台账导出完成:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("调动台账导出失败:%s", e)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,935 @@
|
||||
# -*- 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.8.0
|
||||
- v1.8.0:全部成功时 HR 端不调用结果接口(getTmpDataPage.mc 仅在存在异常行时返回逐行结果),
|
||||
原逻辑会把「未捕获到接口响应」误报为「待人工确认」(成功 0 条)——现改为:流程完整
|
||||
走完(两步「下一步」+「关闭」成功)、监听正常启动且未捕获到任何异常行时,视为全部
|
||||
导入成功,成功数按导入文件条数计,不再误报未确认。
|
||||
- v1.7.1:修复导入条数统计把模板预格式化空白行也计入的问题——改为读 A列序号,
|
||||
取最大序号即需导入条数(原 max_row-3 会因官方模板自带 2000~3000 行空白
|
||||
格式化行误报为几千条)。
|
||||
- v1.7.0:汇总统计「本次调度需增员/减员条数」改从增减员导入文件统计,
|
||||
接口未返回结果的类别仍计入需导入条数并在汇总标注「待人工确认」,避免误报为没有增减员。
|
||||
- v1.6.0:增减员执行顺序改为「先减员、后增员」(原为增员在前,替换/修改人员若先增员
|
||||
会因人员方案冲突直接报错;必须先撤下旧方案,再上新方案)。
|
||||
- v1.5.0:修复监听时机与全量分页——监听从第一个「下一步」前即开启(HR 端流程调整后结果接口
|
||||
可能在第一步即触发,原「第二步前才监听」导致漏捕、误报「未捕获到导入结果接口响应」);
|
||||
wait() 超时返回 False 的判断修正;跳过无 imp_fixed_msg 的格式校验/预览响应;
|
||||
全量翻页改为按首次请求 body 改 pageNo/start 后 POST 拉取(原 GET URL 对 POST 接口无效)。
|
||||
- v1.4.0:钉钉推送改为汇总 + 异常名单拆分多条消息(汇总一条,增员/减员异常名单各一条,
|
||||
名单过长自动分批),仅推接口返回的业务结果。
|
||||
- v1.3.0:导入异常消息写入影刀全局变量 messages(块格式分组列表),供「37du钉钉群机器人推送」指令直接推送;无异常时写入完成提示。
|
||||
- v1.2.0:监听第二个「下一步」(真正导入内容)触发的 getTmpDataPage.mc,捕获并上报导入返回的全部异常;第一个「下一步」为格式校验,不做处理。
|
||||
- v1.1.0:上传表格后监听 getTmpDataPage.mc 解析接口,捕获并上报返回的全部异常(如重复参保),不中断流程。
|
||||
|
||||
设计说明(与 yingdao 下其它单文件版一致):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- 登录态复用共享 hr_cookies.json(缺失/失效引导先运行「37duHR登录」指令,不自动补登)。
|
||||
- 按类别传参(category_names 列表,空/None=全部类别),导入文件取各类别文件夹内的
|
||||
商业保险增员导入.xlsx / 商业保险减员导入.xlsx(由 schedule 步骤生成)。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage openpyxl
|
||||
|
||||
环境变量(.env 文件或系统变量,可选):
|
||||
employer_insurance_base_dir = 雇主险文件目录(默认 D:\\资料\\人资\\雇主险)
|
||||
|
||||
运行:直接执行本文件,按 __main__ 中的示例传参(增员/减员 + 类别列表)调用 main()
|
||||
main(category_names=['三十七度']) 或 import_employee_change(import_type, category_names)
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import traceback
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
from openpyxl import load_workbook
|
||||
except ImportError as _import_err:
|
||||
raise ImportError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install DrissionPage openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
) from _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)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 影刀全局变量(消息/结果写 glv,生成与发送解耦) ====================
|
||||
# 约定见 yingdao/README.md 5.2:业务脚本只生成消息文本写全局变量,
|
||||
# 发送一律由「37du钉钉群机器人推送」指令(yingdao/share/dingtalk_robot.py)完成。
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置(与 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
|
||||
|
||||
# ---------- 接口监听:第二步「下一步」导入内容结果(getTmpDataPage.mc) ----------
|
||||
# 第一个「下一步」为格式校验(不做处理);点击第二个「下一步」(真正导入内容)后,
|
||||
# HR 系统会 POST getTmpDataPage.mc 返回导入结果,其中 datas[].imp_fixed_msg 为逐行导入结果说明:
|
||||
# 异常行如「存在已参保的人员,不允许重复增员!」;成功行返回「导入成功;」(不纳入异常上报)。
|
||||
TMP_DATA_API_MARK = "getTmpDataPage.mc" # 导入内容结果接口(URL 子串过滤)
|
||||
TMP_DATA_STATE_OK = "1" # 导入内容结果接口 state 成功值
|
||||
TMP_DATA_WAIT = 8.0 # 等待导入结果接口响应的超时秒数
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""打开页面被重定向到登录页(cookies 缺失或失效)。"""
|
||||
|
||||
|
||||
class ElementNotFoundError(Exception):
|
||||
"""页面元素/控件未找到(页面结构变化或加载超时)。
|
||||
|
||||
用于区分「UI 状态类失败」(页面没加载出来、元素定位器失效)与其它运行时错误,
|
||||
便于调用方针对性地重试或提示人工介入。
|
||||
"""
|
||||
|
||||
|
||||
# ==================== 登录态(共享 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 ElementNotFoundError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _click_text_in(page, container, text, timeout=5):
|
||||
"""在指定容器内按文本匹配并点击。"""
|
||||
ele = container.ele(f'xpath:.//*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise ElementNotFoundError(f"容器内未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _is_displayed(ele):
|
||||
"""判断元素是否可见且具有尺寸;异常时返回 False(保守不误判)。"""
|
||||
if ele is None:
|
||||
return False
|
||||
try:
|
||||
if not ele.states.is_displayed:
|
||||
return False
|
||||
w, h = ele.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 打开待增减人员页面并确保登录态 ====================
|
||||
def _ensure_logged_in(page):
|
||||
"""访问待增减人员页面;若被重定向到登录页,提示先运行「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 ElementNotFoundError("未找到「更多操作」下拉菜单(#custom-btn-ul)")
|
||||
logger.info("「更多操作」下拉已展开")
|
||||
return menu
|
||||
|
||||
|
||||
def _choose_import_menu(page, menu_label):
|
||||
"""在下拉菜单中选择「增员导入」或「减员导入」。"""
|
||||
menu = _open_more_operations(page)
|
||||
_click_text_in(page, menu, menu_label)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _upload_file(page, file_path):
|
||||
"""在导入弹窗中上传指定文件。
|
||||
|
||||
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 ElementNotFoundError("未找到文件上传控件(input[name=file])")
|
||||
file_input.input(file_path)
|
||||
logger.info("已选择导入文件:%s", file_path)
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
def _click_next(page):
|
||||
"""点击导入弹窗中的「下一步」按钮(btn-success 且可见)。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-success")'
|
||||
' and normalize-space(.)="下一步"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「下一步」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「下一步」")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _click_close(page):
|
||||
"""点击导入完成弹窗中的「关闭」按钮。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-default")'
|
||||
' and normalize-space(.)="关闭"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「关闭」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「关闭」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 接口监听:上传表格后解析结果(getTmpDataPage.mc),捕获返回的全部异常
|
||||
# ---------------------------------------------------------------
|
||||
def _extract_json_response(req):
|
||||
"""从监听到的请求中解析 JSON 响应;解析失败返回 None。"""
|
||||
try:
|
||||
return req.response.json()
|
||||
except Exception:
|
||||
body = getattr(req.response, "body", None)
|
||||
if isinstance(body, (dict, list)):
|
||||
return body
|
||||
if not body:
|
||||
return None
|
||||
try:
|
||||
return json.loads(body)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _merge_datas(result, resp):
|
||||
"""从一次接口响应(resp)中提取并累计统计:需导入总条数、成功数、异常明细。"""
|
||||
for item in resp.get("datas") or []:
|
||||
item = item or {}
|
||||
msg = str(item.get("imp_fixed_msg", "") or "").strip()
|
||||
if not msg:
|
||||
continue
|
||||
# 接口返回的每一行即本次调度的一条需导入记录,全部计入需导入总条数
|
||||
result["total_count"] += 1
|
||||
# HR 对导入成功的行同样返回「导入成功;」等固定文案,成功行只统计数量,
|
||||
# 不纳入异常(否则会被误报为异常,如「异常:导入成功;」)
|
||||
if "导入成功" in msg:
|
||||
result["success_count"] += 1
|
||||
continue
|
||||
result["exceptions"].append({
|
||||
"staff_code": str(item.get("imp_assi_staff_code_ext_table_field_base_id", "") or ""),
|
||||
"staff_name": str(item.get("imp_assi_staff_name_ext_table_field_base_id", "") or ""),
|
||||
"insurance_name": str(item.get("ext_insurance_name", "") or ""),
|
||||
"message": msg,
|
||||
})
|
||||
|
||||
|
||||
def _build_hr_session():
|
||||
"""读取共享 hr_cookies.json 构建可访问 HR 接口的 requests.Session(仅注入 37du.co 域 cookies)。
|
||||
|
||||
与 hr_login.py 的 API 校验同一套构建方式,保证接口请求携带同一登录态。
|
||||
"""
|
||||
if not os.path.isfile(SHARED_HR_COOKIE_FILE):
|
||||
raise FileNotFoundError(f"缺少共享登录态:{SHARED_HR_COOKIE_FILE}")
|
||||
with open(SHARED_HR_COOKIE_FILE, "r", encoding="utf-8") as f:
|
||||
cookies = json.load(f)
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in str(c.get("domain", "")):
|
||||
session.cookies.set(c.get("name"), c.get("value"),
|
||||
domain=c.get("domain"), path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def _fetch_remaining_pages(result, first_url, first_body, page_count, page_size=15):
|
||||
"""getTmpDataPage 每页固定返回 15 条,弹窗只加载第一页时监听只能统计到 15 条,
|
||||
实际导入量常超 15,导致汇总「需增/减员条数、成功/失败数」被截断、异常明细漏统计。
|
||||
此函数用 HR 登录态按 pageNo 主动拉取剩余页并合并全部结果,保证统计覆盖全量。
|
||||
|
||||
注意:该接口为 POST,分页参数(importId/imp_fixed_businessid/start/pageNo/pageSize)
|
||||
在请求 body 中而非 URL 查询串,必须复用首次请求 body 改页码后 POST 拉取,
|
||||
直接 GET URL 会拿不到目标页数据。"""
|
||||
if page_count <= 1:
|
||||
return
|
||||
try:
|
||||
session = _build_hr_session()
|
||||
except Exception as e:
|
||||
logger.warning("分页拉取失败(无法构建 HR 会话):%s,仅统计弹窗第一页", e)
|
||||
return
|
||||
for page_no in range(2, page_count + 1):
|
||||
start = (page_no - 1) * page_size
|
||||
body = re.sub(r"pageNo=\d+", f"pageNo={page_no}", first_body or "")
|
||||
body = re.sub(r"start=\d+", f"start={start}", body)
|
||||
body = re.sub(r"pageSize=\d+", f"pageSize={page_size}", body)
|
||||
try:
|
||||
resp = session.post(first_url, data=body, timeout=15)
|
||||
data = resp.json()
|
||||
except Exception as e:
|
||||
logger.warning("分页第 %s/%s 页拉取失败:%s", page_no, page_count, e)
|
||||
continue
|
||||
if str(data.get("state", "")).strip() != TMP_DATA_STATE_OK:
|
||||
logger.warning("分页第 %s/%s 页返回 state=%s,跳过",
|
||||
page_no, page_count, data.get("state"))
|
||||
continue
|
||||
logger.info("分页第 %s/%s 页返回 %s 条",
|
||||
page_no, page_count, len(data.get("datas") or []))
|
||||
_merge_datas(result, data)
|
||||
|
||||
|
||||
def _capture_import_exceptions(page, timeout=TMP_DATA_WAIT):
|
||||
"""监听导入结果接口(getTmpDataPage.mc),捕获返回的全部异常。
|
||||
|
||||
监听自第一个「下一步」之前即已开启(见 _import_one),因此无论 HR 端是在第一步
|
||||
格式校验/预览还是第二步「真正导入」时才请求 getTmpDataPage.mc 都能捕获到。
|
||||
本函数只处理携带导入结果说明的响应:
|
||||
- state="1" 表示接口正常;meg 为全局提示;
|
||||
- datas[].imp_fixed_msg 为逐行导入结果说明:异常行如「存在已参保的人员,不允许重复增员!」,
|
||||
成功行返回「导入成功;」(成功行不纳入异常上报);
|
||||
- 第一步格式校验/预览的响应行内 imp_fixed_msg 为空,视为无效响应跳过,继续等待最终结果。
|
||||
接口分页返回(每页固定 pageSize=15,响应带 pageCount 总页数),弹窗默认只加载第一页,
|
||||
故捕获首响应后主动按 pageNo 翻页拉取剩余页合并,保证总条数/成功数/异常明细覆盖全量,
|
||||
不再出现「每次固定 15 条」的截断问题。
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
"captured": bool, # 是否捕获到解析接口响应
|
||||
"state": str, # 接口 state(未捕获到为空串)
|
||||
"meg": str, # 全局提示
|
||||
"listen_ok": bool, # 接口监听是否成功启动(False=未监听,结果不可信)
|
||||
"success_count": int, # 接口返回的导入成功行数
|
||||
"total_count": int, # 接口返回的需导入总行数(成功+异常,即本次需导入条数)
|
||||
"exceptions": [ # 全部异常明细
|
||||
{"staff_code":..., "staff_name":..., "insurance_name":..., "message":...}, ...
|
||||
],
|
||||
}
|
||||
"""
|
||||
result = {"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "success_count": 0, "total_count": 0}
|
||||
first_url = None
|
||||
first_body = ""
|
||||
page_count = 1
|
||||
deadline = time.time() + timeout
|
||||
last_hit = time.time()
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
remain = max(0.0, deadline - time.time())
|
||||
req = page.listen.wait(timeout=min(0.5, remain))
|
||||
except Exception as e:
|
||||
logger.warning("监听 %s 接口异常:%s", TMP_DATA_API_MARK, e)
|
||||
break
|
||||
if not req:
|
||||
# DrissionPage wait() 超时返回 False(非 None),统一按「无新响应」处理:
|
||||
# 若已捕获过解析响应,再确认一个间隔后结束,合并所有分页/多次返回的异常
|
||||
if result["captured"] and time.time() - last_hit >= 1.0:
|
||||
break
|
||||
continue
|
||||
if not hasattr(req, "url"):
|
||||
continue
|
||||
if TMP_DATA_API_MARK not in (req.url or ""):
|
||||
continue
|
||||
resp = _extract_json_response(req)
|
||||
if not isinstance(resp, dict):
|
||||
continue
|
||||
# 第一步「下一步」(格式校验/预览)也可能请求 getTmpDataPage.mc,但此时行内
|
||||
# imp_fixed_msg 为空;仅当携带导入结果说明(imp_fixed_msg 非空)时才视为真正的
|
||||
# 导入结果,空说明的预览/校验响应跳过,继续等待最终结果。
|
||||
if not any(str((it or {}).get("imp_fixed_msg", "") or "").strip()
|
||||
for it in (resp.get("datas") or [])):
|
||||
continue
|
||||
result["captured"] = True
|
||||
last_hit = time.time()
|
||||
state = str(resp.get("state", "")).strip()
|
||||
if state:
|
||||
result["state"] = state
|
||||
meg = str(resp.get("meg", "") or "").strip()
|
||||
if meg:
|
||||
result["meg"] = meg
|
||||
# 记录第一页 URL、请求 body 与总页数,用于主动翻页拉全(弹窗默认只加载第一页 15 条)
|
||||
if first_url is None:
|
||||
first_url = req.url
|
||||
# 该接口为 POST,分页参数在 body 中,保存首次请求 body 供翻页复用
|
||||
first_body = req.request.postData or ""
|
||||
try:
|
||||
page_count = max(1, int(resp.get("pageCount") or 1))
|
||||
except Exception:
|
||||
page_count = 1
|
||||
_merge_datas(result, resp)
|
||||
# 若接口存在多页(实际导入量超过一页 15 条),主动翻页拉取剩余页后结束
|
||||
if first_url and page_count > 1:
|
||||
_fetch_remaining_pages(result, first_url, first_body, page_count)
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def _count_import_rows(file_path):
|
||||
"""统计导入文件需导入条数(本次调度生成的增减员导入文件)。
|
||||
|
||||
模板结构:第1行标题 / 第2行表头 / 第3行示例说明,第4行起为数据行,
|
||||
第1列(A列)为数据行序号(1,2,3,...),最大序号即需导入条数。
|
||||
官方模板自带大量预格式化的空白行(max_row 可达 2000~3000 行),因此不能
|
||||
直接用 max_row 统计;取最大序号即可得到真实导入量,与接口是否捕获无关。
|
||||
"""
|
||||
try:
|
||||
wb = load_workbook(file_path, read_only=True)
|
||||
try:
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
max_seq = 0
|
||||
for seq in ws.iter_rows(min_row=4, max_row=ws.max_row,
|
||||
max_col=1, values_only=True):
|
||||
v = seq[0]
|
||||
if v is None or str(v).strip() == "":
|
||||
continue
|
||||
try:
|
||||
max_seq = max(max_seq, int(v))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return max_seq
|
||||
finally:
|
||||
wb.close()
|
||||
except Exception as e:
|
||||
logger.warning("统计导入文件条数失败 %s:%s", file_path, e)
|
||||
return 0
|
||||
|
||||
|
||||
def _import_one(page, category, menu_label, file_path=None):
|
||||
"""对单个类别执行一次导入(更多操作 -> 选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。
|
||||
|
||||
自第一个「下一步」之前即开启对 getTmpDataPage.mc 的监听:HR 端流程调整后,
|
||||
结果接口可能在第一步「格式校验/预览」或第二步「真正导入」时触发,提前监听避免漏捕;
|
||||
监听捕获导入返回的全部异常,异常仅记录并上报,不中断导入流程。
|
||||
|
||||
Returns:
|
||||
dict: 导入结果接口捕获结果(含 exceptions 全部异常明细),见 _capture_import_exceptions。
|
||||
"""
|
||||
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}")
|
||||
# 需导入条数:从本次调度生成的导入文件统计(与接口是否捕获无关,供汇总使用)
|
||||
expected_total = _count_import_rows(file_path)
|
||||
|
||||
logger.info("===== 类别[%s] 开始%s,文件:%s(需导入 %d 条) =====",
|
||||
category["name"], menu_label, file_path, expected_total)
|
||||
_choose_import_menu(page, menu_label)
|
||||
_upload_file(page, file_path)
|
||||
|
||||
# 在第一个「下一步」前开启 getTmpDataPage.mc 监听,贯穿「格式校验/预览 + 真正导入」全过程
|
||||
# 监听启动失败必须上报:若静默继续,未捕获到异常会被误报为「正常」,产生假成功
|
||||
listen_ok = True
|
||||
try:
|
||||
page.listen.start(TMP_DATA_API_MARK)
|
||||
except Exception as e:
|
||||
listen_ok = False
|
||||
logger.error("启动 %s 接口监听失败,无法捕获导入结果:%s", TMP_DATA_API_MARK, e)
|
||||
try:
|
||||
_click_next(page) # 第一步:下一步(格式校验/预览,同时可能在监听中触发结果接口)
|
||||
_click_next(page) # 第二步:下一步(真正导入内容,触发结果接口)
|
||||
import_result = _capture_import_exceptions(page)
|
||||
import_result["listen_ok"] = listen_ok
|
||||
import_result["expected_total"] = expected_total # 需导入条数(来自导入文件)
|
||||
finally:
|
||||
try:
|
||||
page.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 全部成功时 HR 端不会调用结果接口(getTmpDataPage.mc 只在存在异常行时返回逐行结果)。
|
||||
# 若流程已完整走完(两步「下一步」均成功、监听正常启动、未捕获到任何异常行),
|
||||
# 说明全部导入成功:成功数按导入文件条数计,避免误报「接口未返回/待人工确认」。
|
||||
if (not import_result["captured"] and listen_ok and not import_result["exceptions"]):
|
||||
import_result["assumed_all_success"] = True
|
||||
import_result["success_count"] = expected_total
|
||||
import_result["total_count"] = expected_total
|
||||
|
||||
# 上报:全部异常逐条打日志
|
||||
if import_result["exceptions"]:
|
||||
logger.error("类别[%s] %s:导入返回 %d 条异常:",
|
||||
category["name"], menu_label, len(import_result["exceptions"]))
|
||||
for exc in import_result["exceptions"]:
|
||||
logger.error(" - [%s/%s] 方案[%s]:%s",
|
||||
exc["staff_code"], exc["staff_name"], exc["insurance_name"], exc["message"])
|
||||
elif not import_result.get("listen_ok", True):
|
||||
logger.error("类别[%s] %s:接口监听启动失败,无法确认导入结果,请人工核对",
|
||||
category["name"], menu_label)
|
||||
elif import_result["captured"] and import_result["state"] != TMP_DATA_STATE_OK:
|
||||
logger.error("类别[%s] %s:导入接口 state=%s(meg=%s),导入可能失败",
|
||||
category["name"], menu_label, import_result["state"], import_result["meg"])
|
||||
elif import_result.get("assumed_all_success"):
|
||||
logger.info("类别[%s] %s:全部导入成功(全部成功时 HR 不返回结果接口,按文件 %d 条计成功),无异常",
|
||||
category["name"], menu_label, expected_total)
|
||||
elif not import_result["captured"]:
|
||||
logger.warning("类别[%s] %s:未捕获到导入结果接口响应,无法确认导入结果",
|
||||
category["name"], menu_label)
|
||||
else:
|
||||
logger.info("类别[%s] %s:导入成功 %s 人,无异常",
|
||||
category["name"], menu_label, import_result.get("success_count", 0))
|
||||
|
||||
_click_close(page) # 第三步:关闭
|
||||
logger.info("===== 类别[%s] %s完成 =====", category["name"], menu_label)
|
||||
return import_result
|
||||
|
||||
|
||||
# ==================== 钉钉群消息生成(写入全局变量,由「37du钉钉群机器人推送」指令发送) ====================
|
||||
def _build_group_messages(import_type, categories, results, exception_count):
|
||||
"""构建钉钉群机器人推送消息(块格式分组列表 [{title, blocks, status}])。
|
||||
|
||||
拆分为多条独立消息推送(避免异常名单过多时单条消息过长):
|
||||
1. 汇总:标题「雇主险增减员操作完成」,正文为需增员/减员条数、导入成功/失败条数;
|
||||
2. 增员导入异常名单(接口返回的业务异常明细);
|
||||
3. 减员导入异常名单。
|
||||
某操作无异常则不发对应异常名单消息(全部成功时只有 1 条汇总);
|
||||
单条异常名单内异常再多,也会由「37du钉钉群机器人推送」指令按批自动分批发送。
|
||||
|
||||
「本次调度需增员/减员条数」取自已生成的增减员导入文件(results 的 expected_total,
|
||||
与接口是否捕获无关);「导入成功/失败条数」取接口返回的业务结果。
|
||||
代码/流程异常(error)的类别不纳入统计;接口未返回结果(captured=False / state!=1)
|
||||
的类别分两种情况:若流程完整走完且无异常行(assumed_all_success,全部成功时 HR
|
||||
不调用结果接口)→ 按文件条数计全部成功;否则成功/失败未知,汇总中标注「待人工确认」,
|
||||
避免误报为没有增减员。
|
||||
全部类别均无导入数据(文件为空或全部流程失败)→ 返回空列表,不推送。
|
||||
results 每项可带 "menu" 字段(增员导入/减员导入),main() 合并增/减员时使用。
|
||||
"""
|
||||
# 按菜单(增员导入/减员导入)分组统计;需导入条数来自导入文件,成功/失败来自接口
|
||||
group_stats = {} # menu -> {"total":, "success":, "fail":, "excs": [(category, exc), ...]}
|
||||
unconfirmed_menus = {} # menu -> [category, ...](接口未确认结果的类别)
|
||||
for r in results:
|
||||
# 代码/流程异常(登录失败/元素找不到/文件缺失等):无导入数据,不纳入统计(报错进日志)
|
||||
if r.get("error"):
|
||||
continue
|
||||
menu = r.get("menu") or import_type
|
||||
stat = group_stats.setdefault(
|
||||
menu, {"total": 0, "success": 0, "fail": 0, "excs": []})
|
||||
category = r.get("category") or ""
|
||||
# 需导入条数:本次调度生成的增减员导入文件(与接口是否捕获无关)
|
||||
stat["total"] += r.get("expected_total") or 0
|
||||
if not r.get("captured") or r.get("state") != TMP_DATA_STATE_OK:
|
||||
# 接口未捕获/未返回成功:
|
||||
# - assumed_all_success(全部成功时 HR 不调用结果接口,流程完整走完且无异常)
|
||||
# → 按文件条数计全部成功,不再误报「待人工确认」;
|
||||
# - 其余情况成功/失败未知,需导入条数仍计入,记入未确认
|
||||
if r.get("assumed_all_success"):
|
||||
stat["success"] += r.get("success_count") or 0
|
||||
continue
|
||||
unconfirmed_menus.setdefault(menu, []).append(category)
|
||||
continue
|
||||
excs = r.get("exceptions") or []
|
||||
stat["success"] += r.get("success_count") or 0
|
||||
stat["fail"] += len(excs)
|
||||
stat["excs"].extend((category, exc) for exc in excs)
|
||||
|
||||
# 全部无导入数据(文件为空或全部流程失败):不推送,报错交给日志
|
||||
if not any(s["total"] or s["excs"] for s in group_stats.values()):
|
||||
return []
|
||||
|
||||
add_stat = group_stats.get(MENU_ADD, {"total": 0, "success": 0, "fail": 0, "excs": []})
|
||||
sub_stat = group_stats.get(MENU_SUB, {"total": 0, "success": 0, "fail": 0, "excs": []})
|
||||
unconf_add = unconfirmed_menus.get(MENU_ADD, [])
|
||||
unconf_sub = unconfirmed_menus.get(MENU_SUB, [])
|
||||
|
||||
# 标题:按实际分组自动带操作名(减+增合并为「减员增员」,单类型为「减员/增员」)
|
||||
# 顺序与执行顺序一致:先减员、后增员
|
||||
ops = []
|
||||
if sub_stat["total"] or sub_stat["excs"]:
|
||||
ops.append("减员")
|
||||
if add_stat["total"] or add_stat["excs"]:
|
||||
ops.append("增员")
|
||||
title = "雇主险{}操作完成".format("".join(ops) if ops else import_type)
|
||||
|
||||
# 汇总块:需导入条数取自本次调度生成的增减员导入文件;成功/失败取接口返回的业务结果
|
||||
summary_lines = [
|
||||
"**本次调度需增员 {} 条,减员 {} 条**".format(add_stat["total"], sub_stat["total"]),
|
||||
"其中增员导入成功 {} 条,失败 {} 条".format(add_stat["success"], add_stat["fail"]),
|
||||
"其中减员导入成功 {} 条,失败 {} 条".format(sub_stat["success"], sub_stat["fail"]),
|
||||
]
|
||||
if unconf_add:
|
||||
summary_lines.append("⚠️ 增员 {} 个类别接口未返回/未捕获,导入结果待人工确认:{}".format(
|
||||
len(unconf_add), "、".join(unconf_add)))
|
||||
if unconf_sub:
|
||||
summary_lines.append("⚠️ 减员 {} 个类别接口未返回/未捕获,导入结果待人工确认:{}".format(
|
||||
len(unconf_sub), "、".join(unconf_sub)))
|
||||
summary = "\n\n".join(summary_lines)
|
||||
messages = [{
|
||||
"title": title,
|
||||
"blocks": [summary],
|
||||
# 有业务异常或存在未确认类别 → 橙色 warning(提醒查看);全部成功 → 绿色 success
|
||||
"status": "warning" if (add_stat["fail"] or sub_stat["fail"]
|
||||
or unconf_add or unconf_sub) else "success",
|
||||
}]
|
||||
|
||||
# 增员/减员异常名单各拆一条独立消息(名单再长由推送指令按批自动分批发送)
|
||||
for menu, stat in ((MENU_ADD, add_stat), (MENU_SUB, sub_stat)):
|
||||
if not stat["excs"]:
|
||||
continue
|
||||
exc_blocks = []
|
||||
for category, exc in stat["excs"]:
|
||||
exc_blocks.append(
|
||||
"**🔹 {} / {}**\n\n"
|
||||
"> 工号:{}\n\n"
|
||||
"> 姓名:{}\n\n"
|
||||
"> 方案:{}\n\n"
|
||||
"> 异常:{}".format(
|
||||
category,
|
||||
exc.get("staff_name", ""),
|
||||
exc.get("staff_code", ""),
|
||||
exc.get("staff_name", ""),
|
||||
exc.get("insurance_name", "") or "-",
|
||||
exc.get("message", ""),
|
||||
)
|
||||
)
|
||||
messages.append({
|
||||
"title": "【{}】异常名单({} 条)".format(menu, stat["fail"]),
|
||||
"blocks": exc_blocks,
|
||||
"status": "error",
|
||||
})
|
||||
return messages
|
||||
|
||||
|
||||
def _write_group_messages_glv(import_type, categories, results, exception_count):
|
||||
"""把增/减员导入结果写入影刀全局变量 messages,供「37du钉钉群机器人推送」指令读取推送。
|
||||
|
||||
汇总「需导入条数」取自已生成的增减员导入文件(与接口是否捕获无关);代码/流程异常
|
||||
只报错进日志;接口未返回结果的类别分两种情况:全部成功(assumed_all_success,HR
|
||||
全部成功时不调用结果接口)→ 按文件条数计成功;其余未返回 → 需导入条数仍计入汇总并
|
||||
标注「待人工确认」。全部类别均无导入数据时 messages 为空列表,推送指令不会真正发送。
|
||||
"""
|
||||
messages = _build_group_messages(import_type, categories, results, exception_count)
|
||||
_set_glv("messages", messages)
|
||||
biz_exceptions = sum(len(r.get("exceptions") or []) for r in results)
|
||||
# 未确认结果:流程异常、或接口未返回成功(captured=False/state!=1);全部成功推定除外
|
||||
unconfirmed = sum(1 for r in results
|
||||
if not r.get("exceptions")
|
||||
and not r.get("assumed_all_success")
|
||||
and (r.get("error") or not r.get("captured")
|
||||
or r.get("state") != TMP_DATA_STATE_OK))
|
||||
if biz_exceptions:
|
||||
logger.error("汇总消息已写入全局变量 messages:共 %d 条业务异常(由「37du钉钉群机器人推送」指令发送)",
|
||||
biz_exceptions)
|
||||
if unconfirmed:
|
||||
logger.warning("另有 %d 个类别导入结果未确认(流程异常或接口未返回),需导入条数已计入汇总并标注「待人工确认」,请人工核对",
|
||||
unconfirmed)
|
||||
if not biz_exceptions and not unconfirmed:
|
||||
logger.info("完成汇总消息已写入全局变量 messages(由「37du钉钉群机器人推送」指令发送)")
|
||||
|
||||
|
||||
# ==================== 对外入口(函数传参调用,支持多类别) ====================
|
||||
# 参数兼容「增员/减员」短名 与「增员导入/减员导入」菜单全名
|
||||
_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:
|
||||
dict: {
|
||||
"success": bool, # 全部类别流程是否均完成
|
||||
"import_type": str, # 菜单文案(增员导入/减员导入)
|
||||
"categories": [str], # 类别名列表
|
||||
"results": [dict], # 每类别的解析捕获结果(见 _capture_import_exceptions);
|
||||
# 类别流程失败时含 error(错误信息)/error_type(异常类型)字段
|
||||
"exception_count": int, # 上传表格返回的异常总条数
|
||||
}
|
||||
|
||||
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
|
||||
results = []
|
||||
for category in categories:
|
||||
try:
|
||||
res = dict(_import_one(page, category, menu_label, file_path))
|
||||
res["category"] = category["name"]
|
||||
res["menu"] = menu_label
|
||||
results.append(res)
|
||||
ok += 1
|
||||
except Exception as e:
|
||||
logger.exception("类别[%s] %s失败:", category["name"], menu_label)
|
||||
results.append({
|
||||
"category": category["name"], "menu": menu_label,
|
||||
"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"error": str(e),
|
||||
"error_type": type(e).__name__,
|
||||
})
|
||||
exception_count = sum(len(r.get("exceptions") or []) for r in results)
|
||||
logger.info("===== %s 全部完成(成功 %d/%d,异常 %d 条) =====",
|
||||
menu_label, ok, len(categories), exception_count)
|
||||
# 异常/完成消息写入影刀全局变量 messages(供「37du钉钉群机器人推送」指令读取推送)
|
||||
_write_group_messages_glv(
|
||||
menu_label,
|
||||
[c["name"] for c in categories],
|
||||
results,
|
||||
exception_count,
|
||||
)
|
||||
return {
|
||||
"success": ok == len(categories),
|
||||
"import_type": menu_label,
|
||||
"categories": [c["name"] for c in categories],
|
||||
"results": results,
|
||||
"exception_count": exception_count,
|
||||
}
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main(category_names=None):
|
||||
"""影刀自定义指令入口「37du增减员导入」:对指定/全部类别完成减员+增员导入。
|
||||
|
||||
★执行顺序:必须先执行【减员】导入,再执行【增员】导入!涉及替换/修改的人员
|
||||
若先增员会因人员方案冲突直接报错(必须先撤下旧方案,再上新方案)。
|
||||
|
||||
Args:
|
||||
category_names: 类别名列表,空/None=全部类别。
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
"success": bool, # 减员+增员全部类别是否均完成
|
||||
"categories": [str],
|
||||
"details": {"减员导入": bool, "增员导入": bool},
|
||||
"exceptions": [dict], # 全部异常明细(上传表格返回的异常 + 类别流程失败,合并减/增员)
|
||||
"exception_count": int, # 异常总条数
|
||||
}
|
||||
"""
|
||||
load_dotenv()
|
||||
categories = [get_category(n)["name"] for n in category_names] if category_names \
|
||||
else [c["name"] for c in CATEGORIES]
|
||||
details = {}
|
||||
exceptions = []
|
||||
all_results = []
|
||||
ok_all = True
|
||||
# 执行顺序:先全部减员,再全部增员(先增员会让替换/修改人员因方案冲突直接报错)
|
||||
for import_type in ("减员", "增员"):
|
||||
result = import_employee_change(import_type, category_names)
|
||||
details[_IMPORT_TYPE_MAP[import_type]] = result["success"]
|
||||
ok_all = ok_all and result["success"]
|
||||
for r in result["results"]:
|
||||
r["menu"] = r.get("menu") or _IMPORT_TYPE_MAP[import_type]
|
||||
all_results.append(r)
|
||||
# 类别流程本身失败(元素找不到/登录失败/文件缺失等):合并为一条异常上报,避免在推送中漏报
|
||||
if r.get("error"):
|
||||
exceptions.append({
|
||||
"category": r.get("category", ""),
|
||||
"menu": r.get("menu", ""),
|
||||
"staff_code": "", "staff_name": "", "insurance_name": "",
|
||||
"message": f"流程失败({r.get('error_type', 'Exception')}):{r['error']}",
|
||||
})
|
||||
for exc in r.get("exceptions") or []:
|
||||
exceptions.append({
|
||||
"category": r.get("category", ""),
|
||||
"menu": r.get("menu", ""),
|
||||
"staff_code": exc["staff_code"],
|
||||
"staff_name": exc["staff_name"],
|
||||
"insurance_name": exc["insurance_name"],
|
||||
"message": exc["message"],
|
||||
})
|
||||
if exceptions:
|
||||
logger.error("===== 增/减员导入共返回 %d 条异常,明细如下 =====", len(exceptions))
|
||||
for exc in exceptions:
|
||||
logger.error(" - [%s/%s] %s:方案[%s] 异常:%s",
|
||||
exc["category"], exc["staff_code"], exc["staff_name"],
|
||||
exc["insurance_name"], exc["message"])
|
||||
# 合并增/减员结果,覆盖写入影刀全局变量 messages(供「37du钉钉群机器人推送」指令读取推送)
|
||||
_write_group_messages_glv("增员/减员", categories, all_results, len(exceptions))
|
||||
return {
|
||||
"success": ok_all,
|
||||
"categories": categories,
|
||||
"details": details,
|
||||
"exceptions": exceptions,
|
||||
"exception_count": len(exceptions),
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(category_names=["三十七度"])
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,279 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: export_change_sheet.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 雇主险名额调度系统「步骤2.5:导出变更清单独立工作簿」(影刀版,单文件自包含)
|
||||
前置:先运行 employer_insurance_schedule.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
将各类别目标文件中「变更清单」sheet 单独复制为独立工作簿:
|
||||
- 保留样式与格式(字体/边框/填充/数字格式/对齐/列宽/行高/合并单元格)
|
||||
- 单元格内容写为「值」而非公式(以 data_only 读取公式的缓存计算结果),
|
||||
避免独立成簿后公式引用其他 Sheet 产生 #REF! 等计算错误
|
||||
- 不改动原目标文件
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install openpyxl
|
||||
|
||||
环境变量(.env 文件或系统变量,可选,与 employer_insurance_schedule.py 一致):
|
||||
employer_insurance_base_dir = 文件目录(默认 D:\\资料\\人资\\雇主险)
|
||||
|
||||
运行:直接执行本文件即可处理全部类别;仅处理部分类别时以列表传参调用
|
||||
main(category_names=['湖畔酒店'])
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import re
|
||||
import traceback
|
||||
from copy import copy
|
||||
from datetime import datetime, date
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
from openpyxl import Workbook, load_workbook
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,与 employer_insurance_schedule.py 一致) ====================
|
||||
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)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置(与 employer_insurance_schedule.py 一致) ====================
|
||||
BASE_DIR = os.getenv("employer_insurance_base_dir") or r"D:\资料\人资\雇主险"
|
||||
DATE_STR = datetime.now().strftime("%Y.%m.%d")
|
||||
# 变更清单 sheet 名沿用历史模板命名:无横线、月/日不补前导零(如 8.19 / 8.1)
|
||||
DATE_SHORT = f"{datetime.now().month}.{datetime.now().day}"
|
||||
|
||||
# ---------- 四大类别(与 employer_insurance_schedule.py 的 CATEGORIES 一致) ----------
|
||||
CATEGORIES = [
|
||||
{
|
||||
"name": "三十七度",
|
||||
"folder": os.path.join(BASE_DIR, "三十七度"),
|
||||
"change_sheet_prefix": "37度-雇员变更清单",
|
||||
},
|
||||
{
|
||||
"name": "水庄餐饮",
|
||||
"folder": os.path.join(BASE_DIR, "水庄餐饮"),
|
||||
"change_sheet_prefix": "水庄-雇员变更清单",
|
||||
},
|
||||
{
|
||||
"name": "湖畔酒店",
|
||||
"folder": os.path.join(BASE_DIR, "湖畔酒店"),
|
||||
"change_sheet_prefix": "湖畔-雇员变更清单",
|
||||
},
|
||||
{
|
||||
"name": "秒创传媒",
|
||||
"folder": os.path.join(BASE_DIR, "秒创传媒"),
|
||||
"change_sheet_prefix": "秒创-雇员变更清单",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# ---------- 类别辅助函数(与 employer_insurance_schedule.py 一致) ----------
|
||||
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 _target_file_date(filename):
|
||||
"""从目标文件名解析业务日期(优先 YYYY.M.D,回退 M.D 当年)。
|
||||
|
||||
Args:
|
||||
filename: 目标文件名,如「三十七度-雇主险变更记录-2026.08.20.xlsx」/
|
||||
「水庄餐饮-雇主险变更记录-7.23.xlsx」
|
||||
|
||||
Returns:
|
||||
date 对象;无法解析返回 None
|
||||
"""
|
||||
m = re.search(r"(\d{4})\.(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
return None
|
||||
m = re.search(r"(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return date(datetime.now().year, int(m.group(1)), int(m.group(2)))
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def find_latest_target(folder):
|
||||
"""在类别文件夹中定位最新的「*雇主险变更记录*.xlsx」目标文件。
|
||||
|
||||
按「文件名中的业务日期」选择最新(不依赖修改时间),避免昨日文件被改动/
|
||||
打开导致 mtime 更新而被误当成今日文件。
|
||||
|
||||
Args:
|
||||
folder: 类别文件夹路径
|
||||
|
||||
Returns:
|
||||
最新目标文件绝对路径
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 文件夹不存在或其中没有符合条件的雇主险变更记录文件
|
||||
"""
|
||||
if not os.path.isdir(folder):
|
||||
raise FileNotFoundError(f"类别文件夹不存在:{folder}")
|
||||
candidates = [
|
||||
os.path.join(folder, f)
|
||||
for f in os.listdir(folder)
|
||||
if f.lower().endswith(".xlsx") and "雇主险变更记录" in f
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"文件夹 {folder} 下未找到「*雇主险变更记录*.xlsx」文件,请先准备今日的雇主险变更记录模板")
|
||||
|
||||
# 排序键:业务日期优先,同日期内再按修改时间兜底
|
||||
def _sort_key(path):
|
||||
return (_target_file_date(os.path.basename(path)) or date.min,
|
||||
os.path.getmtime(path))
|
||||
|
||||
return max(candidates, key=_sort_key)
|
||||
|
||||
|
||||
def category_target_file(category):
|
||||
"""类别目标文件(各文件夹内最新的雇主险变更记录)。"""
|
||||
return find_latest_target(category["folder"])
|
||||
|
||||
|
||||
def category_change_sheet_workbook(category):
|
||||
"""类别「雇员变更清单」独立工作簿路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], f"{category['name']}-雇员变更清单-{DATE_STR}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_name(category):
|
||||
"""类别「变更清单」sheet 名称(沿用历史模板命名:无横线、不补前导零)。"""
|
||||
return f"{category['change_sheet_prefix']}{DATE_SHORT}"
|
||||
|
||||
|
||||
# ==================== 步骤2.5:导出变更清单独立工作簿 ====================
|
||||
def export_change_sheet_workbook(category):
|
||||
"""将类别目标文件中「变更清单」sheet 复制为独立工作簿(值 + 样式,无公式)。
|
||||
|
||||
以 data_only=True 加载目标文件:公式单元格直接取缓存计算结果(值),普通单元格
|
||||
取原值;样式 / 列宽 / 行高 / 合并单元格原样保留,不改动原目标文件。
|
||||
|
||||
Args:
|
||||
category: 类别配置 dict
|
||||
|
||||
Returns:
|
||||
bool: 是否成功生成(文件缺失 / sheet 不存在时返回 False)。
|
||||
"""
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
change_sheet_name = category_change_sheet_name(category)
|
||||
out_path = category_change_sheet_workbook(category)
|
||||
|
||||
if not os.path.isfile(target_file):
|
||||
logger.warning("类别[%s] 目标文件不存在,跳过:%s", category_name, target_file)
|
||||
return False
|
||||
|
||||
# data_only=True:公式单元格返回其缓存计算结果(值),而非公式字符串
|
||||
wb = load_workbook(target_file, data_only=True)
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
logger.warning("类别[%s] 工作簿中不存在变更清单 sheet [%s],跳过",
|
||||
category_name, change_sheet_name)
|
||||
return False
|
||||
src = wb[change_sheet_name]
|
||||
|
||||
out_wb = Workbook()
|
||||
out_ws = out_wb.active
|
||||
out_ws.title = change_sheet_name
|
||||
|
||||
# 复制单元格(值 + 样式)
|
||||
for row in src.iter_rows():
|
||||
for cell in row:
|
||||
dst = out_ws.cell(row=cell.row, column=cell.column, value=cell.value)
|
||||
if cell.has_style:
|
||||
dst.font = copy(cell.font)
|
||||
dst.border = copy(cell.border)
|
||||
dst.fill = copy(cell.fill)
|
||||
dst.number_format = cell.number_format
|
||||
dst.alignment = copy(cell.alignment)
|
||||
|
||||
# 复制列宽 / 行高
|
||||
for col_letter, dim in src.column_dimensions.items():
|
||||
if dim.width:
|
||||
out_ws.column_dimensions[col_letter].width = dim.width
|
||||
for row_idx, dim in src.row_dimensions.items():
|
||||
if dim.height:
|
||||
out_ws.row_dimensions[row_idx].height = dim.height
|
||||
# 复制合并单元格
|
||||
for mc in src.merged_cells.ranges:
|
||||
out_ws.merge_cells(str(mc))
|
||||
|
||||
out_wb.save(out_path)
|
||||
logger.info("类别[%s] 已导出变更清单独立工作簿:%s(sheet:%s,公式已转为值)",
|
||||
category_name, out_path, change_sheet_name)
|
||||
return True
|
||||
|
||||
|
||||
def main(category_names: list[str] = None):
|
||||
"""步骤2.5:导出变更清单独立工作簿。
|
||||
|
||||
Args:
|
||||
category_names: 类别名列表(如 ["三十七度", "湖畔酒店"]),
|
||||
空列表 / None 表示处理全部类别。
|
||||
|
||||
前置:先运行 employer_insurance_schedule.py(步骤2:调度),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
"""
|
||||
categories = [get_category(n) for n in category_names] if category_names else CATEGORIES
|
||||
for category in categories:
|
||||
try:
|
||||
export_change_sheet_workbook(category)
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 导出变更清单工作簿失败", category["name"])
|
||||
logger.info("全部完成!")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 程序入口(与调度步骤保持一致,默认处理三十七度)
|
||||
# ============================================================
|
||||
if __name__ == "__main__":
|
||||
main(category_names=["三十七度"])
|
||||
@@ -0,0 +1,407 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: roster_filter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险流程「第二步:筛选复制」(影刀版,单文件自包含)——校验源表(员工花名册)
|
||||
与各类别目标表(各文件夹内最新的「*雇主险变更记录*.xlsx」)文件存在性,
|
||||
从花名册按类别 include/exclude 所属单位筛选数据复制到各自类别目标表。
|
||||
前置/后置及流程设计见 docs/雇主险名额调度/需求文档.md、流程文档.md。
|
||||
@Version: 2.0.0
|
||||
|
||||
设计说明(与 yingdao 下其它单文件版一致):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- 源表读取(pandas):自动定位表头行(B 列=「所属单位」),业务列 B~O 共14列;
|
||||
目标表写入(openpyxl):覆盖写入 + 清空超出的旧行。
|
||||
- 源表缺失时默认懒加载共享「37du花名册导出」模块(share/roster_export.py)自动导出(开关见下方环境变量)。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install pandas openpyxl
|
||||
|
||||
环境变量(.env 文件或系统变量,可选):
|
||||
employer_insurance_base_dir = 文件目录(默认 D:\\资料\\人资\\雇主险)
|
||||
roster_filter_export_on_missing = true|false 源表缺失时是否自动导出(默认 true)
|
||||
|
||||
运行:直接执行本文件即可完成全部类别筛选复制;仅处理单个类别时以函数传参调用
|
||||
main(category_names=['湖畔酒店']) 或 filter_and_copy_roster(category)
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import numbers
|
||||
import os
|
||||
import re
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||
try:
|
||||
import pandas as pd
|
||||
from openpyxl import load_workbook
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install 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)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置(与 app 版 config/roster_filter 一致) ====================
|
||||
BASE_DIR = os.getenv("employer_insurance_base_dir") or r"D:\资料\人资\雇主险"
|
||||
DATE_STR = datetime.now().strftime("%Y.%m.%d") # 目标表文件名带日期(如 2026.08.13)
|
||||
|
||||
EMPLOYEE_FILE = os.path.join(BASE_DIR, "员工花名册.xlsx") # 源表(花名册)
|
||||
SHEET_BIZ = "花名册导出-雇主险使用基础信息" # 目标 Sheet
|
||||
|
||||
# ---------- 四大类别(全流程按类别传参处理,与 app 版 config.CATEGORIES 一致) ----------
|
||||
# 每类一个独立文件夹,目标文件为文件夹内最新的「*雇主险变更记录*.xlsx」;
|
||||
# include_dept: 仅保留的所属单位(空列表=不限制);exclude_dept: 需要排除的所属单位。
|
||||
CATEGORIES = [
|
||||
{
|
||||
"name": "三十七度",
|
||||
"folder": os.path.join(BASE_DIR, "三十七度"),
|
||||
"include_dept": [],
|
||||
"exclude_dept": ["金色湖畔事业部", "秒创传媒事业部", "水庄大鹅事业部"],
|
||||
},
|
||||
{
|
||||
"name": "水庄餐饮",
|
||||
"folder": os.path.join(BASE_DIR, "水庄餐饮"),
|
||||
"include_dept": ["水庄大鹅事业部"],
|
||||
"exclude_dept": [],
|
||||
},
|
||||
{
|
||||
"name": "湖畔酒店",
|
||||
"folder": os.path.join(BASE_DIR, "湖畔酒店"),
|
||||
"include_dept": ["金色湖畔事业部"],
|
||||
"exclude_dept": [],
|
||||
},
|
||||
{
|
||||
"name": "秒创传媒",
|
||||
"folder": os.path.join(BASE_DIR, "秒创传媒"),
|
||||
"include_dept": ["秒创传媒事业部"],
|
||||
"exclude_dept": [],
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# ---------- 类别辅助函数(全流程共用,与 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 _target_file_date(filename):
|
||||
"""从目标文件名解析业务日期(优先 YYYY.M.D,回退 M.D 当年)。
|
||||
|
||||
Args:
|
||||
filename: 目标文件名,如「三十七度-雇主险变更记录-2026.08.20.xlsx」/
|
||||
「水庄餐饮-雇主险变更记录-7.23.xlsx」
|
||||
|
||||
Returns:
|
||||
datetime 对象;无法解析返回 None
|
||||
"""
|
||||
m = re.search(r"(\d{4})\.(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
return None
|
||||
m = re.search(r"(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return datetime(datetime.now().year, int(m.group(1)), int(m.group(2)))
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def find_latest_target(folder):
|
||||
"""在类别文件夹中定位最新的「*雇主险变更记录*.xlsx」目标文件。
|
||||
|
||||
按「文件名中的业务日期」选择最新(不依赖修改时间),避免昨日文件被改动/
|
||||
打开导致 mtime 更新而被误当成今日文件(曾因此把变更清单写进昨日文件)。
|
||||
|
||||
Args:
|
||||
folder: 类别文件夹路径
|
||||
|
||||
Returns:
|
||||
最新目标文件绝对路径
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 文件夹不存在或其中没有符合条件的雇主险变更记录文件
|
||||
"""
|
||||
if not os.path.isdir(folder):
|
||||
raise FileNotFoundError(f"类别文件夹不存在:{folder}")
|
||||
candidates = [
|
||||
os.path.join(folder, f)
|
||||
for f in os.listdir(folder)
|
||||
if f.lower().endswith(".xlsx") and "雇主险变更记录" in f
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"文件夹 {folder} 下未找到「*雇主险变更记录*.xlsx」文件,请先准备今日的雇主险变更记录模板")
|
||||
|
||||
# 排序键:业务日期优先,同日期内再按修改时间兜底
|
||||
def _sort_key(path):
|
||||
return (_target_file_date(os.path.basename(path)) or datetime.min,
|
||||
os.path.getmtime(path))
|
||||
|
||||
return max(candidates, key=_sort_key)
|
||||
|
||||
|
||||
# 过滤规则(与 aa.md 宏一致)
|
||||
EXCLUDE_REGION = "虚拟大区" # 统一排除的一级部门(各类别均生效)
|
||||
EXCLUDE_NAME_KEYWORDS = ["人资", "测试"] # 姓名(N列)含这些关键字的行剔除(测试账号/人资账号等)
|
||||
|
||||
# N列 姓名在数据切片(B~O)内的 0-based 索引
|
||||
NAME_COL = 12
|
||||
|
||||
# 源表/目标表格式规范(共享「37du花名册导出」输出统一格式)
|
||||
SOURCE_HEADER_MARK = "所属单位" # 源表表头定位标记(B列)
|
||||
EXPORT_TEMPLATE = "雇主险增减员导出模板" # 雇主险源表使用的自定义导出模板
|
||||
TARGET_HEADER_ROW = 4 # 目标表表头在第4行(数据第5行起)
|
||||
DATA_COLUMNS = 14 # B~O 共14列(所属单位..证件号)
|
||||
|
||||
# 源表缺失时是否自动调用共享导出模块(默认 true)
|
||||
AUTO_EXPORT_ON_MISSING = os.getenv("roster_filter_export_on_missing", "true").lower() == "true"
|
||||
|
||||
# F列 工号(必须文本格式,否则与「手动维护-在参名单」B列及表内公式匹配失败)
|
||||
CODE_COL = 4 # 数据切片(B~O)内 0-based 索引,即目标表第6列(F列)
|
||||
|
||||
|
||||
def _to_text(value):
|
||||
"""将工号等主键值统一转为文本,避免数字/文本混存导致 Excel 公式匹配失败。
|
||||
|
||||
整型 float(如 10086.0)去掉小数点后转 str,保证与文本工号(如"10086")一致。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if pd.isna(value):
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, numbers.Integral):
|
||||
return str(int(value))
|
||||
if isinstance(value, numbers.Real):
|
||||
f = float(value)
|
||||
if f.is_integer():
|
||||
return str(int(f))
|
||||
return str(value)
|
||||
|
||||
|
||||
def filter_and_copy_roster(category: dict, employee_file: str = None, target_file: str = None) -> int:
|
||||
"""从员工花名册按类别筛选数据,复制到该类别的雇主险变更记录表(仅复制,不校验)。
|
||||
|
||||
Args:
|
||||
category: 类别配置(CATEGORIES 中的一项),含 name/folder/include_dept/exclude_dept
|
||||
employee_file: 源表路径,默认 {BASE_DIR}\\员工花名册.xlsx
|
||||
target_file: 目标表路径,默认取该类别文件夹内最新的「*雇主险变更记录*.xlsx」
|
||||
|
||||
Returns:
|
||||
复制的数据行数
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 源表或目标表不存在
|
||||
ValueError: 源表列数不足 或 目标表缺少指定 Sheet
|
||||
"""
|
||||
category_name = category["name"]
|
||||
employee_file = os.path.abspath(employee_file or EMPLOYEE_FILE)
|
||||
target_file = os.path.abspath(target_file or find_latest_target(category["folder"]))
|
||||
|
||||
if not os.path.exists(employee_file):
|
||||
raise FileNotFoundError(f"源表不存在:{employee_file}")
|
||||
if not os.path.exists(target_file):
|
||||
raise FileNotFoundError(f"目标表不存在:{target_file}")
|
||||
|
||||
# ---------- 1. 读取源表(统一规范:单 sheet,自动定位表头行,业务列 B~O) ----------
|
||||
# 先不设表头读取前几行,找到 B 列 =「所属单位」的表头行位置
|
||||
probe = pd.read_excel(employee_file, header=None, nrows=8)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if str(probe.iloc[idx, 1]).strip() == SOURCE_HEADER_MARK:
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"源表未找到表头行(B 列应为「{SOURCE_HEADER_MARK}」)")
|
||||
|
||||
df = pd.read_excel(employee_file, header=header_row)
|
||||
if df.shape[1] < DATA_COLUMNS + 1:
|
||||
raise ValueError(f"源表列数不足:{df.shape[1]}(需要 B~O 共{DATA_COLUMNS}列)")
|
||||
data = df.iloc[:, 1:DATA_COLUMNS + 1].copy() # B~O 14列(「类型」列在末尾,不受影响)
|
||||
|
||||
# 与宏一致:以 B 列(所属单位)最后非空行为数据边界
|
||||
data = data[data.iloc[:, 0].notna()]
|
||||
|
||||
# ---------- 2. 过滤:按类别 include/exclude 所属单位 + 统一排除「虚拟大区」 + 姓名关键字剔除 ----------
|
||||
dept = data.iloc[:, 0].astype(str).str.strip()
|
||||
region = data.iloc[:, 1].astype(str).str.strip()
|
||||
name = data.iloc[:, NAME_COL].astype(str).str.strip()
|
||||
include_dept = category.get("include_dept") or []
|
||||
exclude_dept = category.get("exclude_dept") or []
|
||||
mask = ~(region == EXCLUDE_REGION)
|
||||
if include_dept:
|
||||
mask &= dept.isin(include_dept)
|
||||
if exclude_dept:
|
||||
mask &= ~dept.isin(exclude_dept)
|
||||
for kw in EXCLUDE_NAME_KEYWORDS:
|
||||
mask &= ~name.str.contains(kw, na=False)
|
||||
filtered = data[mask]
|
||||
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除「%s」,姓名剔除含 %s)",
|
||||
category_name, len(data), len(filtered),
|
||||
include_dept or "全部", exclude_dept or "无", EXCLUDE_REGION,
|
||||
" / ".join(EXCLUDE_NAME_KEYWORDS))
|
||||
if len(filtered) == 0:
|
||||
logger.warning("类别[%s] 筛选后没有数据!", category_name)
|
||||
|
||||
# ---------- 3. 写目标表(先覆盖写入,只清空超出新数据的旧行) ----------
|
||||
wb = load_workbook(target_file)
|
||||
if SHEET_BIZ not in wb.sheetnames:
|
||||
raise ValueError(f"目标表缺少 Sheet:{SHEET_BIZ}")
|
||||
ws = wb[SHEET_BIZ]
|
||||
first_data_row = TARGET_HEADER_ROW + 1 # 第5行
|
||||
|
||||
# 找 B 列当前最后非空数据行(用于清空多余旧行)
|
||||
old_last = first_data_row - 1
|
||||
for r in range(first_data_row, ws.max_row + 1):
|
||||
if ws.cell(row=r, column=2).value is not None:
|
||||
old_last = r
|
||||
|
||||
# 写入 B~O(覆盖旧数据,本地化 cell 引用减少开销;F列工号强制文本格式)
|
||||
rows = filtered.values.tolist()
|
||||
cell = ws.cell
|
||||
for i, row in enumerate(rows, start=first_data_row):
|
||||
for j, val in enumerate(row, start=2):
|
||||
c = cell(row=i, column=j)
|
||||
if j - 2 == CODE_COL:
|
||||
c.value = _to_text(val)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = val
|
||||
|
||||
# 清空超出新数据的旧行
|
||||
new_last = first_data_row + len(rows) - 1
|
||||
if old_last > new_last:
|
||||
for r in range(new_last + 1, old_last + 1):
|
||||
for c in range(2, 2 + DATA_COLUMNS):
|
||||
cell(row=r, column=c).value = None
|
||||
|
||||
wb.save(target_file)
|
||||
logger.info("类别[%s] 已写入目标表 %s 第%d行起,共 %d 行", category_name, target_file, first_data_row, len(rows))
|
||||
return len(rows)
|
||||
|
||||
|
||||
def _export_roster():
|
||||
"""源表缺失时,懒加载共享「37du花名册导出」模块(share/roster_export.py)导出雇主险源表。
|
||||
|
||||
登录态复用「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:
|
||||
spec = importlib.util.spec_from_file_location("share_roster_export", share_script)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
except Exception as e:
|
||||
raise RuntimeError(
|
||||
f"源表缺失且无法加载共享导出模块 share/roster_export.py({e}),"
|
||||
f"请先运行「37du花名册导出」指令导出花名册到 {EMPLOYEE_FILE}") from e
|
||||
output = mod.export_roster(
|
||||
template_name=EXPORT_TEMPLATE,
|
||||
statuses=["在职"],
|
||||
output_path=EMPLOYEE_FILE,
|
||||
)
|
||||
logger.info("花名册导出完成:%s", output)
|
||||
|
||||
|
||||
def main(category_names: list[str] = None) -> None:
|
||||
"""第二步:文件存在性校验 + 类别筛选复制(源表缺失时自动导出)。
|
||||
|
||||
Args:
|
||||
category_names: 类别名列表(如 ["三十七度", "湖畔酒店"]),
|
||||
空列表 / None 表示处理全部类别。
|
||||
|
||||
说明:openpyxl 写入后公式列(P~W 工种类别/投保方案/方案处理)的缓存结果会丢失,
|
||||
需手动打开各目标文件刷新公式计算结果并保存,确认复制无误后再运行 schedule 步骤
|
||||
(employer_insurance_schedule.py)。
|
||||
"""
|
||||
categories = [get_category(n) for n in category_names] if category_names else CATEGORIES
|
||||
|
||||
# 源表(员工花名册)缺失才自动导出
|
||||
if not os.path.exists(EMPLOYEE_FILE):
|
||||
if AUTO_EXPORT_ON_MISSING:
|
||||
logger.info("源表不存在:%s,自动调用导出步骤...", EMPLOYEE_FILE)
|
||||
_export_roster()
|
||||
else:
|
||||
raise FileNotFoundError(f"源表不存在:{EMPLOYEE_FILE}")
|
||||
else:
|
||||
logger.info("源表已存在:%s,跳过导出", EMPLOYEE_FILE)
|
||||
|
||||
# 逐类别筛选复制(目标文件=各文件夹内最新的雇主险变更记录)
|
||||
ok = 0
|
||||
for category in categories:
|
||||
try:
|
||||
target_file = find_latest_target(category["folder"])
|
||||
except FileNotFoundError as e:
|
||||
logger.error("跳过类别[%s]:%s", category["name"], e)
|
||||
continue
|
||||
logger.info("=" * 70)
|
||||
logger.info("处理类别[%s],目标文件:%s", category["name"], target_file)
|
||||
try:
|
||||
n = filter_and_copy_roster(category, target_file=target_file)
|
||||
ok += 1
|
||||
logger.info("类别[%s] 完成,写入 %d 行", category["name"], n)
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 处理失败", category["name"])
|
||||
|
||||
logger.info("=" * 70)
|
||||
logger.info("筛选复制完成(成功 %d/%d 个类别)。请手动打开各目标文件刷新公式计算结果(Ctrl+S 保存),",
|
||||
ok, len(categories))
|
||||
logger.info("确认无误后运行:python employer_insurance_schedule.py")
|
||||
logger.info("=" * 70)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(category_names=["三十七度"])
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,793 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: bank_card_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 银行卡检查(单文件版,app 与影刀共用)——复用共享 HR 登录态 -> 调用工资卡接口
|
||||
下载在职+离职工资卡数据 -> 核对身份证/姓名/银行卡号 -> 导出核对结果 + 异常名单
|
||||
-> 打包结果 zip 写入全局变量 messages(由「37du钉钉单聊推送」指令发送)。
|
||||
规则见 docs/银行卡检查/需求文档.md。
|
||||
@Version: 1.1.0
|
||||
|
||||
设计说明(避免维护 app/影刀两套版本):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- 登录态复用共享 hr_cookies.json(由「37duHR登录」指令写入),只读、缺失/失效时
|
||||
友好提示先运行登录指令,不自动补登。
|
||||
- 结果打包后仅写影刀全局变量 messages(file 类型,指向 zip),发送由推送指令完成。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install python-dotenv requests pandas openpyxl
|
||||
|
||||
环境变量(.env 文件或系统变量):
|
||||
可选:wage_card_output_dir=结果输出目录(默认 D:\\资料\\人资\\银行卡检查)
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import functools
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install python-dotenv 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\BankCardCheck(影刀版独立子目录)
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation', 'BankCardCheck'
|
||||
)
|
||||
# 共享登录态 cookies:由「37duHR登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation', '.sessions', 'hr_cookies.json'
|
||||
)
|
||||
|
||||
# ---------- HR 系统 ----------
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
|
||||
# ---------- 工资卡接口 ----------
|
||||
WAGE_CARD_URL = f"{HR_BASE_URL}/RedseaPlatform/getPageAjax/HrStaffWageCard.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ---------- 银行字典接口(aa.md 提供,按 BANK_TYPE 匹配 code -> 开卡银行) ----------
|
||||
BANK_DICT_URL = f"{HR_BASE_URL}/RedseaPlatform/PtCodeTypeValue.mc?method=getCodeValueByCodes"
|
||||
BANK_DICT_CODE_TYPE = "WAGE.BANKTYPE"
|
||||
BANK_DICT_EXPIRE_SEC = 7 * 24 * 60 * 60 # 缓存7天过期,自动重新拉取
|
||||
BANK_DICT_LIST_FILE = os.path.join(_APP_DATA_DIR, "bank_dict_list.json")
|
||||
BANK_DICT_MAP_FILE = os.path.join(_APP_DATA_DIR, "bank_dict_map.json")
|
||||
|
||||
# ---------- 输出 ----------
|
||||
OUTPUT_DIR = os.getenv("wage_card_output_dir") or r"D:\资料\人资\银行卡检查"
|
||||
SAVE_NAME = "工资卡汇总表.xlsx"
|
||||
|
||||
# ---------- 打包推送(结果 zip 写全局变量 messages,由「37du钉钉单聊推送」指令发送) ----------
|
||||
PUSH_RECEIVER_NAME = "刘纤"
|
||||
PUSH_RECEIVER_ID = "37001090"
|
||||
ZIP_NAME_PREFIX = "银行卡检查结果"
|
||||
|
||||
# ---------- 工资卡字段映射 ----------
|
||||
COL_MAP = {
|
||||
"STAFF_NAME": "员工姓名",
|
||||
"STAFF_ID": "员工ID",
|
||||
"IDCARD": "身份证号",
|
||||
"join_date": "入职日期",
|
||||
"leaveOffice_date": "离职日期",
|
||||
"BELONG_UNIT_ORG_NAME": "所属事业部",
|
||||
"DEPT_ORG_NAME": "小组部门",
|
||||
"ORG_FULL_PATH": "组织全路径",
|
||||
"IS_MAIN": "是否主卡",
|
||||
"BANK_TYPE": "银行编码",
|
||||
"BANK_ACCOUNT": "银行卡号",
|
||||
"CARD_ID": "卡片ID",
|
||||
"base_code": "基地编码",
|
||||
"BRANCH_BANK": "支行编码",
|
||||
"bank_province": "银行省份",
|
||||
"bank_city": "银行城市",
|
||||
"wage_card_type": "工资卡类型",
|
||||
"branch_bank_name": "支行名称",
|
||||
"bank_no": "银行行号",
|
||||
"CARD_NAME": "开户人姓名",
|
||||
"CARD_IDCARD": "开户人身份证",
|
||||
"ext_remark": "备注",
|
||||
"si_name": "参保地点",
|
||||
"operator_name": "操作人",
|
||||
"OPERATE_TIME": "操作时间",
|
||||
"BANK_NUM": "银行卡序号",
|
||||
}
|
||||
SHOW_ORDER = [
|
||||
"人员类型", "员工姓名", "员工ID", "身份证号", "入职日期", "离职日期",
|
||||
"所属事业部", "小组部门", "组织全路径", "是否主卡",
|
||||
"银行编码", "开卡银行", "银行卡号", "开户人姓名", "参保地点", "操作人", "操作时间",
|
||||
]
|
||||
|
||||
# ---------- 核对相关列名 ----------
|
||||
COL_IDCARD = "身份证号"
|
||||
COL_CARD_IDCARD = "开户人身份证"
|
||||
COL_STAFF_NAME = "员工姓名"
|
||||
COL_CARD_NAME = "开户人姓名"
|
||||
COL_BANK_ACCOUNT = "银行卡号"
|
||||
COL_BANK_NAME = "开卡银行"
|
||||
COL_BANK_STATUS = "银行卡状态"
|
||||
COL_BANK_REASON = "银行卡说明"
|
||||
COL_CHECK_RESULT = "核对结果"
|
||||
COL_CHECK_BASIS = "校验依据"
|
||||
|
||||
# ---------- 银行卡校验规则 ----------
|
||||
# 16 位银联卡 BIN(按银行归类,经实际工资卡数据比对核验)
|
||||
BIN_16 = {
|
||||
# 招商银行
|
||||
"621483", "621485", "621486", "622588", "622609",
|
||||
# 民生银行
|
||||
"621691", "622615", "622617", "622619", "622620", "622622",
|
||||
# 民生银行信用卡(16 位贷记卡)
|
||||
"622601",
|
||||
# 重庆农村商业银行
|
||||
"621258", "621465", "621528", "622867",
|
||||
# 浦东发展银行
|
||||
"621792", "621793", "622521",
|
||||
# 其他银行
|
||||
"621499", # 建设银行理财金卡
|
||||
"621755", # 重庆三峡银行
|
||||
"623020", # 华夏银行
|
||||
}
|
||||
# 18 位银联储蓄卡 BIN
|
||||
BIN_18 = {"622908"} # 兴业银行
|
||||
# 非 62 开头但合法的老版储蓄卡 BIN(历史卡仍在使用,标准均为 19 位)
|
||||
NON62_BIN = {
|
||||
"436742", # 建设银行龙卡储蓄卡
|
||||
"601382", # 中国银行长城电子借记卡
|
||||
"955882", # 工商银行牡丹灵通卡
|
||||
}
|
||||
NUM_REG = re.compile(r"^\d+$")
|
||||
|
||||
|
||||
# ==================== 重试装饰器 ====================
|
||||
def retry(max_attempts=3):
|
||||
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 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)
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态 cookies 缺失或失效,需先调用「37duHR登录」指令。"""
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
# ==================== HR 登录态(requests.Session) ====================
|
||||
def get_hr_session():
|
||||
"""构建 HR requests.Session(只读共享 cookies,缺失/失效抛 LoginRequiredError)。"""
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
has_hr = any(c.get("domain") and c["domain"].endswith("hr.37du.co") for c in cookies)
|
||||
if not has_hr:
|
||||
raise LoginRequiredError(
|
||||
"共享 cookies 中无 hr.37du.co 登录态,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
logger.info("复用共享 HR 登录态(hr.37du.co,%d 个 cookies)", len(cookies))
|
||||
return _build_hr_session(cookies)
|
||||
|
||||
|
||||
def _build_hr_session(cookies=None):
|
||||
cookies = cookies or _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and c["domain"].endswith("hr.37du.co"):
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 银行字典接口(aa.md 提供) ====================
|
||||
def _fetch_bank_dict(session=None):
|
||||
"""远程调用接口获取银行字典,并写入本地缓存。
|
||||
|
||||
返回 (list[dict], dict[code->name])。
|
||||
"""
|
||||
if session is None:
|
||||
session = get_hr_session()
|
||||
payload = {
|
||||
"codeType": BANK_DICT_CODE_TYPE,
|
||||
"inUse": "0,1,2",
|
||||
"platformMode": "redseaPlatform",
|
||||
}
|
||||
resp = session.post(BANK_DICT_URL, data=payload, timeout=30)
|
||||
resp.raise_for_status()
|
||||
resp_json = resp.json()
|
||||
raw_list = resp_json.get(BANK_DICT_CODE_TYPE) or []
|
||||
result_list = [{"code": str(item.get("code", "")), "name": item.get("name", "")}
|
||||
for item in raw_list]
|
||||
result_map = {item["code"]: item["name"] for item in result_list}
|
||||
|
||||
_ensure_dir(_APP_DATA_DIR)
|
||||
with open(BANK_DICT_LIST_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(result_list, f, ensure_ascii=False, indent=2)
|
||||
with open(BANK_DICT_MAP_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(result_map, f, ensure_ascii=False, indent=2)
|
||||
logger.info("银行字典远程拉取完成,共 %d 条", len(result_list))
|
||||
return result_list, result_map
|
||||
|
||||
|
||||
def _load_bank_dict_cache():
|
||||
"""读取本地银行字典缓存,失败返回 (None, None)。"""
|
||||
try:
|
||||
with open(BANK_DICT_LIST_FILE, "r", encoding="utf-8") as f:
|
||||
lst = json.load(f)
|
||||
with open(BANK_DICT_MAP_FILE, "r", encoding="utf-8") as f:
|
||||
mp = json.load(f)
|
||||
return lst, mp
|
||||
except Exception as e:
|
||||
logger.warning("银行字典本地缓存读取失败:%s", e)
|
||||
return None, None
|
||||
|
||||
|
||||
def get_bank_dict(session=None, force_refresh=False):
|
||||
"""获取银行字典(优先本地缓存,过期/强制刷新才请求接口)。
|
||||
|
||||
:param session: 可选的 HR requests.Session;未提供时自动构建
|
||||
:param force_refresh: True 强制重新调用接口
|
||||
:return: (list版本, map版本)
|
||||
"""
|
||||
need_refresh = force_refresh
|
||||
if not (os.path.exists(BANK_DICT_LIST_FILE) and os.path.exists(BANK_DICT_MAP_FILE)):
|
||||
need_refresh = True
|
||||
else:
|
||||
mtime = os.path.getmtime(BANK_DICT_LIST_FILE)
|
||||
if time.time() - mtime > BANK_DICT_EXPIRE_SEC:
|
||||
need_refresh = True
|
||||
|
||||
if need_refresh:
|
||||
try:
|
||||
return _fetch_bank_dict(session)
|
||||
except Exception as e:
|
||||
logger.error("银行字典远程拉取失败:%s", e)
|
||||
lst, mp = _load_bank_dict_cache()
|
||||
if lst is not None:
|
||||
logger.warning("降级使用本地银行字典缓存,共 %d 条", len(lst))
|
||||
return lst, mp
|
||||
return [], {}
|
||||
|
||||
lst, mp = _load_bank_dict_cache()
|
||||
if lst is None:
|
||||
# 缓存异常时重新拉取
|
||||
return _fetch_bank_dict(session)
|
||||
logger.info("读取本地银行字典缓存,共 %d 条", len(lst))
|
||||
return lst, mp
|
||||
|
||||
|
||||
def _bank_type_to_name(bank_type, bank_map):
|
||||
"""按银行编码(BANK_TYPE)匹配字典 code,返回开卡银行;未命中返回空串。"""
|
||||
if bank_type is None:
|
||||
return ""
|
||||
if isinstance(bank_type, float):
|
||||
if bank_type != bank_type: # NaN
|
||||
return ""
|
||||
bank_type = str(int(bank_type))
|
||||
elif isinstance(bank_type, int):
|
||||
bank_type = str(bank_type)
|
||||
else:
|
||||
bank_type = str(bank_type).strip()
|
||||
return bank_map.get(bank_type, "")
|
||||
|
||||
|
||||
# ==================== 工资卡接口 ====================
|
||||
class HRSessionExpiredError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fetch_wage_card_page(session, status, page_no=1, page_size=PAGE_MAX_SIZE,
|
||||
leave_start=None, leave_end=None):
|
||||
params = {
|
||||
"start": (page_no - 1) * page_size,
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
"ftl_list_STRU_TREE_CODE": "cq37du",
|
||||
"sortName": "hr_staff_wage_card.STAFF_NAME",
|
||||
"sortType": "asc",
|
||||
"commonQuery": "[]",
|
||||
"person_status": status,
|
||||
}
|
||||
if status == 1:
|
||||
params["leaveOffice_date"] = ""
|
||||
elif leave_start and leave_end:
|
||||
params["leaveOffice_date[0]"] = leave_start
|
||||
params["leaveOffice_date[1]"] = leave_end
|
||||
params["leaveOffice_date_start"] = leave_start
|
||||
params["leaveOffice_date_end"] = leave_end
|
||||
|
||||
resp = session.post(WAGE_CARD_URL, data=params, timeout=20)
|
||||
if not resp:
|
||||
raise RuntimeError("工资卡请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"工资卡接口状态码异常: {resp.status_code}")
|
||||
text = resp.text or ""
|
||||
if text and not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容")
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
body = text[:200]
|
||||
raise RuntimeError(f"工资卡接口返回非 JSON 数据(状态码 {resp.status_code}): {body}")
|
||||
|
||||
|
||||
def fetch_all_wage_card(session, status, status_name, leave_start=None, leave_end=None):
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_wage_card_page(session, status, page_no, PAGE_MAX_SIZE, leave_start, leave_end)
|
||||
except HRSessionExpiredError:
|
||||
raise LoginRequiredError(
|
||||
f"【{status_name}】HR 登录态已过期,请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
|
||||
if data.get("state") != "1":
|
||||
logger.error("【%s】第%d页请求失败:%s", status_name, page_no, data.get("meg"))
|
||||
break
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("【%s】无更多数据", status_name)
|
||||
break
|
||||
|
||||
for item in page_list:
|
||||
item["人员类型"] = status_name
|
||||
all_rows.extend(page_list)
|
||||
|
||||
total = data.get("count", 0)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("【%s】已抓取 %d/%d 页,累计 %d/%d 条",
|
||||
status_name, page_no, total_page, len(all_rows), total)
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 离职时间范围 ====================
|
||||
def get_leave_range(today=None):
|
||||
"""根据当前日期计算离职筛选时间范围,返回 (开始日期, 结束日期)。
|
||||
|
||||
规则:每月 8 号及之前 → 上月 1 日 到 今天;
|
||||
每月 8 号之后 → 本月 1 日 到 今天。
|
||||
"""
|
||||
today = today or date.today()
|
||||
if today.day <= 8:
|
||||
first_this_month = today.replace(day=1)
|
||||
last_prev_month = first_this_month - timedelta(days=1)
|
||||
start = last_prev_month.replace(day=1)
|
||||
else:
|
||||
start = today.replace(day=1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 工资卡导出 Excel ====================
|
||||
def export_excel(data_on_job, data_leave, save_dir):
|
||||
if not (data_on_job or data_leave):
|
||||
raise ValueError("未查询到任何数据,无法导出")
|
||||
|
||||
total_all = data_on_job + data_leave
|
||||
df = pd.DataFrame(total_all)
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
# 补充开卡银行:按银行编码(BANK_TYPE)匹配字典 code
|
||||
if "开卡银行" not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df["开卡银行"] = df["银行编码"].apply(lambda c: _bank_type_to_name(c, bank_map))
|
||||
exist_cols = [col for col in SHOW_ORDER if col in df.columns]
|
||||
other_cols = [col for col in df.columns if col not in exist_cols]
|
||||
df = df[exist_cols + other_cols]
|
||||
|
||||
_ensure_dir(save_dir)
|
||||
save_path = os.path.join(save_dir, SAVE_NAME)
|
||||
df.to_excel(save_path, index=False)
|
||||
logger.info("在职数据:%d 条", len(data_on_job))
|
||||
logger.info("离职数据:%d 条", len(data_leave))
|
||||
logger.info("合计总数据:%d 条", len(total_all))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ==================== 银行卡校验 ====================
|
||||
def check_bank_card(card_raw):
|
||||
card = str(card_raw).strip()
|
||||
if isinstance(card_raw, float):
|
||||
if card_raw != card_raw:
|
||||
card = ""
|
||||
else:
|
||||
card = str(int(card_raw))
|
||||
elif isinstance(card_raw, int):
|
||||
card = str(card_raw)
|
||||
else:
|
||||
card = str(card_raw).strip().replace(" ", "")
|
||||
|
||||
if not card:
|
||||
return {"card": card, "status": "无效", "reason": "空白,无卡号"}
|
||||
if not NUM_REG.match(card):
|
||||
return {"card": card, "status": "无效", "reason": "非纯数字,属于文字备注/脏数据"}
|
||||
|
||||
bin6 = card[:6]
|
||||
if not (card.startswith("62") or bin6 in NON62_BIN):
|
||||
return {"card": card, "status": "无效", "reason": "非62开头,非标准银联储蓄卡"}
|
||||
|
||||
card_len = len(card)
|
||||
if card_len not in (16, 18, 19):
|
||||
return {"card": card, "status": "错误", "reason": f"位数异常{card_len}位,仅支持16/18/19位银行卡"}
|
||||
|
||||
if bin6 in BIN_16:
|
||||
if card_len == 16:
|
||||
return {"card": card, "status": "正常", "reason": "合规16位银联卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准16位,录入位数错误"}
|
||||
if bin6 in BIN_18:
|
||||
if card_len == 18:
|
||||
return {"card": card, "status": "正常", "reason": "合规18位兴业储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准18位,录入位数错误"}
|
||||
if card_len == 19:
|
||||
return {"card": card, "status": "正常", "reason": "合规19位储蓄卡"}
|
||||
else:
|
||||
return {"card": card, "status": "错误", "reason": f"BIN{bin6}标准19位,录入位数错误,需人工核对"}
|
||||
|
||||
|
||||
# ==================== 核对分类 ====================
|
||||
def classify_card_issue(idcard, card_idcard, staff_name, card_name, bank_account):
|
||||
"""按 4 类异常对单条工资卡记录分类。
|
||||
|
||||
返回 (issues, basis, id_inconsistent, bank_info)
|
||||
issues: 4 类异常标签(写入核对结果)
|
||||
basis : 详细校验依据(写入校验依据)
|
||||
1. 开户人信息或银行卡空白
|
||||
2. 员工身份证与开户人身份证不一致
|
||||
3. 员工姓名与开户人姓名不一致(仅身份证一致时比对)
|
||||
4. 银行卡信息异常(银行卡非空但格式/位数错误)
|
||||
"""
|
||||
issues = []
|
||||
basis = []
|
||||
bank_info = None
|
||||
|
||||
# ---- 1. 开户人信息或银行卡空白 ----
|
||||
if _is_empty(card_idcard):
|
||||
issues.append("开户人身份证空白")
|
||||
basis.append("开户人身份证空白")
|
||||
if _is_empty(card_name):
|
||||
issues.append("开户人姓名空白")
|
||||
basis.append("开户人姓名空白")
|
||||
if _is_empty(bank_account):
|
||||
issues.append("银行卡空白")
|
||||
basis.append("银行卡空白")
|
||||
|
||||
# ---- 2. 身份证不一致(开户人身份证非空且与员工不一致) ----
|
||||
id_inconsistent = (not _is_empty(card_idcard)) and idcard != card_idcard
|
||||
if id_inconsistent:
|
||||
issues.append("员工身份证与开户人身份证不一致")
|
||||
basis.append(f"身份证不一致(员工:{idcard} vs 开户人:{card_idcard})")
|
||||
|
||||
# ---- 3. 姓名不一致(仅身份证一致时比对) ----
|
||||
if (not id_inconsistent and not _is_empty(card_idcard)
|
||||
and not _is_empty(card_name) and staff_name != card_name):
|
||||
issues.append("员工姓名与开户人姓名不一致")
|
||||
basis.append(f"姓名不一致(员工:{staff_name} vs 开户人:{card_name})")
|
||||
|
||||
# ---- 4. 银行卡信息异常(银行卡非空但格式/位数错误) ----
|
||||
if not _is_empty(bank_account):
|
||||
bank_info = check_bank_card(bank_account)
|
||||
if bank_info["status"] != "正常":
|
||||
issues.append("银行卡信息异常")
|
||||
basis.append(f"银行卡信息异常({bank_info['reason']})")
|
||||
|
||||
return issues, basis, id_inconsistent, bank_info
|
||||
|
||||
|
||||
# ==================== 核对辅助 ====================
|
||||
def _is_empty(val):
|
||||
if val is None:
|
||||
return True
|
||||
if isinstance(val, float) and val != val:
|
||||
return True
|
||||
s = str(val).strip()
|
||||
return s == "" or s.lower() == "nan"
|
||||
|
||||
|
||||
def _normalize_id(val):
|
||||
if val is None:
|
||||
return ""
|
||||
if isinstance(val, float):
|
||||
if val != val:
|
||||
return ""
|
||||
return str(int(val))
|
||||
if isinstance(val, int):
|
||||
return str(val)
|
||||
return str(val).strip().replace(" ", "")
|
||||
|
||||
|
||||
# ==================== 核对主逻辑 ====================
|
||||
def check_wage_card(input_path, output_path=None):
|
||||
"""读取工资卡汇总表,执行核对并保存结果 + 异常名单。
|
||||
|
||||
输出文件:
|
||||
- {汇总表}_核对结果.xlsx:全量核对结果
|
||||
- 无银行卡表.xlsx:未提供银行卡号(银行卡空白)的人员
|
||||
- 工资卡异常名单.xlsx:除无银行卡外的其他异常人员(含身份证不一致)
|
||||
返回:{"核对结果": 路径, "无银行卡表": 路径或None, "异常名单": 路径或None}
|
||||
"""
|
||||
df = pd.read_excel(input_path)
|
||||
logger.info("读取工资卡汇总表:%s(%d 行)", input_path, len(df))
|
||||
|
||||
# 汇总表未带开卡银行列时,按银行编码(BANK_TYPE)补充(aa.md 银行字典接口)
|
||||
if "开卡银行" not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df["开卡银行"] = df["银行编码"].apply(lambda c: _bank_type_to_name(c, bank_map))
|
||||
|
||||
no_bank_rows = []
|
||||
|
||||
for idx, row in df.iterrows():
|
||||
idcard = _normalize_id(row.get(COL_IDCARD, ""))
|
||||
card_idcard = _normalize_id(row.get(COL_CARD_IDCARD, ""))
|
||||
staff_name = str(row.get(COL_STAFF_NAME, "")).strip()
|
||||
card_name = str(row.get(COL_CARD_NAME, "")).strip()
|
||||
bank_account = row.get(COL_BANK_ACCOUNT, "")
|
||||
|
||||
issues, basis, _, bk = classify_card_issue(
|
||||
idcard, card_idcard, staff_name, card_name, bank_account,
|
||||
)
|
||||
if _is_empty(bank_account):
|
||||
no_bank_rows.append(idx)
|
||||
|
||||
df.at[idx, COL_CHECK_RESULT] = "、".join(issues) if issues else "通过"
|
||||
df.at[idx, COL_CHECK_BASIS] = ";".join(basis) if basis else ""
|
||||
df.at[idx, COL_BANK_STATUS] = bk["status"] if bk else ""
|
||||
df.at[idx, COL_BANK_REASON] = bk["reason"] if bk else ""
|
||||
|
||||
# 统计
|
||||
result_counts = df[df[COL_CHECK_RESULT] != "通过"][COL_CHECK_RESULT].value_counts().to_dict()
|
||||
bank_issues = df[df[COL_BANK_STATUS] != "正常"][COL_BANK_STATUS].value_counts().to_dict()
|
||||
passed = len(df[df[COL_CHECK_RESULT] == "通过"])
|
||||
|
||||
logger.info("核对完成:通过 %d / 总计 %d", passed, len(df))
|
||||
if result_counts:
|
||||
logger.info("核对问题分布:%s", result_counts)
|
||||
if bank_issues:
|
||||
logger.info("银行卡问题:%s", bank_issues)
|
||||
|
||||
# 保存核对结果
|
||||
if output_path is None:
|
||||
base, ext = os.path.splitext(input_path)
|
||||
output_path = f"{base}_核对结果{ext}"
|
||||
|
||||
check_cols = [COL_CHECK_RESULT, COL_CHECK_BASIS, COL_BANK_STATUS, COL_BANK_REASON]
|
||||
other_cols = [c for c in df.columns if c not in check_cols]
|
||||
df = df[check_cols + other_cols]
|
||||
|
||||
# 保存核对结果
|
||||
df.to_excel(output_path, index=False)
|
||||
logger.info("核对结果已保存:%s", output_path)
|
||||
|
||||
no_bank_path = None
|
||||
# 无银行卡人员单独存表(独立文件)
|
||||
if no_bank_rows:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
no_bank_path = os.path.join(os.path.dirname(base), f"无银行卡表{ext}")
|
||||
df.loc[no_bank_rows].to_excel(no_bank_path, index=False)
|
||||
logger.info("无银行卡表已保存:%s(%d 条)", no_bank_path, len(no_bank_rows))
|
||||
else:
|
||||
logger.info("无银行卡空白记录,跳过无银行卡表生成")
|
||||
|
||||
abnormal_path = None
|
||||
# 生成异常名单(含身份证不一致,排除已单独成表的无银行卡记录)
|
||||
mask = (df[COL_CHECK_RESULT] != "通过") & (~df.index.isin(no_bank_rows))
|
||||
abnormal = df[mask]
|
||||
if len(abnormal) > 0:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
abnormal_path = os.path.join(os.path.dirname(base), f"工资卡异常名单{ext}")
|
||||
abnormal.to_excel(abnormal_path, index=False)
|
||||
logger.info("异常名单已保存:%s(%d 条)", abnormal_path, len(abnormal))
|
||||
else:
|
||||
logger.info("无异常记录,跳过异常名单生成")
|
||||
|
||||
return {"核对结果": output_path, "无银行卡表": no_bank_path, "异常名单": abnormal_path}
|
||||
|
||||
|
||||
# ==================== 结果打包与推送(写全局变量 messages,由推送指令发送) ====================
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _package_outputs(paths, save_dir):
|
||||
"""把存在的输出文件打包成 zip(时间戳命名),返回 zip 绝对路径;无文件返回 None。"""
|
||||
exist_files = [p for p in paths if p and os.path.exists(p)]
|
||||
if not exist_files:
|
||||
logger.warning("无有效结果文件,跳过打包")
|
||||
return None
|
||||
_ensure_dir(save_dir)
|
||||
zip_path = os.path.join(
|
||||
save_dir,
|
||||
f"{ZIP_NAME_PREFIX}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.zip",
|
||||
)
|
||||
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for fp in exist_files:
|
||||
zf.write(fp, os.path.basename(fp))
|
||||
logger.info("已打包 %d 个文件到 %s", len(exist_files), zip_path)
|
||||
return zip_path
|
||||
|
||||
|
||||
def _build_push_messages(zip_path):
|
||||
"""构造 dws 单聊推送 file 消息(msg_type=file,上传钉盘发送 zip)。"""
|
||||
return [{
|
||||
"msg_type": "file",
|
||||
"name": PUSH_RECEIVER_NAME,
|
||||
"user_id": PUSH_RECEIVER_ID,
|
||||
"content": "",
|
||||
"file_path": zip_path,
|
||||
}]
|
||||
|
||||
|
||||
def _package_and_notify(results):
|
||||
"""收集结果文件打包 zip,并写入影刀全局变量 messages(dws 单聊发文件)。"""
|
||||
paths = []
|
||||
for key in ("工资卡", "核对结果", "无银行卡表", "异常名单"):
|
||||
p = results.get(key)
|
||||
if isinstance(p, str) and not p.startswith("失败"):
|
||||
paths.append(p)
|
||||
zip_path = _package_outputs(paths, OUTPUT_DIR)
|
||||
if not zip_path:
|
||||
return
|
||||
_set_glv("messages", _build_push_messages(zip_path))
|
||||
logger.info("已写全局变量 messages,交由「37du钉钉单聊推送」指令发送 zip 给 %s(%s)",
|
||||
PUSH_RECEIVER_NAME, PUSH_RECEIVER_ID)
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def download_wage_card(save_dir=None):
|
||||
"""下载在职 + 离职工资卡数据并导出汇总 Excel。"""
|
||||
save_dir = save_dir or OUTPUT_DIR
|
||||
# 只读共享登录态;缺失/失效抛 LoginRequiredError 提示先运行「37duHR登录」指令
|
||||
session = get_hr_session()
|
||||
|
||||
# 预检登录态
|
||||
try:
|
||||
fetch_wage_card_page(session, status=1, page_no=1, page_size=1)
|
||||
except HRSessionExpiredError:
|
||||
raise LoginRequiredError(
|
||||
"预检发现 HR 登录态已过期,请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
|
||||
logger.info("===== 开始抓取在职人员工资卡数据 =====")
|
||||
data_on_job = fetch_all_wage_card(session, status=1, status_name="在职")
|
||||
|
||||
logger.info("===== 开始抓取离职人员工资卡数据 =====")
|
||||
leave_start, leave_end = get_leave_range()
|
||||
data_leave = fetch_all_wage_card(
|
||||
session, status=2, status_name="离职",
|
||||
leave_start=leave_start, leave_end=leave_end,
|
||||
)
|
||||
|
||||
return export_excel(data_on_job, data_leave, save_dir)
|
||||
|
||||
|
||||
def run_bank_card_check():
|
||||
"""银行卡检查主流程:工资卡下载 -> 工资卡核对 -> 打包结果写 messages。"""
|
||||
results = {}
|
||||
|
||||
# ---- 第一步:下载工资卡汇总表 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第一步:下载工资卡汇总表")
|
||||
logger.info("=" * 60)
|
||||
wage_path = None
|
||||
try:
|
||||
wage_path = download_wage_card()
|
||||
results["工资卡"] = wage_path
|
||||
logger.info("工资卡下载完成:%s", wage_path)
|
||||
except Exception as e:
|
||||
logger.error("工资卡下载失败:%s", e)
|
||||
results["工资卡"] = f"失败:{e}"
|
||||
|
||||
# ---- 第二步:核对工资卡数据 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】第二步:核对工资卡数据")
|
||||
logger.info("=" * 60)
|
||||
if wage_path:
|
||||
try:
|
||||
check_result = check_wage_card(wage_path)
|
||||
results["核对结果"] = check_result.get("核对结果")
|
||||
results["无银行卡表"] = check_result.get("无银行卡表")
|
||||
results["异常名单"] = check_result.get("异常名单")
|
||||
logger.info("工资卡核对完成:%s", results["核对结果"])
|
||||
except Exception as e:
|
||||
logger.error("工资卡核对失败:%s", e)
|
||||
results["核对结果"] = f"失败:{e}"
|
||||
else:
|
||||
logger.warning("工资卡汇总表未生成,跳过核对")
|
||||
results["核对结果"] = "跳过(工资卡下载失败)"
|
||||
|
||||
# ---- 汇总 + 打包推送 ----
|
||||
logger.info("=" * 60)
|
||||
logger.info("【银行卡检查】全部完成,结果汇总:")
|
||||
for name, path in results.items():
|
||||
logger.info(" %s:%s", name, path)
|
||||
logger.info("=" * 60)
|
||||
_package_and_notify(results)
|
||||
return results
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def main():
|
||||
load_dotenv()
|
||||
run_bank_card_check()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,705 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: attendance_abnormal.py
|
||||
@Description: 周考勤异常处理(影刀单文件版)- 独立自 app/service/hrbp/ehr/attendance/attendance_abnormal.py,
|
||||
业务逻辑:分页拉取本月(1 号查上月,否则当月)未调整考勤异常 → 导出 Excel → 分级分类
|
||||
(轻微直接自动确认[整月]/其余仅上周钉钉核实)→ 按姓名-工号合并推送当事人(仅上周)
|
||||
→ 生成条数汇总(自动确认数、推送当事人确认数)写入群全局变量。
|
||||
规则见 docs/需求单/XQ0006 EHR系统周考勤异常处理/需求文档.md。
|
||||
@Version: 1.1.0
|
||||
|
||||
登录(共享登录态,本脚本仅读取 cookies 文件,不 import 任何共享模块):
|
||||
「37duHR登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json;
|
||||
缺失/失效时先拖入「37duHR登录」指令再运行本流程。
|
||||
|
||||
钉钉推送(消息生成与发送解耦,本脚本不内联发送):
|
||||
main() 将待推送 messages(元组列表 (msg_type, name, user_id, content, file_path),即
|
||||
("text", 姓名, 工号, 文本内容, ""))写入影刀全局变量
|
||||
glv['messages'];处理条数汇总(自动确认数、推送当事人确认数)写入 glv['group_messages']
|
||||
(文本列表,每项一条),分别由流程拖「37du钉钉单聊推送」(个人,yingdao/share/dingtalk_dws_push.py)/
|
||||
「37du钉钉群机器人推送」(群)指令完成发送。
|
||||
自动确认:仅轻微异常(迟到/早退 < 30 分钟,不分职能序列)自动调用确认接口,确认条数计入群汇总。
|
||||
由 AUTO_CONFIRM_ENABLED 总开关控制(布尔值,默认 True,本次起默认启用;置 False 关闭仅统计不执行)。
|
||||
|
||||
小范围测试按钮(影刀「调用模块」传 main(test_mode=True)):
|
||||
仅筛选所属单位为「集团管理中心」「集团营建中心」「金色印象事业部」、且部门路径不含「大区」
|
||||
的考勤异常作为完整数据源,跑通导出/分级/推送全流程;导出文件名带「测试」、
|
||||
汇总消息标注「小范围测试」,与正式结果区分。筛选条件见 TEST_BELONG_UNITS 常量与 filter_test_units。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests python-dotenv pandas openpyxl
|
||||
|
||||
环境变量(.env 或系统变量,固定路径共享 .env 见 yingdao/share/hr_login.py):
|
||||
dingtalk_push_enabled=true|false(默认 false,是否启用钉钉推送,总开关)
|
||||
dingtalk_notify_target=人资专用号钉钉联系人姓名(处理汇总报表推送对象,如 夏一平)
|
||||
attendance_save_dir=(可选)Excel 导出目录,默认 D:\\资料\\人资\\考勤异常
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
import csv
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests python-dotenv pandas openpyxl\n"
|
||||
"(钉钉推送相关依赖 pyautogui/pywin32/pyperclip/psutil/Pillow/numpy/"
|
||||
"rapidocr onnxruntime 由共享指令 dingtalk_sender.py 校验,见其文档头)\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# ==================== 日志(print) ====================
|
||||
class _PrintLogger:
|
||||
"""影刀版无 logging 依赖,直接用 print 输出,行为与项目 logger 对齐。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
# ==================== 影刀全局变量(glv) ====================
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ==================== 共享路径 & 常量配置(与 app 版统一,见 app/common/app_paths.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_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
# HR 登录态:由「37duHR登录」共享指令写入
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- HR 系统 ----------
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
ATTENDANCE_ABNORMAL_URL = f"{HR_BASE_URL}/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
# 考勤异常确认/调整接口(type=1 自动确认异常)
|
||||
ATTENDANCE_ADJUST_URL = f"{HR_BASE_URL}/RedseaPlatform/abnormalAdjust/KqCountAbnormal.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# 默认保存目录(可用环境变量覆盖)
|
||||
SAVE_DIR = os.getenv("attendance_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 英文字段 → 中文字段映射(aa.md 手动导出的考勤异常列,仅导出这些列)
|
||||
COL_MAP = {
|
||||
"base_code": "工号",
|
||||
"STAFF_NAME": "姓名",
|
||||
"sex": "性别",
|
||||
"age": "年龄",
|
||||
"ORG_FULL_PATH": "部门路径",
|
||||
"BELONG_UNIT_ORG_NAME": "所属单位",
|
||||
"DEPT_ORG_NAME": "部门",
|
||||
"POST_ORG_NAME": "岗位",
|
||||
"join_date": "入职日期",
|
||||
"work_day": "日期",
|
||||
"bc_name": "班次",
|
||||
"abnormal": "异常类型",
|
||||
"is_adjusted": "处理状态",
|
||||
"actual_begin_time": "开始时间",
|
||||
"actual_end_time": "结束时间",
|
||||
"abnormal_minute": "时长(分)",
|
||||
"add_reason": "补签原因",
|
||||
"operateName": "操作人",
|
||||
"operateTime": "操作时间",
|
||||
}
|
||||
|
||||
# 导出列顺序(与 aa.md 手动导出一致;「班段」由 begin_time~end_time 合成)
|
||||
SHOW_ORDER = [
|
||||
"工号", "姓名", "性别", "年龄", "部门路径", "所属单位", "部门", "岗位",
|
||||
"入职日期", "日期", "班次", "班段", "异常类型", "处理状态", "处理方式",
|
||||
"开始时间", "结束时间", "时长(分)", "补签原因", "操作人", "操作时间",
|
||||
]
|
||||
|
||||
# 处理状态 is_adjusted 编码 → 中文(0=未调整、1=补签调整、2=确认异常、3=正常调整)
|
||||
STATUS_MAP = {
|
||||
"0": "未调整",
|
||||
"1": "补签调整",
|
||||
"2": "确认异常",
|
||||
"3": "正常调整",
|
||||
}
|
||||
|
||||
# 考勤异常调整状态过滤(本次只查询「未调整」);0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有
|
||||
IS_ADJUSTED = "0"
|
||||
# 钉钉推送总开关(True=启用,False=关闭)
|
||||
DINGTALK_PUSH_ENABLED = True
|
||||
# 自动确认总开关(默认启用:整月轻微异常直接批量确认;置 False 关闭仅统计不执行)
|
||||
AUTO_CONFIRM_ENABLED = True
|
||||
# 小范围测试:仅筛选以下所属单位(BELONG_UNIT_ORG_NAME)的考勤异常,且部门路径(ORG_FULL_PATH)
|
||||
# 不含「大区」,作为「完整数据源」跑通全流程。
|
||||
# 影刀流程通过 main(test_mode=True) 触发(即「小范围测试」按钮入口),
|
||||
# 测试数据照常导出/分级/推送,但文件名与汇总消息会标注「测试」以区分正式结果。
|
||||
TEST_BELONG_UNITS = ["集团管理中心", "集团营建中心", "金色印象事业部"]
|
||||
# ======================================================
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 yingdao/share/hr_login.py),
|
||||
# 本脚本为单文件自包含:仅读取共享 cookies 文件,不 import 任何共享模块。
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;失效抛 HRSessionExpiredError。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _load_shared_hr_cookies():
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
"""确保存在 HR 登录态文件(由「37duHR登录」指令写入);缺失时提示先运行登录指令。"""
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python yingdao/share/hr_login.py")
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
"""用共享 hr_cookies.json 构建 requests.Session(过滤 hr.37du.co 域)。"""
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def _relogin_get_user_info():
|
||||
"""登录态失效后:补登 → 重建会话 → 重新获取 userId/rootId。"""
|
||||
_ensure_hr_cookies()
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
return session, info.get("userId", ""), info.get("rootId", "")
|
||||
|
||||
|
||||
# ==================== HR 接口 ====================
|
||||
def fetch_cur_user_info(session):
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def fetch_attendance_abnormal_page(session, user_id, treecode, begin_date, end_date,
|
||||
page_no=1, page_size=PAGE_MAX_SIZE,
|
||||
is_adjusted=IS_ADJUSTED, abnormal_type=""):
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"sqlId": "kq_count_abnormal_Select",
|
||||
"redapiId": "rf_p_kq_count_abnormal_Select",
|
||||
"treeCodeList": "",
|
||||
"abnormal_type": abnormal_type,
|
||||
"base_code": "",
|
||||
"join_date": "",
|
||||
"join_date_end": end_date,
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"period_order": "",
|
||||
"identity_test": "",
|
||||
"identity": "",
|
||||
"sex": "",
|
||||
"age": "",
|
||||
"age_end": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"operator_username": "",
|
||||
"operator_userid": "",
|
||||
"is_adjusted": is_adjusted,
|
||||
"begin_date": begin_date,
|
||||
"end_date": end_date,
|
||||
"STAFF_NAME": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "work_day",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", ATTENDANCE_ABNORMAL_URL, params, "考勤异常")
|
||||
|
||||
|
||||
def fetch_all_attendance_abnormal(session, user_id, treecode, begin_date, end_date,
|
||||
is_adjusted=IS_ADJUSTED, abnormal_type=""):
|
||||
"""分页拉取全部考勤异常;中途登录态失效自动补登后续抓。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date,
|
||||
page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤异常 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, treecode = _relogin_get_user_info()
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date,
|
||||
page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type)
|
||||
if data.get("state") != "1":
|
||||
logger.error("考勤异常第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤异常无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("考勤异常已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 考勤异常确认 ====================
|
||||
def adjust_abnormal(session, abnormal_ids, type_code=1):
|
||||
"""确认/调整考勤异常单据(调用 HR 接口,type=1 自动确认异常)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
abnormal_ids: 异常单据唯一编号 abnormal_id,可为单个 id 或 id 列表
|
||||
type_code: 处理类型,1=自动确认异常(按接口约定)
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(state=1 表示处理成功)
|
||||
"""
|
||||
if isinstance(abnormal_ids, (list, tuple)):
|
||||
ids = ",".join(str(i) for i in abnormal_ids)
|
||||
else:
|
||||
ids = str(abnormal_ids)
|
||||
params = {"abnormalIds": ids, "type": type_code}
|
||||
return hr_request_json(session, "POST", ATTENDANCE_ADJUST_URL, params, "考勤异常确认")
|
||||
|
||||
|
||||
def confirm_abnormal(abnormal_ids, type_code=1, session=None):
|
||||
"""确认/调整考勤异常单据(按 abnormal_id 唯一编号),会话为空时自动构建并校验。
|
||||
|
||||
Args:
|
||||
abnormal_ids: 异常单据 id,可为单个 id 或 id 列表
|
||||
type_code: 处理类型,1=自动确认异常(默认)
|
||||
session: 已登录会话;为空时自动构建并校验
|
||||
|
||||
Returns:
|
||||
接口返回的 JSON 字典(state=1 表示处理成功)
|
||||
"""
|
||||
if session is None:
|
||||
session = build_hr_session()
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
session, _, _ = _relogin_get_user_info()
|
||||
return adjust_abnormal(session, abnormal_ids, type_code)
|
||||
|
||||
|
||||
def is_mild_abnormal(item):
|
||||
"""轻微异常:迟到/早退 且 异常时长 < 30 分钟(自动确认范围,不分职能序列)。"""
|
||||
return not classify_abnormal(item)
|
||||
|
||||
|
||||
def auto_confirm_mild(data, session=None):
|
||||
"""自动确认轻微异常(迟到/早退 < 30 分钟,不分职能序列)。
|
||||
|
||||
Args:
|
||||
data: 未调整考勤异常记录列表
|
||||
session: 已登录会话;为空时自动构建
|
||||
|
||||
Returns:
|
||||
确认成功的条数
|
||||
"""
|
||||
mild = [it for it in data if is_mild_abnormal(it) and it.get("abnormal_id")]
|
||||
if not mild:
|
||||
logger.info("无轻微异常(迟到/早退<30分钟),跳过自动确认")
|
||||
return 0
|
||||
ids = [it["abnormal_id"] for it in mild]
|
||||
logger.info("自动确认轻微异常 %d 条(不分职能序列)", len(ids))
|
||||
result = confirm_abnormal(ids, session=session)
|
||||
if result.get("state") == "1":
|
||||
logger.info("自动确认接口返回处理成功,共 %d 条", len(ids))
|
||||
return len(ids)
|
||||
logger.error("自动确认失败:%s", result.get("meg") or result)
|
||||
return 0
|
||||
|
||||
|
||||
def build_group_summary(total_count, mild_count, confirmed_count, non_func_count, func_count,
|
||||
push_count, other_count, month, begin, end, test_mode=False):
|
||||
"""生成考勤异常处理条数汇总消息(与汇总日志格式一致,供钉钉群机器人推送)。"""
|
||||
if test_mode:
|
||||
title = "【考勤异常处理汇总(小范围测试)】"
|
||||
else:
|
||||
title = "【考勤异常处理汇总】"
|
||||
return (
|
||||
f"{title}\n\n"
|
||||
f"查询范围:{begin} ~ {end}({month} 整月,推送仅上周)\n\n"
|
||||
f"考勤异常总数:{total_count} 条\n\n"
|
||||
f"直接处理(轻微,整月自动确认):{mild_count} 条,确认成功 {confirmed_count} 条\n\n"
|
||||
f"待通知(职能,上周):{func_count} 条,合并为 {push_count} 条推送\n\n"
|
||||
f"上周非职能(不推送):{non_func_count} 条\n\n"
|
||||
f"本月其他严重异常(非上周,仅导出留痕):{other_count} 条"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 业务规则(与 app 版一致) ====================
|
||||
def last_week_range(today=None):
|
||||
"""返回上周查询范围:(上周一, 上周日)。
|
||||
|
||||
上周定义:本周一往前推 7 天为上周一,上周一 + 6 天为上周日。
|
||||
"""
|
||||
today = today or date.today()
|
||||
this_monday = today - timedelta(days=today.weekday()) # 本周一
|
||||
last_monday = this_monday - timedelta(days=7)
|
||||
last_sunday = this_monday - timedelta(days=1)
|
||||
return last_monday.strftime("%Y-%m-%d"), last_sunday.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def query_month(today=None):
|
||||
"""本次查询月份:1 号(2 号之前,不含 2 号)查上月,否则查当月。
|
||||
|
||||
当月数据过少(仅 1 天)时补处理上月整月;2 号及以后按当月处理。
|
||||
"""
|
||||
today = today or date.today()
|
||||
if today.day < 2:
|
||||
first_of_this_month = today.replace(day=1)
|
||||
return (first_of_this_month - timedelta(days=1)).strftime("%Y-%m")
|
||||
return today.strftime("%Y-%m")
|
||||
|
||||
|
||||
def in_last_week(item, push_begin, push_end):
|
||||
"""判断异常记录(按 work_day)是否落在上周范围内;work_day 缺失时返回 False。"""
|
||||
work_day = str(item.get("work_day") or "")[:10]
|
||||
return bool(work_day) and push_begin <= work_day <= push_end
|
||||
|
||||
|
||||
def filter_test_units(data, units=None, exclude_path_keyword="大区"):
|
||||
"""小范围测试:仅保留指定所属单位(BELONG_UNIT_ORG_NAME)的考勤异常作为完整数据源,
|
||||
且部门路径(ORG_FULL_PATH)不包含指定关键字(默认排除「大区」)。
|
||||
|
||||
units 为空时返回原数据(不筛选)。
|
||||
"""
|
||||
units = units or TEST_BELONG_UNITS
|
||||
if not units:
|
||||
return data
|
||||
kept = [
|
||||
it for it in data
|
||||
if str(it.get("BELONG_UNIT_ORG_NAME", "") or "").strip() in units
|
||||
and exclude_path_keyword not in str(it.get("ORG_FULL_PATH", "") or "")
|
||||
]
|
||||
logger.warning("小范围测试:所属单位 %s 且部门路径不含「%s」,保留 %d/%d 条",
|
||||
"、".join(units), exclude_path_keyword, len(kept), len(data))
|
||||
return kept
|
||||
|
||||
|
||||
def classify_abnormal(item):
|
||||
"""判断该条异常是否需要钉钉推送。
|
||||
迟到/早退 且 异常时长 < 30 分钟 → 不推送(轻微异常,直接处理);
|
||||
迟到/早退 >= 30 分钟 或 其他类型(旷工/工时不足/漏打卡等)→ 推送。
|
||||
"""
|
||||
abnormal = str(item.get("abnormal", ""))
|
||||
try:
|
||||
minute = int(item.get("abnormal_minute", 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
minute = 0
|
||||
if ("迟到" in abnormal or "早退" in abnormal) and minute < 30:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def is_func_staff(item):
|
||||
"""判断该员工是否属于职能序列(first_type_name 含「职能」才推送)。"""
|
||||
return "职能" in str(item.get("first_type_name", "") or "")
|
||||
|
||||
|
||||
def build_notify_text(items):
|
||||
"""按人员合并拼接钉钉通知文本(一人一条,含该人全部异常)。"""
|
||||
first = items[0]
|
||||
lines = [
|
||||
"【考勤异常提醒】",
|
||||
f"姓名:{first.get('STAFF_NAME', '')}",
|
||||
f"工号:{first.get('base_code', '')}",
|
||||
f"共{len(items)}条考勤异常,请在2日内主动对接人事处理考勤异常确认/请假审批/漏打卡监控查询等,"
|
||||
"超时未对接,将视为考勤异常直接封存",
|
||||
]
|
||||
for idx, item in enumerate(items, 1):
|
||||
abnormal = str(item.get("abnormal", "") or "").strip() or "考勤异常"
|
||||
minute = item.get("abnormal_minute") or "0"
|
||||
lines.append(
|
||||
f"{idx}、考勤日期:{item.get('work_day', '')}|异常类型:{abnormal}|异常时长:{minute}分钟"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ==================== 导出 Excel ====================
|
||||
def _status_cn(value):
|
||||
"""处理状态 is_adjusted 编码转中文;空值/未知编码保持原样。"""
|
||||
if value is None or value == "":
|
||||
return ""
|
||||
return STATUS_MAP.get(str(value), str(value))
|
||||
|
||||
|
||||
def export_excel(data, save_dir, month_str, test_mode=False):
|
||||
if not data:
|
||||
raise ValueError("未查询到任何考勤异常数据,无法导出")
|
||||
|
||||
df = pd.DataFrame(data)
|
||||
|
||||
# 处理方式:轻微异常(自动确认)/ 需核实(钉钉推送)
|
||||
df["处理方式"] = df.apply(
|
||||
lambda r: "自动确认" if not classify_abnormal(r) else "钉钉推送", axis=1
|
||||
)
|
||||
|
||||
# 班段:班次时段 begin_time~end_time(如 "09:00~18:00",无班段留空)
|
||||
df["班段"] = df.apply(
|
||||
lambda r: (
|
||||
f"{str(r.get('begin_time') or '').strip()}~{str(r.get('end_time') or '').strip()}"
|
||||
if (r.get("begin_time") or r.get("end_time")) else ""
|
||||
),
|
||||
axis=1,
|
||||
)
|
||||
|
||||
# 英文字段 → 中文字段
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
|
||||
# 处理状态:is_adjusted 编码转中文
|
||||
if "处理状态" in df.columns:
|
||||
df["处理状态"] = df["处理状态"].apply(_status_cn)
|
||||
|
||||
# 仅保留 aa.md 目标列(顺序一致;缺失列补空)
|
||||
for col in SHOW_ORDER:
|
||||
if col not in df.columns:
|
||||
df[col] = ""
|
||||
df = df[SHOW_ORDER]
|
||||
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
# 测试模式:文件名标注「测试」,与正式结果区分,避免误用
|
||||
prefix = "周考勤异常_测试" if test_mode else "周考勤异常"
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"{prefix}_{month_str}_{ts}.xlsx"))
|
||||
try:
|
||||
df.to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
|
||||
)
|
||||
logger.info("考勤异常数据:%d 条", len(data))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ==================== 钉钉推送(总开关控制) ====================
|
||||
def push_abnormal(items):
|
||||
"""按「工号-姓名」分组,合并为 messages 元组列表,写入影刀全局变量 messages,
|
||||
由流程拖「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 = {}
|
||||
for it in items:
|
||||
name = it.get("STAFF_NAME", "") or ""
|
||||
if not name:
|
||||
logger.warning("异常记录缺少姓名,跳过:%s", it)
|
||||
continue
|
||||
key = (it.get("base_code", "") or "", name)
|
||||
groups.setdefault(key, []).append(it)
|
||||
|
||||
messages = []
|
||||
for (code, name), group in groups.items():
|
||||
# 消息类型固定 "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
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def handle_attendance_abnormal(save_dir=None, month=None, test_mode=False):
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
|
||||
# 1. 会话:复用共享登录态,必要时补登
|
||||
session = build_hr_session()
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("cookies 已失效,自动补登")
|
||||
session, user_id, treecode = _relogin_get_user_info()
|
||||
info = {"userId": user_id, "rootId": treecode}
|
||||
user_id = info.get("userId", "")
|
||||
treecode = info.get("rootId", "")
|
||||
if not user_id or not treecode:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId/rootId:{info}")
|
||||
logger.info("cookies 校验通过,user_id=%s,treecode=%s", user_id, treecode)
|
||||
|
||||
# 2. 查询范围:整月(1 号查上月,否则当月);推送仍按上周(周一~周日)
|
||||
month = month or query_month()
|
||||
begin = f"{month}-01"
|
||||
end = f"{month}-31"
|
||||
logger.info("===== 查询考勤异常日期范围:%s ~ %s(%s 整月),调整状态:%s =====",
|
||||
begin, end, month, IS_ADJUSTED or "所有")
|
||||
|
||||
# 3. 拉取数据
|
||||
data = fetch_all_attendance_abnormal(session, user_id, treecode, begin, end, IS_ADJUSTED)
|
||||
# 小范围测试:仅保留指定所属单位数据,作为完整数据源跑通全流程
|
||||
if test_mode:
|
||||
data = filter_test_units(data)
|
||||
if not data:
|
||||
logger.info("本月(%s)无考勤异常数据,跳过导出与推送", month)
|
||||
return None
|
||||
|
||||
# 4. 导出 Excel 底稿
|
||||
month_str = month or end[:7] # 文件名月份标识取上周日所在月
|
||||
path = export_excel(data, save_dir, month_str, test_mode=test_mode)
|
||||
|
||||
# 5. 分级分类:轻微异常整月自动确认;需推送的仅上周(周一~周日)严重异常
|
||||
mild_list = [it for it in data if not classify_abnormal(it)]
|
||||
push_begin, push_end = last_week_range()
|
||||
push_list = [it for it in data if classify_abnormal(it) and in_last_week(it, push_begin, push_end)]
|
||||
other_list = [it for it in data if classify_abnormal(it) and not in_last_week(it, push_begin, push_end)]
|
||||
func_list = [it for it in push_list if is_func_staff(it)]
|
||||
non_func_list = [it for it in push_list if not is_func_staff(it)]
|
||||
|
||||
# 6. 自动确认轻微异常(整月,迟到/早退<30分钟,不分职能序列)——总开关 AUTO_CONFIRM_ENABLED 控制
|
||||
# 统计不受开关影响:始终按数据计算实际条数,便于查看真实情况(开关只决定是否真正调用确认接口)
|
||||
mild_count = len([it for it in mild_list if it.get("abnormal_id")])
|
||||
if AUTO_CONFIRM_ENABLED:
|
||||
confirmed_count = auto_confirm_mild(mild_list, session=session)
|
||||
else:
|
||||
confirmed_count = 0
|
||||
logger.warning("自动确认未启用(AUTO_CONFIRM_ENABLED=%s),仅统计待自动确认 %d 条,未执行确认",
|
||||
AUTO_CONFIRM_ENABLED, mild_count)
|
||||
|
||||
# 7. 钉钉推送(总开关控制)
|
||||
push_count, fail_count = 0, 0
|
||||
if DINGTALK_PUSH_ENABLED:
|
||||
if func_list:
|
||||
push_count, fail_count = push_abnormal(func_list)
|
||||
else:
|
||||
logger.info("无需推送的异常,跳过当事人钉钉通知")
|
||||
logger.info("当事人推送完成:成功 %d 条,失败 %d 条", push_count, fail_count)
|
||||
else:
|
||||
logger.info("钉钉推送未启用(dingtalk_push_enabled!=true),未发送任何钉钉消息")
|
||||
|
||||
# 8. 汇总日志 + 钉钉群条数汇总(与日志格式一致)
|
||||
logger.info("=" * 60)
|
||||
if test_mode:
|
||||
logger.info("【考勤异常处理汇总(小范围测试)】")
|
||||
else:
|
||||
logger.info("【考勤异常处理汇总】")
|
||||
logger.info(" 考勤异常总数:%d 条", len(data))
|
||||
logger.info(" 直接处理(轻微,整月自动确认):%d 条,确认成功 %d 条", mild_count, confirmed_count)
|
||||
logger.info(" 待通知(职能,上周):%d 条,合并为 %d 条推送", len(func_list), push_count)
|
||||
logger.info(" 上周非职能(不推送):%d 条", len(non_func_list))
|
||||
logger.info(" 本月其他严重异常(非上周,仅导出留痕):%d 条", len(other_list))
|
||||
logger.info(" 导出文件:%s", path)
|
||||
logger.info("=" * 60)
|
||||
group_message = build_group_summary(
|
||||
len(data), mild_count, confirmed_count, len(non_func_list), len(func_list), push_count,
|
||||
len(other_list), month, begin, end, test_mode=test_mode)
|
||||
_set_glv('group_messages', [group_message])
|
||||
logger.info("处理条数汇总已写入全局变量 group_messages:%s", group_message)
|
||||
return path
|
||||
|
||||
|
||||
def main(save_dir=None, month=None, test_mode=False):
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行,仅支持关键字参数。
|
||||
|
||||
参数说明:
|
||||
save_dir: 导出目录,默认 SAVE_DIR
|
||||
month: 查询月份 "YYYY-MM";默认本月(1 号查上月,否则当月);指定则查该月
|
||||
test_mode: True=小范围测试:仅筛选 TEST_BELONG_UNITS 所属单位数据跑通全流程,默认 False
|
||||
|
||||
例:
|
||||
main() # 正式全量
|
||||
main(test_mode=True) # 小范围测试(按 TEST_BELONG_UNITS 筛选且排除大区)
|
||||
main(test_mode=True, month="2026-08")
|
||||
"""
|
||||
# 始终定义影刀全局变量 messages / group_messages(默认空),避免后续流程步骤引用时 NameError
|
||||
_set_glv('messages', [])
|
||||
_set_glv('group_messages', [])
|
||||
if not save_dir:
|
||||
save_dir = sys.argv[1] if len(sys.argv) > 1 else None
|
||||
if not month:
|
||||
month = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
if not test_mode and len(sys.argv) > 3:
|
||||
test_mode = str(sys.argv[3]).strip().lower() in ("1", "true", "yes", "on")
|
||||
try:
|
||||
out = handle_attendance_abnormal(save_dir, month, test_mode)
|
||||
if out:
|
||||
logger.info("===== 考勤异常处理完成,导出:%s =====", out)
|
||||
else:
|
||||
logger.info("===== 考勤异常处理完成:本月无数据 =====")
|
||||
return {"success": True, "save_path": out}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。")
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("考勤异常处理失败:%s", e)
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(test_mode=True)
|
||||
@@ -0,0 +1,791 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: social_change.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-07
|
||||
@Description: 社保增减名单核对(统一单文件版,app 与影刀共用)——复用共享 OA 登录态导出参保/停保名单
|
||||
-> 清洗去重 -> 复用共享 HR 登录态核对参保记录 -> 追加结果列
|
||||
-> 写全局变量 messages(文本汇总+表文件,单文件直接推/多文件打包 zip,
|
||||
由「37du钉钉单聊推送」指令发送)。
|
||||
业务判定及规则见 docs/社保增减名单/需求文档.md。
|
||||
@Version: 2.3.0
|
||||
|
||||
设计说明(避免维护 app/影刀两套版本):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- OA 登录态复用共享 oa_cookies.json(由「37duOA登录」指令写入),HR 登录态复用共享
|
||||
hr_cookies.json(由「37duHR登录」指令写入);均只读,缺失/失效时友好提示先运行
|
||||
对应登录指令,不自动补登。
|
||||
- 结果推送写全局变量 messages(text 汇总 + file 附件),发送由「37du钉钉单聊推送」指令完成。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage python-dotenv requests xlrd openpyxl
|
||||
|
||||
环境变量(.env 文件或系统变量):
|
||||
可选:social_change_query_date=查询起始日期(如 2026-08-01,默认当月1号)
|
||||
social_change_output_dir=结果输出目录(默认 D:\资料\人资\员工社保增减名单)
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import functools
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
from urllib.parse import urljoin, urlparse, parse_qs
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, SessionPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import xlrd
|
||||
from openpyxl import load_workbook as _load_workbook
|
||||
from openpyxl import Workbook as _XlsxWorkbook
|
||||
from openpyxl.styles import PatternFill, Font, Alignment
|
||||
from openpyxl.utils import get_column_letter
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install DrissionPage python-dotenv requests xlrd openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 共享登录态 cookies 统一由对应登录指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\
|
||||
_SHARED_SESSIONS_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation', '.sessions'
|
||||
)
|
||||
# OA 登录态 cookies:由「37duOA登录」指令写入(只读,缺失/失效提示先运行登录指令,不自动补登)
|
||||
COOKIE_FILE_OA = os.path.join(_SHARED_SESSIONS_DIR, 'oa_cookies.json')
|
||||
# HR 登录态 cookies:由「37duHR登录」指令写入(只读,缺失/失效提示先运行登录指令,不自动补登)
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SHARED_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- OA 系统 ----------
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
HOME_URL = f"{BASE_URL}/sys/portal/page.jsp?portalId=1754a0f1c8b63479fb544514619903d5"
|
||||
LIST_URL = f"{BASE_URL}/km/review/km_review_main_list.jsp"
|
||||
SEARCH_URL = f"{BASE_URL}/sys/search/search.do"
|
||||
MENU_API_PATH = "/sys/portal/sys_portal_nav/sysPortalNav.do"
|
||||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||||
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
DEFAULT_FIXED_PARAMS = {
|
||||
"fdModelName": "com.landray.kmss.km.review.model.KmReviewMain",
|
||||
"canClose": "false", "isNew": "true",
|
||||
"j_aside": "false", "j_rIframe": "true", "j_iframe": "true",
|
||||
}
|
||||
DEFAULT_EXPORT_COLUMNS = (
|
||||
"fd_38e9dd25e050e0;docCreator;fd_38d49cbc0ceeae;"
|
||||
"fd_390c6988e241ea;fd_390c639f265c78;fd_38e77e5cd6e9fe;"
|
||||
"fd_38d49cd67211e2;fd_38d49cd73eff02;fd_38deea220dc8c4;docStatus"
|
||||
)
|
||||
DEFAULT_EXPORT_COLUMNS_SUSPEND = (
|
||||
"fd_38d32213b2e9cc;fd_38d322164f42f2;fd_38e6887c2b3690;"
|
||||
"fd_3ec504d4c63e02;fd_38dad8035e33e4;fd_38e6887d6b0088;"
|
||||
"fd_38d32227f7a496;fd_38dee9ae569d6a;fd_38e687e91f4fc6;"
|
||||
"fd_38e687eb56dc4c;docStatus;docPublishTime"
|
||||
)
|
||||
MENU_NAME_PARTICIPATE = "员工参保申请"
|
||||
MENU_NAME_SUSPEND = "员工停保申请"
|
||||
FILTER_IDX_PARTICIPATE = "2"
|
||||
FILTER_IDX_SUSPEND = "3"
|
||||
|
||||
# ---------- HR 参保记录核对(si_main 接口) ----------
|
||||
SI_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/getPageAjax/si_main_SelectByTreeCode/CoreRequest.mc"
|
||||
SI_BASE_PARAMS = {
|
||||
"start": "0", "pageNo": "1", "pageSize": "15",
|
||||
"USER_ID": "07b83185-6243-42bc-b79f-b81b4cffb471",
|
||||
"STRU_ID": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"STRU_TREE_CODE": "cq37du",
|
||||
"queryTempPersonType": "queryForList",
|
||||
"belongUnitStruId": "f1a6c12a-cef4-11ee-b449-000c296f9469",
|
||||
"fastMode": "0", "rootId": "cq37du", "_noTrans_": "noTrans",
|
||||
"defineColumnType": "5", "PERSON_STATUS": "", "SI_STATE": "98",
|
||||
"staff_names": "", "base_codes": "", "includeSubUnit": "1",
|
||||
"postStruId": "1", "regist_property": "", "identity": "",
|
||||
"idcards": "", "if_sb": "", "payOrgId": "", "payUnitId": "",
|
||||
"siName": "", "belongUnitId": "", "belongUnitName": "",
|
||||
"DEPT_NAME": "", "inputDeptName": "", "selectType": "1",
|
||||
"operator": "",
|
||||
"joinDate_begin": "", "joinDate_end": "",
|
||||
"leaveDate_begin": "", "leaveDate_end": "",
|
||||
"siBeginDate_begin": "", "siBeginDate_end": "",
|
||||
"siEndDate_begin": "", "siEndDate_end": "",
|
||||
}
|
||||
SI_RESULT_COL = "社保记录查询结果"
|
||||
SI_BATCH_SIZE = 15
|
||||
|
||||
# ---------- 打包推送(结果写全局变量 messages,由「37du钉钉单聊推送」指令发送) ----------
|
||||
PUSH_RECEIVER_NAME = "周卫"
|
||||
PUSH_RECEIVER_ID = "37001166"
|
||||
|
||||
|
||||
# ==================== 日志(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()
|
||||
|
||||
|
||||
# ==================== 重试装饰器 ====================
|
||||
class RetryExhaustedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
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 RetryExhaustedError(
|
||||
f"{func.__name__} failed after {max_attempts} attempts, last error: {last_exc}"
|
||||
) from last_exc
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
|
||||
# ==================== Cookies 读取(共享登录态,只读) ====================
|
||||
def _ensure_dir(path):
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
# ==================== OA 会话(复用共享登录态) ====================
|
||||
def is_oa_session_valid(session):
|
||||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需启动浏览器)。"""
|
||||
try:
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
# 会话有效时返回待办数统计 JSON(如 {"type_2":"39","type_1":"8"});失效会被重定向到登录页返回 HTML
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
logger.info("OA 会话已失效: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def get_oa_session():
|
||||
"""从共享 oa_cookies.json 构建 OA 会话(SessionPage + ChromiumPage)。
|
||||
缺失/失效抛 LoginRequiredError,提示先运行「37duOA登录」指令。"""
|
||||
cookies = load_cookies(COOKIE_FILE_OA)
|
||||
if not cookies:
|
||||
raise LoginRequiredError("未找到 OA 登录态 cookies,请先调用「37duOA登录」指令完成登录后再重试。")
|
||||
session = SessionPage()
|
||||
session.set.cookies(cookies)
|
||||
session.set.timeout(10)
|
||||
if hasattr(session, 'session'):
|
||||
session.session.headers.update({
|
||||
"Referer": LIST_URL,
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
"Accept": "application/json, text/javascript, */*; q=0.01",
|
||||
})
|
||||
if not is_oa_session_valid(session):
|
||||
raise LoginRequiredError("OA 登录态已失效,请先重新调用「37duOA登录」指令完成登录后再重试。")
|
||||
browser = ChromiumPage()
|
||||
browser.set.cookies(cookies)
|
||||
return browser, session
|
||||
|
||||
|
||||
# ==================== HR 登录态(共享 cookies,只读不补登) ====================
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态 cookies 缺失或失效,需先调用「37duHR登录」指令。"""
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def get_hr_session():
|
||||
"""构建 HR requests.Session(只读共享 cookies,缺失/失效抛 LoginRequiredError)。"""
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
has_hr = any(c.get("domain") and c["domain"].endswith("hr.37du.co") for c in cookies)
|
||||
if not has_hr:
|
||||
raise LoginRequiredError(
|
||||
"共享 cookies 中无 hr.37du.co 登录态,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
logger.info("复用共享 HR 登录态(hr.37du.co,%d 个 cookies)", len(cookies))
|
||||
return _build_hr_session(cookies)
|
||||
|
||||
|
||||
def _build_hr_session(cookies=None):
|
||||
cookies = cookies or _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and c["domain"].endswith("hr.37du.co"):
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 导出(fdId / searchId / 总数 / 导出) ====================
|
||||
def _check_response(resp, action):
|
||||
if resp is None:
|
||||
raise RuntimeError(f"{action}失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"{action}失败,状态码: {resp.status_code}")
|
||||
|
||||
|
||||
def _resolve_query_date(query_date=None):
|
||||
return query_date or datetime.now().strftime("%Y-%m-01")
|
||||
|
||||
|
||||
def _build_filter_params(filter_idx, query_date=None):
|
||||
day = _resolve_query_date(query_date)
|
||||
# ge=不早于(包含起始日当天):申请日期 >= 当月1号
|
||||
return {f"v0_{filter_idx}": "ge", f"v1_{filter_idx}": day}
|
||||
|
||||
|
||||
def _get_cookies_with_domain(session):
|
||||
cookies = []
|
||||
try:
|
||||
raw = session.session.cookies
|
||||
for c in raw:
|
||||
cookies.append({"name": c.name, "value": c.value, "domain": c.domain, "path": c.path or "/"})
|
||||
except Exception:
|
||||
cookies = load_cookies(COOKIE_FILE_OA) or []
|
||||
return cookies
|
||||
|
||||
|
||||
def get_fd_id_by_listening(session, browser=None):
|
||||
own_browser = browser is None
|
||||
if own_browser:
|
||||
cookies = _get_cookies_with_domain(session)
|
||||
if not cookies:
|
||||
raise RuntimeError("Session 中没有 cookie,请先执行完整登录")
|
||||
browser = ChromiumPage(ChromiumOptions())
|
||||
browser.set.cookies(cookies)
|
||||
try:
|
||||
browser.listen.start()
|
||||
logger.info("正在访问 OA 首页:%s", HOME_URL)
|
||||
browser.get(HOME_URL)
|
||||
time.sleep(5)
|
||||
# 兜底:若浏览器 cookies 失效会停在登录页,快速失败避免空等,且异常含『登录』可触发主流程自动重登
|
||||
if "login.jsp" in browser.url or browser.ele('tag:input@name=j_username', timeout=2):
|
||||
raise RuntimeError("登录态已失效,页面停留在登录页,请重新登录")
|
||||
deadline = time.time() + 10
|
||||
target = None
|
||||
while time.time() < deadline:
|
||||
req = browser.listen.wait(timeout=1)
|
||||
if req and 'sysPortalNav.do' in req.url:
|
||||
target = req
|
||||
break
|
||||
if target is None:
|
||||
raise RuntimeError("超时未监听到菜单请求,请检查网络或登录态")
|
||||
qs = parse_qs(urlparse(target.url).query)
|
||||
fd_id = qs.get('fdId', [None])[0]
|
||||
if not fd_id:
|
||||
raise RuntimeError("菜单请求中未包含 fdId")
|
||||
logger.info("动态获取到 fdId: %s", fd_id)
|
||||
return fd_id
|
||||
finally:
|
||||
browser.listen.stop()
|
||||
if own_browser:
|
||||
browser.quit()
|
||||
|
||||
|
||||
def get_search_id_from_menu(session, fd_id, menu_name=MENU_NAME_PARTICIPATE):
|
||||
params = {"method": "portlet", "fdId": fd_id, "f_s": "sourcejs", "t": str(int(time.time() * 1000))}
|
||||
session.get(f"{BASE_URL}{MENU_API_PATH}", params=params)
|
||||
_check_response(session.response, "获取菜单")
|
||||
data = session.response.json()
|
||||
|
||||
def find_item(items):
|
||||
for item in items:
|
||||
if item.get("text") == menu_name:
|
||||
return item
|
||||
if "children" in item:
|
||||
found = find_item(item["children"])
|
||||
if found:
|
||||
return found
|
||||
return None
|
||||
|
||||
items = data if isinstance(data, list) else data.get("children", [])
|
||||
item = find_item(items)
|
||||
if not item:
|
||||
raise RuntimeError(f"菜单中未找到 '{menu_name}'")
|
||||
qs = parse_qs(urlparse(urljoin(BASE_URL, item["href"])).query)
|
||||
search_id = qs.get("searchId", [None])[0]
|
||||
if not search_id:
|
||||
raise RuntimeError("菜单链接中未包含 searchId")
|
||||
logger.info("从菜单获取到 searchId: %s", search_id)
|
||||
return search_id
|
||||
|
||||
|
||||
def get_total_count(session, base_params, search_id, timestamp):
|
||||
params = {"method": "result", "searchId": search_id, "j_timestamp": timestamp, **base_params}
|
||||
session.get(SEARCH_URL, params=params, headers={"Referer": LIST_URL})
|
||||
_check_response(session.response, "查询总数")
|
||||
html = session.response.text
|
||||
for pat in (r'exportNum:\s*"(\d+)"', r'总记录数[::]\s*(\d+)', r'共\s*(\d+)\s*条'):
|
||||
m = re.search(pat, html)
|
||||
if m:
|
||||
total = int(m.group(1))
|
||||
logger.info("获取到总记录数: %d", total)
|
||||
return total
|
||||
logger.warning("未找到总条数,默认为 0")
|
||||
return 0
|
||||
|
||||
|
||||
def export_all_data(session, base_params, total, columns, search_id, timestamp):
|
||||
data = {
|
||||
"method": "exportResult", "searchId": search_id, "j_timestamp": timestamp, **base_params,
|
||||
"fdColumns": columns, "fdNum": str(total), "fdNumStart": "1", "fdNumEnd": str(total),
|
||||
"fdKeepRtfStyle": "true", "checkIdValues": "",
|
||||
}
|
||||
session.post(SEARCH_URL, data=data, headers={"Referer": LIST_URL})
|
||||
_check_response(session.response, "导出数据")
|
||||
return session.response.content
|
||||
|
||||
|
||||
# ==================== 读取 + 清洗去重 ====================
|
||||
def _normalize_date_key(value):
|
||||
if value is None:
|
||||
return 0.0
|
||||
if isinstance(value, (int, float)):
|
||||
return float(value)
|
||||
if isinstance(value, str):
|
||||
m = re.match(r"(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})", value.strip())
|
||||
if m:
|
||||
try:
|
||||
y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
||||
return (datetime(y, mo, d) - datetime(1899, 12, 30)).days
|
||||
except ValueError:
|
||||
return 0.0
|
||||
return 0.0
|
||||
|
||||
|
||||
def _date_display(value, wb):
|
||||
if isinstance(value, (int, float)):
|
||||
try:
|
||||
dt = xlrd.xldate_as_datetime(float(value), wb.datemode)
|
||||
except Exception:
|
||||
return value
|
||||
if float(value).is_integer():
|
||||
return dt.strftime("%Y-%m-%d")
|
||||
return dt.strftime("%Y-%m-%d %H:%M:%S")
|
||||
return value
|
||||
|
||||
|
||||
def _read_and_clean(xls_path):
|
||||
wb = xlrd.open_workbook(xls_path)
|
||||
sh = wb.sheet_by_index(0)
|
||||
headers = [str(sh.cell_value(0, c)).strip() for c in range(sh.ncols)]
|
||||
|
||||
def find_col(keyword):
|
||||
for i, h in enumerate(headers):
|
||||
if keyword in h:
|
||||
return i
|
||||
return None
|
||||
|
||||
emp_col = find_col("工号")
|
||||
date_col = find_col("申请日期")
|
||||
status_col = find_col("文档状态")
|
||||
if emp_col is None:
|
||||
raise ValueError(f"未找到『工号』列,表头: {headers}")
|
||||
|
||||
rows = []
|
||||
for r in range(1, sh.nrows):
|
||||
row = []
|
||||
for c in range(sh.ncols):
|
||||
v = sh.cell_value(r, c)
|
||||
if sh.cell_type(r, c) == xlrd.XL_CELL_DATE:
|
||||
v = _date_display(v, wb)
|
||||
row.append(v)
|
||||
emp = str(row[emp_col]).strip()
|
||||
if not emp:
|
||||
continue
|
||||
if status_col is not None and str(row[status_col]).strip() == "废弃":
|
||||
continue
|
||||
row[emp_col] = emp
|
||||
rows.append(row)
|
||||
|
||||
latest = {}
|
||||
for row in rows:
|
||||
emp = row[emp_col]
|
||||
key = _normalize_date_key(row[date_col]) if date_col is not None else 0.0
|
||||
if emp not in latest or key > latest[emp][0]:
|
||||
latest[emp] = (key, row)
|
||||
|
||||
ordered, seen = [], set()
|
||||
for row in rows:
|
||||
emp = row[emp_col]
|
||||
if emp not in seen:
|
||||
seen.add(emp)
|
||||
ordered.append(latest[emp][1])
|
||||
|
||||
logger.info("清洗完成:去掉废弃后 %d 条,去重后 %d 条", len(rows), len(ordered))
|
||||
return headers, ordered, emp_col
|
||||
|
||||
|
||||
# ==================== HR 参保记录核对 ====================
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态过期:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
def _si_is_expired(text):
|
||||
"""接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def _si_query_batch(session, codes_batch):
|
||||
params = SI_BASE_PARAMS.copy()
|
||||
params["base_codes"] = ",".join(codes_batch)
|
||||
resp = session.post(SI_QUERY_URL, data=params, timeout=15)
|
||||
resp.raise_for_status()
|
||||
if _si_is_expired(resp.text):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _si_found_codes(response_json):
|
||||
datas = response_json.get("datas") or []
|
||||
return {str(item.get("base_Code")).strip() for item in datas if item.get("base_Code")}
|
||||
|
||||
|
||||
def _si_check_batch(session, codes_batch):
|
||||
"""返回这一批中『能查到参保记录』的工号集合;查询失败上抛,由调用方决定重登或标注异常。"""
|
||||
return _si_found_codes(_si_query_batch(session, codes_batch))
|
||||
|
||||
|
||||
def _si_preflight(session):
|
||||
"""正式核对前先探测一次接口,确认 HR 登录态有效;过期/异常抛 LoginRequiredError 提示先运行登录指令。"""
|
||||
try:
|
||||
_si_query_batch(session, ["0"])
|
||||
except HRSessionExpiredError as e:
|
||||
raise LoginRequiredError(
|
||||
f"预检发现 HR 登录态已过期,请先重新调用「37duHR登录」指令完成登录后再重试: {e}")
|
||||
except Exception as e:
|
||||
# 网络超时也可能由 cookies 过期(重定向到登录页后加载超时)引发,同样按登录态失效处理
|
||||
raise LoginRequiredError(
|
||||
f"预检查询异常(可能 HR 登录态已过期),请先重新调用「37duHR登录」指令完成登录后再重试: {e}")
|
||||
return session
|
||||
|
||||
|
||||
def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir=".", session=None):
|
||||
"""逐批查 HR 参保记录,追加『社保记录查询结果』列,写出最终 .xlsx。
|
||||
|
||||
session 由调用方预检后传入(复用,避免重复探测);为 None 时内部自行预检。
|
||||
"""
|
||||
unique_codes, seen = [], set()
|
||||
for row in rows:
|
||||
code = str(row[emp_col]).strip()
|
||||
if code and code not in seen:
|
||||
seen.add(code)
|
||||
unique_codes.append(code)
|
||||
|
||||
if session is None:
|
||||
session = _si_preflight(get_hr_session())
|
||||
found = set()
|
||||
failed_codes = set()
|
||||
for i in range(0, len(unique_codes), SI_BATCH_SIZE):
|
||||
batch = unique_codes[i:i + SI_BATCH_SIZE]
|
||||
try:
|
||||
found |= _si_check_batch(session, batch)
|
||||
except HRSessionExpiredError:
|
||||
# 登录态失效时不自动补登,上抛提示先重新运行「37duHR登录」指令(避免大批误标异常)
|
||||
raise LoginRequiredError(
|
||||
f"HR 登录态已过期(第 {min(i + SI_BATCH_SIZE, len(unique_codes))}/{len(unique_codes)} 批),"
|
||||
f"请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
except Exception as e:
|
||||
# 网络超时/其它异常:宁可标注查询异常,也不当作『无记录』避免误判
|
||||
logger.warning("参保记录查询失败(该批标注查询异常,需人工复核): %s", e)
|
||||
failed_codes |= set(batch)
|
||||
logger.info("参保记录核对 %d/%d 个工号", min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes))
|
||||
time.sleep(0.3)
|
||||
|
||||
is_participate = (mode == "participation")
|
||||
new_rows = []
|
||||
for row in rows:
|
||||
code = str(row[emp_col]).strip()
|
||||
if code in failed_codes:
|
||||
val = "异常:参保记录查询失败,需人工复核"
|
||||
else:
|
||||
has_record = code in found
|
||||
if is_participate:
|
||||
val = "异常:已参保(系统有该工号记录)" if has_record else "正常:系统无该工号记录"
|
||||
else:
|
||||
val = "异常:已停保(系统无该工号记录)" if not has_record else "正常:系统有该工号记录"
|
||||
new_rows.append(row + [val])
|
||||
|
||||
out_path = os.path.abspath(os.path.join(output_dir, f"{base_name}_参保核对.xlsx"))
|
||||
out_wb = _XlsxWorkbook()
|
||||
|
||||
# 样式:异常行标红 + 结果列加粗红字(仅当样式可用)
|
||||
red_fill = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid") if PatternFill else None
|
||||
red_font = Font(color="9C0006", bold=True) if Font else None
|
||||
head_fill = PatternFill(start_color="DDEBF7", end_color="DDEBF7", fill_type="solid") if PatternFill else None
|
||||
|
||||
ws = out_wb.active
|
||||
ws.title = "核对明细"
|
||||
ws.append(headers + [SI_RESULT_COL])
|
||||
for c in range(1, len(headers) + 2):
|
||||
cell = ws.cell(1, c)
|
||||
cell.fill = head_fill
|
||||
cell.font = Font(bold=True) if Font else None
|
||||
cell.alignment = Alignment(horizontal="center") if Alignment else None
|
||||
for idx, row in enumerate(new_rows, start=2):
|
||||
ws.append(row)
|
||||
if str(row[-1]).startswith("异常"):
|
||||
for c in range(1, len(row) + 1):
|
||||
cell = ws.cell(idx, c)
|
||||
cell.fill = red_fill
|
||||
if c == len(row):
|
||||
cell.font = red_font
|
||||
ws.freeze_panes = "A2"
|
||||
ws.auto_filter.ref = ws.dimensions
|
||||
if get_column_letter:
|
||||
for c in range(1, len(headers) + 2):
|
||||
ws.column_dimensions[get_column_letter(c)].width = 20
|
||||
|
||||
out_wb.save(out_path)
|
||||
|
||||
abnormal = [r for r in new_rows if r[-1].startswith("异常")]
|
||||
logger.info("参保核对完成:共 %d 个工号,查询到参保记录 %d 个,异常 %d 条,导出 %s",
|
||||
len(unique_codes), len(found), len(abnormal), out_path)
|
||||
return out_path
|
||||
|
||||
|
||||
# ==================== 导出 + 核对一条龙 ====================
|
||||
def export_employee_change_list(menu_name, filter_idx, columns, output_dir, query_date=None):
|
||||
logger.info("社保增减名单核对流程开始,菜单:%s", menu_name)
|
||||
base_params = {**DEFAULT_FIXED_PARAMS, **_build_filter_params(filter_idx, query_date)}
|
||||
|
||||
# 预检 HR 登录态:缺失/失效抛 LoginRequiredError 提示先运行「37duHR登录」指令
|
||||
hr_session = _si_preflight(get_hr_session())
|
||||
|
||||
# 获取 OA 会话:缺失/失效抛 LoginRequiredError 提示先运行「37duOA登录」指令
|
||||
browser, session = get_oa_session()
|
||||
try:
|
||||
fd_id = get_fd_id_by_listening(session, browser)
|
||||
search_id = get_search_id_from_menu(session, fd_id, menu_name)
|
||||
timestamp = str(int(time.time() * 1000))
|
||||
total = get_total_count(session, base_params, search_id, timestamp)
|
||||
if total == 0:
|
||||
logger.warning("查询结果为 0 条,请检查筛选条件或无数据")
|
||||
return ""
|
||||
|
||||
logger.info("开始导出 %d 条记录...", total)
|
||||
content = export_all_data(session, base_params, total, columns, search_id, timestamp)
|
||||
output_path = os.path.abspath(os.path.join(
|
||||
output_dir, f"{time.strftime('%Y%m')}_{menu_name}表_{time.strftime('%H%M%S')}.xls"))
|
||||
with open(output_path, "wb") as f:
|
||||
f.write(content)
|
||||
logger.info("导出完成,文件保存为:%s", output_path)
|
||||
|
||||
headers, rows, emp_col = _read_and_clean(output_path)
|
||||
mode = "suspension" if menu_name == MENU_NAME_SUSPEND else "participation"
|
||||
final_path = _write_annotated(
|
||||
headers, rows, emp_col, mode,
|
||||
os.path.splitext(os.path.basename(output_path))[0], output_dir,
|
||||
session=hr_session)
|
||||
try:
|
||||
os.remove(output_path)
|
||||
logger.info("已清理中间原始导出文件:%s", output_path)
|
||||
except Exception:
|
||||
pass
|
||||
return final_path
|
||||
except Exception as e:
|
||||
logger.error("导出过程出错: %s", e)
|
||||
# 登录态失效(OA/HR):直接上抛,提示先运行对应登录指令,不自动补登
|
||||
raise
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def export_participation(output_dir=".", query_date=None):
|
||||
return export_employee_change_list(
|
||||
MENU_NAME_PARTICIPATE, FILTER_IDX_PARTICIPATE, DEFAULT_EXPORT_COLUMNS, output_dir, query_date)
|
||||
|
||||
|
||||
def export_suspension(output_dir=".", query_date=None):
|
||||
return export_employee_change_list(
|
||||
MENU_NAME_SUSPEND, FILTER_IDX_SUSPEND, DEFAULT_EXPORT_COLUMNS_SUSPEND, output_dir, query_date)
|
||||
|
||||
|
||||
# ==================== 结果推送(写全局变量 messages,由「37du钉钉单聊推送」指令发送) ====================
|
||||
def _read_abnormal(xlsx_path, label):
|
||||
"""读取标注表,返回 (总条数, 异常行列表)。异常行形如 [工号, 申请人/姓名, 结果] 说明文本。"""
|
||||
if not os.path.exists(xlsx_path):
|
||||
return 0, []
|
||||
ws = _load_workbook(xlsx_path).active
|
||||
rows = list(ws.iter_rows(values_only=True))
|
||||
headers = [str(h) if h is not None else "" for h in rows[0]]
|
||||
emp_col = next((i for i, h in enumerate(headers) if "工号" in h), None)
|
||||
res_col = headers.index(SI_RESULT_COL)
|
||||
name_candidates = ("参保人",) if label == "参保" else ("停保人姓名",)
|
||||
name_col = next((i for i, h in enumerate(headers) if h in name_candidates), None)
|
||||
abnormal = []
|
||||
for r in rows[1:]:
|
||||
val = r[res_col] if res_col < len(r) else ""
|
||||
if val and str(val).startswith("异常"):
|
||||
emp = str(r[emp_col]) if emp_col is not None and emp_col < len(r) else ""
|
||||
name = str(r[name_col]) if name_col is not None and name_col < len(r) else ""
|
||||
abnormal.append(f" · 工号{emp} {name} —— {val}")
|
||||
return len(rows) - 1, abnormal
|
||||
|
||||
|
||||
def build_push_text(part_path, susp_path):
|
||||
p_total, p_abn = _read_abnormal(part_path, "参保")
|
||||
s_total, s_abn = _read_abnormal(susp_path, "停保")
|
||||
lines = ["【社保增减名单核对结果】"]
|
||||
lines.append(f"参保表:共 {p_total} 条,异常 {len(p_abn)} 条")
|
||||
if p_abn:
|
||||
lines.extend(p_abn)
|
||||
else:
|
||||
lines.append(" 无异常")
|
||||
lines.append("")
|
||||
lines.append(f"停保表:共 {s_total} 条,异常 {len(s_abn)} 条")
|
||||
if s_abn:
|
||||
lines.extend(s_abn)
|
||||
else:
|
||||
lines.append(" 无异常")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _package_files(paths, save_dir):
|
||||
"""单文件直接返回原路径;多文件打包 zip(时间戳命名);无有效文件返回 None。"""
|
||||
exist_files = [p for p in paths if p and os.path.exists(p)]
|
||||
if not exist_files:
|
||||
return None
|
||||
if len(exist_files) == 1:
|
||||
return exist_files[0]
|
||||
_ensure_dir(save_dir)
|
||||
zip_path = os.path.join(
|
||||
save_dir,
|
||||
f"社保增减名单_{datetime.now().strftime('%Y%m%d_%H%M%S')}.zip",
|
||||
)
|
||||
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for fp in exist_files:
|
||||
zf.write(fp, os.path.basename(fp))
|
||||
logger.info("多文件已打包 %d 个到 %s", len(exist_files), zip_path)
|
||||
return zip_path
|
||||
|
||||
|
||||
def _build_push_messages(part_path, susp_path, save_dir):
|
||||
"""构造 dws 单聊推送消息:先发文本汇总,再发表文件(单文件直接推,多文件打包 zip)。"""
|
||||
messages = [{
|
||||
"msg_type": "text",
|
||||
"name": PUSH_RECEIVER_NAME,
|
||||
"user_id": PUSH_RECEIVER_ID,
|
||||
"content": build_push_text(part_path, susp_path),
|
||||
"file_path": "",
|
||||
}]
|
||||
file_target = _package_files([part_path, susp_path], save_dir)
|
||||
if file_target:
|
||||
messages.append({
|
||||
"msg_type": "file",
|
||||
"name": PUSH_RECEIVER_NAME,
|
||||
"user_id": PUSH_RECEIVER_ID,
|
||||
"content": "",
|
||||
"file_path": file_target,
|
||||
})
|
||||
return messages
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def main():
|
||||
load_dotenv()
|
||||
args = sys.argv[1:]
|
||||
output_dir = os.getenv("social_change_output_dir") or r"D:\资料\人资\员工社保增减名单"
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
query_date = None
|
||||
change_type = "全部"
|
||||
for a in args:
|
||||
if re.match(r"^\d{4}-\d{2}-\d{2}$", a):
|
||||
query_date = a
|
||||
elif a in ("参保", "participate"):
|
||||
change_type = "参保"
|
||||
elif a in ("停保", "suspend"):
|
||||
change_type = "停保"
|
||||
|
||||
if query_date is None:
|
||||
query_date = os.getenv("social_change_query_date") or None
|
||||
|
||||
part_path = ""
|
||||
susp_path = ""
|
||||
if change_type in ("参保", "全部"):
|
||||
part_path = export_participation(output_dir=output_dir, query_date=query_date)
|
||||
if change_type in ("停保", "全部"):
|
||||
susp_path = export_suspension(output_dir=output_dir, query_date=query_date)
|
||||
|
||||
# 写全局变量 messages(dws 单聊推送:文本汇总 + 表文件,单文件直接推/多文件打包 zip)
|
||||
if part_path or susp_path:
|
||||
messages = _build_push_messages(part_path, susp_path, output_dir)
|
||||
_set_glv("messages", messages)
|
||||
logger.info("已写全局变量 messages(%d 条),交由「37du钉钉单聊推送」指令发送给 %s(%s)",
|
||||
len(messages), PUSH_RECEIVER_NAME, PUSH_RECEIVER_ID)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,408 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: generate_add.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: XQ0008 重庆社保增员导入名单制作 —— 单文件自包含版(影刀直接运行)
|
||||
1. 读取《XX月社保变更及增减名单》中【参保名单】sheet(表头在第3行),
|
||||
筛选【区域=重庆】且【参保类型=指定类型】的记录
|
||||
2. 按【参保单位】分组,复制《增员模版.xls》(保留下拉字典 Sheet2),
|
||||
写入 B1(社保号)/D1(参保单位全称) 及 B4 起的数据行,逐店另存为
|
||||
《XX店增员导入名单.xls》至 BASE_DIR/新参保-增员 或 BASE_DIR/转移参保-增员
|
||||
(按参保类型分文件夹存放)
|
||||
3. 日期规则:1号 → 制作「转移参保」;11号 → 制作「新参保」
|
||||
填写标准:首次参加工作日期=本月1号、个人身份=24.工人、
|
||||
工伤参保时间=当日、其他参保时间=本月1号
|
||||
@Version: 1.2.0
|
||||
- v1.2.0:输出按参保类型分文件夹(新参保-增员 / 转移参保-增员),不再混放同一目录。
|
||||
- v1.1.0:适配真实文件——源表表头第3行、类型列「参保类型」(非"申请")、
|
||||
sheet 名按月匹配(202609参保名单)、模板为 .xls(xlrd/xlutils 复制保留下拉);
|
||||
月基本工资额取源表「工资申报」列(按用户要求,申报基数大量为空);
|
||||
影刀单文件自包含(内联全部配置)。
|
||||
- v1.0.0:按 aa.md 拆 config.py + generate_add.py(已废弃,合并进本文件)
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install pandas openpyxl xlrd xlwt xlutils
|
||||
|
||||
环境变量(.env 文件或系统变量,可选):
|
||||
cq_social_change_dir = 资料根目录(默认 D:\\资料\\人资\\重庆社保增减员导入名单制作)
|
||||
|
||||
运行:python generate_add.py
|
||||
(如需强制生成指定类型:python 中调用 generate_add.process_add_members('新参保'))
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import math
|
||||
from datetime import datetime
|
||||
from glob import glob
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把本文件所在目录加入 sys.path,保证可独立运行 ----
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
if str(_HERE) not in sys.path:
|
||||
sys.path.insert(0, str(_HERE))
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import pandas as pd
|
||||
import xlrd
|
||||
import xlwt
|
||||
from xlutils.copy import copy as xl_copy
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install pandas openpyxl xlrd xlwt xlutils\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
# ==================== 1. 文件路径配置 ====================
|
||||
BASE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员导入名单制作"
|
||||
# 源表文件名按月变化(如 2026年9月社保变更及增减名单及人数统计.xlsx),按模式取最新
|
||||
SOURCE_GLOB = "*社保*.xlsx"
|
||||
# 增员导入模板(.xls 老格式,用 xlrd 读取 + xlutils 复制)
|
||||
TEMPLATE_FILE = "增员模版.xls"
|
||||
# 输出子目录(按参保类型分文件夹:新参保 / 转移参保 各存一份,避免混放)
|
||||
OUTPUT_DIR_NAME = {
|
||||
'新参保': '新参保-增员',
|
||||
'转移参保': '转移参保-增员',
|
||||
}
|
||||
# 目标区域
|
||||
TARGET_REGION = "重庆"
|
||||
|
||||
# ==================== 2. 源表结构配置 ====================
|
||||
# 参保名单 sheet 名按月变化(如 202609参保名单),按关键字匹配
|
||||
SHEET_KEY = "参保名单"
|
||||
# 源表表头在第3行(H3-AY3)
|
||||
SOURCE_HEADER_ROW = 3
|
||||
# 源表筛选列:区域(筛选重庆)、参保类型(新参保/转移参保)
|
||||
REGION_COL = "区域"
|
||||
TYPE_COL = "参保类型"
|
||||
|
||||
# ==================== 3. 源表列名 ↔ 模板列名映射 ====================
|
||||
# 键为模板列含义,值为源表列名
|
||||
COLUMN_MAP = {
|
||||
'姓名': '姓名',
|
||||
'证件号码': '身份证号码',
|
||||
'民族': '民族',
|
||||
'月基本工资额': '工资申报', # 用户指定:月基本工资额取「工资申报」列(申报基数大量为空)
|
||||
'户口性质': '户口性质',
|
||||
'文化程度': '文化程度',
|
||||
'联系电话': '电话号码',
|
||||
'单位名称': '参保单位', # 用于分组
|
||||
'社保号': '社保号', # 用于 B1 单元格
|
||||
'参保单位全称': '参保单位全称', # 用于 D1 单元格
|
||||
'备注': '备注',
|
||||
}
|
||||
|
||||
# ==================== 4. 学历映射 ====================
|
||||
EDU_MAP = {
|
||||
'硕士研究生': '14.硕士研究生',
|
||||
'本科': '21.大学本科',
|
||||
'大专': '31.大学专科',
|
||||
'高中': '61.普通中学',
|
||||
'职高/中专/中技': '44.职业高中',
|
||||
'初中': '71.初级中学',
|
||||
'小学': '81.小学',
|
||||
}
|
||||
def translate_education(val):
|
||||
if val is None:
|
||||
return '90.其他'
|
||||
try:
|
||||
if pd.isna(val):
|
||||
return '90.其他'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return EDU_MAP.get(str(val).strip(), '90.其他')
|
||||
|
||||
# ==================== 5. 民族映射 ====================
|
||||
NATION_MAP = {
|
||||
'汉族': '01.汉族', '蒙古族': '02.蒙古族', '回族': '03.回族', '藏族': '04.藏族',
|
||||
'维吾尔族': '05.维吾尔族', '苗族': '06.苗族', '彝族': '07.彝族', '壮族': '08.壮族',
|
||||
'布依族': '09.布依族', '朝鲜族': '10.朝鲜族', '满族': '11.满族', '侗族': '12.侗族',
|
||||
'瑶族': '13.瑶族', '白族': '14.白族', '土家族': '15.土家族', '哈尼族': '16.哈尼族',
|
||||
'哈萨克族': '17.哈萨克族', '傣族': '18.傣族', '黎族': '19.黎族', '傈僳族': '20.傈僳族',
|
||||
'佤族': '21.佤族', '畲族': '22.畲族', '高山族': '23.高山族', '拉祜族': '24.拉祜族',
|
||||
'水族': '25.水族', '东乡族': '26.东乡族', '纳西族': '27.纳西族', '景颇族': '28.景颇族',
|
||||
'柯尔克孜族': '29.柯尔克孜族', '土族': '30.土族', '达斡尔族': '31.达斡尔族',
|
||||
'仫佬族': '32.仫佬族', '羌族': '33.羌族', '布朗族': '34.布朗族', '撒拉族': '35.撒拉族',
|
||||
'毛南族': '36.毛南族', '仡佬族': '37.仡佬族', '锡伯族': '38.锡伯族', '阿昌族': '39.阿昌族',
|
||||
'普米族': '40.普米族', '塔吉克族': '41.塔吉克族', '怒族': '42.怒族',
|
||||
'乌孜别克族': '43.乌孜别克族', '俄罗斯族': '44.俄罗斯族', '鄂温克族': '45.鄂温克族',
|
||||
'德昂族': '46.德昂族', '保安族': '47.保安族', '裕固族': '48.裕固族', '京族': '49.京族',
|
||||
'塔塔尔族': '50.塔塔尔族', '独龙族': '51.独龙族', '鄂伦春族': '52.鄂伦春族',
|
||||
'赫哲族': '53.赫哲族', '门巴族': '54.门巴族', '珞巴族': '55.珞巴族', '基诺族': '56.基诺族',
|
||||
'少数民族': '57.少数民族', '其他': '99.其他',
|
||||
}
|
||||
def translate_nation(val):
|
||||
if val is None:
|
||||
return '99.其他'
|
||||
try:
|
||||
if pd.isna(val):
|
||||
return '99.其他'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return NATION_MAP.get(str(val).strip(), '99.其他')
|
||||
|
||||
# ==================== 6. 户籍类型映射 ====================
|
||||
RESIDENCE_MAP = {
|
||||
'本地城镇': '11.本市城镇',
|
||||
'本地农村': '21.本市农村',
|
||||
'外地城镇': '12.外市城镇',
|
||||
'外地农村': '22.外市农村',
|
||||
}
|
||||
def translate_residence(val):
|
||||
if val is None:
|
||||
return ''
|
||||
try:
|
||||
if pd.isna(val):
|
||||
return ''
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return RESIDENCE_MAP.get(str(val).strip(), '')
|
||||
|
||||
# ==================== 7. 固定默认值 ====================
|
||||
DEFAULT_VALUES = {
|
||||
'个人身份': '24.工人',
|
||||
'证件类型': '01.居民身份证(户口簿)',
|
||||
'国籍': 'CHN.中国',
|
||||
'专职技能': '499.未定职级',
|
||||
'技能等级': '无',
|
||||
'工种': '', # 留空
|
||||
'备注': '', # 留空
|
||||
}
|
||||
|
||||
# ==================== 8. 增员模版配置(表头 B2:U2,数据从第4行起) ====================
|
||||
TPL_DATA_START_ROW = 4 # 数据从第4行开始
|
||||
# 模板表头(B2:U2,共20列,顺序固定)
|
||||
TPL_COLS = [
|
||||
'证件号码', '姓名', '民族', '首次参加工作日期', '月基本工资额', '工种', '个人身份',
|
||||
'户口性质', '联系电话', '文化程度', '养老保险参保时间', '失业保险参保时间',
|
||||
'医疗保险参保时间', '工伤保险参保时间', '生育保险参保时间', '证件类型', '国籍',
|
||||
'备注', '专职技能', '技能等级',
|
||||
]
|
||||
# 需按日期写入的模板列(工伤保险=当日,其余=本月1日)
|
||||
DATE_COLS = {
|
||||
'首次参加工作日期', '养老保险参保时间', '失业保险参保时间',
|
||||
'医疗保险参保时间', '工伤保险参保时间', '生育保险参保时间',
|
||||
}
|
||||
|
||||
|
||||
# ==================== 9. 通用辅助 ====================
|
||||
def _to_text(value):
|
||||
"""转可写文本:证件号/电话等长数字统一为字符串,避免丢精度/科学计数。"""
|
||||
if value is None:
|
||||
return ''
|
||||
try:
|
||||
if pd.isna(value):
|
||||
return ''
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, float) and value.is_integer():
|
||||
return str(int(value))
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _clean_value(value):
|
||||
"""None/NaN 归一为 '',其余原样(用于写入单元格)。"""
|
||||
if value is None:
|
||||
return ''
|
||||
if isinstance(value, float) and math.isnan(value):
|
||||
return ''
|
||||
return value
|
||||
|
||||
|
||||
def _safe_name(value):
|
||||
"""单位名转安全文件名:None/NaN/空白 → '未知单位';只剥掉尾部一个「店」,
|
||||
避免「某某店」拼成「某某店店…」,也避免「某某店店」被全剥成「某某」。"""
|
||||
if value is None:
|
||||
return '未知单位'
|
||||
try:
|
||||
if pd.isna(value) or not str(value).strip():
|
||||
return '未知单位'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
name = str(value).replace("/", "_").replace("\\", "_").replace(":", "_").strip()
|
||||
if name.endswith("店"):
|
||||
name = name[:-1]
|
||||
return name
|
||||
|
||||
|
||||
def _get_dates():
|
||||
"""返回(当日, 当月1日):工伤保险参保时间用当日,其余用当月1日。"""
|
||||
today = datetime.now()
|
||||
first_day = today.replace(day=1)
|
||||
return today, first_day
|
||||
|
||||
|
||||
def find_source_file():
|
||||
"""定位源表(*社保*.xlsx,排除 Excel 临时文件 ~$,取最新)。"""
|
||||
candidates = [
|
||||
p for p in glob(os.path.join(BASE_DIR, SOURCE_GLOB))
|
||||
if not os.path.basename(p).startswith("~$")
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {BASE_DIR} 下未找到源表(匹配 {SOURCE_GLOB}),请先准备《社保变更及增减名单》。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def find_template_file():
|
||||
"""定位《增员模版.xls》(优先精确名,其次按 *增员模版*.xls 匹配)。"""
|
||||
exact = os.path.join(BASE_DIR, TEMPLATE_FILE)
|
||||
if os.path.isfile(exact):
|
||||
return exact
|
||||
candidates = glob(os.path.join(BASE_DIR, "*增员模版*.xls"))
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {BASE_DIR} 下未找到《{TEMPLATE_FILE}》,请先准备增员导入模板。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def find_source_sheet(source_file):
|
||||
"""按关键字匹配源表【参保名单】sheet(sheet 名按月变化,如 202609参保名单)。"""
|
||||
xl = pd.ExcelFile(source_file)
|
||||
for name in xl.sheet_names:
|
||||
if SHEET_KEY in name:
|
||||
return name
|
||||
raise ValueError(
|
||||
f"源表 {os.path.basename(source_file)} 中未找到包含「{SHEET_KEY}」的 sheet,"
|
||||
f"实际 sheets:{xl.sheet_names}")
|
||||
|
||||
|
||||
def get_output_dir(operation_type):
|
||||
"""按参保类型取输出目录(BASE_DIR/新参保-增员 或 BASE_DIR/转移参保-增员)。
|
||||
|
||||
新参保、转移参保分别存放到不同文件夹,避免混放;目录不存在则自动创建。
|
||||
"""
|
||||
sub = OUTPUT_DIR_NAME.get(operation_type)
|
||||
if not sub:
|
||||
raise ValueError(f"未知参保类型:{operation_type}(可选:{'/'.join(OUTPUT_DIR_NAME)})")
|
||||
out_dir = os.path.join(BASE_DIR, sub)
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
return out_dir
|
||||
|
||||
|
||||
# ==================== 10. 模板写入(xlrd 读取 + xlutils 复制,保留下拉字典) ====================
|
||||
def _write_template(template_file, output_path, unit_no, unit_name, records):
|
||||
"""复制《增员模版.xls》写入 B1/D1 及 B4 起数据,另存为 output_path。
|
||||
|
||||
- 使用 xlrd 读取(formatting_info 保留样式)+ xlutils.copy 复制,
|
||||
保留 Sheet2 下拉字典与数据有效性;
|
||||
- B1=社保号,D1=参保单位全称;数据从模板第4行起,按 TPL_COLS 顺序写入 B~U 列;
|
||||
- 日期列以序列数 + YYYY-MM-DD 格式写入(工伤=当日,其余在 rec 中已填本月1日);
|
||||
- 模板原数据区中未被覆盖的多余示例行清空。
|
||||
"""
|
||||
rb = xlrd.open_workbook(template_file, formatting_info=True)
|
||||
datemode = rb.datemode
|
||||
orig_rows = rb.sheet_by_index(0).nrows
|
||||
wb = xl_copy(rb)
|
||||
ws = wb.get_sheet(0) # 批量导入
|
||||
ws.write(0, 1, unit_no) # B1 社保号
|
||||
ws.write(0, 3, unit_name) # D1 参保单位全称
|
||||
date_style = xlwt.easyxf(num_format_str='YYYY-MM-DD')
|
||||
for i, rec in enumerate(records):
|
||||
r = TPL_DATA_START_ROW - 1 + i # 0-based:模板第4行 → index 3
|
||||
for c, col in enumerate(TPL_COLS):
|
||||
val = rec.get(col)
|
||||
if col in DATE_COLS and val is not None:
|
||||
xld = xlrd.xldate.xldate_from_datetime_tuple(
|
||||
(val.year, val.month, val.day, 0, 0, 0), datemode)
|
||||
ws.write(r, c + 1, xld, date_style) # 列 c+1:B=1 ... U=20
|
||||
else:
|
||||
ws.write(r, c + 1, _clean_value(val))
|
||||
# 清空模板原数据区(第4行起)未被覆盖的多余示例行
|
||||
for r in range(TPL_DATA_START_ROW - 1 + len(records), orig_rows):
|
||||
for c in range(1, len(TPL_COLS) + 1):
|
||||
ws.write(r, c, "")
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
wb.save(output_path)
|
||||
|
||||
|
||||
# ==================== 11. 主流程 ====================
|
||||
def process_add_members(operation_type):
|
||||
"""
|
||||
生成增员导入名单
|
||||
operation_type: '新参保' 或 '转移参保'
|
||||
"""
|
||||
# 1. 读取源表【参保名单】sheet(表头在第3行)
|
||||
source_file = find_source_file()
|
||||
sheet_name = find_source_sheet(source_file)
|
||||
print(f"源表:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||||
df_source = pd.read_excel(
|
||||
source_file,
|
||||
sheet_name=sheet_name,
|
||||
header=SOURCE_HEADER_ROW - 1,
|
||||
# 身份证/电话按文本读:18 位身份证若被推断为数字会丢精度(与停保脚本一致);
|
||||
# 工资申报等数值列保持默认数值读法,写模板时才是数字而非 "5200.0" 文本
|
||||
dtype={'身份证号码': str, '电话号码': str}
|
||||
)
|
||||
|
||||
# 2. 筛选:区域=重庆,参保类型=指定类型
|
||||
mask = (
|
||||
(df_source[REGION_COL] == TARGET_REGION) &
|
||||
(df_source[TYPE_COL] == operation_type)
|
||||
)
|
||||
df_filtered = df_source[mask].copy()
|
||||
if df_filtered.empty:
|
||||
print(f"没有找到【{operation_type}】的数据({TARGET_REGION}区域)")
|
||||
return
|
||||
|
||||
# 3. 获取日期
|
||||
today, first_day = _get_dates()
|
||||
print(f"今日日期:{today.strftime('%Y-%m-%d')}")
|
||||
print(f"本月1日:{first_day.strftime('%Y-%m-%d')}(首次参加/养老/失业/医疗/生育参保时间)")
|
||||
print(f"工伤参保时间:{today.strftime('%Y-%m-%d')}(当日)")
|
||||
|
||||
# 4. 按参保单位分组生成
|
||||
template_file = find_template_file()
|
||||
output_dir = get_output_dir(operation_type)
|
||||
print(f"输出目录:{output_dir}")
|
||||
store_col = COLUMN_MAP['单位名称']
|
||||
for store_name, group in df_filtered.groupby(store_col):
|
||||
print(f" 正在处理:{store_name},共 {len(group)} 人")
|
||||
first_row = group.iloc[0]
|
||||
unit_no = first_row[COLUMN_MAP['社保号']]
|
||||
unit_full_name = first_row[COLUMN_MAP['参保单位全称']]
|
||||
|
||||
# 5. 逐行生成数据(键 = 模板列名)
|
||||
records = []
|
||||
for _, row in group.iterrows():
|
||||
rec = {
|
||||
'证件号码': _to_text(row[COLUMN_MAP['证件号码']]),
|
||||
'姓名': row[COLUMN_MAP['姓名']],
|
||||
'民族': translate_nation(row[COLUMN_MAP['民族']]),
|
||||
'首次参加工作日期': first_day,
|
||||
'月基本工资额': _clean_value(row[COLUMN_MAP['月基本工资额']]),
|
||||
'工种': DEFAULT_VALUES['工种'],
|
||||
'个人身份': DEFAULT_VALUES['个人身份'],
|
||||
'户口性质': translate_residence(row[COLUMN_MAP['户口性质']]),
|
||||
'联系电话': _to_text(row[COLUMN_MAP['联系电话']]),
|
||||
'文化程度': translate_education(row[COLUMN_MAP['文化程度']]),
|
||||
'养老保险参保时间': first_day,
|
||||
'失业保险参保时间': first_day,
|
||||
'医疗保险参保时间': first_day,
|
||||
'工伤保险参保时间': today,
|
||||
'生育保险参保时间': first_day,
|
||||
'证件类型': DEFAULT_VALUES['证件类型'],
|
||||
'国籍': DEFAULT_VALUES['国籍'],
|
||||
'备注': DEFAULT_VALUES['备注'],
|
||||
'专职技能': DEFAULT_VALUES['专职技能'],
|
||||
'技能等级': DEFAULT_VALUES['技能等级'],
|
||||
}
|
||||
records.append(rec)
|
||||
|
||||
# 6. 写入模板并另存
|
||||
output_path = os.path.join(output_dir, f"{_safe_name(store_name)}增员导入名单.xls")
|
||||
_write_template(template_file, output_path, unit_no, unit_full_name, records)
|
||||
print(f" 已生成:{output_path}")
|
||||
|
||||
print(f"所有【{operation_type}】导入名单生成完成!")
|
||||
|
||||
|
||||
# ==================== 12. 主入口(日期规则) ====================
|
||||
if __name__ == "__main__":
|
||||
process_add_members('转移参保')
|
||||
process_add_members('新参保')
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: generate_stop.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: XQ0008 重庆社保停保导入名单制作 —— 单文件自包含版(影刀直接运行)
|
||||
与 generate_add.py(增员)同套实现方式:xlrd 读取 + xlutils 复制模板,保留下拉字典与样式。
|
||||
1. 读取《XX月社保变更及增减名单》中【停保名单】sheet(表头在第3行),
|
||||
筛选【区域=重庆】的记录(身份证/社保编号按文本读取,防丢精度)
|
||||
2. 按【参保单位】分组,复制《减员模版.xls》(保留下拉字典 二级代码),
|
||||
写入 B1(单位社保号)/D1(参保单位) 及 B4 起的数据行,逐单位另存为
|
||||
《XX减员导入名单.xls》至 BASE_DIR/停保-减员(与增员按单位命名一致)
|
||||
3. 填写标准:减少时间=当天、减少原因=在职人员主动解除劳动合同、
|
||||
五个险种减少标志=1 减少、失业原因=3 劳动者自愿辞职
|
||||
(固定 28 号执行,可调用 process_stop_members() 强制)
|
||||
@Version: 1.0.0
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install pandas openpyxl xlrd xlwt xlutils
|
||||
|
||||
环境变量(.env 文件或系统变量,可选):
|
||||
cq_social_change_dir = 资料根目录(默认 D:\\资料\\人资\\重庆社保增减员导入名单制作)
|
||||
|
||||
运行:python generate_stop.py
|
||||
(如需强制生成:python 中调用 generate_stop.process_stop_members())
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import math
|
||||
from datetime import datetime
|
||||
from glob import glob
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把本文件所在目录加入 sys.path,保证可独立运行 ----
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
if str(_HERE) not in sys.path:
|
||||
sys.path.insert(0, str(_HERE))
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import pandas as pd
|
||||
import xlrd
|
||||
import xlwt
|
||||
from xlutils.copy import copy as xl_copy
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install pandas openpyxl xlrd xlwt xlutils\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
# ==================== 1. 文件路径配置 ====================
|
||||
BASE_DIR = os.getenv("cq_social_change_dir") or r"D:\资料\人资\重庆社保增减员导入名单制作"
|
||||
# 源表文件名按月变化(如 2026年9月社保变更及增减名单及人数统计.xlsx),按模式取最新
|
||||
SOURCE_GLOB = "*社保*.xlsx"
|
||||
# 停保导入模板(.xls 老格式,用 xlrd 读取 + xlutils 复制)
|
||||
TEMPLATE_FILE = "减员模版.xls"
|
||||
# 输出子目录(BASE_DIR/停保-减员),存放各单位停保导入名单(与增员的「新参保-增员/转移参保-增员」并列)
|
||||
OUTPUT_DIR_NAME = "停保-减员"
|
||||
# 目标区域
|
||||
TARGET_REGION = "重庆"
|
||||
|
||||
# ==================== 2. 源表结构配置 ====================
|
||||
# 停保名单 sheet 名按月变化(如 202609停保名单),按关键字匹配
|
||||
SHEET_KEY = "停保名单"
|
||||
# 源表表头在第3行
|
||||
SOURCE_HEADER_ROW = 3
|
||||
# 源表筛选列:区域(筛选重庆)
|
||||
REGION_COL = "区域"
|
||||
# 用于分组的列(参保单位,按单位存储/命名,与增员一致)
|
||||
GROUP_COL = "参保单位"
|
||||
|
||||
# ==================== 3. 源表列名 ↔ 模板列名映射 ====================
|
||||
# 键为模板列含义,值为源表列名
|
||||
COLUMN_MAP = {
|
||||
'个人编号': '社保编号', # 模板列 → 源表「社保编号」
|
||||
'证件号码': '身份证号码', # 模板列 → 源表「身份证号码」
|
||||
'姓名': '停保人姓名', # 模板列 → 源表「停保人姓名」
|
||||
'单位社保号': '单位社保号', # 用于 B1 单元格
|
||||
'单位名称': '参保单位', # 用于分组、文件名 和 D1 单元格
|
||||
}
|
||||
|
||||
# ==================== 4. 固定默认值 ====================
|
||||
DEFAULT_VALUES = {
|
||||
# 减少原因(固定)
|
||||
'减少原因': '在职人员主动解除劳动合同',
|
||||
# 五个险种减少标志(固定为"1 减少")
|
||||
'养老保险减少标志': '1 减少',
|
||||
'失业保险减少标志': '1 减少',
|
||||
'医疗保险减少标志': '1 减少',
|
||||
'工伤保险减少标志': '1 减少',
|
||||
'生育保险减少标志': '1 减少',
|
||||
# 失业原因(固定,取值须与模板下拉「二级代码」一致:数字3后两个空格)
|
||||
'失业原因': '3 劳动者自愿辞职',
|
||||
}
|
||||
|
||||
# ==================== 5. 减员模版配置(表头 B2:L2,数据从第4行起) ====================
|
||||
TPL_DATA_START_ROW = 4 # 数据从第4行开始
|
||||
# 模板表头(B2:L2,共11列,顺序固定)
|
||||
TPL_COLS = [
|
||||
'个人编号', '证件号码', '姓名', '减少时间', '减少原因',
|
||||
'养老保险减少标志', '失业保险减少标志', '医疗保险减少标志',
|
||||
'工伤保险减少标志', '生育保险减少标志', '失业原因',
|
||||
]
|
||||
# 需按日期写入的模板列(减少时间=当天)
|
||||
DATE_COLS = {'减少时间'}
|
||||
|
||||
|
||||
# ==================== 6. 通用辅助 ====================
|
||||
def _clean_value(value):
|
||||
"""None/NaN 归一为 '',其余原样(用于写入单元格)。"""
|
||||
if value is None:
|
||||
return ''
|
||||
if isinstance(value, float) and math.isnan(value):
|
||||
return ''
|
||||
return value
|
||||
|
||||
|
||||
def _safe_name(value):
|
||||
"""单位名转安全文件名:None/NaN/空白 → '未知单位';只剥掉尾部一个「店」,
|
||||
避免「某某店」拼成「某某店店…」,也避免「某某店店」被全剥成「某某」。"""
|
||||
if value is None:
|
||||
return '未知单位'
|
||||
try:
|
||||
if pd.isna(value) or not str(value).strip():
|
||||
return '未知单位'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
name = str(value).replace("/", "_").replace("\\", "_").replace(":", "_").strip()
|
||||
if name.endswith("店"):
|
||||
name = name[:-1]
|
||||
return name
|
||||
|
||||
|
||||
def _get_today():
|
||||
"""返回当日日期(停保减少时间 = 制作当天)。"""
|
||||
return datetime.now()
|
||||
|
||||
|
||||
def find_source_file():
|
||||
"""定位源表(*社保*.xlsx,排除 Excel 临时文件 ~$,取最新)。"""
|
||||
candidates = [
|
||||
p for p in glob(os.path.join(BASE_DIR, SOURCE_GLOB))
|
||||
if not os.path.basename(p).startswith("~$")
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {BASE_DIR} 下未找到源表(匹配 {SOURCE_GLOB}),请先准备《社保变更及增减名单》。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def find_template_file():
|
||||
"""定位《减员模版.xls》(优先精确名,其次按 *减员模版*.xls 匹配)。"""
|
||||
exact = os.path.join(BASE_DIR, TEMPLATE_FILE)
|
||||
if os.path.isfile(exact):
|
||||
return exact
|
||||
candidates = glob(os.path.join(BASE_DIR, "*减员模版*.xls"))
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {BASE_DIR} 下未找到《{TEMPLATE_FILE}》,请先准备停保导入模板。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def find_source_sheet(source_file):
|
||||
"""按关键字匹配源表【停保名单】sheet(sheet 名按月变化,如 202609停保名单)。"""
|
||||
xl = pd.ExcelFile(source_file)
|
||||
for name in xl.sheet_names:
|
||||
if SHEET_KEY in name:
|
||||
return name
|
||||
raise ValueError(
|
||||
f"源表 {os.path.basename(source_file)} 中未找到包含「{SHEET_KEY}」的 sheet,"
|
||||
f"实际 sheets:{xl.sheet_names}")
|
||||
|
||||
|
||||
def get_output_dir():
|
||||
"""输出目录(BASE_DIR/减员),不存在则自动创建。"""
|
||||
out_dir = os.path.join(BASE_DIR, OUTPUT_DIR_NAME)
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
return out_dir
|
||||
|
||||
|
||||
# ==================== 7. 模板写入(xlrd 读取 + xlutils 复制,保留下拉字典) ====================
|
||||
def _write_template(template_file, output_path, unit_no, unit_name, records):
|
||||
"""复制《减员模版.xls》写入 B1/D1 及 B4 起数据,另存为 output_path。
|
||||
|
||||
- 使用 xlrd 读取(formatting_info 保留样式)+ xlutils.copy 复制,
|
||||
保留「二级代码」下拉字典与数据有效性;
|
||||
- B1=单位社保号,D1=参保单位;数据从模板第4行起,按 TPL_COLS 顺序写入 B~L 列;
|
||||
- 减少时间以序列数 + YYYY-MM-DD 格式写入(当天);
|
||||
- 模板原数据区中未被覆盖的多余示例行清空。
|
||||
"""
|
||||
rb = xlrd.open_workbook(template_file, formatting_info=True)
|
||||
datemode = rb.datemode
|
||||
orig_rows = rb.sheet_by_index(0).nrows
|
||||
wb = xl_copy(rb)
|
||||
ws = wb.get_sheet(0) # 批量导入
|
||||
ws.write(0, 1, unit_no) # B1 单位社保号
|
||||
ws.write(0, 3, unit_name) # D1 单位全称
|
||||
date_style = xlwt.easyxf(num_format_str='YYYY-MM-DD')
|
||||
for i, rec in enumerate(records):
|
||||
r = TPL_DATA_START_ROW - 1 + i # 0-based:模板第4行 → index 3
|
||||
for c, col in enumerate(TPL_COLS):
|
||||
val = rec.get(col)
|
||||
if col in DATE_COLS and val is not None:
|
||||
xld = xlrd.xldate.xldate_from_datetime_tuple(
|
||||
(val.year, val.month, val.day, 0, 0, 0), datemode)
|
||||
ws.write(r, c + 1, xld, date_style) # 列 c+1:B=1 ... L=11
|
||||
else:
|
||||
ws.write(r, c + 1, _clean_value(val))
|
||||
# 清空模板原数据区(第4行起)未被覆盖的多余示例行
|
||||
for r in range(TPL_DATA_START_ROW - 1 + len(records), orig_rows):
|
||||
for c in range(1, len(TPL_COLS) + 1):
|
||||
ws.write(r, c, "")
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
wb.save(output_path)
|
||||
|
||||
|
||||
# ==================== 8. 主流程 ====================
|
||||
def process_stop_members():
|
||||
"""
|
||||
生成停保导入名单
|
||||
规则:区域=重庆;按单位社保号分组;减少时间=当天;减少原因=在职人员主动解除劳动合同;
|
||||
五个险种减少标志=1 减少;失业原因=3 劳动者自愿辞职
|
||||
"""
|
||||
# 1. 读取源表【停保名单】sheet(表头在第3行,全列按文本读,保住身份证/社保编号完整值)
|
||||
source_file = find_source_file()
|
||||
sheet_name = find_source_sheet(source_file)
|
||||
print(f"源表:{os.path.basename(source_file)}(sheet: {sheet_name})")
|
||||
df_source = pd.read_excel(
|
||||
source_file,
|
||||
sheet_name=sheet_name,
|
||||
header=SOURCE_HEADER_ROW - 1,
|
||||
dtype=str
|
||||
)
|
||||
|
||||
# 2. 筛选:区域=重庆
|
||||
df_filtered = df_source[df_source[REGION_COL] == TARGET_REGION].copy()
|
||||
if df_filtered.empty:
|
||||
print(f"没有找到【{TARGET_REGION}】区域的停保数据")
|
||||
return
|
||||
print(f"共找到 {len(df_filtered)} 条 {TARGET_REGION} 区域停保记录")
|
||||
|
||||
# 3. 获取当天日期(减少时间 = 当天)
|
||||
today = _get_today()
|
||||
print(f"制作日期:{today.strftime('%Y-%m-%d')}")
|
||||
print(f"减少时间:{today.strftime('%Y-%m-%d')}(当日)")
|
||||
|
||||
# 4. 按单位社保号分组生成
|
||||
template_file = find_template_file()
|
||||
output_dir = get_output_dir()
|
||||
print(f"输出目录:{output_dir}")
|
||||
for group_key, group in df_filtered.groupby(GROUP_COL):
|
||||
print(f" 正在处理:单位【{group_key}】,共 {len(group)} 人")
|
||||
first_row = group.iloc[0]
|
||||
unit_no = first_row[COLUMN_MAP['单位社保号']] # 单位社保号 → B1
|
||||
unit_name = first_row[COLUMN_MAP['单位名称']] # 参保单位 → D1
|
||||
|
||||
# 5. 逐行生成数据(键 = 模板列名)
|
||||
records = []
|
||||
for _, row in group.iterrows():
|
||||
rec = {
|
||||
'个人编号': _clean_value(row[COLUMN_MAP['个人编号']]),
|
||||
'证件号码': _clean_value(row[COLUMN_MAP['证件号码']]),
|
||||
'姓名': _clean_value(row[COLUMN_MAP['姓名']]),
|
||||
'减少时间': today,
|
||||
'减少原因': DEFAULT_VALUES['减少原因'],
|
||||
'养老保险减少标志': DEFAULT_VALUES['养老保险减少标志'],
|
||||
'失业保险减少标志': DEFAULT_VALUES['失业保险减少标志'],
|
||||
'医疗保险减少标志': DEFAULT_VALUES['医疗保险减少标志'],
|
||||
'工伤保险减少标志': DEFAULT_VALUES['工伤保险减少标志'],
|
||||
'生育保险减少标志': DEFAULT_VALUES['生育保险减少标志'],
|
||||
'失业原因': DEFAULT_VALUES['失业原因'],
|
||||
}
|
||||
records.append(rec)
|
||||
|
||||
# 6. 写入模板并另存
|
||||
output_path = os.path.join(output_dir, f"{_safe_name(group_key)}减员导入名单.xls")
|
||||
_write_template(template_file, output_path, unit_no, unit_name, records)
|
||||
print(f" 已生成:{output_path}")
|
||||
|
||||
print(f"所有停保导入名单生成完成!共 {len(df_filtered[GROUP_COL].unique())} 个单位")
|
||||
|
||||
|
||||
# ==================== 9. 主入口(固定28号执行) ====================
|
||||
if __name__ == "__main__":
|
||||
process_stop_members()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,998 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: attendance_abnormal_monthly.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-18
|
||||
@Description: EHR 系统月考勤异常处理(影刀版,单文件自包含)——三重复核上月考勤异常
|
||||
(结合考勤异常/请假/加班/打卡/排班五类接口),输出多 Sheet Excel 报告。
|
||||
检查1/2/3 及详细规则见 docs/考勤异常处理/月考勤异常处理需求文档.md。
|
||||
|
||||
登录(共享登录态,本脚本仅读取 cookies 文件,不 import 任何共享模块):
|
||||
「37duHR登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json;
|
||||
缺失/失效时先拖入「37duHR登录」指令再运行本流程。
|
||||
|
||||
设计说明(与 yingdao 下其它单文件版一致):
|
||||
- 单文件自包含,内联 HR 接口(getCurUserInfo / 考勤异常 / 请假 / 加班 / 打卡 / 排班),不依赖 app 包。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests python-dotenv pandas openpyxl
|
||||
|
||||
环境变量(.env 或系统变量,固定路径共享 .env 见 yingdao/share/hr_login.py):
|
||||
attendance_check_save_dir=(可选)报告导出目录,默认 D:\\资料\\人资\\考勤异常
|
||||
|
||||
运行:
|
||||
- 影刀「调用模块」:main()
|
||||
- 直接运行:python attendance_abnormal_monthly.py
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests python-dotenv pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# ==================== 日志(print) ====================
|
||||
class _PrintLogger:
|
||||
"""影刀版无 logging 依赖,直接用 print 输出,行为与项目 logger 对齐。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
# ==================== 影刀全局变量(glv) ====================
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ==================== 共享路径 & 常量配置(与 app 版统一) ====================
|
||||
_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_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
# HR 登录态:由「37duHR登录」共享指令(yingdao/share/hr_login.py)写入
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- HR 系统 ----------
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
KQ_LIST_URL = f"{HR_BASE_URL}/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ---------- 输出配置(与 app 版一致) ----------
|
||||
# 默认保存目录(与周考勤异常导出目录保持一致)
|
||||
SAVE_DIR = os.getenv("attendance_check_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 考勤异常调整状态过滤:0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有状态
|
||||
IS_ADJUSTED_CONFIRMED = "2" # 已确认异常(检查1)
|
||||
IS_ADJUSTED_OPEN = "0" # 未调整异常(检查3并集之一)
|
||||
|
||||
# 加班类型:空=全部、1=延时加班、2=法定假日加班、3=休息日加班
|
||||
WORK_OVERTIME_TYPE_REST = "3"
|
||||
|
||||
# 休息日半天加班判定阈值(ot_days / sys_ot_days / plan_ot_days ≈ 0.5)
|
||||
HALF_DAY = 0.5
|
||||
EPS = 1e-6
|
||||
|
||||
# 打卡与班段边界匹配容差(分钟):上班打卡在班段开始前后、下班打卡在班段结束前后
|
||||
PUNCH_TOLERANCE_MIN = 60
|
||||
|
||||
# 假期类型编码 → 名称(与 app 版 common/config.VACATION_TYPE_MAP 一致)
|
||||
VACATION_TYPE_MAP = {
|
||||
"04": "病假",
|
||||
"05": "产假",
|
||||
"09": "事假",
|
||||
"11": "调休假",
|
||||
"15": "普通事假",
|
||||
"17": "特殊事假",
|
||||
"18": "小时特假",
|
||||
"19": "普通事假(晚/高峰)",
|
||||
"20": "普通事假(早/中)",
|
||||
"22": "半天休(仅限人资专用)",
|
||||
"23": "特别福利假",
|
||||
"24": "年度福利假",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 yingdao/share/hr_login.py),
|
||||
# 本脚本为单文件自包含:仅读取共享 cookies 文件,不 import 任何共享模块。
|
||||
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
"""确保存在 HR 登录态文件;缺失时提示先运行「37duHR登录」指令。"""
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 "
|
||||
"python yingdao/share/hr_login.py")
|
||||
|
||||
|
||||
# ==================== HR 接口(内联,与 app 版 hr_api 一致) ====================
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;失效抛 HRSessionExpiredError。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
"""用共享 hr_cookies.json 构建 requests.Session(过滤 hr.37du.co 域)。"""
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
"""调用 getCurUserInfo,返回 userId / rootId(treecode)。"""
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def _relogin_get_user_info():
|
||||
"""登录态失效后:补登 → 重建会话 → 重新获取 userId/rootId。"""
|
||||
_ensure_hr_cookies()
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
return session, info.get("userId", ""), info.get("rootId", "")
|
||||
|
||||
|
||||
def fetch_attendance_abnormal_page(session, user_id, treecode, begin_date, end_date,
|
||||
page_no=1, page_size=PAGE_MAX_SIZE, is_adjusted=""):
|
||||
"""请求单页考勤异常数据。"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"sqlId": "kq_count_abnormal_Select",
|
||||
"redapiId": "rf_p_kq_count_abnormal_Select",
|
||||
"treeCodeList": "",
|
||||
"abnormal_type": "",
|
||||
"base_code": "",
|
||||
"join_date": "",
|
||||
"join_date_end": end_date,
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"period_order": "",
|
||||
"identity_test": "",
|
||||
"identity": "",
|
||||
"sex": "",
|
||||
"age": "",
|
||||
"age_end": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"operator_username": "",
|
||||
"operator_userid": "",
|
||||
"is_adjusted": is_adjusted,
|
||||
"begin_date": begin_date,
|
||||
"end_date": end_date,
|
||||
"STAFF_NAME": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "work_day",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", KQ_LIST_URL, params, "考勤异常")
|
||||
|
||||
|
||||
def fetch_all_attendance_abnormal(session, user_id, treecode, begin_date, end_date,
|
||||
is_adjusted=""):
|
||||
"""分页拉取全部考勤异常;中途登录态失效自动补登后续抓。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date,
|
||||
page_no, PAGE_MAX_SIZE, is_adjusted)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤异常 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, treecode = _relogin_get_user_info()
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date,
|
||||
page_no, PAGE_MAX_SIZE, is_adjusted)
|
||||
if data.get("state") != "1":
|
||||
logger.error("考勤异常第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤异常无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("考勤异常已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_leave_page(session, user_id, base_code, start_time, end_time,
|
||||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页请假记录数据。"""
|
||||
params = {
|
||||
"STRU_TREE_CODE": treecode,
|
||||
"user_id": user_id,
|
||||
"begin_date": "",
|
||||
"end_date": "",
|
||||
"sqlId": "select_kqLeave_record",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"post_no": "",
|
||||
"source": "",
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"staffNames": "",
|
||||
"post_type": "1",
|
||||
"processing_reason": "",
|
||||
"processing_date": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"orgAlias": "",
|
||||
"dept_ids": "",
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "operat_time",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", KQ_LIST_URL, params, "请假查询")
|
||||
|
||||
|
||||
def fetch_all_leave(session, user_id, base_code, start_time, end_time, treecode="cq37du"):
|
||||
"""分页抓取指定工号、日期范围内的全部请假记录(空工号=全量)。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_leave_page(session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("请假查询 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, _ = _relogin_get_user_info()
|
||||
data = fetch_leave_page(session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("请假查询第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("请假查询无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("请假查询已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_overtime_page(session, user_id, base_code, start_time, end_time,
|
||||
work_overtime_type="", treecode="cq37du",
|
||||
page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页加班记录数据。"""
|
||||
params = {
|
||||
"STRU_TREE_CODE": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_overtime_detail_select",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"BPM_STATUS": "",
|
||||
"post_no": "",
|
||||
"postName": "",
|
||||
"source": "",
|
||||
"IS_SUBSIDY": "",
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"staffNames": "",
|
||||
"post_type": "1",
|
||||
"processing_reason": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"WORK_OVERTIME_TYPE": work_overtime_type,
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "OPERATE_TIME",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", KQ_LIST_URL, params, "加班查询")
|
||||
|
||||
|
||||
def fetch_all_overtime(session, user_id, base_code, start_time, end_time,
|
||||
work_overtime_type="", treecode="cq37du"):
|
||||
"""分页抓取指定工号、日期范围内的全部加班记录(空工号=全量)。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_overtime_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
work_overtime_type, treecode, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("加班查询 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, _ = _relogin_get_user_info()
|
||||
data = fetch_overtime_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
work_overtime_type, treecode, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("加班查询第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("加班查询无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("加班查询已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_kq_data_page(session, user_id, base_code, start_time, end_time,
|
||||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页打卡记录数据。"""
|
||||
params = {
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_data_query",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"kqStaffIds": "",
|
||||
"staff_id": "",
|
||||
"staff_name": "",
|
||||
"orgAlias": "",
|
||||
"dept_ids": "",
|
||||
"kq_type": "",
|
||||
"post_type": "",
|
||||
"person_status": "",
|
||||
"dkstatus": "",
|
||||
"addr_status": " ",
|
||||
"struTreeCode": treecode,
|
||||
"belongUnitStruId": "",
|
||||
"work_day_begin": start_time,
|
||||
"work_day_end": end_time,
|
||||
"base_code": base_code,
|
||||
"STAFF_NAME": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", KQ_LIST_URL, params, "打卡查询")
|
||||
|
||||
|
||||
def fetch_all_kq_data(session, user_id, base_code, start_time, end_time, treecode="cq37du"):
|
||||
"""分页抓取指定工号、日期范围内的全部打卡记录。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_kq_data_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("打卡查询 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, _ = _relogin_get_user_info()
|
||||
data = fetch_kq_data_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("打卡查询第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("打卡查询无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("打卡查询已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_shift_page(session, user_id, base_code, begin_date, end_date,
|
||||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页排班数据。"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_count_SelectBanci",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"staff_ids": "",
|
||||
"person_status": "1,4",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"post_level": "",
|
||||
"identity": "",
|
||||
"showType": "1",
|
||||
"dateType": "1",
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"bc_date": begin_date,
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SHIFT_URL, params, "排班")
|
||||
|
||||
|
||||
def fetch_all_shift(session, user_id, base_code, begin_date, end_date, treecode="cq37du"):
|
||||
"""分页抓取指定工号、日期范围内的全部排班数据。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_shift_page(
|
||||
session, user_id, base_code, begin_date, end_date,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("排班 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, _ = _relogin_get_user_info()
|
||||
data = fetch_shift_page(
|
||||
session, user_id, base_code, begin_date, end_date,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("排班第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("排班无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("排班已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 工具函数(与 app 版 abnormal_check 一致) ====================
|
||||
def last_month_range(today=None):
|
||||
"""返回上月完整月份的查询日期范围 (开始日期, 结束日期)。"""
|
||||
today = today or date.today()
|
||||
end = today.replace(day=1) - timedelta(days=1) # 上月最后一天
|
||||
begin = end.replace(day=1) # 上月1日
|
||||
return begin.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _get(rec, *keys, default=""):
|
||||
"""从记录中取第一个存在的键的值(兼容字段大小写差异)。"""
|
||||
for k in keys:
|
||||
if rec.get(k) is not None and rec.get(k) != "":
|
||||
return rec[k]
|
||||
return default
|
||||
|
||||
|
||||
def _to_date_str(value):
|
||||
"""将接口返回的日期/时间值归一化为 'YYYY-MM-DD'(取前10位)。"""
|
||||
if value is None:
|
||||
return ""
|
||||
s = str(value).strip()
|
||||
return s[:10] if len(s) >= 10 else s
|
||||
|
||||
|
||||
def _float(value, default=0.0):
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _is_half_day_ot(rec):
|
||||
"""判断加班记录是否为休息日半天(0.5 天)。依次取 ot_days / sys_ot_days / plan_ot_days。"""
|
||||
for key in ("ot_days", "sys_ot_days", "plan_ot_days"):
|
||||
val = rec.get(key)
|
||||
if val is not None and val != "":
|
||||
if abs(_float(val) - HALF_DAY) <= EPS:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _leave_type_name(rec):
|
||||
"""从请假记录中提取假期类型名称(兼容编码与名称两种输入)。"""
|
||||
raw = _get(rec, "leave_type", "vacation_type", "sub_type", "LEAVE_TYPE")
|
||||
raw = str(raw).strip()
|
||||
if raw in VACATION_TYPE_MAP:
|
||||
return VACATION_TYPE_MAP[raw]
|
||||
return raw
|
||||
|
||||
|
||||
def _staff_name(rec):
|
||||
"""兼容取员工姓名字段(不同接口命名不同)。"""
|
||||
return str(_get(rec, "STAFF_NAME", "staff_name", "staffName", default=""))
|
||||
|
||||
|
||||
def _punch_analysis(records):
|
||||
"""对某日打卡流水做统计(打卡记录无法可靠区分上下班,按最早=上班、最晚=下班)。"""
|
||||
times = []
|
||||
for rec in records:
|
||||
t = _get(rec, "kq_time", "kqTime", "punch_time")
|
||||
if t:
|
||||
times.append(str(t))
|
||||
times.sort()
|
||||
if not times:
|
||||
return {"count": 0, "first": "", "last": ""}
|
||||
return {"count": len(times), "first": times[0], "last": times[-1]}
|
||||
|
||||
|
||||
def _to_minutes(value):
|
||||
"""将 "HH:MM[:SS]" 时间串转为当日分钟数;解析失败返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
s = str(value).strip()
|
||||
if not s:
|
||||
return None
|
||||
m = re.search(r"(\d{1,2}):(\d{2})(?::(\d{2}))?$", s)
|
||||
if not m:
|
||||
return None
|
||||
return int(m.group(1)) * 60 + int(m.group(2))
|
||||
|
||||
|
||||
def _time_hhmm(value):
|
||||
"""取日期时间串中的 "HH:MM";无时间部分返回空串。"""
|
||||
if value is None:
|
||||
return ""
|
||||
m = re.search(r"(\d{1,2}):(\d{2})", str(value))
|
||||
return "%02d:%s" % (int(m.group(1)), m.group(2)) if m else ""
|
||||
|
||||
|
||||
def _shift_segment(rec):
|
||||
"""合成异常记录的班段 "HH:MM ~ HH:MM"(begin_time ~ end_time,区分同一日多班段异常)。"""
|
||||
b = _time_hhmm(_get(rec, "begin_time"))
|
||||
e = _time_hhmm(_get(rec, "end_time"))
|
||||
return "%s ~ %s" % (b, e) if b or e else ""
|
||||
|
||||
|
||||
def _parse_shift_time(bc_time):
|
||||
"""解析班段时间 "09:00 ~ 18:00" -> (开始分钟, 结束分钟);无班段返回 (None, None)。"""
|
||||
if not bc_time:
|
||||
return None, None
|
||||
m = re.search(r"(\d{1,2}):(\d{2})\s*~\s*(\d{1,2}):(\d{2})", str(bc_time))
|
||||
if not m:
|
||||
return None, None
|
||||
start = int(m.group(1)) * 60 + int(m.group(2))
|
||||
end = int(m.group(3)) * 60 + int(m.group(4))
|
||||
return start, end
|
||||
|
||||
|
||||
def _extract_day_shift(shift_rows, date_str):
|
||||
"""从某员工排班记录中提取指定日期的班段信息。
|
||||
|
||||
排班接口 datas 为动态列(key 为 "YYYY-MM-DD_bc_name/bc_time/..."):
|
||||
bc_name 为班次名(休息日为「休息」,是休息与否的可靠判定依据);
|
||||
bc_time 为空串表示休息日。
|
||||
注意:paiban_type 不可靠(休息也可能为 -2 / 0),不可用来判定休息。
|
||||
"""
|
||||
info = {"bc_name": "", "bc_time": ""}
|
||||
for rec in shift_rows:
|
||||
name = _get(rec, f"{date_str}_bc_name", default="")
|
||||
time_ = _get(rec, f"{date_str}_bc_time", default="")
|
||||
if name or time_:
|
||||
info = {"bc_name": str(name), "bc_time": str(time_)}
|
||||
break
|
||||
return info
|
||||
|
||||
|
||||
def _judge_punch_by_shift(p, shift_info):
|
||||
"""结合班段时间判断当日打卡是否正常(容差 PUNCH_TOLERANCE_MIN 分钟)。"""
|
||||
start_min, end_min = _parse_shift_time(shift_info.get("bc_time", ""))
|
||||
count = p["count"]
|
||||
tol = PUNCH_TOLERANCE_MIN
|
||||
|
||||
# 无班段(休息日排班):按打卡次数判断
|
||||
if start_min is None or end_min is None:
|
||||
if count >= 2:
|
||||
return "正常(有上班+下班打卡)"
|
||||
if count == 1:
|
||||
return "漏打卡(当日仅 1 次打卡,缺一次)"
|
||||
return "漏打卡(当日无打卡记录)"
|
||||
|
||||
# 有班段:最早打卡覆盖班段开始、最晚打卡覆盖班段结束
|
||||
first_min = _to_minutes(p["first"])
|
||||
last_min = _to_minutes(p["last"])
|
||||
first_ok = first_min is not None and first_min <= start_min + tol
|
||||
last_ok = last_min is not None and last_min >= end_min - tol
|
||||
if count >= 2 and first_ok and last_ok:
|
||||
return "正常(按班段上班/下班打卡齐全)"
|
||||
if count == 0:
|
||||
return "漏打卡(当日无打卡记录)"
|
||||
if count == 1:
|
||||
return "漏打卡(当日仅 1 次打卡,缺一次)"
|
||||
return "漏打卡(打卡未按班段覆盖上下班)"
|
||||
|
||||
|
||||
# ==================== 会话校验 & 数据获取(与 app 版一致) ====================
|
||||
def _validate_session(session):
|
||||
"""调用 getCurUserInfo 校验 cookies 有效性,并返回 (session, user_id, treecode)。"""
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("cookies 已失效,正在重新登录")
|
||||
session, user_id, treecode = _relogin_get_user_info()
|
||||
return session, user_id, treecode
|
||||
user_id = info.get("userId", "")
|
||||
treecode = info.get("rootId", "")
|
||||
if not user_id or not treecode:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId/rootId:{info}")
|
||||
logger.info("cookies 校验通过,user_id=%s,treecode=%s", user_id, treecode)
|
||||
return session, user_id, treecode
|
||||
|
||||
|
||||
def _fetch_all_data(session, user_id, treecode, begin, end):
|
||||
"""一次性拉取三项检查所需的基础数据(考勤异常 / 请假 / 休息日加班)。"""
|
||||
logger.info("===== 月考勤异常三查,日期范围:%s ~ %s =====", begin, end)
|
||||
|
||||
abnormal_confirmed = fetch_all_attendance_abnormal(
|
||||
session, user_id, treecode, begin, end, IS_ADJUSTED_CONFIRMED
|
||||
)
|
||||
abnormal_open = fetch_all_attendance_abnormal(
|
||||
session, user_id, treecode, begin, end, IS_ADJUSTED_OPEN
|
||||
)
|
||||
logger.info("已确认异常 %d 条,未调整异常 %d 条", len(abnormal_confirmed), len(abnormal_open))
|
||||
|
||||
# 请假:空工号 = 查询全部员工(返回记录自带 base_code)
|
||||
leaves = fetch_all_leave(session, user_id, "", begin, end)
|
||||
logger.info("请假记录(全部员工)%d 条", len(leaves))
|
||||
|
||||
# 休息日加班:空工号 = 查询全部员工
|
||||
rest_overtime = fetch_all_overtime(
|
||||
session, user_id, "", begin, end, WORK_OVERTIME_TYPE_REST
|
||||
)
|
||||
logger.info("休息日加班记录(全部员工)%d 条", len(rest_overtime))
|
||||
|
||||
return {
|
||||
"abnormal_confirmed": abnormal_confirmed,
|
||||
"abnormal_open": abnormal_open,
|
||||
"leaves": leaves,
|
||||
"rest_overtime": rest_overtime,
|
||||
}
|
||||
|
||||
|
||||
def _build_leave_set(leaves, need_full_day=False):
|
||||
"""把请假记录索引化为 {(base_code, 'YYYY-MM-DD'): leave_rec}。
|
||||
|
||||
need_full_day=True 时只保留整日请假(leave_days>=1)的每一天;
|
||||
否则保留请假范围内的每一天(供检查1判断「日期是否有请假流程」)。
|
||||
"""
|
||||
index = {}
|
||||
for rec in leaves:
|
||||
code = str(_get(rec, "base_code")).strip()
|
||||
# 用 begin_date/end_date(考勤归属日期)而非 start_time/end_time:
|
||||
# 跨天夜班请假 end_time 会落到次日,导致请假范围多算一天
|
||||
start = _to_date_str(_get(rec, "begin_date", "start_time"))
|
||||
end = _to_date_str(_get(rec, "end_date", "end_time"))
|
||||
leave_days = _float(rec.get("leave_days"))
|
||||
if not code or not start or not end:
|
||||
continue
|
||||
if need_full_day and leave_days < 1:
|
||||
continue
|
||||
try:
|
||||
cur = datetime.strptime(start, "%Y-%m-%d").date()
|
||||
end_d = datetime.strptime(end, "%Y-%m-%d").date()
|
||||
except ValueError:
|
||||
continue
|
||||
if end_d < cur:
|
||||
continue
|
||||
step = timedelta(days=1)
|
||||
while cur <= end_d:
|
||||
index[(code, cur.strftime("%Y-%m-%d"))] = rec
|
||||
cur += step
|
||||
return index
|
||||
|
||||
|
||||
# ==================== 检查1:已确认异常 × 请假流程 ====================
|
||||
def check_leave_after_confirm(abnormal_confirmed, leave_index):
|
||||
"""已确认异常(is_adjusted=2)的日期,是否同时存在请假流程。"""
|
||||
rows = []
|
||||
for ab in abnormal_confirmed:
|
||||
code = str(_get(ab, "base_code")).strip()
|
||||
work_day = _to_date_str(_get(ab, "work_day"))
|
||||
if not code or not work_day:
|
||||
continue
|
||||
leave_rec = leave_index.get((code, work_day))
|
||||
if not leave_rec:
|
||||
continue
|
||||
rows.append({
|
||||
"员工姓名": _staff_name(ab),
|
||||
"工号": code,
|
||||
"考勤日期": work_day,
|
||||
"异常类型": _get(ab, "abnormal"),
|
||||
"请假类型": _leave_type_name(leave_rec),
|
||||
"请假起止": f"{_to_date_str(_get(leave_rec, 'begin_date', 'start_time'))} ~ "
|
||||
f"{_to_date_str(_get(leave_rec, 'end_date', 'end_time'))}",
|
||||
"问题说明": "该日期已确认考勤异常,但同时存在请假流程,可能为「提前确认后请假」仍为异常",
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查2:休息日半天加班 × 打卡校验(结合排班班段) ====================
|
||||
def check_rest_day_half_day_punch(session, user_id, treecode, rest_overtime, begin, end):
|
||||
"""休息日加班(类型3)且加班天数为 0.5 天时,校验当日打卡是否按考勤班段正常打卡。"""
|
||||
rows = []
|
||||
half_ots = [ot for ot in rest_overtime if _is_half_day_ot(ot)]
|
||||
logger.info("休息日半天加班 %d 条,逐一校验打卡(结合排班班段)", len(half_ots))
|
||||
|
||||
# 按工号缓存排班记录,避免重复请求
|
||||
shift_cache = {}
|
||||
|
||||
for ot in half_ots:
|
||||
code = str(_get(ot, "base_code")).strip()
|
||||
ot_date = _to_date_str(_get(ot, "OT_DATE", "ot_date"))
|
||||
if not code or not ot_date:
|
||||
continue
|
||||
kq = fetch_all_kq_data(session, user_id, code, ot_date, ot_date, treecode)
|
||||
|
||||
# 拉取该员工排班(缓存),取加班日的班段
|
||||
if code not in shift_cache:
|
||||
shift_cache[code] = fetch_all_shift(session, user_id, code, begin, end, treecode)
|
||||
shift_info = _extract_day_shift(shift_cache.get(code, []), ot_date)
|
||||
|
||||
p = _punch_analysis(kq)
|
||||
judge = _judge_punch_by_shift(p, shift_info)
|
||||
rows.append({
|
||||
"员工姓名": _staff_name(ot),
|
||||
"工号": code,
|
||||
"加班日期": ot_date,
|
||||
"加班天数": _get(ot, "ot_days", "sys_ot_days", "plan_ot_days", default="0.5"),
|
||||
"排班班次": shift_info["bc_name"],
|
||||
"排班班段时间": shift_info["bc_time"],
|
||||
"计划时段": f"{_get(ot, 'PLAN_START_TIME') or _get(ot, 'FINAL_START_TIME')} ~ "
|
||||
f"{_get(ot, 'PLAN_END_TIME') or _get(ot, 'FINAL_END_TIME')}",
|
||||
"上班打卡": p["first"],
|
||||
"下班打卡": p["last"],
|
||||
"打卡次数": p["count"],
|
||||
"判定": judge,
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查3:整日请假 × 考勤异常 → 提示 ====================
|
||||
def check_full_day_leave_abnormal(abnormal_confirmed, abnormal_open, leaves):
|
||||
"""员工整日请假(leave_days>=1)当日,仍存在其他考勤异常(未调整/已确认)→ 提示。"""
|
||||
rows = []
|
||||
|
||||
# 整日请假日期索引 {(code, date): leave_rec}
|
||||
full_day_leave = _build_leave_set(leaves, need_full_day=True)
|
||||
if not full_day_leave:
|
||||
logger.info("无整日请假记录,检查3跳过")
|
||||
return rows
|
||||
|
||||
# 异常并集(同一员工同一日期可能同时有未调整/已确认,各自输出一条便于核查)
|
||||
for ab in list(abnormal_open) + list(abnormal_confirmed):
|
||||
code = str(_get(ab, "base_code")).strip()
|
||||
work_day = _to_date_str(_get(ab, "work_day"))
|
||||
if not code or not work_day:
|
||||
continue
|
||||
leave_rec = full_day_leave.get((code, work_day))
|
||||
if not leave_rec:
|
||||
continue
|
||||
is_adjusted = str(ab.get("is_adjusted", ""))
|
||||
status = "确认异常" if is_adjusted == "2" else ("未调整" if is_adjusted == "0" else "异常")
|
||||
hint = f"该员工{work_day}考勤状态存在异常"
|
||||
rows.append({
|
||||
"员工姓名": _staff_name(ab),
|
||||
"工号": code,
|
||||
"请假日期": work_day,
|
||||
"请假类型": _leave_type_name(leave_rec),
|
||||
"请假天数": _get(leave_rec, "leave_days"),
|
||||
"异常类型": _get(ab, "abnormal"),
|
||||
"班段": _shift_segment(ab),
|
||||
"异常状态": status,
|
||||
"提示": hint,
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 导出多 Sheet Excel 报告 ====================
|
||||
def export_report(results, save_dir, month_str):
|
||||
"""将三项检查结果导出为多 Sheet Excel 报告(无数据的 Sheet 也保留表头便于对照)。"""
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"月考勤异常三查_{month_str}_{ts}.xlsx"))
|
||||
|
||||
sheet_cfg = [
|
||||
("检查1_确认异常有请假", "check1", [
|
||||
"员工姓名", "工号", "考勤日期", "异常类型", "请假类型", "请假起止", "问题说明"]),
|
||||
("检查2_休息日半天打卡", "check2", [
|
||||
"员工姓名", "工号", "加班日期", "加班天数", "排班班次", "排班班段时间", "计划时段",
|
||||
"上班打卡", "下班打卡", "打卡次数", "判定"]),
|
||||
("检查3_整日请假有异常", "check3", [
|
||||
"员工姓名", "工号", "请假日期", "请假类型", "请假天数", "异常类型", "班段",
|
||||
"异常状态", "提示"]),
|
||||
]
|
||||
|
||||
c1 = results.get("check1", [])
|
||||
c2 = results.get("check2", [])
|
||||
c3 = results.get("check3", [])
|
||||
|
||||
# 汇总行
|
||||
summary = [
|
||||
{"检查项": "检查1:确认异常日期存在请假流程", "条数": len(c1)},
|
||||
{"检查项": "检查2:休息日半天加班打卡校验", "条数": len(c2)},
|
||||
{"检查项": "检查3:整日请假当日仍有考勤异常", "条数": len(c3)},
|
||||
]
|
||||
summary[1]["备注"] = "「判定」列中 漏打卡 需人工复核"
|
||||
summary[0]["备注"] = "可能为「提前确认后请假」仍为异常"
|
||||
|
||||
try:
|
||||
with pd.ExcelWriter(save_path, engine="openpyxl") as writer:
|
||||
pd.DataFrame(summary).to_excel(writer, sheet_name="汇总", index=False)
|
||||
for sheet_name, key, cols in sheet_cfg:
|
||||
data = results.get(key, [])
|
||||
df = pd.DataFrame(data, columns=cols)
|
||||
df.to_excel(writer, sheet_name=sheet_name, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
|
||||
)
|
||||
logger.info("月考勤异常三查完成:检查1=%d 条,检查2=%d 条,检查3=%d 条",
|
||||
len(c1), len(c2), len(c3))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def handle_abnormal_check(save_dir=None):
|
||||
"""执行上月考勤异常三项检查并导出 Excel 报告,返回导出文件路径。
|
||||
|
||||
Args:
|
||||
save_dir: 保存目录,默认 SAVE_DIR
|
||||
"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
session = build_hr_session()
|
||||
session, user_id, treecode = _validate_session(session)
|
||||
|
||||
begin, end = last_month_range()
|
||||
month_str = end[:7] # "YYYY-MM"
|
||||
|
||||
data = _fetch_all_data(session, user_id, treecode, begin, end)
|
||||
|
||||
# 请假索引(全部请假,供检查1判断日期是否有请假流程)
|
||||
leave_index = _build_leave_set(data["leaves"], need_full_day=False)
|
||||
|
||||
# 检查1
|
||||
c1 = check_leave_after_confirm(data["abnormal_confirmed"], leave_index)
|
||||
logger.info("检查1(确认异常有请假):命中 %d 条", len(c1))
|
||||
for r in c1:
|
||||
logger.warning("【检查1】%s %s 考勤日期 %s,异常:%s,请假:%s",
|
||||
r["员工姓名"], r["工号"], r["考勤日期"], r["异常类型"], r["请假类型"])
|
||||
|
||||
# 检查2
|
||||
c2 = check_rest_day_half_day_punch(session, user_id, treecode,
|
||||
data["rest_overtime"], begin, end)
|
||||
logger.info("检查2(休息日半天打卡):校验 %d 条", len(c2))
|
||||
for r in c2:
|
||||
if "漏打卡" in r["判定"]:
|
||||
logger.warning("【检查2】%s %s %s 加班半天,%s",
|
||||
r["员工姓名"], r["工号"], r["加班日期"], r["判定"])
|
||||
|
||||
# 检查3
|
||||
c3 = check_full_day_leave_abnormal(
|
||||
data["abnormal_confirmed"], data["abnormal_open"], data["leaves"])
|
||||
logger.info("检查3(整日请假有异常):命中 %d 条", len(c3))
|
||||
for r in c3:
|
||||
logger.warning("【检查3】%s %s %s:%s(异常:%s / %s)",
|
||||
r["员工姓名"], r["工号"], r["请假日期"], r["提示"],
|
||||
r["异常类型"], r["异常状态"])
|
||||
|
||||
return export_report({"check1": c1, "check2": c2, "check3": c3}, save_dir, month_str)
|
||||
|
||||
|
||||
def main():
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行(固定查上月完整月份)。"""
|
||||
try:
|
||||
out = handle_abnormal_check()
|
||||
_set_glv('attendance_check_save_path', out)
|
||||
logger.info("===== 月考勤异常三查完成,导出:%s =====", out)
|
||||
return {"success": True, "save_path": out}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。")
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("月考勤异常三查失败:%s", e)
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,421 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: seal_data_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-07
|
||||
@UpdateTime: 2026-09-07
|
||||
@Description: 考勤月报封存检查 - 封存数据导出与预处理模块(影刀单文件,自包含)。
|
||||
统一负责:拉取当月全集团考勤封存数据 → 预处理筛选(所属单位仅保留白名单单位)→
|
||||
保存为预处理后的封存表(固定路径)。检查1/检查5 等各检查模块不再直连接口,
|
||||
一律通过本模块 load_seal_rows() 读取预处理封存表。
|
||||
|
||||
所属单位白名单(预处理口径,需调整时只改 SEAL_UNIT_WHITELIST 一处):
|
||||
财务管理部 / 集团管理中心 / 集团营建中心 / 金色印象事业部 / 金色湖畔事业部
|
||||
|
||||
数据来源(接口直取,对应 aa.md / aa.json):
|
||||
- 接口:POST https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc
|
||||
sqlId = kq_count_leave_wage_SelectV2,入参 yearmonth = YYYYMM,base_code 留空 = 全集团批量。
|
||||
- 每员工一条封存记录,所属单位字段 BELONG_UNIT_ORG_NAME(aa.md 列:所属单位)。
|
||||
|
||||
输出:
|
||||
考勤封存数据_{月份}.xlsx 预处理后的封存表(固定路径,覆盖式保存,仅含白名单单位员工,
|
||||
中文表头,供人工复核 & 各检查模块读取复用)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:需存在「37duHR登录」写入的共享登录态(hr_cookies.json)。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_seal_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
|
||||
class _PrintLogger:
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
_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_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
SEAL_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
SEAL_SQL_ID = "kq_count_leave_wage_SelectV2"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
SAVE_DIR = os.getenv("monthly_seal_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 所属单位白名单(预处理口径:封存表仅保留以下单位员工)
|
||||
SEAL_UNIT_FIELD = "BELONG_UNIT_ORG_NAME" # aa.md:所属单位
|
||||
SEAL_UNIT_WHITELIST: Tuple[str, ...] = (
|
||||
"财务管理部",
|
||||
"集团管理中心",
|
||||
"集团营建中心",
|
||||
"金色印象事业部",
|
||||
"金色湖畔事业部",
|
||||
)
|
||||
|
||||
# 封存记录工号字段
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
|
||||
# 中文导出列 → 接口字段(来源:aa.md 封存页列定义。保存封存数据时按此重命名表头,读取时反查还原)
|
||||
CN_FIELD_MAP: Dict[str, str] = {
|
||||
"姓名": "staff_name", "工号": "base_code", "岗位": "POST_ALIAS_NAME",
|
||||
"所属单位": "BELONG_UNIT_ORG_NAME", "一级部门": "DEPT_ORG_ONE",
|
||||
"二级部门": "DEPT_ORG_TWO", "三级部门": "DEPT_ORG_THREE",
|
||||
"四级部门": "DEPT_ORG_FOUR", "五级部门": "DEPT_ORG_FIVE", "部门全路径": "ORG_FULL_PATH",
|
||||
"封存月份": "yearmonth", "开始日期": "count_begin_date", "结束日期": "count_end_date",
|
||||
"实际出勤天日": "kq_stat_cal_ext19", "_在职应勤工作日": "kq_stat_month_yq_work_day_in",
|
||||
"休息天": "kq_stat_cal_ext9", "旷工天数": "kq_stat_cal_ext39", "漏打卡次数": "kq_stat_cal_ext8",
|
||||
"年假天": "kq_stat_leave_day_num1", "_病假天": "kq_stat_leave_day_num4",
|
||||
"_产假天": "kq_stat_leave_day_num5", "_事假天": "kq_stat_leave_day_num9",
|
||||
"_普通事假天": "kq_stat_leave_day_num16", "_特殊事假天": "kq_stat_leave_day_num17",
|
||||
"_小时特假小时": "kq_stat_leave_hour_num18", "_普通事假(晚/高峰)天": "kq_stat_leave_day_num19",
|
||||
"_普通事假(早/中)天": "kq_stat_leave_day_num20", "_特别福利假天": "kq_stat_leave_day_num23",
|
||||
"_年度福利假天": "kq_stat_leave_day_num24",
|
||||
"_工作日加班转补贴小时": "kq_stat_ps_bt_hour", "法定节假日加班转补贴天": "kq_stat_cal_ext69",
|
||||
"休息日加班转补贴天": "kq_stat_cal_ext44", "当月未休调休天": "kq_stat_cal_ext63",
|
||||
"迟到30分钟内次数": "kq_stat_cal_ext60", "迟到30到60分钟内次数": "kq_stat_cal_ext61",
|
||||
"迟到60到120分钟内次数": "kq_stat_cal_ext62",
|
||||
"早退30分钟内次数": "kq_stat_cal_ext51", "早退30到60分钟内次数": "kq_stat_cal_ext52",
|
||||
"早退60到120分钟内次数": "kq_stat_cal_ext53", "连班次数": "kq_stat_cal_ext40",
|
||||
"是否未休小时特假": "kq_stat_cal_ext42", "是否全勤": "kq_stat_cal_ext43",
|
||||
"离职时间": "leaveOffice_date", "入职日期": "join_date", "身份证": "idCard",
|
||||
"用工类型": "identity", "操作时间": "operate_time", "操作人": "operator_name",
|
||||
"考勤封存状态": "kq_data_state", "考勤封存操作人": "kq_data_operator_name",
|
||||
"员工状态": "staff_status", "在职状态": "person_status_name",
|
||||
}
|
||||
|
||||
|
||||
# ==================== HR 登录态(共享 cookies) ====================
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def _load_shared_hr_cookies():
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
return json.load(f) or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python yingdao/share/hr_login.py")
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def _relogin_get_user_id():
|
||||
"""登录态失效后:重建会话 → 重新获取 userId。"""
|
||||
_ensure_hr_cookies()
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
return session, _clean(info.get("userId"))
|
||||
|
||||
|
||||
# ==================== 考勤封存接口(aa.md:getPageAjaxList.mc + leave_wage_SelectV2) ====================
|
||||
def fetch_seal_page(session, user_id, yearmonth, page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页考勤封存数据。
|
||||
|
||||
base_code / staff_name 留空 = 不过滤,按组织树全集团批量返回当月封存记录。
|
||||
"""
|
||||
params = {
|
||||
"tree_code": "cq37du",
|
||||
"user_id": user_id,
|
||||
"sqlId": SEAL_SQL_ID,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"dept_org_name": "",
|
||||
"confirm_state": "",
|
||||
"person_status": "",
|
||||
"identity": "",
|
||||
"staff_status": "",
|
||||
"orgAlias": "",
|
||||
"dept_ids": "",
|
||||
"post_type": "1",
|
||||
"custom_dept_ids": "",
|
||||
"custom_dept_names": "",
|
||||
"STAFF_ID": "",
|
||||
"sealOrgAlias": "",
|
||||
"seal_dept_stru_id": "",
|
||||
"kqDataOperatorName": "",
|
||||
"kqDataOperatorId": "",
|
||||
"base_code": "",
|
||||
"staff_name": "",
|
||||
"yearmonth": yearmonth,
|
||||
"kq_data_state": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SEAL_URL, params, "考勤封存")
|
||||
|
||||
|
||||
def fetch_all_seal(session, user_id, yearmonth: str) -> List[dict]:
|
||||
"""分页抓取某月全集团完整封存数据(pageSize=500 分页拉取)。"""
|
||||
all_rows: List[dict] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_seal_page(session, user_id, yearmonth, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤封存登录态过期,自动补登录后续抓")
|
||||
session, user_id = _relogin_get_user_id()
|
||||
data = fetch_seal_page(session, user_id, yearmonth, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("考勤封存第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤封存无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("考勤封存已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
if v is None:
|
||||
return ""
|
||||
try:
|
||||
if pd.isna(v):
|
||||
return ""
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _normalize_month(month) -> str:
|
||||
"""月份归一化:None → 上月;YYYYMM → YYYY-MM;其余原样。"""
|
||||
if not month:
|
||||
py, pm = _prev_month(date.today().year, date.today().month)
|
||||
return f"{py:04d}-{pm:02d}"
|
||||
s = str(month).strip()
|
||||
if len(s) == 6 and s.isdigit():
|
||||
return f"{s[:4]}-{s[4:]}"
|
||||
return s
|
||||
|
||||
|
||||
def _seal_path(ym: str) -> str:
|
||||
"""预处理封存表固定路径(按月覆盖式保存,供检查模块稳定读取)。"""
|
||||
return os.path.join(SAVE_DIR, f"考勤封存数据_{ym}.xlsx")
|
||||
|
||||
|
||||
def _rename_columns_cn(frame: "pd.DataFrame", cn_map: Dict[str, str]) -> "pd.DataFrame":
|
||||
"""把封存数据列名按 中文导出列→接口字段 映射替换为中文表头。
|
||||
|
||||
仅重命名 cn_map 中存在的列,未映射的列(如各类 kq_stat_* 扩展字段)保留原英文名,
|
||||
列顺序不变,保证保存的封存数据信息不丢失。
|
||||
"""
|
||||
rename = {en: cn for cn, en in cn_map.items() if en in frame.columns}
|
||||
return frame.rename(columns=rename)
|
||||
|
||||
|
||||
# ==================== 预处理:所属单位白名单筛选 ====================
|
||||
def _filter_by_unit(rows: List[dict]) -> List[dict]:
|
||||
"""封存数据预处理:仅保留所属单位在白名单内的记录。"""
|
||||
return [rec for rec in rows if _clean(rec.get(SEAL_UNIT_FIELD)) in SEAL_UNIT_WHITELIST]
|
||||
|
||||
|
||||
# ==================== 导出 / 读取 ====================
|
||||
def export_seal_data(month: str = None) -> List[dict]:
|
||||
"""拉取当月全集团考勤封存数据 → 所属单位白名单预处理 → 保存固定路径封存表。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(接口原始字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
yearmonth = ym.replace("-", "")
|
||||
logger.info("===== 封存数据导出与预处理,月份:%s =====", ym)
|
||||
|
||||
# 1. 拉取当月全集团封存数据(base_code 留空批量)
|
||||
session = build_hr_session()
|
||||
user_id = _clean(fetch_cur_user_info(session).get("userId"))
|
||||
if not user_id:
|
||||
raise RuntimeError("获取当前用户 userId 失败")
|
||||
seal_rows = fetch_all_seal(session, user_id, yearmonth)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」未拉到考勤封存数据,请确认该月已封存。")
|
||||
logger.info("全集团封存记录共 %d 人:%s", len(seal_rows), ym)
|
||||
|
||||
# 2. 预处理:所属单位白名单筛选
|
||||
filtered = _filter_by_unit(seal_rows)
|
||||
logger.info("封存数据预处理:全集团 %d 人 → 白名单单位 %d 人", len(seal_rows), len(filtered))
|
||||
|
||||
# 3. 保存预处理封存表(固定路径,覆盖式)
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
path = _seal_path(ym)
|
||||
try:
|
||||
_rename_columns_cn(pd.DataFrame(filtered), CN_FIELD_MAP).to_excel(path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(path)}」后重试")
|
||||
logger.info("预处理封存表已保存:%s(%d 行)", path, len(filtered))
|
||||
return filtered
|
||||
|
||||
|
||||
def load_seal_rows(month: str = None) -> List[dict]:
|
||||
"""读取预处理封存表(固定路径),返回接口原始字段名的记录行列表,供各检查模块使用。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(中文表头已反查还原为接口字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
path = _seal_path(ym)
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到预处理封存表:{path}\n"
|
||||
"请先运行「seal_data_export.py」导出并预处理当月封存数据(所属单位白名单筛选),"
|
||||
"再运行各检查模块。")
|
||||
df = pd.read_excel(path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
# CN_FIELD_MAP 为 中文导出列→接口字段,反查:中文表头 → 接口字段名
|
||||
reverse = {cn: en for cn, en in CN_FIELD_MAP.items()}
|
||||
df = df.rename(columns={c: reverse.get(c, c) for c in df.columns})
|
||||
rows: List[dict] = [dict(r) for r in df.to_dict(orient="records")]
|
||||
logger.info("已读取预处理封存表:%s(%d 行)", path, len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
month = args.get("month") or os.getenv("monthly_seal_month") or (sys_argv_if(2))
|
||||
try:
|
||||
rows = export_seal_data(month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【封存数据导出与预处理完成】")
|
||||
logger.info(" 月份:%s | 白名单单位封存人数:%d", _normalize_month(month), len(rows))
|
||||
logger.info(" 输出目录:%s", SAVE_DIR)
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": len(rows)}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("封存数据导出失败:%s\n%s", e, traceback.format_exc())
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,314 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: unsealed_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-31
|
||||
@UpdateTime: 2026-09-07
|
||||
@Description: 考勤月报封存检查 - 检查5「未封存名单」(影刀单文件,自包含)。
|
||||
当月考勤封存完毕后执行,检查范围为「上月完整月份」。识别当月有在职记录的员工是否都有
|
||||
考勤月报封存记录;有在职记录但无封存记录者输出异常名单,异常类型 = 「考勤月报未封存,请处理」。
|
||||
|
||||
数据来源:
|
||||
1) 在职记录(花名册):由「37du花名册导出」共享指令导出到固定路径,本脚本只读取。
|
||||
导出参数:在职状态 = 在职 + 离职(离职需设置离职时间范围 = 检查月月初 至今天),
|
||||
模板 = 员工基础信息。这样才能把「检查月内仍在职 / 检查月内离职」的人全部覆盖到。
|
||||
口径与封存表保持一致:仅检查所属单位白名单单位员工
|
||||
(财务管理部/集团管理中心/集团营建中心/金色印象事业部/金色湖畔事业部)。
|
||||
2) 考勤月报封存记录:由 seal_data_export.py 导出并预处理(所属单位白名单筛选),
|
||||
保存为固定路径 考勤封存数据_{月份}.xlsx,本模块只读取该预处理封存表,不再直连接口。
|
||||
|
||||
判定口径(对应需求文档 XQ0011 检查5):
|
||||
- 花名册逐人取 入职时间 / 离职时间,判定其「在检查月是否在职」:
|
||||
在职 =(入职时间 ≤ 月末)且(无离职时间 或 离职时间 ≥ 月初)。
|
||||
- 仅统计所属单位在白名单内的员工;
|
||||
- 有在职记录但工号不在当月封存记录集合里 → 异常。
|
||||
|
||||
输出:
|
||||
未封存名单_{月份}_{时间戳}.xlsx 异常名单(含 37工号/姓名/月报检查月份/异常类型/所属单位/一~五级部门)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
2. 需先运行「37du花名册导出」指令导出花名册到固定路径。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_unsealed_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
monthly_unsealed_roster_path 花名册文件路径(默认 D:\\资料\\人资\\考勤异常\\员工花名册.xlsx)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import List, Optional, Set, Tuple
|
||||
|
||||
# 同目录模块引入(seal_data_export.py:封存数据导出与预处理,本模块只读取预处理封存表)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from seal_data_export import SEAL_UNIT_WHITELIST, load_seal_rows # noqa: E402
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
|
||||
class _PrintLogger:
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
SAVE_DIR = os.getenv("monthly_unsealed_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
# 花名册固定路径:由「37du花名册导出」共享指令导出(在职 + 离职,离职时间范围 = 检查月月初至今)
|
||||
DEFAULT_ROSTER_PATH = os.getenv("monthly_unsealed_roster_path") or r"D:\资料\人资\考勤异常\员工花名册.xlsx"
|
||||
|
||||
# 异常类型(对应需求文档检查5)
|
||||
ABNORMAL_TYPE = "考勤月报未封存,请处理"
|
||||
|
||||
# 封存记录工号字段
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
|
||||
# 花名册字段(与「37du花名册导出」指令导出的列名一致)
|
||||
ROSTER_CODE_COL = "工号"
|
||||
ROSTER_NAME_COL = "姓名"
|
||||
ROSTER_UNIT_COL = "所属单位"
|
||||
ROSTER_DEPT_COLS = ["一级部门", "二级部门", "三级部门", "四级部门", "五级部门"]
|
||||
ROSTER_JOIN_COL = "入职时间"
|
||||
ROSTER_LEAVE_COL = "离职时间"
|
||||
|
||||
# 输出列(对应需求文档检查5输出字段)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
if v is None:
|
||||
return ""
|
||||
try:
|
||||
if pd.isna(v):
|
||||
return ""
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
s = _clean(v)[:10]
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _month_range(ym: str) -> Tuple[date, date]:
|
||||
y, m = int(ym[:4]), int(ym[5:7])
|
||||
total_days = pd.Timestamp(year=y, month=m, day=1).daysinmonth
|
||||
return date(y, m, 1), date(y, m, total_days)
|
||||
|
||||
|
||||
def _seal_code_set(rows: List[dict]) -> Set[str]:
|
||||
"""取当月封存记录的全部工号集合。"""
|
||||
codes: Set[str] = set()
|
||||
for rec in rows:
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
code = _clean(rec.get(f))
|
||||
if code:
|
||||
codes.add(code)
|
||||
break
|
||||
return codes
|
||||
|
||||
|
||||
# ==================== 花名册在职判定 ====================
|
||||
def _load_roster(roster_path: str) -> "pd.DataFrame":
|
||||
"""读取花名册(由「37du花名册导出」指令导出,表头在第 1 行)。"""
|
||||
roster_path = roster_path or DEFAULT_ROSTER_PATH
|
||||
if not os.path.exists(roster_path):
|
||||
raise RuntimeError(
|
||||
f"未找到花名册文件:{roster_path}\n"
|
||||
"请先在影刀流程中拖入「37du花名册导出」指令导出花名册"
|
||||
f"(在职状态=在职+离职,离职时间范围=检查月月初至今,模板=员工基础信息),再运行本流程;"
|
||||
"或通过 roster_path 参数指定已有花名册文件。")
|
||||
df = pd.read_excel(roster_path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
logger.info("已读取花名册:%s,共 %d 行", roster_path, len(df))
|
||||
return df
|
||||
|
||||
|
||||
def _in_month(join: Optional[date], leave: Optional[date], first: date, last: date) -> bool:
|
||||
"""判断员工检查月是否在职:入职 ≤ 月末 且(未离职 或 离职 ≥ 月初)。"""
|
||||
if join is None or join > last:
|
||||
return False
|
||||
if leave is None or leave >= first:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def _build_unsealed_rows(df, seal_codes: Set[str], ym: str, first: date, last: date) -> List[dict]:
|
||||
"""遍历花名册,找出检查月在职、所属单位在白名单内但无封存记录的员工,返回名单行列表。"""
|
||||
abnormal: List[dict] = []
|
||||
seen: Set[str] = set()
|
||||
for _, row in df.iterrows():
|
||||
code = _clean(row.get(ROSTER_CODE_COL))
|
||||
if not code or code in seen:
|
||||
continue # 花名册在职/离职同一工号可能多行,取一行即可
|
||||
seen.add(code)
|
||||
unit = _clean(row.get(ROSTER_UNIT_COL))
|
||||
if unit not in SEAL_UNIT_WHITELIST:
|
||||
continue # 与封存表预处理口径一致:仅检查白名单单位员工
|
||||
join = _parse_date(row.get(ROSTER_JOIN_COL))
|
||||
leave = _parse_date(row.get(ROSTER_LEAVE_COL))
|
||||
if not _in_month(join, leave, first, last):
|
||||
continue # 检查月不在职(尚未入职或已离职早于月初)
|
||||
if code in seal_codes:
|
||||
continue # 已有封存记录,正常
|
||||
abnormal.append({
|
||||
"37工号": code,
|
||||
"姓名": _clean(row.get(ROSTER_NAME_COL)),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": ABNORMAL_TYPE,
|
||||
"所属单位": unit,
|
||||
**{f"第{chn}级部门": _clean(row.get(c)) for chn, c in zip(
|
||||
["一", "二", "三", "四", "五"], ROSTER_DEPT_COLS)},
|
||||
})
|
||||
return abnormal
|
||||
|
||||
|
||||
def run_unsealed_check(roster_path: str = None, month: str = None) -> List[dict]:
|
||||
"""执行检查5「未封存名单」,返回异常名单行列表(并写 Excel 留档)。
|
||||
|
||||
Args:
|
||||
roster_path: 花名册文件路径,默认 DEFAULT_ROSTER_PATH。
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
|
||||
Returns:
|
||||
异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。
|
||||
"""
|
||||
today = date.today()
|
||||
if month:
|
||||
try:
|
||||
first, last = _month_range(month)
|
||||
except (ValueError, IndexError, TypeError):
|
||||
raise ValueError(f"月份格式应为 YYYY-MM,收到:{month}")
|
||||
ym = month
|
||||
else:
|
||||
py, pm = _prev_month(today.year, today.month)
|
||||
first, last = _month_range(f"{py:04d}-{pm:02d}")
|
||||
ym = f"{py:04d}-{pm:02d}"
|
||||
logger.info("===== 检查5「未封存名单」月份:%s(%s ~ %s) =====", ym, first, last)
|
||||
|
||||
# 1. 读花名册(在职记录)
|
||||
df = _load_roster(roster_path)
|
||||
|
||||
# 2. 读取预处理封存表(seal_data_export.py 已按所属单位白名单筛选并保存)
|
||||
seal_rows = load_seal_rows(ym)
|
||||
seal_codes = _seal_code_set(seal_rows)
|
||||
logger.info("考勤封存记录共 %d 人:%s", len(seal_codes), ym)
|
||||
|
||||
# 3. 找出在册未封存
|
||||
abnormal = _build_unsealed_rows(df, seal_codes, ym, first, last)
|
||||
logger.info("检查5命中异常 %d 人(在册未封存)", len(abnormal))
|
||||
|
||||
# 4. 导出异常名单
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.join(SAVE_DIR, f"未封存名单_{ym}_{ts}.xlsx")
|
||||
try:
|
||||
pd.DataFrame(abnormal if abnormal else [],
|
||||
columns=OUTPUT_COLUMNS).to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试")
|
||||
logger.info("异常名单已保存:%s(共 %d 条)", save_path, len(abnormal))
|
||||
return abnormal
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:
|
||||
roster_path(花名册文件路径)、month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
roster_path = args.get("roster_path") or (
|
||||
os.getenv("monthly_unsealed_roster_path")
|
||||
or (sys_argv_if(2)))
|
||||
month = args.get("month") or os.getenv("monthly_unsealed_month") or (sys_argv_if(3))
|
||||
try:
|
||||
rows = run_unsealed_check(roster_path, month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【检查5 考勤月报未封存名单完成】")
|
||||
logger.info(" 检查月份:%s | 未封存人数:%d", month or "默认上月", len(rows))
|
||||
logger.info(" 输出目录:%s", SAVE_DIR)
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": len(rows)}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("检查5执行失败:%s\n%s", e, traceback.format_exc())
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
import sys
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,291 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: working_days_shift_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-31
|
||||
@UpdateTime: 2026-09-07
|
||||
@Description: 考勤月报封存检查 - 检查1「在职天数是否均排班验证」(影刀单文件,自包含)。
|
||||
当月考勤封存完毕后执行,检查范围为「上月完整月份」。
|
||||
|
||||
数据来源(预处理封存表,由 seal_data_export.py 导出并预处理):
|
||||
- 先运行 seal_data_export.py:拉取当月全集团考勤封存数据(接口
|
||||
POST https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc,
|
||||
sqlId = kq_count_leave_wage_SelectV2),并做预处理:所属单位仅保留白名单单位
|
||||
(财务管理部/集团管理中心/集团营建中心/金色印象事业部/金色湖畔事业部),
|
||||
保存为固定路径 考勤封存数据_{月份}.xlsx。
|
||||
- 本模块只读取该预处理封存表,不再直连接口。
|
||||
- 每员工一条封存记录,检查1用到的字段(aa.md 列定义):
|
||||
base_code 工号 / staff_name 姓名
|
||||
join_date 入职日期 / leaveOffice_date 离职时间(算在职天数)
|
||||
kq_stat_month_yq_work_day_in 在职应勤工作日
|
||||
kq_stat_cal_ext9 休息天(考勤日报休息日天数总和)
|
||||
BELONG_UNIT_ORG_NAME 所属单位 / DEPT_ORG_ONE~FIVE 一级~五级部门
|
||||
|
||||
判断口径(对应需求文档 XQ0011 检查1):
|
||||
- 在职天数:由封存「入职/离职时间」计算员工当月应在职的自然天数;
|
||||
- 在职应勤工作日 + 休息天:直接取封存字段 kq_stat_month_yq_work_day_in / kq_stat_cal_ext9;
|
||||
- 差值 = 在职天数 - (应勤工作日 + 休息天);差值非 0 视为异常,异常类型 = 「当月在职天数有差缺排班」。
|
||||
样例:37035483 8-3 离职,在职天数 3;应勤 3、休息 0 → 差值 0 正常。
|
||||
|
||||
在职天数口径(统一采用「月初1日~末日」与「入职日起~离职日止」闭区间交集的自然天数,含首尾)
|
||||
- 全月在职:月初1日即已在职且当月末在职 → 在职天数 = 当月自然天数;
|
||||
- 月初1日在职、当月内离职:在职天数 = 离职日 - 1号 + 1 → 覆盖需求「离职时间 - 1号」;
|
||||
- 月初1日尚未入职、月末在职:在职天数 = 末日 - 入职日 + 1 → 覆盖需求「末日 - 入职时间」;
|
||||
- 当月在册(月初未入职且月内离职):在职天数 = 离职日 - 入职日 + 1 → 覆盖需求「离职 - 入职」;
|
||||
- 月初1日与末日均在职但有入离职异动:在职天数 = 自然天数 - 异动缺勤段。
|
||||
(注:口径与封存样例一致,均含入职/离职当天。若贵司某类口径不含离职/入职当天,请调 _working_days。)
|
||||
|
||||
输出:
|
||||
在职天数排班异常_{月份}_{时间戳}.xlsx 异常名单(含在职天数/应勤/休息/差值便于排查)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
2. 需存在「37duHR登录」写入的共享登录态(hr_cookies.json,仅供导出模块使用)。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_wd_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# 同目录模块引入(seal_data_export.py:封存数据导出与预处理,本模块只读取预处理封存表)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from seal_data_export import load_seal_rows # noqa: E402
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\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)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
SAVE_DIR = os.getenv("monthly_wd_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 异常类型(对应需求文档检查1)
|
||||
ABNORMAL_TYPE = "当月在职天数有差缺排班"
|
||||
|
||||
# 封存记录的字段→角色映射(字段名以 aa.md 接口列定义为准)
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
SEAL_NAME_FIELD = "staff_name"
|
||||
SEAL_JOIN_FIELD = "join_date" # aa.md:入职日期
|
||||
SEAL_LEAVE_FIELD = "leaveOffice_date" # aa.md:离职时间
|
||||
SEAL_WORK_FIELD = "kq_stat_month_yq_work_day_in" # aa.md:_在职应勤工作日
|
||||
SEAL_REST_FIELD = "kq_stat_cal_ext9" # aa.md:休息天(考勤日报休息日天数总和)
|
||||
SEAL_UNIT_FIELD = "BELONG_UNIT_ORG_NAME" # aa.md:所属单位
|
||||
SEAL_DEPT_FIELDS = ["DEPT_ORG_ONE", "DEPT_ORG_TWO", "DEPT_ORG_THREE",
|
||||
"DEPT_ORG_FOUR", "DEPT_ORG_FIVE"] # 一~五级部门
|
||||
|
||||
# 输出列(对应需求文档检查1输出字段)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"在职天数", "应勤工作日", "休息天", "差值",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
if v is None:
|
||||
return ""
|
||||
if pd.isna(v):
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
return s
|
||||
|
||||
|
||||
def _text(v) -> str:
|
||||
t = _clean(v)
|
||||
if t.endswith(".0"):
|
||||
t = t[:-2]
|
||||
return t
|
||||
|
||||
|
||||
def _num(v) -> float:
|
||||
try:
|
||||
return float(_clean(v))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
s = _clean(v)
|
||||
if not s:
|
||||
return None
|
||||
s = s[:10]
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _month_range(ym: str) -> Tuple[date, date]:
|
||||
y, m = int(ym[:4]), int(ym[5:7])
|
||||
total_days = pd.Timestamp(year=y, month=m, day=1).daysinmonth
|
||||
return date(y, m, 1), date(y, m, total_days)
|
||||
|
||||
|
||||
def _working_days(first: date, last: date, join: Optional[date], leave: Optional[date]) -> int:
|
||||
"""计算员工当月在职自然天数(月区间 ∩ 在职区间闭区间,含首尾)。"""
|
||||
lo = first if not join else (join if join >= first else first)
|
||||
hi = last if not leave else (leave if leave <= last else last)
|
||||
if lo > hi:
|
||||
return 0
|
||||
return (hi - lo).days + 1
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def _build_seal_map(rows: List[dict]) -> Dict[str, dict]:
|
||||
"""按工号建立 封存记录索引(一员工一条)。"""
|
||||
mapping: Dict[str, dict] = {}
|
||||
for rec in rows:
|
||||
code = ""
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
code = _text(rec.get(f))
|
||||
if code:
|
||||
break
|
||||
if code:
|
||||
mapping.setdefault(code, rec)
|
||||
return mapping
|
||||
|
||||
|
||||
def run_working_days_shift_check(month: str = None) -> List[dict]:
|
||||
"""执行检查1「在职天数是否均排班验证」,返回异常名单行列表(并写 Excel 留档)。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
|
||||
Returns:
|
||||
异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。
|
||||
"""
|
||||
today = date.today()
|
||||
if month:
|
||||
try:
|
||||
first, last = _month_range(month)
|
||||
except (ValueError, IndexError, TypeError):
|
||||
raise ValueError(f"月份格式应为 YYYY-MM,收到:{month}")
|
||||
ym = month
|
||||
else:
|
||||
py, pm = _prev_month(today.year, today.month)
|
||||
first, last = _month_range(f"{py:04d}-{pm:02d}")
|
||||
ym = f"{py:04d}-{pm:02d}"
|
||||
logger.info("===== 检查1「在职天数是否均排班验证」月份:%s(%s ~ %s) =====", ym, first, last)
|
||||
|
||||
# 1. 读取预处理封存表(seal_data_export.py 已按所属单位白名单筛选并保存)
|
||||
seal_rows = load_seal_rows(ym)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」预处理封存表为空,请确认该月已封存并已运行导出模块。")
|
||||
seal_map = _build_seal_map(seal_rows)
|
||||
logger.info("考勤封存加载完成,共 %d 人:%s", len(seal_map), ym)
|
||||
|
||||
# 2. 逐人检查
|
||||
abnormal: List[dict] = []
|
||||
for code, rec in seal_map.items():
|
||||
join = _parse_date(rec.get(SEAL_JOIN_FIELD))
|
||||
leave = _parse_date(rec.get(SEAL_LEAVE_FIELD))
|
||||
wd = _working_days(first, last, join, leave)
|
||||
if wd <= 0:
|
||||
continue # 当月无在职日,跳过
|
||||
work = _num(rec.get(SEAL_WORK_FIELD))
|
||||
rest = _num(rec.get(SEAL_REST_FIELD))
|
||||
diff = wd - (work + rest)
|
||||
if diff != 0:
|
||||
abnormal.append({
|
||||
"37工号": code,
|
||||
"姓名": _text(rec.get(SEAL_NAME_FIELD)),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": ABNORMAL_TYPE,
|
||||
"在职天数": wd,
|
||||
"应勤工作日": int(work),
|
||||
"休息天": int(rest),
|
||||
"差值": diff,
|
||||
"所属单位": _text(rec.get(SEAL_UNIT_FIELD)),
|
||||
**{f"第{chn}级部门": _text(rec.get(f)) for chn, f in zip(
|
||||
["一", "二", "三", "四", "五"], SEAL_DEPT_FIELDS)},
|
||||
})
|
||||
logger.info("检查1命中异常 %d 人(在职天数≠应勤+休息)", len(abnormal))
|
||||
|
||||
# 3. 导出异常名单
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.join(SAVE_DIR, f"在职天数排班异常_{ym}_{ts}.xlsx")
|
||||
try:
|
||||
pd.DataFrame(abnormal if abnormal else [],
|
||||
columns=OUTPUT_COLUMNS).to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试")
|
||||
logger.info("异常名单已保存:%s(共 %d 条)", save_path, len(abnormal))
|
||||
return abnormal
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
month = args.get("month") or os.getenv("monthly_wd_month") or (sys_argv_if(2))
|
||||
try:
|
||||
rows = run_working_days_shift_check(month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【检查1 在职天数是否均排班验证完成】")
|
||||
logger.info(" 检查月份:%s | 异常人数:%d", month or "默认上月", len(rows))
|
||||
logger.info(" 输出目录:%s", SAVE_DIR)
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": len(rows)}
|
||||
except Exception as e:
|
||||
logger.error("检查1执行失败:%s", e)
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,9 @@
|
||||
# XQ0012 EHR预支及支付报酬自动发起ERP付款申请 — 影刀脚本占位
|
||||
|
||||
- 需求单文档:`docs/需求单/XQ0012 EHR预支及支付报酬自动发起ERP付款申请/`
|
||||
- 状态:**未实现(预留目录,供后续直接放代码)**
|
||||
|
||||
## 本目录应放置
|
||||
按影刀「单文件自包含」规范,将本需求单的影刀脚本直接放入本目录,例如:
|
||||
- `<业务名>.py`:主流程(单文件、可直接运行)
|
||||
- 如需拆步骤,可放多个单文件,文件间互不 `import`
|
||||
@@ -0,0 +1,10 @@
|
||||
# XQ0013 社保费用申报导出并汇总 — 影刀脚本占位
|
||||
|
||||
- 需求单文档:`docs/需求单/XQ0013 社保费用申报导出并汇总/`
|
||||
- 状态:**未实现(预留目录,供后续直接放代码)**
|
||||
|
||||
## 本目录应放置
|
||||
按影刀「单文件自包含」规范,将本需求单的影刀脚本直接放入本目录,例如:
|
||||
- `export_calc.py`:社保费用申报导出
|
||||
- `summary.py`:汇总结算
|
||||
- 如需拆步骤,可放多个单文件,文件间互不 `import`
|
||||
@@ -0,0 +1,12 @@
|
||||
# XQ0014 社保系统增减员办理 — 影刀脚本占位
|
||||
|
||||
- 需求单文档:`docs/需求单/XQ0014 社保系统增减员办理/`
|
||||
- 状态:**未实现(预留目录,供后续直接放代码)**
|
||||
|
||||
## 本目录应放置
|
||||
按影刀「单文件自包含」规范,将本需求单的影刀脚本直接放入本目录,例如:
|
||||
- `<业务名>.py`:主流程(单文件、可直接运行)
|
||||
- 如需拆步骤,可放多个单文件,文件间互不 `import`
|
||||
|
||||
## 参考
|
||||
- 增减员办理与 `XQ0002/add_sub_import.py`(HR「待增减人员」上传)逻辑相近,可复用其页面操作思路
|
||||
@@ -0,0 +1,934 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: notice_mail_merge.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-26
|
||||
@Description: 告知书制作与下发(影刀版,单文件自包含)——读取《{YYYYMM}参保与停保名单.xlsx》
|
||||
中「参保名单」sheet(表头第3行),按三类模板规则筛选当月人员,逐人生成
|
||||
Word 告知书并转 PDF:
|
||||
- 模板1 员工参与社会保险告知书(办理状态=已参 & 参保类型=新参保)
|
||||
- 模板2 参保异常告知书(办理状态=参保失败 & 参保类型=新参保)
|
||||
- 模板3 社保转移告知书(办理状态=已参 & 参保类型=转移参保)
|
||||
公共过滤:人员类型不含「职能」、二级部门包含「经营中心」或「石桥铺会馆」、办理时间为当月。
|
||||
输出命名:按(二级部门,四级部门)分组合并,同一部门+类型的所有员工合并为一份,
|
||||
文件名 = 二级部门_四级部门_告知书类型.docx/pdf,同一部门内多人逐页排列。
|
||||
OA 工作沟通推送:构造 2 条推送数据(员工参与社会保险+参保异常合并一条、
|
||||
社保转移单独一条),各类型输出目录下全部告知书 PDF 均作为附件推送(不筛选),
|
||||
接收人统一追加固定抄送人周卫;写入影刀全局变量 messages(列表),
|
||||
供「OA工作沟通推送」指令逐条调用。
|
||||
业务判定及占位符约定见 aa.md、docs/参保成功及异常告知书、docs/社保转移告知书。
|
||||
@Version: 1.2.0
|
||||
|
||||
设计说明(与 yingdao 下其它单文件版一致):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- 不 import 任何共享指令模块、不做 sys.path 注入、不做目录向上查找。
|
||||
- 占位符约定:模板中仅允许纯变量占位符(如 {{姓名}}、{{下月}}、{{一次性扣款}}),
|
||||
不支持 {{当前月+1}} / {{费用*2}} 这类带表达式的写法(脚本会自动兼容旧写法)。
|
||||
- PDF 转换走 WPS 文字 COM(Kwps.Application),兼容未安装 MS Word 的环境;
|
||||
另存/导出失败自动重试 3 次(AGENTS.md 全局重试约定)。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install openpyxl python-docx pywin32
|
||||
|
||||
环境变量(.env 文件或系统变量,可选):
|
||||
notice_base_dir = 告知书目录(默认 D:\\资料\\人资\\告知书制作与下发)
|
||||
notice_output_dir = 输出根目录(默认 {notice_base_dir}\\输出)
|
||||
|
||||
运行:直接执行本文件即可生成当月全部三类告知书;
|
||||
也可用函数传参调用 generate_notices(excel_path=..., output_dir=..., ym=(2026,8))
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import random
|
||||
import functools
|
||||
import traceback
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import openpyxl
|
||||
from docx import Document
|
||||
from docx.enum.text import WD_BREAK
|
||||
from docx.oxml.ns import qn
|
||||
import win32com.client
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install openpyxl python-docx pywin32\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)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 重试装饰器(全局重试3次,AGENTS.md) ====================
|
||||
class RetryExhaustedError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
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 RetryExhaustedError(
|
||||
f"{func.__name__} failed after {max_attempts} attempts, last error: {last_exc}"
|
||||
) from last_exc
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
|
||||
# ==================== 影刀全局变量(写入 glv[name]=value) ====================
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
BASE_DIR = os.getenv("notice_base_dir") or r"D:\资料\人资\告知书制作与下发"
|
||||
OUTPUT_ROOT = os.getenv("notice_output_dir") or os.path.join(BASE_DIR, "输出")
|
||||
|
||||
# 模板清单:folder=输出子目录名;status/type=该类告知书的办理状态与参保类型过滤条件
|
||||
TEMPLATES = {
|
||||
"新参保": {
|
||||
"file": os.path.join(BASE_DIR, "参保状态告知", "员工参与社会保险告知书模板.docx"),
|
||||
"folder": "员工参与社会保险告知书",
|
||||
"status": "已参",
|
||||
"type": "新参保",
|
||||
},
|
||||
"参保异常": {
|
||||
"file": os.path.join(BASE_DIR, "参保状态告知", "参保异常告知模板.docx"),
|
||||
"folder": "参保异常告知书",
|
||||
"status": "参保失败",
|
||||
"type": "新参保",
|
||||
},
|
||||
"社保转移": {
|
||||
"file": os.path.join(BASE_DIR, "社保转移告知书", "社保转移告知模板.docx"),
|
||||
"folder": "社保转移告知书",
|
||||
"status": "已参",
|
||||
"type": "转移参保",
|
||||
},
|
||||
}
|
||||
|
||||
EXCEL_KEYWORD = "参保与停保名单" # 表格文件名关键字
|
||||
SHEET_KEYWORD = "参保名单" # sheet 名关键字
|
||||
HEADER_ROW = 3 # 表头所在行
|
||||
MAIN_COLS = 49 # 主表字段到「费用」列为止(AX 为空列,其后为粘贴重复区)
|
||||
EXCLUDE_TYPE_KEYWORDS = ("职能",) # 人员类型排除关键字
|
||||
DEPT_KEYWORDS = ("经营中心", "石桥铺会馆") # 二级部门需包含的关键字(任一命中即可)
|
||||
RETRY_TIMES = 3 # 全局重试次数
|
||||
|
||||
# 社保转移数据源(社保变更人员名单):替代「参保与停保名单」中的转移参保
|
||||
TRANSFER_EXCEL_KEYWORD = "社保变更人员名单" # 数据源文件名关键字
|
||||
TRANSFER_SHEET_GENERATE = ("变更-职能及干部", "变更-门店") # 生成覆盖的 sheet(关键字)
|
||||
TRANSFER_SHEET_PUSH = "变更-门店" # 推送仅限该 sheet
|
||||
TRANSFER_CHANGE_COL = "是否变更" # 筛选列
|
||||
TRANSFER_CHANGE_VALUE = "是" # 筛选值
|
||||
# 列名映射:社保变更名单列名 -> 标准列名(模板占位符依赖标准列名)
|
||||
TRANSFER_COL_MAP = {"新区域": "区域", "个人费用": "费用"}
|
||||
|
||||
# ---- OA 工作沟通推送数据构造 ----
|
||||
ROSTER_PATH = r"D:\资料\人资\告知书制作与下发\员工花名册.xlsx" # 员工花名册路径
|
||||
DEPT2_HR_OVERRIDE = {"石桥铺会馆": ["37001302"]} # 二级部门 -> 固定人事工号(梁敏)
|
||||
OA_GLV_NAME = "messages" # 影刀全局变量名(列表:工作沟通推送数据)
|
||||
|
||||
# 测试模式:True=推送接收人统一覆盖为测试接收人(不推真实店长/人事);正式运行请改为 False
|
||||
TEST_MODE = True
|
||||
TEST_RECEIVER = ["37036361", "37001166"] # 测试接收人(多人):37036361 夏一平 + 37001166
|
||||
|
||||
# 固定抄送人:统一加入每条工作沟通推送的接收人(周卫)
|
||||
CC_RECEIVER_NAME = "周卫"
|
||||
CC_RECEIVER_ID = "37001166"
|
||||
|
||||
# 工作沟通推送配置:rule_keys=参与该条推送的模板名;subject/content 支持 {y}/{m} 动态月份替换
|
||||
OA_MESSAGE_TEMPLATES = (
|
||||
{
|
||||
"key": "参保类",
|
||||
"rule_keys": ("新参保", "参保异常"),
|
||||
"subject": "{y}年{m}月员工参保结果告知书",
|
||||
"content": (
|
||||
"各位店长、人行伙伴:\n"
|
||||
"重庆区域门店{m}月新参保已完成,以下是各门店《参保成功告知书》/《参保异常告知书》,\n"
|
||||
"现需涉及的门店对员工本人进行传达告知(下载并签收);其中参保异常人员,重庆户籍的可以在渝快办APP上查询办理停保,"
|
||||
"如办理不成功,也可打12333咨询社保机构,异地区域拨打区号+12333;若员工处理完毕,请店长报表至人资周卫,以便下月再参;\n"
|
||||
"请门店在{m}月26日前完成签署并将《签收回执》传递人行,"
|
||||
"人行跟进本经营中心所有人员的告知书回收,{m}月28日前传递人资周卫。\n"
|
||||
"@@R人力资源部\n"
|
||||
"@@R{push_date}"
|
||||
),
|
||||
"category": "工作安排",
|
||||
},
|
||||
{
|
||||
"key": "社保转移",
|
||||
"rule_keys": ("社保转移",),
|
||||
"subject": "{y}年{m}月员工参保单位变更确认",
|
||||
"content": (
|
||||
"各位领导/同事:\n"
|
||||
"根据《社保执行细则》,本月人力资源部已输出“工作与参保单位不一致”的人员,"
|
||||
"现需要涉及门店/经营中心与员工本人进行转移确认(下载变更告知书、打印并与员工清晰讲解),"
|
||||
"在{m}月25日下班前完成签署并将《社保缴纳确认单》传递分部人行,"
|
||||
"在{m}月27日内传递人资周卫处。\n"
|
||||
"特别注意:员工若有住院就医计划,须及时反馈可暂不转移,待处理完毕后办理。"
|
||||
"员工若属于暂调(后续会回到原门店),也须及时反馈可暂不转移。\n"
|
||||
"@@R人力资源部\n"
|
||||
"@@R{push_date}"
|
||||
),
|
||||
"category": "工作安排",
|
||||
},
|
||||
)
|
||||
|
||||
# 正文关键词高亮(红色):keyword 支持 {m} 月份占位符,format 后替换为 <span style="color:#c0392b">
|
||||
OA_HIGHLIGHTS = {
|
||||
"参保类": [
|
||||
("《参保成功告知书》", "#c0392b"),
|
||||
("《参保异常告知书》", "#c0392b"),
|
||||
("《签收回执》", "#c0392b"),
|
||||
("{m}月26日前", "#c0392b"),
|
||||
("{m}月28日前", "#c0392b"),
|
||||
],
|
||||
"社保转移": [
|
||||
("《社保缴纳确认单》", "#c0392b"),
|
||||
("{m}月25日下班前", "#c0392b"),
|
||||
("27日内", "#c0392b"),
|
||||
("特别注意:员工若有住院就医计划,须及时反馈可暂不转移,待处理完毕后办理。员工若属于暂调(后续会回到原门店),也须及时反馈可暂不转移。", "#c0392b"),
|
||||
],
|
||||
}
|
||||
|
||||
# 旧占位符 → 新占位符(模板兼容旧写法,自动归一化)
|
||||
LEGACY_PLACEHOLDERS = {
|
||||
"{{当前月15日}}": "{{当月15日}}",
|
||||
"{{重庆}}": "{{区域}}",
|
||||
"{{当前月+1}}": "{{下月}}",
|
||||
"{{费用*2}}": "{{一次性扣款}}",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 基础工具 ====================
|
||||
def _fmt_num(value) -> str:
|
||||
"""金额格式化:509 -> '509';467.42 -> '467.42';#N/A 等错误值返回 ''。"""
|
||||
if value is None:
|
||||
return ""
|
||||
s = str(value).strip()
|
||||
if s in ("", "#N/A", "#REF!", "#VALUE!", "NA", "None"):
|
||||
return ""
|
||||
try:
|
||||
f = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return s
|
||||
if f == int(f):
|
||||
return str(int(f))
|
||||
return ("%.2f" % f).rstrip("0").rstrip(".")
|
||||
|
||||
|
||||
def _month_of(value):
|
||||
"""把单元格值解析为 (年, 月);无法解析返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return (value.year, value.month)
|
||||
if isinstance(value, str):
|
||||
m = re.search(r"(20\d{2})[年\-/\.]?(\d{1,2})", value.strip())
|
||||
if m:
|
||||
return (int(m.group(1)), int(m.group(2)))
|
||||
return None
|
||||
|
||||
|
||||
def _extract_ym(filename: str):
|
||||
"""从文件名解析 YYYYMM;失败返回当月。"""
|
||||
m = re.search(r"(20\d{2})(\d{2})", filename)
|
||||
if m:
|
||||
return (int(m.group(1)), int(m.group(2)))
|
||||
now = datetime.now()
|
||||
return (now.year, now.month)
|
||||
|
||||
|
||||
def _find_excel(dir_path: str) -> str:
|
||||
"""在目录内查找包含「参保与停保名单」的 xlsx 文件。"""
|
||||
if not os.path.isdir(dir_path):
|
||||
raise FileNotFoundError(f"目录不存在:{dir_path}")
|
||||
for name in os.listdir(dir_path):
|
||||
if EXCEL_KEYWORD in name and name.lower().endswith(".xlsx") and not name.startswith("~$"):
|
||||
return os.path.join(dir_path, name)
|
||||
raise FileNotFoundError(f"目录 {dir_path} 下未找到包含「{EXCEL_KEYWORD}」的 xlsx 文件")
|
||||
|
||||
|
||||
def _find_transfer_excel(dir_path: str = None) -> str:
|
||||
"""在目录内查找包含「社保变更人员名单」的 xlsx 文件(社保转移数据源)。"""
|
||||
dir_path = dir_path or BASE_DIR
|
||||
if not os.path.isdir(dir_path):
|
||||
raise FileNotFoundError(f"目录不存在:{dir_path}")
|
||||
for name in os.listdir(dir_path):
|
||||
if TRANSFER_EXCEL_KEYWORD in name and name.lower().endswith(".xlsx") and not name.startswith("~$"):
|
||||
return os.path.join(dir_path, name)
|
||||
raise FileNotFoundError(f"目录 {dir_path} 下未找到包含「{TRANSFER_EXCEL_KEYWORD}」的 xlsx 文件")
|
||||
|
||||
|
||||
def _read_insurance_records(excel_path: str) -> list:
|
||||
"""读取「参保名单」sheet,返回人员记录列表(dict,key=表头字段名)。"""
|
||||
wb = openpyxl.load_workbook(excel_path, read_only=True, data_only=True)
|
||||
try:
|
||||
sheet = None
|
||||
for ws in wb.worksheets:
|
||||
if SHEET_KEYWORD in ws.title:
|
||||
sheet = ws
|
||||
break
|
||||
if sheet is None:
|
||||
raise ValueError(f"工作簿 {excel_path} 中未找到包含「{SHEET_KEYWORD}」的 sheet")
|
||||
|
||||
# 表头第 HEADER_ROW 行,只取主表字段(到「费用」列为止)
|
||||
header = [c.value for c in next(sheet.iter_rows(min_row=HEADER_ROW, max_row=HEADER_ROW, max_col=MAIN_COLS))]
|
||||
col_names = {i: str(h).strip() for i, h in enumerate(header) if h}
|
||||
if "姓名" not in col_names.values() or "办理状态" not in col_names.values():
|
||||
raise ValueError(f"「{sheet.title}」第{HEADER_ROW}行未解析到标准表头(缺少姓名/办理状态等)")
|
||||
|
||||
records = []
|
||||
for row in sheet.iter_rows(min_row=HEADER_ROW + 1, max_row=sheet.max_row, max_col=MAIN_COLS):
|
||||
values = [c.value for c in row]
|
||||
if all(v is None for v in values):
|
||||
continue
|
||||
rec = {name: values[i] for i, name in col_names.items() if i < len(values)}
|
||||
if rec.get("姓名") is not None:
|
||||
records.append(rec)
|
||||
return records
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def _match_rule(rec: dict, status: str, ins_type: str, ym: tuple) -> bool:
|
||||
"""按模板规则 + 公共过滤条件判断记录是否命中。"""
|
||||
if str(rec.get("办理状态") or "").strip() != status:
|
||||
return False
|
||||
if str(rec.get("参保类型") or "").strip() != ins_type:
|
||||
return False
|
||||
ptype = str(rec.get("人员类型") or "").strip()
|
||||
if any(kw in ptype for kw in EXCLUDE_TYPE_KEYWORDS):
|
||||
return False
|
||||
dept2 = str(rec.get("二级部门") or "")
|
||||
if not any(kw in dept2 for kw in DEPT_KEYWORDS):
|
||||
return False
|
||||
return _month_of(rec.get("办理时间")) == ym
|
||||
|
||||
|
||||
def _build_placeholders(rec: dict, ym: tuple) -> dict:
|
||||
"""根据记录与目标月份计算占位符替换值。"""
|
||||
y, m = ym
|
||||
next_y, next_m = (y, m + 1) if m < 12 else (y + 1, 1)
|
||||
today = datetime.now()
|
||||
|
||||
fee_txt = _fmt_num(rec.get("费用"))
|
||||
try:
|
||||
fee_num = float(rec.get("费用"))
|
||||
once_txt = _fmt_num(fee_num * 2)
|
||||
except (TypeError, ValueError):
|
||||
once_txt = ""
|
||||
|
||||
return {
|
||||
"{{姓名}}": str(rec.get("姓名") or ""),
|
||||
"{{四级部门}}": str(rec.get("四级部门") or ""),
|
||||
"{{参保单位全称}}": str(rec.get("参保单位全称") or ""),
|
||||
"{{区域}}": str(rec.get("区域") or ""),
|
||||
"{{费用}}": fee_txt,
|
||||
"{{备注}}": str(rec.get("备注") or ""),
|
||||
"{{一次性扣款}}": once_txt,
|
||||
# 模板文案已自带「月」字(如「{{当前月}} 月工资」「{{下月}}月15日」),故取纯数字
|
||||
"{{当前月}}": f"{m}",
|
||||
"{{下月}}": f"{next_m}",
|
||||
"{{当月15日}}": f"{m}月15日",
|
||||
"{{制作日年份}}": str(today.year),
|
||||
"{{制作日月份}}": str(today.month),
|
||||
"{{制作日天}}": str(today.day),
|
||||
}
|
||||
|
||||
|
||||
# ==================== Word 占位符替换(兼容占位符被 Word 拆成多个 run) ====================
|
||||
def _replace_in_paragraph(p, mapping: dict) -> None:
|
||||
runs = p.runs
|
||||
if not runs:
|
||||
return
|
||||
full = "".join(r.text for r in runs)
|
||||
if not any(k in full for k in mapping):
|
||||
return
|
||||
|
||||
# 1) 替换单个 run 内完整的占位符(保留 run 原格式)
|
||||
for r in runs:
|
||||
t = r.text
|
||||
for k, v in mapping.items():
|
||||
if k in t:
|
||||
t = t.replace(k, v)
|
||||
r.text = t
|
||||
|
||||
# 2) 处理跨 run 占位符(合并所在 run 区间,格式取起始 run)
|
||||
for k, v in mapping.items():
|
||||
if k in full and not any(k in r.text for r in runs):
|
||||
for i in range(len(runs)):
|
||||
rt = runs[i].text
|
||||
if k in rt:
|
||||
continue
|
||||
start = None
|
||||
for L in range(min(len(rt), len(k)), 0, -1):
|
||||
if rt[-L:] == k[:L]:
|
||||
start = len(rt) - L
|
||||
break
|
||||
if start is None:
|
||||
continue
|
||||
acc = rt
|
||||
j = i
|
||||
while k not in acc and j + 1 < len(runs):
|
||||
j += 1
|
||||
acc += runs[j].text
|
||||
if k in acc:
|
||||
runs[i].text = acc.replace(k, v)
|
||||
for x in range(i + 1, j + 1):
|
||||
runs[x].text = ""
|
||||
break
|
||||
|
||||
|
||||
def _fill_doc(template_path: str, mapping: dict):
|
||||
"""读取模板并替换占位符,返回内存中的 Document 对象(不保存)。"""
|
||||
if not os.path.exists(template_path):
|
||||
raise FileNotFoundError(f"模板不存在:{template_path}")
|
||||
doc = Document(template_path)
|
||||
|
||||
# 旧占位符统一归一化为新占位符
|
||||
norm = dict(LEGACY_PLACEHOLDERS)
|
||||
norm.update(mapping)
|
||||
|
||||
for para in doc.paragraphs:
|
||||
_replace_in_paragraph(para, norm)
|
||||
for tbl in doc.tables:
|
||||
for row in tbl.rows:
|
||||
for cell in row.cells:
|
||||
for para in cell.paragraphs:
|
||||
_replace_in_paragraph(para, norm)
|
||||
return doc
|
||||
|
||||
|
||||
def _leftover_placeholders(doc) -> set:
|
||||
"""统计文档(含表格)中残留的 {{...}} 占位符。"""
|
||||
leftover = set()
|
||||
for para in doc.paragraphs:
|
||||
leftover.update(re.findall(r"\{\{.*?\}\}", para.text))
|
||||
for tbl in doc.tables:
|
||||
for row in tbl.rows:
|
||||
for cell in row.cells:
|
||||
for para in cell.paragraphs:
|
||||
leftover.update(re.findall(r"\{\{.*?\}\}", para.text))
|
||||
return leftover
|
||||
|
||||
|
||||
def _merge_notice_docs(docs) -> object:
|
||||
"""把多份已填充的告知书 Document 合并为一份(每份之间插入分页符)。"""
|
||||
base = docs[0]
|
||||
body = base.element.body
|
||||
sect_pr = body.find(qn("w:sectPr"))
|
||||
for d in docs[1:]:
|
||||
# 分页符段落
|
||||
p = base.add_paragraph()
|
||||
p.add_run().add_break(WD_BREAK.PAGE)
|
||||
# 将该份告知书的段落与表格追加到正文末尾(跳过节属性)
|
||||
for child in list(d.element.body):
|
||||
if child.tag == qn("w:sectPr"):
|
||||
continue
|
||||
if sect_pr is not None:
|
||||
sect_pr.addprevious(deepcopy(child))
|
||||
else:
|
||||
body.append(deepcopy(child))
|
||||
return base
|
||||
|
||||
|
||||
def _safe_filename(name: str) -> str:
|
||||
"""过滤 Windows 文件名非法字符,避免路径/分隔符冲突。"""
|
||||
for ch in '\\/:*?"<>|':
|
||||
name = name.replace(ch, "_")
|
||||
return name.strip() or "未命名"
|
||||
|
||||
|
||||
def _fill_template(template_path: str, mapping: dict, out_path: str) -> int:
|
||||
"""读取模板并替换占位符,保存为 out_path。返回残留占位符数量。"""
|
||||
doc = _fill_doc(template_path, mapping)
|
||||
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
||||
doc.save(out_path)
|
||||
return len(_leftover_placeholders(doc))
|
||||
|
||||
|
||||
# ==================== PDF 转换(WPS 文字 COM,兼容无 MS Word 环境) ====================
|
||||
@retry(max_attempts=RETRY_TIMES)
|
||||
def _publish_via_wps(src_docx: str, target_docx: str, target_pdf: str) -> None:
|
||||
"""用 WPS 打开 src_docx,另存为 target_docx 并导出 target_pdf。失败自动重试 3 次。"""
|
||||
os.makedirs(os.path.dirname(target_docx), exist_ok=True)
|
||||
src_docx = os.path.abspath(src_docx)
|
||||
target_docx = os.path.abspath(target_docx)
|
||||
target_pdf = os.path.abspath(target_pdf)
|
||||
|
||||
app = None
|
||||
try:
|
||||
app = win32com.client.Dispatch("Kwps.Application")
|
||||
app.Visible = False
|
||||
try:
|
||||
app.DisplayAlerts = 0
|
||||
except Exception:
|
||||
pass
|
||||
doc = app.Documents.Open(src_docx)
|
||||
try:
|
||||
doc.SaveAs2(target_docx, 12) # 12 = wdFormatXMLDocument
|
||||
except Exception:
|
||||
doc.SaveAs(target_docx, 12)
|
||||
doc.ExportAsFixedFormat(target_pdf, 17) # 17 = wdFormatPDF
|
||||
doc.Close(False)
|
||||
finally:
|
||||
if app is not None:
|
||||
try:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== OA 工作沟通推送数据构造 ====================
|
||||
def _norm_code(value):
|
||||
"""工号统一转文本:浮点整数(37036835.0)去掉小数部分,与花名册文本工号保持一致。"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
f = float(value)
|
||||
if f.is_integer():
|
||||
return str(int(f))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
s = str(value).strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def _read_roster_map(roster_path: str) -> dict:
|
||||
"""读取花名册,返回 {工号: {姓名, 二级部门, 四级部门, 岗位}};表头行自动定位(含「工号」列)。"""
|
||||
if not os.path.exists(roster_path):
|
||||
raise FileNotFoundError(f"花名册文件不存在:{roster_path}")
|
||||
wb = openpyxl.load_workbook(roster_path, read_only=True, data_only=True)
|
||||
try:
|
||||
ws = wb.active
|
||||
col_idx, header_row = {}, None
|
||||
for row in ws.iter_rows():
|
||||
if header_row is None:
|
||||
names = {str(c.value).strip(): i for i, c in enumerate(row) if c.value is not None}
|
||||
if "工号" in names:
|
||||
col_idx, header_row = names, row[0].row
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"花名册未找到表头行(缺少「工号」字段):{roster_path}")
|
||||
need = ("工号", "姓名", "二级部门", "四级部门", "岗位")
|
||||
missing = [c for c in need if c not in col_idx]
|
||||
if missing:
|
||||
raise ValueError(f"花名册缺少必需列:{missing}")
|
||||
|
||||
def _cell(vals, key):
|
||||
i = col_idx[key]
|
||||
return vals[i] if i < len(vals) else None
|
||||
|
||||
result = {}
|
||||
for row in ws.iter_rows(min_row=header_row + 1):
|
||||
vals = [c.value for c in row]
|
||||
code = _norm_code(_cell(vals, "工号"))
|
||||
if not code:
|
||||
continue
|
||||
result[code] = {
|
||||
"姓名": str(_cell(vals, "姓名") or ""),
|
||||
"二级部门": str(_cell(vals, "二级部门") or ""),
|
||||
"四级部门": str(_cell(vals, "四级部门") or ""),
|
||||
"岗位": str(_cell(vals, "岗位") or ""),
|
||||
}
|
||||
return result
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def _fill_dept4(rec: dict, roster_map: dict) -> str:
|
||||
"""四级部门:源数据缺失时查花名册(按37工号),仍缺失 fallback 二级部门。"""
|
||||
dept4 = str(rec.get("四级部门") or "").strip()
|
||||
if dept4:
|
||||
return dept4
|
||||
code = _norm_code(rec.get("37工号"))
|
||||
if code and roster_map and code in roster_map:
|
||||
dept4 = str(roster_map[code].get("四级部门") or "").strip()
|
||||
if dept4:
|
||||
return dept4
|
||||
return str(rec.get("二级部门") or "").strip() or "未知"
|
||||
|
||||
|
||||
def _read_transfer_records(excel_path: str, roster_map: dict = None) -> list:
|
||||
"""读取社保变更人员名单,返回「是否变更」=是 的记录列表。
|
||||
|
||||
每条 rec 带标准列名(新区域->区域、个人费用->费用)与 _source=sheet 名(区分职能/门店);
|
||||
四级部门缺失时用花名册补全,仍缺失 fallback 二级部门。
|
||||
"""
|
||||
wb = openpyxl.load_workbook(excel_path, read_only=True, data_only=True)
|
||||
try:
|
||||
records = []
|
||||
for ws in wb.worksheets:
|
||||
if not any(kw in ws.title for kw in TRANSFER_SHEET_GENERATE):
|
||||
continue # 仅处理配置范围内的 sheet(职能及干部/门店)
|
||||
# 自动定位表头行:同时含「37工号」与「是否变更」列
|
||||
col_idx, header_row = None, None
|
||||
for row in ws.iter_rows():
|
||||
if header_row is None:
|
||||
names = {str(c.value).strip(): i for i, c in enumerate(row) if c.value is not None}
|
||||
if "37工号" in names and TRANSFER_CHANGE_COL in names:
|
||||
col_idx, header_row = names, row[0].row
|
||||
break
|
||||
if header_row is None:
|
||||
continue # 非目标 sheet(如说明/汇总页)
|
||||
|
||||
def _cell(vals, key):
|
||||
i = col_idx.get(key)
|
||||
return vals[i] if i is not None and i < len(vals) else None
|
||||
|
||||
for row in ws.iter_rows(min_row=header_row + 1):
|
||||
vals = [c.value for c in row]
|
||||
if all(v is None for v in vals):
|
||||
continue
|
||||
if str(_cell(vals, TRANSFER_CHANGE_COL) or "").strip() != TRANSFER_CHANGE_VALUE:
|
||||
continue
|
||||
rec = {}
|
||||
for src, std in TRANSFER_COL_MAP.items():
|
||||
if src in col_idx:
|
||||
rec[std] = _cell(vals, src)
|
||||
for key in ("姓名", "二级部门", "四级部门", "37工号", "参保单位全称", "备注"):
|
||||
if key in col_idx:
|
||||
rec[key] = _cell(vals, key)
|
||||
if rec.get("姓名") is None:
|
||||
continue
|
||||
rec["_source"] = ws.title
|
||||
rec["四级部门"] = _fill_dept4(rec, roster_map)
|
||||
if not rec.get("工号") and rec.get("37工号") is not None:
|
||||
rec["工号"] = rec["37工号"]
|
||||
records.append(rec)
|
||||
return records
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def _find_store_manager_in_map(roster_map: dict, code: str):
|
||||
"""在已读花名册中查店长(同四级部门岗位含「店长」,按行序取第一个),返回店长工号或 None。"""
|
||||
info = roster_map.get(code)
|
||||
if not info or not info["四级部门"]:
|
||||
return None
|
||||
for c, it in roster_map.items():
|
||||
if it["四级部门"] == info["四级部门"] and "店长" in it["岗位"]:
|
||||
return c
|
||||
return None
|
||||
|
||||
|
||||
def _find_hr_personnel_in_map(roster_map: dict, code: str) -> list:
|
||||
"""在已读花名册中查人事:二级部门为「石桥铺会馆」固定返回;经营中心下岗位含「人事」全量返回。"""
|
||||
info = roster_map.get(code)
|
||||
if not info:
|
||||
return []
|
||||
dept2 = info["二级部门"]
|
||||
if dept2 in DEPT2_HR_OVERRIDE:
|
||||
return list(DEPT2_HR_OVERRIDE[dept2])
|
||||
if "经营中心" not in dept2:
|
||||
return []
|
||||
return [c for c, it in roster_map.items() if it["二级部门"] == dept2 and "人事" in it["岗位"]]
|
||||
|
||||
|
||||
def _resolve_receivers(roster_map: dict, codes: list) -> list:
|
||||
"""为员工工号列表解析接收人(店长+人事),按出现顺序去重,返回工号列表。"""
|
||||
receivers = []
|
||||
for code in codes:
|
||||
mgr = _find_store_manager_in_map(roster_map, code)
|
||||
if mgr and mgr not in receivers:
|
||||
receivers.append(mgr)
|
||||
for hr in _find_hr_personnel_in_map(roster_map, code):
|
||||
if hr and hr not in receivers:
|
||||
receivers.append(hr)
|
||||
return receivers
|
||||
|
||||
|
||||
def _collect_rule_pdfs(month_dir: str, rule_folder: str) -> list:
|
||||
"""收集该类型输出目录下全部告知书 PDF 附件路径(不按命中人员筛选,全部推送)。"""
|
||||
folder = os.path.join(month_dir, rule_folder)
|
||||
if not os.path.isdir(folder):
|
||||
return []
|
||||
return [os.path.join(folder, f) for f in sorted(os.listdir(folder)) if f.lower().endswith(".pdf")]
|
||||
|
||||
|
||||
def _text_to_html(text: str) -> str:
|
||||
"""多行纯文本转 HTML:
|
||||
- 普通段落用 <p style="text-indent:2em"> 首行缩进 2 字符;
|
||||
- 行以 @@R 前缀标记右对齐(落款),输出时去除前缀并用 <p style="text-align:right">。
|
||||
"""
|
||||
parts = []
|
||||
for ln in str(text).splitlines():
|
||||
ln = ln.strip()
|
||||
if not ln:
|
||||
continue
|
||||
if ln.startswith("@@R"):
|
||||
parts.append(f'<p style="text-align:right">{ln[3:]}</p>')
|
||||
else:
|
||||
parts.append(f'<p style="text-indent:2em">{ln}</p>')
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def _highlight_text(text: str, highlights: tuple, m: int = None) -> str:
|
||||
"""给文案关键词加颜色高亮(<span style="color:...">),keyword 支持 {m} 月份占位符。"""
|
||||
for keyword, color in highlights:
|
||||
kw = keyword.format(m=m) if m is not None else keyword
|
||||
text = text.replace(kw, f'<span style="color:{color}">{kw}</span>')
|
||||
return text
|
||||
|
||||
|
||||
def build_work_communication_data(excel_path: str = None, output_dir: str = None,
|
||||
ym: tuple = None, roster_path: str = None) -> list:
|
||||
"""
|
||||
构造 OA 工作沟通推送数据:员工参与社会保险+参保异常合并一条、社保转移单独一条。
|
||||
附件为该类型输出目录下全部告知书 PDF(不筛选);接收人为店长+人事工号
|
||||
并统一追加固定抄送人周卫(37001166)。每条含
|
||||
subject/content(HTML)/attachment_paths/receivers/category,
|
||||
并写入影刀全局变量 messages(列表),供「OA工作沟通推送」指令逐条调用。
|
||||
|
||||
Args:
|
||||
excel_path: 参保/停保名单 xlsx 路径,默认自动在 BASE_DIR 查找
|
||||
output_dir: 输出目录,默认 OUTPUT_ROOT(须先执行 generate_notices 生成 PDF)
|
||||
ym: 目标年月 (year, month),默认从文件名解析
|
||||
roster_path: 员工花名册路径,默认 ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
list: [{"subject", "content", "attachment_paths", "receivers", "category"}, ...]
|
||||
"""
|
||||
excel_path = excel_path or _find_excel(BASE_DIR)
|
||||
ym = ym or _extract_ym(os.path.basename(excel_path))
|
||||
output_dir = output_dir or OUTPUT_ROOT
|
||||
roster_path = roster_path or ROSTER_PATH
|
||||
y, m = ym
|
||||
month_dir = os.path.join(output_dir, f"{y}{m:02d}")
|
||||
|
||||
logger.info("构造 OA 工作沟通数据:%s(%d-%02d)", excel_path, y, m)
|
||||
records = _read_insurance_records(excel_path)
|
||||
|
||||
# 社保转移:独立数据源(社保变更人员名单),推送仅限「变更-门店」sheet
|
||||
try:
|
||||
roster_map = _read_roster_map(roster_path or ROSTER_PATH)
|
||||
except Exception as e:
|
||||
logger.warning("花名册读取失败,社保转移四级部门将回退二级部门:%s", e)
|
||||
roster_map = {}
|
||||
transfer_excel = _find_transfer_excel(BASE_DIR)
|
||||
transfer_records = _read_transfer_records(transfer_excel, roster_map)
|
||||
|
||||
# 按模板规则筛出命中员工
|
||||
matched_by_rule = {}
|
||||
for rule_name, rule in TEMPLATES.items():
|
||||
if rule_name == "社保转移":
|
||||
matched = [r for r in transfer_records if TRANSFER_SHEET_PUSH in str(r.get("_source") or "")]
|
||||
else:
|
||||
matched = [r for r in records if _match_rule(r, rule["status"], rule["type"], ym)]
|
||||
matched_by_rule[rule_name] = matched
|
||||
logger.info("[%s] 命中 %d 人", rule_name, len(matched))
|
||||
|
||||
roster_map = _read_roster_map(roster_path)
|
||||
logger.info("花名册共 %d 人:%s", len(roster_map), roster_path)
|
||||
|
||||
messages = []
|
||||
for tpl in OA_MESSAGE_TEMPLATES:
|
||||
matched_recs = []
|
||||
for rn in tpl["rule_keys"]:
|
||||
matched_recs.extend(matched_by_rule.get(rn, []))
|
||||
|
||||
# 附件:仅 PDF,收集该类型输出目录下全部告知书(不筛选,全部推送)
|
||||
attachment_paths = []
|
||||
for rn in tpl["rule_keys"]:
|
||||
attachment_paths.extend(_collect_rule_pdfs(month_dir, TEMPLATES[rn]["folder"]))
|
||||
# 同一二级部门的所有告知书挨着排列(文件名首段=二级部门,段内按文件名排)
|
||||
attachment_paths = sorted(
|
||||
attachment_paths,
|
||||
key=lambda p: (os.path.basename(p).split("_", 1)[0], os.path.basename(p)),
|
||||
)
|
||||
if not attachment_paths:
|
||||
logger.warning("[%s] 未收集到告知书 PDF(请先执行告知书生成),跳过该推送", tpl["key"])
|
||||
continue
|
||||
|
||||
# 接收人:店长 + 人事(工号去重),并统一加上固定抄送人(周卫)
|
||||
codes = []
|
||||
for r in matched_recs:
|
||||
c = _norm_code(r.get("工号"))
|
||||
if c:
|
||||
codes.append(c)
|
||||
else:
|
||||
logger.warning("员工「%s」无工号,跳过接收人解析", r.get("姓名"))
|
||||
receivers = _resolve_receivers(roster_map, codes)
|
||||
if TEST_MODE:
|
||||
receivers = list(TEST_RECEIVER)
|
||||
logger.info("[测试模式] [%s] 接收人覆盖为测试接收人:%s", tpl["key"], TEST_RECEIVER)
|
||||
if CC_RECEIVER_ID not in receivers:
|
||||
receivers.append(CC_RECEIVER_ID) # 固定抄送人:周卫
|
||||
if not receivers:
|
||||
logger.warning("[%s] 未解析到任何接收人(店长/人事),跳过该推送", tpl["key"])
|
||||
continue
|
||||
|
||||
# 落款日期 = 实际推送当天日期(如 2026年08月26日,带前导0)
|
||||
push_date = datetime.today().strftime("%Y年%m月%d日")
|
||||
content = _highlight_text(tpl["content"].format(y=y, m=m, push_date=push_date), OA_HIGHLIGHTS.get(tpl["key"], ()), m=m)
|
||||
|
||||
messages.append({
|
||||
"subject": tpl["subject"].format(y=y, m=m),
|
||||
"content": _text_to_html(content),
|
||||
"attachment_paths": attachment_paths,
|
||||
"receivers": receivers,
|
||||
"category": tpl["category"],
|
||||
})
|
||||
logger.info("[%s] 附件 %d 份,接收人 %d 人:%s",
|
||||
tpl["key"], len(attachment_paths), len(receivers), ", ".join(receivers))
|
||||
|
||||
_set_glv(OA_GLV_NAME, messages)
|
||||
logger.info("构造完成:%d 条工作沟通推送数据,已写入全局变量 %s", len(messages), OA_GLV_NAME)
|
||||
return messages
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def generate_notices(excel_path: str = None, output_dir: str = None, ym: tuple = None,
|
||||
roster_path: str = None) -> dict:
|
||||
"""
|
||||
生成三类告知书(Word + PDF)。
|
||||
|
||||
Args:
|
||||
excel_path: 参保/停保名单 xlsx 路径,默认自动在 BASE_DIR 查找
|
||||
output_dir: 输出目录,默认 OUTPUT_ROOT
|
||||
ym: 目标年月 (year, month),默认从文件名解析
|
||||
roster_path: 员工花名册路径(社保转移四级部门补全用),默认 ROSTER_PATH
|
||||
|
||||
Returns:
|
||||
{模板名: [输出文件路径, ...]}
|
||||
"""
|
||||
excel_path = excel_path or _find_excel(BASE_DIR)
|
||||
ym = ym or _extract_ym(os.path.basename(excel_path))
|
||||
output_dir = output_dir or OUTPUT_ROOT
|
||||
y, m = ym
|
||||
month_dir = os.path.join(output_dir, f"{y}{m:02d}")
|
||||
|
||||
logger.info("读取名单:%s(目标年月 %d-%02d)", excel_path, y, m)
|
||||
records = _read_insurance_records(excel_path)
|
||||
logger.info("「参保名单」共 %d 条记录", len(records))
|
||||
|
||||
# 社保转移:独立数据源(社保变更人员名单),生成覆盖职能及干部+门店两个 sheet
|
||||
try:
|
||||
roster_map = _read_roster_map(roster_path or ROSTER_PATH)
|
||||
except Exception as e:
|
||||
logger.warning("花名册读取失败,社保转移四级部门将回退二级部门:%s", e)
|
||||
roster_map = {}
|
||||
transfer_excel = _find_transfer_excel(BASE_DIR)
|
||||
transfer_records = _read_transfer_records(transfer_excel, roster_map)
|
||||
logger.info("「社保变更人员名单」命中 %d 人:%s", len(transfer_records), transfer_excel)
|
||||
|
||||
results = {}
|
||||
for rule_name, rule in TEMPLATES.items():
|
||||
tpl_path = rule["file"]
|
||||
if not os.path.exists(tpl_path):
|
||||
raise FileNotFoundError(f"模板不存在:{tpl_path}")
|
||||
if rule_name == "社保转移":
|
||||
matched = transfer_records
|
||||
else:
|
||||
matched = [r for r in records if _match_rule(r, rule["status"], rule["type"], ym)]
|
||||
if not matched:
|
||||
logger.info("[%s] 无命中人员,跳过", rule_name)
|
||||
results[rule_name] = []
|
||||
continue
|
||||
|
||||
out_folder = os.path.join(month_dir, rule["folder"])
|
||||
os.makedirs(out_folder, exist_ok=True)
|
||||
files = []
|
||||
logger.info("=" * 70)
|
||||
logger.info("[%s] 命中 %d 人(%s)", rule_name, len(matched), ", ".join(str(r.get("姓名")) for r in matched))
|
||||
|
||||
# 按(二级部门,四级部门)分组合并,生成一份告知书
|
||||
groups = {}
|
||||
for rec in matched:
|
||||
key = (str(rec.get("二级部门") or "未知").strip(), str(rec.get("四级部门") or "未知").strip())
|
||||
groups.setdefault(key, []).append(rec)
|
||||
|
||||
for (dept2, dept4), recs in groups.items():
|
||||
# 每人生成一份已填充的内存文档,再合并(每份之间分页)
|
||||
docs = [_fill_doc(tpl_path, _build_placeholders(r, ym)) for r in recs]
|
||||
doc = _merge_notice_docs(docs) if len(docs) > 1 else docs[0]
|
||||
base_name = _safe_filename(f"{dept2}_{dept4}_{rule['folder']}")
|
||||
docx_path = os.path.join(out_folder, base_name + ".docx")
|
||||
pdf_path = docx_path[:-5] + ".pdf"
|
||||
|
||||
doc.save(docx_path)
|
||||
leftover = _leftover_placeholders(doc)
|
||||
if leftover:
|
||||
logger.warning("[%s] %s 模板存在未替换占位符:%s", rule_name, base_name, sorted(leftover))
|
||||
_publish_via_wps(docx_path, docx_path, pdf_path)
|
||||
logger.info("已生成:%s(%d 人)", os.path.basename(docx_path), len(recs))
|
||||
files.append(docx_path)
|
||||
results[rule_name] = files
|
||||
|
||||
logger.info("=" * 70)
|
||||
logger.info("全部完成,输出目录:%s", month_dir)
|
||||
return results
|
||||
|
||||
|
||||
def main() -> list:
|
||||
"""告知书制作与下发(影刀入口):生成当月三类告知书,并构造 OA 工作沟通推送数据。
|
||||
|
||||
Returns:
|
||||
工作沟通推送数据列表(每条含 receivers/subject/content/attachment_paths/category),
|
||||
与影刀全局变量 messages 内容一致;即使无影刀环境,调用方也可直接用返回值推送。
|
||||
"""
|
||||
try:
|
||||
results = generate_notices()
|
||||
messages = build_work_communication_data()
|
||||
_set_glv("notice_output_dir", os.path.join(OUTPUT_ROOT, datetime.now().strftime("%Y%m")))
|
||||
_set_glv(OA_GLV_NAME, messages)
|
||||
total = sum(len(files) for files in results.values())
|
||||
logger.info("共生成 %d 份告知书(docx+pdf),构造 %d 条工作沟通推送数据", total, len(messages))
|
||||
return messages
|
||||
except Exception:
|
||||
logger.exception("告知书制作与下发失败")
|
||||
_set_glv("notice_error", traceback.format_exc())
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,11 @@
|
||||
# XQ0016 社保转移告知书制作与下发 — 影刀脚本占位
|
||||
|
||||
- 需求单文档:`docs/需求单/XQ0016 社保转移告知书制作与下发/`
|
||||
- 状态:**已由 XQ0015 覆盖实现,本目录为归档占位**
|
||||
|
||||
## 说明
|
||||
- 实现脚本:`XQ0015/notice_mail_merge.py`
|
||||
- 该脚本一次处理「参保 / 参保异常 / 社保转移」三类告知书模板,社保转移告知书由同一模块生成,**本目录无需再放代码**。
|
||||
|
||||
## 如需独立拆出
|
||||
将本类告知书的生成逻辑单独拆为 `XQ0016/<业务名>.py`,并移除 `XQ0015/notice_mail_merge.py` 中对社保转移的处理分支。
|
||||
@@ -0,0 +1,9 @@
|
||||
# XQ0017 入职人事手续办理 — 影刀脚本占位
|
||||
|
||||
- 需求单文档:`docs/需求单/XQ0017 入职人事手续办理/`
|
||||
- 状态:**未实现(预留目录,供后续直接放代码)**
|
||||
|
||||
## 本目录应放置
|
||||
按影刀「单文件自包含」规范,将本需求单的影刀脚本直接放入本目录,例如:
|
||||
- `<业务名>.py`:主流程(单文件、可直接运行)
|
||||
- 如需拆步骤,可放多个单文件,文件间互不 `import`
|
||||
@@ -0,0 +1,13 @@
|
||||
# XQ0018 调动人事手续跟进 — 影刀脚本占位
|
||||
|
||||
- 需求单文档:`docs/需求单/XQ0018 调动人事手续跟进/`
|
||||
- 状态:**未实现(预留目录,供后续直接放代码)**
|
||||
|
||||
## 本目录应放置
|
||||
按影刀「单文件自包含」规范,将本需求单的影刀脚本直接放入本目录,例如:
|
||||
- `<业务名>.py`:主流程(单文件、可直接运行)
|
||||
- 如需拆步骤,可放多个单文件,文件间互不 `import`
|
||||
|
||||
## 参考
|
||||
- 调动台账导出可参考 `XQ0001/transfer_roster_export.py`
|
||||
- 店长/人事查询可参考 `app/service/hrbp/ehr/roster/roster_query.py`
|
||||
@@ -0,0 +1,12 @@
|
||||
# XQ0019 离职人事手续跟进与检查 — 影刀脚本占位
|
||||
|
||||
- 需求单文档:`docs/需求单/XQ0019 离职人事手续跟进与检查/`
|
||||
- 状态:**未实现(预留目录,供后续直接放代码)**
|
||||
|
||||
## 本目录应放置
|
||||
按影刀「单文件自包含」规范,将本需求单的影刀脚本直接放入本目录,例如:
|
||||
- `<业务名>.py`:主流程(单文件、可直接运行)
|
||||
- 如需拆步骤,可放多个单文件,文件间互不 `import`
|
||||
|
||||
## 参考
|
||||
- 离职电子签审核见 `XQ0020/resign_e_sign_approval.py`
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,640 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: dingtalk_dws_push.py
|
||||
@Description: 钉钉推送共享模块(单聊 + 群聊,文本 / 文件,基于 dws 命令行)。
|
||||
供各业务脚本 import 复用,也可作为影刀自定义指令「37du钉钉推送」的模块源码
|
||||
(同一入口,chat_type 参数决定单聊还是群聊)。
|
||||
|
||||
入口(统一 main,按消息结构自动识别单聊/群聊):
|
||||
main(messages, record_dir='', chat_type='') 影刀自定义指令「37du钉钉推送」调用入口。
|
||||
通道判定:chat_type 留空(默认)时按每条消息结构自动判断——dict 含 group/群名 键为群聊,
|
||||
其余为单聊;显式传 'single'/'group' 时整批强制用该通道(兼容旧流程)。
|
||||
chat_type='single'/单聊:传入消息列表,每项为五元组 (消息类型, 姓名, 工号, 消息内容, 文件地址):
|
||||
msg_type 消息类型:'text'/'文本' 或 'file'/'文件'
|
||||
name 接收人姓名(文本/文件均按姓名解析 openDingTalkId;同名多人时按工号精确定位)
|
||||
user_id 接收人工号(同名消歧;发文件且对方无会话时用于先建会话)
|
||||
content 消息内容(msg_type=text 时必填)
|
||||
file_path 文件地址(msg_type=file 时必填,本地绝对路径)
|
||||
chat_type='group'/群聊:传入消息列表,每项支持 dict 或元组:
|
||||
dict: {"group": 群名, "content": 文本, "file_path": 文件,
|
||||
"title": 标题, "at_all": bool, "at_open_ids": "openId1,openId2"}
|
||||
元组: (群名, 文本内容, 文件地址, 标题, at_all, at_open_ids),后 4 项可省略
|
||||
按群名解析 openconversation_id 后发送(文本/文件可同时存在,@ 需在内容中含占位符)。
|
||||
record_dir(可选):非空时每条结果写入 <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='') # 单聊单条发送(内部/业务脚本复用)
|
||||
send_group_message(group_name, content, file_path, title, at_all, at_open_ids, record_dir='') # 群聊单条发送
|
||||
|
||||
推送原理(DWS CLI,零第三方 Python 依赖,仅标准库):
|
||||
单聊:
|
||||
- 文本:按姓名解析 openDingTalkId 后 dws chat message send --open-dingtalk-id <openId> --content <内容>
|
||||
(dws 的 --user 只认钉钉 org userId,与工号不同,故文本/文件统一走 --open-dingtalk-id;
|
||||
内容按钉钉 markdown 渲染:单行换行用 <br>,空行用 <br><br>;单聊会话由首条消息自动创建,
|
||||
遇 11056 自动等待后重试一次,无需对方先聊过天)
|
||||
- 文件:按姓名查 openDingTalkId → 取单聊会话共享空间 ID → 上传文件到钉盘
|
||||
→ 按 dentry 信息发文件消息;对方未建立会话(11056)时自动先发一条
|
||||
文本建立会话再发文件。
|
||||
群聊:
|
||||
- 按群名 dws chat search --query <群名> 解析 openconversation_id(模糊搜索→精确同名过滤→歧义报错);
|
||||
- 文本:dws chat message send --conversation-id <openconversation_id> --content <内容>
|
||||
(支持 --title 标题、--at-all @所有人、--at-open-dingtalk-ids @指定成员;
|
||||
@ 场景内容里需包含占位符 <@all> / <@openDingTalkId>)
|
||||
- 文件:dws chat message send --conversation-id <id> --msg-type file --file <本地路径>
|
||||
(CLI 自动完成上传并按 file 消息发送,无需像单聊那样手动取会话空间)。
|
||||
|
||||
防风控限流:
|
||||
每次实际发送前经滑动窗口限流(默认 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=""):
|
||||
"""尽力追加一条推送记录到 <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:
|
||||
"""先按姓名搜索候选,再按工号(jobNumber)锁定唯一推送人;未传工号才按姓名判定。
|
||||
查询结果按 (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}」的成员")
|
||||
|
||||
# 批量拉详情(含工号 jobNumber、部门)。注意:search 是关键词模糊搜索(会误命中「陈杰顺」
|
||||
# 等近似名)且返回里没有工号字段,工号只在 get 详情的 orgEmployeeModel.jobNumber,
|
||||
# 故不能拿 search 的 userId(钉钉长 id)当工号匹配。
|
||||
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 []
|
||||
# search 的 userId 与 get 返回的 orgEmployeeModel.orgUserId 同源,据此关联详情
|
||||
info_map = {}
|
||||
for d in details:
|
||||
org = d.get("orgEmployeeModel") or {}
|
||||
if org.get("orgUserId"):
|
||||
info_map[org["orgUserId"]] = d
|
||||
|
||||
# 传入工号:在姓名候选里按工号(jobNumber)锁定实际推送人,命中即唯一,绝不猜第一个
|
||||
if user_id:
|
||||
for u in users:
|
||||
org_model = info_map.get(u["userId"], {}).get("orgEmployeeModel", {})
|
||||
if str(org_model.get("jobNumber") or "").strip() == user_id:
|
||||
print(f"[INFO] 按工号锁定: {u['name']} | 工号={user_id} | {org_model.get('orgTitle') or ''}")
|
||||
_OPEN_ID_CACHE[key] = u["openDingTalkId"]
|
||||
return u["openDingTalkId"]
|
||||
hints = []
|
||||
for u in users:
|
||||
org_model = info_map.get(u["userId"], {}).get("orgEmployeeModel", {})
|
||||
job = str(org_model.get("jobNumber") or "").strip() or "未知"
|
||||
hints.append(f" {u.get('name')} | 工号={job}")
|
||||
raise RuntimeError(
|
||||
f"按姓名「{name}」搜索的候选中未找到工号 {user_id},请核对姓名与工号是否匹配:\n"
|
||||
+ "\n".join(hints)
|
||||
)
|
||||
|
||||
# 未传工号:按姓名搜索结果判定(候选唯一 → 采用;多个 → 精确同名过滤 → 歧义报错)
|
||||
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"]
|
||||
|
||||
# 按姓名精确过滤:search 为关键词模糊搜索,剔除「陈杰顺」这类误命中后再判
|
||||
exact = [u for u in users if (u.get("name") or "").strip() == name]
|
||||
if len(exact) == 1:
|
||||
u = exact[0]
|
||||
print(f"[INFO] 按姓名精确命中: {u['name']} | userId={u['userId']} | {u.get('title') or ''}")
|
||||
_OPEN_ID_CACHE[key] = u["openDingTalkId"]
|
||||
return u["openDingTalkId"]
|
||||
|
||||
# 仍无法唯一确定:禁止默认选第一个,报歧义错误并带工号辅助人工核对
|
||||
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)
|
||||
job = str(org_model.get("jobNumber") or "").strip() or "未知"
|
||||
hints.append(
|
||||
f" {u.get('name')} | 工号={job} | "
|
||||
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, "--content", 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 search_group(query: str, limit: int = 20) -> list:
|
||||
"""按群名搜索群聊(关键词模糊搜索),返回候选列表。
|
||||
注意:dws 要求 query 使用群名连续核心词(如「项目冲刺」),勿拆成单字搜索。
|
||||
dws chat search 返回结构为 result.groups(result 是字典),此处统一提取列表。
|
||||
"""
|
||||
data = _run_dws([DWS_BIN, "chat", "search", "--query", query,
|
||||
"--limit", str(limit), "--format", "json"])
|
||||
result = data.get("result") or {}
|
||||
if isinstance(result, dict):
|
||||
return result.get("groups") or []
|
||||
return result or []
|
||||
|
||||
|
||||
def _group_conv_id(group: dict) -> str:
|
||||
"""从群搜索结果条目中提取 openconversation_id(兼容多个候选字段名)。"""
|
||||
for key in ("openConversationId", "conversationId", "chatId", "id"):
|
||||
val = (group or {}).get(key)
|
||||
if val:
|
||||
return str(val)
|
||||
return ""
|
||||
|
||||
|
||||
def _group_title(group: dict) -> str:
|
||||
"""群搜索条目里的群名:dws chat search 返回的群名字段是 title(个别场景可能是 name)。"""
|
||||
for key in ("title", "name"):
|
||||
val = (group or {}).get(key)
|
||||
if val:
|
||||
return str(val)
|
||||
return ""
|
||||
|
||||
|
||||
def resolve_group_id(group_name: str) -> str:
|
||||
"""按群名精确解析群聊 openconversation_id(群名一律传全称)。
|
||||
先按全称搜索,再对 title 做全等过滤:唯一命中即返回;无匹配或同名多个直接报错,
|
||||
不采用模糊候选(绝不推给相近群名)。
|
||||
"""
|
||||
group_name = str(group_name or "").strip()
|
||||
if not group_name:
|
||||
raise RuntimeError("群名不能为空(请传群全称)")
|
||||
groups = search_group(group_name)
|
||||
if not groups:
|
||||
raise RuntimeError(f"未找到群「{group_name}」,请确认群全称后重试")
|
||||
exact = [g for g in groups if _group_title(g) == group_name]
|
||||
if len(exact) == 1:
|
||||
g = exact[0]
|
||||
print(f"[INFO] 命中群: {_group_title(g)} | openConversationId={_group_conv_id(g)}")
|
||||
return _group_conv_id(g)
|
||||
if not exact:
|
||||
hints = "\n".join(
|
||||
f" {_group_title(g) or '未知群名'}" for g in groups)
|
||||
raise RuntimeError(
|
||||
f"未找到与「{group_name}」全等匹配的群,附近候选:\n{hints}")
|
||||
hints = "\n".join(
|
||||
f" {_group_title(g) or '未知群名'} | {_group_conv_id(g)}" for g in exact)
|
||||
raise RuntimeError(
|
||||
f"群名「{group_name}」匹配到 {len(exact)} 个同名候选,请确认后重试:\n{hints}")
|
||||
|
||||
|
||||
def send_group_text(conversation_id: str, text: str, title: str = "",
|
||||
at_all: bool = False, at_open_ids: str = ""):
|
||||
"""向群聊发送文本(纯文本 / Markdown,单行换行用 <br>)。
|
||||
at_all=True 或传 at_open_ids 时,消息内容需包含对应占位符 <@all> / <@openDingTalkId>。
|
||||
"""
|
||||
cmd = [DWS_BIN, "chat", "message", "send",
|
||||
"--conversation-id", conversation_id, "--content", str(text)]
|
||||
if title:
|
||||
cmd += ["--title", str(title)]
|
||||
if at_all:
|
||||
cmd += ["--at-all"]
|
||||
if at_open_ids:
|
||||
cmd += ["--at-open-dingtalk-ids", str(at_open_ids)]
|
||||
cmd += ["--format", "json"]
|
||||
_rate_limit_wait() # 限流:每次实际发送占用一个名额
|
||||
_run_dws(cmd)
|
||||
print(f"[INFO] 群文本已发送: {text}")
|
||||
|
||||
|
||||
def send_group_file(conversation_id: str, file_path: str):
|
||||
"""向群聊发送本地文件(dws CLI 自动上传并按 file 消息发送,无需手动取会话空间)。"""
|
||||
_rate_limit_wait() # 限流:文件消息占用一个名额
|
||||
_run_dws([DWS_BIN, "chat", "message", "send",
|
||||
"--conversation-id", conversation_id,
|
||||
"--msg-type", "file", "--file", str(file_path), "--format", "json"])
|
||||
print(f"[INFO] 群文件已发送: {os.path.basename(file_path)}")
|
||||
|
||||
|
||||
def send_group_message(group_name, content="", file_path="", title="",
|
||||
at_all=False, at_open_ids="", record_dir=""):
|
||||
"""向群聊推送文本/文件(按群名解析 openconversation_id 后发送)。
|
||||
|
||||
Args:
|
||||
group_name: 群名(模糊搜索 → 精确同名过滤;歧义报错)
|
||||
content: 文本内容(发文本时必填;@ 场景需含 <@all> / <@openDingTalkId> 占位符)
|
||||
file_path: 本地文件地址(非空时发送文件;文本与文件可同时存在)
|
||||
title: 消息标题(可选,显示在消息列表)
|
||||
at_all: 是否 @所有人(仅群聊生效)
|
||||
at_open_ids: 逗号分隔的 openDingTalkId 列表(仅群聊生效)
|
||||
record_dir: 非空时写入 <record_dir>/YYYY-MM-DD/推送记录.csv
|
||||
|
||||
Returns:
|
||||
{"success": bool, "message": str}
|
||||
"""
|
||||
name = str(group_name or "").strip()
|
||||
try:
|
||||
if not name:
|
||||
return _record_and_return({"success": False, "message": "群名不能为空"},
|
||||
record_dir, "", name, content, file_path)
|
||||
if not content and not file_path:
|
||||
return _record_and_return({"success": False, "message": "文本内容与文件地址至少传一个"},
|
||||
record_dir, "", name, content, file_path)
|
||||
conv_id = resolve_group_id(name)
|
||||
print(f"[INFO] 目标群 openConversationId: {conv_id}")
|
||||
if file_path:
|
||||
file_path = str(file_path or "").strip()
|
||||
if not os.path.exists(file_path):
|
||||
return _record_and_return({"success": False, "message": f"文件不存在: {file_path}"},
|
||||
record_dir, "", name, content, file_path)
|
||||
send_group_file(conv_id, file_path)
|
||||
if content:
|
||||
send_group_text(conv_id, content, title=title, at_all=at_all, at_open_ids=at_open_ids)
|
||||
return _record_and_return({"success": True, "message": f"已向群「{name}」推送"},
|
||||
record_dir, "", name, content, file_path)
|
||||
except Exception as e:
|
||||
return _record_and_return({"success": False, "message": str(e)},
|
||||
record_dir, "", name, content, 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(可选):非空时写入 <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 _normalize_chat_type(chat_type: str) -> str:
|
||||
"""推送通道归一化:'single'/'单聊' → 'single';'group'/'群聊' → 'group'"""
|
||||
key = str(chat_type or "").strip().lower()
|
||||
if key in ("single", "单聊", "single_chat", "person", "个人", "私聊"):
|
||||
return "single"
|
||||
if key in ("group", "群聊", "group_chat", "群"):
|
||||
return "group"
|
||||
raise ValueError(f"未知推送通道「{chat_type}」,仅支持:single/单聊、group/群聊")
|
||||
|
||||
|
||||
def _item_is_group(item) -> bool:
|
||||
"""按消息结构自动判断推送通道:dict 含 group/群名 键 → 群聊;其余(元组 / msg_type dict)→ 单聊。"""
|
||||
return isinstance(item, dict) and bool(item.get("group") or item.get("群名"))
|
||||
|
||||
|
||||
def main(messages, record_dir="", chat_type=""):
|
||||
"""影刀自定义指令「37du钉钉推送」统一调用入口。
|
||||
|
||||
通道判定(二选一):
|
||||
- chat_type 显式传 'single'/'group':整批消息强制按该通道发送(兼容旧流程);
|
||||
- chat_type 留空(默认):按每条消息结构自动判断——dict 含 group/群名 键为群聊,其余为单聊。
|
||||
因此流程只需传消息列表,群聊消息自带 group 字段即可,无需单独配置 chat_type。
|
||||
|
||||
chat_type='single'/单聊:每项为五元组 (消息类型, 姓名, 工号, 消息内容, 文件地址),
|
||||
或 dict 含 msg_type/name/user_id(缺省字段按空处理):
|
||||
msg_type 'text'/'文本' 或 'file'/'文件'
|
||||
name 接收人姓名
|
||||
user_id 接收人工号
|
||||
content 消息内容(文本类型必填)
|
||||
file_path 文件地址(文件类型必填,可留空)
|
||||
chat_type='group'/群聊:每项支持 dict 或元组:
|
||||
dict: {"group": 群名, "content": 文本, "file_path": 文件,
|
||||
"title": 标题, "at_all": bool, "at_open_ids": "openId1,openId2"}
|
||||
元组: (群名, 文本内容, 文件地址, 标题, at_all, at_open_ids),后 4 项可省略
|
||||
record_dir(可选):非空时每条结果写入 <record_dir>/YYYY-MM-DD/推送记录.csv,
|
||||
并把记录文件路径写入影刀全局变量 push_record_path,供流程自行处理失败名单。
|
||||
逐条发送,返回: {"success": bool, "message": str, "results": [...]}
|
||||
"""
|
||||
forced_channel = _normalize_chat_type(chat_type) if chat_type else ""
|
||||
results = []
|
||||
for item in messages or []:
|
||||
if (forced_channel == "group") or (not forced_channel and _item_is_group(item)):
|
||||
# 群聊:按群名解析 openconversation_id 后发送(文本/文件可同时存在)
|
||||
if isinstance(item, dict):
|
||||
group = item.get("group") or item.get("群名") or ""
|
||||
content = item.get("content") or item.get("文本内容") or ""
|
||||
file_path = item.get("file_path") or item.get("文件地址") or ""
|
||||
title = item.get("title") or item.get("标题") or ""
|
||||
at_all = bool(item.get("at_all") or item.get("@所有人"))
|
||||
at_open_ids = item.get("at_open_ids") or item.get("@成员") or ""
|
||||
else:
|
||||
group = item[0] if len(item) > 0 else ""
|
||||
content = item[1] if len(item) > 1 else ""
|
||||
file_path = item[2] if len(item) > 2 else ""
|
||||
title = item[3] if len(item) > 3 else ""
|
||||
at_all = bool(item[4]) if len(item) > 4 else False
|
||||
at_open_ids = item[5] if len(item) > 5 else ""
|
||||
results.append(send_group_message(group, content, file_path, title,
|
||||
at_all, at_open_ids, record_dir))
|
||||
else:
|
||||
# 单聊:按姓名解析 openDingTalkId 后发送
|
||||
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 后调用
|
||||
# 单聊(chat_type 留空自动识别):
|
||||
# main([("文本", "姓名", "工号", "消息内容", ""),
|
||||
# ("文件", "姓名", "工号", "", r"文件绝对路径")])
|
||||
# 群聊(消息 dict 含 group 键自动识别,无需传 chat_type):
|
||||
# main([{"group": "群名", "content": "消息内容"},
|
||||
# {"group": "群名", "content": "", "file_path": r"文件绝对路径"}])
|
||||
messages = [
|
||||
{"msg_type": "text", "name": "夏一平", "user_id": "37036361", "content": "你好,这是由ai推送的文本消息"},
|
||||
# {"msg_type": "file", "name": "夏一平", "user_id": "37036361", "file_path": r"C:\Users\admin\Desktop\test.xlsx"},
|
||||
]
|
||||
result = main(messages)
|
||||
print(result)
|
||||
@@ -0,0 +1,330 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: dingtalk_robot.py
|
||||
@Description: 钉钉群机器人推送(影刀自定义指令模块源码,单一真源)。
|
||||
使用方式:main("需要推送的通知文本") 即可,标题/颜色/环境等均可选。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 dingtalk_robot,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加一个流程参数(文本类型,如 text),并勾选「参数可见」;
|
||||
4. 保存并「发版」;在需要钉钉群推送的应用中「获取指令」并安装;
|
||||
5. 流程中拖入该指令,把业务脚本输出的文本直接传给 text 参数即可。
|
||||
|
||||
推送原理(HTTP Webhook,零第三方依赖,仅标准库):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
|
||||
|
||||
约定:
|
||||
- 影刀运行环境无 .env 读取,故推送地址/加签密钥/页脚署名直接内联在下方
|
||||
「默认配置」区(单一真源),改推送目标时改常量即可;
|
||||
- 页脚署名默认 "小芒 任务调度平台":
|
||||
注意:钉钉机器人若配置了"自定义关键词"安全校验,
|
||||
页脚署名需包含该关键词(如 小芒)才会被接受。
|
||||
|
||||
入口:
|
||||
main(text, title='消息通知', status='info', webhook='', secret='', server_name='', env='prod')
|
||||
第一个参数传通知文本即可,其余可选。
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
# ==================== 默认配置 ====================
|
||||
DEFAULT_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=65dd3f38dea12d2419743aad62ed25f5544ae1ff2ff7d2f667682e0dc912ff6e'
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
# 测试环境配置(env='dev' 时使用;默认使用 DEFAULT_WEBHOOK )
|
||||
DEV_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
DEV_SECRET = '' # 测试环境加签密钥(未配置则不加签)
|
||||
DEV_SERVER_NAME = '小芒 任务调度平台'
|
||||
|
||||
# 环境 → 机器人配置(main 的 env 参数选择;缺省/未知环境回退 prod)
|
||||
ENV_CONFIGS = {
|
||||
'prod': {'webhook': DEFAULT_WEBHOOK, 'secret': DEFAULT_SECRET, 'server_name': DEFAULT_SERVER_NAME},
|
||||
'dev': {'webhook': DEV_WEBHOOK, 'secret': DEV_SECRET, 'server_name': DEV_SERVER_NAME},
|
||||
}
|
||||
|
||||
DEFAULT_TIMEOUT = 10 # HTTP 请求超时秒数
|
||||
DEFAULT_RETRY_TIMES = 3 # 失败重试次数(含首次)
|
||||
|
||||
# 通知状态 → 标题颜色
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff', # 蓝色
|
||||
'success': '#00b300', # 绿色
|
||||
'warning': '#ff9900', # 橙色
|
||||
'error': '#ff0000', # 红色
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""钉钉群机器人推送器。"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError('webhook 不能为空')
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
print(f"[WARN] 推送失败(第 {attempt + 1}/{DEFAULT_RETRY_TIMES} 次):{e}")
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def send(self, title, content, status='info', server_name=''):
|
||||
"""发送统一通知(Markdown:标题按状态着色,正文直接渲染,带页脚)。
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息正文(Markdown,引用块/加粗/超链接/列表等语法会被钉钉渲染)
|
||||
status: info|success|warning|error,决定标题颜色(默认 info)
|
||||
server_name: 页脚署名
|
||||
"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
footer = f"\n\n---\n\n###### {display_name} | {now}"
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += footer
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
print(f"[INFO] 钉钉机器人推送通知 [{status}]: {title}")
|
||||
self._post(payload)
|
||||
|
||||
def send_in_batches(self, title, content, status='info', server_name='',
|
||||
max_chars=15000):
|
||||
"""分批发送长内容(按行智能拆分,避免切断单行数据)。
|
||||
|
||||
当钉钉消息内容超过 max_chars 字符时,自动按行拆成多批发送,
|
||||
每批带「第 N/M 批」标题前缀,便于接收方识别。
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息正文(长文本)
|
||||
status: info|success|warning|error,决定标题颜色
|
||||
server_name: 页脚署名
|
||||
max_chars: 单批最大字符数(默认 15000,钉钉 Markdown 上限约 20000)
|
||||
"""
|
||||
lines = content.strip().split('\n')
|
||||
batches = []
|
||||
current_batch = []
|
||||
current_len = 0
|
||||
|
||||
for line in lines:
|
||||
line_len = len(line) + 1 # +1 for newline
|
||||
if current_len + line_len > max_chars and current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
current_batch = [line]
|
||||
current_len = line_len
|
||||
else:
|
||||
current_batch.append(line)
|
||||
current_len += line_len
|
||||
|
||||
if current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
|
||||
total = len(batches)
|
||||
for i, batch_content in enumerate(batches, 1):
|
||||
batch_title = f"{title}(第{i}/{total}批)" if total > 1 else title
|
||||
print(f"[INFO] 分批推送 {i}/{total}: {batch_title}")
|
||||
self.send(batch_title, batch_content, status=status,
|
||||
server_name=server_name)
|
||||
|
||||
|
||||
# ==================== 影刀自定义指令入口 ====================
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name='',
|
||||
env='prod', batch=False, max_chars=15000):
|
||||
"""
|
||||
影刀自定义指令「37du钉钉群机器人推送」调用入口。
|
||||
只需把要推送的通知文本传进来即可,例如:
|
||||
|
||||
main("订单同步失败,错误原因:接口超时")
|
||||
|
||||
支持逐条推送多条:text 传「文本列表」时按顺序逐条发送,列表项可为纯文本,
|
||||
也可为字典 {text, title?, status?, batch?} 自定义该条标题、颜色与格式。
|
||||
消息正文一律按 Markdown 渲染(引用块/加粗/超链接/列表等语法直接生效)。
|
||||
|
||||
块格式分组(推荐,调用方不关心分批):
|
||||
text 传字典列表,每项形如 {title, blocks, status?, batch_size?},
|
||||
blocks 为每条记录格式化好的 block 字符串列表。模块自动按 batch_size
|
||||
(默认 10)分批、每批带「第N/M批」标题并逐条推送。示例:
|
||||
main([
|
||||
{"title": "【请假审批】通过",
|
||||
"blocks": ["**🔹 张三‑特殊事假**\n> 工号:...", "..."]},
|
||||
])
|
||||
|
||||
可选参数:
|
||||
title: 消息标题(默认 消息通知)
|
||||
status: info|success|warning|error,决定标题颜色(默认 info)
|
||||
webhook: 机器人 webhook(缺省按 env 选择;显式传入则优先)
|
||||
secret: 加签密钥(缺省按 env 选择;显式传入则优先)
|
||||
server_name: 页脚署名(缺省按 env 选择;显式传入则优先)
|
||||
env: 环境 prod|dev,决定缺省 webhook/secret/server_name(默认 prod)
|
||||
batch: 是否启用分批发送(默认 False)。
|
||||
True: 当内容超长时自动按行拆成多批发送,每批标题带「第N/M批」;
|
||||
False: 单条发送(内容超长可能被钉钉截断或报错)。
|
||||
max_chars: 单批最大字符数(默认 15000,钉钉 Markdown 上限约 20000),
|
||||
仅在 batch=True 时生效。
|
||||
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
try:
|
||||
if text is None or (isinstance(text, str) and not str(text).strip()) \
|
||||
or (isinstance(text, list) and not text):
|
||||
return {'success': False, 'message': '通知文本不能为空'}
|
||||
env_key = (env or 'prod').strip().lower()
|
||||
if env_key not in ENV_CONFIGS:
|
||||
return {'success': False, 'message': f'未知环境 [{env_key}],可选:{" / ".join(ENV_CONFIGS)}'}
|
||||
cfg = ENV_CONFIGS[env_key]
|
||||
webhook = webhook or cfg['webhook']
|
||||
secret = secret or cfg['secret']
|
||||
server_name = server_name or cfg['server_name']
|
||||
if not webhook:
|
||||
return {'success': False, 'message': f'环境 [{env_key}] 的 webhook 未配置,请先在 dingtalk_robot.py 中填写'}
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
|
||||
items = text if isinstance(text, list) else [text]
|
||||
sent = 0
|
||||
last_title, last_status = title, status
|
||||
for item in items:
|
||||
if isinstance(item, dict) and item.get('blocks') is not None:
|
||||
# 块格式分组:调用方只传格式化好的 block 列表 + 标题,
|
||||
# 分批、加批次标题、逐条推送全部由本模块负责(调用方不关心批次)
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bs = int(item.get('batch_size', 10) or 10)
|
||||
for batch_content in compose_batch_messages(item['blocks'], ti, bs):
|
||||
robot.send(str(ti), str(batch_content), status=st,
|
||||
server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
continue
|
||||
if isinstance(item, dict):
|
||||
t = item.get('text')
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bc = item.get('batch', batch)
|
||||
mc = item.get('max_chars', max_chars)
|
||||
else:
|
||||
t, ti, st, bc, mc = item, title, status, batch, max_chars
|
||||
if t is None or not str(t).strip():
|
||||
continue
|
||||
if bc:
|
||||
robot.send_in_batches(str(ti), str(t), status=st,
|
||||
server_name=server_name, max_chars=mc)
|
||||
else:
|
||||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
if sent == 0:
|
||||
return {'success': False, 'message': '通知文本为空'}
|
||||
if len(items) == 1:
|
||||
return {'success': True, 'message': f'已推送通知 [{env_key}/{last_status}]:{last_title}'}
|
||||
return {'success': True, 'message': f'已推送 {sent} 条通知 [{env_key}]'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
|
||||
|
||||
# ==================== 块格式工具:调用方把每条记录格式化为 block 字符串列表,
|
||||
# 这里统一负责分批、加头尾、生成最终待推送的消息文本列表 ====================
|
||||
|
||||
def compose_batch_messages(blocks, title_prefix, batch_size=10):
|
||||
"""把块格式 block 字符串列表按 batch_size 条一批,生成带批次标题的消息文本列表。
|
||||
|
||||
Args:
|
||||
blocks: 每条记录格式化后的 block 字符串列表(调用方负责格式化业务字段)
|
||||
title_prefix: 批次标题前缀,如 "【请假审批】通过"
|
||||
batch_size: 每批最大条数(默认 10)
|
||||
|
||||
Returns:
|
||||
字符串列表,每项是一条完整的待推送 Markdown 文本,可直接传给 main(text=...)
|
||||
配合 batch=True 发送。
|
||||
"""
|
||||
if not blocks:
|
||||
return []
|
||||
result = []
|
||||
total_batches = (len(blocks) + batch_size - 1) // batch_size
|
||||
for bi in range(total_batches):
|
||||
batch = blocks[bi * batch_size:(bi + 1) * batch_size]
|
||||
header = f"###### {title_prefix}(第{bi + 1}/{total_batches}批)\n\n"
|
||||
# 钉钉中引用块尾行后需空行(双换行)再进入新标题,否则会紧贴渲染
|
||||
footer = f"\n\n###### 本批共{len(batch)}条"
|
||||
content = header + '\n\n'.join(batch) + footer
|
||||
result.append(content)
|
||||
return result
|
||||
|
||||
if __name__ == '__main__':
|
||||
# ==================== 本地自测/演示入口 ====================
|
||||
# 影刀中本模块作为「37du钉钉群机器人推送」指令源码,由流程传 text 参数调用 main();
|
||||
# 此处 __main__ 仅用于本地命令行自测:演示块格式分组用法(调用方只传 {title, blocks},
|
||||
# 分批/推送由模块内部负责)。注意:demo 数据为占位示例,勿用于生产;
|
||||
# env='dev' 走测试环境机器人,避免误发生产群。
|
||||
texts = [
|
||||
{
|
||||
"title": "【请假审批】通过",
|
||||
"blocks": [
|
||||
"**🔹 示例员工‑特殊事假**\n\n"
|
||||
"> 工号:00000000\n\n"
|
||||
"> 所属部门:示例部门\n\n"
|
||||
"> 开始日期:2026-08-19|开始段:上半段\n\n"
|
||||
"> 结束日期:2026-08-19|结束段:下半段\n\n"
|
||||
"> 请假天数:1.0\n\n"
|
||||
"> 实际上班天数:1\n\n"
|
||||
"> 填报天数:1.0\n\n",
|
||||
],
|
||||
},
|
||||
]
|
||||
notice_type = 'dev'
|
||||
print(main(texts, env=notice_type))
|
||||
@@ -0,0 +1,774 @@
|
||||
# -*- 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 模块源码,单一真源,已废弃)。
|
||||
作为「37du钉钉推送」影刀自定义指令的模块源码,
|
||||
供所有需要钉钉单人推送的影刀脚本/流程复用(周考勤、请假审批、加班审批、人事变动等),
|
||||
避免每个脚本各自内联 OCR 视觉发送逻辑。
|
||||
仅推送「联系人」(单聊);群消息已改用钉钉群机器人(webhook)推送,
|
||||
见同目录 dingtalk_robot.py(「37du钉钉群机器人推送」指令)。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 dingtalk_sender,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 messages(列表类型),每项为 (search_keyword, text, verify_keyword) 元组;
|
||||
4. 保存并「发版」;在需要钉钉推送的应用中「获取指令」并安装;
|
||||
5. 在流程中拖入该指令,把业务脚本输出的消息列表直接传给 messages 参数;
|
||||
指令返回 JSON:{"success": bool, "message": str, "results": [...]},可在后续流程中判断是否重试。
|
||||
|
||||
推送原理(OCR 视觉方案,与 app/utils/dingtalk_sender.py 一致):
|
||||
查找钉钉窗口 → 多策略激活到前台 → Ctrl+Shift+F 搜索联系人 → OCR 定位输入框
|
||||
→ 粘贴文本 → 回车发送。
|
||||
|
||||
依赖(影刀「Python包管理」安装;启动校验不懒加载):
|
||||
pip install pyautogui pywin32 pyperclip psutil
|
||||
pip install Pillow numpy rapidocr onnxruntime
|
||||
|
||||
入口:
|
||||
main(messages) 影刀自定义指令调用入口,直接传列表,每项为 (search_keyword, text, verify_keyword) 元组:
|
||||
search_keyword 联系人搜索关键字(支持工号,避免同名误选)
|
||||
text 要发送的消息内容
|
||||
verify_keyword 会话校验关键字(钉钉标题显示姓名,用工号搜索时传姓名校验,可选)
|
||||
仅推送联系人(单聊);群消息请改用同目录 dingtalk_robot.py(「37du钉钉群机器人推送」指令)。
|
||||
返回 JSON 安全 dict:{"success": bool, "message": str, "results": [...]}
|
||||
|
||||
python dingtalk_sender.py 独立运行(默认发送 __main__ 中的测试消息列表)
|
||||
|
||||
推送记录(可选,best-effort,不影响发送):
|
||||
1. 在 main 传入 record_dir(推送记录保存目录,空串=不记录)时,每次推送结果写入:
|
||||
记录目录/YYYY-MM-DD/推送记录.csv,列 = 推送时间, 工号, 姓名, 结果, 消息摘要;
|
||||
由调用方按场景传入,不写死(dingtalk_sender 供所有场景复用);
|
||||
2. 推送结束后把推送记录文件路径写入影刀全局变量 push_record_path,
|
||||
失败名单由流程自行读取记录文件处理(不在此生成名单文本)。
|
||||
"""
|
||||
import csv
|
||||
import os
|
||||
import time
|
||||
import ctypes
|
||||
from datetime import datetime
|
||||
|
||||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import pyautogui
|
||||
import win32gui
|
||||
import win32con
|
||||
import win32api
|
||||
import win32process
|
||||
import pyperclip
|
||||
import psutil
|
||||
from PIL import Image, ImageGrab
|
||||
import numpy as np
|
||||
from rapidocr import RapidOCR
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(钉钉推送指令要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install pyautogui pywin32 pyperclip psutil\n"
|
||||
" pip install Pillow numpy rapidocr onnxruntime\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print) ====================
|
||||
class _PrintLogger:
|
||||
"""影刀版无 logging 依赖,直接用 print 输出,行为与项目 logger 对齐。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
# ==================== 推送记录(main 传入 record_dir 时自动写入,best-effort) ====================
|
||||
_DT_RECORD_COLUMNS = ["推送时间", "工号", "姓名", "结果", "消息摘要"]
|
||||
_DT_SUMMARY_MAX_CHARS = 200
|
||||
_DT_GLV_RECORD_PATH = "push_record_path" # 推送记录文件路径(影刀全局变量,供流程自行取用/发送失败名单)
|
||||
|
||||
|
||||
def _dt_set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _dt_record_csv_path(record_dir):
|
||||
return os.path.join(record_dir, datetime.now().strftime("%Y-%m-%d"), "推送记录.csv")
|
||||
|
||||
|
||||
def _dt_record_push(keyword, name, result, text="", error="", record_dir=""):
|
||||
"""尽力追加一条推送记录到 <record_dir>/YYYY-MM-DD/推送记录.csv。
|
||||
record_dir 为空串时不记录(dingtalk_sender 供所有场景复用,由调用方传位置)。
|
||||
best-effort,任何失败都不影响推送。返回记录文件路径(未记录返回空串)。
|
||||
"""
|
||||
if not record_dir:
|
||||
return ""
|
||||
try:
|
||||
path = _dt_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(text or "").replace("\r\n", "\n").replace("\r", "\n")
|
||||
if len(summary) > _DT_SUMMARY_MAX_CHARS:
|
||||
summary = summary[:_DT_SUMMARY_MAX_CHARS] + "..."
|
||||
with open(path, "a", newline="", encoding="utf-8-sig") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=_DT_RECORD_COLUMNS)
|
||||
if new_file:
|
||||
writer.writeheader()
|
||||
writer.writerow({
|
||||
"推送时间": now,
|
||||
"工号": keyword,
|
||||
"姓名": name,
|
||||
"结果": result,
|
||||
"消息摘要": summary,
|
||||
})
|
||||
logger.info("推送记录已写入:%s(%s)", path, result)
|
||||
return path
|
||||
except Exception as e:
|
||||
logger.warning("推送记录写入失败(不影响推送):%s", e)
|
||||
return ""
|
||||
|
||||
|
||||
def _dt_write_record_path_to_glv(record_dir):
|
||||
"""把推送记录文件路径写入影刀全局变量 push_record_path。
|
||||
未传 record_dir 或记录失败时写空串,由流程自行读取记录文件处理失败名单。
|
||||
"""
|
||||
path = _dt_record_csv_path(record_dir) if record_dir else ""
|
||||
_dt_set_glv(_DT_GLV_RECORD_PATH, path)
|
||||
if path:
|
||||
logger.info("推送记录文件路径已写入全局变量 %s:%s", _DT_GLV_RECORD_PATH, path)
|
||||
|
||||
# ==================== 钉钉 OCR 视觉推送(单一真源,与 app/utils/dingtalk_sender.py 一致) ====================
|
||||
_DT_SEARCH_RETRY = 4 # 搜索并打开会话的外层重试次数(标签/会话校验的 OCR 偶发抖动由它兜底)
|
||||
_DT_RETRY_TIMES = 3
|
||||
_DT_TOP_HEIGHT_RATIO = 0.18
|
||||
_DT_CACHED_INPUT_POS = None # (rect, screen_x, screen_y) 输入框坐标缓存:同批次窗口未移动则复用,省去重复 OCR
|
||||
|
||||
|
||||
def _dt_warmup_ocr(inst):
|
||||
"""预热 OCR 模型:实例创建后跑一次空白图,提前加载 onnx 模型,
|
||||
避免真正识别时因模型加载/首轮推理过慢导致漏检(搜索面板「联系人」标签未识别到)。
|
||||
"""
|
||||
try:
|
||||
blank = Image.new("RGB", (64, 64), (255, 255, 255))
|
||||
inst(np.array(blank))
|
||||
logger.info("OCR 模型预热完成")
|
||||
except Exception as e:
|
||||
logger.warning("OCR 预热失败(不影响后续使用): %s", e)
|
||||
|
||||
|
||||
def _dt_get_ocr():
|
||||
"""获取 RapidOCR 实例(单例)。
|
||||
实例挂在函数自身属性上,避免依赖模块级可变全局变量:影刀指令运行环境对
|
||||
「模块级 global 变量」的作用域处理与标准 Python 不同(曾报
|
||||
name '_dt_ocr' is not defined),函数属性存放在函数对象自身,任何环境都可靠。
|
||||
"""
|
||||
inst = getattr(_dt_get_ocr, "_instance", None)
|
||||
if inst is None:
|
||||
inst = RapidOCR()
|
||||
_dt_get_ocr._instance = inst
|
||||
_dt_warmup_ocr(inst)
|
||||
return inst
|
||||
|
||||
|
||||
def _dt_get_process_name_by_pid(pid):
|
||||
try:
|
||||
return psutil.Process(pid).name()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _dt_find_dingtalk_window(include_hidden=True):
|
||||
"""查找钉钉主窗口句柄(排除 0 尺寸阴影/辅助窗口,只认 DingTalk 进程或主标题)。"""
|
||||
def has_valid_rect(hwnd):
|
||||
try:
|
||||
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
|
||||
return (right - left) > 0 and (bottom - top) > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def is_main_title(hwnd):
|
||||
return win32gui.GetWindowText(hwnd) in ('钉钉', 'DingTalk')
|
||||
|
||||
candidates = []
|
||||
|
||||
def enum_callback(hwnd, _):
|
||||
if not include_hidden and not win32gui.IsWindowVisible(hwnd):
|
||||
return True
|
||||
title = win32gui.GetWindowText(hwnd)
|
||||
if title == '钉钉' or title == 'DingTalk':
|
||||
candidates.append(hwnd)
|
||||
return True
|
||||
try:
|
||||
_, pid = win32process.GetWindowThreadProcessId(hwnd)
|
||||
proc_name = _dt_get_process_name_by_pid(pid)
|
||||
if proc_name and proc_name.lower() == 'dingtalk.exe':
|
||||
candidates.append(hwnd)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
win32gui.EnumWindows(enum_callback, None)
|
||||
|
||||
valid = [h for h in candidates if has_valid_rect(h)]
|
||||
if not valid:
|
||||
return None
|
||||
for h in valid:
|
||||
if is_main_title(h) and win32gui.IsWindowVisible(h):
|
||||
return h
|
||||
for h in valid:
|
||||
if is_main_title(h):
|
||||
return h
|
||||
for h in valid:
|
||||
if win32gui.IsWindowVisible(h):
|
||||
return h
|
||||
return valid[0]
|
||||
|
||||
|
||||
def _dt_activate_window(hwnd):
|
||||
"""确保窗口在前台(最小化、隐藏、托盘均可恢复)。
|
||||
|
||||
已在前台直接返回,绝不无谓地抢焦点——否则批量推送时会反复把焦点从用户正在
|
||||
操作的应用抢到钉钉(表现为「所有窗口失焦、点不动」)。
|
||||
|
||||
前台锁绕过:Windows 禁止后台进程直接 SetForegroundWindow(表现为窗口只在任务栏
|
||||
「闪现」却上不了前台)。用两步让它真正前置并保持:
|
||||
1. SPI_SETFOREGROUNDLOCKTIMEOUT=0:临时关闭系统「前台锁超时」,允许后台进程
|
||||
抢占前台(随后立即恢复原值,副作用最小);
|
||||
2. Alt 完整按下+抬起(down+up 对,不是孤立的 KEYUP):告诉系统「用户刚按了
|
||||
键」,进一步放宽前台锁;完整按键对不会遗留粘滞状态。
|
||||
"""
|
||||
if win32gui.GetForegroundWindow() == hwnd:
|
||||
return
|
||||
if win32gui.IsIconic(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
|
||||
time.sleep(0.1)
|
||||
if not win32gui.IsWindowVisible(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_SHOW)
|
||||
time.sleep(0.1)
|
||||
|
||||
# 前台锁绕过:临时关闭前台锁超时 + Alt 按下/抬起 + TOPMOST 强制置顶,
|
||||
# 让 SetForegroundWindow 真正生效(见函数头注释)。
|
||||
old_lock = None
|
||||
try:
|
||||
lock_val = ctypes.c_uint()
|
||||
if ctypes.windll.user32.SystemParametersInfoW(0x2000, 0, ctypes.byref(lock_val), 0): # SPI_GETFOREGROUNDLOCKTIMEOUT
|
||||
old_lock = lock_val.value
|
||||
ctypes.windll.user32.SystemParametersInfoW(0x2001, 0, 0, 0x2) # SPI_SETFOREGROUNDLOCKTIMEOUT=0, SPIF_SENDCHANGE
|
||||
time.sleep(0.05) # 等系统设置生效
|
||||
except Exception:
|
||||
old_lock = None
|
||||
try:
|
||||
win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_EXTENDEDKEY, 0) # Alt 按下
|
||||
win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0) # Alt 抬起
|
||||
win32gui.SetForegroundWindow(hwnd)
|
||||
win32gui.BringWindowToTop(hwnd)
|
||||
# TOPMOST 强制置顶再取消:后台进程也能把窗口顶到 Z 序最前,
|
||||
# 是对「SetForegroundWindow 被前台锁拒绝 → 任务栏闪现」最可靠的兜底。
|
||||
win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0,
|
||||
win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_SHOWWINDOW)
|
||||
win32gui.SetWindowPos(hwnd, win32con.HWND_NOTOPMOST, 0, 0, 0, 0,
|
||||
win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_SHOWWINDOW)
|
||||
finally:
|
||||
if old_lock is not None:
|
||||
try:
|
||||
ctypes.windll.user32.SystemParametersInfoW(0x2001, old_lock, 0, 0x2) # 恢复原超时
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def _dt_get_window_rect(hwnd):
|
||||
return win32gui.GetWindowRect(hwnd)
|
||||
|
||||
|
||||
def _dt_safe_click(x, y):
|
||||
"""异常安全的鼠标左键点击:任何情况(异常/打断)都保证左键松开。
|
||||
不用 pyautogui.click——它在 mouseDown 与 mouseUp 之间被打断时会留下卡死的左键
|
||||
(症状:屏幕点不动、滚轮失效,必须重启才能恢复)。
|
||||
实现:SetCursorPos 瞬移指针 + mouse_event 按下/抬起(finally 兜底松开)。
|
||||
"""
|
||||
ctypes.windll.user32.SetCursorPos(int(x), int(y))
|
||||
time.sleep(0.05)
|
||||
try:
|
||||
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
|
||||
time.sleep(0.05)
|
||||
finally:
|
||||
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
|
||||
time.sleep(0.05)
|
||||
|
||||
|
||||
def _dt_release_mouse():
|
||||
"""安全兜底:补发左键松开,清掉历史遗留的卡死左键状态(幂等,无害)。"""
|
||||
try:
|
||||
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _dt_find_dingtalk_main_window():
|
||||
"""只找钉钉主窗口(标题为「钉钉/DingTalk」且有效尺寸)。
|
||||
优先返回可见的主窗口;找不到可见的再回退到任意有效尺寸的主标题窗口。
|
||||
用于「可见性」判断,避免 _dt_find_dingtalk_window 偶发选中搜索/辅助/阴影窗口,
|
||||
导致把已显示的钉钉误判为隐藏,从而误按 Ctrl+Alt+D 切换键把它切到托盘。
|
||||
"""
|
||||
visible_main = None
|
||||
any_main = None
|
||||
|
||||
def enum_callback(hwnd, _):
|
||||
nonlocal visible_main, any_main
|
||||
if win32gui.GetWindowText(hwnd) not in ('钉钉', 'DingTalk'):
|
||||
return True
|
||||
try:
|
||||
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
|
||||
if (right - left) <= 0 or (bottom - top) <= 0:
|
||||
return True
|
||||
if any_main is None:
|
||||
any_main = hwnd
|
||||
if win32gui.IsWindowVisible(hwnd) and visible_main is None:
|
||||
visible_main = hwnd
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
win32gui.EnumWindows(enum_callback, None)
|
||||
return visible_main or any_main
|
||||
|
||||
|
||||
def _dt_is_dingtalk_foreground():
|
||||
"""钉钉主窗口是否在前台:直接比对前台窗口句柄 == 钉钉主窗口句柄(毫秒级,比标题匹配更准)。"""
|
||||
main_hwnd = _dt_find_dingtalk_main_window()
|
||||
return bool(main_hwnd) and win32gui.GetForegroundWindow() == main_hwnd
|
||||
|
||||
|
||||
def _dt_capture_region(x, y, w, h):
|
||||
if w <= 0 or h <= 0:
|
||||
logger.warning("截图区域无效: (%s, %s, %s, %s),跳过", x, y, w, h)
|
||||
return None
|
||||
img = ImageGrab.grab(bbox=(x, y, x + w, y + h))
|
||||
if img is None or img.size[0] == 0 or img.size[1] == 0:
|
||||
logger.warning("抓取图像为空")
|
||||
return None
|
||||
return img
|
||||
|
||||
|
||||
def _dt_ocr_image(img):
|
||||
if img is None:
|
||||
return []
|
||||
img_np = np.array(img)
|
||||
result = _dt_get_ocr()(img_np)
|
||||
ocr_data = []
|
||||
if result is not None and result.boxes is not None:
|
||||
for box, text, score in zip(result.boxes, result.txts, result.scores):
|
||||
xs = [p[0] for p in box]
|
||||
ys = [p[1] for p in box]
|
||||
x1, y1 = min(xs), min(ys)
|
||||
x2, y2 = max(xs), max(ys)
|
||||
ocr_data.append((text, (x1, y1, x2, y2)))
|
||||
return ocr_data
|
||||
|
||||
|
||||
def _dt_find_text_center(ocr_data, target_text):
|
||||
for text, (x1, y1, x2, y2) in ocr_data:
|
||||
if target_text in text:
|
||||
return (x1 + x2) // 2, (y1 + y2) // 2
|
||||
return None
|
||||
|
||||
|
||||
def _dt_analyze_top_region(hwnd):
|
||||
"""截取窗口顶部区域并 OCR,返回 (text, (x1,y1,x2,y2)) 列表。
|
||||
顶部区域「截屏+OCR」样板代码的唯一封装点(DRY),供 _dt_wait_for_tab /
|
||||
_dt_is_chat_opened / _dt_focus_search_box / _dt_search_and_open 复用,
|
||||
避免各处重复写 rect 计算 + 截图 + OCR 三件套。
|
||||
"""
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO))
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
return _dt_ocr_image(img)
|
||||
|
||||
|
||||
def _dt_wait_for_tab(hwnd, expected_tab):
|
||||
"""顶部区域 OCR 检测 expected_tab 标签(如「联系人」)。
|
||||
快速失败(fail-fast):最多 OCR 2 次(即时 + 0.3s 重试),失败交由外层
|
||||
_DT_SEARCH_RETRY 循环兜底重试,不再长时间轮询死磕 OCR(OCR 是重型计算,按次计费)。
|
||||
"""
|
||||
for i in range(2):
|
||||
ocr_data = _dt_analyze_top_region(hwnd)
|
||||
if _dt_find_text_center(ocr_data, expected_tab):
|
||||
logger.info("检测到'%s'标签", expected_tab)
|
||||
return True
|
||||
if i == 0:
|
||||
time.sleep(0.3) # 给 UI 渲染一个短暂重试机会
|
||||
logger.warning("未检测到'%s'标签", expected_tab)
|
||||
return False
|
||||
|
||||
|
||||
def _dt_is_chat_opened(hwnd, target_name):
|
||||
"""顶部区域 OCR 校验会话标题是否包含 target_name。
|
||||
快速失败(fail-fast):最多 OCR 2 次(即时 + 0.3s 重试),失败由
|
||||
_dt_search_and_open 的外层 _DT_SEARCH_RETRY 循环兜底重试,不再原地死循环轮询。
|
||||
"""
|
||||
for i in range(2):
|
||||
ocr_data = _dt_analyze_top_region(hwnd)
|
||||
for text, _ in ocr_data:
|
||||
if target_name in text:
|
||||
logger.debug("标题识别到: '%s'", text)
|
||||
return True
|
||||
if i == 0:
|
||||
time.sleep(0.3)
|
||||
return False
|
||||
|
||||
|
||||
def _dt_search_and_open(hwnd, search_keyword, verify_keyword=None):
|
||||
"""搜索并打开指定联系人的会话(仅单聊;群消息改用钉钉群机器人 webhook 推送)。
|
||||
|
||||
search_keyword 为搜索关键字(支持工号,避免同名人员误选,如搜索 10086);
|
||||
verify_keyword 为打开会话后校验标题用的关键字(钉钉会话标题显示的是联系人姓名
|
||||
而非工号,故同名人场景需传姓名用于校验;不传则回退为 search_keyword)。
|
||||
|
||||
简化设计:不再用 Ctrl+Shift+F 快捷键 + OCR 兜底的双路径(快捷键会被前台锁/输入法
|
||||
干扰且逻辑重复),一律 OCR 点击主界面搜索框(_dt_focus_search_box)→ 输入关键字 →
|
||||
回车。每个 attempt 开头 esc 复位,避免上一个 attempt 残留的搜索面板遮住占位文本。
|
||||
|
||||
快速失败设计(fail-fast):标签检测(_dt_wait_for_tab)与会话校验(_dt_is_chat_opened)
|
||||
都只做最多 2 次 OCR(即时 + 0.3s 重试),失败不再原地长时间轮询死磕 OCR,
|
||||
而是 continue 回到外层 _DT_SEARCH_RETRY 循环重试(避免「会话校验偶发漏检 →
|
||||
整条消息永久失败」的致命坑)。
|
||||
"""
|
||||
for attempt in range(_DT_SEARCH_RETRY):
|
||||
_dt_activate_window(hwnd)
|
||||
# 复位:关闭可能残留的搜索面板,让「搜索或提问」占位文本回到可见
|
||||
pyautogui.press('esc')
|
||||
time.sleep(0.3)
|
||||
if not _dt_focus_search_box(hwnd):
|
||||
logger.warning("未识别到搜索框(第%d次),外层重试", attempt + 1)
|
||||
continue
|
||||
|
||||
# 输入关键字并搜索
|
||||
pyautogui.hotkey('ctrl', 'a')
|
||||
pyautogui.press('delete')
|
||||
pyperclip.copy(search_keyword)
|
||||
pyautogui.hotkey('ctrl', 'v')
|
||||
time.sleep(0.2)
|
||||
pyautogui.press('enter')
|
||||
logger.info("搜索 '%s' (尝试 %d)", search_keyword, attempt + 1)
|
||||
time.sleep(0.5)
|
||||
if not _dt_wait_for_tab(hwnd, "联系人"):
|
||||
logger.warning("未检测到'联系人'标签(第%d次),外层重试", attempt + 1)
|
||||
continue
|
||||
|
||||
# 点击「联系人」标签 → 回车打开第一个匹配项
|
||||
ocr_data = _dt_analyze_top_region(hwnd)
|
||||
left, top, _, _ = _dt_get_window_rect(hwnd)
|
||||
pos = _dt_find_text_center(ocr_data, "联系人")
|
||||
if pos:
|
||||
cx, cy = pos
|
||||
_dt_safe_click(left + cx, top + cy)
|
||||
logger.info("点击'联系人'标签")
|
||||
else:
|
||||
logger.warning("未识别'联系人'标签")
|
||||
time.sleep(0.3)
|
||||
|
||||
pyautogui.press('enter')
|
||||
logger.info("打开第一个匹配项")
|
||||
time.sleep(1.0)
|
||||
|
||||
# 会话校验:最多 2 次 OCR,失败继续外层重试(不再原地死循环轮询)
|
||||
if _dt_is_chat_opened(hwnd, verify_keyword or search_keyword):
|
||||
logger.info("成功进入会话 '%s'", verify_keyword or search_keyword)
|
||||
return True
|
||||
logger.warning("未检测到会话名 '%s',外层重试", verify_keyword or search_keyword)
|
||||
continue
|
||||
logger.error("搜索并打开会话失败(重试 %d 次后仍失败)", _DT_SEARCH_RETRY)
|
||||
return False
|
||||
|
||||
|
||||
def _dt_find_input_box_by_ocr(hwnd):
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
bottom_region_top = top + int(height * 0.6)
|
||||
bottom_region_height = int(height * 0.4)
|
||||
img = _dt_capture_region(left, bottom_region_top, width, bottom_region_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
keywords = ["请输入消息", "发送消息", "输入消息", "说点什么"]
|
||||
for keyword in keywords:
|
||||
pos = _dt_find_text_center(ocr_data, keyword)
|
||||
if pos:
|
||||
cx, cy = pos
|
||||
screen_x = left + cx
|
||||
screen_y = bottom_region_top + cy
|
||||
logger.info("定位输入框: '%s' 坐标 (%s, %s)", keyword, screen_x, screen_y)
|
||||
return screen_x, screen_y
|
||||
logger.warning("未识别到输入框提示")
|
||||
return None
|
||||
|
||||
|
||||
def _dt_focus_input_box(hwnd):
|
||||
"""定位并点击输入框,使其获得焦点。
|
||||
优化:批量推送时钉钉窗口位置/尺寸不变,输入框在窗口内的位置也固定,
|
||||
因此首次 OCR 定位后按窗口 rect 缓存绝对坐标,后续会话直接复用缓存点击,
|
||||
省去每人一次的输入框 OCR;窗口被拖动/缩放(rect 变化)时缓存自动失效重定位。
|
||||
"""
|
||||
global _DT_CACHED_INPUT_POS
|
||||
rect = _dt_get_window_rect(hwnd)
|
||||
cached = _DT_CACHED_INPUT_POS
|
||||
if cached and cached[0] == rect:
|
||||
_, cx, cy = cached
|
||||
_dt_safe_click(cx, cy)
|
||||
logger.info("使用缓存输入框坐标 (%s, %s)", cx, cy)
|
||||
return True
|
||||
if cached:
|
||||
logger.info("窗口位置/尺寸变化,输入框缓存失效,重新 OCR 定位")
|
||||
|
||||
input_pos = _dt_find_input_box_by_ocr(hwnd)
|
||||
if input_pos:
|
||||
_DT_CACHED_INPUT_POS = (rect, input_pos[0], input_pos[1])
|
||||
_dt_safe_click(input_pos[0], input_pos[1])
|
||||
return True
|
||||
left, top, right, bottom = rect
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
_dt_safe_click(left + width // 2, top + height - 60)
|
||||
logger.warning("使用固定坐标点击输入框")
|
||||
return False
|
||||
|
||||
|
||||
def _dt_send_hotkey_to_activate():
|
||||
logger.info("尝试快捷键 Ctrl+Alt+D 激活")
|
||||
pyautogui.hotkey('ctrl', 'alt', 'd')
|
||||
time.sleep(0.8)
|
||||
|
||||
|
||||
def _dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10):
|
||||
"""快捷键主力 + 窗口状态检测兜底(不再用 Win32 SetForegroundWindow 前置——
|
||||
本机实测后台进程调它会被前台锁拒绝,表现为窗口只在任务栏「闪现」却上不了前台;
|
||||
而 Ctrl+Alt+D 是钉钉注册的全局快捷键,钉钉自己响应用户级热键唤出,能真正前置)。
|
||||
|
||||
Ctrl+Alt+D 是「唤起/隐藏主面板」的【切换】键——窗口已显示时按下会把它隐藏到托盘
|
||||
(原始 bug「发着发着钉钉窗口突然隐藏且再也唤不回来」即因此触发)。
|
||||
因此严格依赖窗口状态检测,绝不盲目按键:
|
||||
1. 已在前台 → 直接成功,绝不按键、绝不抢焦点(否则批量推送反复抢焦点
|
||||
→ 「所有窗口失焦、点不动」);
|
||||
2. 主窗口不可见(托盘/最小化)→ 按 Ctrl+Alt+D 唤出(唤出时钉钉自动前置),
|
||||
每次按键后自校验是否变为可见;
|
||||
3. 主窗口可见但不前台 → 先按一次切到托盘,确认隐藏后再按一次唤出,
|
||||
借「唤出」时机把窗口带到前台(直接按键会把可见窗口切隐藏,绝不可行);
|
||||
若按键后状态与预期不符(快捷键未生效)立即补按纠正,绝不让窗口停在隐藏态;
|
||||
4. 快速失败:最多 3 轮「唤出 + 稳定校验」(激活后稍等再比对前台句柄,
|
||||
避免「闪现」瞬间误判成功),尽快给出结论。
|
||||
"""
|
||||
def find_main():
|
||||
return _dt_find_dingtalk_main_window()
|
||||
|
||||
def main_visible():
|
||||
main = find_main()
|
||||
return bool(main) and win32gui.IsWindowVisible(main)
|
||||
|
||||
def wait_state(want_visible, max_wait=1.5):
|
||||
end = time.time() + max_wait
|
||||
while time.time() < end:
|
||||
if main_visible() == want_visible:
|
||||
return True
|
||||
time.sleep(0.2)
|
||||
return False
|
||||
|
||||
def stable_foreground():
|
||||
# 稳定校验:激活动作后稍等再比对前台句柄,避免「闪现」瞬间误判成功
|
||||
time.sleep(0.35)
|
||||
main = find_main()
|
||||
return bool(main) and win32gui.GetForegroundWindow() == main
|
||||
|
||||
if _dt_is_dingtalk_foreground():
|
||||
logger.info("钉钉已在最前,跳过激活")
|
||||
return True
|
||||
|
||||
for _ in range(3): # 快速失败:最多 3 轮「唤出 + 稳定校验」
|
||||
if main_visible():
|
||||
# 可见但不前台:先切隐藏,确认后再唤出(借唤出时机前置)
|
||||
_dt_send_hotkey_to_activate()
|
||||
if not wait_state(False):
|
||||
# 按键后仍可见(快捷键未生效/状态异常)→ 不盲目再按,重试一轮
|
||||
logger.warning("切换隐藏未生效,重试")
|
||||
time.sleep(0.3)
|
||||
continue
|
||||
_dt_send_hotkey_to_activate() # 从托盘唤出(此时钉钉自动前置)
|
||||
if stable_foreground():
|
||||
logger.info("激活成功(快捷键唤出)")
|
||||
return True
|
||||
time.sleep(0.2)
|
||||
raise RuntimeError("所有激活策略失败")
|
||||
|
||||
|
||||
def _dt_find_hwnd_or_raise():
|
||||
hwnd = _dt_find_dingtalk_window(include_hidden=True)
|
||||
if not hwnd:
|
||||
dingtalk_running = any(p.name().lower() == 'dingtalk.exe' for p in psutil.process_iter())
|
||||
if not dingtalk_running:
|
||||
raise RuntimeError("钉钉进程未运行,请手动启动并登录")
|
||||
else:
|
||||
raise RuntimeError("找到进程但无窗口,请手动激活")
|
||||
return hwnd
|
||||
|
||||
|
||||
def _dt_focus_search_box(hwnd):
|
||||
"""OCR 定位主界面搜索框(占位文本「搜索或提问」)并点击一次,
|
||||
让钉钉把焦点放到搜索框(比纯快捷键更稳,避免 Ctrl+Shift+F 失败),
|
||||
同时该次识别本身就是一次真实 OCR 预热。
|
||||
"""
|
||||
ocr_data = _dt_analyze_top_region(hwnd)
|
||||
if not ocr_data:
|
||||
return False
|
||||
left, top, _, _ = _dt_get_window_rect(hwnd)
|
||||
for keyword in ("搜索或提问", "搜索", "提问"):
|
||||
pos = _dt_find_text_center(ocr_data, keyword)
|
||||
if pos:
|
||||
cx, cy = pos
|
||||
screen_x, screen_y = left + cx, top + cy
|
||||
_dt_safe_click(screen_x, screen_y)
|
||||
logger.info("已点击搜索框: '%s' 坐标 (%s, %s)", keyword, screen_x, screen_y)
|
||||
time.sleep(0.3)
|
||||
return True
|
||||
logger.warning("未识别到搜索框占位文本(搜索或提问/搜索/提问)")
|
||||
return False
|
||||
|
||||
|
||||
def _dt_send_text_to_person(search_keyword, text, verify_keyword=None):
|
||||
"""向指定联系人发送文本(OCR 视觉方案):查找窗口→多策略激活→搜索打开会话→定位输入框→粘贴发送。
|
||||
search_keyword 为搜索关键字(支持工号);verify_keyword 为会话标题校验关键字(钉钉标题显示姓名,
|
||||
同名人时传姓名校验;不传则用 search_keyword 校验),二者分离避免同名误选。
|
||||
"""
|
||||
if not text or not text.strip():
|
||||
raise ValueError("text 不能为空")
|
||||
|
||||
_dt_release_mouse() # 清掉可能的卡死左键,再开始本消息
|
||||
for attempt in range(_DT_RETRY_TIMES):
|
||||
try:
|
||||
hwnd = _dt_find_hwnd_or_raise()
|
||||
_dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10)
|
||||
hwnd = _dt_find_dingtalk_window(include_hidden=True) or hwnd
|
||||
|
||||
if not _dt_search_and_open(hwnd, search_keyword, verify_keyword):
|
||||
raise RuntimeError("打开联系人会话失败")
|
||||
|
||||
_dt_focus_input_box(hwnd)
|
||||
time.sleep(0.3)
|
||||
|
||||
pyperclip.copy(text)
|
||||
pyautogui.hotkey('ctrl', 'v')
|
||||
time.sleep(0.2)
|
||||
pyautogui.press('enter')
|
||||
logger.info("发送成功:%s...", text[:30])
|
||||
return True
|
||||
|
||||
except RuntimeError as e:
|
||||
logger.error(str(e))
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error("第%d次尝试失败:%s", attempt + 1, e)
|
||||
time.sleep(2)
|
||||
|
||||
raise RuntimeError("重试 %d 次后失败" % _DT_RETRY_TIMES)
|
||||
|
||||
|
||||
def send_dingtalk_text(search_keyword, text, verify_keyword=None):
|
||||
"""推送文本到钉钉联系人(OCR 视觉方案,仅单聊)。供业务脚本 import 调用。
|
||||
search_keyword 为搜索关键字(支持工号);verify_keyword 为会话标题校验关键字(可选,同名人传姓名)。
|
||||
群消息请改用 dingtalk_robot(钉钉群机器人 webhook)推送。
|
||||
"""
|
||||
return _dt_send_text_to_person(search_keyword, text, verify_keyword)
|
||||
|
||||
|
||||
# ==================== 影刀自定义指令入口 ====================
|
||||
def main(messages, record_dir=""):
|
||||
"""
|
||||
影刀自定义指令「37du钉钉推送」调用入口。
|
||||
直接传列表,每项为 (search_keyword, text, verify_keyword) 元组,verify_keyword 可省略:
|
||||
search_keyword 联系人搜索关键字(支持工号,避免同名误选)
|
||||
text 要发送的消息内容
|
||||
verify_keyword 会话校验关键字(可选;钉钉标题显示姓名,用工号搜索时传姓名校验)
|
||||
record_dir(可选):推送记录保存目录,非空时每次推送结果写入
|
||||
<record_dir>/YYYY-MM-DD/推送记录.csv(列=推送时间, 工号, 姓名, 结果, 消息摘要);
|
||||
空串=不记录。由调用方按场景传入,不写死(本指令供所有场景复用)。
|
||||
仅推送联系人(单聊);群消息请改用 dingtalk_robot.py(「37du钉钉群机器人推送」指令)。
|
||||
每次推送自动写入推送记录(见模块头说明);推送记录文件路径写入全局变量 push_record_path,
|
||||
由流程自行读取记录文件处理失败名单。
|
||||
返回: {"success": bool, "message": str, "results": [...]}
|
||||
"""
|
||||
results = []
|
||||
_total_start = time.time()
|
||||
for item in messages:
|
||||
search_keyword = str(item[0] or "").strip()
|
||||
text = str(item[1] or "")
|
||||
verify_keyword = str(item[2] or "").strip() or None if len(item) > 2 else None
|
||||
name = verify_keyword or search_keyword
|
||||
if not text.strip():
|
||||
results.append({"success": False, "message": "参数 text 不能为空"})
|
||||
_dt_record_push(search_keyword, name, "失败", text,
|
||||
error="参数 text 不能为空", record_dir=record_dir)
|
||||
continue
|
||||
if not search_keyword:
|
||||
results.append({"success": False, "message": "参数 search_keyword 不能为空"})
|
||||
_dt_record_push(search_keyword, name, "失败", text,
|
||||
error="参数 search_keyword 不能为空", record_dir=record_dir)
|
||||
continue
|
||||
_t_start = time.time()
|
||||
try:
|
||||
send_dingtalk_text(search_keyword, text, verify_keyword)
|
||||
_t_cost = time.time() - _t_start
|
||||
logger.info("本条推送耗时 %.1f 秒(%s)", _t_cost, search_keyword)
|
||||
results.append({"success": True, "message": f"已向 {search_keyword} 发送成功",
|
||||
"cost_sec": round(_t_cost, 1)})
|
||||
_dt_record_push(search_keyword, name, "成功", text, record_dir=record_dir)
|
||||
except Exception as e:
|
||||
_t_cost = time.time() - _t_start
|
||||
logger.error("本条推送失败,耗时 %.1f 秒(%s):%s", _t_cost, search_keyword, e)
|
||||
results.append({"success": False, "message": str(e), "cost_sec": round(_t_cost, 1)})
|
||||
_dt_record_push(search_keyword, name, "失败", text, error=str(e), record_dir=record_dir)
|
||||
_total_cost = time.time() - _total_start
|
||||
logger.info("全部推送完成,总耗时 %.1f 秒,共 %d 条", _total_cost, len(results))
|
||||
ok = sum(1 for r in results if r.get("success"))
|
||||
# 推送记录文件路径写入影刀全局变量,由流程自行读取记录文件处理失败名单
|
||||
_dt_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__":
|
||||
messages = [("37036361", "【37du钉钉推送·测试1】你好,这是一条连通性测试消息。", "夏一平"),("37036361", "【37du钉钉推送·测试2】你好,这是第二条测试消息。", "夏一平")]
|
||||
# 本地自测:传记录目录则写入推送记录;留空则不记录
|
||||
print(main(messages, record_dir="D:\资料\人资\考勤异常\推送记录"))
|
||||
@@ -0,0 +1,447 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: hr_login.py
|
||||
@Description: HR 登录自定义指令(影刀编码版 Python 模块源码)。
|
||||
作为「37duHR登录」影刀自定义指令的模块源码(单一真源),
|
||||
供所有 HR 系统影刀脚本复用,避免每个脚本各自内联滑块登录逻辑。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 hr_login,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json,
|
||||
各影刀业务脚本自行用这些 cookies 构建 requests.Session。
|
||||
|
||||
配置(已直接内置在模块源码中,无需 .env / 环境变量):
|
||||
LOGIN_URL=HR 登录页 URL
|
||||
SUCCESS_KEYWORD=HR 登录成功后 URL 关键字
|
||||
USERNAME=用户名
|
||||
PASSWORD=密码
|
||||
hr_validate_url=(可选,.env/系统变量)HR 会话校验接口 URL;默认使用 getCurUserInfo 接口
|
||||
hr_captcha_debug_dir=(可选)滑块调试图片输出目录;不设置则不落盘
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests python-dotenv opencv-python numpy Pillow
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
python hr_login.py 独立运行(等价于 main({"force": true}))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import random
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_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')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 直接内置配置:影刀分享出去的脚本找不到 .env,登录参数直接写死
|
||||
LOGIN_URL = 'https://hr.37du.co/RedseaPlatform/'
|
||||
SUCCESS_KEYWORD = 'https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic'
|
||||
USERNAME = '37036273'
|
||||
PASSWORD = '***REMOVED***'
|
||||
|
||||
# HR 会话校验接口:cookies 有效时返回 JSON,失效时返回登录页等非 JSON
|
||||
GET_CUR_USER_INFO_URL = "https://hr.37du.co/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
|
||||
LOGIN_BTN = "@id=login-btn"
|
||||
ACCOUNT_INPUT = "@id=j_username"
|
||||
PASSWORD_INPUT = "@id=j_password_2"
|
||||
CAPTCHA_CONTAINER = ".:comImageValidate"
|
||||
SLIDER_BTN = ".:v_rightBtn"
|
||||
BG_IMG = ".imgBg"
|
||||
SLIDER_IMG = "css:div.imgBg_3 > img"
|
||||
|
||||
RETRY_MAX = 5
|
||||
TIMEOUT = 10
|
||||
HEADLESS = False
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(登录成功后缓存,下次免登录复用) ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||||
def _is_hr_session_valid():
|
||||
"""API 轻量校验 HR cookies:请求 hr_validate_url(默认 getCurUserInfo 接口),
|
||||
返回 JSON 视为 cookies 有效;返回登录页等非 JSON 即视为失效。
|
||||
|
||||
与业务脚本(attendance_abnormal/bank_card_check 等)使用同一套构建方式:
|
||||
requests.Session + Chrome UA/Content-Type + 仅注入 37du.co 域 cookies。
|
||||
"""
|
||||
validate_url = os.getenv('hr_validate_url', '').strip() or GET_CUR_USER_INFO_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.post(validate_url, data={}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 滑块匹配(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
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:
|
||||
print(f"拖拽异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 验证码处理(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def handle_captcha(page):
|
||||
for retry in range(RETRY_MAX):
|
||||
print(f"\n--- 第 {retry + 1} 次尝试验证 ---")
|
||||
try:
|
||||
container = page.ele(CAPTCHA_CONTAINER, timeout=TIMEOUT)
|
||||
if not container:
|
||||
print("验证码容器未出现")
|
||||
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:
|
||||
print("找不到背景图/滑块小图元素")
|
||||
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
|
||||
|
||||
if not bg_screenshot or not slider_screenshot:
|
||||
print("截图数据为空")
|
||||
continue
|
||||
|
||||
distance_phys = match_slider_dual(bg_screenshot, slider_screenshot)
|
||||
dpr = page.run_js('return window.devicePixelRatio') or 1
|
||||
distance_css = distance_phys / dpr
|
||||
print(f" 匹配距离 {distance_phys}px -> CSS {distance_css:.1f}px")
|
||||
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if btn and perform_slide(page, btn, distance_css):
|
||||
time.sleep(2)
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
return True
|
||||
if not page.ele(CAPTCHA_CONTAINER, timeout=1):
|
||||
return True
|
||||
time.sleep(2)
|
||||
except Exception as e:
|
||||
print(f"异常:{e}")
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login():
|
||||
"""打开浏览器完成登录(含滑块),成功保存 cookies。"""
|
||||
co = ChromiumOptions()
|
||||
if HEADLESS:
|
||||
co.headless()
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(2)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("已登录")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
|
||||
account = page.ele(ACCOUNT_INPUT)
|
||||
if not account:
|
||||
print("找不到账号输入框")
|
||||
return False
|
||||
account.clear()
|
||||
account.input(USERNAME)
|
||||
time.sleep(0.5)
|
||||
|
||||
pwd = page.ele(PASSWORD_INPUT)
|
||||
if not pwd:
|
||||
print("找不到密码输入框")
|
||||
return False
|
||||
pwd.clear()
|
||||
pwd.input(PASSWORD)
|
||||
time.sleep(0.5)
|
||||
|
||||
login_btn = page.ele(LOGIN_BTN)
|
||||
if not login_btn:
|
||||
print("找不到登录按钮")
|
||||
return False
|
||||
login_btn.click()
|
||||
time.sleep(3)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("登录成功(无滑块)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
|
||||
if handle_captcha(page):
|
||||
print("登录成功(验证通过)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
print("登录失败")
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 HR 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||||
_set_login_state(False)
|
||||
|
||||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_url / hr_target_url_keyword 未配置且无内置默认值)", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_username / hr_login_password 未配置且无内置默认值)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_hr_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 HR 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = _do_login()
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败(滑块验证未通过)", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37duHR登录」调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": False})
|
||||
print("最终结果:", result)
|
||||
@@ -0,0 +1,239 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: oa_login.py
|
||||
@Description: OA 登录自定义指令(影刀编码版 Python 模块源码)。
|
||||
作为「37duOA登录」影刀自定义指令的模块源码(单一真源),
|
||||
供所有 OA 系统影刀脚本(请假/加班/社保增减等)复用。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 oa_login,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\oa_cookies.json,
|
||||
各影刀业务脚本自行用这些 cookies 构建 SessionPage / requests.Session。
|
||||
|
||||
配置(已直接内置在模块源码中,无需 .env / 环境变量):
|
||||
LOGIN_URL=OA 登录页 URL
|
||||
SUCCESS_KEYWORD=OA 登录成功后 URL 关键字
|
||||
USERNAME=用户名
|
||||
PASSWORD=密码
|
||||
oa_validate_url=(可选,.env/系统变量)轻量会话校验接口 URL;默认使用 sumTodoCount 待办统计接口
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests python-dotenv
|
||||
|
||||
入口:
|
||||
main(force=True) 影刀自定义指令调用入口,force 传 True/False(是否强制重新登录),返回 JSON 安全 dict
|
||||
python oa_login.py 独立运行(等价于 main(force=True))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
|
||||
from DrissionPage import ChromiumPage
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_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')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 直接内置配置:影刀分享出去的脚本找不到 .env,登录参数直接写死
|
||||
LOGIN_URL = 'https://oa.37du.co/login.jsp'
|
||||
SUCCESS_KEYWORD = 'https://oa.37du.co/sys/portal/page.jsp'
|
||||
USERNAME = '37036273'
|
||||
PASSWORD = '***REMOVED***'
|
||||
|
||||
# OA 会话校验接口:cookies 有效时返回 JSON,失效时被重定向到登录页返回 HTML
|
||||
TODO_COUNT_URL = "https://oa.37du.co/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
USERNAME_INPUT = 'tag:input@name=j_username'
|
||||
PASSWORD_INPUT = 'tag:input@name=j_password'
|
||||
LOGIN_BTN = '.lui_login_button_div_c'
|
||||
|
||||
TIMEOUT = 10
|
||||
WAIT_AFTER_LOAD = 2
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化 ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||||
def _is_oa_session_valid():
|
||||
"""API 轻量校验 OA cookies:请求 oa_validate_url(默认 sumTodoCount 待办统计接口),
|
||||
返回 JSON 视为 cookies 有效;被重定向到登录页返回 HTML 即视为失效。
|
||||
|
||||
与业务脚本(overtime_approval/leave_approval/social_change 等)使用同一套接口与校验逻辑:
|
||||
requests.Session + Chrome UA + 仅注入 37du.co 域 cookies,GET method=sumTodoCount。
|
||||
"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip() or TODO_COUNT_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login(timeout=TIMEOUT, wait_after_load=WAIT_AFTER_LOAD):
|
||||
"""打开浏览器完成 OA 账号密码登录,成功保存 cookies。"""
|
||||
page = ChromiumPage()
|
||||
try:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(wait_after_load)
|
||||
|
||||
username_input = page.ele(USERNAME_INPUT)
|
||||
if not username_input:
|
||||
raise RuntimeError("未找到用户名输入框")
|
||||
username_input.input(USERNAME)
|
||||
page.wait(0.5)
|
||||
|
||||
password_input = page.ele(PASSWORD_INPUT)
|
||||
if not password_input:
|
||||
raise RuntimeError("未找到密码输入框")
|
||||
password_input.input(PASSWORD)
|
||||
page.wait(0.5)
|
||||
|
||||
login_button = page.ele(LOGIN_BTN)
|
||||
if not login_button:
|
||||
raise RuntimeError("未找到登录按钮")
|
||||
login_button.click()
|
||||
page.wait(0.5)
|
||||
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print(f"登录成功!当前 URL: {page.url}")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
|
||||
error_elem = page.ele('.error-msg') or page.ele('.alert-danger')
|
||||
if error_elem:
|
||||
print(f"登录失败,提示: {error_elem.text}")
|
||||
raise RuntimeError(f"登录超时,当前 URL: {page.url}")
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 OA 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||||
_set_login_state(False)
|
||||
|
||||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(oa_login_url / oa_target_url_keyword 未配置且无内置默认值)", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(oa_login_username / oa_login_password 未配置且无内置默认值)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_oa_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 OA 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = _do_login()
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(force=True):
|
||||
"""
|
||||
影刀自定义指令「37duOA登录」调用入口。
|
||||
force: bool 是否强制重新登录(默认 True,便于本地独立运行直接刷新登录态)
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main(force=True)
|
||||
print("最终结果:", result)
|
||||
@@ -0,0 +1,401 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: org_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: 组织维护(组织设置)导出(影刀共享指令,单文件自包含)——从共享登录态读取
|
||||
HR cookies,调用组织维护台账实时查询接口(queryRealTimeData.mc)分页拉取
|
||||
全部组织数据,转换为页面 18 列格式后导出 Excel。纯接口实现,无需浏览器。
|
||||
@Version: 1.0.0
|
||||
|
||||
运行方式:
|
||||
1. 影刀:注册为自定义指令「37du组织维护导出」,main(...) 关键字传参(缺省用内置默认值,见 DEFAULT_* 常量)
|
||||
output_path Excel 保存路径(默认 D:\\资料\\人资\\组织维护\\组织维护.xlsx)
|
||||
2. 命令行:python org_export.py 直接运行(__main__ 中按示例传参)
|
||||
3. 业务脚本:懒加载本模块调用 export_orgs(...)
|
||||
|
||||
依赖安装(启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests pandas openpyxl
|
||||
|
||||
登录态:读取 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json(由「37duHR登录」指令写入);
|
||||
缺失/失效时不自动补登,抛出提示先重新执行「37duHR登录」指令。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(共享指令要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,正常 INFO 不输出大体积 JSON) ====================
|
||||
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()
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
# 自定义 Base64 字符表(索引0~63,64为填充字符)
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_PAD_CHAR = '7' # 填充字符(索引64)
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
# 1. JSON(无空格,同 JSON.stringify) 2. URI 编码(不编码 ! ' ( ) * - . _ ~)
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
# 3. 自定义 Base64 + 盐值 4. 重排:前2位 + 后3位 + 中间部分
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 缓存统一放在 %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 一致) ----------
|
||||
ORG_QUERY_URL = "https://hr.37du.co/RedseaPlatform/hrRoster/110118b4-b094-11ea-b588-14187743d052/queryRealTimeData.mc"
|
||||
ORG_TABLE_ID = "assemble-pt_organzation"
|
||||
ORG_ROSTER_ID = "110118b4-b094-11ea-b588-14187743d052"
|
||||
PAGE_MAX_SIZE = 500 # 每页最大条数
|
||||
|
||||
# 组织维护查询固定入参(从浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
# commonQuery 由自实现前端加密动态生成(等价抓包原始串,即 in_use in ('1') 条件);
|
||||
# 需要追加/修改查询条件时改 ORG_QUERY_CONDITIONS 后由 encode_common_query 重新加密
|
||||
ORG_QUERY_CONDITIONS = [
|
||||
build_condition("`pt_organzation.IN_USE`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
]
|
||||
|
||||
ORG_QUERY_BASE_PARAMS = {
|
||||
"menuName": "组织维护",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": encode_common_query(ORG_QUERY_CONDITIONS),
|
||||
"newCondition": "",
|
||||
"urlConditions": "_t%3A1788589944798%23clickFlag%3Atrue%23cancelNodeClick%3A1%23treePermitType%3Apermit%23useSealTreeData%3A0%23menuName%3A%E7%BB%84%E7%BB%87%E7%BB%B4%E6%8A%A4%23_t%3A1788589944798%23",
|
||||
"exportConfig": "",
|
||||
"tableId": ORG_TABLE_ID,
|
||||
"rosterId": ORG_ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http://hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
}
|
||||
|
||||
# ---------- 接口字段 -> 页面列名映射(「序号」接口不返回,转换时按行号生成;
|
||||
# 分管部门对应 pt_structure2.ORG_ALIAS,当前数据未使用但列位保留) ----------
|
||||
ORG_FIELD_MAP = [
|
||||
("pt_organzation.ORG_NAME", "组织名称"),
|
||||
("pt_organzation.ORG_CODE", "组织编号"),
|
||||
("pt_organzation.ORG_TYPE_CODE", "组织类型"),
|
||||
("pt_structure1.ORG_ALIAS", "上级组织"),
|
||||
("org_principal_staff_name_select.org_principal_staff_name", "组织负责人"),
|
||||
("pt_structure2.ORG_ALIAS", "分管部门"),
|
||||
("branch_leader_name_select.branch_leader_name", "分管领导"),
|
||||
("pt_organzation.BEGIN_DATE", "成立日期"),
|
||||
("pt_orgnization_extend.FOUND_DOC_NUM", "成立文号"),
|
||||
("pt_organzation.CANT_CODE", "所属地区"),
|
||||
("pt_organzation.office_address", "办公地址"),
|
||||
("pt_organzation.remarks", "备注"),
|
||||
("pt_orgnization_extend.FOUND_REASON", "成立原因"),
|
||||
("pt_structure.ORG_FULL_PATH", "组织全路径"),
|
||||
("pt_organzation.create_time", "创建时间"),
|
||||
("pt_organzation.IN_USE", "使用状态"),
|
||||
("pt_organzation_ext.ext_payday", "发薪日"),
|
||||
]
|
||||
|
||||
# 使用状态编码 -> 文字
|
||||
IN_USE_MAP = {"1": "在用", "0": "停用"}
|
||||
|
||||
# ---------- 默认导出参数(内置默认值,便于分发共享;如需覆盖请直接改这里或由 main(args) 传参) ----------
|
||||
DEFAULT_OUTPUT_PATH = r"D:\资料\人资\组织维护\组织维护.xlsx"
|
||||
|
||||
# ---------- 项目级重试次数(单页请求失败最大尝试次数,含首次) ----------
|
||||
MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _build_session():
|
||||
"""读取共享 HR cookies 构造 requests 会话(仅取 hr.37du.co 域)。
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 共享 cookies 文件不存在
|
||||
"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def _is_expired(text) -> bool:
|
||||
"""接口正常返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成组织维护查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
|
||||
# 上月(本月 1 号减一天即上月最后一天)
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 接口请求 ====================
|
||||
def _fetch_org_page_once(session, page_no, page_size):
|
||||
"""请求单页组织维护数据(单次请求,不含重试)。"""
|
||||
params = ORG_QUERY_BASE_PARAMS.copy()
|
||||
params.update(get_date_params())
|
||||
params.update({
|
||||
"pageNo": str(page_no),
|
||||
"pageSize": str(page_size),
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"_t": str(int(time.time() * 1000)),
|
||||
})
|
||||
resp = session.request("POST", ORG_QUERY_URL, params=params, timeout=30)
|
||||
if not resp or resp.status_code != 200:
|
||||
raise RuntimeError(f"组织维护接口状态码异常: {getattr(resp, 'status_code', '无响应')}")
|
||||
if _is_expired(resp.text):
|
||||
raise LoginRequiredError("HR 登录态已失效,请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _fetch_org_page(session, page_no, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页组织维护数据(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _fetch_org_page_once(session, page_no, page_size)
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("组织维护第%d页请求第 %d 次失败:%s,%.1f 秒后重试", page_no, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("组织维护第%d页连续 %d 次请求失败,放弃", page_no, MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
def fetch_all_orgs(session):
|
||||
"""分页抓取全部组织维护数据(在职组织,in_use=1),返回接口原始记录列表。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
total_page = None
|
||||
while True:
|
||||
data = _fetch_org_page(session, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
raise RuntimeError(f"组织维护第{page_no}页接口返回错误:{data.get('meg') or data.get('des')}")
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("组织维护无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
|
||||
if total_page is None:
|
||||
logger.info("总记录数:%s,总页数:%s", data.get("count"), data.get("pageCount"))
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("组织维护已抓取 %d/%s 页,累计 %d/%s 条",
|
||||
page_no, total_page, len(all_rows), data.get("count"))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2) # 轻微限速,避免触发风控
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 字段转换 ====================
|
||||
def to_org_rows(datalist):
|
||||
"""将接口原始记录转换为页面列名顺序的字典列表(18 列,含序号)。"""
|
||||
rows = []
|
||||
for i, r in enumerate(datalist, 1):
|
||||
row = {"序号": i}
|
||||
for key, name in ORG_FIELD_MAP:
|
||||
value = r.get(key)
|
||||
if name == "使用状态":
|
||||
value = IN_USE_MAP.get(str(value), value)
|
||||
elif name == "成立日期" and value:
|
||||
value = str(value).split(" ")[0] # 去掉 00:00:00 时分秒
|
||||
row[name] = value
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_orgs(output_path=None):
|
||||
"""查询全部组织维护数据并导出 Excel(18 列,与页面列一致)。
|
||||
|
||||
Args:
|
||||
output_path: Excel 保存路径(默认 DEFAULT_OUTPUT_PATH)
|
||||
|
||||
Returns:
|
||||
(导出文件路径, 数据条数)
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: HR 登录态缺失或失效
|
||||
RuntimeError: 请求失败(重试耗尽)或接口返回异常
|
||||
"""
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
|
||||
logger.info("===== 开始组织维护导出,保存路径:%s =====", output_path)
|
||||
session = _build_session()
|
||||
datalist = fetch_all_orgs(session)
|
||||
if not datalist:
|
||||
raise RuntimeError("组织维护接口未查询到任何数据")
|
||||
|
||||
rows = to_org_rows(datalist)
|
||||
out_dir = os.path.dirname(output_path)
|
||||
if out_dir:
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
pd.DataFrame(rows).to_excel(output_path, index=False)
|
||||
logger.info("===== 组织维护导出完成:共 %d 条,已保存 %s =====", len(rows), output_path)
|
||||
return output_path, len(rows)
|
||||
|
||||
|
||||
def main(output_path=None):
|
||||
"""影刀自定义指令入口「37du组织维护导出」。
|
||||
|
||||
Args:
|
||||
output_path: Excel 保存路径(缺省用内置默认值 DEFAULT_OUTPUT_PATH)
|
||||
|
||||
Returns:
|
||||
{"success": bool, "save_path": str, "count": int}
|
||||
save_path 即导出的 Excel 文件路径。
|
||||
"""
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
try:
|
||||
save_path, count = export_orgs(output_path)
|
||||
return {"success": True, "save_path": save_path, "count": count}
|
||||
except Exception as e:
|
||||
logger.error("组织维护导出失败:%s", e)
|
||||
return {"success": False, "error": str(e), "save_path": output_path}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
output_path = r"D:\资料\人资\组织维护\组织维护.xlsx"
|
||||
main(output_path)
|
||||
@@ -0,0 +1,465 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: pre_entry_roster_export_api.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: 预入职台账导出(影刀共享指令,单文件自包含)——纯接口版。
|
||||
与浏览器版 pre_entry_roster_export.py 的 export_pre_entry_roster(...) 调用签名一致:
|
||||
export_pre_entry_roster(download_dir, template_name, output_path, start, end)
|
||||
底层改为:访问预入职台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||||
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)->
|
||||
接收 "--end--|文件路径" 推送 -> 下载并保存为《预入职台账.xlsx》。
|
||||
无需 DrissionPage/浏览器;「已入职」tab 对应台账 rosterId=112adc5b(抓包确认),
|
||||
API 直接向该台账提交导出,无需模拟 tab 切换;预入职日期筛选通过 commonQuery 加密传入。
|
||||
@Version: 1.0.0
|
||||
|
||||
运行方式:
|
||||
1. 影刀:注册为自定义指令「37du预入职台账导出」,main(...) 关键字传参(缺省用内置默认值,见 DEFAULT_* 常量)
|
||||
start / end 预入职日期范围 "YYYY-MM-DD"(不传默认 近30天,与浏览器版一致)
|
||||
template 自定义导出模板名(默认 排班异常识别导出)
|
||||
output_path 导出 Excel 保存路径(默认 D:\\资料\\人资\\排班异常识别\\预入职台账.xlsx)
|
||||
download_dir 兼容浏览器版签名的占位参数(接口版不使用,仅保持调用兼容)
|
||||
2. 命令行:python pre_entry_roster_export_api.py 直接运行(__main__ 中按示例传参)
|
||||
3. 业务脚本:懒加载本模块调用 main(...) / export_pre_entry_roster(...)
|
||||
|
||||
依赖安装(启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests websocket-client
|
||||
|
||||
登录态:读取 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json(由「37duHR登录」指令写入);
|
||||
缺失/失效时不自动补登,抛出提示先重新执行「37duHR登录」指令。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import requests
|
||||
import websocket # websocket-client
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(共享指令要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests websocket-client\n"
|
||||
f"缺失依赖详情: {_import_err}")
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,正常 INFO 不输出大体积 JSON) ====================
|
||||
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()
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
# 自定义 Base64 字符表(索引0~63,64为填充字符)
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_PAD_CHAR = '7' # 填充字符(索引64)
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
# 1. JSON(无空格,同 JSON.stringify) 2. URI 编码(不编码 ! ' ( ) * - . _ ~)
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
# 3. 自定义 Base64 + 盐值 4. 重排:前2位 + 后3位 + 中间部分
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 缓存统一放在 %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')
|
||||
|
||||
# ---------- 预入职台账查询/导出接口(浏览器抓包提取) ----------
|
||||
# 「已入职」tab 对应的台账 id(入口页 rosterId=10fe9cd6 为默认 tab,切 tab 后导出实际走 112adc5b)
|
||||
PRE_ENTRY_ROSTER_ID = "112adc5b-b094-11ea-b588-14187743d052"
|
||||
PRE_ENTRY_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{PRE_ENTRY_ROSTER_ID}/getCustomCommonList.mc"
|
||||
PRE_ENTRY_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{PRE_ENTRY_ROSTER_ID}/exportCommonListData.mc"
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
# 预入职台账导出固定入参(浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
# commonQuery 按预入职日期范围动态加密生成
|
||||
PRE_ENTRY_QUERY_BASE_PARAMS = {
|
||||
"menuName": "预入职台账",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": "",
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": "assemble-hr_staff_base_offer",
|
||||
"rosterId": PRE_ENTRY_ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
"dataIds": "",
|
||||
"hideCols": "",
|
||||
}
|
||||
|
||||
# ---------- 自定义导出模板(exportFilters 字段串,浏览器抓包「排班异常识别导出」模板,顺序与页面一致) ----------
|
||||
PRE_ENTRY_TEMPLATE_FILTERS = {
|
||||
"排班异常识别导出": ",".join([
|
||||
"hr_staff_base_offer.staff_name", # 姓名
|
||||
"hr_staff_base_offer.base_code", # 工号
|
||||
"hr_staff_base_offer.join_date", # 预入职日期
|
||||
"hr_staff_base_offer.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"hr_staff_base_offer.DEPT_ORG_NAME", # 所属部门
|
||||
"hr_staff_base_offer.POST_ORG_NAME", # 岗位
|
||||
"hr_staff_base_offer.first_type_id", # 职位序列
|
||||
"hr_staff_base_offer.OPERAT_TIME", # 操作时间
|
||||
]),
|
||||
}
|
||||
|
||||
# ---------- 默认导出参数(与浏览器版 pre_entry_roster_export.py 保持一致) ----------
|
||||
DEFAULT_TEMPLATE = "排班异常识别导出"
|
||||
DEFAULT_OUTPUT_PATH = r"D:\资料\人资\排班异常识别\预入职台账.xlsx"
|
||||
|
||||
# 异步导出等待超时(秒)
|
||||
EXPORT_TIMEOUT_SECONDS = 300
|
||||
|
||||
# ---------- 项目级重试次数(导出失败最大尝试次数,含首次) ----------
|
||||
MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _build_session():
|
||||
"""读取共享 HR cookies 构造 requests 会话(仅取 37du.co 域)。
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 共享 cookies 文件不存在
|
||||
"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成预入职台账导出所需的动态日期参数(当月 / 上月 / 当年首月,与页面抓包一致)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
|
||||
# 上月(本月 1 号减一天即上月最后一天)
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
def get_pre_entry_range(today: date = None, days: int = 30) -> tuple:
|
||||
"""计算预入职日期筛选范围,返回 (开始日期, 结束日期)。
|
||||
|
||||
默认「近30天」:取今天往前 days 天(含今天),与浏览器版 get_pre_entry_range 一致。
|
||||
"""
|
||||
today = today or date.today()
|
||||
start = today - timedelta(days=days - 1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 查询条件构造 ====================
|
||||
def _build_join_date_conditions(start, end):
|
||||
"""预入职日期区间条件(与页面「更多搜索 -> 预入职日期」抓包条件一致)。"""
|
||||
return [
|
||||
build_condition("`hr_staff_base_offer.join_date`", ">=", start,
|
||||
left_bracket="(", input_type="date"),
|
||||
build_condition("`hr_staff_base_offer.join_date`", "<=", end,
|
||||
right_bracket=")", input_type="date"),
|
||||
]
|
||||
|
||||
|
||||
# ==================== WebSocket 异步导出 ====================
|
||||
def _bind_session(session):
|
||||
"""绑定会话:先访问预入职台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。
|
||||
|
||||
服务端依赖页面访问后的会话状态,未绑定时 bridge 返回 "0"、WS 握手报 500(用户登录)。
|
||||
"""
|
||||
session.get(PRE_ENTRY_PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
|
||||
"useSealTreeData": "0"}, timeout=30)
|
||||
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
|
||||
if "成功" not in r.text and r.text.strip() != "1":
|
||||
raise LoginRequiredError(
|
||||
f"ws/bridge 会话注册失败(登录态可能已失效):{r.text[:100]}。"
|
||||
"请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
|
||||
|
||||
def _export_once(session, download_dir, template_name, start, end):
|
||||
"""单次异步导出:提交任务 -> WS 收 --end-- -> 下载文件。
|
||||
|
||||
Returns:
|
||||
导出 Excel 文件路径
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 登录态失效
|
||||
RuntimeError: 提交失败 / 超时 / 下载失败
|
||||
"""
|
||||
# 1. 会话绑定(页面访问 + bridge 注册)
|
||||
_bind_session(session)
|
||||
|
||||
# 2. WebSocket 连接并订阅主题
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in session.cookies
|
||||
if "hr.37du.co" in (c.domain or ""))
|
||||
ws = websocket.WebSocket()
|
||||
ws.connect(WS_SERVICE_URL, header=[
|
||||
f"Cookie: {cookie_hdr}",
|
||||
"Origin: https://hr.37du.co",
|
||||
f"User-Agent: {USER_AGENT}",
|
||||
], timeout=10)
|
||||
try:
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
|
||||
|
||||
# 3. 提交异步导出任务(预入职日期区间加密为 commonQuery,服务端翻译全部字典字段)
|
||||
params = {k: str(v) for k, v in PRE_ENTRY_QUERY_BASE_PARAMS.items()}
|
||||
params["commonQuery"] = encode_common_query(_build_join_date_conditions(start, end))
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template_name,
|
||||
"exportFilters": PRE_ENTRY_TEMPLATE_FILTERS.get(template_name, "")},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
ts = str(int(time.time() * 1000))
|
||||
params["_t"] = ts
|
||||
# urlConditions 复刻页面抓包格式(_t/clickFlag/treePermitType/useSealTreeData/menuName)
|
||||
params["urlConditions"] = "#".join([
|
||||
f"_t:{ts}", "clickFlag:true", "treePermitType:permit",
|
||||
"useSealTreeData:0", "menuName:预入职台账", f"_t:{ts}", ""])
|
||||
|
||||
resp = session.post(PRE_ENTRY_EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
logger.info("导出任务已提交(预入职日期:%s ~ %s,模板:%s)", start, end, template_name)
|
||||
|
||||
# 4. 接收进度推送,直到 --end--|文件路径
|
||||
file_url = None
|
||||
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
|
||||
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
txt, code = msg.get("txt", ""), msg.get("code", "")
|
||||
if code != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
if txt.startswith("--end--"):
|
||||
file_url = txt.split("|", 1)[1].strip()
|
||||
break
|
||||
if txt.startswith(("开始下载", "正在生成")):
|
||||
logger.info(" 进度:%s", txt)
|
||||
if not file_url:
|
||||
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}s)")
|
||||
logger.info("导出完成,文件地址:%s", file_url)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
# 5. 下载文件到目标目录
|
||||
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
|
||||
dl = session.get(dl_url, timeout=120)
|
||||
if dl.status_code != 200 or not dl.content:
|
||||
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
save_path = os.path.join(download_dir, os.path.basename(DEFAULT_OUTPUT_PATH))
|
||||
with open(save_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("已保存导出文件:%s(%d 字节)", save_path, len(dl.content))
|
||||
return save_path
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_pre_entry_roster(download_dir: str = None, template_name: str = DEFAULT_TEMPLATE,
|
||||
output_path: str = None, start: str = None, end: str = None) -> str:
|
||||
"""执行预入职台账自定义导出(已入职,预入职日期近30天),返回导出 xlsx 文件路径。
|
||||
|
||||
与浏览器版 export_pre_entry_roster(...) 签名一致,download_dir 仅作兼容占位。
|
||||
|
||||
Args:
|
||||
download_dir: 兼容浏览器版签名的占位参数(接口版直接写 output_path,不使用)。
|
||||
template_name: 自定义导出模板名,默认「排班异常识别导出」。
|
||||
output_path: 导出结果保存路径;默认 D:\\资料\\人资\\排班异常识别\\预入职台账.xlsx。
|
||||
start/end: 预入职日期范围,默认取近30天(get_pre_entry_range)。
|
||||
|
||||
Returns:
|
||||
导出后的 xlsx 文件路径。
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: HR 登录态缺失或失效
|
||||
RuntimeError: 导出失败(重试耗尽)或接口返回异常
|
||||
"""
|
||||
output_path = os.path.abspath(output_path or DEFAULT_OUTPUT_PATH)
|
||||
download_dir = os.path.dirname(output_path) # 接口版:直接落盘到输出目录
|
||||
if not start or not end:
|
||||
start, end = get_pre_entry_range()
|
||||
logger.info("===== 开始预入职台账导出(纯接口版,模板:%s,日期:%s ~ %s),保存路径:%s =====",
|
||||
template_name, start, end, output_path)
|
||||
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
session = None
|
||||
try:
|
||||
session = _build_session()
|
||||
save_path = _export_once(session, download_dir, template_name, start, end)
|
||||
# 保存路径与 output_path 不同(模板名改动等)时重命名/移动
|
||||
if os.path.abspath(save_path) != output_path:
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
import shutil
|
||||
shutil.move(save_path, output_path)
|
||||
logger.info("===== 预入职台账导出完成:%s =====", output_path)
|
||||
return output_path
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("预入职台账导出第 %d 次失败:%s,%.1f 秒后重试", attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("预入职台账导出连续 %d 次失败,放弃", MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
def main(start=None, end=None, template=None, output_path=None, download_dir=None):
|
||||
"""影刀自定义指令入口「37du预入职台账导出」(与浏览器版 main 调用兼容)。
|
||||
|
||||
Args(缺省用内置默认值,见 DEFAULT_* 常量):
|
||||
start / end: 预入职日期范围 "YYYY-MM-DD"(不传默认 近30天)
|
||||
template: 自定义导出模板名
|
||||
output_path: 导出 Excel 保存路径
|
||||
download_dir: 兼容占位参数(接口版不使用)
|
||||
|
||||
Returns:
|
||||
{"success": bool, "save_path": str, "start": str, "end": str, "template": str}
|
||||
save_path 即调用方传入的 output_path(导出文件路径)。
|
||||
"""
|
||||
template = template or DEFAULT_TEMPLATE
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
|
||||
try:
|
||||
save_path = export_pre_entry_roster(
|
||||
download_dir=download_dir, template_name=template,
|
||||
output_path=output_path, start=start, end=end)
|
||||
return {"success": True, "save_path": save_path,
|
||||
"start": start, "end": end, "template": template}
|
||||
except Exception as e:
|
||||
logger.error("预入职台账导出失败:%s", e)
|
||||
return {"success": False, "error": str(e), "start": start, "end": end, "template": template}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
_start, _end = get_pre_entry_range()
|
||||
_output = DEFAULT_OUTPUT_PATH
|
||||
main(start=_start, end=_end, template=DEFAULT_TEMPLATE, output_path=_output)
|
||||
@@ -0,0 +1,641 @@
|
||||
# -*- 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)
|
||||
|
||||
@@ -0,0 +1,661 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: roster_export_api.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: 员工花名册导出(影刀共享指令,单文件自包含)——纯接口版。
|
||||
与浏览器版 roster_export.py 的 main(...) 调用签名完全一致:
|
||||
main(statuses, leave_start, leave_end, template, output_path, download_dir)
|
||||
底层改为:访问台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||||
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)->
|
||||
接收 "--end--|文件路径" 推送 -> 下载临时文件 -> 按状态合并(追加「类型」列)。
|
||||
无需 DrissionPage/浏览器,字典翻译(星级/参保类型/职衔/职级等)由服务端完成。
|
||||
@Version: 1.0.0
|
||||
|
||||
运行方式:
|
||||
1. 影刀:注册为自定义指令「37du花名册导出」,main(...) 关键字传参(缺省用内置默认值,见 DEFAULT_* 常量)
|
||||
statuses 在职状态,str "在职" / "在职,离职" 或 list(默认 在职+离职)
|
||||
leave_start 离职时间开始 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
leave_end 离职时间结束 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
template 自定义导出模板名(默认 员工基础信息)
|
||||
output_path 合并后 Excel 保存路径(默认 D:\\资料\\人资\\花名册\\花名册.xlsx)
|
||||
download_dir 单状态临时文件目录(默认 D:\\资料\\人资\\花名册\\download,合并后自动清理)
|
||||
2. 命令行:python roster_export_api.py 直接运行(__main__ 中按示例传参)
|
||||
3. 业务脚本:懒加载本模块调用 main(...) / export_roster(...)
|
||||
|
||||
依赖安装(启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests pandas openpyxl websocket-client
|
||||
|
||||
登录态:读取 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json(由「37duHR登录」指令写入);
|
||||
缺失/失效时不自动补登,抛出提示先重新执行「37duHR登录」指令。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import requests
|
||||
import pandas as pd
|
||||
import websocket # websocket-client
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(共享指令要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests pandas openpyxl websocket-client\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,正常 INFO 不输出大体积 JSON) ====================
|
||||
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()
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
# 自定义 Base64 字符表(索引0~63,64为填充字符)
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_PAD_CHAR = '7' # 填充字符(索引64)
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
# 1. JSON(无空格,同 JSON.stringify) 2. URI 编码(不编码 ! ' ( ) * - . _ ~)
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
# 3. 自定义 Base64 + 盐值 4. 重排:前2位 + 后3位 + 中间部分
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 缓存统一放在 %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/hr_api 一致) ----------
|
||||
ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||||
ROSTER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/getCustomCommonList.mc"
|
||||
ROSTER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/exportCommonListData.mc"
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
# 自定义导出模板定义(页面「自定义导出」弹窗同款接口:列表拿 id -> 详情拿 exportField)
|
||||
TEMPLATE_LIST_URL = ("https://hr.37du.co/RedseaPlatform/redmagicapi/"
|
||||
"rf_pt_users_export_define_select/getExecuteResult.mc")
|
||||
TEMPLATE_DETAIL_URL = "https://hr.37du.co/RedseaPlatform/ptUsersExportDefine/getPtusersexportdefine.mc"
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
# 花名册查询固定入参(从浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
# commonQuery 在导出时按「在职/离职」条件动态加密生成
|
||||
ROSTER_QUERY_BASE_PARAMS = {
|
||||
"menuName": "员工花名册",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": "",
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": "assemble-hr_staff_base",
|
||||
"rosterId": ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
"dataIds": "",
|
||||
"hideCols": "",
|
||||
}
|
||||
|
||||
# ---------- 自定义导出模板(exportFilters 字段串,顺序与页面导出模板列一致) ----------
|
||||
ROSTER_TEMPLATE_FILTERS = {
|
||||
# 「员工基础信息」模板(31 列,与页面抓包 exportFilters 一致)
|
||||
"员工基础信息": ",".join([
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_base.idCard", # 证件号
|
||||
"hr_staff_base.join_date", # 入职时间
|
||||
"hr_staff_base.leaveOffice_date", # 离职时间
|
||||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"pt_staff_stru.DEPT_ORG_NAME", # 所属部门
|
||||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||||
"pt_staff_stru.DEPT_ORG_THREE", # 三级部门
|
||||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||||
"pt_staff_stru.DEPT_ORG_FIVE", # 五级部门
|
||||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||||
"hr_staff_base_ext.ext_technician_code", # 技师工号
|
||||
"hr_staff_base_ext.ext_star_level", # 星级
|
||||
"pt_staff_stru.first_type_id", # 职位序列
|
||||
"pt_staff_stru.POST_LEVEL_ID", # 职衔
|
||||
"pt_staff_stru.PT_POST_GRADE_ID", # 职级
|
||||
"pt_post_level.ext_grade_name", # 职等
|
||||
"hr_staff_base.mobile_phone", # 手机号码
|
||||
"hr_staff_base.person_status", # 在职状态
|
||||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||||
"pt_staff_stru.ORG_FULL_PATH", # 组织全路径
|
||||
"hr_staff_base.nation", # 民族
|
||||
"hr_staff_base.sex", # 性别
|
||||
"hr_staff_base.age", # 年龄
|
||||
"hr_staff_base.period", # 试用期限(月)
|
||||
"hr_staff_base.pre_correction_date", # 试用期结束日期
|
||||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||||
"hr_staff_base_ext.ext_recruit_way", # 招聘渠道
|
||||
"hr_staff_base.identity", # 用工类型
|
||||
]),
|
||||
# 「雇主险增减员导出模板」(14 列,无三级/五级部门,顺序按模板)
|
||||
"雇主险增减员导出模板": ",".join([
|
||||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_base.age", # 年龄
|
||||
"hr_staff_base.sex", # 性别
|
||||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||||
"pt_staff_stru.first_type_id", # 职位序列
|
||||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||||
"hr_staff_base.join_date", # 入职时间
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.idCard", # 证件号
|
||||
]),
|
||||
}
|
||||
|
||||
# ---------- 默认导出参数(与浏览器版 roster_export.py 保持一致) ----------
|
||||
DEFAULT_TEMPLATE = "员工基础信息"
|
||||
DEFAULT_STATUSES = ["在职", "离职"]
|
||||
DEFAULT_OUTPUT_PATH = r"D:\资料\人资\花名册\花名册.xlsx"
|
||||
DEFAULT_DOWNLOAD_DIR = r"D:\资料\人资\花名册\download"
|
||||
DEFAULT_TTL_SECONDS = 15 * 60 # 缓存有效期(秒)
|
||||
|
||||
# 异步导出等待超时(秒,服务端逐条生成 7000+ 条约需 10~20 秒,留足余量)
|
||||
EXPORT_TIMEOUT_SECONDS = 300
|
||||
|
||||
# ---------- 项目级重试次数(单状态导出失败最大尝试次数,含首次) ----------
|
||||
MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _build_session():
|
||||
"""读取共享 HR cookies 构造 requests 会话(仅取 37du.co 域)。
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 共享 cookies 文件不存在
|
||||
"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def _is_expired(text) -> bool:
|
||||
"""接口正常返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成花名册查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
|
||||
# 上月(本月 1 号减一天即上月最后一天)
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
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 _build_in_service_conditions():
|
||||
"""在职人员条件:主职 in (1) + 在职状态 in (1),等价页面默认抓包条件。"""
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
]
|
||||
|
||||
|
||||
def _build_leave_conditions(leave_start, leave_end):
|
||||
"""离职人员条件:主职 in (1) + 在职状态 in (2) + 离职时间区间,等价页面离职筛选抓包串。"""
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "2",
|
||||
query_text="2", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", ">=", leave_start,
|
||||
left_bracket="(", input_type="date"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", "<=", leave_end,
|
||||
right_bracket=")", input_type="date"),
|
||||
]
|
||||
|
||||
|
||||
# ==================== 自定义导出模板动态解析 ====================
|
||||
def resolve_template_filters(session, template_name, user_id=None):
|
||||
"""按模板名动态解析 exportFilters 字段串(与页面「自定义导出」弹窗逻辑一致)。
|
||||
|
||||
两步:模板列表(redmagicapi select,拿 id + ext1 名称)-> 模板详情
|
||||
(getPtusersexportdefine,拿 exportField JSON)-> 按 exportField 顺序拼接字段串。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
template_name: 模板名(对应模板列表的 ext1)
|
||||
user_id: 当前登录用户 id(缺省用 ROSTER_QUERY_BASE_PARAMS 里的 currentUserId)
|
||||
|
||||
Returns:
|
||||
exportFilters 字段串(逗号分隔,顺序与模板一致);解析失败返回 None(调用方回退内置模板)
|
||||
"""
|
||||
user_id = user_id or ROSTER_QUERY_BASE_PARAMS["currentUserId"]
|
||||
try:
|
||||
# 1. 模板列表 -> 按名称匹配拿 id
|
||||
r = session.post(TEMPLATE_LIST_URL, headers=XHR_HEADERS, timeout=15).json()
|
||||
templates = r.get("jsonList") or []
|
||||
target = next((t for t in templates if t.get("ext1") == template_name), None)
|
||||
if not target:
|
||||
logger.warning("模板列表中未找到「%s」(可选:%s),回退内置模板",
|
||||
template_name, [t.get("ext1") for t in templates])
|
||||
return None
|
||||
|
||||
# 2. 模板详情 -> exportField JSON -> 按顺序拼字段串
|
||||
r2 = session.post(TEMPLATE_DETAIL_URL, headers=XHR_HEADERS,
|
||||
data={"rosterId": ROSTER_ID, "id": target["id"]}, timeout=15).json()
|
||||
export_field = (r2.get("result") or {}).get("exportField") or ""
|
||||
fields = json.loads(export_field)
|
||||
if not fields:
|
||||
logger.warning("模板「%s」详情无 exportField,回退内置模板", template_name)
|
||||
return None
|
||||
filters = ",".join(f["tableCode"] for f in fields)
|
||||
logger.info("模板「%s」动态解析成功(%d 列)", template_name, len(fields))
|
||||
return filters
|
||||
except Exception as e:
|
||||
logger.warning("模板「%s」动态解析失败:%s,回退内置模板", template_name, e)
|
||||
return None
|
||||
|
||||
|
||||
# ==================== WebSocket 异步导出(单状态) ====================
|
||||
def _bind_session(session):
|
||||
"""绑定会话:先访问台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。
|
||||
|
||||
服务端依赖页面访问后的会话状态,未绑定时 bridge 返回 "0"、WS 握手报 500(用户登录)。
|
||||
"""
|
||||
session.get(ROSTER_PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
|
||||
"useSealTreeData": "0"}, timeout=30)
|
||||
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
|
||||
if "成功" not in r.text and r.text.strip() != "1":
|
||||
raise LoginRequiredError(
|
||||
f"ws/bridge 会话注册失败(登录态可能已失效):{r.text[:100]}。"
|
||||
"请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
|
||||
|
||||
def _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""单个在职状态的异步导出(单次尝试):提交任务 -> WS 收 --end-- -> 下载临时文件。
|
||||
|
||||
Returns:
|
||||
临时 Excel 文件路径
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 登录态失效
|
||||
RuntimeError: 提交失败 / 超时 / 下载失败
|
||||
"""
|
||||
# 1. 会话绑定(页面访问 + bridge 注册)
|
||||
_bind_session(session)
|
||||
|
||||
# 2. WebSocket 连接并订阅主题
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in session.cookies
|
||||
if "hr.37du.co" in (c.domain or ""))
|
||||
ws = websocket.WebSocket()
|
||||
ws.connect(WS_SERVICE_URL, header=[
|
||||
f"Cookie: {cookie_hdr}",
|
||||
"Origin: https://hr.37du.co",
|
||||
f"User-Agent: {USER_AGENT}",
|
||||
], timeout=10)
|
||||
try:
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
|
||||
|
||||
# 3. 提交异步导出任务(按状态构造 commonQuery,服务端翻译全部字典字段)
|
||||
params = {k: str(v) for k, v in ROSTER_QUERY_BASE_PARAMS.items()}
|
||||
if status == "离职":
|
||||
ls = leave_start or ""
|
||||
le = leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
params["commonQuery"] = encode_common_query(_build_leave_conditions(ls, le))
|
||||
logger.info("离职时间范围:%s ~ %s", ls, le)
|
||||
else:
|
||||
params["commonQuery"] = encode_common_query(_build_in_service_conditions())
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template_name,
|
||||
"exportFilters": export_filters or ROSTER_TEMPLATE_FILTERS.get(template_name, "")},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
params["_t"] = str(int(time.time() * 1000))
|
||||
|
||||
resp = session.post(ROSTER_EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
logger.info("导出任务已提交(状态:%s,模板:%s)", status, template_name)
|
||||
|
||||
# 4. 接收进度推送,直到 --end--|文件路径
|
||||
file_url = None
|
||||
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
|
||||
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
txt, code = msg.get("txt", ""), msg.get("code", "")
|
||||
if code != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
if txt.startswith("--end--"):
|
||||
file_url = txt.split("|", 1)[1].strip()
|
||||
break
|
||||
if txt.startswith(("开始下载", "正在生成")):
|
||||
logger.info(" 进度:%s", txt)
|
||||
if not file_url:
|
||||
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}s)")
|
||||
logger.info("导出完成,文件地址:%s", file_url)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
# 5. 下载文件到临时目录
|
||||
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
|
||||
dl = session.get(dl_url, timeout=120)
|
||||
if dl.status_code != 200 or not dl.content:
|
||||
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
temp_path = os.path.join(download_dir, f"花名册_{status}_{int(time.time())}.xlsx")
|
||||
with open(temp_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("已下载临时文件:%s(%d 字节)", temp_path, len(dl.content))
|
||||
return temp_path
|
||||
|
||||
|
||||
def _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""导出单个在职状态的花名册(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("导出在职状态「%s」第 %d 次失败:%s,%.1f 秒后重试",
|
||||
status, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("导出在职状态「%s」连续 %d 次失败,放弃", status, MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
# ==================== 合并输出 ====================
|
||||
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)
|
||||
out_dir = os.path.dirname(output_path)
|
||||
if out_dir:
|
||||
os.makedirs(out_dir, 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_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:
|
||||
合并后的花名册文件路径
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: HR 登录态缺失或失效
|
||||
RuntimeError: 导出失败(重试耗尽)或接口返回异常
|
||||
"""
|
||||
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
|
||||
|
||||
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)
|
||||
|
||||
session = _build_session()
|
||||
# 模板动态解析(列表 -> 详情 -> exportField),失败回退内置模板字段串
|
||||
export_filters = resolve_template_filters(session, template_name)
|
||||
|
||||
files_with_status = []
|
||||
for status in statuses:
|
||||
logger.info("===== 开始导出在职状态:%s =====", status)
|
||||
path = _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
files_with_status.append((status, path))
|
||||
|
||||
# 合并所有花名册文件
|
||||
result = _normalize_and_save(files_with_status, output_path)
|
||||
logger.info("===== 花名册导出并合并完成:%s =====", result)
|
||||
return result
|
||||
|
||||
|
||||
def main(statuses=None, leave_start=None, leave_end=None,
|
||||
template=None, output_path=None, download_dir=None):
|
||||
"""影刀自定义指令入口「37du花名册导出」(与浏览器版 roster_export.py 签名一致)。
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,478 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: transfer_roster_export_api.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: 调动台账导出(影刀共享指令,单文件自包含)——纯接口版。
|
||||
与浏览器版 transfer_roster_export.py 的 export_transfer_roster(...) 调用签名一致:
|
||||
export_transfer_roster(download_dir, template_name, output_path, start, end)
|
||||
底层改为:访问调动台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||||
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)->
|
||||
接收 "--end--|文件路径" 推送 -> 下载并保存为《调动台账.xlsx》。
|
||||
无需 DrissionPage/浏览器;「调动已生效」tab 对应台账 rosterId=10feec75(抓包确认),
|
||||
API 直接向该台账提交导出,无需模拟 tab 切换;调动时间筛选通过 commonQuery 加密传入。
|
||||
@Version: 1.0.0
|
||||
|
||||
运行方式:
|
||||
1. 影刀:注册为自定义指令「37du调动台账导出」,main(...) 关键字传参(缺省用内置默认值,见 DEFAULT_* 常量)
|
||||
start / end 调动时间范围 "YYYY-MM-DD"(不传默认 近30天,与浏览器版一致)
|
||||
template 自定义导出模板名(默认 排班异常识别导出)
|
||||
output_path 导出 Excel 保存路径(默认 D:\\资料\\人资\\排班异常识别\\调动台账.xlsx)
|
||||
download_dir 兼容浏览器版签名的占位参数(接口版不使用,仅保持调用兼容)
|
||||
2. 命令行:python transfer_roster_export_api.py 直接运行(__main__ 中按示例传参)
|
||||
3. 业务脚本:懒加载本模块调用 main(...) / export_transfer_roster(...)
|
||||
|
||||
依赖安装(启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests websocket-client
|
||||
|
||||
登录态:读取 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json(由「37duHR登录」指令写入);
|
||||
缺失/失效时不自动补登,抛出提示先重新执行「37duHR登录」指令。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import requests
|
||||
import websocket # websocket-client
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(共享指令要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests websocket-client\n"
|
||||
f"缺失依赖详情: {_import_err}")
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,正常 INFO 不输出大体积 JSON) ====================
|
||||
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()
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
# 自定义 Base64 字符表(索引0~63,64为填充字符)
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_PAD_CHAR = '7' # 填充字符(索引64)
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
# 1. JSON(无空格,同 JSON.stringify) 2. URI 编码(不编码 ! ' ( ) * - . _ ~)
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
# 3. 自定义 Base64 + 盐值 4. 重排:前2位 + 后3位 + 中间部分
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 缓存统一放在 %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')
|
||||
|
||||
# ---------- 调动台账查询/导出接口(浏览器抓包提取) ----------
|
||||
# 「调动已生效」tab 对应的台账 id(入口页 rosterId=1123d951 为默认 tab,切 tab 后导出实际走 10feec75)
|
||||
TRANSFER_ROSTER_ID = "10feec75-b094-11ea-b588-14187743d052"
|
||||
TRANSFER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{TRANSFER_ROSTER_ID}/getCustomCommonList.mc"
|
||||
TRANSFER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{TRANSFER_ROSTER_ID}/exportCommonListData.mc"
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
# 调动台账导出固定入参(浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
# commonQuery 按调动时间范围动态加密生成
|
||||
TRANSFER_QUERY_BASE_PARAMS = {
|
||||
"menuName": "调动台账",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": "",
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": "assemble-hr_staff_move_info",
|
||||
"rosterId": TRANSFER_ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
"dataIds": "",
|
||||
"hideCols": "",
|
||||
}
|
||||
|
||||
# ---------- 自定义导出模板(exportFilters 字段串,浏览器抓包「排班异常识别导出」模板,顺序与页面一致) ----------
|
||||
TRANSFER_TEMPLATE_FILTERS = {
|
||||
"排班异常识别导出": ",".join([
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_move_info.CHANGE_TYPE", # 调动类型
|
||||
"hr_staff_move_info.PRE_ORG_NAME", # 原所属单位
|
||||
"hr_staff_move_info.PRE_DEPT_NAME", # 原部门
|
||||
"hr_staff_move_info.PRE_PARENT_ORG_NAME", # 原上级部门
|
||||
"hr_staff_move_info_ext.ext_pre_dept_one", # 原一级部门
|
||||
"hr_staff_move_info_ext.ext_pre_dept_five", # 原五级部门
|
||||
"hr_staff_move_info.PRE_POST_NAME", # 原岗位
|
||||
"hr_staff_move_info.pre_first_type_id", # 原职位序列
|
||||
"hr_staff_move_info.NOW_ORG_NAME", # 现所属单位
|
||||
"hr_staff_move_info.DEPT_NAME", # 现部门
|
||||
"hr_staff_move_info.NOW_PARENT_ORG_NAME", # 现上级部门
|
||||
"hr_staff_move_info_ext.ext_now_dept_one", # 现一级部门
|
||||
"hr_staff_move_info_ext.ext_now_dept_five", # 现五级部门
|
||||
"hr_staff_move_info.POST_NAME", # 现岗位
|
||||
"hr_staff_move_info.now_first_type_id", # 现职位序列
|
||||
"pt_structure1.dept_org_four", # 原四级部门
|
||||
"pt_structure.dept_org_four", # 现四级部门
|
||||
"hr_staff_move_info.MOVE_DATE", # 调动时间
|
||||
"hr_staff_move_info.OPERAT_TIME", # 操作时间
|
||||
]),
|
||||
}
|
||||
|
||||
# ---------- 默认导出参数(与浏览器版 transfer_roster_export.py 保持一致) ----------
|
||||
DEFAULT_TEMPLATE = "排班异常识别导出"
|
||||
DEFAULT_OUTPUT_PATH = r"D:\资料\人资\排班异常识别\调动台账.xlsx"
|
||||
|
||||
# 异步导出等待超时(秒)
|
||||
EXPORT_TIMEOUT_SECONDS = 300
|
||||
|
||||
# ---------- 项目级重试次数(导出失败最大尝试次数,含首次) ----------
|
||||
MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _build_session():
|
||||
"""读取共享 HR cookies 构造 requests 会话(仅取 37du.co 域)。
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 共享 cookies 文件不存在
|
||||
"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成调动台账导出所需的动态日期参数(当月 / 上月 / 当年首月,与页面抓包一致)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
|
||||
# 上月(本月 1 号减一天即上月最后一天)
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
def get_transfer_range(today: date = None, days: int = 30) -> tuple:
|
||||
"""计算调动日期筛选范围,返回 (开始日期, 结束日期)。
|
||||
|
||||
默认「近30天」:取今天往前 days 天(含今天),与浏览器版 get_transfer_range 一致。
|
||||
"""
|
||||
today = today or date.today()
|
||||
start = today - timedelta(days=days - 1)
|
||||
end = today
|
||||
return start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 查询条件构造 ====================
|
||||
def _build_move_date_conditions(start, end):
|
||||
"""调动时间区间条件(与页面「更多搜索 -> 调动时间」抓包条件一致)。"""
|
||||
return [
|
||||
build_condition("`hr_staff_move_info.MOVE_DATE`", ">=", start,
|
||||
left_bracket="(", input_type="date"),
|
||||
build_condition("`hr_staff_move_info.MOVE_DATE`", "<=", end,
|
||||
right_bracket=")", input_type="date"),
|
||||
]
|
||||
|
||||
|
||||
# ==================== WebSocket 异步导出 ====================
|
||||
def _bind_session(session):
|
||||
"""绑定会话:先访问调动台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。
|
||||
|
||||
服务端依赖页面访问后的会话状态,未绑定时 bridge 返回 "0"、WS 握手报 500(用户登录)。
|
||||
"""
|
||||
session.get(TRANSFER_PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
|
||||
"useSealTreeData": "0"}, timeout=30)
|
||||
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
|
||||
if "成功" not in r.text and r.text.strip() != "1":
|
||||
raise LoginRequiredError(
|
||||
f"ws/bridge 会话注册失败(登录态可能已失效):{r.text[:100]}。"
|
||||
"请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
|
||||
|
||||
def _export_once(session, download_dir, template_name, start, end):
|
||||
"""单次异步导出:提交任务 -> WS 收 --end-- -> 下载文件。
|
||||
|
||||
Returns:
|
||||
导出 Excel 文件路径
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 登录态失效
|
||||
RuntimeError: 提交失败 / 超时 / 下载失败
|
||||
"""
|
||||
# 1. 会话绑定(页面访问 + bridge 注册)
|
||||
_bind_session(session)
|
||||
|
||||
# 2. WebSocket 连接并订阅主题
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in session.cookies
|
||||
if "hr.37du.co" in (c.domain or ""))
|
||||
ws = websocket.WebSocket()
|
||||
ws.connect(WS_SERVICE_URL, header=[
|
||||
f"Cookie: {cookie_hdr}",
|
||||
"Origin: https://hr.37du.co",
|
||||
f"User-Agent: {USER_AGENT}",
|
||||
], timeout=10)
|
||||
try:
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
|
||||
|
||||
# 3. 提交异步导出任务(调动时间区间加密为 commonQuery,服务端翻译全部字典字段)
|
||||
params = {k: str(v) for k, v in TRANSFER_QUERY_BASE_PARAMS.items()}
|
||||
params["commonQuery"] = encode_common_query(_build_move_date_conditions(start, end))
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template_name,
|
||||
"exportFilters": TRANSFER_TEMPLATE_FILTERS.get(template_name, "")},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
ts = str(int(time.time() * 1000))
|
||||
params["_t"] = ts
|
||||
# urlConditions 复刻页面抓包格式(_t/clickFlag/treePermitType/useSealTreeData/menuName)
|
||||
params["urlConditions"] = "#".join([
|
||||
f"_t:{ts}", "clickFlag:true", "treePermitType:permit",
|
||||
"useSealTreeData:0", "menuName:调动台账", f"_t:{ts}", ""])
|
||||
|
||||
resp = session.post(TRANSFER_EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
logger.info("导出任务已提交(调动时间:%s ~ %s,模板:%s)", start, end, template_name)
|
||||
|
||||
# 4. 接收进度推送,直到 --end--|文件路径
|
||||
file_url = None
|
||||
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
|
||||
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
txt, code = msg.get("txt", ""), msg.get("code", "")
|
||||
if code != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
if txt.startswith("--end--"):
|
||||
file_url = txt.split("|", 1)[1].strip()
|
||||
break
|
||||
if txt.startswith(("开始下载", "正在生成")):
|
||||
logger.info(" 进度:%s", txt)
|
||||
if not file_url:
|
||||
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}s)")
|
||||
logger.info("导出完成,文件地址:%s", file_url)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
# 5. 下载文件到目标目录
|
||||
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
|
||||
dl = session.get(dl_url, timeout=120)
|
||||
if dl.status_code != 200 or not dl.content:
|
||||
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
save_path = os.path.join(download_dir, os.path.basename(DEFAULT_OUTPUT_PATH))
|
||||
with open(save_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("已保存导出文件:%s(%d 字节)", save_path, len(dl.content))
|
||||
return save_path
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_transfer_roster(download_dir: str = None, template_name: str = DEFAULT_TEMPLATE,
|
||||
output_path: str = None, start: str = None, end: str = None) -> str:
|
||||
"""执行调动台账自定义导出(调动已生效,调动时间近30天),返回导出 xlsx 文件路径。
|
||||
|
||||
与浏览器版 export_transfer_roster(...) 签名一致,download_dir 仅作兼容占位。
|
||||
|
||||
Args:
|
||||
download_dir: 兼容浏览器版签名的占位参数(接口版直接写 output_path,不使用)。
|
||||
template_name: 自定义导出模板名,默认「排班异常识别导出」。
|
||||
output_path: 导出结果保存路径;默认 D:\\资料\\人资\\排班异常识别\\调动台账.xlsx。
|
||||
start/end: 调动时间范围,默认取近30天(get_transfer_range)。
|
||||
|
||||
Returns:
|
||||
导出后的 xlsx 文件路径。
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: HR 登录态缺失或失效
|
||||
RuntimeError: 导出失败(重试耗尽)或接口返回异常
|
||||
"""
|
||||
output_path = os.path.abspath(output_path or DEFAULT_OUTPUT_PATH)
|
||||
download_dir = os.path.dirname(output_path) # 接口版:直接落盘到输出目录
|
||||
if not start or not end:
|
||||
start, end = get_transfer_range()
|
||||
logger.info("===== 开始调动台账导出(纯接口版,模板:%s,日期:%s ~ %s),保存路径:%s =====",
|
||||
template_name, start, end, output_path)
|
||||
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
session = None
|
||||
try:
|
||||
session = _build_session()
|
||||
save_path = _export_once(session, download_dir, template_name, start, end)
|
||||
# 保存路径与 output_path 不同(模板名改动等)时重命名/移动
|
||||
if os.path.abspath(save_path) != output_path:
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
import shutil
|
||||
shutil.move(save_path, output_path)
|
||||
logger.info("===== 调动台账导出完成:%s =====", output_path)
|
||||
return output_path
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("调动台账导出第 %d 次失败:%s,%.1f 秒后重试", attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("调动台账导出连续 %d 次失败,放弃", MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
def main(start=None, end=None, template=None, output_path=None, download_dir=None):
|
||||
"""影刀自定义指令入口「37du调动台账导出」(与浏览器版 main 调用兼容)。
|
||||
|
||||
Args(缺省用内置默认值,见 DEFAULT_* 常量):
|
||||
start / end: 调动时间范围 "YYYY-MM-DD"(不传默认 近30天)
|
||||
template: 自定义导出模板名
|
||||
output_path: 导出 Excel 保存路径
|
||||
download_dir: 兼容占位参数(接口版不使用)
|
||||
|
||||
Returns:
|
||||
{"success": bool, "save_path": str, "start": str, "end": str, "template": str}
|
||||
save_path 即调用方传入的 output_path(导出文件路径)。
|
||||
"""
|
||||
template = template or DEFAULT_TEMPLATE
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
|
||||
try:
|
||||
save_path = export_transfer_roster(
|
||||
download_dir=download_dir, template_name=template,
|
||||
output_path=output_path, start=start, end=end)
|
||||
return {"success": True, "save_path": save_path,
|
||||
"start": start, "end": end, "template": template}
|
||||
except Exception as e:
|
||||
logger.error("调动台账导出失败:%s", e)
|
||||
return {"success": False, "error": str(e), "start": start, "end": end, "template": template}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
_start, _end = get_transfer_range()
|
||||
_output = DEFAULT_OUTPUT_PATH
|
||||
main(start=_start, end=_end, template=DEFAULT_TEMPLATE, output_path=_output)
|
||||
@@ -0,0 +1,653 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: work_communication.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-25
|
||||
@Description: OA 工作沟通推送自定义指令(影刀编码版 Python 模块源码,单一真源)。
|
||||
作为「OA工作沟通推送」影刀自定义指令的模块源码,供所有需要 OA 工作沟通推送的
|
||||
业务脚本/流程复用(告知书下发、参保通知等),避免各自内联搜索/上传/提交逻辑。
|
||||
合并自 app 公共模块 app/service/hrbp/oa/common/
|
||||
(work_communication.py + oa_api/work_communication.py + config.py),
|
||||
业务逻辑与接口调用完全一致。具体业务逻辑见 docs/工作沟通推送/需求文档.md、开发文档.md。
|
||||
单文件自包含:不 import 任何共享指令模块,只读共享 cookies 文件、只写影刀全局变量。
|
||||
@Version: 1.0.0
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage requests
|
||||
|
||||
登录(共享登录态,本脚本仅读取 cookies 文件,不 import 任何共享模块):
|
||||
「37duOA登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json;
|
||||
缺失/失效时先拖入「37duOA登录」指令再运行本流程。
|
||||
|
||||
用法(作为影刀指令/业务脚本被调用):
|
||||
from yingdao.share.work_communication import send_work_communication
|
||||
|
||||
doc_id = send_work_communication(
|
||||
receiver_keywords=["37001166", "37036361"], # 工号或姓名,列表或单个字符串
|
||||
subject="【通知】...",
|
||||
content="<p>正文支持 HTML</p>",
|
||||
attachment_paths=[r"D:\\资料\\附件.xlsx"], # 可选,多个
|
||||
creator_id="1342173e36cf416088266b17d7d084a4", # 当前操作人 ID;不传则尝试从新建页自动提取
|
||||
category="工作安排", # 可选:工作交流/信息传递/工作安排/项目沟通/温馨提示/其他
|
||||
)
|
||||
|
||||
main() 入口返回 {"success", "message", "doc_id"},并写入影刀全局变量 push_result。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import base64
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
from typing import List, Optional, Union
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install DrissionPage requests\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 数据目录固定放在 AppData\Local\37duAutomation,登录态由「37duOA登录」指令写入
|
||||
_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')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
# 人员搜索接口:按工号/姓名模糊搜索,返回人员 XML(<data id=.. name=..>)
|
||||
PERSON_SEARCH_URL = f"{BASE_URL}/sys/common/dataxml.jsp"
|
||||
# 附件上传接口:getuserkey / submit 两步共用
|
||||
ATT_UPLOAD_URL = f"{BASE_URL}/sys/attachment/sys_att_main/sysAttMain.do"
|
||||
# 附件二进制上传接口
|
||||
ATT_UPLOADER_URL = f"{BASE_URL}/sys/attachment/uploaderServlet"
|
||||
# 新建工作沟通页面:method=add 返回表单页,其中含新建草稿 fdId 与通知方式随机字段 __notify_type_<id>
|
||||
WORK_COMMUNICATION_ADD_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do?method=add"
|
||||
# 保存工作沟通:POST 表单字段(application/x-www-form-urlencoded),成功返回「操作成功」提示页
|
||||
KM_COLLABORATE_SAVE_URL = f"{BASE_URL}/km/collaborate/km_collaborate_main/kmCollaborateMain.do"
|
||||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||||
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
# 沟通内容 fdContent 序列化前缀:真实格式为 固定前缀 + {base64(HTML)}(前缀为抓包确认的固定字节)
|
||||
FD_CONTENT_PREFIX = b"\xe4\x99\x89\xe5\xa0\xa0\xe4\xb5\x85\xe4\x89\x81\xe5\x8d\x85\xe3\x98\xb4".decode("utf-8")
|
||||
# 沟通类型(fdCategoryId 必填 validate=required),全部类型如下,调用方可任选,默认「工作安排」
|
||||
FD_CATEGORY_COMMUNICATION = "15e4c970dd59cd559f096644cecadbc7" # 工作交流
|
||||
FD_CATEGORY_INFO = "15e4c980ff72365007fc1a741ceb0c7d" # 信息传递
|
||||
FD_CATEGORY_WORK_ARRANGE = "17646e8283a07a43be3003d485492a4f" # 工作安排
|
||||
FD_CATEGORY_PROJECT = "1767a1195ec34b0de7d53764c84812f1" # 项目沟通
|
||||
FD_CATEGORY_REMINDER = "17efb81557d1e74c532aa78407a95189" # 温馨提示
|
||||
FD_CATEGORY_OTHER = "15e4c985cd9a92cc54cb20c413d9b29e" # 其他
|
||||
FD_CATEGORY_MAP = {
|
||||
"工作交流": FD_CATEGORY_COMMUNICATION,
|
||||
"信息传递": FD_CATEGORY_INFO,
|
||||
"工作安排": FD_CATEGORY_WORK_ARRANGE,
|
||||
"项目沟通": FD_CATEGORY_PROJECT,
|
||||
"温馨提示": FD_CATEGORY_REMINDER,
|
||||
"其他": FD_CATEGORY_OTHER,
|
||||
}
|
||||
FD_CATEGORY_DEFAULT = FD_CATEGORY_WORK_ARRANGE
|
||||
# 工作沟通(协作)业务模型名:附件绑定与沟通提交共用
|
||||
KM_COLLABORATE_MODEL = "com.landray.kmss.km.collaborate.model.KmCollaborateMain"
|
||||
|
||||
# 附件二进制上传时的请求头(Referer 指向 OA 根地址,避免被服务端拦截)
|
||||
_DEFAULT_HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Referer": f"{BASE_URL}/",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 日志(影刀环境用 print 替代 logging) ====================
|
||||
class _PrintLogger:
|
||||
"""简易日志器,用 print 输出,兼容原有 logger.xxx(msg, *args) 调用。"""
|
||||
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()
|
||||
|
||||
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _load_shared_oa_cookies():
|
||||
"""读取共享 OA 登录 cookies(由「37duOA登录」指令写入)。"""
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
return json.load(f) or None
|
||||
|
||||
|
||||
def _ensure_oa_cookies():
|
||||
"""确保存在有效的 OA 登录态文件;缺失/失效时友好提示先运行「37duOA登录」指令。"""
|
||||
if _load_shared_oa_cookies():
|
||||
return True
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
raise SystemExit(
|
||||
"未找到 OA 登录态文件(oa_cookies.json)。\n"
|
||||
"请先在影刀流程开头拖入「37duOA登录」指令完成登录,"
|
||||
"或本地运行: python yingdao/share/oa_login.py\n"
|
||||
"登录完成后再运行本流程。")
|
||||
raise SystemExit(
|
||||
"OA 登录态已失效(oa_cookies.json 已过期)。\n"
|
||||
"请先重新运行「37duOA登录」指令完成登录,"
|
||||
"或本地运行: python yingdao/share/oa_login.py\n"
|
||||
"重新登录后再运行本流程。")
|
||||
|
||||
|
||||
def is_session_valid(session):
|
||||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需拉待办)。"""
|
||||
try:
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
text = resp.text or ""
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
logger.info("会话已失效,需重新登录: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def build_session():
|
||||
"""用共享 oa_cookies.json 构建 SessionPage(纯接口,不开浏览器),并校验会话有效。"""
|
||||
_ensure_oa_cookies()
|
||||
session = SessionPage()
|
||||
session.set.timeout(10)
|
||||
cookies = _load_shared_oa_cookies()
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
if is_session_valid(session):
|
||||
return session
|
||||
raise SystemExit(
|
||||
"OA 登录态已失效(oa_cookies.json 已过期)。\n"
|
||||
"请先重新运行「37duOA登录」指令完成登录,"
|
||||
"或本地运行: python yingdao/share/oa_login.py\n"
|
||||
"重新登录后再运行本流程。")
|
||||
|
||||
|
||||
# ==================== 通用响应校验 ====================
|
||||
class OALoginExpiredError(Exception):
|
||||
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
def _check_response(resp, label):
|
||||
"""校验响应:存在性 / 状态码 / 登录态。供返回 XML 或纯文本等非 JSON 的接口使用。"""
|
||||
if not resp:
|
||||
raise RuntimeError(f"{label}请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"{label}接口状态码异常: {resp.status_code}")
|
||||
text = resp.text or ""
|
||||
if "login.jsp" in text or "j_username" in text:
|
||||
raise OALoginExpiredError(f"{label}接口返回登录页,OA 登录态已失效")
|
||||
return resp
|
||||
|
||||
|
||||
def oa_request_json(session, method, url, params, label, timeout=20, headers=None):
|
||||
"""通用「发送请求 + 校验响应」:发出请求 → 校验状态码/JSON → 返回解析后的 JSON。"""
|
||||
if method.upper() == "GET":
|
||||
session.get(url, params=params, timeout=timeout, headers=headers)
|
||||
else:
|
||||
session.post(url, data=params, timeout=timeout, headers=headers)
|
||||
resp = _check_response(session.response, label)
|
||||
text = resp.text or ""
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
raise RuntimeError(f"{label}接口返回非 JSON 数据(状态码 {resp.status_code}): {text[:200]}")
|
||||
|
||||
|
||||
# ==================== 人员搜索 ====================
|
||||
def search_person(session, keyword, org_type="15"):
|
||||
"""
|
||||
按工号或姓名搜索人员,返回 (person_id, person_name);未找到返回 None。
|
||||
精确匹配优先(工号/姓名全等);模糊命中多个时默认取第一个并记录警告。
|
||||
"""
|
||||
params = {
|
||||
"s_bean": "organizationDialogSearch",
|
||||
"orgType": org_type,
|
||||
"deptLimit": "",
|
||||
"isExternal": "",
|
||||
"key": keyword,
|
||||
"s_ajax": "true",
|
||||
}
|
||||
session.get(PERSON_SEARCH_URL, params=params, timeout=20)
|
||||
resp = _check_response(session.response, "人员搜索")
|
||||
|
||||
try:
|
||||
root = ET.fromstring(resp.text)
|
||||
except ET.ParseError as e:
|
||||
logger.warning("人员搜索[%s]响应解析失败: %s", keyword, e)
|
||||
return None
|
||||
|
||||
matches = []
|
||||
for node in root.iter("data"):
|
||||
pid = node.get("id")
|
||||
pname = node.get("name")
|
||||
if pid and pname:
|
||||
matches.append((pid, pname))
|
||||
|
||||
if not matches:
|
||||
logger.warning("未搜索到人员: %s", keyword)
|
||||
return None
|
||||
|
||||
for pid, pname in matches:
|
||||
if keyword in (pid, pname):
|
||||
logger.info("搜索到人员: %s (ID: %s)", pname, pid)
|
||||
return (pid, pname)
|
||||
|
||||
if len(matches) > 1:
|
||||
logger.warning("关键字[%s]模糊匹配到 %d 人,默认取第一个: %s", keyword, len(matches), matches[0])
|
||||
pid, pname = matches[0]
|
||||
logger.info("搜索到人员: %s (ID: %s)", pname, pid)
|
||||
return (pid, pname)
|
||||
|
||||
|
||||
# ==================== 附件上传 ====================
|
||||
def upload_attachment(session, file_path):
|
||||
"""
|
||||
上传单个附件,返回最终附件 ID(attid)。
|
||||
普通上传流程(不实现 MD5 秒传):getuserkey → 二进制上传 → submit 绑定。
|
||||
"""
|
||||
file_path = os.path.abspath(file_path)
|
||||
if not os.path.exists(file_path):
|
||||
raise FileNotFoundError(f"附件文件不存在: {file_path}")
|
||||
|
||||
file_name = os.path.basename(file_path)
|
||||
file_size = str(os.path.getsize(file_path))
|
||||
file_type = mimetypes.guess_type(file_name)[0] or "application/octet-stream"
|
||||
last_modified = time.strftime(
|
||||
"%a %b %d %Y %H:%M:%S GMT+0800",
|
||||
time.localtime(os.path.getmtime(file_path)),
|
||||
)
|
||||
# fdSign = Base64(文件名) 并去掉 + / = 字符(与 swf_attachment.js 的 createAttMainInfo 一致)
|
||||
fd_sign = base64.b64encode(file_name.encode("utf-8")).decode("utf-8")
|
||||
fd_sign = fd_sign.replace("+", "").replace("/", "").replace("=", "")
|
||||
|
||||
# ---- 步骤1:获取 userkey ----
|
||||
params1 = {
|
||||
"method": "handleAttUpload",
|
||||
"gettype": "getuserkey",
|
||||
"format": "json",
|
||||
"filesize": file_size,
|
||||
"md5": "",
|
||||
"fileName": file_name,
|
||||
"isSupportDirect": "false",
|
||||
"s_ajax": "true",
|
||||
}
|
||||
resp1 = oa_request_json(session, "GET", ATT_UPLOAD_URL, params1, "附件上传-获取userkey", headers=_DEFAULT_HEADERS)
|
||||
userkey = resp1.get("token", {}).get("header", {}).get("userkey")
|
||||
if not userkey:
|
||||
raise RuntimeError(f"获取 userkey 失败: {resp1}")
|
||||
logger.info(" 1. 获取 userkey 成功")
|
||||
|
||||
# ---- 步骤2:上传二进制(userkey 需随请求带上,否则报「附件上传密钥为空」) ----
|
||||
uploader_url = f"{ATT_UPLOADER_URL}?gettype=upload&format=json&userkey={userkey}"
|
||||
files = {"file": (file_name, open(file_path, "rb"), file_type)}
|
||||
data2 = {
|
||||
"id": "WU_FILE_0",
|
||||
"name": file_name,
|
||||
"type": file_type,
|
||||
"lastModifiedDate": last_modified,
|
||||
"size": file_size,
|
||||
}
|
||||
session.post(uploader_url, data=data2, files=files, timeout=60, headers=_DEFAULT_HEADERS)
|
||||
resp2 = _check_response(session.response, "附件上传-二进制")
|
||||
try:
|
||||
filekey = resp2.json().get("filekey")
|
||||
except Exception:
|
||||
filekey = None
|
||||
if not filekey:
|
||||
raise RuntimeError(f"二进制上传失败: {resp2.text[:200]}")
|
||||
logger.info(" 2. 二进制上传成功, filekey: %s...", filekey[:16])
|
||||
|
||||
# ---- 步骤3:submit 绑定附件,获取最终 attid ----
|
||||
params3 = {
|
||||
"method": "handleAttUpload",
|
||||
"gettype": "submit",
|
||||
"format": "json",
|
||||
"filekey": filekey,
|
||||
"filename": file_name,
|
||||
"fdKey": "attachment",
|
||||
"fdModelName": KM_COLLABORATE_MODEL,
|
||||
"fdAttType": "byte",
|
||||
"width": "null",
|
||||
"height": "null",
|
||||
"proportion": "true",
|
||||
"fdSign": fd_sign,
|
||||
"s_ajax": "true",
|
||||
}
|
||||
resp3 = oa_request_json(session, "GET", ATT_UPLOAD_URL, params3, "附件上传-提交绑定", headers=_DEFAULT_HEADERS)
|
||||
attid = resp3.get("attid")
|
||||
if str(resp3.get("status")) != "1" or not attid:
|
||||
raise RuntimeError(f"提交绑定附件失败: {resp3}")
|
||||
logger.info(" 3. 提交绑定成功, attid: %s", attid)
|
||||
return attid
|
||||
|
||||
|
||||
# ==================== 工作沟通提交 ====================
|
||||
def _encode_fd_content(content):
|
||||
"""把沟通内容编码为 OA 要求的 fdContent 格式:固定前缀 + {base64(HTML)}。"""
|
||||
return FD_CONTENT_PREFIX + "{" + base64.b64encode(content.encode("utf-8")).decode("utf-8") + "}"
|
||||
|
||||
|
||||
def _get_add_page_fd_info(session):
|
||||
"""打开新建工作沟通页(method=add),解析出草稿 fdId、通知方式随机字段名、当前用户 ID。
|
||||
|
||||
Returns:
|
||||
(fd_id, notify_field, creator_id):fdId 隐藏域值;`__notify_type_<随机id>` 字段名;
|
||||
页面里 docCreatorId 隐藏域值(当前登录用户 ID,可能为空)
|
||||
"""
|
||||
session.get(WORK_COMMUNICATION_ADD_URL, timeout=20)
|
||||
resp = _check_response(session.response, "新建工作沟通-取页面")
|
||||
html = resp.text or ""
|
||||
m = re.search(r'name="fdId"\s+value="([^"]*)"', html)
|
||||
fd_id = m.group(1) if m else ""
|
||||
m2 = re.search(r'name="(__notify_type_[a-f0-9]+)"', html)
|
||||
notify_field = m2.group(1) if m2 else ""
|
||||
m3 = re.search(r'name="docCreatorId"\s+value="([^"]*)"', html)
|
||||
creator_id = m3.group(1) if m3 else ""
|
||||
if not fd_id:
|
||||
raise RuntimeError("新建工作沟通页面解析失败:未找到 fdId")
|
||||
logger.info("获取新建草稿 fdId: %s, 通知方式字段: %s, 页面当前用户ID: %s", fd_id, notify_field, creator_id or "无")
|
||||
return fd_id, notify_field, creator_id
|
||||
|
||||
|
||||
def submit_work_communication(
|
||||
session,
|
||||
receiver_ids,
|
||||
receiver_names,
|
||||
subject,
|
||||
content,
|
||||
attachment_ids=None,
|
||||
creator_id=None,
|
||||
category_id=FD_CATEGORY_DEFAULT,
|
||||
):
|
||||
"""
|
||||
提交工作沟通(新建),成功返回沟通文档 ID(fdId)。
|
||||
|
||||
真实提交端点:kmCollaborateMain.do?method=save&s_seq=1(aa.md 中 user.jsp 为错误端点)。
|
||||
流程:打开新建页取草稿 fdId 与通知方式随机字段 → 以真实表单结构 POST 保存。
|
||||
多值分隔符:多人参与人 / 多附件 ID 以「;」分号拼接(真实抓包确认,非逗号)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
receiver_ids: 接收人 ID,单个字符串或列表(多个以「;」分号分隔)
|
||||
receiver_names: 接收人姓名,单个字符串或列表(顺序与 ID 一致)
|
||||
subject: 标题
|
||||
content: 内容(支持 HTML 富文本)
|
||||
attachment_ids: 附件 ID(attid),单个字符串或列表(多个以「;」分号分隔),可空
|
||||
creator_id: 创建人(当前操作人)ID,必填;为空时尝试从新建页自动提取
|
||||
category_id: 沟通类型,可传中文名(如「工作安排」)或类型 ID,默认「工作安排」
|
||||
|
||||
Returns:
|
||||
沟通文档 ID(fdId,字符串)
|
||||
|
||||
Raises:
|
||||
ValueError: 缺少必填参数
|
||||
RuntimeError: 提交失败
|
||||
OALoginExpiredError: OA 登录态已失效
|
||||
"""
|
||||
# 沟通类型:支持中文名 -> ID 映射,空值回退默认「工作安排」(fdCategoryId 必填)
|
||||
if category_id in FD_CATEGORY_MAP:
|
||||
category_id = FD_CATEGORY_MAP[category_id]
|
||||
elif not category_id:
|
||||
category_id = FD_CATEGORY_DEFAULT
|
||||
|
||||
receiver_ids_str = ";".join(receiver_ids) if isinstance(receiver_ids, list) else receiver_ids
|
||||
receiver_names_str = ";".join(receiver_names) if isinstance(receiver_names, list) else receiver_names
|
||||
if isinstance(attachment_ids, list):
|
||||
attachment_ids_str = ";".join(attachment_ids)
|
||||
else:
|
||||
attachment_ids_str = attachment_ids or ""
|
||||
|
||||
# 1) 打开新建页,取草稿 fdId、通知方式随机字段、当前用户 ID(creator_id 兜底来源)
|
||||
fd_id, notify_field, page_creator_id = _get_add_page_fd_info(session)
|
||||
creator_id = creator_id or page_creator_id
|
||||
if not creator_id:
|
||||
raise ValueError("docCreatorId(creator_id) 必填,且无法从新建页自动提取,请显式传入当前操作人的用户 ID")
|
||||
|
||||
# 2) 组装保存请求(结构对齐真实抓包的 method=save&s_seq=1 表单体)
|
||||
data = {
|
||||
"fdId": fd_id,
|
||||
"fdNumber": "",
|
||||
"participantIds": receiver_ids_str,
|
||||
"participantNames": receiver_names_str,
|
||||
"docSubject": subject,
|
||||
"fdIsPriority": "",
|
||||
"fdCategoryId": category_id,
|
||||
"fdContent": _encode_fd_content(content),
|
||||
"attachmentForms.attachment.fdModelId": "",
|
||||
"attachmentForms.attachment.extParam": "",
|
||||
"attachmentForms.attachment.fdModelName": KM_COLLABORATE_MODEL,
|
||||
"attachmentForms.attachment.fdKey": "attachment",
|
||||
"attachmentForms.attachment.fdAttType": "",
|
||||
"attachmentForms.attachment.fdMulti": "",
|
||||
"attachmentForms.attachment.deletedAttachmentIds": "",
|
||||
"attachmentForms.attachment.attachmentIds": attachment_ids_str,
|
||||
"__landray_fileattachment": "",
|
||||
"fdNotifyType": "todo",
|
||||
"__notify_type_placeholder": "todo", # 占位,下方替换为真实随机字段名
|
||||
"_fdPartnerOperating": "true",
|
||||
"fdPartnerOperating": "true",
|
||||
"fdIsOnlyView": "false",
|
||||
"fdIsReminders": "false",
|
||||
"fdRemindersDay_hidden": "",
|
||||
"fdRemindersDay": "2",
|
||||
"docCreatorId": creator_id,
|
||||
}
|
||||
if notify_field:
|
||||
data[notify_field] = data.pop("__notify_type_placeholder")
|
||||
else:
|
||||
data.pop("__notify_type_placeholder", None)
|
||||
|
||||
# 3) POST 保存
|
||||
session.post(KM_COLLABORATE_SAVE_URL, params={"method": "save", "s_seq": "1"}, data=data, timeout=30)
|
||||
resp = _check_response(session.response, "工作沟通提交")
|
||||
text = resp.text or ""
|
||||
|
||||
# 成功标志:返回「您的操作已成功!」提示页(自动关闭),而非数字 ID
|
||||
if "您的操作已成功" in text:
|
||||
logger.info("工作沟通发送成功, 文档ID: %s", fd_id)
|
||||
return fd_id
|
||||
|
||||
raise RuntimeError(f"提交工作沟通失败: {text[:200]}")
|
||||
|
||||
|
||||
# ==================== 一键推送入口 ====================
|
||||
def _to_list(value):
|
||||
"""把单个字符串或列表统一成列表(空值返回空列表)。"""
|
||||
if not value:
|
||||
return []
|
||||
return [value] if isinstance(value, str) else list(value)
|
||||
|
||||
|
||||
def send_work_communication(
|
||||
receiver_keywords,
|
||||
subject,
|
||||
content,
|
||||
attachment_paths=None,
|
||||
creator_id=None,
|
||||
category=None,
|
||||
):
|
||||
"""
|
||||
发送工作沟通(一键推送入口)。完整流程:解析接收人 -> 上传附件 -> 提交沟通。
|
||||
- 接收人支持多个,用工号或姓名(姓名同名时建议用工号保证准确);
|
||||
- 附件支持多个,任一上传失败即整体失败(不发送部分数据);
|
||||
- 所有步骤成功才返回沟通文档 ID(fdId)。
|
||||
|
||||
Args:
|
||||
receiver_keywords: 接收人工号或姓名,单个字符串或列表
|
||||
subject: 沟通标题
|
||||
content: 沟通内容(支持 HTML 富文本)
|
||||
attachment_paths: 附件文件路径,单个字符串或列表,可空
|
||||
creator_id: 创建人(当前操作人)用户 ID;为空时尝试从新建页自动提取
|
||||
category: 沟通类型,可传中文名(如「工作安排」「信息传递」)或类型 ID,默认「工作安排」
|
||||
|
||||
Returns:
|
||||
沟通文档 ID(fdId,字符串)
|
||||
|
||||
Raises:
|
||||
ValueError: 缺少必填参数
|
||||
RuntimeError: 接收人解析失败 / 附件上传失败 / 提交失败(含具体原因)
|
||||
OALoginExpiredError: OA 登录态已失效
|
||||
"""
|
||||
if not subject or not subject.strip():
|
||||
raise ValueError("subject(标题) 不能为空")
|
||||
if not content or not content.strip():
|
||||
raise ValueError("content(内容) 不能为空")
|
||||
|
||||
session = build_session()
|
||||
|
||||
# ---- 1. 解析接收人 ----
|
||||
receiver_ids, receiver_names = [], []
|
||||
unresolved = []
|
||||
for kw in _to_list(receiver_keywords):
|
||||
kw = str(kw).strip()
|
||||
if not kw:
|
||||
continue
|
||||
result = search_person(session, kw)
|
||||
if result:
|
||||
pid, pname = result
|
||||
receiver_ids.append(pid)
|
||||
receiver_names.append(pname)
|
||||
logger.info("接收人[%s] -> %s (ID: %s)", kw, pname, pid)
|
||||
else:
|
||||
unresolved.append(kw)
|
||||
|
||||
if not receiver_ids:
|
||||
raise RuntimeError("未解析到任何接收人,请检查传入的工号/姓名")
|
||||
if unresolved:
|
||||
raise RuntimeError(f"以下接收人解析失败,已中止发送: {', '.join(unresolved)}")
|
||||
|
||||
# ---- 2. 上传附件(任一失败即整体失败) ----
|
||||
attachment_ids = []
|
||||
for path in _to_list(attachment_paths):
|
||||
attid = upload_attachment(session, path)
|
||||
attachment_ids.append(attid)
|
||||
logger.info("附件[%s] -> attid: %s", path, attid)
|
||||
|
||||
# ---- 3. 提交沟通 ----
|
||||
return submit_work_communication(
|
||||
session=session,
|
||||
receiver_ids=receiver_ids,
|
||||
receiver_names=receiver_names,
|
||||
subject=subject,
|
||||
content=content,
|
||||
attachment_ids=attachment_ids or None,
|
||||
creator_id=creator_id,
|
||||
category_id=category,
|
||||
)
|
||||
|
||||
|
||||
def _send_work_communication_wrapped(receiver_keywords, subject, content, attachment_paths="",
|
||||
creator_id="", category="工作安排"):
|
||||
"""单条工作沟通推送(捕获异常,返回 result dict)。"""
|
||||
try:
|
||||
doc_id = send_work_communication(
|
||||
receiver_keywords=receiver_keywords,
|
||||
subject=subject,
|
||||
content=content,
|
||||
attachment_paths=attachment_paths or None,
|
||||
creator_id=creator_id or None,
|
||||
category=category,
|
||||
)
|
||||
return {"success": True, "message": f"工作沟通发送成功,文档ID: {doc_id}", "doc_id": doc_id}
|
||||
except SystemExit as e:
|
||||
return {"success": False, "message": str(e), "doc_id": ""}
|
||||
except Exception as e:
|
||||
logger.error("工作沟通推送失败: %s", e)
|
||||
return {"success": False, "message": f"工作沟通推送失败: {e}", "doc_id": ""}
|
||||
|
||||
|
||||
# ==================== 主入口(影刀指令) ====================
|
||||
def main(messages=None, receiver_keywords=None, subject=None, content=None,
|
||||
attachment_paths="", creator_id="", category="工作安排"):
|
||||
"""
|
||||
影刀指令入口:发送工作沟通推送。
|
||||
|
||||
支持两种调用方式:
|
||||
1) main(messages):messages 为列表,每条含字段
|
||||
{receivers, subject, content, attachment_paths, creator_id, category},
|
||||
对应 notice 模块 oa_work_communications 全局变量结构,逐条推送
|
||||
2) main(receiver_keywords=..., subject=..., content=..., ...):单条推送(向后兼容)
|
||||
|
||||
Returns:
|
||||
{"success": bool, "message": str, "doc_id": str};并写入影刀全局变量 push_result。
|
||||
"""
|
||||
if isinstance(messages, list) and messages:
|
||||
results = []
|
||||
for i, msg in enumerate(messages, 1):
|
||||
r = _send_work_communication_wrapped(
|
||||
receiver_keywords=msg.get("receivers", []),
|
||||
subject=msg.get("subject", ""),
|
||||
content=msg.get("content", ""),
|
||||
attachment_paths=msg.get("attachment_paths", ""),
|
||||
creator_id=msg.get("creator_id", ""),
|
||||
category=msg.get("category", "工作安排"),
|
||||
)
|
||||
results.append(r)
|
||||
logger.info("[%d/%d] %s", i, len(messages), r.get("message"))
|
||||
ok = sum(1 for r in results if r.get("success"))
|
||||
result = {
|
||||
"success": ok == len(results),
|
||||
"message": f"共推送 {len(results)} 条,成功 {ok} 条",
|
||||
"doc_id": ",".join(r.get("doc_id", "") for r in results if r.get("doc_id")),
|
||||
}
|
||||
else:
|
||||
result = _send_work_communication_wrapped(
|
||||
receiver_keywords=receiver_keywords or [],
|
||||
subject=subject or "",
|
||||
content=content or "",
|
||||
attachment_paths=attachment_paths,
|
||||
creator_id=creator_id,
|
||||
category=category,
|
||||
)
|
||||
_set_glv("push_result", result)
|
||||
logger.info("推送结果: %s", result)
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 本地独立运行调试示例:messages 结构同 notice 模块的 oa_work_communications 全局变量,
|
||||
# 逐条调用 main 推送(影刀中同样按该结构循环推送)。
|
||||
messages = [
|
||||
{
|
||||
"receivers": ["37036361", "37001166"], # 测试接收人(多人)
|
||||
"subject": "2026年8月员工参保结果告知书",
|
||||
"content": "<p>【测试】重庆区域门店8月新参保已完成,请各门店传达告知。</p>",
|
||||
"attachment_paths": [],
|
||||
"category": "工作安排",
|
||||
},
|
||||
{
|
||||
"receivers": ["37036361", "37001166"],
|
||||
"subject": "2026年8月员工参保单位变更确认",
|
||||
"content": "<p>【测试】本月人力资源部已输出“工作与参保单位不一致”人员,请完成转移确认。</p>",
|
||||
"attachment_paths": [],
|
||||
"category": "工作安排",
|
||||
},
|
||||
]
|
||||
main(messages)
|
||||
result = main(messages)
|
||||
print("RESULT:", result)
|
||||
Reference in New Issue
Block a user