diff --git a/.gitignore b/.gitignore index bd275a2..7b95f31 100644 --- a/.gitignore +++ b/.gitignore @@ -13,8 +13,13 @@ sdist/ wheels/ *.manifest *.spec +# 桌面版打包产物(desktop 专属目录,不落根目录) +desktop/releases/ +desktop/build/ pip-log.txt pip-delete-this-directory.txt +webhost/frontend/node_modules +webhost/frontend/dist/ # ---------- 虚拟环境 ---------- .venv/ diff --git a/README.md b/README.md index f12805f..07a8e82 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ HR 业务流程自动化(37duAutomation):覆盖 HRBP OA 审批、EHR 数 * **EHR 数据处理自动化**:对接 HR 平台接口与本地 Excel,完成考勤异常核对、排班异常识别、工资卡核对、社保增减名单/告知书、雇主险名额等; -* **影刀 RPA 单文件版**:`yingdao/` 下按业务隔离的单文件自包含脚本,可直接导入影刀平台运行。 +* **影刀 RPA 单文件版**:`workflows/` 下按业务隔离的单文件自包含脚本,可直接导入影刀平台运行。 ## 项目结构 @@ -35,7 +35,7 @@ Process-Automation/ │ │ ├── employer_insurance/ # 雇主险增减操作 │ │ └── roster/ # 花名册导出与查询 │ └── utils/ # 智能重试、日志 -├── yingdao/ # 影刀 RPA 单文件版本(按需求单编号目录归档,对应 docs/需求单/XQ00xx) +├── workflows/ # 影刀 RPA 单文件版本(按需求单编号目录归档,对应 docs/需求单/XQ00xx) │ ├── share/ # 共享指令:钉钉群机器人/推送、OA/HR 登录、花名册导出、工作沟通 │ ├── XQ0001 排班异常识别/ # 调动/预入职台账导出 + 排班异常判定(钉钉单聊推送) │ ├── XQ0002 雇主险增减操作/ # 名额调度、变更清单导出、增减员导入 @@ -105,32 +105,32 @@ pip install -r requirements.txt # 影刀版脚本(单文件自包含,直接运行): # 排班异常识别(第二步导出 + 第三步识别) -python "yingdao/XQ0001 排班异常识别/transfer_roster_export.py" -python "yingdao/XQ0001 排班异常识别/pre_entry_roster_export.py" -python "yingdao/XQ0001 排班异常识别/shift_abnormal_check.py" +python "workflows/XQ0001 排班异常识别/transfer_roster_export.py" +python "workflows/XQ0001 排班异常识别/pre_entry_roster_export.py" +python "workflows/XQ0001 排班异常识别/shift_abnormal_check.py" # 雇主险增减操作(名额调度、增减员导入) -python "yingdao/XQ0002 雇主险增减操作/roster_filter.py" -python "yingdao/XQ0002 雇主险增减操作/employer_insurance_schedule.py" -python "yingdao/XQ0002 雇主险增减操作/add_sub_import.py" +python "workflows/XQ0002 雇主险增减操作/roster_filter.py" +python "workflows/XQ0002 雇主险增减操作/employer_insurance_schedule.py" +python "workflows/XQ0002 雇主险增减操作/add_sub_import.py" # OA 审批流程审核(请假 / 加班 / 离职电子签) -python "yingdao/XQ0003 EHR系统请假流程审核/leave_approval.py" -python "yingdao/XQ0004 EHR系统加班流程审核/overtime_approval.py" -python "yingdao/XQ0020 EHR系统离职电子签流程审核/resign_e_sign_approval.py" +python "workflows/XQ0003 EHR系统请假流程审核/leave_approval.py" +python "workflows/XQ0004 EHR系统加班流程审核/overtime_approval.py" +python "workflows/XQ0020 EHR系统离职电子签流程审核/resign_e_sign_approval.py" # 考勤异常处理(周 / 月) -python "yingdao/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py" -python "yingdao/XQ0010 EHR系统月考勤异常处理/attendance_abnormal_monthly.py" +python "workflows/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py" +python "workflows/XQ0010 EHR系统月考勤异常处理/attendance_abnormal_monthly.py" # 社保增减名单梳理 / 告知书制作与下发 -python "yingdao/XQ0007 OA系统社保增减名单梳理/social_change.py" -python "yingdao/XQ0015 参保成功及异常告知书制作与下发/notice_mail_merge.py" +python "workflows/XQ0007 OA系统社保增减名单梳理/social_change.py" +python "workflows/XQ0015 参保成功及异常告知书制作与下发/notice_mail_merge.py" # 先运行登录指令写入共享登录态,再执行业务脚本 -python yingdao/share/oa_login.py -python yingdao/share/hr_login.py -python yingdao/share/roster_export.py +python workflows/share/oa_login.py +python workflows/share/hr_login.py +python workflows/share/roster_export.py ``` ## 文档体系 @@ -144,9 +144,9 @@ python yingdao/share/roster_export.py ## 注意事项 1. 确保已安装 Chrome/Edge; -2. 首次运行需手动登录一次并缓存会话/cookie(或先运行 `yingdao/share/` 下的 `oa_login.py` / `hr_login.py` 写入共享登录态); +2. 首次运行需手动登录一次并缓存会话/cookie(或先运行 `workflows/share/` 下的 `oa_login.py` / `hr_login.py` 写入共享登录态); 3. OA/HR 需在登录态有效期内运行,脚本会自动重登或提示重新登录; -4. 影刀版本为单文件自包含,直接导入影刀平台运行;业务脚本不 import 共享指令模块,仅读 cookies 文件、写全局变量,消息生成与发送解耦(详见 `yingdao/README.md`)。 +4. 影刀版本为单文件自包含,直接导入影刀平台运行;业务脚本不 import 共享指令模块,仅读 cookies 文件、写全局变量,消息生成与发送解耦(详见 `workflows/README.md`)。 -> **影刀版与 app 版**:开发流程为「先 app 版(`app/`,模块化蓝图)测试通过 → 影刀版(`yingdao/`,单文件自包含)落地部署」;后续更新与维护均以**影刀版为部署/维护真源**,正式上线时全量同步回 app 版,使蓝图与真源保持一致(如排班异常识别、雇主险增减操作)。 +> **影刀版与 app 版**:开发流程为「先 app 版(`app/`,模块化蓝图)测试通过 → 影刀版(`workflows/`,单文件自包含)落地部署」;后续更新与维护均以**影刀版为部署/维护真源**,正式上线时全量同步回 app 版,使蓝图与真源保持一致(如排班异常识别、雇主险增减操作)。 diff --git a/docs/迭代规划.md b/docs/迭代规划.md index be2675a..dbe9937 100644 --- a/docs/迭代规划.md +++ b/docs/迭代规划.md @@ -18,7 +18,7 @@ * **app 版(`app/service/hrbp/`)**:模块化、有公共层(登录/会话/配置/hr\_api),每个业务子模块已有明确入口函数(如 `leave_approval.py`、`shift_abnormal_check.py`、`employer_insurance.py`),是**天然的任务候选**。 -* **影刀版(`yingdao/`)**:单文件自包含,适配 RPA,含浏览器自动化类任务(台账导出、增减员导入、滑块登录),不适合同步接口直连,需走**异步 + 事件驱动**接入。 +* **影刀版(`workflows/`)**:单文件自包含,适配 RPA,含浏览器自动化类任务(台账导出、增减员导入、滑块登录),不适合同步接口直连,需走**异步 + 事件驱动**接入。 * **两者关系**:app 为开发蓝图、影刀为部署真源;演进层应**统一挂在影刀版之上**,app 版作为逻辑回归基线。 diff --git a/docs/需求单/XQ0001 排班异常识别/开发文档.md b/docs/需求单/XQ0001 排班异常识别/开发文档.md index ab918de..6802fa8 100644 --- a/docs/需求单/XQ0001 排班异常识别/开发文档.md +++ b/docs/需求单/XQ0001 排班异常识别/开发文档.md @@ -1,13 +1,13 @@ # 排班异常识别 —— 开发文档 > 需求单:XQ0001 · 状态:可行(代码已完成落地) -> 模块:`yingdao/XQ0001 排班异常识别/`(影刀版,**主版本**) +> 模块:`workflows/XQ0001 排班异常识别/`(影刀版,**主版本**) > 说明:`app/service/hrbp/ehr/shift_abnormal/` 为开发蓝图,影刀版为部署与维护真源;逻辑以影刀版为准,上线时全量同步回 app 版。 ## 一、代码结构 ``` -yingdao/XQ0001 排班异常识别/ +workflows/XQ0001 排班异常识别/ ├── transfer_roster_export.py # 第二步:调动台账导出(浏览器自动化 DrissionPage) ├── pre_entry_roster_export.py # 第二步:预入职台账导出(浏览器自动化 DrissionPage) └── shift_abnormal_check.py # 第三步:排班异常识别 + 店长分组钉钉单聊推送消息构造 @@ -79,7 +79,7 @@ yingdao/XQ0001 排班异常识别/ ### 3.3 钉钉单聊推送(发送由共享指令完成) -`shift_abnormal_check.py` **只负责生成消息**,写入全局变量 `messages`;实际发送由共享指令「37du钉钉单聊推送」(`yingdao/share/dingtalk_dws_push.py`)在流程中完成,生成与发送解耦。 +`shift_abnormal_check.py` **只负责生成消息**,写入全局变量 `messages`;实际发送由共享指令「37du钉钉单聊推送」(`workflows/share/dingtalk_dws_push.py`)在流程中完成,生成与发送解耦。 消息体文案按异常原因区分: @@ -108,11 +108,11 @@ yingdao/XQ0001 排班异常识别/ ```bash # 第二步(需先通过「37duHR登录」指令写入共享登录态;会弹出浏览器窗口,勿关闭) -python yingdao/XQ0001 排班异常识别/transfer_roster_export.py -python yingdao/XQ0001 排班异常识别/pre_entry_roster_export.py +python workflows/XQ0001 排班异常识别/transfer_roster_export.py +python workflows/XQ0001 排班异常识别/pre_entry_roster_export.py # 第三步:排班异常识别(生成名单留档 + 构造钉钉单聊消息,写入全局变量 messages) -python yingdao/XQ0001 排班异常识别/shift_abnormal_check.py +python workflows/XQ0001 排班异常识别/shift_abnormal_check.py ``` 第三步运行前需先准备好花名册(含列:工号/姓名/四级部门/岗位,由「37du花名册导出」指令生成)。 diff --git a/docs/需求单/XQ0001 排班异常识别/流程文档.md b/docs/需求单/XQ0001 排班异常识别/流程文档.md index cb95a00..54601bc 100644 --- a/docs/需求单/XQ0001 排班异常识别/流程文档.md +++ b/docs/需求单/XQ0001 排班异常识别/流程文档.md @@ -1,7 +1,7 @@ # 排班异常识别 —— 流程文档 > 需求单:XQ0001 · 状态:可行(代码已完成落地) -> 依据:`yingdao/XQ0001 排班异常识别/`(影刀版,主版本) +> 依据:`workflows/XQ0001 排班异常识别/`(影刀版,主版本) ## 一、整体流程概览 @@ -56,7 +56,7 @@ ## 五、第四步:发送 -由共享指令「37du钉钉单聊推送」(`yingdao/share/dingtalk_dws_push.py`)读取全局变量 `messages` 完成实际单聊发送。 +由共享指令「37du钉钉单聊推送」(`workflows/share/dingtalk_dws_push.py`)读取全局变量 `messages` 完成实际单聊发送。 ## 六、判断口径小结 diff --git a/docs/需求单/XQ0001 排班异常识别/需求文档.md b/docs/需求单/XQ0001 排班异常识别/需求文档.md index 578a7f6..df75e6b 100644 --- a/docs/需求单/XQ0001 排班异常识别/需求文档.md +++ b/docs/需求单/XQ0001 排班异常识别/需求文档.md @@ -1,7 +1,7 @@ # 排班异常识别 —— 需求文档 > 需求单:XQ0001 · 状态:可行(代码已完成落地) -> 编写:小布丁 · 依据:`yingdao/XQ0001 排班异常识别/`(影刀版,主版本) +> 编写:小布丁 · 依据:`workflows/XQ0001 排班异常识别/`(影刀版,主版本) > 说明:`app/service/hrbp/ehr/shift_abnormal/` 为开发蓝图(先在此验证 V1),影刀版为部署与维护真源;后续改动以影刀版为准,上线时全量同步回 app 版。 ## 一、需求背景 diff --git a/docs/需求单/XQ0002 雇主险增减操作/开发文档.md b/docs/需求单/XQ0002 雇主险增减操作/开发文档.md index 37e4786..259de1e 100644 --- a/docs/需求单/XQ0002 雇主险增减操作/开发文档.md +++ b/docs/需求单/XQ0002 雇主险增减操作/开发文档.md @@ -5,7 +5,7 @@ > > * app 版:`app/service/hrbp/ehr/employer_insurance/`(config.py / roster\_filter.py / employer\_insurance.py) > -> * 影刀版:`yingdao/XQ0002 雇主险增减操作/`(roster\_filter.py / employer\_insurance\_schedule.py / add\_sub\_import.py / export\_change\_sheet.py) +> * 影刀版:`workflows/XQ0002 雇主险增减操作/`(roster\_filter.py / employer\_insurance\_schedule.py / add\_sub\_import.py / export\_change\_sheet.py) > 更新日期:2026-08-14 ## 1. 概述 @@ -66,7 +66,7 @@ pip install DrissionPage python-dotenv requests opencv-python numpy Pillow # | 文件 | 职责 | | ------------------------------------ | ------------------------------------------------------------------------------------ | -| `yingdao/share/roster_export.py`(共享) | 步骤1 导出:HR 登录(滑块验证码)→ 花名册自定义导出「雇主险增减员导出模板」→ 合并下载文件为统一格式源表 | +| `workflows/share/roster_export.py`(共享) | 步骤1 导出:HR 登录(滑块验证码)→ 花名册自定义导出「雇主险增减员导出模板」→ 合并下载文件为统一格式源表 | | `roster_filter.py` | 步骤2 筛选复制:与 app 版 `roster_filter.py` 逻辑一致 | | `employer_insurance_schedule.py` | 步骤3 调度:与 app 版 `employer_insurance.py` 逻辑一致 | | `export_change_sheet.py` | 步骤3.5 导出变更清单独立工作簿:值+样式复制「雇员变更清单」sheet 为独立 xlsx(无公式,避免跨 sheet 引用报 #REF!) | @@ -246,7 +246,7 @@ python app/service/hrbp/ehr/employer_insurance/employer_insurance.py ### 6.2 影刀版 ```bash -python yingdao/share/roster_export.py # 步骤1:导出花名册(源表缺失时) +python workflows/share/roster_export.py # 步骤1:导出花名册(源表缺失时) python roster_filter.py # 步骤2:筛选复制 python employer_insurance_schedule.py # 步骤3:调度(先手动刷新目标文件公式) python export_change_sheet.py # 步骤3.5:导出变更清单独立工作簿(先 Ctrl+S 保存) diff --git a/docs/需求单/XQ0002 雇主险增减操作/评分文档.md b/docs/需求单/XQ0002 雇主险增减操作/评分文档.md index ac77a3e..89720bf 100644 --- a/docs/需求单/XQ0002 雇主险增减操作/评分文档.md +++ b/docs/需求单/XQ0002 雇主险增减操作/评分文档.md @@ -3,7 +3,7 @@ > 状态:已评估(v2,依据优化后代码重评估;待业务方签字/网络部审批/HR备案) > 所属需求单:XQ0002 雇主险增减操作 -关联代码:`app/service/hrbp/ehr/employer_insurance/employer_insurance.py`(步骤2调度)、`roster_filter.py`、`export_change_sheet.py`、`config.py`;影刀版 `yingdao/XQ0002 雇主险增减操作/` +关联代码:`app/service/hrbp/ehr/employer_insurance/employer_insurance.py`(步骤2调度)、`roster_filter.py`、`export_change_sheet.py`、`config.py`;影刀版 `workflows/XQ0002 雇主险增减操作/` ## 一、场景描述 diff --git a/docs/需求单/XQ0002 雇主险增减操作/需求文档.md b/docs/需求单/XQ0002 雇主险增减操作/需求文档.md index 6f816f4..f3cb4d1 100644 --- a/docs/需求单/XQ0002 雇主险增减操作/需求文档.md +++ b/docs/需求单/XQ0002 雇主险增减操作/需求文档.md @@ -2,7 +2,7 @@ > 版本:v2.1.0 > 状态:待评审 -> 所属模块:`app/service/hrbp/ehr/employer_insurance/`(app 版)+ `yingdao/XQ0002 雇主险增减操作/`(影刀版) +> 所属模块:`app/service/hrbp/ehr/employer_insurance/`(app 版)+ `workflows/XQ0002 雇主险增减操作/`(影刀版) > 更新日期:2026-08-31 ## 1. 背景 @@ -152,8 +152,8 @@ - `config.py`:路径、Sheet 名、列名映射、校验常量、功能开关 - `roster_filter.py`:步骤2 筛选复制(含按需导出) - `employer_insurance.py`:步骤3 调度(校验/初始化/业务处理/分配/输出) -- 影刀版:`yingdao/XQ0002 雇主险增减操作/` - - 步骤1 导出花名册:复用 `yingdao/share/roster_export.py`(「37du花名册导出」指令) +- 影刀版:`workflows/XQ0002 雇主险增减操作/` + - 步骤1 导出花名册:复用 `workflows/share/roster_export.py`(「37du花名册导出」指令) - `roster_filter.py`:步骤2 筛选复制 - `employer_insurance_schedule.py`:步骤3 调度 - `export_change_sheet.py`:步骤3.5 导出变更清单独立工作簿 diff --git a/docs/需求单/XQ0003 EHR系统请假流程审核/开发文档.md b/docs/需求单/XQ0003 EHR系统请假流程审核/开发文档.md index 9dbc842..65e61a7 100644 --- a/docs/需求单/XQ0003 EHR系统请假流程审核/开发文档.md +++ b/docs/需求单/XQ0003 EHR系统请假流程审核/开发文档.md @@ -4,7 +4,7 @@ > 对应文件: > - App 版:`app/service/hrbp/oa/leave/`(`leave_approval.py` / `parser.py` / `validator.py` / `reporter.py`) > - 公共审批引擎:`app/service/hrbp/oa/common/approval_flow.py`(请假/加班共用) -> - 影刀单文件版:`yingdao/leave_approval_yingdao.py` +> - 影刀单文件版:`workflows/leave_approval_workflows.py` > 更新日期:2026-08-17 ## 1. 概述 @@ -76,7 +76,7 @@ pip install DrissionPage python-dotenv pyautogui pywin32 pyperclip Pillow numpy ### 4.2 影刀单文件版 -`yingdao/leave_approval_yingdao.py` 一个文件按顺序包含: +`workflows/leave_approval_workflows.py` 一个文件按顺序包含: | 段落 | 内容 | |------|------| @@ -256,7 +256,7 @@ python -m app.service.hrbp.oa.leave.leave_approval python -c "from app.service.hrbp.oa.leave.leave_approval import main; main()" # 影刀单文件版(可直接双击运行或命令行) -python leave_approval_yingdao.py +python leave_approval_workflows.py ``` `run_flow` 返回报告文本,主流程结束打印报告并推送钉钉。 @@ -275,7 +275,7 @@ python leave_approval_yingdao.py ## 10. 扩展与维护注意事项 -- **新增假期类型**:① `app/service/hrbp/common/config.py` 的 `VACATION_TYPE_MAP`(编码→名称);② `validator.py` 的 `HOURLY_LEAVE_TYPES` / `LEAVE_TYPE_GROUP_1` / `LEAVE_TYPE_GROUP_2` 分组。影刀版需同步 `leave_approval_yingdao.py` 内联定义。 +- **新增假期类型**:① `app/service/hrbp/common/config.py` 的 `VACATION_TYPE_MAP`(编码→名称);② `validator.py` 的 `HOURLY_LEAVE_TYPES` / `LEAVE_TYPE_GROUP_1` / `LEAVE_TYPE_GROUP_2` 分组。影刀版需同步 `leave_approval_workflows.py` 内联定义。 - **OCR 关键词调整**:改 `app/utils/ocr.py` 的 `LEAVE_KEYWORDS`;影刀版同步改内置 `_OCR_LEAVE_KEYWORDS`。 - **附件保存目录**:`oa/common/config.py` 的 `ATTACHMENT_SAVE_DIR`(影刀版 `_verify_attachment`/`download_attachment` 的 `save_dir` 默认值)。 - **真实审批开关**:App 版改 `.env` 的 `overtime_approve_enabled`;影刀版改 `APPROVE_ENABLED` 常量。 diff --git a/docs/需求单/XQ0003 EHR系统请假流程审核/需求文档.md b/docs/需求单/XQ0003 EHR系统请假流程审核/需求文档.md index 824f467..cd5a11a 100644 --- a/docs/需求单/XQ0003 EHR系统请假流程审核/需求文档.md +++ b/docs/需求单/XQ0003 EHR系统请假流程审核/需求文档.md @@ -2,7 +2,7 @@ > 版本:v1.0 > 状态:待评审 -> 所属模块:`app/service/hrbp/oa/leave/`(App 版)+ `yingdao/leave_approval_yingdao.py`(影刀单文件版) +> 所属模块:`app/service/hrbp/oa/leave/`(App 版)+ `workflows/leave_approval_workflows.py`(影刀单文件版) > 更新日期:2026-08-17 ## 1. 背景 diff --git a/docs/需求单/XQ0004 EHR系统加班流程审核/开发文档.md b/docs/需求单/XQ0004 EHR系统加班流程审核/开发文档.md index 955c5c2..a500c04 100644 --- a/docs/需求单/XQ0004 EHR系统加班流程审核/开发文档.md +++ b/docs/需求单/XQ0004 EHR系统加班流程审核/开发文档.md @@ -4,7 +4,7 @@ > 对应文件: > - App 版:`app/service/hrbp/oa/work_overtime/`(`overtime_approval.py` / `parser.py` / `validator.py` / `reporter.py`) > - 公共审批引擎:`app/service/hrbp/oa/common/approval_flow.py`(请假/加班共用) -> - 影刀单文件版:`yingdao/overtime_approval_yingdao.py` +> - 影刀单文件版:`workflows/overtime_approval_workflows.py` > 更新日期:2026-08-17 ## 1. 概述 @@ -77,7 +77,7 @@ pip install DrissionPage python-dotenv chinese_calendar pyautogui pywin32 pyperc ### 4.2 影刀单文件版 -`yingdao/overtime_approval_yingdao.py` 一个文件按顺序包含: +`workflows/overtime_approval_workflows.py` 一个文件按顺序包含: | 段落 | 内容 | |------|------| @@ -290,7 +290,7 @@ python -m app.service.hrbp.oa.work_overtime.overtime_approval python -c "from app.service.hrbp.oa.work_overtime.overtime_approval import main; main()" # 影刀单文件版(可直接双击运行或命令行) -python overtime_approval_yingdao.py +python overtime_approval_workflows.py ``` `run_flow` 返回报告文本,主流程结束打印报告并推送钉钉。 @@ -309,7 +309,7 @@ python overtime_approval_yingdao.py ## 10. 扩展与维护注意事项 - **新增加班类型**:① `parser.py` 的 `OT_TYPE_MAP`;② `validator.validate_doc` 的分派分支。影刀版需同步内联定义。 -- **规则常量调整**:全部集中在 `oa/common/config.py`(App 版)与 `overtime_approval_yingdao.py` 顶部常量区:`WORK_START_TIME/WORK_END_TIME`(默认 09:00/18:00)、`FLEX_TRIGGER_TIME`(23:00)、`OT_MIN_HOURS`(1)、`CROSS_DAY_BEFORE_HOUR`(6)、`OT_REVIEW_DAYS`(8)、`MONTH_CUTOFF_DAY/HOUR`(2/12)、`ZHINENG_HALF_*`(职能半天 3.5/4.5h)、`OT_PRE_SHIFT_ARRIVE_*`(提前到岗证据窗口 1h)。 +- **规则常量调整**:全部集中在 `oa/common/config.py`(App 版)与 `overtime_approval_workflows.py` 顶部常量区:`WORK_START_TIME/WORK_END_TIME`(默认 09:00/18:00)、`FLEX_TRIGGER_TIME`(23:00)、`OT_MIN_HOURS`(1)、`CROSS_DAY_BEFORE_HOUR`(6)、`OT_REVIEW_DAYS`(8)、`MONTH_CUTOFF_DAY/HOUR`(2/12)、`ZHINENG_HALF_*`(职能半天 3.5/4.5h)、`OT_PRE_SHIFT_ARRIVE_*`(提前到岗证据窗口 1h)。 - **真实审批开关**:App 版改 `.env` 的 `overtime_approve_enabled`;影刀版改 `APPROVE_ENABLED` 常量。 - **审批按钮选择器变更**:改 `_APPROVE_BUTTONS`(通过 `#chooseSubmit` / 校验不通过未处理 `#backApplySubmit`)。 - **待办去重键**:以 `detail_url`(含 taskId)为键,详情链接结构变化需同步调整。 diff --git a/docs/需求单/XQ0004 EHR系统加班流程审核/需求文档.md b/docs/需求单/XQ0004 EHR系统加班流程审核/需求文档.md index 8086371..64092e6 100644 --- a/docs/需求单/XQ0004 EHR系统加班流程审核/需求文档.md +++ b/docs/需求单/XQ0004 EHR系统加班流程审核/需求文档.md @@ -2,7 +2,7 @@ > 版本:v1.0 > 状态:待评审 -> 所属模块:`app/service/hrbp/oa/work_overtime/`(App 版)+ `yingdao/overtime_approval_yingdao.py`(影刀单文件版) +> 所属模块:`app/service/hrbp/oa/work_overtime/`(App 版)+ `workflows/overtime_approval_workflows.py`(影刀单文件版) > 更新日期:2026-08-17 ## 1. 背景 diff --git a/docs/需求单/XQ0005 银行卡检查/开发文档.md b/docs/需求单/XQ0005 银行卡检查/开发文档.md index 11676f6..ca5058e 100644 --- a/docs/需求单/XQ0005 银行卡检查/开发文档.md +++ b/docs/需求单/XQ0005 银行卡检查/开发文档.md @@ -1,7 +1,7 @@ # 银行卡检查(影刀版)— 开发文档 > 版本:v1.1.0 -> 对应文件:`yingdao/bank_card_check_yingdao.py` +> 对应文件:`workflows/bank_card_check_workflows.py` > 更新日期:2026-08-14 ## 1. 概述 @@ -158,10 +158,10 @@ check_wage_card → 工资卡汇总表_核对结果.xlsx ```bash # 方式一:直接运行(影刀 / 命令行) -python bank_card_check_yingdao.py +python bank_card_check_workflows.py # 方式二:作为模块调用 -from bank_card_check_yingdao import run_bank_card_check +from bank_card_check_workflows import run_bank_card_check results = run_bank_card_check() ``` diff --git a/docs/需求单/XQ0005 银行卡检查/需求文档.md b/docs/需求单/XQ0005 银行卡检查/需求文档.md index 5d168de..d136130 100644 --- a/docs/需求单/XQ0005 银行卡检查/需求文档.md +++ b/docs/需求单/XQ0005 银行卡检查/需求文档.md @@ -2,7 +2,7 @@ > 版本:v1.1 > 状态:待评审 -> 所属模块:`yingdao/bank_card_check_yingdao.py`(单文件版,app 与影刀共用) +> 所属模块:`workflows/bank_card_check_workflows.py`(单文件版,app 与影刀共用) > 更新日期:2026-08-14 ## 1. 背景 @@ -135,7 +135,7 @@ HR 需要定期核对员工的工资卡信息(身份证号、姓名、银行 ## 9. 交付物 -- `yingdao/bank_card_check_yingdao.py`:完整主流程(登录、下载、补充开卡银行、核对、导出)。 +- `workflows/bank_card_check_workflows.py`:完整主流程(登录、下载、补充开卡银行、核对、导出)。 - 输出文件(目录可配置,默认 `D:\资料\人资\银行卡检查`): - `工资卡汇总表.xlsx` - `工资卡汇总表_核对结果.xlsx` diff --git a/docs/需求单/XQ0006 EHR系统周考勤异常处理/开发文档.md b/docs/需求单/XQ0006 EHR系统周考勤异常处理/开发文档.md index 60df1ca..e29c62c 100644 --- a/docs/需求单/XQ0006 EHR系统周考勤异常处理/开发文档.md +++ b/docs/需求单/XQ0006 EHR系统周考勤异常处理/开发文档.md @@ -1,7 +1,7 @@ # EHR 系统周考勤异常处理 — 开发文档 > 版本:v2.1.0 -> 对应文件:`app/service/hrbp/ehr/attendance/attendance_abnormal.py`(业务逻辑实现);生产调度脚本见 `yingdao/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py` +> 对应文件:`app/service/hrbp/ehr/attendance/attendance_abnormal.py`(业务逻辑实现);生产调度脚本见 `workflows/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py` > 更新日期:2026-08-25 ## 1. 概述 @@ -129,7 +129,7 @@ python attendance_abnormal.py python attendance_abnormal.py "D:\资料\人资\考勤异常" 2026-08 ``` -> **影刀调度(已确认)**:每周三 15:00 后触发,运行生产脚本 `yingdao/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py`。默认查询「上周一至上周日」,无需额外参数;如需要可在影刀任务中传入 save_dir。 +> **影刀调度(已确认)**:每周三 15:00 后触发,运行生产脚本 `workflows/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py`。默认查询「上周一至上周日」,无需额外参数;如需要可在影刀任务中传入 save_dir。 ```python # 作为模块调用 diff --git a/docs/需求单/XQ0006 EHR系统周考勤异常处理/需求文档.md b/docs/需求单/XQ0006 EHR系统周考勤异常处理/需求文档.md index 8447162..fc064de 100644 --- a/docs/需求单/XQ0006 EHR系统周考勤异常处理/需求文档.md +++ b/docs/需求单/XQ0006 EHR系统周考勤异常处理/需求文档.md @@ -3,7 +3,7 @@ > 版本:v1.3(草案) > 状态:待评审 > 所属模块: -> - `yingdao/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py`(生产调度脚本,影刀定时任务每周执行) +> - `workflows/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py`(生产调度脚本,影刀定时任务每周执行) > - `app/service/hrbp/ehr/attendance/attendance_abnormal.py`(业务逻辑实现,供本地/测试运行) > 创建时间:2026-08-14 > 更新日期:2026-08-28 @@ -120,7 +120,7 @@ HR 每周需处理 EHR 系统的考勤异常(迟到、早退、漏打卡、旷 ## 10. 交付物 -- `yingdao/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py`:生产调度脚本(影刀每周三执行)。 +- `workflows/XQ0006 EHR系统周考勤异常处理/attendance_abnormal.py`:生产调度脚本(影刀每周三执行)。 - `app/service/hrbp/ehr/attendance/attendance_abnormal.py`:业务逻辑实现(查询导出 + 分级 + 推送主流程)。 - 复用:`hr_api.fetch_all_attendance_abnormal`、`hr_api.adjust_abnormal`、`hr_session`、`utils.dingtalk_sender`。 - 输出:`D:\资料\人资\考勤异常\周考勤异常_{月份}_{时间戳}.xlsx`。 diff --git a/docs/需求单/XQ0007 OA系统社保增减名单梳理/开发文档.md b/docs/需求单/XQ0007 OA系统社保增减名单梳理/开发文档.md index 2675251..0bc2eee 100644 --- a/docs/需求单/XQ0007 OA系统社保增减名单梳理/开发文档.md +++ b/docs/需求单/XQ0007 OA系统社保增减名单梳理/开发文档.md @@ -1,10 +1,10 @@ # OA 社保增减名单梳理 — 开发文档 -> 版本:v2.4.0(employee_change_list.py)/ v2.1.0(si_insurance_check.py / social_change_yingdao.py) +> 版本:v2.4.0(employee_change_list.py)/ v2.1.0(si_insurance_check.py / social_change_workflows.py) > 对应文件: > - App 版主流程:`app/service/hrbp/oa/social_change/employee_change_list.py` > - App 版独立核对工具:`app/service/hrbp/oa/social_change/si_insurance_check.py` -> - 影刀统一单文件版:`yingdao/social_change_yingdao.py`(含 HR 滑块登录 + 钉钉推送,app 与影刀共用) +> - 影刀统一单文件版:`workflows/social_change_workflows.py`(含 HR 滑块登录 + 钉钉推送,app 与影刀共用) > 更新日期:2026-08-17 ## 1. 概述 @@ -14,7 +14,7 @@ 三套实现关系: - `employee_change_list.py`:主流程(导出 + 清洗 + 核对一条龙),复用 OA 共享层会话。 - `si_insurance_check.py`:独立工具,读「已清洗」名单(.xls/.xlsx)只做核对 + 标注,供已有名单的场景。 -- `social_change_yingdao.py`:统一单文件版(自包含 OA/HR 登录、滑块验证、导出、核对、钉钉推送),设计目标是避免维护 app/影刀两套版本。 +- `social_change_workflows.py`:统一单文件版(自包含 OA/HR 登录、滑块验证、导出、核对、钉钉推送),设计目标是避免维护 app/影刀两套版本。 完整链路: @@ -92,7 +92,7 @@ pip install DrissionPage python-dotenv requests xlrd openpyxl | `check_and_annotate` | 按工号去重 → 分批核对 → 追加结果列 → 导出 | | `check_participation` / `check_suspension` / `main` | 便捷入口;main 自动找项目内最新 `*参保*_去重.xlsx` / `*停保*_去重.xlsx` | -### 4.3 影刀统一单文件版(social_change_yingdao.py) +### 4.3 影刀统一单文件版(social_change_workflows.py) | 段落 | 内容 | |------|------| @@ -209,7 +209,7 @@ python -m app.service.hrbp.oa.social_change.employee_change_list 停保 2026-08- python -m app.service.hrbp.oa.social_change.si_insurance_check # 影刀统一单文件版(可放任意目录直接运行) -python social_change_yingdao.py [参保|停保] [YYYY-MM-DD] +python social_change_workflows.py [参保|停保] [YYYY-MM-DD] ``` 命令行参数:`参保/participate/participation`、`停保/suspend/suspension`,日期 `YYYY-MM-DD`;无参数默认参保 + 停保都跑。 diff --git a/docs/需求单/XQ0007 OA系统社保增减名单梳理/需求文档.md b/docs/需求单/XQ0007 OA系统社保增减名单梳理/需求文档.md index 398bdc5..6d38ce1 100644 --- a/docs/需求单/XQ0007 OA系统社保增减名单梳理/需求文档.md +++ b/docs/需求单/XQ0007 OA系统社保增减名单梳理/需求文档.md @@ -1,7 +1,7 @@ # OA 社保增减名单梳理 — 需求文档 > 版本:v2.4.0(employee_change_list.py)/ v2.1.0(si_insurance_check.py / 影刀单文件版) -> 所属模块:`app/service/hrbp/oa/social_change/`(App 版)+ `yingdao/social_change_yingdao.py`(影刀统一单文件版) +> 所属模块:`app/service/hrbp/oa/social_change/`(App 版)+ `workflows/social_change_workflows.py`(影刀统一单文件版) > 更新日期:2026-08-17 ## 1. 背景 diff --git a/docs/需求单/XQ0008 重庆社保增减员导入名单制作/开发文档.md b/docs/需求单/XQ0008 重庆社保增减员导入名单制作/开发文档.md index a867fab..7230854 100644 --- a/docs/需求单/XQ0008 重庆社保增减员导入名单制作/开发文档.md +++ b/docs/需求单/XQ0008 重庆社保增减员导入名单制作/开发文档.md @@ -3,9 +3,9 @@ > 版本:v1.2.0(generate\_add.py)/ v1.0.0(generate\_stop.py) > 对应文件: > -> - `yingdao/XQ0008 重庆社保增减员导入名单制作/generate_add.py`(增员:新参保 / 转移参保) +> - `workflows/XQ0008 重庆社保增减员导入名单制作/generate_add.py`(增员:新参保 / 转移参保) > -> - `yingdao/XQ0008 重庆社保增减员导入名单制作/generate_stop.py`(停保:减员) +> - `workflows/XQ0008 重庆社保增减员导入名单制作/generate_stop.py`(停保:减员) > 更新日期:2026-09-05 ## 1. 概述 @@ -169,8 +169,8 @@ find_source_file(*社保*.xlsx 取最新) + find_template_file(增员/减 ```bash # 影刀版(在模块目录内直接运行,单文件自包含) -python "yingdao\XQ0008 重庆社保增减员导入名单制作\generate_add.py" # 依次生成 转移参保 → 新参保 -python "yingdao\XQ0008 重庆社保增减员导入名单制作\generate_stop.py" # 生成停保名单(28号执行) +python "workflows\XQ0008 重庆社保增减员导入名单制作\generate_add.py" # 依次生成 转移参保 → 新参保 +python "workflows\XQ0008 重庆社保增减员导入名单制作\generate_stop.py" # 生成停保名单(28号执行) ``` - 增员日期规则:`1号 → 转移参保`,`11号 → 新参保`(`__main__` 按此先后执行;需强制指定类型可调用 `process_add_members('新参保')`)。 diff --git a/docs/需求单/XQ0008 重庆社保增减员导入名单制作/评分文档.md b/docs/需求单/XQ0008 重庆社保增减员导入名单制作/评分文档.md index 6777cb9..f029bf7 100644 --- a/docs/需求单/XQ0008 重庆社保增减员导入名单制作/评分文档.md +++ b/docs/需求单/XQ0008 重庆社保增减员导入名单制作/评分文档.md @@ -2,7 +2,7 @@ > 状态:初稿(依据《XQ0008 重庆社保增减员导入名单制作 需求文档》与影刀实现评估) -> 关联代码:`yingdao/XQ0008 重庆社保增减员导入名单制作/generate_add.py`、`generate_stop.py` +> 关联代码:`workflows/XQ0008 重庆社保增减员导入名单制作/generate_add.py`、`generate_stop.py` ## 一、场景描述 diff --git a/docs/需求单/XQ0008 重庆社保增减员导入名单制作/需求文档.md b/docs/需求单/XQ0008 重庆社保增减员导入名单制作/需求文档.md index e59d8ef..089d491 100644 --- a/docs/需求单/XQ0008 重庆社保增减员导入名单制作/需求文档.md +++ b/docs/需求单/XQ0008 重庆社保增减员导入名单制作/需求文档.md @@ -1,7 +1,7 @@ # 重庆社保增减员导入名单制作 — 需求文档 > 版本:v1.2.0(generate\_add.py)/ v1.0.0(generate\_stop.py)影刀单文件版 -> 所属模块:`yingdao/XQ0008 重庆社保增减员导入名单制作/`(generate\_add.py + generate\_stop.py) +> 所属模块:`workflows/XQ0008 重庆社保增减员导入名单制作/`(generate\_add.py + generate\_stop.py) > 更新日期:2026-09-05 > 对接人:周卫 diff --git a/requirements.txt b/requirements.txt index db27ae5..6ad8b34 100644 --- a/requirements.txt +++ b/requirements.txt @@ -14,4 +14,9 @@ onnxruntime rapidocr PyMuPDF pandas -requests \ No newline at end of file +requests +# ---------- Web 版(webhost/ 宿主:FastAPI + 前端构建) ---------- +fastapi +uvicorn +psutil +websockets \ No newline at end of file diff --git a/tests/hrbp/test_07_confirm_abnormal.py b/tests/hrbp/test_07_confirm_abnormal.py index 9722463..3c4856b 100644 --- a/tests/hrbp/test_07_confirm_abnormal.py +++ b/tests/hrbp/test_07_confirm_abnormal.py @@ -102,10 +102,10 @@ def main(): # 影刀单文件版静态就绪校验(不发起真实请求) import importlib - yingdao = importlib.import_module("yingdao.hr.attendance_abnormal") - assert callable(yingdao.confirm_abnormal), "影刀版缺少 confirm_abnormal" - assert callable(yingdao.adjust_abnormal), "影刀版缺少 adjust_abnormal" - assert yingdao.ATTENDANCE_ADJUST_URL.endswith("KqCountAbnormal.mc"), "影刀版确认接口地址异常" + workflows = importlib.import_module("workflows.hr.attendance_abnormal") + assert callable(workflows.confirm_abnormal), "影刀版缺少 confirm_abnormal" + assert callable(workflows.adjust_abnormal), "影刀版缺少 adjust_abnormal" + assert workflows.ATTENDANCE_ADJUST_URL.endswith("KqCountAbnormal.mc"), "影刀版确认接口地址异常" logger.info("[通过] 影刀单文件版 confirm_abnormal 已就绪(未发请求)") diff --git a/tests/rest_rules.py b/tests/rest_rules.py new file mode 100644 index 0000000..d14460b --- /dev/null +++ b/tests/rest_rules.py @@ -0,0 +1,126 @@ +from dataclasses import dataclass +from typing import Optional + + +@dataclass +class LeaveRule: + """正休规则返回对象""" + days: int # 默认正休天数 + rule_type: str # 规则类型:大小休 / 固休 / 天数限额排休 + max_days: Optional[int] = None # 限额排休时的上限天数 + note: str = "" # 备注说明 + + +class LeavePolicyEngine: + """ + 正休规则查询引擎 + 用法:直接调用 .query(所属单位, 组织类型, 职位序列) 即可获得天数 + """ + + def __init__(self): + # ========== 可配置参数(方便后期调整) ========== + self.DAYS_SIZE_REST = 6 # 大小休默认天数 + self.DAYS_FIXED_REST = 5 # 固休天数 + self.DAYS_QUOTA_LIMIT = 8 # 限额排休上限 + + # ========== 规则判定用单位列表(方便后期增删) ========== + # 集团总部职能部门(大小休) + self.GROUP_HEADQUARTER_UNITS = [ + "财务管理部", + "集团管理中心", + "集团营建中心", + ] + + def query(self, unit: str, org: str, sequence: str = "") -> LeaveRule: + """ + 查询正休天数 + + :param unit: 所属单位,如 "财务管理部"、"金色印象事业部"、"金色湖畔事业部" + :param org: 组织类型,如 "财务管理部"、"大区"、"会馆" + :param sequence: 职位序列,如 "门店技师序列"、"经营系管理序列"(可选) + :return: LeaveRule 对象 + """ + # ---------- 优先级1:技师序列(跨事业部通用) ---------- + if "技师" in sequence: + return LeaveRule( + days=self.DAYS_QUOTA_LIMIT, + rule_type="天数限额排休", + max_days=self.DAYS_QUOTA_LIMIT, + note=f"排班上限{self.DAYS_QUOTA_LIMIT}天" + ) + + # ---------- 优先级2:金色湖畔事业部(全员固休,除技师外) ---------- + if unit == "金色湖畔事业部": + return LeaveRule( + days=self.DAYS_FIXED_REST, + rule_type="固休", + note="固定单休" + ) + + # ---------- 优先级3:集团总部职能部门 ---------- + if unit in self.GROUP_HEADQUARTER_UNITS: + return LeaveRule( + days=self.DAYS_SIZE_REST, + rule_type="大小休", + note=f"大小休,默认{self.DAYS_SIZE_REST}天" + ) + + # ---------- 优先级4:金色印象事业部 ---------- + if unit == "金色印象事业部": + # 组织类型包含"事业部" → 大小休;其他(大区、经营中心、片区、会馆等)→ 固休 + if "事业部" in org: + return LeaveRule( + days=self.DAYS_SIZE_REST, + rule_type="大小休", + note=f"大小休,默认{self.DAYS_SIZE_REST}天" + ) + else: + # 大区、经营中心、片区、会馆(经营/服务序列) + return LeaveRule( + days=self.DAYS_FIXED_REST, + rule_type="固休", + note="固定单休" + ) + + # ---------- 兜底:未匹配到规则 ---------- + return LeaveRule( + days=0, + rule_type="未知", + note="未匹配到对应规则,请检查入参是否正确" + ) + + +# ======================== 使用示例 & 测试 ======================== +if __name__ == "__main__": + engine = LeavePolicyEngine() + + # 构造测试数据(覆盖所有场景) + test_cases = [ + # (所属单位, 组织类型, 职位序列) + ("财务管理部", "", ""), + ("集团管理中心", "", ""), + ("集团营建中心", "", ""), + ("金色印象事业部", "事业部", ""), + ("金色印象事业部", "事业部职能部门", ""), + ("金色印象事业部", "大区", ""), + ("金色印象事业部", "经营中心", ""), + ("金色印象事业部", "片区", ""), + ("金色印象事业部", "会馆", "经营系管理序列"), + ("金色印象事业部", "会馆", "门店服务序列"), + ("金色印象事业部", "会馆", "门店技师序列"), + ("金色湖畔事业部", "事业部", ""), + ("金色湖畔事业部", "大区", ""), + ("金色湖畔事业部", "会馆", "经营系管理序列"), + ("金色湖畔事业部", "会馆", "门店技师序列"), + # 异常测试 + ("未知单位", "未知组织", ""), + ] + + print("=" * 60) + print(f"{'所属单位':<12} | {'组织':<10} | {'序列':<12} | {'天数':<4} | {'规则':<10} | 备注") + print("=" * 60) + + for unit, org, seq in test_cases: + rule = engine.query(unit, org, seq) + seq_display = seq if seq else "-" + print(f"{unit:<12} | {org:<10} | {seq_display:<12} | {rule.days:<4} | {rule.rule_type:<10} | {rule.note}") \ No newline at end of file diff --git a/webhost/backend/__init__.py b/webhost/backend/__init__.py new file mode 100644 index 0000000..250306e --- /dev/null +++ b/webhost/backend/__init__.py @@ -0,0 +1,3 @@ +# -*- coding: utf-8 -*- +"""webhost 后端:场景插件宿主 +""" \ No newline at end of file diff --git a/webhost/backend/auth.py b/webhost/backend/auth.py new file mode 100644 index 0000000..670f5fd --- /dev/null +++ b/webhost/backend/auth.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +"""平台登录态管理(webhost 宿主壳 · 复用 desktop/shared 单一真源) + +- cookies 与 desktop/影刀版共用同一份共享文件(%LOCALAPPDATA%\37duAutomation\.sessions), + 任一端登录成功后,webhost 直接复用,无需重复登录 +- is_online():真实校验(轻量 API 校验 cookies 有效性),不是内存假状态 +- login():真实登录(cookies 有效则秒级复用;失效则浏览器自动化滑块登录) +- build_session():从共享 cookies 构建 requests.Session,供插件直接调用 shared 数据模块 + +约定:webhost 只依赖 desktop/shared 的真源登录模块,不复制登录逻辑。 +""" +from __future__ import annotations + +import json +import os + +import requests + +from webhost.backend.shared import hr_login as _hr +from webhost.backend.shared import oa_login as _oa +from webhost.backend.shared import seal_data_export as _seal + +_LABELS = {"hr": "HR 系统", "oa": "OA 系统"} + +# 共享 cookies:与 desktop/shared 版本使用同一份文件,路径约定保持一致 +_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 文件与域名(构建 session 时按域过滤) +_COOKIE_DEFS = { + "hr": {"file": "hr_cookies.json", "domain": "hr.37du.co"}, + "oa": {"file": "oa_cookies.json", "domain": "oa.37du.co"}, +} + +# 登录模块(desktop/shared 真源) +_LOGIN_MODS = {"hr": _hr, "oa": _oa} + + +class PlatformAuthError(Exception): + """平台不存在 / 登录态不可用等宿主层错误。""" + + +def platforms() -> list: + return [{"id": pid, "label": label} for pid, label in _LABELS.items()] + + +def is_online(pid: str) -> bool: + """真实校验平台登录态(发起轻量 API 校验,非内存假状态)。""" + if pid == "hr": + return _hr._is_hr_session_valid() + if pid == "oa": + return _oa._is_oa_session_valid() + return False + + +def login(pid: str) -> dict: + """真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。 + + 返回 {id, label, online, message} + """ + if pid not in _LOGIN_MODS: + raise PlatformAuthError(f"未知平台: {pid}") + result = _LOGIN_MODS[pid].ensure_login(force=False) + ok = bool(result and result.get("success")) + return {"id": pid, "label": _LABELS[pid], "online": ok, + "message": (result or {}).get("message", "")} + + +def build_session(pid: str) -> "requests.Session": + """从共享 cookies 构建已登录 requests.Session(供插件调用 shared 数据模块)。 + + 若登录态缺失则抛 PlatformAuthError,提示先登录。 + """ + if pid not in _COOKIE_DEFS: + raise PlatformAuthError(f"未知平台: {pid}") + path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"]) + if not os.path.exists(path): + raise PlatformAuthError( + f"未找到 {_LABELS[pid]} 登录态({path}),请先在页面点击登录") + with open(path, encoding="utf-8") as f: + cookies = json.load(f) + if not cookies: + raise PlatformAuthError(f"{_LABELS[pid]} 登录态为空,请重新登录") + + 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", + }) + domain = _COOKIE_DEFS[pid]["domain"] + injected: set = set() + for c in cookies: + if c.get("domain") and domain in c["domain"]: + session.cookies.set(c["name"], c["value"], + domain=c["domain"], path=c.get("path", "/")) + injected.add(c["name"]) + # 兜底:domain 未命中目标域名的 cookie(如别名域名),且 name 尚未注入时, + # 按目标域名补注入,避免漏掉关键 cookie 导致接口鉴权失败。 + for c in cookies: + name = c.get("name") + if name and name not in injected: + session.cookies.set(name, c.get("value", ""), + domain=domain, path=c.get("path", "/")) + return session + + +def get_user_id(pid: str) -> str: + """获取平台用户 ID(HR 数据接口大多需要 user_id 参数)。""" + if pid == "hr": + session = build_session("hr") + info = _seal.fetch_cur_user_info(session) + return str(info.get("userId") or "") + raise PlatformAuthError(f"平台 {pid} 暂不支持取 user_id") diff --git a/webhost/backend/hub.py b/webhost/backend/hub.py new file mode 100644 index 0000000..477ba00 --- /dev/null +++ b/webhost/backend/hub.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +"""WebSocket 广播枢纽:把插件 run 线程产生的 日志/进度/完成 事件实时推给前端。 +run 在 worker 线程执行,publish 通过 run_coroutine_threadsafe 投递到主事件循环。 +""" +from __future__ import annotations + +import asyncio +import threading +from typing import Dict + + +class Hub: + def __init__(self): + self._loop: asyncio.AbstractEventLoop | None = None + self._clients: list = [] + self._lock = threading.Lock() + + def bind(self, loop: asyncio.AbstractEventLoop): + self._loop = loop + + async def connect(self, websocket) -> None: + await websocket.accept() + with self._lock: + self._clients.append(websocket) + try: + await websocket.receive_text() # 挂起直到客户端断开 + finally: + with self._lock: + self._clients.remove(websocket) + + def publish(self, event: Dict) -> None: + if self._loop is None: + return + asyncio.run_coroutine_threadsafe(self._send(event), self._loop) + + async def _send(self, event: Dict) -> None: + with self._lock: + clients = list(self._clients) + for ws in clients: + try: + await ws.send_json(event) + except Exception: + with self._lock: + self._clients.remove(ws) + + +HUB = Hub() \ No newline at end of file diff --git a/webhost/backend/main.py b/webhost/backend/main.py new file mode 100644 index 0000000..bcdf0c2 --- /dev/null +++ b/webhost/backend/main.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +"""webhost 宿主:FastAPI 后端。 + +- 承载平台登录态(复用 desktop/shared 的共享登录态单一真源,真实登录/校验) +- 场景插件注册表 + 表单 schema +- 执行 run 到 worker 线程,经 /ws 广播 日志/进度/完成 +- 挂载前端构建产物(frontend/dist)实现单产物 +""" +from __future__ import annotations + +import asyncio +import socket +import threading +import uuid +from contextlib import asynccontextmanager +from datetime import datetime +from pathlib import Path + +from fastapi import FastAPI, HTTPException, WebSocket +from fastapi.middleware.cors import CORSMiddleware +from fastapi.staticfiles import StaticFiles +from pydantic import BaseModel + +from webhost.backend import auth as platform_auth +from webhost.backend.hub import HUB +from webhost.backend.plugins import PLUGINS # noqa: F401 触发注册 +from webhost.backend.plugins.base import RunContext + +PORT = 8799 +DIST = Path(__file__).resolve().parents[1] / "frontend" / "dist" + +# 平台登录态:标签/展示名来自 auth,在线状态实时校验(非内存假状态) +PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]} + for p in platform_auth.platforms()} + +# 运行会话:run_id -> {status, result, error} +RUNS: dict = {} +RUN_LOCK = threading.Lock() +MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长 + + +class RunReq(BaseModel): + plugin_id: str + fields: dict = {} + + +@asynccontextmanager +async def lifespan(app: FastAPI): + HUB.bind(asyncio.get_running_loop()) + yield + + +app = FastAPI(title="37du Web Host", lifespan=lifespan) +app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) + + +def _plugin_schema(p) -> dict: + return {"id": p.id, "name": p.name, "version": p.version, + "description": p.description, "uses_month": getattr(p, "uses_month", False), + "fields": p.fields} + + +@app.get("/api/meta") +def meta() -> dict: + plugins = [_plugin_schema(p) for p in PLUGINS] + platforms = [{"id": pid, "label": m["label"], "online": platform_auth.is_online(pid)} + for pid, m in PLATFORMS.items()] + return {"appName": "37du 业务场景工具集", "platforms": platforms, "plugins": plugins} + + +@app.post("/api/platforms/{pid}/login") +def login(pid: str) -> dict: + """真实登录:复用有效 cookies 或浏览器自动化登录(滑块),秒级~分钟级阻塞。""" + plat = PLATFORMS.get(pid) + if not plat: + raise HTTPException(404, "平台不存在") + return platform_auth.login(pid) + + +def _run_target(plugin, fields: dict, run_id: str) -> None: + ctx = RunContext(HUB, run_id=run_id, plugin_id=plugin.id, auth=platform_auth) + try: + result = plugin.run(fields, ctx) + with RUN_LOCK: + RUNS[run_id] = {"status": "done", "result": result, "error": None} + HUB.publish({"t": "run_done", "run_id": run_id, "ok": True}) + except Exception as e: # noqa: BLE001 全局兜底,推送失败给前端 + with RUN_LOCK: + RUNS[run_id] = {"status": "error", "result": None, "error": str(e)} + HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": str(e)}) + + +@app.post("/api/runs", status_code=202) +def start_run(req: RunReq) -> dict: + try: + plugin = PLUGINS.find(req.plugin_id) + except KeyError: + raise HTTPException(404, "插件不存在") + run_id = uuid.uuid4().hex + with RUN_LOCK: + if len(RUNS) >= MAX_RUNS: + RUNS.pop(next(iter(RUNS))) # dict 有序:弹出最老的记录 + RUNS[run_id] = {"status": "running", "result": None, "error": None} + HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id, + "at": datetime.now().strftime("%H:%M:%S")}) + threading.Thread(target=_run_target, args=(plugin, req.fields, run_id), + daemon=True, name=f"run-{plugin.id}").start() + return {"run_id": run_id} + + +@app.get("/api/runs/{run_id}") +def get_run(run_id: str) -> dict: + with RUN_LOCK: + run = RUNS.get(run_id) + if not run: + raise HTTPException(404, "运行不存在") + return run + + +@app.websocket("/ws") +async def ws(websocket: WebSocket): + await HUB.connect(websocket) + + +if DIST.exists(): + app.mount("/", StaticFiles(directory=str(DIST), html=True), name="web") + + +def _port_free(port: int) -> bool: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + return s.connect_ex(("127.0.0.1", port)) != 0 + + +if __name__ == "__main__": + import uvicorn + + print(f"[webhost] port {PORT} free = {_port_free(PORT)}") + uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="info") \ No newline at end of file diff --git a/webhost/backend/plugins/__init__.py b/webhost/backend/plugins/__init__.py new file mode 100644 index 0000000..293ec39 --- /dev/null +++ b/webhost/backend/plugins/__init__.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +"""插件注册表——目录动态扫描加载。 + +加载约定(扫描协议): +- 插件形态:plugins/ 下的**目录包**(含 __init__.py,在其中定义 ScenePlugin 子类并 + PLUGINS.append,如 seal_check/)。顶层单模块(*.py)仅用于兼容旧 demo/platform_check。 +- 私有辅助文件**必须用 `_` 前缀**(如 _utils.py、_common/),扫描时一律排除, + 避免被误当作插件 import。 +- 只有继承 ScenePlugin 并通过 PLUGINS.append 注册的才会进入注册表;_ 前缀约定 + 确保辅助模块根本不会被 import,杜绝误注册与无用告警。 +- 同名冲突:目录优先于同名 .py(先收目录再收 py,同名仅保留目录)。 +- 单个插件加载失败记 ERROR 并保留堆栈首行后跳过,不拖垮整体启动。 + +阶段二(权限):把「有权限的插件名」传给 load_plugins(allowed) 即可,无权限不 import。 +届时触发点建议从「import 副作用」改为由 main.py 在应用启动时显式调用 load_plugins(), +以便每次按登录账号动态决定允许集。 +""" +from __future__ import annotations + +import importlib +import logging +import pathlib +import traceback + +from webhost.backend.plugins.base import PLUGINS # noqa: F401 由 base 构造空注册表 + +_PLUGINS_ROOT = pathlib.Path(__file__).resolve().parent +_PKG_NAME = __name__ +_LOGGER = logging.getLogger(__name__) + + +def _discover_modules() -> list: + """发现插件模块:目录优先,排除 base 与 `_` 前缀的私有文件。""" + names: list = [] + seen: set = set() + for d in sorted(_PLUGINS_ROOT.iterdir()): + if not d.is_dir() or d.name.startswith("_") or d.name == "__pycache__": + continue + if (d / "__init__.py").exists(): + names.append(d.name) + seen.add(d.name) + for f in sorted(_PLUGINS_ROOT.glob("*.py")): + if f.name in ("__init__.py", "base.py") or f.name.startswith("_"): + continue + if f.stem not in seen: # 已被同名目录占用则跳过 + names.append(f.stem) + return names + + +def load_plugins(allowed: set = None) -> None: + """动态加载插件。allowed 为空 = 全量;否则仅加载白名单内的插件。 + + 单插件加载失败记 ERROR(含堆栈首行)后跳过,不拖垮整体启动。 + """ + allowed = allowed if allowed is not None else set() + for _mod in _discover_modules(): + if allowed and _mod not in allowed: + _LOGGER.info("插件 %s 不在权限白名单,跳过加载", _mod) + continue + try: + importlib.import_module(f"{_PKG_NAME}.{_mod}") + except Exception as _exc: # noqa: BLE001 + _LOGGER.error("插件 %s 加载失败,已跳过\n%s", _mod, + traceback.format_exc(limit=1)) + + +# 触发加载(阶段一:全量;阶段二改由 main.py 显式调用并传入权限白名单) +load_plugins() \ No newline at end of file diff --git a/webhost/backend/plugins/base.py b/webhost/backend/plugins/base.py new file mode 100644 index 0000000..6dc181b --- /dev/null +++ b/webhost/backend/plugins/base.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +"""场景插件抽象:后端 `run` 承载真实逻辑(浏览器自动化/登录态等), +前端按 `fields` 渲染通用表单,执行过程经 `RunContext.log/progress` 推送到 WebSocket。 +""" +from __future__ import annotations + +from typing import List + + +class RunContext: + """传给插件 `run` 的执行上下文:把日志/进度实时推给前端,并提供共享登录态访问。""" + + def __init__(self, hub, run_id: str, plugin_id: str, auth=None): + self._hub = hub + self._auth = auth # webhost.backend.auth 模块(宿主注入的共享登录态) + self.run_id = run_id + self.plugin_id = plugin_id + + def log(self, msg: str, level: str = "INFO"): + self._hub.publish({ + "t": "log", "run_id": self.run_id, "plugin_id": self.plugin_id, + "level": level, "msg": msg, + }) + + def progress(self, pct: int): + self._hub.publish({ + "t": "progress", "run_id": self.run_id, + "plugin_id": self.plugin_id, "pct": int(max(0, min(100, pct))), + }) + + # ---------- 共享登录态 ---------- + def get_session(self, platform: str) -> "requests.Session": + """获取指定平台的共享登录 session,可直接传给 shared 数据模块。""" + if not self._auth: + raise RuntimeError("宿主未注入登录态服务,无法构建 session") + return self._auth.build_session(platform) + + def get_user_id(self, platform: str) -> str: + """获取指定平台的用户 ID(HR 数据接口大多需要 user_id 参数)。""" + if not self._auth: + raise RuntimeError("宿主未注入登录态服务,无法获取 user_id") + return self._auth.get_user_id(platform) + + +class ScenePlugin: + """场景插件基类。新增场景:子类填 id/name/fields/run 并注册到 plugins 列表。""" + + id: str = "" + name: str = "" + version: str = "1.0.0" + description: str = "" + platform: str = "" # 所需平台登录态:hr / oa / ""(无需登录) + uses_month: bool = False # 是否需要底座页眉的“执行月份”(前端据此注入 ref_month 字段) + # 表单字段定义:[{key,label,type,default,options}] + # type ∈ int | text | select + fields: List[dict] = [] + + def run(self, fields: dict, ctx: RunContext) -> dict: + raise NotImplementedError(f"插件 {self.id} 未实现 run") + + +class _Registry(list): + def find(self, pid: str) -> ScenePlugin: + for p in self: + if p.id == pid: + return p + raise KeyError(pid) + + +PLUGINS: _Registry = _Registry() \ No newline at end of file diff --git a/webhost/backend/plugins/demo.py b/webhost/backend/plugins/demo.py new file mode 100644 index 0000000..41ebe2f --- /dev/null +++ b/webhost/backend/plugins/demo.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +"""示例场景插件:证明「后端 run + 前端通用表单 + 实时日志/进度」的插件化链路可用。 +后续真实场景(如考勤月报封存检查)按同样方式接入即可。 +""" +import time + +from webhost.backend.plugins.base import PLUGINS, RunContext, ScenePlugin + + +class DemoPlugin(ScenePlugin): + id = "demo" + name = "示例检查" + version = "1.0.0" + description = "跑一个带进度与日志的假任务,用于验证插件链路。" + fields = [ + {"key": "steps", "label": "步数", "type": "int", "default": 3}, + {"key": "mode", "label": "模式", "type": "select", + "options": ["正常", "中途报错"], "default": "正常"}, + ] + + def run(self, fields: dict, ctx: RunContext) -> dict: + steps = max(1, min(50, int(fields.get("steps", 3)))) + mode = fields.get("mode", "正常") + ctx.log(f"开始示例检查:{steps} 步,模式={mode}") + for i in range(1, steps + 1): + time.sleep(0.6) + ctx.progress(int(i / steps * 90)) + ctx.log(f"第 {i}/{steps} 步完成") + if mode == "中途报错": + raise RuntimeError("按模式设置的报错,用于演示失败处理") + ctx.progress(100) + ctx.log("示例检查完成") + return { + "summary": f"共执行 {steps} 步,全部正常", + "rows": [[i, f"结果 {i}"] for i in range(1, steps + 1)], + } + + +PLUGINS.append(DemoPlugin()) \ No newline at end of file diff --git a/webhost/backend/plugins/platform_check.py b/webhost/backend/plugins/platform_check.py new file mode 100644 index 0000000..326f208 --- /dev/null +++ b/webhost/backend/plugins/platform_check.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +"""登录态自检(共享登录态 + 共享模块验证) + +- 校验 HR / OA 共享登录态(真实 API 校验,非内存假状态) +- 若 HR 在线:实测共享数据模块(desktop/shared/seal_data_export)能否构建 session、 + 取 userId 并拉取指定月份封存数据 —— 验证 webhost 复用共享模块的完整链路 +""" +from __future__ import annotations + +from datetime import datetime + +from webhost.backend.shared import seal_data_export as _seal +from webhost.backend import auth as platform_auth +from webhost.backend.plugins.base import PLUGINS, ScenePlugin + + +class PlatformCheck(ScenePlugin): + id = "platform_check" + name = "登录态自检" + version = "1.0.0" + description = "校验 HR/OA 共享登录态,并实测共享模块(封存数据拉取)可用性" + platform = "" + + def run(self, fields: dict, ctx) -> dict: + report = {} + for pid in ("hr", "oa"): + online = platform_auth.is_online(pid) + label = platform_auth._LABELS[pid] + report[pid] = "已登录" if online else "未登录" + ctx.log(f"[共享登录态] {label}:{'已登录' if online else '未登录'}") + + seal_info = None + if report.get("hr") == "已登录": + ym = str(fields.get("_month") or datetime.now().strftime("%Y-%m")) + try: + ctx.log("开始实测共享模块 seal_data_export……") + ctx.progress(40) + session = ctx.get_session("hr") + user_id = ctx.get_user_id("hr") + ctx.log(f"构建 session 成功,HR userId = {user_id or '(空)'}") + page = _seal.fetch_seal_page( + session, user_id, ym, page_no=1, page_size=5) + rows = page.get("datas") or [] + seal_info = f"{ym} 返回 {len(rows)} 条(state={page.get('state')})" + ctx.log(f"[共享模块] 封存数据拉取成功:{seal_info}") + ctx.progress(100) + except Exception as e: # noqa: BLE001 + ctx.log(f"[共享模块] 调用失败:{e}", level="ERROR") + seal_info = f"error: {e}" + else: + ctx.log("HR 未登录,跳过共享模块实测(请先点击顶部 HR 登录)") + + summary = ";".join(f"{platform_auth._LABELS[k]}={v}" for k, v in report.items()) + if seal_info: + summary += f";封存模块:{seal_info}" + return {"summary": summary, "report": report, "seal": seal_info} + + +PLUGINS.append(PlatformCheck()) diff --git a/webhost/backend/plugins/seal_check/__init__.py b/webhost/backend/plugins/seal_check/__init__.py new file mode 100644 index 0000000..0858431 --- /dev/null +++ b/webhost/backend/plugins/seal_check/__init__.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +"""考勤月报封存检查 - webhost 场景插件(XQ0011) + +流程:填写检查月份与正休规则 → 一键执行(拉取数据 + 运行五项检查 + 自动导出多 Sheet Excel)。 +复用 desktop/shared 数据真源(由宿主共享登录态注入 session/user_id),不内置登录逻辑。 +""" +from datetime import datetime, timedelta + +from webhost.backend.plugins.base import PLUGINS, RunContext, ScenePlugin + +from webhost.backend.plugins.seal_check import config +from webhost.backend.plugins.seal_check.data import ( + fetch_compare_diffs, fetch_org_name_map, fetch_roster_data, + fetch_seal_rows, fetch_shift_batch, +) +from webhost.backend.plugins.seal_check.logic import LeaveRuleEngine, run_all_checks +from webhost.backend.plugins.seal_check.report import CHECK_TAB_TITLES, export_report + + +def _default_month() -> str: + last_end = datetime.now().replace(day=1) - timedelta(days=1) + return f"{last_end.year:04d}-{last_end.month:02d}" + + +class SealCheckPlugin(ScenePlugin): + id = "seal_check" + name = "考勤月报封存检查" + version = "1.0.0" + description = "填写每月正休规则,一键执行五项检查并导出多 Sheet Excel 报告" + platform = "hr" + uses_month = True # 月份由底座页眉统一提供(注入 ref_month),插件自身不再单列 + fields = [ + {"key": "fixed_rest_days", "label": "固休应休天数", "type": "int", + "default": config.DEFAULT_RULES["fixed_rest_days"]}, + {"key": "size_rest_days", "label": "大小休应休天数", "type": "int", + "default": config.DEFAULT_RULES["size_rest_days"]}, + {"key": "quota_rest_days", "label": "限额排休上限", "type": "int", + "default": config.DEFAULT_RULES["quota_rest_days"]}, + ] + + def run(self, fields: dict, ctx: RunContext) -> dict: + month_str = str(fields.get("ref_month") or _default_month()).strip() + year, month = int(month_str[:4]), int(month_str[5:7].strip()) + yearmonth = f"{year:04d}{month:02d}" + month_display = f"{year:04d}-{month:02d}" + + engine = LeaveRuleEngine( + size_rest_days=int(fields.get("size_rest_days") or config.DEFAULT_RULES["size_rest_days"]), + fixed_rest_days=int(fields.get("fixed_rest_days") or config.DEFAULT_RULES["fixed_rest_days"]), + quota_rest_days=int(fields.get("quota_rest_days") or config.DEFAULT_RULES["quota_rest_days"]), + ) + + session = ctx.get_session("hr") + user_id = ctx.get_user_id("hr") + + ctx.log(f"开始考勤月报封存检查:{month_display}") + ctx.progress(5) + + ctx.log("拉取考勤封存数据……") + seal_rows = fetch_seal_rows(session, user_id, yearmonth) + ctx.progress(30) + ctx.log(f"封存数据 {len(seal_rows)} 人") + + ctx.log("拉取组织表……") + org_name_map = fetch_org_name_map(session) + ctx.progress(45) + ctx.log(f"组织 {len(org_name_map)} 条") + + ctx.log("导出花名册(获取职位序列)……") + seq_map, in_service_records = fetch_roster_data(session) + ctx.progress(60) + ctx.log(f"花名册职位序列 {len(seq_map)} 人,在职 {len(in_service_records)} 人") + + ctx.log("批量拉取排班(计算应出勤天数)……") + shift_map = fetch_shift_batch(session, user_id, yearmonth) + ctx.progress(80) + ctx.log(f"排班应出勤 {len(shift_map)} 人") + + diff_rows, diff_note = fetch_compare_diffs(session, user_id, yearmonth) + ctx.progress(90) + + notes = [diff_note] if diff_note else [] + ctx.log("运行全部检查……") + result = run_all_checks( + seal_rows=seal_rows, + org_name_map=org_name_map, + seq_map=seq_map, + in_service_records=in_service_records, + shift_map=shift_map, + engine=engine, + year=year, month=month, + diff_rows=diff_rows, diff_fields=None, notes=notes, + ) + ctx.progress(95) + + path = export_report(result["rows"], month_display, result["notes"]) + ctx.progress(100) + + for note in result["notes"]: + ctx.log(f"[提示] {note}") + summary = ";".join( + f"{CHECK_TAB_TITLES[i]} {len(result['rows'].get(i, []))} 条" + for i in range(1, 6)) + ctx.log(f"结果汇总:{summary}") + ctx.log(f"===== 检查完成,报告已导出:{path} =====") + + return { + "summary": summary, + "path": path, + "rows": {str(k): v for k, v in result["rows"].items()}, + "notes": result["notes"], + } + + +PLUGINS.append(SealCheckPlugin()) \ No newline at end of file diff --git a/webhost/backend/plugins/seal_check/config.py b/webhost/backend/plugins/seal_check/config.py new file mode 100644 index 0000000..8cdc709 --- /dev/null +++ b/webhost/backend/plugins/seal_check/config.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +"""考勤月报封存检查(webhost 场景插件)配置。 + +与 desktop/plugins/seal_check/config.py 保持同步(影刀/桌面版为单一真源)。 +""" +import os + +# ==================== 输出目录 ==================== +SAVE_DIR = os.getenv("monthly_seal_save_dir") or r"D:\资料\人资\考勤异常" + +# 花名册导出(取职位序列,服务端已翻译中文) +ROSTER_EXPORT_PATH = os.path.join(SAVE_DIR, "员工花名册_桌面版.xlsx") +ROSTER_DOWNLOAD_DIR = os.path.join(SAVE_DIR, "花名册下载") + +# ==================== 每月正休规则(默认值,界面可覆盖) ==================== +DEFAULT_RULES = { + "size_rest_days": 6, # 大小休 应休天数 + "fixed_rest_days": 5, # 固休 应休天数 + "quota_rest_days": 8, # 天数限额排休 上限 +} + +# 集团总部职能部门(大小休) +GROUP_HEADQUARTER_UNITS = ( + "财务管理部", + "集团管理中心", + "集团营建中心", +) + +# ==================== 排班接口 ==================== +HR_BASE_URL = "https://hr.37du.co" +SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc" +PAGE_MAX_SIZE = 500 + +# 排班休息日判定:当日班次名({日期}_bc_name)等于该值视为休息 +REST_SHIFT_NAME = "休息" \ No newline at end of file diff --git a/webhost/backend/plugins/seal_check/data.py b/webhost/backend/plugins/seal_check/data.py new file mode 100644 index 0000000..b13b515 --- /dev/null +++ b/webhost/backend/plugins/seal_check/data.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- +"""考勤月报封存检查 - 数据拉取(webhost 场景插件) + +数据真源复用 desktop/shared(与桌面/影刀版单一真源一致),传入宿主构建的 +requests.Session / user_id 即可,不内置任何登录逻辑。 +session 由 webhost 宿主的共享登录态提供(RunContext.get_session / get_user_id)。 +""" +import calendar +from datetime import datetime, timedelta +from typing import Dict, List, Tuple + +from webhost.backend.shared import org_export, roster_export_api, seal_data_export + +from webhost.backend.plugins.seal_check import config + +# hr_request_json:统一做全局重试(3次) + 登录态失效判定(复用桌面 shared 真源) +hr_request_json = seal_data_export.hr_request_json + + +# ==================== 通用工具 ==================== +def _clean(v) -> str: + 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 _norm_path(p: str) -> str: + p = _clean(p).replace("\\", "/").strip("/") + if p.startswith("集团/"): + p = p[len("集团/"):] + elif p == "集团": + p = "" + return p.strip("/") + + +def last_month_ym(today: datetime = None) -> str: + today = today or datetime.now() + last_end = today.replace(day=1) - timedelta(days=1) + return f"{last_end.year:04d}{last_end.month:02d}" + + +# ==================== 1. 封存数据 ==================== +def fetch_seal_rows(session, user_id: str, yearmonth: str) -> List[dict]: + rows = seal_data_export.fetch_all_seal(session, user_id, yearmonth) + return seal_data_export._filter_by_unit(rows) + + +# ==================== 2. 组织表 ==================== +def fetch_org_name_map(session) -> Dict[str, str]: + """组织全路径 -> 组织名称(用于解析组织类型)。""" + rows = org_export.fetch_all_orgs(session) + name_map: Dict[str, str] = {} + for rec in rows: + path = _norm_path(rec.get("pt_structure.ORG_FULL_PATH")) + name = _clean(rec.get("pt_organzation.ORG_NAME")) + if path and name: + name_map[path] = name + return name_map + + +# ==================== 3. 花名册(导出接口,职位序列已翻译) ==================== +def fetch_roster_data(session) -> Tuple[Dict[str, str], List[dict]]: + """导出花名册(在职+离职)。返回 (seq_map, in_service_records)。""" + import pandas as pd + + path = roster_export_api.export_roster( + output_path=config.ROSTER_EXPORT_PATH, + download_dir=config.ROSTER_DOWNLOAD_DIR, + template_name="员工基础信息", + statuses=["在职", "离职"], + ) + df = pd.read_excel(path, dtype=str) + df.columns = [str(c).strip() for c in df.columns] + + seq_map: Dict[str, str] = {} + in_service_records: List[dict] = [] + for _, r in df.iterrows(): + code = _clean(r.get("工号")) + seq = _clean(r.get("职位序列")) + if code: + seq_map[code] = seq + if _clean(r.get("在职状态")) == "在职": + in_service_records.append({ + "工号": code, + "姓名": _clean(r.get("姓名")), + "所属单位": _clean(r.get("所属单位")), + "一级部门": _clean(r.get("一级部门")), + "二级部门": _clean(r.get("二级部门")), + "三级部门": _clean(r.get("三级部门")), + "四级部门": _clean(r.get("四级部门")), + "五级部门": _clean(r.get("五级部门")), + }) + return seq_map, in_service_records + + +# ==================== 4. 排班(批量导出) ==================== +def fetch_shift_batch(session, user_id: str, yearmonth: str) -> Dict[str, int]: + """批量拉取某月全集团排班,返回 {工号: 应出勤天数}。 + + base_code 留空 = 全集团批量;每条记录 = 一个员工整月排班, + 逐日列 key 为 "YYYY-MM-DD_bc_name",休息日判定 bc_name == config.REST_SHIFT_NAME。 + """ + ym = str(yearmonth) + year, month = int(ym[:4]), int(ym[4:6]) + days_in_month = calendar.monthrange(year, month)[1] + begin = f"{year:04d}-{month:02d}-01" + end = f"{year:04d}-{month:02d}-{days_in_month:02d}" + + all_rows: List[dict] = [] + page_no = 1 + while True: + params = { + "treecode": "cq37du", "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, "end": end, "bc_date": begin, + "base_code": "", "staff_name": "", + "start": str((page_no - 1) * config.PAGE_MAX_SIZE), + "sortType": "", "sortName": "", + "pageNo": page_no, "pageSize": config.PAGE_MAX_SIZE, + } + data = hr_request_json(session, "POST", config.SHIFT_URL, params, "排班批量") + if data.get("state") != "1": + break + page_list = data.get("datas", []) or [] + if not page_list: + break + all_rows.extend(page_list) + # 分页保护:pageCount 缺失/为 0 时不能提前 break,否则会静默截断数据 + page_count = data.get("pageCount") or 0 + if page_count and page_no >= page_count: + break + if len(page_list) < config.PAGE_MAX_SIZE: + break + page_no += 1 + + result: Dict[str, int] = {} + for rec in all_rows: + code = _clean(rec.get("base_code")) + if not code: + continue + work_days = 0 + for d in range(1, days_in_month + 1): + bc = _clean(rec.get(f"{year:04d}-{month:02d}-{d:02d}_bc_name")) + if bc and bc != config.REST_SHIFT_NAME: + work_days += 1 + result[code] = work_days + return result + + +# ==================== 5. 对比差异(检查3,接口待封装) ==================== +def fetch_compare_diffs(session, user_id: str, yearmonth: str) -> Tuple[List[dict], str]: + """考勤月报封存「对比」差异数据;接口未封装前返回空 + 提示。""" + return [], "检查3「封存值是否最新」的对比接口尚未封装,本次跳过该检查,请在数据层补充接口后启用" \ No newline at end of file diff --git a/webhost/backend/plugins/seal_check/logic.py b/webhost/backend/plugins/seal_check/logic.py new file mode 100644 index 0000000..8a55e56 --- /dev/null +++ b/webhost/backend/plugins/seal_check/logic.py @@ -0,0 +1,279 @@ +# -*- coding: utf-8 -*- +"""考勤月报封存检查 - 规则引擎与五项检查(webhost 场景插件) + +与 desktop/plugins/seal_check/logic.py 保持同步(桌面版为单一真源)。 + +规则完全由运行人员每月在界面录入的天数值驱动: + - 固休:应休 = fixed_rest_days + - 大小休:应休 = size_rest_days(实际允许 size_rest_days ~ 8 天区间) + - 天数限额排休:应休 <= quota_rest_days(上限) +""" +import calendar +from dataclasses import dataclass +from datetime import date, datetime +from typing import Dict, List + +from webhost.backend.plugins.seal_check import config + +# ==================== 异常名单统一列 ==================== +OUTPUT_COLUMNS = [ + "37工号", "姓名", "月报检查月份", "异常类型", "所属单位", + "一级部门", "二级部门", "三级部门", "四级部门", "五级部门", +] + +TYPE_1 = "当月在职天数有差缺排班" +TYPE_3 = "考勤封存非最新值,请重新封存" +TYPE_4 = "出勤天数大于当月应出勤天数" +TYPE_5 = "考勤月报未封存,请处理" + + +# ==================== 规则引擎 ==================== +@dataclass +class RestRule: + rule_type: str # 大小休 / 固休 / 限额 / 未知 + days: int = None # 应休天数(限额为 None) + max_days: int = None # 限额上限 + desc: str = "" # 规则描述(异常类型) + + def validate(self, rest_days: int) -> bool: + if self.rule_type == "固休": + return rest_days == self.days + if self.rule_type == "大小休": + return self.days <= rest_days <= 8 + if self.rule_type == "限额": + return rest_days <= self.max_days + return True + + +def _normalize_rest_days(v) -> int: + try: + s = str(v).strip() + if s in ("", "nan", "None"): + return -1 + if s.endswith(".0"): + s = s[:-2] + return int(float(s)) + except (TypeError, ValueError): + return -1 + + +class LeaveRuleEngine: + def __init__(self, size_rest_days=6, fixed_rest_days=5, quota_rest_days=8): + self.size_rest_days = int(size_rest_days) + self.fixed_rest_days = int(fixed_rest_days) + self.quota_rest_days = int(quota_rest_days) + + def query(self, unit: str, org_label: str = "", sequence: str = "") -> RestRule: + if "技师" in sequence: + return RestRule("限额", max_days=self.quota_rest_days, + desc=f"当月排休不满足<={self.quota_rest_days}天规则") + if unit == "金色湖畔事业部": + return RestRule("固休", days=self.fixed_rest_days, + desc=f"当月排休不满足={self.fixed_rest_days}天规则") + if unit in config.GROUP_HEADQUARTER_UNITS: + return RestRule("大小休", days=self.size_rest_days, + desc=f"当月排休不满足>={self.size_rest_days}天<=8天规则") + if unit == "金色印象事业部": + if "事业部" in org_label: + return RestRule("大小休", days=self.size_rest_days, + desc=f"当月排休不满足>={self.size_rest_days}天<=8天规则") + return RestRule("固休", days=self.fixed_rest_days, + desc=f"当月排休不满足={self.fixed_rest_days}天规则") + return RestRule("未知") + + def check(self, unit, org_label, sequence, rest_days): + rule = self.query(unit, org_label, sequence) + days = _normalize_rest_days(rest_days) + if rule.rule_type == "未知" or days < 0: + return False, rule, days + return (not rule.validate(days)), rule, days + + +# ==================== 检查工具 ==================== +def _clean(v) -> str: + 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 _to_int(v, default=0) -> int: + s = _clean(v) + if not s: + return default + try: + return int(float(s)) + except (TypeError, ValueError): + return default + + +def _norm_path(p: str) -> str: + p = _clean(p).replace("\\", "/").strip("/") + if p.startswith("集团/"): + p = p[len("集团/"):] + elif p == "集团": + p = "" + return p.strip("/") + + +def _parse_date(s): + s = _clean(s)[:10] + if not s: + return None + try: + return datetime.strptime(s, "%Y-%m-%d").date() + except ValueError: + return None + + +def _row_from_seal(rec: dict, month_display: str, abnormal_type: str) -> dict: + return { + "37工号": _clean(rec.get("base_code")), + "姓名": _clean(rec.get("staff_name")), + "月报检查月份": month_display, + "异常类型": abnormal_type, + "所属单位": _clean(rec.get("BELONG_UNIT_ORG_NAME")), + "一级部门": _clean(rec.get("DEPT_ORG_ONE")), + "二级部门": _clean(rec.get("DEPT_ORG_TWO")), + "三级部门": _clean(rec.get("DEPT_ORG_THREE")), + "四级部门": _clean(rec.get("DEPT_ORG_FOUR")), + "五级部门": _clean(rec.get("DEPT_ORG_FIVE")), + } + + +def _resolve_org_label(rec: dict, org_name_map: Dict[str, str]) -> str: + """解析员工组织类型标签:部门全路径匹配组织表组织全路径 → 组织名称。 + 匹配失败回退取路径最后一个节点名。""" + path = _norm_path(rec.get("ORG_FULL_PATH")) + if path and path in org_name_map: + return org_name_map[path] + if path: + return path.split("/")[-1] + return "" + + +# ==================== 检查1:在职天数是否均排班 ==================== +def _calc_working_days(rec: dict, year: int, month: int) -> int: + """按需求文档规则计算当月在职天数(基于入职/离职时间)。""" + month_days = calendar.monthrange(year, month)[1] + first = date(year, month, 1) + last = date(year, month, month_days) + join_d = _parse_date(rec.get("join_date")) + leave_d = _parse_date(rec.get("leaveOffice_date")) + + def in_service(d): + if join_d and d < join_d: + return False + if leave_d and d > leave_d: + return False + return True + + in_first, in_last = in_service(first), in_service(last) + if in_first and in_last: + # 1号和月末都在职 = 全月在职,在职天数即为当月自然天数 + return month_days + if in_first and not in_last: + return (leave_d - first).days if leave_d else 0 + if not in_first and in_last: + return (last - join_d).days if join_d else 0 + # 首尾都不在职:仅当入职、离职日期都落在本月内时按差计算;否则返回 0 + if join_d and leave_d and first <= join_d <= last and first <= leave_d <= last: + return (leave_d - join_d).days + return 0 + + +def check1(seal_rows: List[dict], year: int, month: int) -> List[dict]: + month_display = f"{year:04d}-{month:02d}" + rows = [] + for rec in seal_rows: + wd = _calc_working_days(rec, year, month) + yq = _to_int(rec.get("kq_stat_month_yq_work_day_in")) # 在职应勤工作日 + rest = _to_int(rec.get("kq_stat_cal_ext9")) # 休息天 + if wd - (yq + rest) != 0: + rows.append(_row_from_seal(rec, month_display, TYPE_1)) + return rows + + +# ==================== 检查2:排休天数验证 ==================== +def check2(seal_rows, org_name_map, seq_map, engine, year, month) -> List[dict]: + month_display = f"{year:04d}-{month:02d}" + rows = [] + for rec in seal_rows: + unit = _clean(rec.get("BELONG_UNIT_ORG_NAME")) + org_label = _resolve_org_label(rec, org_name_map) + seq = seq_map.get(_clean(rec.get("base_code")), "") + abnormal, rule, _days = engine.check(unit, org_label, seq, rec.get("kq_stat_cal_ext9")) + if abnormal: + rows.append(_row_from_seal(rec, month_display, rule.desc)) + return rows + + +# ==================== 检查3:封存值是否为最新值 ==================== +def check3(diff_rows, seal_rows, diff_fields, year, month) -> List[dict]: + month_display = f"{year:04d}-{month:02d}" + if not diff_rows: + return [] + seal_by_code = {_clean(r.get("base_code")): r for r in seal_rows} + rows = [] + for dr in diff_rows: + code = _clean(dr.get("base_code")) or _clean(dr.get("工号")) + if any(_clean(dr.get(f)) for f in diff_fields) and code in seal_by_code: + rows.append(_row_from_seal(seal_by_code[code], month_display, TYPE_3)) + return rows + + +# ==================== 检查4:出勤天数验证 ==================== +def check4(seal_rows, shift_map, year, month) -> List[dict]: + month_display = f"{year:04d}-{month:02d}" + rows = [] + for rec in seal_rows: + code = _clean(rec.get("base_code")) + expected = shift_map.get(code) + if expected is None: + continue + attend = _to_int(rec.get("kq_stat_cal_ext19"), default=-1) # 实际出勤天日 + if attend >= 0 and attend > expected: + rows.append(_row_from_seal(rec, month_display, TYPE_4)) + return rows + + +# ==================== 检查5:未封存名单 ==================== +def check5(seal_rows, in_service_records, year, month) -> List[dict]: + month_display = f"{year:04d}-{month:02d}" + seal_codes = {_clean(r.get("base_code")) for r in seal_rows} + rows = [] + for rec in in_service_records: + code = _clean(rec.get("工号")) + if code and code not in seal_codes: + rows.append({ + "37工号": code, "姓名": _clean(rec.get("姓名")), + "月报检查月份": month_display, "异常类型": TYPE_5, + "所属单位": _clean(rec.get("所属单位")), + "一级部门": _clean(rec.get("一级部门")), + "二级部门": _clean(rec.get("二级部门")), + "三级部门": _clean(rec.get("三级部门")), + "四级部门": _clean(rec.get("四级部门")), + "五级部门": _clean(rec.get("五级部门")), + }) + return rows + + +# ==================== 汇总编排 ==================== +def run_all_checks(*, seal_rows, org_name_map, seq_map, in_service_records, + shift_map, engine, year, month, diff_rows=None, diff_fields=None, + notes=None) -> dict: + notes = list(notes or []) + results = { + 1: check1(seal_rows, year, month), + 2: check2(seal_rows, org_name_map, seq_map, engine, year, month), + 3: check3(diff_rows or [], seal_rows, diff_fields or [], year, month), + 4: check4(seal_rows, shift_map, year, month), + 5: check5(seal_rows, in_service_records, year, month), + } + if diff_rows is None: + notes.append("检查3「封存值是否为最新值」:对比接口数据未提供,本次跳过该检查") + return {"rows": results, "notes": notes} \ No newline at end of file diff --git a/webhost/backend/plugins/seal_check/report.py b/webhost/backend/plugins/seal_check/report.py new file mode 100644 index 0000000..086c6fa --- /dev/null +++ b/webhost/backend/plugins/seal_check/report.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +"""考勤月报封存检查 - Excel 报告导出(webhost 场景插件) + +与 desktop/plugins/seal_check/report.py 保持同步(桌面版为单一真源)。 + +输出:考勤月报封存检查_{月份}_{时间戳}.xlsx(汇总 + 检查1~5 Sheet,空 Sheet 保留表头) +""" +import os +from datetime import datetime +from typing import Dict, List + +from webhost.backend.plugins.seal_check import config +from webhost.backend.plugins.seal_check.logic import OUTPUT_COLUMNS, TYPE_1, TYPE_3, TYPE_4, TYPE_5 + +CHECK_TAB_TITLES = { + 1: "检查1_在职天数排班异常", + 2: "检查2_排休天数异常", + 3: "检查3_封存非最新值", + 4: "检查4_出勤天数异常", + 5: "检查5_未封存名单", +} + +CHECK_DESCRIPTIONS = { + 1: TYPE_1, + 2: "当月排休不满足……天规则(动态)", + 3: TYPE_3, + 4: TYPE_4, + 5: TYPE_5, +} + + +def export_report(rows_map: Dict[int, List[dict]], month: str, notes: List[str] = None, + save_dir: str = None) -> str: + try: + import pandas as pd + except ImportError: + raise RuntimeError("缺少 pandas / openpyxl 依赖,无法导出 Excel") + + save_dir = save_dir or config.SAVE_DIR + os.makedirs(save_dir, exist_ok=True) + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + path = os.path.join(save_dir, f"考勤月报封存检查_{month}_{ts}.xlsx") + + with pd.ExcelWriter(path, engine="openpyxl") as writer: + summary = [] + for i in range(1, 6): + n = len(rows_map.get(i, [])) + summary.append({ + "检查项": CHECK_TAB_TITLES[i], + "命中条数": n, + "异常类型": CHECK_DESCRIPTIONS[i], + "说明": "详见对应 Sheet" if n else "无异常", + }) + if notes: + summary.append({"检查项": "备注", "命中条数": len(notes), + "异常类型": "", "说明": ";".join(notes)}) + pd.DataFrame(summary).to_excel(writer, sheet_name="汇总", index=False) + + for i in range(1, 6): + df = pd.DataFrame(rows_map.get(i, []), columns=OUTPUT_COLUMNS) + df.to_excel(writer, sheet_name=CHECK_TAB_TITLES[i], index=False) + + return path \ No newline at end of file diff --git a/webhost/backend/shared/__init__.py b/webhost/backend/shared/__init__.py new file mode 100644 index 0000000..2bc19ab --- /dev/null +++ b/webhost/backend/shared/__init__.py @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +"""webhost.backend.shared:webhost 共享模块(登录/导出/封存拉取) + +原 desktop/shared 迁入,webhost 单一真源,完全自包含、不依赖其他目录。 +与 workflows/(影刀版)为**独立维护的两份副本**,修改时若需同步, +请手动将 workflows 对应文件复制覆盖到本目录。 +""" diff --git a/webhost/backend/shared/hr_login.py b/webhost/backend/shared/hr_login.py new file mode 100644 index 0000000..5a9e6ff --- /dev/null +++ b/webhost/backend/shared/hr_login.py @@ -0,0 +1,449 @@ +# -*- 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 读取(%LOCALAPPDATA%\37duAutomation\.env 或项目 .env),不内置明文, +# 避免真实凭据写进源码/git 历史;缺失时登录会提示「登录配置缺失」。 +_load_shared_env() +LOGIN_URL = 'https://hr.37du.co/RedseaPlatform/' +SUCCESS_KEYWORD = 'https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic' +USERNAME = os.getenv('hr_login_username', '') +PASSWORD = os.getenv('hr_login_password', '') + +# 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) diff --git a/webhost/backend/shared/oa_login.py b/webhost/backend/shared/oa_login.py new file mode 100644 index 0000000..5530517 --- /dev/null +++ b/webhost/backend/shared/oa_login.py @@ -0,0 +1,241 @@ +# -*- 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 读取(%LOCALAPPDATA%\37duAutomation\.env 或项目 .env),不内置明文, +# 避免真实凭据写进源码/git 历史;缺失时登录会提示「登录配置缺失」。 +_load_shared_env() +LOGIN_URL = 'https://oa.37du.co/login.jsp' +SUCCESS_KEYWORD = 'https://oa.37du.co/sys/portal/page.jsp' +USERNAME = os.getenv('oa_login_username', '') +PASSWORD = os.getenv('oa_login_password', '') + +# 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) diff --git a/webhost/backend/shared/org_export.py b/webhost/backend/shared/org_export.py new file mode 100644 index 0000000..ae97f22 --- /dev/null +++ b/webhost/backend/shared/org_export.py @@ -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) diff --git a/webhost/backend/shared/roster_export_api.py b/webhost/backend/shared/roster_export_api.py new file mode 100644 index 0000000..2902226 --- /dev/null +++ b/webhost/backend/shared/roster_export_api.py @@ -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) diff --git a/webhost/backend/shared/seal_data_export.py b/webhost/backend/shared/seal_data_export.py new file mode 100644 index 0000000..4226a0b --- /dev/null +++ b/webhost/backend/shared/seal_data_export.py @@ -0,0 +1,440 @@ +# -*- 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 workflows/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): + """POST/GET 请求并校验返回 JSON;登录态失效抛 HRSessionExpiredError。 + + 按项目规范做全局重试(最大 3 次,指数退避),仅在网络/服务端异常时重试; + 登录态失效(HRSessionExpiredError)属确定性失败,直接抛出、不重试。 + """ + last_exc = None + for attempt in range(1, 4): + try: + 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}:登录态失效(返回非 JSON)") + return resp.json() + except HRSessionExpiredError: + raise + except Exception as e: + last_exc = e + if attempt < 3: + time.sleep(1.0 * (2 ** (attempt - 1))) + raise last_exc + + +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") or 0 + logger.info("考勤封存已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows)) + # 分页保护:pageCount 缺失/为 0 时不能提前 break,否则会静默截断数据; + # 仅当 pageCount 存在且已到最后页,或返回行数不足一页时才结束分页。 + if total_page and page_no >= total_page: + break + if len(page_list) < PAGE_MAX_SIZE: + 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() diff --git a/webhost/frontend/index.html b/webhost/frontend/index.html new file mode 100644 index 0000000..5a6a934 --- /dev/null +++ b/webhost/frontend/index.html @@ -0,0 +1,12 @@ + + +
+ + +执行日志与进度实时显示在下方日志区,结果完成后自动汇总于此。
+