refactor: 重构雇主险业务,适配多类别拆分与影刀脚本整合
1. 重构ehr/common/config.py与employer_insurance/config.py,新增多类别配置与工具函数 2. 重写employer_insurance.py,支持按类别调度处理 3. 新增影刀共享模块与业务脚本,统一RPA开发规范 4. 移除旧版冗余的影刀脚本文件
This commit is contained in:
@@ -1,253 +1,23 @@
|
||||
{
|
||||
"code" : 200,
|
||||
"message" : "操作成功",
|
||||
"data" : {
|
||||
"total" : 34,
|
||||
"start" : 1,
|
||||
"pageCount" : 5,
|
||||
"list" : [ {
|
||||
"id" : "3ca6c81c7c5d44dda8c52a640c646fea",
|
||||
"staff_id" : "567a66fd-7a9f-11ec-b449-000c296f9469",
|
||||
"kq_time" : "2026-08-18 08:54:44",
|
||||
"status" : "1",
|
||||
"addr_status" : "0",
|
||||
"time_order" : "1",
|
||||
"pb_id" : "CJDE220960286",
|
||||
"time_id" : "",
|
||||
"kq_type" : "9",
|
||||
"comp_id" : "b9cee736-cef2-11ee-b449-000c296f9469",
|
||||
"kq_bc_id" : "de1daf426e7f4fa6916f3012434e8973",
|
||||
"dept_id" : "8daffc5d-0ce1-4fd5-b485-3edfbcd4cb78",
|
||||
"status_time" : null,
|
||||
"team_id" : "355945ef0e894881a21980b79b7dfbf1",
|
||||
"bc_type" : null,
|
||||
"work_date_id" : null,
|
||||
"bc_date" : "2026-08-18",
|
||||
"create_time" : "2026-08-18 08:56:14",
|
||||
"address" : "总部-考勤-库房",
|
||||
"staff_name" : "余陈斌",
|
||||
"varchar1" : null,
|
||||
"operate_time" : "2026-08-18 08:56:14",
|
||||
"Longitude" : null,
|
||||
"Latitude" : null,
|
||||
"DEPT_ORG_NAME" : "物流小组",
|
||||
"POST_ALIAS_NAME" : "车队长",
|
||||
"Content" : null,
|
||||
"ssid" : null,
|
||||
"mac" : null
|
||||
}, {
|
||||
"id" : "ab6fd17b0898452a971b17402d5f64a3",
|
||||
"staff_id" : "567a66fd-7a9f-11ec-b449-000c296f9469",
|
||||
"kq_time" : "2026-08-18 00:03:00",
|
||||
"status" : "5",
|
||||
"addr_status" : "0",
|
||||
"time_order" : "2",
|
||||
"pb_id" : "CJDE211661047",
|
||||
"time_id" : "",
|
||||
"kq_type" : "9",
|
||||
"comp_id" : "b9cee736-cef2-11ee-b449-000c296f9469",
|
||||
"kq_bc_id" : "de1daf426e7f4fa6916f3012434e8973",
|
||||
"dept_id" : "8daffc5d-0ce1-4fd5-b485-3edfbcd4cb78",
|
||||
"status_time" : null,
|
||||
"team_id" : "355945ef0e894881a21980b79b7dfbf1",
|
||||
"bc_type" : null,
|
||||
"work_date_id" : null,
|
||||
"bc_date" : "2026-08-17",
|
||||
"create_time" : "2026-08-18 00:11:14",
|
||||
"address" : "总部-考勤-前厅",
|
||||
"staff_name" : "余陈斌",
|
||||
"varchar1" : "1",
|
||||
"operate_time" : "2026-08-18 03:05:06",
|
||||
"Longitude" : null,
|
||||
"Latitude" : null,
|
||||
"DEPT_ORG_NAME" : "物流小组",
|
||||
"POST_ALIAS_NAME" : "车队长",
|
||||
"Content" : null,
|
||||
"ssid" : null,
|
||||
"mac" : null
|
||||
}, {
|
||||
"id" : "f0f1ae065fa447c99d45ca3ae4d4b31d",
|
||||
"staff_id" : "567a66fd-7a9f-11ec-b449-000c296f9469",
|
||||
"kq_time" : "2026-08-17 08:45:46",
|
||||
"status" : "1",
|
||||
"addr_status" : "0",
|
||||
"time_order" : "1",
|
||||
"pb_id" : "CJDE220960286",
|
||||
"time_id" : "",
|
||||
"kq_type" : "9",
|
||||
"comp_id" : "b9cee736-cef2-11ee-b449-000c296f9469",
|
||||
"kq_bc_id" : "de1daf426e7f4fa6916f3012434e8973",
|
||||
"dept_id" : "8daffc5d-0ce1-4fd5-b485-3edfbcd4cb78",
|
||||
"status_time" : null,
|
||||
"team_id" : "355945ef0e894881a21980b79b7dfbf1",
|
||||
"bc_type" : null,
|
||||
"work_date_id" : null,
|
||||
"bc_date" : "2026-08-17",
|
||||
"create_time" : "2026-08-17 08:51:04",
|
||||
"address" : "总部-考勤-库房",
|
||||
"staff_name" : "余陈斌",
|
||||
"varchar1" : "1",
|
||||
"operate_time" : "2026-08-18 03:05:06",
|
||||
"Longitude" : null,
|
||||
"Latitude" : null,
|
||||
"DEPT_ORG_NAME" : "物流小组",
|
||||
"POST_ALIAS_NAME" : "车队长",
|
||||
"Content" : null,
|
||||
"ssid" : null,
|
||||
"mac" : null
|
||||
}, {
|
||||
"id" : "041e3ebdab964131ab32b7238b5efd0c",
|
||||
"staff_id" : "567a66fd-7a9f-11ec-b449-000c296f9469",
|
||||
"kq_time" : "2026-08-16 21:04:08",
|
||||
"status" : "5",
|
||||
"addr_status" : "0",
|
||||
"time_order" : "2",
|
||||
"pb_id" : "CJDE220960286",
|
||||
"time_id" : "",
|
||||
"kq_type" : "9",
|
||||
"comp_id" : "b9cee736-cef2-11ee-b449-000c296f9469",
|
||||
"kq_bc_id" : "de1daf426e7f4fa6916f3012434e8973",
|
||||
"dept_id" : "8daffc5d-0ce1-4fd5-b485-3edfbcd4cb78",
|
||||
"status_time" : null,
|
||||
"team_id" : "355945ef0e894881a21980b79b7dfbf1",
|
||||
"bc_type" : null,
|
||||
"work_date_id" : null,
|
||||
"bc_date" : "2026-08-16",
|
||||
"create_time" : "2026-08-16 21:06:03",
|
||||
"address" : "总部-考勤-库房",
|
||||
"staff_name" : "余陈斌",
|
||||
"varchar1" : "1",
|
||||
"operate_time" : "2026-08-17 09:19:00",
|
||||
"Longitude" : null,
|
||||
"Latitude" : null,
|
||||
"DEPT_ORG_NAME" : "物流小组",
|
||||
"POST_ALIAS_NAME" : "车队长",
|
||||
"Content" : null,
|
||||
"ssid" : null,
|
||||
"mac" : null
|
||||
}, {
|
||||
"id" : "2f001d7f3795468fb071585cc3a2ed38",
|
||||
"staff_id" : "567a66fd-7a9f-11ec-b449-000c296f9469",
|
||||
"kq_time" : "2026-08-16 08:49:19",
|
||||
"status" : "1",
|
||||
"addr_status" : "0",
|
||||
"time_order" : "1",
|
||||
"pb_id" : "CJDE220960286",
|
||||
"time_id" : "",
|
||||
"kq_type" : "9",
|
||||
"comp_id" : "b9cee736-cef2-11ee-b449-000c296f9469",
|
||||
"kq_bc_id" : "de1daf426e7f4fa6916f3012434e8973",
|
||||
"dept_id" : "8daffc5d-0ce1-4fd5-b485-3edfbcd4cb78",
|
||||
"status_time" : null,
|
||||
"team_id" : "355945ef0e894881a21980b79b7dfbf1",
|
||||
"bc_type" : null,
|
||||
"work_date_id" : null,
|
||||
"bc_date" : "2026-08-16",
|
||||
"create_time" : "2026-08-16 08:51:15",
|
||||
"address" : "总部-考勤-库房",
|
||||
"staff_name" : "余陈斌",
|
||||
"varchar1" : "1",
|
||||
"operate_time" : "2026-08-17 09:19:00",
|
||||
"Longitude" : null,
|
||||
"Latitude" : null,
|
||||
"DEPT_ORG_NAME" : "物流小组",
|
||||
"POST_ALIAS_NAME" : "车队长",
|
||||
"Content" : null,
|
||||
"ssid" : null,
|
||||
"mac" : null
|
||||
}, {
|
||||
"id" : "3ece02fb14834c7997fe22742f446782",
|
||||
"staff_id" : "567a66fd-7a9f-11ec-b449-000c296f9469",
|
||||
"kq_time" : "2026-08-15 19:36:58",
|
||||
"status" : "5",
|
||||
"addr_status" : "0",
|
||||
"time_order" : "2",
|
||||
"pb_id" : "CJDE211661047",
|
||||
"time_id" : "",
|
||||
"kq_type" : "9",
|
||||
"comp_id" : "b9cee736-cef2-11ee-b449-000c296f9469",
|
||||
"kq_bc_id" : "de1daf426e7f4fa6916f3012434e8973",
|
||||
"dept_id" : "8daffc5d-0ce1-4fd5-b485-3edfbcd4cb78",
|
||||
"status_time" : null,
|
||||
"team_id" : "355945ef0e894881a21980b79b7dfbf1",
|
||||
"bc_type" : null,
|
||||
"work_date_id" : null,
|
||||
"bc_date" : "2026-08-15",
|
||||
"create_time" : "2026-08-15 19:41:00",
|
||||
"address" : "总部-考勤-前厅",
|
||||
"staff_name" : "余陈斌",
|
||||
"varchar1" : "1",
|
||||
"operate_time" : "2026-08-17 12:09:01",
|
||||
"Longitude" : null,
|
||||
"Latitude" : null,
|
||||
"DEPT_ORG_NAME" : "物流小组",
|
||||
"POST_ALIAS_NAME" : "车队长",
|
||||
"Content" : null,
|
||||
"ssid" : null,
|
||||
"mac" : null
|
||||
}, {
|
||||
"id" : "1104cbe2cc1247f9b55e3c0e53daf53a",
|
||||
"staff_id" : "567a66fd-7a9f-11ec-b449-000c296f9469",
|
||||
"kq_time" : "2026-08-15 10:46:42",
|
||||
"status" : "1",
|
||||
"addr_status" : "0",
|
||||
"time_order" : "1",
|
||||
"pb_id" : "CJDE220960286",
|
||||
"time_id" : "",
|
||||
"kq_type" : "9",
|
||||
"comp_id" : "b9cee736-cef2-11ee-b449-000c296f9469",
|
||||
"kq_bc_id" : "de1daf426e7f4fa6916f3012434e8973",
|
||||
"dept_id" : "8daffc5d-0ce1-4fd5-b485-3edfbcd4cb78",
|
||||
"status_time" : null,
|
||||
"team_id" : "355945ef0e894881a21980b79b7dfbf1",
|
||||
"bc_type" : null,
|
||||
"work_date_id" : null,
|
||||
"bc_date" : "2026-08-15",
|
||||
"create_time" : "2026-08-15 10:51:00",
|
||||
"address" : "总部-考勤-库房",
|
||||
"staff_name" : "余陈斌",
|
||||
"varchar1" : "1",
|
||||
"operate_time" : "2026-08-17 12:09:00",
|
||||
"Longitude" : null,
|
||||
"Latitude" : null,
|
||||
"DEPT_ORG_NAME" : "物流小组",
|
||||
"POST_ALIAS_NAME" : "车队长",
|
||||
"Content" : null,
|
||||
"ssid" : null,
|
||||
"mac" : null
|
||||
}, {
|
||||
"id" : "37883245622e4821a9a54907e15db3fc",
|
||||
"staff_id" : "567a66fd-7a9f-11ec-b449-000c296f9469",
|
||||
"kq_time" : "2026-08-14 20:30:35",
|
||||
"status" : "5",
|
||||
"addr_status" : "0",
|
||||
"time_order" : "2",
|
||||
"pb_id" : "CJDE220960286",
|
||||
"time_id" : "",
|
||||
"kq_type" : "9",
|
||||
"comp_id" : "b9cee736-cef2-11ee-b449-000c296f9469",
|
||||
"kq_bc_id" : "de1daf426e7f4fa6916f3012434e8973",
|
||||
"dept_id" : "8daffc5d-0ce1-4fd5-b485-3edfbcd4cb78",
|
||||
"status_time" : null,
|
||||
"team_id" : "355945ef0e894881a21980b79b7dfbf1",
|
||||
"bc_type" : null,
|
||||
"work_date_id" : null,
|
||||
"bc_date" : "2026-08-14",
|
||||
"create_time" : "2026-08-14 20:36:00",
|
||||
"address" : "总部-考勤-库房",
|
||||
"staff_name" : "余陈斌",
|
||||
"varchar1" : "1",
|
||||
"operate_time" : "2026-08-17 14:50:01",
|
||||
"Longitude" : null,
|
||||
"Latitude" : null,
|
||||
"DEPT_ORG_NAME" : "物流小组",
|
||||
"POST_ALIAS_NAME" : "车队长",
|
||||
"Content" : null,
|
||||
"ssid" : null,
|
||||
"mac" : null
|
||||
} ]
|
||||
},
|
||||
"des" : null,
|
||||
"errStack" : null,
|
||||
"success" : true
|
||||
}
|
||||
访问待增减员工页面
|
||||
点击更多操作按钮
|
||||
<div class="btn-group dropdown mgr-10" id="more-btns" style="">
|
||||
<button type="button" class="btn btn-success btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i18n key="COMMON_BTN">更多操作</i18n>
|
||||
<span style="font-size: 14px;margin-left:5px;float: none;" class="icon icon-angle-down"></span>
|
||||
<span class="sr-only">Toggle Dropdown</span>
|
||||
</button>
|
||||
<ul class="dropdown-menu" id="custom-btn-ul"><li trans-id="6c6416a4-c6a2-488f-a38c-18b7abecf28a" btn-property-page-id="null" class=""><a>增员导入</a></li><li trans-id="c3d720ca-d91c-4515-a9d5-0c40c73525aa" btn-property-page-id="null" class=""><a>减员导入</a></li><li trans-id="" btn-property-page-id="undefined" class=""><a>导出</a></li></ul>
|
||||
</div>
|
||||
根据传入的增员还是减员,点击对应的按钮
|
||||
选择文件夹按钮(glyphicon glyphicon-folder-open)
|
||||
<div class="input-group input-group-sm"><input type="text" readonly="readonly" class="form-control" style="min-width: 150px;"> <input name="file" type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" class="hidden"> <span class="input-group-addon btn"><i class="glyphicon glyphicon-folder-open"></i></span> <span class="input-group-addon btn" style="margin-left: 40px;"><i class="glyphicon glyphicon-trash"></i></span></div>
|
||||
这个时候会弹出文件选择器,选择传入的文件("D:\资料\人资\雇主险\商业保险增员导入.xlsx")
|
||||
点击下一步按钮
|
||||
<div class="sub-btn custom-sub-btn"><button type="button" class="btn btn-default">关闭</button> <button type="button" class="btn btn-default" style="display: none;">继续导入</button> <button type="button" class="btn btn-default">导入异常记录</button> <button type="button" class="btn btn-success" style="display: none;">上一步</button> <button type="button" class="btn btn-success">下一步</button></div>
|
||||
接着点击下一步按钮
|
||||
<div class="sub-btn custom-sub-btn"><button type="button" class="btn btn-default">关闭</button> <button type="button" class="btn btn-default" style="display: none;">继续导入</button> <button type="button" class="btn btn-default">导入异常记录</button> <button type="button" class="btn btn-success" style="">上一步</button> <button type="button" class="btn btn-success" style="">下一步</button></div>
|
||||
点击关闭按钮
|
||||
<div class="sub-btn custom-sub-btn"><button type="button" class="btn btn-default">关闭</button> <button type="button" class="btn btn-default" style="display: none;">继续导入</button> <button type="button" class="btn btn-default">导入异常记录</button> <button type="button" class="btn btn-success" style="">上一步</button> <button type="button" class="btn btn-success" style="display: none;">下一步</button></div>
|
||||
以上是增员导入的流程
|
||||
减员选择传入的文件为("D:\资料\人资\雇主险\商业保险减员导入.xlsx")
|
||||
接着是同样的流程
|
||||
|
||||
|
||||
@@ -15,14 +15,17 @@ WAGE_CARD_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/HrStaffWageCard.m
|
||||
# 单页最大抓取条数
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ---------- 银行字典接口(aa.md 提供,按 BANK_TYPE 匹配 code -> 开卡银行) ----------
|
||||
# ---------- 银行字典接口 ----------
|
||||
BANK_DICT_URL = "https://hr.37du.co/RedseaPlatform/PtCodeTypeValue.mc?method=getCodeValueByCodes"
|
||||
BANK_DICT_CODE_TYPE = "WAGE.BANKTYPE"
|
||||
BANK_DICT_EXPIRE_SEC = 7 * 24 * 60 * 60 # 缓存7天过期,自动重新拉取
|
||||
|
||||
# ---------- 员工花名册(自定义导出)页面 ----------
|
||||
# 花名册自定义导出页面(aa.md 提供),基于 DrissionPage 浏览器自动化操作
|
||||
ROSTER_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-77128-52242&nworktoday-40175-24311|/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/getCustomCommonList.mc?clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=%E5%91%98%E5%B7%A5%E8%8A%B1%E5%90%8D%E5%86%8C"
|
||||
# 花名册自定义导出页面
|
||||
ROSTER_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-77128-52242&nworktoday-40175-24311|/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/getCustomCommonList.mc?clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=员工花名册"
|
||||
|
||||
# 待增减人员操作页面
|
||||
ADD_SUB_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-13664-23874-98879&nworktoday-40175-13664|/RedseaPlatform/hrRoster/7984ae1a-16ec-11ed-bea9-822ff8ed5b28/getCustomCommonList.mc?menuName=待增减人员"
|
||||
|
||||
# 花名册自定义导出模板(下拉框中全部模板,后续各业务场景可按需选用)
|
||||
ROSTER_TEMPLATE_NAME = "员工基础信息" # 默认模板
|
||||
@@ -40,16 +43,16 @@ ATTENDANCE_ABNORMAL_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPag
|
||||
# 考勤异常确认/调整接口(abnormalIds=异常单据id,type=1 表示自动确认)
|
||||
ATTENDANCE_ADJUST_URL = "https://hr.37du.co/RedseaPlatform/abnormalAdjust/KqCountAbnormal.mc"
|
||||
|
||||
# 查询排班接口(aa.md 提供,用于过滤虚假异常)
|
||||
# 查询排班接口
|
||||
SHIFT_URL = "https://hr.37du.co/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
|
||||
# 查询请假记录接口(aa.md 提供,用于过滤虚假异常)
|
||||
# 查询请假记录接口
|
||||
LEAVE_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
# 查询加班记录接口(aa.md 提供,用于过滤虚假异常)
|
||||
# 查询加班记录接口
|
||||
OVERTIME_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
# 查询打卡记录接口(aa.md 提供,sqlId=kq_data_query,按 base_code 工号查原始打卡流水)
|
||||
# 查询打卡记录接口
|
||||
KQ_DATA_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
|
||||
# 假期类型编码映射已上移到 HR 平台共享层 app/service/hrbp/common/config.py(VACATION_TYPE_MAP),
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance
|
||||
@FileName: add_sub_import.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-18
|
||||
@Description: 雇主险流程「步骤3:增减员导入」。在 HR「待增减人员」页面执行增员/减员导入
|
||||
(复刻 aa.md 的操作流程:访问页面 -> 更多操作 -> 增员导入/减员导入 -> 上传文件 -> 下一步 -> 下一步 -> 关闭)
|
||||
- 前置:步骤2 调度(employer_insurance.py)完成,并准备好增员/减员导入文件
|
||||
- 传入参数:增员(默认商业保险增员导入.xlsx)或 减员(商业保险减员导入.xlsx)
|
||||
- 复用 HR 登录态(app.service.hrbp.common.login 的缓存 cookies)
|
||||
@Version: 1.0.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块完成登录并缓存 cookies;后续自动复用,过期自动重新登录。
|
||||
2. 通过函数传参调用(无命令行入口):
|
||||
from app.service.hrbp.ehr.employer_insurance.add_sub_import import import_employee_change
|
||||
|
||||
import_employee_change("增员") # 增员导入(默认文件)
|
||||
import_employee_change("减员") # 减员导入(默认文件)
|
||||
import_employee_change("增员", r"D:\\...\\xxx.xlsx") # 指定导入文件
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
except ImportError:
|
||||
ChromiumPage = None
|
||||
ChromiumOptions = None
|
||||
|
||||
from app.service.hrbp.ehr.common.config import ADD_SUB_URL # noqa: E402
|
||||
from app.service.hrbp.common.login import load_cookies # noqa: E402
|
||||
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
ADD_SUB_IMPORT_ADD_FILE,
|
||||
ADD_SUB_IMPORT_SUB_FILE,
|
||||
get_category,
|
||||
category_import_add_file,
|
||||
category_import_sub_file,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ===================== 流程步骤所用文案常量(aa.md 提供) =====================
|
||||
BTN_MORE = "更多操作" # 「更多操作」下拉按钮
|
||||
MENU_ADD = "增员导入" # 下拉菜单:增员导入
|
||||
MENU_SUB = "减员导入" # 下拉菜单:减员导入
|
||||
BTN_NEXT = "下一步" # 导入弹窗「下一步」按钮(第 2/3 步)
|
||||
BTN_CLOSE = "关闭" # 导入完成弹窗「关闭」按钮
|
||||
|
||||
# 通用等待秒数
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 1. 元素定位辅助(DrissionPage)
|
||||
# ---------------------------------------------------------------
|
||||
def _click_text(page, text, timeout=10):
|
||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise RuntimeError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _click_text_in(page, container, text, timeout=5):
|
||||
"""在指定容器内按文本匹配并点击。"""
|
||||
ele = container.ele(f'xpath:.//*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise RuntimeError(f"容器内未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _is_displayed(ele):
|
||||
"""判断元素是否可见且具有尺寸;异常时返回 False(保守不误判)。"""
|
||||
if ele is None:
|
||||
return False
|
||||
try:
|
||||
if not ele.states.is_displayed:
|
||||
return False
|
||||
w, h = ele.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 2. 打开待增减人员页面并确保登录态(复用缓存 cookies)
|
||||
# ---------------------------------------------------------------
|
||||
def _ensure_logged_in(page):
|
||||
"""访问待增减人员页面;若被重定向到登录页,则复用/重登 HR 登录态。"""
|
||||
page.get(ADD_SUB_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
|
||||
# 登录页特征:存在用户名输入框
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
logger.info("HR 登录态已失效,执行重新登录")
|
||||
from app.service.hrbp.common.login import login as hr_login
|
||||
if not hr_login():
|
||||
raise RuntimeError("HR 重新登录失败")
|
||||
cookies = load_cookies()
|
||||
if cookies:
|
||||
page.set.cookies(cookies)
|
||||
page.get(ADD_SUB_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise RuntimeError("HR 重新登录后仍停留在登录页")
|
||||
logger.info("已进入待增减人员页面:%s", page.url)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 3. 增员/减员导入主流程(aa.md 步骤)
|
||||
# ---------------------------------------------------------------
|
||||
def _open_more_operations(page):
|
||||
"""点击「更多操作」按钮,展开下拉菜单(幂等,已展开则跳过)。"""
|
||||
# 若下拉菜单已可见,直接返回
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=2)
|
||||
if menu and _is_displayed(menu):
|
||||
logger.info("「更多操作」下拉已展开,跳过")
|
||||
time.sleep(WAIT_SHORT)
|
||||
return menu
|
||||
|
||||
# 定位「更多操作」按钮(#more-btns 容器内的 btn-success dropdown-toggle)
|
||||
more_btn = page.ele('css:#more-btns button.dropdown-toggle', timeout=15)
|
||||
if not more_btn:
|
||||
more_btn = page.ele('css:button.btn-success.dropdown-toggle', timeout=5)
|
||||
if not more_btn:
|
||||
_click_text(page, BTN_MORE)
|
||||
else:
|
||||
more_btn.click()
|
||||
logger.info("已点击「更多操作」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=5)
|
||||
if not menu:
|
||||
raise RuntimeError("未找到「更多操作」下拉菜单(#custom-btn-ul)")
|
||||
logger.info("「更多操作」下拉已展开")
|
||||
return menu
|
||||
|
||||
|
||||
def _choose_import_menu(page, import_type):
|
||||
"""在下拉菜单中选择「增员导入」或「减员导入」。"""
|
||||
if import_type not in (MENU_ADD, MENU_SUB):
|
||||
raise ValueError(f"不支持的导入类型:{import_type}(应为 {MENU_ADD} 或 {MENU_SUB})")
|
||||
menu = _open_more_operations(page)
|
||||
_click_text_in(page, menu, import_type)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _upload_file(page, file_path):
|
||||
"""在导入弹窗中上传指定文件。
|
||||
|
||||
aa.md:选择文件夹按钮(glyphicon glyphicon-folder-open)会弹出文件选择器;
|
||||
这里直接用 DrissionPage 对 <input type="file"> 设置文件路径,跳过系统文件选择框。
|
||||
"""
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
|
||||
file_input = page.ele('css:input[name="file"]', timeout=15)
|
||||
if not file_input:
|
||||
raise RuntimeError("未找到文件上传控件(input[name=file])")
|
||||
file_input.input(file_path)
|
||||
logger.info("已选择导入文件:%s", file_path)
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
def _click_next(page):
|
||||
"""点击导入弹窗中的「下一步」按钮(btn-success 且可见)。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-success")'
|
||||
' and normalize-space(.)="下一步"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise RuntimeError("未找到可见的「下一步」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「下一步」")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _click_close(page):
|
||||
"""点击导入完成弹窗中的「关闭」按钮。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-default")'
|
||||
' and normalize-space(.)="关闭"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise RuntimeError("未找到可见的「关闭」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「关闭」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 4. 对外入口(函数传参调用)
|
||||
# ---------------------------------------------------------------
|
||||
# 参数兼容「增员/减员」短名 与「增员导入/减员导入」菜单全名
|
||||
_IMPORT_TYPE_MAP = {
|
||||
"增员": MENU_ADD,
|
||||
"减员": MENU_SUB,
|
||||
MENU_ADD: MENU_ADD,
|
||||
MENU_SUB: MENU_SUB,
|
||||
}
|
||||
|
||||
|
||||
def _resolve_import_file(menu_label, category_name):
|
||||
"""按类别+导入类型解析默认导入文件路径。
|
||||
|
||||
指定类别时取该类别文件夹内的导入文件;未指定类别(None)时用三十七度的默认文件。
|
||||
"""
|
||||
if category_name:
|
||||
category = get_category(category_name)
|
||||
if menu_label == MENU_ADD:
|
||||
return category_import_add_file(category)
|
||||
return category_import_sub_file(category)
|
||||
return (
|
||||
ADD_SUB_IMPORT_ADD_FILE if menu_label == MENU_ADD else ADD_SUB_IMPORT_SUB_FILE
|
||||
)
|
||||
|
||||
|
||||
def import_employee_change(import_type="增员", category_name=None, file_path=None):
|
||||
"""执行增员/减员导入。
|
||||
|
||||
Args:
|
||||
import_type: "增员" 或 "减员"(也兼容 "增员导入"/"减员导入"),默认增员。
|
||||
category_name: 类别名(如「湖畔酒店」/「湖畔」),None 表示默认使用三十七度。
|
||||
file_path: 要上传的文件路径;不传则按类别+导入类型取默认文件
|
||||
(各类别文件夹内的 商业保险增员导入.xlsx / 商业保险减员导入.xlsx;
|
||||
category_name 为 None 时用三十七度的默认文件)。
|
||||
|
||||
Returns:
|
||||
bool: 成功返回 True。
|
||||
|
||||
Raises:
|
||||
ValueError: import_type 非法。
|
||||
FileNotFoundError: 导入文件不存在。
|
||||
RuntimeError: 缺少 DrissionPage 依赖或流程任一步骤失败时抛出。
|
||||
"""
|
||||
setup_logging()
|
||||
if ChromiumPage is None:
|
||||
raise RuntimeError("缺少 DrissionPage 依赖,请先安装: pip install DrissionPage")
|
||||
|
||||
if import_type not in _IMPORT_TYPE_MAP:
|
||||
raise ValueError(f"不支持的导入类型:{import_type}(应为「增员」或「减员」)")
|
||||
menu_label = _IMPORT_TYPE_MAP[import_type]
|
||||
|
||||
file_path = file_path or _resolve_import_file(menu_label, category_name)
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
|
||||
logger.info("===== 开始%s,文件:%s =====", menu_label, file_path)
|
||||
|
||||
co = ChromiumOptions()
|
||||
page = ChromiumPage(co)
|
||||
logger.info("浏览器已启动")
|
||||
try:
|
||||
# 注入缓存 cookies,再访问页面
|
||||
cookies = load_cookies()
|
||||
logger.info("加载缓存 cookies:%d 个", len(cookies or []))
|
||||
if cookies:
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
except Exception as e:
|
||||
logger.warning("注入缓存 cookies 失败:%s", e)
|
||||
|
||||
_ensure_logged_in(page)
|
||||
_choose_import_menu(page, menu_label)
|
||||
_upload_file(page, file_path)
|
||||
_click_next(page) # 第一步:下一步(进入解析)
|
||||
_click_next(page) # 第二步:下一步(进入确认/完成)
|
||||
_click_close(page) # 第三步:关闭
|
||||
|
||||
logger.info("===== %s完成 =====", menu_label)
|
||||
return True
|
||||
except Exception:
|
||||
logger.exception("%s失败,详细堆栈如下:", menu_label)
|
||||
raise
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import_employee_change("增员")
|
||||
import_employee_change("减员")
|
||||
@@ -19,10 +19,120 @@ DATE_STR = datetime.now().strftime("%Y.%m.%d")
|
||||
DATE_SHORT = datetime.now().strftime("%m.%d")
|
||||
TODAY_DATE = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
# 输入/输出文件路径
|
||||
TARGET_FILE = os.path.join(BASE_DIR, f"三十七度-雇主险变更记录-{DATE_STR}.xlsx")
|
||||
# 输入/输出文件路径(三十七度默认,其余类别由 CATEGORIES 动态解析)
|
||||
OUTPUT_IN_PARAM = os.path.join(BASE_DIR, f"新在参名单-{DATE_STR}.xlsx")
|
||||
|
||||
# ---------- 四大类别(全流程按类别传参处理) ----------
|
||||
# 每类一个独立文件夹,目标文件为文件夹内最新的「*雇主险变更记录*.xlsx」。
|
||||
# include_dept: 仅保留的所属单位(空列表=不限制);exclude_dept: 需要排除的所属单位;
|
||||
# change_sheet_prefix: 步骤2调度时「变更清单」sheet 名称前缀(各类须统一该命名规则)。
|
||||
CATEGORIES = [
|
||||
{
|
||||
"name": "三十七度",
|
||||
"folder": os.path.join(BASE_DIR, "三十七度"),
|
||||
"include_dept": [],
|
||||
"exclude_dept": ["金色湖畔事业部", "秒创传媒事业部", "水庄大鹅事业部"],
|
||||
"change_sheet_prefix": "37度-雇员变更清单",
|
||||
},
|
||||
{
|
||||
"name": "水庄餐饮",
|
||||
"folder": os.path.join(BASE_DIR, "水庄餐饮"),
|
||||
"include_dept": ["水庄大鹅事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "水庄-雇员变更清单",
|
||||
},
|
||||
{
|
||||
"name": "湖畔酒店",
|
||||
"folder": os.path.join(BASE_DIR, "湖畔酒店"),
|
||||
"include_dept": ["金色湖畔事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "湖畔-雇员变更清单",
|
||||
},
|
||||
{
|
||||
"name": "秒创传媒",
|
||||
"folder": os.path.join(BASE_DIR, "秒创传媒"),
|
||||
"include_dept": ["秒创传媒事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "秒创-雇员变更清单",
|
||||
},
|
||||
]
|
||||
|
||||
# ---------- 类别辅助函数(全流程共用) ----------
|
||||
def get_category(name):
|
||||
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。
|
||||
|
||||
Args:
|
||||
name: 类别名
|
||||
|
||||
Returns:
|
||||
类别配置 dict
|
||||
|
||||
Raises:
|
||||
ValueError: 未知名或前缀不唯一
|
||||
"""
|
||||
name = (name or "").strip()
|
||||
for c in CATEGORIES:
|
||||
if c["name"] == name:
|
||||
return c
|
||||
matched = [c for c in CATEGORIES if c["name"].startswith(name)]
|
||||
if len(matched) == 1:
|
||||
return matched[0]
|
||||
raise ValueError(f"未知类别:{name},可选:{[c['name'] for c in CATEGORIES]}")
|
||||
|
||||
|
||||
def find_latest_target(folder):
|
||||
"""在类别文件夹中定位最新的「*雇主险变更记录*.xlsx」目标文件。
|
||||
|
||||
Args:
|
||||
folder: 类别文件夹路径
|
||||
|
||||
Returns:
|
||||
最新目标文件绝对路径
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 文件夹不存在或其中没有符合条件的雇主险变更记录文件
|
||||
"""
|
||||
if not os.path.isdir(folder):
|
||||
raise FileNotFoundError(f"类别文件夹不存在:{folder}")
|
||||
candidates = [
|
||||
os.path.join(folder, f)
|
||||
for f in os.listdir(folder)
|
||||
if f.lower().endswith(".xlsx") and "雇主险变更记录" in f
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"文件夹 {folder} 下未找到「*雇主险变更记录*.xlsx」文件,请先准备今日的雇主险变更记录模板")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def category_target_file(category):
|
||||
"""类别目标文件(各文件夹内最新的雇主险变更记录)。"""
|
||||
return find_latest_target(category["folder"])
|
||||
|
||||
|
||||
def category_output_backup(category):
|
||||
"""类别「新在参名单」备份路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], f"新在参名单-{DATE_STR}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_name(category):
|
||||
"""类别「变更清单」sheet 名称。"""
|
||||
return f"{category['change_sheet_prefix']}-{DATE_SHORT}"
|
||||
|
||||
|
||||
def category_import_add_file(category):
|
||||
"""类别「增员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], "商业保险增员导入.xlsx")
|
||||
|
||||
|
||||
def category_import_sub_file(category):
|
||||
"""类别「减员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(category["folder"], "商业保险减员导入.xlsx")
|
||||
|
||||
# 增减员导入文件(步骤3:在 HR「待增减人员」页面上传,aa.md 提供)
|
||||
ADD_SUB_IMPORT_ADD_FILE = os.path.join(BASE_DIR, "商业保险增员导入.xlsx")
|
||||
ADD_SUB_IMPORT_SUB_FILE = os.path.join(BASE_DIR, "商业保险减员导入.xlsx")
|
||||
|
||||
# 固定 Sheet 名称
|
||||
SHEET_BIZ = "花名册导出-雇主险使用基础信息"
|
||||
SHEET_IN_PARAM = "手动维护-在参名单"
|
||||
|
||||
@@ -51,14 +51,10 @@ from copy import copy
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
BASE_DIR,
|
||||
TODAY_DATE,
|
||||
TARGET_FILE,
|
||||
OUTPUT_IN_PARAM,
|
||||
CATEGORIES,
|
||||
SHEET_BIZ,
|
||||
SHEET_IN_PARAM,
|
||||
CHANGE_SHEET_PREFIX,
|
||||
CHANGE_SHEET_NAME,
|
||||
BIZ_COL_EMPLOYEE_ID,
|
||||
BIZ_COL_CATEGORY,
|
||||
BIZ_COL_SCHEME,
|
||||
@@ -67,6 +63,10 @@ from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
VALID_CATEGORIES,
|
||||
VALID_SCHEMES,
|
||||
ENABLE_VALIDATION,
|
||||
get_category,
|
||||
category_target_file,
|
||||
category_output_backup,
|
||||
category_change_sheet_name,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
@@ -356,7 +356,7 @@ def allocate_slots(idle_pools, employee_map, pending_queues, change_log):
|
||||
# ============================================================
|
||||
def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
in_param_df, column_names, target_file, output_backup,
|
||||
change_sheet_name, in_param_sheet):
|
||||
change_sheet_name, change_sheet_prefix, in_param_sheet):
|
||||
"""
|
||||
输出三部分内容:
|
||||
1. 更新"手动维护-在参名单"(第17行起B~N列)
|
||||
@@ -558,7 +558,7 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
# 收集所有以"37度-雇员变更清单"开头、且不是当前目标名的Sheet作为候选模板
|
||||
candidates = [
|
||||
name for name in wb.sheetnames
|
||||
if name.startswith(CHANGE_SHEET_PREFIX) and name != change_sheet_name
|
||||
if name.startswith(change_sheet_prefix) and name != change_sheet_name
|
||||
]
|
||||
|
||||
def _template_sort_key(name):
|
||||
@@ -673,21 +673,27 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
# ============================================================
|
||||
# 六、入口(步骤2:调度)
|
||||
# ============================================================
|
||||
def main():
|
||||
"""步骤2:调度(读取已刷新公式的目标文件,输出结果)。
|
||||
def schedule_category(category):
|
||||
"""对单个类别执行调度全流程(读取已刷新公式的目标文件,输出结果)。
|
||||
|
||||
前置:先运行 roster_filter.py(步骤1:筛选复制),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
"""
|
||||
logger.info("目标文件:%s", TARGET_FILE)
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
output_backup = category_output_backup(category)
|
||||
change_sheet_prefix = category["change_sheet_prefix"]
|
||||
change_sheet_name = category_change_sheet_name(category)
|
||||
logger.info("=" * 70)
|
||||
logger.info("类别[%s] 目标文件:%s", category_name, target_file)
|
||||
|
||||
# 检查文件是否存在
|
||||
if not os.path.exists(TARGET_FILE):
|
||||
logger.error("目标表不存在:%s,请先运行 roster_filter.py 步骤生成。", TARGET_FILE)
|
||||
if not os.path.exists(target_file):
|
||||
logger.error("目标表不存在:%s,请先运行 roster_filter.py 步骤生成。", target_file)
|
||||
return
|
||||
|
||||
# 检查必需Sheet
|
||||
xl = pd.ExcelFile(TARGET_FILE)
|
||||
xl = pd.ExcelFile(target_file)
|
||||
required_sheets = [SHEET_BIZ, SHEET_IN_PARAM]
|
||||
for s in required_sheets:
|
||||
if s not in xl.sheet_names:
|
||||
@@ -696,7 +702,7 @@ def main():
|
||||
logger.info("文件结构检查通过。")
|
||||
|
||||
# ---------- 读取并清洗花名册数据 ----------
|
||||
biz_df = pd.read_excel(TARGET_FILE, sheet_name=SHEET_BIZ, header=3)
|
||||
biz_df = pd.read_excel(target_file, sheet_name=SHEET_BIZ, header=3)
|
||||
logger.info("原始花名册数据:%d 行", len(biz_df))
|
||||
|
||||
# 过滤:证件号为空 或 方案处理为 "/"
|
||||
@@ -707,7 +713,7 @@ def main():
|
||||
logger.info("清洗后花名册数据:%d 行", len(biz_df))
|
||||
|
||||
# ---------- 读取在参名单 ----------
|
||||
in_param_df = pd.read_excel(TARGET_FILE, sheet_name=SHEET_IN_PARAM, header=5)
|
||||
in_param_df = pd.read_excel(target_file, sheet_name=SHEET_IN_PARAM, header=5)
|
||||
column_names = in_param_df.columns.tolist()
|
||||
logger.info("在参名单:%d 行", len(in_param_df))
|
||||
|
||||
@@ -756,12 +762,32 @@ def main():
|
||||
biz_df,
|
||||
in_param_df,
|
||||
column_names,
|
||||
TARGET_FILE,
|
||||
OUTPUT_IN_PARAM,
|
||||
CHANGE_SHEET_NAME,
|
||||
target_file,
|
||||
output_backup,
|
||||
change_sheet_name,
|
||||
change_sheet_prefix,
|
||||
SHEET_IN_PARAM
|
||||
)
|
||||
|
||||
logger.info("类别[%s] 调度完成!", category_name)
|
||||
|
||||
|
||||
def main(category_name: str = None):
|
||||
"""步骤2:调度(读取已刷新公式的目标文件,输出结果)。
|
||||
|
||||
Args:
|
||||
category_name: 类别名(如「湖畔酒店」/「湖畔」),None 表示处理全部类别。
|
||||
|
||||
前置:先运行 roster_filter.py(步骤1:筛选复制),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
"""
|
||||
categories = [get_category(category_name)] if category_name else CATEGORIES
|
||||
for category in categories:
|
||||
try:
|
||||
schedule_category(category)
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 调度失败", category["name"])
|
||||
|
||||
logger.info("全部完成!")
|
||||
|
||||
|
||||
|
||||
@@ -4,13 +4,14 @@
|
||||
@FileName: roster_filter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险流程「步骤1:筛选复制」。从员工花名册筛选数据,复制到雇主险变更记录表
|
||||
@Description: 雇主险流程「步骤1:筛选复制」。从员工花名册按四大类别筛选数据,复制到各自类别的雇主险变更记录表
|
||||
(复刻 aa.md 的 WPS JS 宏,仅复制,不校验)
|
||||
- 源表:员工花名册.xlsx(统一格式:单 sheet、表头自动定位、业务列 B~O 14列)
|
||||
- 过滤:排除指定事业部(B列/所属单位)+「虚拟大区」(C列/一级部门)
|
||||
- 目标:三十七度-雇主险变更记录 的「花名册导出-雇主险使用基础信息」sheet,表头第4行,数据第5行起(B~O 14列)
|
||||
- 四大类别(config.CATEGORIES):三十七度 / 水庄餐饮 / 湖畔酒店 / 秒创传媒,各自独立文件夹
|
||||
- 过滤:按类别 include/exclude 所属单位(B列)+ 统一排除「虚拟大区」(C列/一级部门)
|
||||
- 目标:各文件夹内最新的「*雇主险变更记录*.xlsx」的「花名册导出-雇主险使用基础信息」sheet,表头第4行,数据第5行起(B~O 14列)
|
||||
- 源表缺失时自动调用 roster_export 从 HR 系统导出(输出位置由本场景指定)
|
||||
@Version: 1.1.0
|
||||
@Version: 2.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
@@ -36,18 +37,19 @@ from openpyxl import load_workbook # noqa: E402
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
BASE_DIR,
|
||||
TARGET_FILE,
|
||||
CATEGORIES,
|
||||
SHEET_BIZ,
|
||||
ROSTER_TEMPLATE_NAME,
|
||||
ROSTER_EXPORT_STATUSES,
|
||||
get_category,
|
||||
find_latest_target,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ---------- 源表配置(与 aa.md 宏保持一致) ----------
|
||||
EMPLOYEE_FILE = os.path.join(BASE_DIR, "员工花名册.xlsx")
|
||||
EXCLUDE_DEPT = ["金色湖畔事业部", "秒创传媒事业部", "水庄大鹅事业部"]
|
||||
EXCLUDE_REGION = "虚拟大区"
|
||||
EXCLUDE_REGION = "虚拟大区" # 统一排除的一级部门(各类别均生效)
|
||||
|
||||
# 源表统一格式规范(roster_export._merge_roster_files 输出):
|
||||
# 单 sheet、只保留第2行表头(丢弃第1行标题)、「类型」列统一在最后一列
|
||||
@@ -57,13 +59,14 @@ TARGET_HEADER_ROW = 4 # 目标表表头在第4行(数据第5行起
|
||||
DATA_COLUMNS = 14 # B~O 共14列(所属单位..证件号)
|
||||
|
||||
|
||||
def filter_and_copy_roster(employee_file: str = None, target_file: str = None) -> int:
|
||||
def filter_and_copy_roster(category: dict, employee_file: str = None, target_file: str = None) -> int:
|
||||
"""
|
||||
从员工花名册筛选数据,复制到雇主险变更记录表(仅复制,不校验)。
|
||||
从员工花名册按类别筛选数据,复制到该类别的雇主险变更记录表(仅复制,不校验)。
|
||||
|
||||
Args:
|
||||
category: 类别配置(config.CATEGORIES 中的一项),含 name/folder/include_dept/exclude_dept
|
||||
employee_file: 源表路径,默认 D:\\资料\\人资\\雇主险\\员工花名册.xlsx
|
||||
target_file: 目标表路径,默认今日的三十七度-雇主险变更记录文件
|
||||
target_file: 目标表路径,默认取该类别文件夹内最新的「*雇主险变更记录*.xlsx」
|
||||
|
||||
Returns:
|
||||
复制的数据行数
|
||||
@@ -72,14 +75,14 @@ def filter_and_copy_roster(employee_file: str = None, target_file: str = None) -
|
||||
FileNotFoundError: 源表或目标表不存在
|
||||
ValueError: 源表列数不足 或 目标表缺少指定 Sheet
|
||||
"""
|
||||
category_name = category["name"]
|
||||
employee_file = os.path.abspath(employee_file or EMPLOYEE_FILE)
|
||||
target_file = os.path.abspath(target_file or TARGET_FILE)
|
||||
target_file = os.path.abspath(target_file or find_latest_target(category["folder"]))
|
||||
|
||||
if not os.path.exists(employee_file):
|
||||
raise FileNotFoundError(f"源表不存在:{employee_file}")
|
||||
if not os.path.exists(target_file):
|
||||
raise FileNotFoundError(
|
||||
f"目标表不存在:{target_file},请先准备三十七度-雇主险变更记录模板文件")
|
||||
raise FileNotFoundError(f"目标表不存在:{target_file}")
|
||||
|
||||
# ---------- 1. 读取源表(统一规范:单 sheet,自动定位表头行,业务列 B~O) ----------
|
||||
# 先不设表头读取前几行,找到 B 列 =「所属单位」的表头行位置
|
||||
@@ -100,15 +103,22 @@ def filter_and_copy_roster(employee_file: str = None, target_file: str = None) -
|
||||
# 与宏一致:以 B 列(所属单位)最后非空行为数据边界
|
||||
data = data[data.iloc[:, 0].notna()]
|
||||
|
||||
# ---------- 2. 过滤:排除指定事业部 +「虚拟大区」 ----------
|
||||
# ---------- 2. 过滤:按类别 include/exclude 所属单位 + 统一排除「虚拟大区」 ----------
|
||||
dept = data.iloc[:, 0].astype(str).str.strip()
|
||||
region = data.iloc[:, 1].astype(str).str.strip()
|
||||
mask = ~(dept.isin(EXCLUDE_DEPT) | (region == EXCLUDE_REGION))
|
||||
include_dept = category.get("include_dept") or []
|
||||
exclude_dept = category.get("exclude_dept") or []
|
||||
mask = ~(region == EXCLUDE_REGION)
|
||||
if include_dept:
|
||||
mask &= dept.isin(include_dept)
|
||||
if exclude_dept:
|
||||
mask &= ~dept.isin(exclude_dept)
|
||||
filtered = data[mask]
|
||||
logger.info("源表共 %d 行,过滤后 %d 行(排除事业部 %s 与「%s」)",
|
||||
len(data), len(filtered), EXCLUDE_DEPT, EXCLUDE_REGION)
|
||||
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除「%s」)",
|
||||
category_name, len(data), len(filtered),
|
||||
include_dept or "全部", exclude_dept or "无", EXCLUDE_REGION)
|
||||
if len(filtered) == 0:
|
||||
logger.warning("筛选后没有数据!")
|
||||
logger.warning("类别[%s] 筛选后没有数据!", category_name)
|
||||
|
||||
# ---------- 3. 写目标表(先覆盖写入,只清空超出新数据的旧行,避免大范围逐格清空) ----------
|
||||
wb = load_workbook(target_file)
|
||||
@@ -138,7 +148,7 @@ def filter_and_copy_roster(employee_file: str = None, target_file: str = None) -
|
||||
cell(row=r, column=c).value = None
|
||||
|
||||
wb.save(target_file)
|
||||
logger.info("已写入目标表 %s 第%d行起,共 %d 行", target_file, first_data_row, len(rows))
|
||||
logger.info("类别[%s] 已写入目标表 %s 第%d行起,共 %d 行", category_name, target_file, first_data_row, len(rows))
|
||||
return len(rows)
|
||||
|
||||
|
||||
@@ -161,20 +171,26 @@ def export_roster_for_employer_insurance(download_dir: str = None) -> str:
|
||||
output_path=output_path, statuses=ROSTER_EXPORT_STATUSES)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""步骤1:就绪检查 + 导出(如需)+ 筛选复制。
|
||||
def main(category_name: str = None) -> None:
|
||||
"""步骤1:就绪检查 + 导出(如需)+ 类别筛选复制。
|
||||
|
||||
Args:
|
||||
category_name: 类别名(如「湖畔酒店」/「湖畔」),None 表示处理全部类别。
|
||||
|
||||
说明:openpyxl 写入后公式列(P~W 工种类别/投保方案/方案处理)的缓存结果会丢失,
|
||||
需手动打开目标文件刷新公式计算结果并保存,确认复制无误后再运行 schedule 步骤
|
||||
需手动打开各目标文件刷新公式计算结果并保存,确认复制无误后再运行 schedule 步骤
|
||||
(employer_insurance.py)。
|
||||
"""
|
||||
setup_logging()
|
||||
args = sys.argv[1:]
|
||||
|
||||
# 目标表是用户每日准备的表,必须已存在;若未准备则提示并终止,不下载花名册
|
||||
if not os.path.exists(TARGET_FILE):
|
||||
logger.error("目标表未准备:%s,请先准备今日的雇主险变更记录表。", TARGET_FILE)
|
||||
return
|
||||
# 命令行第一个非 -- 参数可作为类别名(如:python roster_filter.py 湖畔酒店)
|
||||
if not category_name:
|
||||
for a in args:
|
||||
if not a.startswith("--"):
|
||||
category_name = a
|
||||
break
|
||||
categories = [get_category(category_name)] if category_name else CATEGORIES
|
||||
|
||||
# 源表(员工花名册)缺失才自动导出
|
||||
if "--export-roster" in args or not os.path.exists(EMPLOYEE_FILE):
|
||||
@@ -182,11 +198,26 @@ def main() -> None:
|
||||
else:
|
||||
logger.info("源表已存在:%s,跳过导出", EMPLOYEE_FILE)
|
||||
|
||||
# 筛选复制,生成输入文件
|
||||
filter_and_copy_roster()
|
||||
# 逐类别筛选复制(目标文件=各文件夹内最新的雇主险变更记录)
|
||||
ok = 0
|
||||
for category in categories:
|
||||
try:
|
||||
target_file = find_latest_target(category["folder"])
|
||||
except FileNotFoundError as e:
|
||||
logger.error("跳过类别[%s]:%s", category["name"], e)
|
||||
continue
|
||||
logger.info("=" * 70)
|
||||
logger.info("处理类别[%s],目标文件:%s", category["name"], target_file)
|
||||
try:
|
||||
n = filter_and_copy_roster(category, target_file=target_file)
|
||||
ok += 1
|
||||
logger.info("类别[%s] 完成,写入 %d 行", category["name"], n)
|
||||
except Exception:
|
||||
logger.exception("类别[%s] 处理失败", category["name"])
|
||||
|
||||
logger.info("=" * 70)
|
||||
logger.info("筛选复制完成。请手动打开目标文件刷新公式计算结果(Ctrl+S 保存),")
|
||||
logger.info("筛选复制完成(成功 %d/%d 个类别)。请手动打开各目标文件刷新公式计算结果(Ctrl+S 保存),",
|
||||
ok, len(categories))
|
||||
logger.info("确认无误后运行:python employer_insurance.py schedule")
|
||||
logger.info("=" * 70)
|
||||
|
||||
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
import os
|
||||
import time
|
||||
import pandas as pd
|
||||
from docxtpl import DocxTemplate
|
||||
from datetime import datetime
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
|
||||
# ========================== 配置区域 ==========================
|
||||
SUCCESS_TEMPLATE = r"D:\资料\人资\参保状态告知\参保成功告知书模板.docx"
|
||||
FAILURE_TEMPLATE = r"D:\资料\人资\参保状态告知\参保异常告知书模板.docx"
|
||||
EXCEL_PATH = r"D:\资料\人资\参保状态告知\data.xlsx"
|
||||
OUTPUT_DIR = r"D:\资料\人资\参保状态告知\output"
|
||||
|
||||
COLUMN_MAPPING = {
|
||||
"姓名": "name",
|
||||
"身份证号": "id_card",
|
||||
"状态": "status",
|
||||
"保单号": "policy_number",
|
||||
"生效日期": "effective_date",
|
||||
"异常原因": "reason",
|
||||
}
|
||||
|
||||
DATE_FORMAT = "%Y年%m月%d日"
|
||||
|
||||
# ===================== WPS 转 PDF(增强版:带重试) =====================
|
||||
def wps_docx_to_pdf(docx_file: str, pdf_file: str, retries=3, delay=2):
|
||||
"""
|
||||
使用 WPS 将 docx 导出为 PDF,带重试机制
|
||||
"""
|
||||
for attempt in range(retries):
|
||||
# 如果 PDF 已存在且有效,直接成功(避免重复转换)
|
||||
if os.path.exists(pdf_file) and os.path.getsize(pdf_file) > 0:
|
||||
return True
|
||||
|
||||
pythoncom.CoInitialize()
|
||||
wps = None
|
||||
try:
|
||||
# WPS 文字的 ProgID:kwps.application
|
||||
wps = win32com.client.Dispatch("kwps.application")
|
||||
wps.Visible = False
|
||||
wps.DisplayAlerts = 0 # 不弹窗
|
||||
|
||||
doc = wps.Documents.Open(os.path.abspath(docx_file))
|
||||
# 17 = wdFormatPDF (PDF 格式)
|
||||
doc.ExportAsFixedFormat(os.path.abspath(pdf_file), 17)
|
||||
doc.Close()
|
||||
|
||||
# 检查是否真正生成
|
||||
if os.path.exists(pdf_file) and os.path.getsize(pdf_file) > 0:
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
if attempt < retries - 1:
|
||||
print(f" 🔄 WPS 转换重试 {attempt+2}/{retries}...")
|
||||
time.sleep(delay) # 等待 WPS 资源释放
|
||||
continue
|
||||
else:
|
||||
print(f" ❌ WPS 转换失败(已重试 {retries} 次): {e}")
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
if wps is not None:
|
||||
wps.Quit()
|
||||
except:
|
||||
pass
|
||||
try:
|
||||
pythoncom.CoUninitialize()
|
||||
except:
|
||||
pass
|
||||
|
||||
return False
|
||||
|
||||
# ========================== 辅助函数 ==========================
|
||||
def safe_mkdir(path):
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
|
||||
def format_value(value, var_name):
|
||||
if pd.isna(value):
|
||||
return ""
|
||||
if var_name == "effective_date":
|
||||
if isinstance(value, datetime):
|
||||
return value.strftime(DATE_FORMAT)
|
||||
try:
|
||||
return pd.to_datetime(value).strftime(DATE_FORMAT)
|
||||
except:
|
||||
return str(value)
|
||||
return str(value)
|
||||
|
||||
# ========================== 主流程 ==========================
|
||||
def main():
|
||||
# 检查文件
|
||||
if not os.path.exists(SUCCESS_TEMPLATE):
|
||||
print(f"❌ 找不到成功模板:{SUCCESS_TEMPLATE}")
|
||||
return
|
||||
if not os.path.exists(FAILURE_TEMPLATE):
|
||||
print(f"❌ 找不到异常模板:{FAILURE_TEMPLATE}")
|
||||
return
|
||||
if not os.path.exists(EXCEL_PATH):
|
||||
print(f"❌ 找不到 Excel 数据:{EXCEL_PATH}")
|
||||
return
|
||||
|
||||
safe_mkdir(OUTPUT_DIR)
|
||||
|
||||
try:
|
||||
df = pd.read_excel(EXCEL_PATH, engine="openpyxl")
|
||||
print(f"📊 共读取 {len(df)} 条参保记录")
|
||||
except Exception as e:
|
||||
print(f"❌ 读取 Excel 失败:{e}")
|
||||
return
|
||||
|
||||
success_count = 0
|
||||
fail_count = 0
|
||||
skip_count = 0
|
||||
|
||||
for idx, row in df.iterrows():
|
||||
try:
|
||||
context = {}
|
||||
for excel_col, var_name in COLUMN_MAPPING.items():
|
||||
raw_value = row.get(excel_col)
|
||||
context[var_name] = format_value(raw_value, var_name)
|
||||
|
||||
context["current_date"] = datetime.now().strftime(DATE_FORMAT)
|
||||
|
||||
status = context.get("status", "").strip()
|
||||
if status == "成功":
|
||||
template_path = SUCCESS_TEMPLATE
|
||||
prefix = "成功"
|
||||
elif status == "异常":
|
||||
template_path = FAILURE_TEMPLATE
|
||||
prefix = "异常"
|
||||
else:
|
||||
print(f"⚠️ 第 {idx+1} 行状态未知('{status}'),已跳过")
|
||||
skip_count += 1
|
||||
continue
|
||||
|
||||
# 生成 Word
|
||||
doc = DocxTemplate(template_path)
|
||||
doc.render(context)
|
||||
|
||||
name = context.get("name", f"row_{idx+1}")
|
||||
safe_name = "".join(c for c in str(name) if c.isalnum() or c in "._- ")
|
||||
base_filename = f"{safe_name}_{prefix}_{idx+1:03d}"
|
||||
|
||||
docx_path = os.path.join(OUTPUT_DIR, f"{base_filename}.docx")
|
||||
doc.save(docx_path)
|
||||
print(f"✅ Word 已生成:{os.path.basename(docx_path)}")
|
||||
|
||||
# 转换 PDF(带重试)
|
||||
pdf_path = os.path.join(OUTPUT_DIR, f"{base_filename}.pdf")
|
||||
ok = wps_docx_to_pdf(docx_path, pdf_path, retries=3, delay=2)
|
||||
if ok:
|
||||
print(f"✅ PDF 已生成:{os.path.basename(pdf_path)}")
|
||||
if status == "成功":
|
||||
success_count += 1
|
||||
else:
|
||||
fail_count += 1
|
||||
else:
|
||||
print(f"❌ PDF 生成失败:{base_filename},Word 文件已保留")
|
||||
# 仍计入统计(状态已知,但 PDF 缺失)
|
||||
if status == "成功":
|
||||
success_count += 1
|
||||
else:
|
||||
fail_count += 1
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 第 {idx+1} 行处理异常:{e}")
|
||||
continue
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print(f"🎉 处理完成!")
|
||||
print(f" ✅ 参保成功:{success_count} 份")
|
||||
print(f" ❌ 参保异常:{fail_count} 份")
|
||||
print(f" ⏭️ 跳过记录:{skip_count} 份")
|
||||
print(f" 📁 文件保存在:{OUTPUT_DIR}")
|
||||
print("=" * 50)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,230 @@
|
||||
# 影刀脚本开发指南(yingdao/)
|
||||
|
||||
本文档沉淀 `yingdao/` 目录下影刀(Yingdao)RPA 脚本的统一编写方式:共享指令模块、业务脚本写法、以及各模块之间的通信约定。后续新增/拆解影刀脚本时以此为准。
|
||||
|
||||
## 1. 体系总览
|
||||
|
||||
影刀体系采用 **「共享指令模块 + 单文件业务脚本」** 架构:
|
||||
|
||||
- 公共能力(登录、钉钉推送)抽成**独立指令模块**,放在 `share/` 目录,在影刀中注册为自定义指令,单一真源;
|
||||
- 每个业务流程是一个**单文件 Python 脚本**(如请假、加班、考勤异常),按系统分组放在 `oa/`、`hr/`、`employer_insurance/` 目录;
|
||||
- **单文件自包含是硬性原则**:业务脚本与共享指令模块各自独立运行,业务脚本**不 import 任何共享指令模块、不做 sys.path 注入、不做目录向上查找**;
|
||||
- 模块之间通过**文件(共享登录态)+ 影刀全局变量(消息/路径)** 弱耦合通信,做到「登录一次、全局复用、消息生成与发送解耦」。
|
||||
|
||||
## 2. 目录结构
|
||||
|
||||
```
|
||||
yingdao/
|
||||
├── share/ # 共享指令模块(单一真源,注册为影刀自定义指令,各自独立运行)
|
||||
│ ├── oa_login.py # 「37duOA登录」OA 登录
|
||||
│ ├── hr_login.py # 「37duHR登录」HR 登录(滑块验证码)
|
||||
│ ├── dingtalk_robot.py # 「37du钉钉群机器人推送」webhook 群推送
|
||||
│ └── dingtalk_sender.py # 「37du钉钉推送」OCR 联系人单聊 + 群消息自动路由
|
||||
├── oa/ # OA 系统业务脚本(单文件自包含)
|
||||
│ ├── leave_approval.py # 请假审批 —— 自包含范例
|
||||
│ └── overtime_approval.py # 加班审批
|
||||
├── hr/ # HR 系统业务脚本(单文件自包含)
|
||||
│ ├── attendance_abnormal.py # 考勤异常
|
||||
│ ├── attendance_abnormal_monthly.py # 考勤异常月度
|
||||
│ ├── absence_analysis.py # 缺勤分析
|
||||
│ ├── bank_card_check.py # 银行卡检查
|
||||
│ └── social_change.py # 人事变动
|
||||
├── employer_insurance/ # 雇主险类业务脚本(单文件自包含)
|
||||
│ ├── roster_export.py # 花名册导出(第一步)
|
||||
│ ├── roster_filter.py # 筛选复制(第二步)
|
||||
│ └── employer_insurance_schedule.py # 名额调度(第三步)
|
||||
└── README.md # 本文档
|
||||
```
|
||||
|
||||
> 文件命名统一去掉 `_yingdao` 后缀(如 `leave_approval.py`),子目录名即系统名。
|
||||
|
||||
## 3. 共享路径与约定(与 app 版统一,见 app/common/app_paths.py)
|
||||
|
||||
所有模块统一使用固定路径,**禁止各自散落配置**:
|
||||
|
||||
| 用途 | 路径 |
|
||||
|---|---|
|
||||
| 共享配置 | `%LOCALAPPDATA%\37duAutomation\.env`(本地开发兼容当前工作目录 `.env`) |
|
||||
| OA 登录态 | `%LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json` |
|
||||
| HR 登录态 | `%LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json` |
|
||||
|
||||
## 4. 共享指令模块(share/,各自独立运行)
|
||||
|
||||
### 4.1 oa_login.py(「37duOA登录」)
|
||||
|
||||
- 环境变量:`oa_login_url`、`oa_target_url_keyword`、`oa_login_username`、`oa_login_password`、`oa_validate_url`(可选)
|
||||
- 会话校验接口(默认):`sysNotifyTodo.do?method=sumTodoCount`,cookies 有效时返回 JSON、失效时被重定向返回 HTML
|
||||
- 入口:`main(args)`、`ensure_login(force=False)`、`_load_shared_env()`
|
||||
- 写 `oa_cookies.json`;流程全局变量 `login_state`
|
||||
- 依赖:`DrissionPage requests python-dotenv`
|
||||
|
||||
### 4.2 hr_login.py(「37duHR登录」)
|
||||
|
||||
- 环境变量:`hr_login_url`、`hr_target_url_keyword`、`hr_login_username`、`hr_login_password`、`hr_validate_url`(可选)、`hr_captcha_debug_dir`(可选)
|
||||
- 滑块验证码登录;会话校验接口(默认):`PtUsers.mc?method=getCurUserInfo`
|
||||
- 入口:`main(args)`;写 `hr_cookies.json`;流程全局变量 `login_state`
|
||||
- 依赖:`DrissionPage requests python-dotenv opencv-python numpy Pillow`
|
||||
|
||||
### 4.3 dingtalk_robot.py(「37du钉钉群机器人推送」)
|
||||
|
||||
- 入口:`main(text, title='消息通知', status='info', webhook='', secret='', server_name='')`
|
||||
- **只收纯文本**,`text` 必传;返回 `{"success": bool, "message": str}`
|
||||
- HMAC-SHA256 加签 + Base64 + URL 编码,HTTP webhook 推送 Markdown;默认 webhook/secret 内联
|
||||
- 零第三方依赖(仅标准库)
|
||||
|
||||
### 4.4 dingtalk_sender.py(「37du钉钉推送」)
|
||||
|
||||
- 入口:`main(args)`,`args` 支持两种方式:
|
||||
- **方式A(批量,推荐)**:`{"messages": [{target?, text, display_name?}, ...]}` 逐条发送,返回 `{success, message, sent, failed, results}`
|
||||
- **方式B(单条)**:`{"params": {target, text}}` 或 `{"target", "text"}`
|
||||
- 发送路由:消息**含 `target` → OCR 联系人单聊**;**不含 `target` → 视为群消息,自动改用钉钉群机器人**(调用 `dingtalk_robot`)
|
||||
- OCR 视觉方案:查找钉钉窗口 → 多策略激活前台 → Ctrl+Shift+F 搜索联系人 → OCR 定位输入框 → 粘贴 → 回车
|
||||
- 依赖:`pyautogui pywin32 pyperclip psutil Pillow numpy rapidocr-onnxruntime`
|
||||
|
||||
## 5. 模块通信(弱耦合:文件 + 全局变量)
|
||||
|
||||
### 5.1 登录态通信(文件级,登录一次全局复用)
|
||||
|
||||
```
|
||||
「37duOA登录」指令(独立运行) ──写──▶ %LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json
|
||||
▲
|
||||
│ 只读文件,不 import、不补登
|
||||
▼
|
||||
业务脚本(oa/hr/employer_insurance 下单文件)──读── 构建 SessionPage / ChromiumPage
|
||||
```
|
||||
|
||||
业务脚本侧的标准写法(**单文件自包含,不做路径查找、不 import 共享模块**):
|
||||
|
||||
1. **读共享 cookies 文件**:
|
||||
|
||||
```python
|
||||
def _load_shared_oa_cookies():
|
||||
"""读取共享 OA 登录 cookies(由「37duOA登录」指令写入)。"""
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
return json.load(f) or None
|
||||
```
|
||||
|
||||
2. **缺失/失效时直接报错提示先运行登录指令**(不在脚本内补登):
|
||||
|
||||
```python
|
||||
def _ensure_oa_cookies(force=False):
|
||||
"""确保存在有效登录态文件;缺失时提示先运行「37duOA登录」指令。"""
|
||||
if not force and _load_shared_oa_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 OA 登录态(oa_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duOA登录」指令,或本地先运行 "
|
||||
"python yingdao/share/oa_login.py")
|
||||
```
|
||||
|
||||
3. **会话有效性校验**(轻量接口,返回 JSON 视为有效、HTML 视为失效):
|
||||
|
||||
```python
|
||||
def is_session_valid(session, subject="请假"):
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
```
|
||||
|
||||
### 5.2 消息/路径通信(全局变量级,生成与发送解耦)
|
||||
|
||||
业务脚本只负责**生成消息文本**,不内联发送;通过写影刀全局变量把结果交给流程,由推送指令发送:
|
||||
|
||||
```python
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
```
|
||||
|
||||
各脚本的全局变量约定:
|
||||
|
||||
| 脚本 | 全局变量 | 值类型 | 消费方 |
|
||||
|---|---|---|---|
|
||||
| 请假审批 `oa/leave_approval` | `messages` | **纯文本**(多段空行分隔,群消息) | 「37du钉钉群机器人推送」指令 |
|
||||
| 考勤异常 `hr/attendance_abnormal` | `messages` | 字典列表 `[{target, text}, ...]` | 「37du钉钉推送」指令批量模式 |
|
||||
| 考勤异常月度 `hr/attendance_abnormal_monthly` | `attendance_check_save_path` | 文件路径 | 流程后续处理 |
|
||||
| 缺勤分析 `hr/absence_analysis` | `absence_save_path` | 文件路径 | 流程后续处理 |
|
||||
| 登录指令(oa/hr) | `login_state` | 布尔 | 流程判断是否继续 |
|
||||
|
||||
### 5.3 消息推送完整链路(请假脚本范例)
|
||||
|
||||
```
|
||||
main(push_type="group", target=None)
|
||||
│
|
||||
├─ group(默认):_set_glv("messages", 纯文本) ──▶ 流程拖「37du钉钉群机器人推送」指令
|
||||
│
|
||||
└─ person:main() 返回 [{target, text}, ...] ──▶ 流程拖「37du钉钉推送」指令走 OCR 单聊
|
||||
```
|
||||
|
||||
- **group 模式**:`messages` 全局变量是纯文本,直接交给群机器人指令即可
|
||||
- **person 模式**:需要单聊目标时,用 `main()` 的返回值(含 `target` 的字典列表)交给钉钉推送指令
|
||||
|
||||
### 5.4 按需启动浏览器(请假脚本范例)
|
||||
|
||||
所有**纯接口操作**(查待办、拉表单、会话校验)只用 `SessionPage`,不启动浏览器;仅当**确实有单据**时才启动 `ChromiumPage`(SSO 跳转解析、真实审批点击、结果弹窗):
|
||||
|
||||
```
|
||||
build_session(纯 SessionPage,不开浏览器)
|
||||
└─ 拉待办列表
|
||||
├─ 无单据 → 直接生成「暂无待审批的XX单据」消息返回(全程不闪浏览器)
|
||||
└─ 有单据 → build_browser(ChromiumPage)→ SSO 解析 / 审批 / 弹窗
|
||||
```
|
||||
|
||||
## 6. 业务脚本统一写法(单文件自包含模板)
|
||||
|
||||
推荐按以下骨架编写(参考 `oa/leave_approval.py`):
|
||||
|
||||
```python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: xxx.py
|
||||
@Description: 业务说明;单文件自包含,不 import 共享指令模块,只读 cookies 文件、只写全局变量。
|
||||
...(文件头:约定、环境变量、全局变量、依赖、入口)
|
||||
"""
|
||||
|
||||
# 0) 全局变量兜底 + logger
|
||||
# 1) _set_glv(name, value) 写全局变量(try/except 容错)
|
||||
# 2) 常量:共享路径、接口 URL、开关、默认保存目录
|
||||
# 3) 登录态:_load_shared_cookies / _ensure_cookies(缺失只报错提示,不补登)
|
||||
# 4) 会话:build_session(纯 SessionPage)/ build_browser(有单据才 ChromiumPage)
|
||||
# 5) 数据层:get_documents / get_xxx_detail(只用 SessionPage)
|
||||
# 6) 业务层:validate_doc / generate_report(纯逻辑)
|
||||
# 7) 流程编排:run_flow(subject, validate_doc, generate_report, push_type="group", target=None)
|
||||
# - build_session 拉待办 → 无单据直接生成提示消息返回
|
||||
# - 有单据才 build_browser → SSO 解析 → 校验 → 审批 → 报告
|
||||
# 8) 入口:main(push_type="group", target=None) 返回消息,并 _set_glv 写全局变量
|
||||
```
|
||||
|
||||
## 7. 影刀集成步骤(新建指令时)
|
||||
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码(如 `oa_login`)→ 添加 Python 模块;
|
||||
2. 把 `yingdao/share/` 下对应文件内容粘贴进指令的 Python 模块(或直接以该文件为模块源码);
|
||||
3. 增加流程参数(如 `force`、`params`、`text`);
|
||||
4. 保存并「发版」→ 在需要登录/推送的应用中「获取指令」并安装;
|
||||
5. 在每个应用流程开头拖入登录指令,业务脚本执行后读全局变量,再拖入推送指令。
|
||||
|
||||
## 8. 代码编写要点
|
||||
|
||||
- **单文件自包含**:业务脚本不得 import 共享指令模块、不得做 sys.path 注入或向上目录查找;共享模块各自独立运行
|
||||
- **先加载 .env 再读环境变量**:登录指令内 `_load_shared_env()` 必须在读取环境变量前调用
|
||||
- **返回 JSON 安全 dict**:指令入口统一 `{"success": bool, "message": str}`
|
||||
- **logger 兜底**:`_PrintLogger` 简易实现,避免依赖第三方日志
|
||||
- **cookies 缺失只提示不补登**:业务脚本内不调用登录模块,缺失/失效时报错并提示先运行登录指令
|
||||
- **消息生成与发送解耦**:业务脚本只产出文本/列表写全局变量,发送一律由推送指令完成
|
||||
|
||||
## 9. 依赖清单
|
||||
|
||||
| 用途 | pip 包 |
|
||||
|---|---|
|
||||
| OA/HR 登录、浏览器自动化 | `DrissionPage requests python-dotenv` |
|
||||
| HR 滑块验证码 | 另加 `opencv-python numpy Pillow` |
|
||||
| OCR 钉钉单聊推送 | `pyautogui pywin32 pyperclip psutil Pillow numpy rapidocr-onnxruntime` |
|
||||
| 钉钉群机器人推送 | 无(仅标准库) |
|
||||
+4
-4
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: employer_insurance_schedule_yingdao.py
|
||||
@FileName: employer_insurance_schedule.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险名额调度系统(影刀版,单文件自包含)「步骤2:调度」——读取已刷新公式的目标表,
|
||||
@@ -9,7 +9,7 @@
|
||||
@Version: 1.0.0
|
||||
|
||||
场景定位(雇主险流程第二步:调度):
|
||||
- 前置步骤:roster_filter_yingdao.py(筛选复制)后,需手动打开目标文件刷新公式计算结果
|
||||
- 前置步骤:roster_filter.py(筛选复制)后,需手动打开目标文件刷新公式计算结果
|
||||
(Ctrl+S 保存),确认无误后再运行本步骤。
|
||||
1. 读取花名册业务数据(增加投保/要替换)
|
||||
2. 结合在参名单(空闲名额池、当前参保状态)
|
||||
@@ -713,14 +713,14 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
def main():
|
||||
"""步骤2:调度(读取已刷新公式的目标文件,输出结果)。
|
||||
|
||||
前置:先运行 roster_filter_yingdao.py(筛选复制),并手动打开目标文件
|
||||
前置:先运行 roster_filter.py(筛选复制),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
"""
|
||||
logger.info("目标文件:%s", TARGET_FILE)
|
||||
|
||||
# 检查文件是否存在
|
||||
if not os.path.exists(TARGET_FILE):
|
||||
logger.error("目标表不存在:%s,请先运行 roster_filter_yingdao.py 步骤生成。", TARGET_FILE)
|
||||
logger.error("目标表不存在:%s,请先运行 roster_filter.py 步骤生成。", TARGET_FILE)
|
||||
return
|
||||
|
||||
# 检查必需Sheet
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: roster_export_yingdao.py
|
||||
@FileName: roster_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险花名册导出(影刀版,单文件自包含)——HR 登录(滑块验证码)
|
||||
+10
-10
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: roster_filter_yingdao.py
|
||||
@FileName: roster_filter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险流程「第二步:筛选复制」(影刀版,单文件自包含)——校验源表(员工花名册)
|
||||
@@ -9,8 +9,8 @@
|
||||
@Version: 1.0.0
|
||||
|
||||
场景定位(雇主险流程第二步:筛选复制):
|
||||
- 前置步骤:roster_export_yingdao.py 导出花名册(源表)。本文件先校验源表/目标表存在性,
|
||||
源表缺失时(默认)自动调用同目录 roster_export_yingdao 导出。
|
||||
- 前置步骤:roster_export.py 导出花名册(源表)。本文件先校验源表/目标表存在性,
|
||||
源表缺失时(默认)自动调用同目录 roster_export 导出。
|
||||
- 本步骤:校验文件存在性 -> 过滤(排除指定事业部 +「虚拟大区」)-> 复制到目标表 B~O 列。
|
||||
|
||||
设计说明(与 yingdao 下其它单文件版一致):
|
||||
@@ -18,7 +18,7 @@
|
||||
- 源表读取(pandas):自动定位表头行(B 列=「所属单位」),业务列 B~O 共14列。
|
||||
- 目标表写入(openpyxl):Sheet「花名册导出-雇主险使用基础信息」表头第4行、数据第5行起,
|
||||
B~O 覆盖写入、清空超出新数据的旧行(与 app 版逻辑一致)。
|
||||
- 依赖同目录 roster_export_yingdao.py(仅源表缺失且需自动导出时懒加载引用)。
|
||||
- 依赖同目录 roster_export.py(仅源表缺失且需自动导出时懒加载引用)。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install pandas openpyxl
|
||||
@@ -79,12 +79,12 @@ SHEET_BIZ = "花名册导出-雇主险使用基础信息"
|
||||
EXCLUDE_DEPT = ["金色湖畔事业部", "秒创传媒事业部", "水庄大鹅事业部"]
|
||||
EXCLUDE_REGION = "虚拟大区"
|
||||
|
||||
# 源表/目标表格式规范(roster_export_yingdao 输出统一格式)
|
||||
# 源表/目标表格式规范(roster_export 输出统一格式)
|
||||
SOURCE_HEADER_MARK = "所属单位" # 源表表头定位标记(B列)
|
||||
TARGET_HEADER_ROW = 4 # 目标表表头在第4行(数据第5行起)
|
||||
DATA_COLUMNS = 14 # B~O 共14列(所属单位..证件号)
|
||||
|
||||
# 源表缺失时是否自动调用 roster_export_yingdao 导出(默认 true)
|
||||
# 源表缺失时是否自动调用 roster_export 导出(默认 true)
|
||||
AUTO_EXPORT_ON_MISSING = os.getenv("roster_filter_export_on_missing", "true").lower() == "true"
|
||||
|
||||
|
||||
@@ -195,14 +195,14 @@ def filter_and_copy_roster(employee_file: str = None, target_file: str = None) -
|
||||
|
||||
|
||||
def _export_roster():
|
||||
"""源表缺失时,懒加载同目录 roster_export_yingdao 导出花名册到源表路径。"""
|
||||
"""源表缺失时,懒加载同目录 roster_export 导出花名册到源表路径。"""
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
try:
|
||||
from roster_export_yingdao import export_roster
|
||||
from roster_export import export_roster
|
||||
except ImportError as e:
|
||||
raise RuntimeError(
|
||||
f"源表缺失且无法加载导出模块 roster_export_yingdao({e}),"
|
||||
f"请先运行 roster_export_yingdao.py 导出花名册到 {EMPLOYEE_FILE}") from e
|
||||
f"源表缺失且无法加载导出模块 roster_export({e}),"
|
||||
f"请先运行 roster_export.py 导出花名册到 {EMPLOYEE_FILE}") from e
|
||||
output = export_roster(output_path=EMPLOYEE_FILE)
|
||||
logger.info("花名册导出完成:%s", output)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,34 +1,29 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: attendance_abnormal_yingdao.py
|
||||
@FileName: attendance_abnormal.py
|
||||
@Description: 周考勤异常处理(影刀单文件版)- 独立自 app/service/hrbp/ehr/attendance/attendance_abnormal.py,
|
||||
业务逻辑完全一致:HR 登录态(共享登录)→ 分页拉取当月未调整考勤异常 → 导出 Excel 底稿
|
||||
→ 分级分类(轻微直接处理 / 其余钉钉核实)→ 按「姓名-工号」合并推送当事人
|
||||
→ 生成处理汇总报表 → 推送给 人资专用号 留痕。
|
||||
@Version: 1.1.0
|
||||
|
||||
登录(共享登录,不内联滑块算法):
|
||||
登录(共享登录态,本脚本为单文件自包含):
|
||||
- 登录态统一由「37duHR登录」影刀自定义指令写入共享 cookies:
|
||||
%LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json
|
||||
- 本脚本直接复用该 cookies;缺失/失效时,若当前目录存在 yingdao/instructions/hr_login.py
|
||||
则自动调用共享登录模块补登(便于本地 python 独立运行调试);
|
||||
影刀定时任务中请在流程开头先拖入「37duHR登录」指令。
|
||||
- 本脚本仅读取该 cookies 文件,不 import 任何共享模块;缺失/失效时
|
||||
报错提示先运行登录指令(影刀流程开头请先拖入「37duHR登录」指令)。
|
||||
|
||||
钉钉推送(共享指令,不内联 OCR 视觉发送代码):
|
||||
- 实际发送统一由「37du钉钉推送」影刀自定义指令承担(单一真源:
|
||||
yingdao/instructions/dingtalk_sender.py),本脚本通过 import 调用其
|
||||
main({"messages": [...]}) 批量发送(messages 为字典列表,逐条发送并汇总结果);
|
||||
- 影刀流程中也可直接拖入「37du钉钉推送」指令,把 messages(字典列表)
|
||||
或 target/text 传入即可完成发送,等价于本脚本内部调用;
|
||||
- 本脚本运行后会同步把待推送的 messages(字典列表)写入影刀全局变量
|
||||
glv['messages'](无数据时置为空列表),供流程后续步骤读取复用;
|
||||
- 钉钉 OCR 视觉发送所需依赖(pyautogui/pywin32/pyperclip/psutil/Pillow/numpy/
|
||||
rapidocr-onnxruntime)由共享指令内自校验,本脚本不再重复安装。
|
||||
钉钉推送(消息生成与发送解耦,本脚本不内联发送):
|
||||
- 本脚本不内联任何发送逻辑,也不 import 共享推送模块;
|
||||
- 运行后会同步把待推送的 messages(字典列表)写入影刀全局变量
|
||||
glv['messages'](无数据时置为空列表),由流程拖「37du钉钉推送」指令
|
||||
完成发送(含 target 走 OCR 单聊,不含 target 走群机器人);
|
||||
- 处理汇总报表文本写入全局变量 glv['report'],由流程推送给 人资专用号。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests python-dotenv pandas openpyxl
|
||||
|
||||
环境变量(.env 或系统变量,固定路径共享 .env 见 yingdao/instructions/hr_login.py):
|
||||
环境变量(.env 或系统变量,固定路径共享 .env 见 yingdao/share/hr_login.py):
|
||||
dingtalk_push_enabled=true|false(默认 false,是否启用钉钉推送,总开关)
|
||||
dingtalk_notify_target=人资专用号钉钉联系人姓名(处理汇总报表推送对象,如 夏一平)
|
||||
attendance_save_dir=(可选)Excel 导出目录,默认 D:\\资料\\人资\\考勤异常
|
||||
@@ -137,51 +132,9 @@ DINGTALK_PUSH_ENABLED = "true"
|
||||
DINGTALK_NOTIFY_TARGET = "夏一平"
|
||||
|
||||
|
||||
# ==================== 共享登录集成 ====================
|
||||
# 脚本位于 yingdao/ 下,共享登录模块位于 yingdao/instructions/ 下,可直接 import(本地独立运行);
|
||||
# 影刀部署时若未携带该目录则退化为「仅复用共享 cookies」。
|
||||
_INSTRUCTION_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "instructions")
|
||||
if _INSTRUCTION_DIR not in sys.path:
|
||||
sys.path.insert(0, _INSTRUCTION_DIR)
|
||||
|
||||
try:
|
||||
import hr_login as _hr_login_shared # noqa: E402
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
from dotenv import load_dotenv as _reload_dotenv
|
||||
_reload_dotenv(SHARED_ENV_FILE)
|
||||
_hr_login_shared._load_shared_env()
|
||||
except ImportError:
|
||||
_hr_login_shared = None
|
||||
|
||||
try:
|
||||
import dingtalk_sender as _dt_sender_shared # noqa: E402
|
||||
except ImportError:
|
||||
_dt_sender_shared = None
|
||||
|
||||
|
||||
def _send_dingtalk_text(target, text):
|
||||
"""钉钉 OCR 视觉推送(共享指令):调用 dingtalk_sender.send_dingtalk_text(单条)。
|
||||
本地运行时要求 yingdao/instructions/dingtalk_sender.py 存在;影刀流程中
|
||||
也可直接拖入「37du钉钉推送」指令发送,二者等价。
|
||||
"""
|
||||
if _dt_sender_shared is not None:
|
||||
return _dt_sender_shared.send_dingtalk_text(target, text)
|
||||
raise RuntimeError(
|
||||
"未加载共享钉钉推送模块(yingdao/instructions/dingtalk_sender.py)。\n"
|
||||
"请在影刀流程中拖入「37du钉钉推送」指令发送,或本地放置该共享模块文件。")
|
||||
|
||||
|
||||
def _send_dingtalk_messages(messages):
|
||||
"""批量钉钉推送(共享指令):调用 dingtalk_sender.main({"messages": [...]})。
|
||||
messages 为字典列表,逐条发送并汇总;返回 (成功数, 失败数),单条失败不中断整体。
|
||||
"""
|
||||
if _dt_sender_shared is None:
|
||||
raise RuntimeError(
|
||||
"未加载共享钉钉推送模块(yingdao/instructions/dingtalk_sender.py)。\n"
|
||||
"请在影刀流程中拖入「37du钉钉推送」指令发送,或本地放置该共享模块文件。")
|
||||
result = _dt_sender_shared.main({"messages": messages})
|
||||
return result.get("sent", 0), result.get("failed", 0)
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 yingdao/share/hr_login.py),
|
||||
# 本脚本为单文件自包含:仅读取共享 cookies 文件,不 import 任何共享模块。
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
@@ -206,18 +159,12 @@ def _load_shared_hr_cookies():
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
"""确保存在 HR 登录态文件;缺失时优先调用共享登录模块补登。"""
|
||||
"""确保存在 HR 登录态文件(由「37duHR登录」指令写入);缺失时提示先运行登录指令。"""
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
if _hr_login_shared is not None:
|
||||
logger.info("无 HR cookies,调用共享 HR 登录模块自动登录")
|
||||
result = _hr_login_shared.ensure_login(force=False)
|
||||
if result.get("success"):
|
||||
return True
|
||||
raise RuntimeError(f"HR 自动登录失败:{result.get('message')}")
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)且无法加载共享登录模块。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python yingdao/instructions/hr_login.py")
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python yingdao/share/hr_login.py")
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
@@ -404,10 +351,11 @@ def export_excel(data, save_dir, month_str):
|
||||
|
||||
# ==================== 钉钉推送(总开关控制) ====================
|
||||
def push_abnormal(items):
|
||||
"""按「工号-姓名」分组,合并为 messages 字典列表后一次性批量推送给当事人。
|
||||
"""按「工号-姓名」分组,合并为 messages 字典列表,写入影刀全局变量 messages,
|
||||
由流程拖「37du钉钉推送」指令发送(本脚本不内联发送,保持单文件自包含)。
|
||||
推送目标(target)使用工号作为钉钉搜索关键字,避免同名人员误发;
|
||||
会话标题校验名(display_name)传姓名(钉钉标题显示姓名而非工号)。
|
||||
返回 (成功数, 失败数);单条失败不中断整体(共享指令内部逐条 try/except 汇总)。
|
||||
返回 (待推送条数, 失败数=0)。
|
||||
"""
|
||||
groups = {}
|
||||
for it in items:
|
||||
@@ -422,29 +370,22 @@ def push_abnormal(items):
|
||||
{"target": _code or _name, "display_name": _name, "text": build_notify_text(group)}
|
||||
for (_code, _name), group in groups.items()
|
||||
]
|
||||
# 同步写入影刀全局变量,供流程后续步骤/「37du钉钉推送」指令读取(无数据也置空,避免 NameError)
|
||||
# 写入影刀全局变量,供流程「37du钉钉推送」指令读取(无数据也置空,避免 NameError)
|
||||
_set_glv('messages', messages)
|
||||
if not messages:
|
||||
return 0, 0
|
||||
|
||||
push_count, fail_count = _send_dingtalk_messages(messages)
|
||||
logger.info("当事人批量推送完成:成功 %d 条,失败 %d 条(共 %d 人)",
|
||||
push_count, fail_count, len(messages))
|
||||
return push_count, fail_count
|
||||
logger.info("当事人消息已生成并写入全局变量 messages:共 %d 条(由流程推送)", len(messages))
|
||||
return len(messages), 0
|
||||
|
||||
|
||||
def push_report(report):
|
||||
"""推送处理汇总报表到 人资专用号(未配置则跳过,失败不影响主流程)。"""
|
||||
"""生成处理汇总报表文本并写入全局变量 report(未配置目标则跳过)。
|
||||
由流程拖「37du钉钉推送」指令推送给 人资专用号(本脚本不内联发送)。
|
||||
"""
|
||||
if not DINGTALK_NOTIFY_TARGET:
|
||||
logger.warning("未配置 dingtalk_notify_target,跳过汇总报表推送")
|
||||
return False
|
||||
try:
|
||||
_send_dingtalk_text(DINGTALK_NOTIFY_TARGET, report)
|
||||
logger.info("汇总报表已推送至人资专用号:%s", DINGTALK_NOTIFY_TARGET)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("汇总报表推送失败:%s", e)
|
||||
return False
|
||||
_set_glv('report', report)
|
||||
logger.info("汇总报表已生成并写入全局变量 report(目标:%s,由流程推送)", DINGTALK_NOTIFY_TARGET)
|
||||
return True
|
||||
|
||||
|
||||
# ==================== 处理汇总报表(推送前生成最终结果) ====================
|
||||
@@ -0,0 +1,996 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: attendance_abnormal_monthly.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-18
|
||||
@Description: EHR 系统月考勤异常处理(影刀版,单文件自包含)——复刻 app 版
|
||||
abnormal_check.py 业务逻辑:对上月考勤异常做三重复核(结合 考勤异常/请假/加班/
|
||||
打卡/排班 五类接口),输出多 Sheet Excel 报告。独立于周考勤异常处理流程。
|
||||
|
||||
检查1:已确认异常(is_adjusted=2)的日期,是否存在请假流程?
|
||||
—— 可能存在「提前确认后请假」导致仍为考勤异常的情况;
|
||||
检查2:休息日加班(类型3)且加班天数为 0.5 天,当日打卡是否按考勤班段正常打卡(无漏打卡)?
|
||||
检查3:员工整日请假(leave_days>=1)当日,仍存在其他考勤异常(未调整/已确认)。
|
||||
|
||||
场景定位(月度定时任务,每月 1 号 14:00-17:00 由影刀调度触发,传上月月份参数):
|
||||
- 登录:登录态统一由「37duHR登录」指令写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json;
|
||||
本脚本为单文件自包含,仅读取该 cookies 文件,不 import 任何共享模块。
|
||||
- 本模块不涉及花名册/浏览器页面操作,纯接口调用 + 数据校验 + 导出报告。
|
||||
|
||||
设计说明(与 yingdao 下其它单文件版一致):
|
||||
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
|
||||
- 内联 HR 接口(getCurUserInfo / 考勤异常 / 请假 / 加班 / 打卡 / 排班),不依赖 app 包。
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests python-dotenv pandas openpyxl
|
||||
|
||||
环境变量(.env 或系统变量,固定路径共享 .env 见 yingdao/share/hr_login.py):
|
||||
attendance_check_save_dir=(可选)报告导出目录,默认 D:\\资料\\人资\\考勤异常
|
||||
attendance_check_month=(可选)查询月份 "YYYY-MM",默认当月
|
||||
|
||||
运行:
|
||||
- 影刀「调用模块」:main({"save_dir": ..., "month": "2026-08"})
|
||||
- 直接运行:python attendance_abnormal_monthly.py [save_dir] [month]
|
||||
例:python attendance_abnormal_monthly.py "D:\\资料\\人资\\考勤异常" "2026-08"
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
# 任一依赖缺失会立即报错退出,避免运行到中途才发现缺库
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests python-dotenv pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# ==================== 日志(print) ====================
|
||||
class _PrintLogger:
|
||||
"""影刀版无 logging 依赖,直接用 print 输出,行为与项目 logger 对齐。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
# ==================== 影刀全局变量(glv) ====================
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ==================== 共享路径 & 常量配置(与 app 版统一) ====================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
# HR 登录态:由「37duHR登录」共享指令(yingdao/share/hr_login.py)写入
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- HR 系统 ----------
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
KQ_LIST_URL = f"{HR_BASE_URL}/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ---------- 输出配置(与 app 版一致) ----------
|
||||
# 默认保存目录(与周考勤异常导出目录保持一致)
|
||||
SAVE_DIR = os.getenv("attendance_check_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 考勤异常调整状态过滤:0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有状态
|
||||
IS_ADJUSTED_CONFIRMED = "2" # 已确认异常(检查1)
|
||||
IS_ADJUSTED_OPEN = "0" # 未调整异常(检查3并集之一)
|
||||
|
||||
# 加班类型:空=全部、1=延时加班、2=法定假日加班、3=休息日加班
|
||||
WORK_OVERTIME_TYPE_REST = "3"
|
||||
|
||||
# 休息日半天加班判定阈值(ot_days / sys_ot_days / plan_ot_days ≈ 0.5)
|
||||
HALF_DAY = 0.5
|
||||
EPS = 1e-6
|
||||
|
||||
# 打卡与班段边界匹配容差(分钟):上班打卡在班段开始前后、下班打卡在班段结束前后
|
||||
PUNCH_TOLERANCE_MIN = 60
|
||||
|
||||
# 假期类型编码 → 名称(与 app 版 common/config.VACATION_TYPE_MAP 一致)
|
||||
VACATION_TYPE_MAP = {
|
||||
"04": "病假",
|
||||
"05": "产假",
|
||||
"09": "事假",
|
||||
"11": "调休假",
|
||||
"15": "普通事假",
|
||||
"17": "特殊事假",
|
||||
"18": "小时特假",
|
||||
"19": "普通事假(晚/高峰)",
|
||||
"20": "普通事假(早/中)",
|
||||
"22": "半天休(仅限人资专用)",
|
||||
"23": "特别福利假",
|
||||
"24": "年度福利假",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 yingdao/share/hr_login.py),
|
||||
# 本脚本为单文件自包含:仅读取共享 cookies 文件,不 import 任何共享模块。
|
||||
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def _load_shared_hr_cookies():
|
||||
"""读取共享 HR cookies 文件(由「37duHR登录」指令写入)。"""
|
||||
if os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
return None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
"""确保存在 HR 登录态文件;缺失时提示先运行「37duHR登录」指令。"""
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 "
|
||||
"python yingdao/share/hr_login.py")
|
||||
|
||||
|
||||
# ==================== HR 接口(内联,与 app 版 hr_api 一致) ====================
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;失效抛 HRSessionExpiredError。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
"""用共享 hr_cookies.json 构建 requests.Session(过滤 hr.37du.co 域)。"""
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
"""调用 getCurUserInfo,返回 userId / rootId(treecode)。"""
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def _relogin_get_user_info():
|
||||
"""登录态失效后:补登 → 重建会话 → 重新获取 userId/rootId。"""
|
||||
_ensure_hr_cookies()
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
return session, info.get("userId", ""), info.get("rootId", "")
|
||||
|
||||
|
||||
def fetch_attendance_abnormal_page(session, user_id, treecode, begin_date, end_date,
|
||||
page_no=1, page_size=PAGE_MAX_SIZE, is_adjusted=""):
|
||||
"""请求单页考勤异常数据。"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"sqlId": "kq_count_abnormal_Select",
|
||||
"redapiId": "rf_p_kq_count_abnormal_Select",
|
||||
"treeCodeList": "",
|
||||
"abnormal_type": "",
|
||||
"base_code": "",
|
||||
"join_date": "",
|
||||
"join_date_end": end_date,
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"period_order": "",
|
||||
"identity_test": "",
|
||||
"identity": "",
|
||||
"sex": "",
|
||||
"age": "",
|
||||
"age_end": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"operator_username": "",
|
||||
"operator_userid": "",
|
||||
"is_adjusted": is_adjusted,
|
||||
"begin_date": begin_date,
|
||||
"end_date": end_date,
|
||||
"STAFF_NAME": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "work_day",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", KQ_LIST_URL, params, "考勤异常")
|
||||
|
||||
|
||||
def fetch_all_attendance_abnormal(session, user_id, treecode, begin_date, end_date,
|
||||
is_adjusted=""):
|
||||
"""分页拉取全部考勤异常;中途登录态失效自动补登后续抓。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date,
|
||||
page_no, PAGE_MAX_SIZE, is_adjusted)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤异常 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, treecode = _relogin_get_user_info()
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date,
|
||||
page_no, PAGE_MAX_SIZE, is_adjusted)
|
||||
if data.get("state") != "1":
|
||||
logger.error("考勤异常第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤异常无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("考勤异常已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_leave_page(session, user_id, base_code, start_time, end_time,
|
||||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页请假记录数据。"""
|
||||
params = {
|
||||
"STRU_TREE_CODE": treecode,
|
||||
"user_id": user_id,
|
||||
"begin_date": "",
|
||||
"end_date": "",
|
||||
"sqlId": "select_kqLeave_record",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"post_no": "",
|
||||
"source": "",
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"staffNames": "",
|
||||
"post_type": "1",
|
||||
"processing_reason": "",
|
||||
"processing_date": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"orgAlias": "",
|
||||
"dept_ids": "",
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "operat_time",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", KQ_LIST_URL, params, "请假查询")
|
||||
|
||||
|
||||
def fetch_all_leave(session, user_id, base_code, start_time, end_time, treecode="cq37du"):
|
||||
"""分页抓取指定工号、日期范围内的全部请假记录(空工号=全量)。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_leave_page(session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("请假查询 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, _ = _relogin_get_user_info()
|
||||
data = fetch_leave_page(session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("请假查询第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("请假查询无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("请假查询已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_overtime_page(session, user_id, base_code, start_time, end_time,
|
||||
work_overtime_type="", treecode="cq37du",
|
||||
page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页加班记录数据。"""
|
||||
params = {
|
||||
"STRU_TREE_CODE": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_overtime_detail_select",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"BPM_STATUS": "",
|
||||
"post_no": "",
|
||||
"postName": "",
|
||||
"source": "",
|
||||
"IS_SUBSIDY": "",
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"staffNames": "",
|
||||
"post_type": "1",
|
||||
"processing_reason": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"WORK_OVERTIME_TYPE": work_overtime_type,
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "OPERATE_TIME",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", KQ_LIST_URL, params, "加班查询")
|
||||
|
||||
|
||||
def fetch_all_overtime(session, user_id, base_code, start_time, end_time,
|
||||
work_overtime_type="", treecode="cq37du"):
|
||||
"""分页抓取指定工号、日期范围内的全部加班记录(空工号=全量)。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_overtime_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
work_overtime_type, treecode, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("加班查询 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, _ = _relogin_get_user_info()
|
||||
data = fetch_overtime_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
work_overtime_type, treecode, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("加班查询第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("加班查询无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("加班查询已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_kq_data_page(session, user_id, base_code, start_time, end_time,
|
||||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页打卡记录数据。"""
|
||||
params = {
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_data_query",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"kqStaffIds": "",
|
||||
"staff_id": "",
|
||||
"staff_name": "",
|
||||
"orgAlias": "",
|
||||
"dept_ids": "",
|
||||
"kq_type": "",
|
||||
"post_type": "",
|
||||
"person_status": "",
|
||||
"dkstatus": "",
|
||||
"addr_status": " ",
|
||||
"struTreeCode": treecode,
|
||||
"belongUnitStruId": "",
|
||||
"work_day_begin": start_time,
|
||||
"work_day_end": end_time,
|
||||
"base_code": base_code,
|
||||
"STAFF_NAME": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", KQ_LIST_URL, params, "打卡查询")
|
||||
|
||||
|
||||
def fetch_all_kq_data(session, user_id, base_code, start_time, end_time, treecode="cq37du"):
|
||||
"""分页抓取指定工号、日期范围内的全部打卡记录。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_kq_data_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("打卡查询 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, _ = _relogin_get_user_info()
|
||||
data = fetch_kq_data_page(
|
||||
session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("打卡查询第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("打卡查询无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("打卡查询已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def fetch_shift_page(session, user_id, base_code, begin_date, end_date,
|
||||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页排班数据。"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_count_SelectBanci",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"staff_ids": "",
|
||||
"person_status": "1,4",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"post_level": "",
|
||||
"identity": "",
|
||||
"showType": "1",
|
||||
"dateType": "1",
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"bc_date": begin_date,
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SHIFT_URL, params, "排班")
|
||||
|
||||
|
||||
def fetch_all_shift(session, user_id, base_code, begin_date, end_date, treecode="cq37du"):
|
||||
"""分页抓取指定工号、日期范围内的全部排班数据。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_shift_page(
|
||||
session, user_id, base_code, begin_date, end_date,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("排班 HR 登录态过期,自动补登后续抓")
|
||||
session, user_id, _ = _relogin_get_user_info()
|
||||
data = fetch_shift_page(
|
||||
session, user_id, base_code, begin_date, end_date,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("排班第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("排班无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("排班已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 工具函数(与 app 版 abnormal_check 一致) ====================
|
||||
def current_month_range(today=None):
|
||||
"""返回当月的查询日期范围 (开始日期, 结束日期)。开始=当月1日,结束=今天。"""
|
||||
today = today or date.today()
|
||||
begin = today.replace(day=1)
|
||||
return begin.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _get(rec, *keys, default=""):
|
||||
"""从记录中取第一个存在的键的值(兼容字段大小写差异)。"""
|
||||
for k in keys:
|
||||
if rec.get(k) is not None and rec.get(k) != "":
|
||||
return rec[k]
|
||||
return default
|
||||
|
||||
|
||||
def _to_date_str(value):
|
||||
"""将接口返回的日期/时间值归一化为 'YYYY-MM-DD'(取前10位)。"""
|
||||
if value is None:
|
||||
return ""
|
||||
s = str(value).strip()
|
||||
return s[:10] if len(s) >= 10 else s
|
||||
|
||||
|
||||
def _float(value, default=0.0):
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _is_half_day_ot(rec):
|
||||
"""判断加班记录是否为休息日半天(0.5 天)。依次取 ot_days / sys_ot_days / plan_ot_days。"""
|
||||
for key in ("ot_days", "sys_ot_days", "plan_ot_days"):
|
||||
val = rec.get(key)
|
||||
if val is not None and val != "":
|
||||
if abs(_float(val) - HALF_DAY) <= EPS:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _leave_type_name(rec):
|
||||
"""从请假记录中提取假期类型名称(兼容编码与名称两种输入)。"""
|
||||
raw = _get(rec, "leave_type", "vacation_type", "sub_type", "LEAVE_TYPE")
|
||||
raw = str(raw).strip()
|
||||
if raw in VACATION_TYPE_MAP:
|
||||
return VACATION_TYPE_MAP[raw]
|
||||
return raw
|
||||
|
||||
|
||||
def _staff_name(rec):
|
||||
"""兼容取员工姓名字段(不同接口命名不同)。"""
|
||||
return str(_get(rec, "STAFF_NAME", "staff_name", "staffName", default=""))
|
||||
|
||||
|
||||
def _punch_analysis(records):
|
||||
"""对某日打卡流水做统计(打卡记录无法可靠区分上下班,按最早=上班、最晚=下班)。"""
|
||||
times = []
|
||||
for rec in records:
|
||||
t = _get(rec, "kq_time", "kqTime", "punch_time")
|
||||
if t:
|
||||
times.append(str(t))
|
||||
times.sort()
|
||||
if not times:
|
||||
return {"count": 0, "first": "", "last": ""}
|
||||
return {"count": len(times), "first": times[0], "last": times[-1]}
|
||||
|
||||
|
||||
def _to_minutes(value):
|
||||
"""将 "HH:MM[:SS]" 时间串转为当日分钟数;解析失败返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
s = str(value).strip()
|
||||
if not s:
|
||||
return None
|
||||
m = re.search(r"(\d{1,2}):(\d{2})(?::(\d{2}))?$", s)
|
||||
if not m:
|
||||
return None
|
||||
return int(m.group(1)) * 60 + int(m.group(2))
|
||||
|
||||
|
||||
def _parse_shift_time(bc_time):
|
||||
"""解析班段时间 "09:00 ~ 18:00" -> (开始分钟, 结束分钟);无班段返回 (None, None)。"""
|
||||
if not bc_time:
|
||||
return None, None
|
||||
m = re.search(r"(\d{1,2}):(\d{2})\s*~\s*(\d{1,2}):(\d{2})", str(bc_time))
|
||||
if not m:
|
||||
return None, None
|
||||
start = int(m.group(1)) * 60 + int(m.group(2))
|
||||
end = int(m.group(3)) * 60 + int(m.group(4))
|
||||
return start, end
|
||||
|
||||
|
||||
def _extract_day_shift(shift_rows, date_str):
|
||||
"""从某员工排班记录中提取指定日期的班段信息(动态列 key 为 "YYYY-MM-DD_bc_name/bc_time/paiban_type")。"""
|
||||
info = {"bc_name": "", "bc_time": "", "paiban_type": ""}
|
||||
for rec in shift_rows:
|
||||
name = _get(rec, f"{date_str}_bc_name", default="")
|
||||
time_ = _get(rec, f"{date_str}_bc_time", default="")
|
||||
paiban = _get(rec, f"{date_str}_paiban_type", default="")
|
||||
if name or time_ or paiban:
|
||||
info = {"bc_name": str(name), "bc_time": str(time_), "paiban_type": str(paiban)}
|
||||
break
|
||||
return info
|
||||
|
||||
|
||||
def _judge_punch_by_shift(p, shift_info):
|
||||
"""结合班段时间判断当日打卡是否正常(容差 PUNCH_TOLERANCE_MIN 分钟)。"""
|
||||
start_min, end_min = _parse_shift_time(shift_info.get("bc_time", ""))
|
||||
count = p["count"]
|
||||
tol = PUNCH_TOLERANCE_MIN
|
||||
|
||||
# 无班段(休息日排班):按打卡次数判断
|
||||
if start_min is None or end_min is None:
|
||||
if count >= 2:
|
||||
return "正常(有上班+下班打卡)"
|
||||
if count == 1:
|
||||
return "漏打卡(当日仅 1 次打卡,缺一次)"
|
||||
return "漏打卡(当日无打卡记录)"
|
||||
|
||||
# 有班段:最早打卡覆盖班段开始、最晚打卡覆盖班段结束
|
||||
first_min = _to_minutes(p["first"])
|
||||
last_min = _to_minutes(p["last"])
|
||||
first_ok = first_min is not None and first_min <= start_min + tol
|
||||
last_ok = last_min is not None and last_min >= end_min - tol
|
||||
if count >= 2 and first_ok and last_ok:
|
||||
return "正常(按班段上班/下班打卡齐全)"
|
||||
if count == 0:
|
||||
return "漏打卡(当日无打卡记录)"
|
||||
if count == 1:
|
||||
return "漏打卡(当日仅 1 次打卡,缺一次)"
|
||||
return "漏打卡(打卡未按班段覆盖上下班)"
|
||||
|
||||
|
||||
# ==================== 会话校验 & 数据获取(与 app 版一致) ====================
|
||||
def _validate_session(session):
|
||||
"""调用 getCurUserInfo 校验 cookies 有效性,并返回 (session, user_id, treecode)。"""
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("cookies 已失效,正在重新登录")
|
||||
session, user_id, treecode = _relogin_get_user_info()
|
||||
return session, user_id, treecode
|
||||
user_id = info.get("userId", "")
|
||||
treecode = info.get("rootId", "")
|
||||
if not user_id or not treecode:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId/rootId:{info}")
|
||||
logger.info("cookies 校验通过,user_id=%s,treecode=%s", user_id, treecode)
|
||||
return session, user_id, treecode
|
||||
|
||||
|
||||
def _fetch_all_data(session, user_id, treecode, begin, end):
|
||||
"""一次性拉取三项检查所需的基础数据(考勤异常 / 请假 / 休息日加班)。"""
|
||||
logger.info("===== 月考勤异常三查,日期范围:%s ~ %s =====", begin, end)
|
||||
|
||||
abnormal_confirmed = fetch_all_attendance_abnormal(
|
||||
session, user_id, treecode, begin, end, IS_ADJUSTED_CONFIRMED
|
||||
)
|
||||
abnormal_open = fetch_all_attendance_abnormal(
|
||||
session, user_id, treecode, begin, end, IS_ADJUSTED_OPEN
|
||||
)
|
||||
logger.info("已确认异常 %d 条,未调整异常 %d 条", len(abnormal_confirmed), len(abnormal_open))
|
||||
|
||||
# 请假:空工号 = 查询全部员工(返回记录自带 base_code)
|
||||
leaves = fetch_all_leave(session, user_id, "", begin, end)
|
||||
logger.info("请假记录(全部员工)%d 条", len(leaves))
|
||||
|
||||
# 休息日加班:空工号 = 查询全部员工
|
||||
rest_overtime = fetch_all_overtime(
|
||||
session, user_id, "", begin, end, WORK_OVERTIME_TYPE_REST
|
||||
)
|
||||
logger.info("休息日加班记录(全部员工)%d 条", len(rest_overtime))
|
||||
|
||||
return {
|
||||
"abnormal_confirmed": abnormal_confirmed,
|
||||
"abnormal_open": abnormal_open,
|
||||
"leaves": leaves,
|
||||
"rest_overtime": rest_overtime,
|
||||
}
|
||||
|
||||
|
||||
def _build_leave_set(leaves, need_full_day=False):
|
||||
"""把请假记录索引化为 {(base_code, 'YYYY-MM-DD'): leave_rec}。
|
||||
|
||||
need_full_day=True 时只保留整日请假(leave_days>=1)的每一天;
|
||||
否则保留请假范围内的每一天(供检查1判断「日期是否有请假流程」)。
|
||||
"""
|
||||
index = {}
|
||||
for rec in leaves:
|
||||
code = str(_get(rec, "base_code")).strip()
|
||||
start = _to_date_str(_get(rec, "start_time", "begin_date"))
|
||||
end = _to_date_str(_get(rec, "end_time", "end_date"))
|
||||
leave_days = _float(rec.get("leave_days"))
|
||||
if not code or not start or not end:
|
||||
continue
|
||||
if need_full_day and leave_days < 1:
|
||||
continue
|
||||
try:
|
||||
cur = datetime.strptime(start, "%Y-%m-%d").date()
|
||||
end_d = datetime.strptime(end, "%Y-%m-%d").date()
|
||||
except ValueError:
|
||||
continue
|
||||
if end_d < cur:
|
||||
continue
|
||||
step = timedelta(days=1)
|
||||
while cur <= end_d:
|
||||
index[(code, cur.strftime("%Y-%m-%d"))] = rec
|
||||
cur += step
|
||||
return index
|
||||
|
||||
|
||||
# ==================== 检查1:已确认异常 × 请假流程 ====================
|
||||
def check_leave_after_confirm(abnormal_confirmed, leave_index):
|
||||
"""已确认异常(is_adjusted=2)的日期,是否同时存在请假流程。"""
|
||||
rows = []
|
||||
for ab in abnormal_confirmed:
|
||||
code = str(_get(ab, "base_code")).strip()
|
||||
work_day = _to_date_str(_get(ab, "work_day"))
|
||||
if not code or not work_day:
|
||||
continue
|
||||
leave_rec = leave_index.get((code, work_day))
|
||||
if not leave_rec:
|
||||
continue
|
||||
rows.append({
|
||||
"员工姓名": _staff_name(ab),
|
||||
"工号": code,
|
||||
"考勤日期": work_day,
|
||||
"异常类型": _get(ab, "abnormal"),
|
||||
"请假类型": _leave_type_name(leave_rec),
|
||||
"请假起止": f"{_to_date_str(_get(leave_rec, 'start_time', 'begin_date'))} ~ "
|
||||
f"{_to_date_str(_get(leave_rec, 'end_time', 'end_date'))}",
|
||||
"问题说明": "该日期已确认考勤异常,但同时存在请假流程,可能为「提前确认后请假」仍为异常",
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查2:休息日半天加班 × 打卡校验(结合排班班段) ====================
|
||||
def check_rest_day_half_day_punch(session, user_id, treecode, rest_overtime, begin, end):
|
||||
"""休息日加班(类型3)且加班天数为 0.5 天时,校验当日打卡是否按考勤班段正常打卡。"""
|
||||
rows = []
|
||||
half_ots = [ot for ot in rest_overtime if _is_half_day_ot(ot)]
|
||||
logger.info("休息日半天加班 %d 条,逐一校验打卡(结合排班班段)", len(half_ots))
|
||||
|
||||
# 按工号缓存排班记录,避免重复请求
|
||||
shift_cache = {}
|
||||
|
||||
for ot in half_ots:
|
||||
code = str(_get(ot, "base_code")).strip()
|
||||
ot_date = _to_date_str(_get(ot, "OT_DATE", "ot_date"))
|
||||
if not code or not ot_date:
|
||||
continue
|
||||
kq = fetch_all_kq_data(session, user_id, code, ot_date, ot_date, treecode)
|
||||
|
||||
# 拉取该员工排班(缓存),取加班日的班段
|
||||
if code not in shift_cache:
|
||||
shift_cache[code] = fetch_all_shift(session, user_id, code, begin, end, treecode)
|
||||
shift_info = _extract_day_shift(shift_cache.get(code, []), ot_date)
|
||||
|
||||
p = _punch_analysis(kq)
|
||||
judge = _judge_punch_by_shift(p, shift_info)
|
||||
rows.append({
|
||||
"员工姓名": _staff_name(ot),
|
||||
"工号": code,
|
||||
"加班日期": ot_date,
|
||||
"加班天数": _get(ot, "ot_days", "sys_ot_days", "plan_ot_days", default="0.5"),
|
||||
"排班班次": shift_info["bc_name"],
|
||||
"排班班段时间": shift_info["bc_time"],
|
||||
"计划时段": f"{_get(ot, 'PLAN_START_TIME') or _get(ot, 'FINAL_START_TIME')} ~ "
|
||||
f"{_get(ot, 'PLAN_END_TIME') or _get(ot, 'FINAL_END_TIME')}",
|
||||
"上班打卡": p["first"],
|
||||
"下班打卡": p["last"],
|
||||
"打卡次数": p["count"],
|
||||
"判定": judge,
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 检查3:整日请假 × 考勤异常 → 提示 ====================
|
||||
def check_full_day_leave_abnormal(abnormal_confirmed, abnormal_open, leaves):
|
||||
"""员工整日请假(leave_days>=1)当日,仍存在其他考勤异常(未调整/已确认)→ 提示。"""
|
||||
rows = []
|
||||
|
||||
# 整日请假日期索引 {(code, date): leave_rec}
|
||||
full_day_leave = _build_leave_set(leaves, need_full_day=True)
|
||||
if not full_day_leave:
|
||||
logger.info("无整日请假记录,检查3跳过")
|
||||
return rows
|
||||
|
||||
# 异常并集(同一员工同一日期可能同时有未调整/已确认,各自输出一条便于核查)
|
||||
for ab in list(abnormal_open) + list(abnormal_confirmed):
|
||||
code = str(_get(ab, "base_code")).strip()
|
||||
work_day = _to_date_str(_get(ab, "work_day"))
|
||||
if not code or not work_day:
|
||||
continue
|
||||
leave_rec = full_day_leave.get((code, work_day))
|
||||
if not leave_rec:
|
||||
continue
|
||||
is_adjusted = str(ab.get("is_adjusted", ""))
|
||||
status = "确认异常" if is_adjusted == "2" else ("未调整" if is_adjusted == "0" else "异常")
|
||||
hint = f"该员工{work_day}考勤状态存在异常"
|
||||
rows.append({
|
||||
"员工姓名": _staff_name(ab),
|
||||
"工号": code,
|
||||
"请假日期": work_day,
|
||||
"请假类型": _leave_type_name(leave_rec),
|
||||
"请假天数": _get(leave_rec, "leave_days"),
|
||||
"异常类型": _get(ab, "abnormal"),
|
||||
"异常状态": status,
|
||||
"提示": hint,
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 导出多 Sheet Excel 报告 ====================
|
||||
def export_report(results, save_dir, month_str):
|
||||
"""将三项检查结果导出为多 Sheet Excel 报告(无数据的 Sheet 也保留表头便于对照)。"""
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"月考勤异常三查_{month_str}_{ts}.xlsx"))
|
||||
|
||||
sheet_cfg = [
|
||||
("检查1_确认异常有请假", "check1", [
|
||||
"员工姓名", "工号", "考勤日期", "异常类型", "请假类型", "请假起止", "问题说明"]),
|
||||
("检查2_休息日半天打卡", "check2", [
|
||||
"员工姓名", "工号", "加班日期", "加班天数", "排班班次", "排班班段时间", "计划时段",
|
||||
"上班打卡", "下班打卡", "打卡次数", "判定"]),
|
||||
("检查3_整日请假有异常", "check3", [
|
||||
"员工姓名", "工号", "请假日期", "请假类型", "请假天数", "异常类型", "异常状态", "提示"]),
|
||||
]
|
||||
|
||||
c1 = results.get("check1", [])
|
||||
c2 = results.get("check2", [])
|
||||
c3 = results.get("check3", [])
|
||||
|
||||
# 汇总行
|
||||
summary = [
|
||||
{"检查项": "检查1:确认异常日期存在请假流程", "条数": len(c1)},
|
||||
{"检查项": "检查2:休息日半天加班打卡校验", "条数": len(c2)},
|
||||
{"检查项": "检查3:整日请假当日仍有考勤异常", "条数": len(c3)},
|
||||
]
|
||||
summary[1]["备注"] = "「判定」列中 漏打卡 需人工复核"
|
||||
summary[0]["备注"] = "可能为「提前确认后请假」仍为异常"
|
||||
|
||||
try:
|
||||
with pd.ExcelWriter(save_path, engine="openpyxl") as writer:
|
||||
pd.DataFrame(summary).to_excel(writer, sheet_name="汇总", index=False)
|
||||
for sheet_name, key, cols in sheet_cfg:
|
||||
data = results.get(key, [])
|
||||
df = pd.DataFrame(data, columns=cols)
|
||||
df.to_excel(writer, sheet_name=sheet_name, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
|
||||
)
|
||||
logger.info("月考勤异常三查完成:检查1=%d 条,检查2=%d 条,检查3=%d 条",
|
||||
len(c1), len(c2), len(c3))
|
||||
logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def handle_abnormal_check(save_dir=None, month=None):
|
||||
"""执行月考勤异常三项检查并导出 Excel 报告,返回导出文件路径。
|
||||
|
||||
Args:
|
||||
save_dir: 保存目录,默认 SAVE_DIR
|
||||
month: 查询月份 "YYYY-MM"(默认当月)。传该参数时查询整个月,
|
||||
不传则按「当月 1 日 至 今天」查询。
|
||||
"""
|
||||
save_dir = save_dir or SAVE_DIR
|
||||
session = build_hr_session()
|
||||
session, user_id, treecode = _validate_session(session)
|
||||
|
||||
if month:
|
||||
begin = f"{month}-01"
|
||||
end = f"{month}-31"
|
||||
month_str = month
|
||||
else:
|
||||
begin, end = current_month_range()
|
||||
month_str = date.today().strftime("%Y-%m")
|
||||
|
||||
data = _fetch_all_data(session, user_id, treecode, begin, end)
|
||||
|
||||
# 请假索引(全部请假,供检查1判断日期是否有请假流程)
|
||||
leave_index = _build_leave_set(data["leaves"], need_full_day=False)
|
||||
|
||||
# 检查1
|
||||
c1 = check_leave_after_confirm(data["abnormal_confirmed"], leave_index)
|
||||
logger.info("检查1(确认异常有请假):命中 %d 条", len(c1))
|
||||
for r in c1:
|
||||
logger.warning("【检查1】%s %s 考勤日期 %s,异常:%s,请假:%s",
|
||||
r["员工姓名"], r["工号"], r["考勤日期"], r["异常类型"], r["请假类型"])
|
||||
|
||||
# 检查2
|
||||
c2 = check_rest_day_half_day_punch(session, user_id, treecode,
|
||||
data["rest_overtime"], begin, end)
|
||||
logger.info("检查2(休息日半天打卡):校验 %d 条", len(c2))
|
||||
for r in c2:
|
||||
if "漏打卡" in r["判定"]:
|
||||
logger.warning("【检查2】%s %s %s 加班半天,%s",
|
||||
r["员工姓名"], r["工号"], r["加班日期"], r["判定"])
|
||||
|
||||
# 检查3
|
||||
c3 = check_full_day_leave_abnormal(
|
||||
data["abnormal_confirmed"], data["abnormal_open"], data["leaves"])
|
||||
logger.info("检查3(整日请假有异常):命中 %d 条", len(c3))
|
||||
for r in c3:
|
||||
logger.warning("【检查3】%s %s %s:%s(异常:%s / %s)",
|
||||
r["员工姓名"], r["工号"], r["请假日期"], r["提示"],
|
||||
r["异常类型"], r["异常状态"])
|
||||
|
||||
return export_report({"check1": c1, "check2": c2, "check3": c3}, save_dir, month_str)
|
||||
|
||||
|
||||
def main(args=None):
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段 save_dir(导出目录)、month("YYYY-MM",默认当月;月度调度传上月)
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
save_dir = args.get("save_dir") or (sys.argv[1] if len(sys.argv) > 1 else None)
|
||||
month = args.get("month") or os.getenv("attendance_check_month") or (sys.argv[2] if len(sys.argv) > 2 else None)
|
||||
try:
|
||||
out = handle_abnormal_check(save_dir, month)
|
||||
_set_glv('attendance_check_save_path', out)
|
||||
logger.info("===== 月考勤异常三查完成,导出:%s =====", out)
|
||||
return {"success": True, "save_path": out}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。")
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("月考勤异常三查失败:%s", e)
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: bank_card_check_yingdao.py
|
||||
@FileName: bank_card_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-08
|
||||
@Description: 银行卡检查(单文件版,app 与影刀共用)——HR 登录(滑块验证码)
|
||||
@@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: social_change_yingdao.py
|
||||
@FileName: social_change.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-07
|
||||
@Description: 社保增减名单核对(统一单文件版,app 与影刀共用)——OA 登录导出参保/停保名单 -> 清洗去重 -> HR 登录(滑块验证码)调用 si_main 参保记录接口核对 -> 追加结果列 -> 钉钉推送两张表
|
||||
@@ -1,496 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: dingtalk_robot.py
|
||||
@Description: 钉钉群机器人推送自定义指令(影刀编码版 Python 模块源码,单一真源)。
|
||||
作为「37du钉钉群机器人推送」影刀自定义指令的模块源码,
|
||||
供所有需要往钉钉群发通知的影刀脚本/流程复用(周考勤、请假审批、加班审批、人事变动等),
|
||||
避免每个脚本各自内联 Webhook 加签与 Markdown 排版逻辑。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 dingtalk_robot,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 params(字典类型,dict),或分别增加 msgtype/title/content/status 等参数;
|
||||
4. 保存并「发版」;在需要钉钉群推送的应用中「获取指令」并安装;
|
||||
5. 在流程中拖入该指令,把业务脚本输出的参数传入(两种方式任选):
|
||||
方式A(推荐):流程中先拼一个字典变量(如 {"title": "任务执行失败", "content": "..."}),
|
||||
作为 params 整体传入;
|
||||
方式B:分别传 msgtype、title、content 等变量,指令内部自动拼成字典;
|
||||
指令返回 JSON:{"success": bool, "message": str},可在后续流程中判断是否重试。
|
||||
|
||||
推送原理(HTTP Webhook 方式,与 app/utils/dingtalk_robot.py 一致):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 JSON 消息,无需登录钉钉桌面端。
|
||||
失败自动重试 3 次,成功/失败均有日志。
|
||||
|
||||
依赖:
|
||||
仅使用 Python 标准库(urllib/hashlib/hmac/base64),零第三方依赖,无需 pip 安装。
|
||||
|
||||
约定(与项目 app 版一致,见 app/utils/dingtalk_robot.py):
|
||||
- 配置:影刀运行环境无 .env 文件读取,故推送地址/加签密钥/页脚署名
|
||||
直接内联在下方「默认参数」区(单一真源),改推送目标时改常量即可;
|
||||
也可在调用 main(args) 时通过 webhook/secret/server_name 参数覆盖;
|
||||
- 页脚署名默认 "小芒 任务调度平台":
|
||||
注意:钉钉机器人若配置了"自定义关键词"安全校验,
|
||||
页脚署名需包含该关键词(如 小芒)才会被接受。
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口
|
||||
args = {
|
||||
"msgtype": "notification|text|markdown|actionCard(可选,默认 notification)",
|
||||
"title": "消息标题(notification/markdown/actionCard 使用)",
|
||||
"content": "消息正文,多行自动转引用块(notification 使用)",
|
||||
"text": "文本内容(msgtype=text 使用)",
|
||||
"status": "info|success|warning|error(可选,默认 info,决定标题颜色)",
|
||||
"at_mobiles": "需 @ 的手机号列表(可选;兼容逗号分隔字符串)",
|
||||
"at_user_ids":"需 @ 的用户 userid 列表(可选)",
|
||||
"is_at_all": "是否 @所有人(可选,默认 false)",
|
||||
"webhook": "机器人 webhook(可选,缺省用内联默认值)",
|
||||
"secret": "加签密钥(可选,缺省用内联默认值)",
|
||||
"server_name":"页脚署名(可选,缺省用内联默认值)",
|
||||
"single_title":"按钮文字(msgtype=actionCard 使用)",
|
||||
"single_url": "按钮跳转链接(msgtype=actionCard 使用)",
|
||||
}
|
||||
通过流程参数传入(支持整字典 params 或分别传各字段)
|
||||
返回 JSON 安全 dict:{"success": bool, "message": str}
|
||||
|
||||
python dingtalk_robot.py 消息内容 [--title 标题] [--status info] [--webhook ...] [--secret ...]
|
||||
独立运行(等价于 main({"title": ..., "content": ..., ...}))
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
# ==================== 日志(print) ====================
|
||||
class _PrintLogger:
|
||||
"""影刀版无 logging 依赖,直接用 print 输出,行为与项目 logger 对齐。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
# ==================== 默认参数 ====================
|
||||
# 影刀运行环境无 .env 文件读取,故 webhook/secret/署名直接内联在此(单一真源),
|
||||
# 需要调整推送目标时改这里即可;也可在调用 main(args) 时通过 webhook/secret/server_name 覆盖。
|
||||
DEFAULT_WEBHOOK = (
|
||||
'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
)
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '37du 任务调度平台'
|
||||
DEFAULT_TIMEOUT = 10 # HTTP 请求超时秒数
|
||||
DEFAULT_RETRY_TIMES = 3 # 失败重试次数(含首次)
|
||||
DINGTALK_ROBOT_ENDPOINT = 'https://oapi.dingtalk.com/robot/send'
|
||||
|
||||
# 通知状态 → 标题颜色(与 app 版 dingtalk_robot.py 色板一致)
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff', # 蓝色
|
||||
'success': '#00b300', # 绿色
|
||||
'warning': '#ff9900', # 橙色
|
||||
'error': '#ff0000', # 红色
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
def _at_payload(at_mobiles=None, at_user_ids=None, is_at_all=False):
|
||||
"""构造 @ 参数。三种 @ 方式可组合,都不指定时返回空 dict。"""
|
||||
at = {}
|
||||
if at_mobiles:
|
||||
at['atMobiles'] = list(at_mobiles)
|
||||
if at_user_ids:
|
||||
at['atUserIds'] = list(at_user_ids)
|
||||
if is_at_all:
|
||||
at['isAtAll'] = True
|
||||
return at
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""
|
||||
钉钉群机器人推送器。
|
||||
|
||||
Args:
|
||||
webhook: 机器人 webhook 地址;缺省用内联默认值 DEFAULT_WEBHOOK
|
||||
secret: 加签密钥;缺省用内联默认值 DEFAULT_SECRET
|
||||
server_name: 页脚平台署名;缺省用内联默认值 DEFAULT_SERVER_NAME,
|
||||
默认 "小芒 任务调度平台"(含关键词"小芒",可满足机器人自定义关键词校验)
|
||||
timeout: HTTP 请求超时秒数
|
||||
|
||||
Raises:
|
||||
ValueError: webhook 为空
|
||||
"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError(
|
||||
'webhook 不能为空,请通过参数传入或修改模块内 DEFAULT_WEBHOOK 内联常量'
|
||||
)
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
logger.debug('钉钉机器人推送成功,响应: %s', resp_data)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
logger.warning('推送失败(第 %d/%d 次):%s', attempt + 1, DEFAULT_RETRY_TIMES, e)
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def _build_footer(self, server_name=''):
|
||||
"""构建页脚:###### {署名} | {当前时间}。署名缺省取实例的 server_name。"""
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
return f"###### {display_name} | {current_time}"
|
||||
|
||||
def send_text(self, content, at_mobiles=None, at_user_ids=None, is_at_all=False):
|
||||
"""发送文本消息。"""
|
||||
if not content or not content.strip():
|
||||
raise ValueError('content 不能为空')
|
||||
|
||||
payload = {'msgtype': 'text', 'text': {'content': content}}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload['at'] = at
|
||||
|
||||
logger.info('钉钉机器人推送文本: %s', content[:50] + ('...' if len(content) > 50 else ''))
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
def send_markdown(self, title, text, at_mobiles=None, at_user_ids=None, is_at_all=False):
|
||||
"""发送 Markdown 消息(底层通用方法,内容完全由调用方控制)。"""
|
||||
if not title or not title.strip():
|
||||
raise ValueError('title 不能为空')
|
||||
if not text or not text.strip():
|
||||
raise ValueError('text 不能为空')
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload['at'] = at
|
||||
|
||||
logger.info('钉钉机器人推送 Markdown: %s', title)
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
def send_notification(
|
||||
self, title, content, status='info',
|
||||
at_mobiles=None, at_user_ids=None, is_at_all=False,
|
||||
server_name='', append_footer=True,
|
||||
):
|
||||
"""
|
||||
统一通知方法(推荐业务方使用),样式与 app 版 dingtalk_robot.py 一致:
|
||||
|
||||
**<font color='#ff0000'>任务执行失败</font>** ← 标题按 status 着色
|
||||
|
||||
内容详情:
|
||||
> 订单同步失败 ← 内容多行自动转引用块
|
||||
> 错误原因:接口超时
|
||||
|
||||
---
|
||||
|
||||
###### 小芒 任务调度平台 | 2026-08-14 14:30:00 ← 页脚:署名 + 当前时间
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息主体内容,支持多行(自动按行转引用块)
|
||||
status: 状态类型,决定标题颜色: info(蓝) | success(绿) | warning(橙) | error(红)
|
||||
at_mobiles: 需要 @ 的手机号列表
|
||||
at_user_ids: 需要 @ 的用户 userid 列表
|
||||
is_at_all: 是否 @所有人
|
||||
server_name: 页脚署名,缺省用实例的 server_name
|
||||
append_footer: 是否自动追加页脚(署名 + 时间),默认 True
|
||||
|
||||
Returns:
|
||||
是否推送成功
|
||||
|
||||
Raises:
|
||||
ValueError: title 或 content 为空
|
||||
"""
|
||||
if not title or not title.strip():
|
||||
raise ValueError('title 不能为空')
|
||||
if not content or not content.strip():
|
||||
raise ValueError('content 不能为空')
|
||||
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += '内容详情:\n'
|
||||
for line in content.strip().splitlines():
|
||||
line = line.strip()
|
||||
if line:
|
||||
# 行尾两个空格 + 换行:钉钉 markdown 单个 \n 不换行,必须用硬换行才分行显示
|
||||
text += f"> {line} \n"
|
||||
if append_footer:
|
||||
text += f"\n\n---\n\n{self._build_footer(server_name)}"
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload['at'] = at
|
||||
|
||||
logger.info('钉钉机器人推送通知 [%s]: %s', status, title)
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
def send_action_card(
|
||||
self, title, content, single_title, single_url,
|
||||
at_mobiles=None, at_user_ids=None, is_at_all=False,
|
||||
server_name='',
|
||||
):
|
||||
"""发送 ActionCard 消息(底部带按钮,如"点击下载报表")。"""
|
||||
if not title or not title.strip():
|
||||
raise ValueError('title 不能为空')
|
||||
if not content or not content.strip():
|
||||
raise ValueError('content 不能为空')
|
||||
if not single_title or not single_title.strip():
|
||||
raise ValueError('single_title 不能为空')
|
||||
if not single_url or not single_url.strip():
|
||||
raise ValueError('single_url 不能为空')
|
||||
|
||||
text = f"**{title}**\n\n{content}\n\n---\n\n{self._build_footer(server_name)}"
|
||||
payload = {
|
||||
'msgtype': 'actionCard',
|
||||
'actionCard': {
|
||||
'title': title,
|
||||
'text': text,
|
||||
'singleTitle': single_title,
|
||||
'singleURL': single_url,
|
||||
},
|
||||
}
|
||||
at = _at_payload(at_mobiles, at_user_ids, is_at_all)
|
||||
if at:
|
||||
payload['at'] = at
|
||||
|
||||
logger.info('钉钉机器人推送 ActionCard: %s -> %s', title, single_url)
|
||||
self._post(payload)
|
||||
return True
|
||||
|
||||
|
||||
# ==================== 一次性便捷函数 ====================
|
||||
def send_robot_text(content, webhook='', secret='', at_mobiles=None, at_user_ids=None, is_at_all=False):
|
||||
"""一键发送文本到群机器人(webhook 缺省用内联默认值 DEFAULT_WEBHOOK)。"""
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret)
|
||||
return robot.send_text(content, at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all)
|
||||
|
||||
|
||||
def send_robot_notification(
|
||||
title, content, status='info',
|
||||
webhook='', secret='',
|
||||
at_mobiles=None, at_user_ids=None, is_at_all=False,
|
||||
server_name='',
|
||||
):
|
||||
"""一键发送统一通知(样式与 send_notification 一致)。"""
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret)
|
||||
return robot.send_notification(
|
||||
title, content, status=status,
|
||||
at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all,
|
||||
server_name=server_name,
|
||||
)
|
||||
|
||||
|
||||
# ==================== 影刀自定义指令入口 ====================
|
||||
def _to_list(value):
|
||||
"""把 at_mobiles / at_user_ids 参数归一为 list:列表原样返回,字符串按逗号拆。"""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [str(v).strip() for v in value if str(v).strip()]
|
||||
if isinstance(value, str):
|
||||
return [v.strip() for v in value.replace(',', ',').split(',') if v.strip()]
|
||||
return [str(value)]
|
||||
|
||||
|
||||
def _send_one(args):
|
||||
"""按 args 字典发送一条消息,返回 {success: bool, message: str}。"""
|
||||
try:
|
||||
msgtype = str(args.get('msgtype', '') or 'notification').strip().lower() or 'notification'
|
||||
webhook = str(args.get('webhook', '') or '').strip()
|
||||
secret = str(args.get('secret', '') or '').strip()
|
||||
server_name = str(args.get('server_name', '') or '').strip()
|
||||
at_mobiles = _to_list(args.get('at_mobiles'))
|
||||
at_user_ids = _to_list(args.get('at_user_ids'))
|
||||
is_at_all = bool(args.get('is_at_all', False))
|
||||
title = str(args.get('title', '') or '').strip()
|
||||
content = str(args.get('content', '') or '')
|
||||
text = str(args.get('text', '') or '').strip()
|
||||
status = str(args.get('status', '') or 'info').strip().lower() or 'info'
|
||||
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
|
||||
if msgtype == 'text':
|
||||
if not text:
|
||||
return {'success': False, 'message': 'msgtype=text 时参数 text 不能为空'}
|
||||
robot.send_text(text, at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all)
|
||||
return {'success': True, 'message': f"已发送文本消息({len(text)} 字)"}
|
||||
|
||||
if msgtype == 'markdown':
|
||||
if not title or not text:
|
||||
return {'success': False, 'message': 'msgtype=markdown 时参数 title/text 不能为空'}
|
||||
robot.send_markdown(
|
||||
title, text, at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all
|
||||
)
|
||||
return {'success': True, 'message': f'已发送 Markdown 消息:{title}'}
|
||||
|
||||
if msgtype == 'actioncard':
|
||||
single_title = str(args.get('single_title', '') or '').strip()
|
||||
single_url = str(args.get('single_url', '') or '').strip()
|
||||
if not title or not content or not single_title or not single_url:
|
||||
return {
|
||||
'success': False,
|
||||
'message': 'msgtype=actionCard 时参数 title/content/single_title/single_url 不能为空',
|
||||
}
|
||||
robot.send_action_card(
|
||||
title, content, single_title, single_url,
|
||||
at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all,
|
||||
server_name=server_name,
|
||||
)
|
||||
return {'success': True, 'message': f'已发送 ActionCard:{title}'}
|
||||
|
||||
# 默认 notification
|
||||
if not title or not content.strip():
|
||||
return {'success': False, 'message': '参数 title/content 不能为空'}
|
||||
robot.send_notification(
|
||||
title, content, status=status,
|
||||
at_mobiles=at_mobiles, at_user_ids=at_user_ids, is_at_all=is_at_all,
|
||||
server_name=server_name,
|
||||
)
|
||||
return {'success': True, 'message': f"已发送通知 [{status}]:{title}"}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
|
||||
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37du钉钉群机器人推送」调用入口。
|
||||
args: dict,通过流程变量传入(影刀变量支持传字典/列表):
|
||||
方式A(批量,推荐):args = {"messages": [{msgtype?, title?, content?, ...}, ...]}
|
||||
messages 为「字典列表」,逐条推送并返回汇总结果;
|
||||
方式B(单条):args = {"params": {...}} 或直接 {"msgtype":..., "title":..., "content":...};
|
||||
返回: dict
|
||||
单条: {success: bool, message: str}
|
||||
批量: {success: bool, message: str, sent: int, failed: int, results: [...]}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
# 兼容「整个字典作为 params 传入」的用法
|
||||
if isinstance(args.get('params'), dict):
|
||||
merged = dict(args)
|
||||
merged.update(args['params'])
|
||||
args = merged
|
||||
|
||||
# 批量:messages 为字典列表,逐条推送
|
||||
if isinstance(args.get('messages'), list):
|
||||
results = [_send_one(m) for m in args['messages']]
|
||||
ok = sum(1 for r in results if r.get('success'))
|
||||
return {
|
||||
'success': ok == len(results),
|
||||
'message': f'共 {len(results)} 条,成功 {ok},失败 {len(results) - ok}',
|
||||
'sent': ok,
|
||||
'failed': len(results) - ok,
|
||||
'results': results,
|
||||
}
|
||||
|
||||
# 单条推送
|
||||
return _send_one(args)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 仅本地自测连通性。影刀中会直接调用 main(args) 并通过流程变量传参,不会走这里。
|
||||
# 批量测试:流程变量 messages = 字典列表,每条含 title/content,main 逐条推送并汇总。
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description='钉钉群机器人消息推送工具(影刀指令源码独立运行)')
|
||||
parser.add_argument('content', nargs='?', default='', help='消息正文/文本(多行可用换行分隔)')
|
||||
parser.add_argument('-t', '--title', default='消息通知', help='消息标题')
|
||||
parser.add_argument('--status', default='info',
|
||||
choices=['info', 'success', 'warning', 'error'], help='通知状态(决定标题颜色)')
|
||||
parser.add_argument('--msgtype', default='notification',
|
||||
choices=['notification', 'text', 'markdown', 'actionCard'], help='消息类型')
|
||||
parser.add_argument('-w', '--webhook', default='', help='机器人 webhook,缺省用内联默认值')
|
||||
parser.add_argument('-s', '--secret', default='', help='加签密钥,缺省用内联默认值')
|
||||
parser.add_argument('--name', default='', help='页脚平台署名,缺省用内联默认值')
|
||||
parser.add_argument('--all', action='store_true', help='@所有人')
|
||||
parser.add_argument('--text', default='', help='msgtype=text/markdown 时的文本内容')
|
||||
parser.add_argument('--single-title', default='点击查看', help='actionCard 按钮文字')
|
||||
parser.add_argument('--single-url', default='https://www.37du.co', help='actionCard 按钮链接')
|
||||
_cli = parser.parse_args()
|
||||
|
||||
_params = {
|
||||
'msgtype': _cli.msgtype,
|
||||
'title': _cli.title,
|
||||
'content': _cli.content,
|
||||
'text': _cli.text,
|
||||
'status': _cli.status,
|
||||
'webhook': _cli.webhook,
|
||||
'secret': _cli.secret,
|
||||
'server_name': _cli.name,
|
||||
'is_at_all': _cli.all,
|
||||
'single_title': _cli.single_title,
|
||||
'single_url': _cli.single_url,
|
||||
}
|
||||
result = main(_params)
|
||||
print('最终结果:', result)
|
||||
@@ -1,21 +1,27 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: leave_approval_yingdao.py
|
||||
@FileName: leave_approval.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06
|
||||
@Description: 请假审批流程(影刀单文件版)- 合并自原项目 13 个模块,业务逻辑完全一致
|
||||
@Version: 2.0.0
|
||||
@Version: 2.2.0
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage python-dotenv pyautogui pywin32 pyperclip Pillow numpy rapidocr-onnxruntime psutil
|
||||
pip install DrissionPage python-dotenv Pillow numpy rapidocr-onnxruntime
|
||||
|
||||
环境变量(.env 文件或系统变量):
|
||||
oa_login_url=登录页URL
|
||||
oa_target_url_keyword=登录成功后URL关键字
|
||||
oa_login_username=用户名
|
||||
oa_login_password=密码
|
||||
dingtalk_notify_enabled=true|false(默认 false,是否推送审批结果到钉钉)
|
||||
dingtalk_notify_target=钉钉联系人姓名(如 夏一平)
|
||||
登录(共享登录态,本脚本为单文件自包含):
|
||||
- 登录态统一由「37duOA登录」影刀自定义指令写入共享 cookies:
|
||||
%LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json
|
||||
- 本脚本仅读取该 cookies 文件,不 import 任何共享模块;缺失/失效时
|
||||
报错提示先运行登录指令(影刀流程开头请先拖入「37duOA登录」指令)。
|
||||
|
||||
推送消息(本脚本不发送任何消息,只负责生成文本):
|
||||
- 本脚本不内联任何消息推送逻辑;仅生成待推送的文本消息,经 main() 写入影刀全局变量
|
||||
messages(纯文本,多段用空行分隔),由「37du钉钉群机器人推送」指令直接读取发送;
|
||||
本地独立运行时静默跳过写全局变量;
|
||||
- main(push_type, target):
|
||||
push_type="group"(默认)群消息:全局变量 messages 为纯文本,直接交钉钉群机器人 webhook 推送;
|
||||
push_type="person" 单聊:main 返回值仍为 {target, text} 列表,可交给「37du钉钉推送」指令走 OCR 单聊。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
@@ -25,6 +31,7 @@ import math
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Callable
|
||||
@@ -35,23 +42,14 @@ from urllib.parse import urlencode, urlparse, parse_qs
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, SessionPage
|
||||
from dotenv import load_dotenv
|
||||
import pyautogui
|
||||
import win32gui
|
||||
import win32con
|
||||
import win32clipboard
|
||||
import win32process
|
||||
import win32api
|
||||
import pyperclip
|
||||
import psutil
|
||||
from PIL import Image, ImageEnhance, ImageGrab
|
||||
from PIL import Image, ImageEnhance
|
||||
import numpy as np
|
||||
from rapidocr_onnxruntime import RapidOCR
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install DrissionPage python-dotenv pyautogui pywin32 pyperclip "
|
||||
"Pillow numpy rapidocr-onnxruntime psutil\n"
|
||||
" pip install DrissionPage python-dotenv Pillow numpy rapidocr-onnxruntime\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
@@ -61,10 +59,12 @@ except ImportError as _import_err:
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 数据目录固定放在 AppData\Local\37duAutomation,不依赖脚本位置,每台电脑都有(影刀版独立子目录)
|
||||
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), '37duAutomation', 'LeaveApproval')
|
||||
# 数据目录固定放在 AppData\Local\37duAutomation,不依赖脚本位置,每台电脑都有
|
||||
# 登录态与共享 .env 统一由「37duOA登录」影刀自定义指令写入(见 yingdao/share/oa_login.py)
|
||||
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), '37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
# ---------- OA 系统 ----------
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
@@ -103,6 +103,20 @@ class _PrintLogger:
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
# 登录态统一由「37duOA登录」影刀自定义指令维护(见 yingdao/share/oa_login.py),
|
||||
# 本脚本为单文件自包含:仅读取共享 cookies 文件,不 import 任何共享模块。
|
||||
# cookies 缺失/失效时提示先运行登录指令,不再内联调用共享登录模块。
|
||||
|
||||
|
||||
# ==================== 内置 OCR 兜底实现 ====================
|
||||
# 内置 OCR 实现(单文件自包含),行为与原项目 app/utils/ocr.py 完全一致:
|
||||
# 病假/婚假/产检假按关键词命中检测,结婚证按最大日期识别登记日期并判断 1 年内。
|
||||
@@ -606,24 +620,6 @@ def _parse_leave_form(result):
|
||||
|
||||
|
||||
# ==================== 会话管理 ====================
|
||||
def init_session_from_page(browser_page, copy_headers=True):
|
||||
session = SessionPage()
|
||||
cookies_dict = browser_page.cookies(all_domains=True)
|
||||
if cookies_dict:
|
||||
session.set.cookies(cookies_dict)
|
||||
logger.info("已复制 %d 个 Cookies 到 SessionPage", len(cookies_dict))
|
||||
else:
|
||||
logger.warning("未获取到 Cookies,请确认浏览器已登录")
|
||||
|
||||
if copy_headers:
|
||||
headers = {"User-Agent": browser_page.run_js("return navigator.userAgent;")}
|
||||
session.set.headers(headers)
|
||||
logger.info("已复制 User-Agent: %s...", headers['User-Agent'][:50])
|
||||
|
||||
session.set.timeout(10)
|
||||
return session
|
||||
|
||||
|
||||
def refresh_session_cookies(session, browser_page):
|
||||
cookies = browser_page.cookies(all_domains=True)
|
||||
if cookies:
|
||||
@@ -694,41 +690,23 @@ def download_attachment(session, file_id, save_dir=r"D:\资料\人资\请假流
|
||||
return path
|
||||
|
||||
|
||||
def save_browser_cookies(browser_page, path=COOKIE_FILE):
|
||||
cookies = browser_page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
logger.warning("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
logger.info("已保存 %d 个 Cookies 到 %s", len(cookies), path)
|
||||
|
||||
|
||||
def load_cookies(path=COOKIE_FILE):
|
||||
if not os.path.exists(path):
|
||||
def _load_shared_oa_cookies():
|
||||
"""读取共享 OA 登录 cookies(由「37duOA登录」影刀自定义指令写入)。"""
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(path, encoding='utf-8') as f:
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
def load_saved_session(path=COOKIE_FILE):
|
||||
cookies = load_cookies(path)
|
||||
if not cookies:
|
||||
return None
|
||||
session = SessionPage()
|
||||
session.set.cookies(cookies)
|
||||
session.set.timeout(10)
|
||||
return session
|
||||
|
||||
|
||||
def create_browser_with_saved_cookies(path=COOKIE_FILE):
|
||||
browser = ChromiumPage()
|
||||
cookies = load_cookies(path)
|
||||
if cookies:
|
||||
browser.set.cookies(cookies)
|
||||
return browser
|
||||
def _ensure_oa_cookies(force=False):
|
||||
"""确保存在有效的 OA 登录态文件(由「37duOA登录」指令写入);缺失时提示先运行登录指令。"""
|
||||
if not force and _load_shared_oa_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 OA 登录态(oa_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duOA登录」指令,或本地先运行 "
|
||||
"python yingdao/share/oa_login.py")
|
||||
|
||||
|
||||
def is_session_valid(session, subject="请假"):
|
||||
@@ -746,62 +724,41 @@ def is_session_valid(session, subject="请假"):
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 登录 ====================
|
||||
@retry(max_attempts=3)
|
||||
def oa_login(username=None, password=None, timeout=10, wait_after_load=2):
|
||||
load_dotenv()
|
||||
def build_session(subject):
|
||||
"""仅构建 SessionPage(不启动浏览器),从共享 cookies 填充登录态。
|
||||
|
||||
login_url = os.getenv('oa_login_url')
|
||||
if not login_url:
|
||||
raise RuntimeError("环境变量 oa_login_url 未设置")
|
||||
target_url_keyword = os.getenv('oa_target_url_keyword')
|
||||
if not target_url_keyword:
|
||||
raise RuntimeError("环境变量 oa_target_url_keyword 未设置")
|
||||
用于查待办、拉表单等纯接口操作;会话失效时调用共享登录模块强制重登后重建。
|
||||
"""
|
||||
_ensure_oa_cookies()
|
||||
session = SessionPage()
|
||||
session.set.timeout(10)
|
||||
cookies = _load_shared_oa_cookies()
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
if is_session_valid(session, subject):
|
||||
return session
|
||||
logger.warning("共享登录态已失效,强制重登")
|
||||
_ensure_oa_cookies(force=True)
|
||||
cookies = _load_shared_oa_cookies()
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
return session
|
||||
|
||||
final_username = username or os.getenv('oa_login_username')
|
||||
final_password = password or os.getenv('oa_login_password')
|
||||
if not final_username or not final_password:
|
||||
raise RuntimeError("用户名或密码未提供,请设置环境变量或传入参数")
|
||||
|
||||
page = ChromiumPage()
|
||||
def build_browser(subject):
|
||||
"""有单据时才启动浏览器(SSO 跳转解析 / 真实审批点击 / 结果弹窗用),并填充共享 cookies。"""
|
||||
_ensure_oa_cookies()
|
||||
browser = ChromiumPage()
|
||||
cookies = _load_shared_oa_cookies()
|
||||
if cookies:
|
||||
browser.set.cookies(cookies)
|
||||
return browser
|
||||
|
||||
try:
|
||||
page.get(login_url)
|
||||
time.sleep(wait_after_load)
|
||||
|
||||
username_input = page.ele('tag:input@name=j_username')
|
||||
if not username_input:
|
||||
raise RuntimeError("未找到用户名输入框")
|
||||
username_input.input(final_username)
|
||||
page.wait(0.5)
|
||||
|
||||
password_input = page.ele('tag:input@name=j_password')
|
||||
if not password_input:
|
||||
raise RuntimeError("未找到密码输入框")
|
||||
password_input.input(final_password)
|
||||
page.wait(0.5)
|
||||
|
||||
login_button = page.ele('.lui_login_button_div_c')
|
||||
if not login_button:
|
||||
raise RuntimeError("未找到登录按钮")
|
||||
login_button.click()
|
||||
page.wait(0.5)
|
||||
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
if target_url_keyword in page.url:
|
||||
logger.info("登录成功!当前 URL: %s", page.url)
|
||||
return page
|
||||
time.sleep(0.5)
|
||||
|
||||
error_elem = page.ele('.error-msg') or page.ele('.alert-danger')
|
||||
if error_elem:
|
||||
logger.warning("登录失败,提示: %s", error_elem.text)
|
||||
raise RuntimeError(f"登录超时,当前 URL: {page.url}")
|
||||
|
||||
except Exception as e:
|
||||
page.quit()
|
||||
raise RuntimeError(f"登录过程出错: {e}")
|
||||
# ==================== 登录(共享) ====================
|
||||
# 登录态统一由「37duOA登录」影刀自定义指令维护(见 yingdao/share/oa_login.py),
|
||||
# 本脚本通过 build_session()/build_browser() 复用共享 cookies,不再内联账号密码登录代码;
|
||||
# 无待办单据时不启动浏览器(build_session 纯接口即可),仅在确有单据时才开浏览器。
|
||||
|
||||
|
||||
# ==================== SSO 解析 ====================
|
||||
@@ -824,19 +781,6 @@ def resolve_sso_params(browser, sso_url, wait_timeout=20):
|
||||
|
||||
|
||||
# ==================== 审批引擎 ====================
|
||||
def _get_browser_and_session(subject):
|
||||
saved_session = load_saved_session()
|
||||
if saved_session is not None and is_session_valid(saved_session, subject):
|
||||
logger.info("复用已保存的登录会话,跳过登录")
|
||||
browser = create_browser_with_saved_cookies()
|
||||
return browser, saved_session, False
|
||||
|
||||
browser = oa_login()
|
||||
session = init_session_from_page(browser)
|
||||
save_browser_cookies(browser)
|
||||
return browser, session, True
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_documents(session, subject):
|
||||
return get_documents(session, subject=subject)
|
||||
@@ -935,425 +879,30 @@ def show_rpa_result_popup(page: ChromiumPage,
|
||||
|
||||
|
||||
|
||||
# ==================== 钉钉推送(OCR 视觉方案内联,保持单文件自包含) ====================
|
||||
# 内联自 app/utils/dingtalk_sender.py(视觉方案),相比旧固定坐标模拟大幅提升稳定性:
|
||||
# 窗口查找排除 0 尺寸阴影/辅助窗口,只认主窗口;多策略激活(快捷键→Win32 API→组合);
|
||||
# 搜索框/标签/输入框全部通过 OCR 校验后再操作。
|
||||
_DT_TIMEOUT = 8
|
||||
_DT_SEARCH_RETRY = 3
|
||||
_DT_RETRY_TIMES = 3
|
||||
_DT_TOP_HEIGHT_RATIO = 0.18
|
||||
|
||||
_dt_ocr = None
|
||||
# ==================== 推送消息生成(不发送,交由消息推送模块) ====================
|
||||
# 本脚本不发送任何消息:仅把审批结果拼成文本消息(默认群消息,只含 text;
|
||||
# 传 push_type="person" 时生成含 target 的单聊消息),经 main() 把纯文本写入影刀全局变量 messages。
|
||||
|
||||
|
||||
def _dt_get_ocr():
|
||||
"""获取 RapidOCR 实例(单例;若模块已初始化 _ocr_engine 则复用,避免重复加载模型)。"""
|
||||
global _dt_ocr
|
||||
# 用 globals().get 而非直接读 _dt_ocr:避免个别运行环境/旧 pyc 下模块级 _dt_ocr 未定义时抛 NameError
|
||||
_dt_ocr = globals().get("_dt_ocr")
|
||||
if _dt_ocr is None:
|
||||
_dt_ocr = globals().get("_ocr_engine") or RapidOCR()
|
||||
return _dt_ocr
|
||||
def _build_push_messages(texts, push_type="group", target=None):
|
||||
"""把文本列表转成推送消息列表(字典列表)。
|
||||
|
||||
|
||||
def _dt_get_process_name_by_pid(pid):
|
||||
"""根据进程 ID 获取进程名称,失败返回 None"""
|
||||
try:
|
||||
return psutil.Process(pid).name()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _dt_find_dingtalk_window(include_hidden=True):
|
||||
"""查找钉钉“主窗口”句柄(排除 0 尺寸阴影/辅助窗口,只认 DingTalk 进程或主标题)。"""
|
||||
def has_valid_rect(hwnd):
|
||||
try:
|
||||
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
|
||||
return (right - left) > 0 and (bottom - top) > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def is_main_title(hwnd):
|
||||
return win32gui.GetWindowText(hwnd) in ('钉钉', 'DingTalk')
|
||||
|
||||
candidates = []
|
||||
def enum_callback(hwnd, _):
|
||||
if not include_hidden and not win32gui.IsWindowVisible(hwnd):
|
||||
return True
|
||||
title = win32gui.GetWindowText(hwnd)
|
||||
if title == '钉钉' or title == 'DingTalk':
|
||||
candidates.append(hwnd)
|
||||
return True
|
||||
try:
|
||||
_, pid = win32process.GetWindowThreadProcessId(hwnd)
|
||||
proc_name = _dt_get_process_name_by_pid(pid)
|
||||
if proc_name and proc_name.lower() == 'dingtalk.exe':
|
||||
candidates.append(hwnd)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
win32gui.EnumWindows(enum_callback, None)
|
||||
|
||||
valid = [h for h in candidates if has_valid_rect(h)]
|
||||
if not valid:
|
||||
return None
|
||||
for h in valid:
|
||||
if is_main_title(h) and win32gui.IsWindowVisible(h):
|
||||
return h
|
||||
for h in valid:
|
||||
if is_main_title(h):
|
||||
return h
|
||||
for h in valid:
|
||||
if win32gui.IsWindowVisible(h):
|
||||
return h
|
||||
return valid[0]
|
||||
|
||||
|
||||
def _dt_activate_window(hwnd):
|
||||
"""强制激活窗口(最小化、隐藏、托盘均可恢复)"""
|
||||
if win32gui.IsIconic(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
|
||||
time.sleep(0.3)
|
||||
if not win32gui.IsWindowVisible(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_SHOW)
|
||||
time.sleep(0.3)
|
||||
win32gui.SetForegroundWindow(hwnd)
|
||||
win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_KEYUP, 0)
|
||||
time.sleep(0.3)
|
||||
|
||||
|
||||
def _dt_get_window_rect(hwnd):
|
||||
"""获取窗口矩形 (left, top, right, bottom)"""
|
||||
return win32gui.GetWindowRect(hwnd)
|
||||
|
||||
|
||||
def _dt_is_dingtalk_main_visible():
|
||||
"""钉钉主窗口当前是否可见"""
|
||||
hwnd = _dt_find_dingtalk_window(include_hidden=True)
|
||||
return bool(hwnd) and win32gui.IsWindowVisible(hwnd)
|
||||
|
||||
|
||||
def _dt_is_dingtalk_foreground():
|
||||
"""钉钉主窗口是否已处于最前"""
|
||||
fg = win32gui.GetForegroundWindow()
|
||||
if not fg:
|
||||
return False
|
||||
title = win32gui.GetWindowText(fg) or ""
|
||||
return '钉钉' in title or 'DingTalk' in title
|
||||
|
||||
|
||||
def _dt_capture_region(x, y, w, h):
|
||||
"""截取屏幕指定区域,若区域无效则返回 None"""
|
||||
if w <= 0 or h <= 0:
|
||||
logger.warning("截图区域无效: (%s, %s, %s, %s),跳过", x, y, w, h)
|
||||
return None
|
||||
img = ImageGrab.grab(bbox=(x, y, x + w, y + h))
|
||||
if img is None or img.size[0] == 0 or img.size[1] == 0:
|
||||
logger.warning("抓取图像为空")
|
||||
return None
|
||||
return img
|
||||
|
||||
|
||||
def _dt_ocr_image(img):
|
||||
"""对图像进行 OCR 识别,返回 (text, (x1,y1,x2,y2)) 列表"""
|
||||
if img is None:
|
||||
return []
|
||||
img_np = np.array(img)
|
||||
result, _ = _dt_get_ocr()(img_np)
|
||||
ocr_data = []
|
||||
if result is not None:
|
||||
for box, text, score in result:
|
||||
xs = [p[0] for p in box]
|
||||
ys = [p[1] for p in box]
|
||||
x1, y1 = min(xs), min(ys)
|
||||
x2, y2 = max(xs), max(ys)
|
||||
ocr_data.append((text, (x1, y1, x2, y2)))
|
||||
return ocr_data
|
||||
|
||||
|
||||
def _dt_find_text_center(ocr_data, target_text):
|
||||
"""在 OCR 结果中查找包含 target_text 的文本框,返回中心坐标 (x, y)"""
|
||||
for text, (x1, y1, x2, y2) in ocr_data:
|
||||
if target_text in text:
|
||||
return (x1 + x2) // 2, (y1 + y2) // 2
|
||||
return None
|
||||
|
||||
|
||||
def _dt_wait_for_tab(hwnd, expected_tab, timeout=_DT_TIMEOUT):
|
||||
"""循环检测窗口顶部是否出现 expected_tab 标签(如“联系人”或“群组”)。"""
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO))
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
if _dt_find_text_center(ocr_data, expected_tab):
|
||||
logger.info("检测到'%s'标签", expected_tab)
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
logger.warning("未检测到'%s'标签", expected_tab)
|
||||
return False
|
||||
|
||||
|
||||
def _dt_is_chat_opened(hwnd, target_name):
|
||||
"""截取窗口顶部区域,OCR识别是否有目标名称"""
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO))
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
for text, _ in ocr_data:
|
||||
if target_name in text:
|
||||
logger.debug("标题识别到: '%s'", text)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _dt_search_and_open(hwnd, target_name, chat_type="联系人"):
|
||||
"""搜索并打开指定的联系人或群组会话。"""
|
||||
_dt_activate_window(hwnd)
|
||||
for attempt in range(_DT_SEARCH_RETRY):
|
||||
pyautogui.hotkey('ctrl', 'shift', 'f')
|
||||
time.sleep(0.8)
|
||||
pyautogui.hotkey('ctrl', 'a')
|
||||
pyautogui.press('delete')
|
||||
pyperclip.copy(target_name)
|
||||
pyautogui.hotkey('ctrl', 'v')
|
||||
time.sleep(0.5)
|
||||
pyautogui.press('enter')
|
||||
logger.info("搜索 '%s' (尝试 %d)", target_name, attempt + 1)
|
||||
time.sleep(0.8)
|
||||
if _dt_wait_for_tab(hwnd, chat_type, timeout=3):
|
||||
break
|
||||
else:
|
||||
pyautogui.press('esc')
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
logger.error("搜索框未正常打开")
|
||||
return False
|
||||
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO))
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
pos = _dt_find_text_center(ocr_data, chat_type)
|
||||
if pos:
|
||||
cx, cy = pos
|
||||
pyautogui.click(left + cx, top + cy)
|
||||
logger.info("点击'%s'标签", chat_type)
|
||||
else:
|
||||
logger.warning("未识别'%s'标签", chat_type)
|
||||
time.sleep(0.5)
|
||||
|
||||
pyautogui.press('enter')
|
||||
logger.info("打开第一个匹配项")
|
||||
time.sleep(1.5)
|
||||
|
||||
start = time.time()
|
||||
while time.time() - start < _DT_TIMEOUT:
|
||||
if _dt_is_chat_opened(hwnd, target_name):
|
||||
logger.info("成功进入会话 '%s'", target_name)
|
||||
return True
|
||||
_dt_activate_window(hwnd)
|
||||
time.sleep(0.5)
|
||||
logger.warning("未检测到会话名 '%s'", target_name)
|
||||
return False
|
||||
|
||||
|
||||
def _dt_find_input_box_by_ocr(hwnd):
|
||||
"""通过OCR识别“请输入消息”等提示文字,返回屏幕坐标"""
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
bottom_region_top = top + int(height * 0.6)
|
||||
bottom_region_height = int(height * 0.4)
|
||||
img = _dt_capture_region(left, bottom_region_top, width, bottom_region_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
keywords = ["请输入消息", "发送消息", "输入消息", "说点什么"]
|
||||
for keyword in keywords:
|
||||
pos = _dt_find_text_center(ocr_data, keyword)
|
||||
if pos:
|
||||
cx, cy = pos
|
||||
screen_x = left + cx
|
||||
screen_y = bottom_region_top + cy
|
||||
logger.info("定位输入框: '%s' 坐标 (%s, %s)", keyword, screen_x, screen_y)
|
||||
return screen_x, screen_y
|
||||
logger.warning("未识别到输入框提示")
|
||||
return None
|
||||
|
||||
|
||||
def _dt_focus_input_box(hwnd):
|
||||
"""定位并点击输入框,使其获得焦点"""
|
||||
input_pos = _dt_find_input_box_by_ocr(hwnd)
|
||||
if input_pos:
|
||||
pyautogui.click(input_pos[0], input_pos[1])
|
||||
return True
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
pyautogui.click(left + width // 2, top + height - 60)
|
||||
logger.warning("使用固定坐标点击输入框")
|
||||
return False
|
||||
|
||||
|
||||
def _dt_send_hotkey_to_activate():
|
||||
"""模拟按下全局快捷键 Ctrl+Alt+D 以激活钉钉窗口"""
|
||||
logger.info("尝试快捷键 Ctrl+Alt+D 激活")
|
||||
pyautogui.hotkey('ctrl', 'alt', 'd')
|
||||
time.sleep(0.8)
|
||||
|
||||
|
||||
def _dt_is_dingtalk_activated(hwnd, target_name=None):
|
||||
"""通过 OCR 检测钉钉窗口是否已激活到前台(主界面可见)。"""
|
||||
try:
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
if width <= 0 or height <= 0:
|
||||
return False
|
||||
top_height = max(50, int(height * 0.18))
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
if img is None:
|
||||
return False
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
if target_name:
|
||||
for text, _ in ocr_data:
|
||||
if target_name in text:
|
||||
return True
|
||||
main_keywords = ["搜索或提问", "消息", "未读", "搜索", "提问"]
|
||||
for kw in main_keywords:
|
||||
for text, _ in ocr_data:
|
||||
if kw in text:
|
||||
return True
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.warning("激活检测异常: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def _dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10):
|
||||
"""多策略确保钉钉窗口激活到前台(快捷键→Win32 API→组合)。"""
|
||||
def wait_for_valid_rect(hwnd, max_wait=1.5):
|
||||
end = time.time() + max_wait
|
||||
while time.time() < end:
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
if (right - left) > 0 and (bottom - top) > 0:
|
||||
return True
|
||||
time.sleep(0.2)
|
||||
return False
|
||||
|
||||
def find_current():
|
||||
return _dt_find_dingtalk_window(include_hidden=True) or hwnd
|
||||
|
||||
def verify(hwnd):
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
if _dt_is_dingtalk_activated(hwnd, target_name=None):
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
if _dt_is_dingtalk_foreground():
|
||||
logger.info("钉钉已在最前,跳过激活")
|
||||
return True
|
||||
|
||||
if not _dt_is_dingtalk_main_visible():
|
||||
_dt_send_hotkey_to_activate()
|
||||
cur = find_current()
|
||||
if cur and wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("快捷键激活成功")
|
||||
win32gui.SetForegroundWindow(cur)
|
||||
return True
|
||||
logger.warning("快捷键后窗口尺寸无效")
|
||||
else:
|
||||
logger.info("窗口已可见,跳过切换快捷键(避免将其隐藏)")
|
||||
|
||||
logger.info("尝试 Win32 API 激活")
|
||||
cur = find_current()
|
||||
if cur:
|
||||
_dt_activate_window(cur)
|
||||
if wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("API激活成功")
|
||||
return True
|
||||
logger.warning("API后窗口尺寸无效")
|
||||
|
||||
logger.info("组合激活")
|
||||
if not _dt_is_dingtalk_main_visible():
|
||||
_dt_send_hotkey_to_activate()
|
||||
time.sleep(0.5)
|
||||
cur = find_current()
|
||||
if cur:
|
||||
_dt_activate_window(cur)
|
||||
time.sleep(1)
|
||||
if wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("组合激活成功")
|
||||
return True
|
||||
|
||||
raise RuntimeError("所有激活策略失败")
|
||||
|
||||
|
||||
def _dt_find_hwnd_or_raise():
|
||||
"""查找钉钉窗口,失败时给出可读的错误信息。"""
|
||||
hwnd = _dt_find_dingtalk_window(include_hidden=True)
|
||||
if not hwnd:
|
||||
dingtalk_running = any(p.name().lower() == 'dingtalk.exe' for p in psutil.process_iter())
|
||||
if not dingtalk_running:
|
||||
raise RuntimeError("钉钉进程未运行,请手动启动并登录")
|
||||
else:
|
||||
raise RuntimeError("找到进程但无窗口,请手动激活")
|
||||
return hwnd
|
||||
|
||||
|
||||
def _dt_send_text_to_person(name, text):
|
||||
"""向指定联系人发送文本(OCR 视觉方案):查找窗口→多策略激活→搜索打开会话→定位输入框→粘贴发送。"""
|
||||
if not text or not text.strip():
|
||||
raise ValueError("text 不能为空")
|
||||
|
||||
for attempt in range(_DT_RETRY_TIMES):
|
||||
try:
|
||||
hwnd = _dt_find_hwnd_or_raise()
|
||||
_dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10)
|
||||
hwnd = _dt_find_dingtalk_window(include_hidden=True) or hwnd
|
||||
|
||||
if not _dt_search_and_open(hwnd, name, "联系人"):
|
||||
raise RuntimeError("打开联系人会话失败")
|
||||
|
||||
_dt_focus_input_box(hwnd)
|
||||
time.sleep(0.3)
|
||||
|
||||
pyperclip.copy(text)
|
||||
pyautogui.hotkey('ctrl', 'v')
|
||||
time.sleep(0.2)
|
||||
pyautogui.press('enter')
|
||||
logger.info("发送成功:%s...", text[:30])
|
||||
return True
|
||||
|
||||
except RuntimeError as e:
|
||||
logger.error(str(e))
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error("第%d次尝试失败:%s", attempt + 1, e)
|
||||
time.sleep(2)
|
||||
|
||||
raise RuntimeError(f"重试 {_DT_RETRY_TIMES} 次后失败")
|
||||
|
||||
|
||||
def _send_dingtalk_text(target, text):
|
||||
"""推送文本到钉钉联系人(OCR 视觉方案,与 app/utils/dingtalk_sender.py 行为一致)。"""
|
||||
_dt_send_text_to_person(target, text)
|
||||
push_type 推送类型:"group" 群消息(仅 text,钉钉群机器人 webhook 推送);
|
||||
"person" 单聊(含 target,钉钉联系人 OCR 推送)。
|
||||
"""
|
||||
messages = []
|
||||
for text in texts:
|
||||
msg = {"text": text}
|
||||
if push_type == "person":
|
||||
msg["target"] = target
|
||||
messages.append(msg)
|
||||
return messages
|
||||
|
||||
|
||||
def build_push_summary(results, subject=""):
|
||||
"""
|
||||
根据校验结果生成钉钉推送文字消息(多行)。
|
||||
通过/驳回/人工复核三组均以文字说明推送。无业务结果时返回空串。
|
||||
根据校验结果生成推送消息文字(多行)。
|
||||
通过/驳回/人工复核三组均以文字说明。无业务结果时返回空串。
|
||||
"""
|
||||
if not results:
|
||||
return ""
|
||||
@@ -1399,29 +948,6 @@ def build_push_summary(results, subject=""):
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def push_report(report, subject=""):
|
||||
"""推送审批报告到钉钉联系人(env 控制,失败不影响主流程)。"""
|
||||
load_dotenv()
|
||||
if not report or not report.strip():
|
||||
logger.info("[%s] 无推送内容(无通过项),跳过钉钉推送", subject)
|
||||
return False
|
||||
enabled = os.getenv("dingtalk_notify_enabled", "false").lower() == "true"
|
||||
if not enabled:
|
||||
logger.info("[%s] 钉钉推送未开启(dingtalk_notify_enabled!=true),跳过", subject)
|
||||
return False
|
||||
target = os.getenv("dingtalk_notify_target", "").strip()
|
||||
if not target:
|
||||
logger.warning("[%s] 未配置 dingtalk_notify_target,跳过钉钉推送", subject)
|
||||
return False
|
||||
try:
|
||||
_send_dingtalk_text(target, report)
|
||||
logger.info("[%s] 审批报告已推送至钉钉: %s", subject, target)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("[%s] 钉钉推送失败: %s", subject, e)
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 真实审批提交 ====================
|
||||
# 影刀环境无 .env 文件,开关直接写死在代码中;如需临时关闭自动审批改为 False
|
||||
APPROVE_ENABLED = True
|
||||
@@ -1497,16 +1023,34 @@ def submit_approval(page, decision):
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
|
||||
|
||||
def run_flow(subject, validate_doc, generate_report):
|
||||
def run_flow(subject, validate_doc, generate_report, push_type="group", target=None):
|
||||
"""请假审批主流程;返回生成的推送消息列表(字典列表,本脚本不发送)。
|
||||
|
||||
push_type 推送类型:"group" 群消息(钉钉群机器人 webhook);"person" 单聊(钉钉联系人 OCR 推送)。
|
||||
target 单聊推送目标(联系人),仅 push_type="person" 时使用。
|
||||
"""
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
# 运行中遇 OA 登录态失效(待办/表单接口返回登录页):删除 cookie、自动重新登录并重跑一遍(最多 2 轮)
|
||||
# 运行中遇 OA 登录态失效(待办/表单接口返回登录页):调用共享登录模块强制重登并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
# 先用纯接口 SessionPage(不开浏览器)拉待办;无单据则全程不启动浏览器
|
||||
session = build_session(subject)
|
||||
browser = None
|
||||
try:
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
# 无待办单据:不开浏览器,直接生成提示消息返回
|
||||
if not docs:
|
||||
logger.info("%s无待审批单据,跳过浏览器操作", subject)
|
||||
push_messages = _build_push_messages([f"暂无待审批的{subject}单据"], push_type, target)
|
||||
logger.info("%s审批流程结束,共处理 0 条(无单据)", subject)
|
||||
return push_messages
|
||||
|
||||
# 有单据才启动浏览器:SSO 跳转解析 / 真实审批提交 / 结果弹窗
|
||||
browser = build_browser(subject)
|
||||
refresh_session_cookies(session, browser)
|
||||
|
||||
results = []
|
||||
for doc in docs:
|
||||
try:
|
||||
@@ -1546,26 +1090,31 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
|
||||
# 有驳回/人工复核/失败时,再推送完整报告(含明细表格)
|
||||
# 生成推送消息文本(本脚本不发送,交由流程/消息推送模块):
|
||||
# 摘要 + 有驳回/人工复核/失败时追加完整报告(含明细)
|
||||
texts = []
|
||||
summary = build_push_summary(results, subject)
|
||||
if summary:
|
||||
texts.append(summary)
|
||||
has_detail = any(r.get("decision") != "通过" for r in results)
|
||||
if has_detail:
|
||||
push_report(report, subject)
|
||||
texts.append(report)
|
||||
# 无任何待办/结果时也生成一条提示消息,避免静默不推送
|
||||
if not texts:
|
||||
texts.append(f"暂无待审批的{subject}单据")
|
||||
push_messages = _build_push_messages(texts, push_type, target)
|
||||
|
||||
save_browser_cookies(browser)
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return report
|
||||
return push_messages
|
||||
except OALoginExpiredError as e:
|
||||
logger.warning("OA 登录态失效: %s", e)
|
||||
if login_attempt == 0:
|
||||
# cookies 由共享登录指令维护,这里仅强制重登(重写共享 cookies)后重跑
|
||||
try:
|
||||
if os.path.exists(COOKIE_FILE):
|
||||
os.remove(COOKIE_FILE)
|
||||
logger.info("已删除失效 cookie,自动重新登录后重跑")
|
||||
except Exception:
|
||||
pass
|
||||
_ensure_oa_cookies(force=True)
|
||||
logger.info("已强制调用共享登录模块重登,重新跑一遍")
|
||||
except Exception as e2:
|
||||
logger.error("强制重登失败: %s", e2)
|
||||
continue
|
||||
raise
|
||||
finally:
|
||||
@@ -1881,9 +1430,33 @@ def generate_report(results):
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def main():
|
||||
"""请假审批:登录 -> 查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告"""
|
||||
run_flow(subject="请假", validate_doc=validate_doc, generate_report=generate_report)
|
||||
def main(push_type="group", target=None):
|
||||
"""请假审批:登录 -> 查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告 -> 生成推送消息。
|
||||
|
||||
push_type 推送类型:"group" 群消息(缺省,写入全局变量 messages 为纯文本,
|
||||
直接交给钉钉群机器人 webhook 推送);
|
||||
"person" 单聊(钉钉联系人 OCR 推送,需配合 target)
|
||||
target 单聊推送目标(联系人),仅 push_type="person" 时使用
|
||||
返回:推送消息列表(字典列表,本脚本不发送);同时把纯文本写入全局变量 messages。
|
||||
"""
|
||||
push_type = str(push_type or "group").lower()
|
||||
if push_type == "person" and not target:
|
||||
logger.warning("push_type=person 但未提供 target,已按群消息(group)处理")
|
||||
push_type = "group"
|
||||
push_messages = run_flow(
|
||||
subject="请假",
|
||||
validate_doc=validate_doc,
|
||||
generate_report=generate_report,
|
||||
push_type=push_type,
|
||||
target=target,
|
||||
)
|
||||
# 写入影刀全局变量 messages(纯文本,多段用空行分隔),
|
||||
# 供「37du钉钉群机器人推送」指令直接读取发送;本地独立运行时静默跳过
|
||||
_set_glv("messages", "\n\n".join(
|
||||
str(m.get("text", "") or "").strip()
|
||||
for m in push_messages if str(m.get("text", "") or "").strip()
|
||||
))
|
||||
return push_messages
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -1,22 +1,27 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: overtime_approval_yingdao.py
|
||||
@FileName: overtime_approval.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06
|
||||
@Description: 加班审批流程(影刀单文件版)- 合并自原项目 13 个模块
|
||||
@Version: 1.0.0
|
||||
@Description: 加班审批流程(影刀单文件版)- 合并自原项目 13 个模块,业务逻辑完全一致
|
||||
@Version: 2.0.0
|
||||
|
||||
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install DrissionPage python-dotenv chinese_calendar pyautogui pywin32 pyperclip
|
||||
pip install Pillow numpy rapidocr-onnxruntime psutil
|
||||
pip install DrissionPage python-dotenv chinese_calendar
|
||||
|
||||
环境变量(.env 文件或系统变量):
|
||||
oa_login_url=登录页URL
|
||||
oa_target_url_keyword=登录成功后URL关键字
|
||||
oa_login_username=用户名
|
||||
oa_login_password=密码
|
||||
dingtalk_notify_enabled=true|false(默认 false,是否推送审批结果到钉钉)
|
||||
dingtalk_notify_target=钉钉联系人姓名(如 夏一平)
|
||||
登录(共享登录态,本脚本为单文件自包含):
|
||||
- 登录态统一由「37duOA登录」影刀自定义指令写入共享 cookies:
|
||||
%LOCALAPPDATA%\37duAutomation\.sessions\oa_cookies.json
|
||||
- 本脚本仅读取该 cookies 文件,不 import 任何共享模块;缺失/失效时
|
||||
报错提示先运行登录指令(影刀流程开头请先拖入「37duOA登录」指令)。
|
||||
|
||||
推送消息(本脚本不发送任何消息,只负责生成文本):
|
||||
- 本脚本不内联任何消息推送逻辑;仅生成待推送的文本消息,经 main() 写入影刀全局变量
|
||||
messages(纯文本,多段用空行分隔),由「37du钉钉群机器人推送」指令直接读取发送;
|
||||
本地独立运行时静默跳过写全局变量;
|
||||
- main(push_type, target):
|
||||
push_type="group"(默认)群消息:全局变量 messages 为纯文本,直接交钉钉群机器人 webhook 推送;
|
||||
push_type="person" 单聊:main 返回值仍为 {target, text} 列表,可交给「37du钉钉推送」指令走 OCR 单聊。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
@@ -29,7 +34,7 @@ import random
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
from typing import Callable
|
||||
from urllib.parse import urlencode, urlparse, parse_qs
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
|
||||
@@ -37,36 +42,22 @@ from urllib.parse import urlencode, urlparse, parse_qs
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, SessionPage
|
||||
from dotenv import load_dotenv
|
||||
import pyautogui
|
||||
import win32gui
|
||||
import win32con
|
||||
import win32clipboard
|
||||
import win32process
|
||||
import win32api
|
||||
import pyperclip
|
||||
import psutil
|
||||
import chinese_calendar as cc
|
||||
import numpy as np
|
||||
from PIL import ImageGrab
|
||||
from rapidocr_onnxruntime import RapidOCR
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install DrissionPage python-dotenv chinese_calendar pyautogui pywin32 pyperclip\n"
|
||||
" pip install Pillow numpy rapidocr-onnxruntime psutil\n"
|
||||
" pip install DrissionPage python-dotenv chinese_calendar\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
# 模块加载时即读取 .env,避免复用已保存会话(跳过 oa_login)时环境变量未加载
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 数据目录固定放在 AppData\Local\37duAutomation,不依赖脚本位置,每台电脑都有(影刀版独立子目录)
|
||||
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), '37duAutomation', 'OvertimeApproval')
|
||||
# 数据目录固定放在 AppData\Local\37duAutomation,不依赖脚本位置,每台电脑都有;
|
||||
# 登录态与共享 .env 统一由「37duOA登录」影刀自定义指令写入(见 yingdao/share/oa_login.py)
|
||||
_APP_DATA_DIR = os.path.join(os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), '37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
# ---------- OA 系统 ----------
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
@@ -137,6 +128,14 @@ class _PrintLogger:
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
def _set_glv(name, value):
|
||||
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
|
||||
try:
|
||||
glv[name] = value
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 重试装饰器 ====================
|
||||
class RetryExhaustedError(Exception):
|
||||
pass
|
||||
@@ -555,69 +554,29 @@ def parse_overtime_form(result):
|
||||
return overtime_info
|
||||
|
||||
|
||||
# ==================== 会话管理 ====================
|
||||
def init_session_from_page(browser_page, copy_headers=True):
|
||||
session = SessionPage()
|
||||
cookies_dict = browser_page.cookies(all_domains=True)
|
||||
if cookies_dict:
|
||||
session.set.cookies(cookies_dict)
|
||||
logger.info("已复制 %d 个 Cookies 到 SessionPage", len(cookies_dict))
|
||||
else:
|
||||
logger.warning("未获取到 Cookies,请确认浏览器已登录")
|
||||
|
||||
if copy_headers:
|
||||
headers = {"User-Agent": browser_page.run_js("return navigator.userAgent;")}
|
||||
session.set.headers(headers)
|
||||
logger.info("已复制 User-Agent: %s...", headers['User-Agent'][:50])
|
||||
|
||||
session.set.timeout(10)
|
||||
return session
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
# 登录态统一由「37duOA登录」影刀自定义指令维护(见 yingdao/share/oa_login.py),
|
||||
# 本脚本为单文件自包含:仅读取共享 cookies 文件,不 import 任何共享模块。
|
||||
# cookies 缺失/失效时提示先运行登录指令,不再内联调用共享登录模块。
|
||||
|
||||
|
||||
def refresh_session_cookies(session, browser_page):
|
||||
cookies = browser_page.cookies(all_domains=True)
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
logger.info("已同步 %d 个 Cookies 到 SessionPage(含 SSO 会话)", len(cookies))
|
||||
else:
|
||||
logger.warning("未获取到 Cookies,请确认浏览器登录态")
|
||||
|
||||
|
||||
def save_browser_cookies(browser_page, path=COOKIE_FILE):
|
||||
cookies = browser_page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
logger.warning("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
logger.info("已保存 %d 个 Cookies 到 %s", len(cookies), path)
|
||||
|
||||
|
||||
def load_cookies(path=COOKIE_FILE):
|
||||
if not os.path.exists(path):
|
||||
def _load_shared_oa_cookies():
|
||||
"""读取共享 OA 登录 cookies(由「37duOA登录」影刀自定义指令写入)。"""
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(path, encoding='utf-8') as f:
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
def load_saved_session(path=COOKIE_FILE):
|
||||
cookies = load_cookies(path)
|
||||
if not cookies:
|
||||
return None
|
||||
session = SessionPage()
|
||||
session.set.cookies(cookies)
|
||||
session.set.timeout(10)
|
||||
return session
|
||||
|
||||
|
||||
def create_browser_with_saved_cookies(path=COOKIE_FILE):
|
||||
browser = ChromiumPage()
|
||||
cookies = load_cookies(path)
|
||||
if cookies:
|
||||
browser.set.cookies(cookies)
|
||||
return browser
|
||||
def _ensure_oa_cookies(force=False):
|
||||
"""确保存在有效的 OA 登录态文件(由「37duOA登录」指令写入);缺失时提示先运行登录指令。"""
|
||||
if not force and _load_shared_oa_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 OA 登录态(oa_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duOA登录」指令,或本地先运行 "
|
||||
"python yingdao/share/oa_login.py")
|
||||
|
||||
|
||||
def is_session_valid(session, subject="加班"):
|
||||
@@ -635,62 +594,50 @@ def is_session_valid(session, subject="加班"):
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 登录 ====================
|
||||
@retry(max_attempts=3)
|
||||
def oa_login(username=None, password=None, timeout=10, wait_after_load=2):
|
||||
load_dotenv()
|
||||
def refresh_session_cookies(session, browser_page):
|
||||
cookies = browser_page.cookies(all_domains=True)
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
logger.info("已同步 %d 个 Cookies 到 SessionPage(含 SSO 会话)", len(cookies))
|
||||
else:
|
||||
logger.warning("未获取到 Cookies,请确认浏览器登录态")
|
||||
|
||||
login_url = os.getenv('oa_login_url')
|
||||
if not login_url:
|
||||
raise RuntimeError("环境变量 oa_login_url 未设置")
|
||||
target_url_keyword = os.getenv('oa_target_url_keyword')
|
||||
if not target_url_keyword:
|
||||
raise RuntimeError("环境变量 oa_target_url_keyword 未设置")
|
||||
|
||||
final_username = username or os.getenv('oa_login_username')
|
||||
final_password = password or os.getenv('oa_login_password')
|
||||
if not final_username or not final_password:
|
||||
raise RuntimeError("用户名或密码未提供,请设置环境变量或传入参数")
|
||||
def build_session(subject):
|
||||
"""仅构建 SessionPage(不启动浏览器),从共享 cookies 填充登录态。
|
||||
|
||||
page = ChromiumPage()
|
||||
用于查待办、拉表单等纯接口操作;会话失效时调用共享登录指令强制重登后重建。
|
||||
"""
|
||||
_ensure_oa_cookies()
|
||||
session = SessionPage()
|
||||
session.set.timeout(10)
|
||||
cookies = _load_shared_oa_cookies()
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
if is_session_valid(session, subject):
|
||||
return session
|
||||
logger.warning("共享登录态已失效,强制重登")
|
||||
_ensure_oa_cookies(force=True)
|
||||
cookies = _load_shared_oa_cookies()
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
return session
|
||||
|
||||
try:
|
||||
page.get(login_url)
|
||||
time.sleep(wait_after_load)
|
||||
|
||||
username_input = page.ele('tag:input@name=j_username')
|
||||
if not username_input:
|
||||
raise RuntimeError("未找到用户名输入框")
|
||||
username_input.input(final_username)
|
||||
page.wait(0.5)
|
||||
def build_browser(subject):
|
||||
"""有单据时才启动浏览器(SSO 跳转解析 / 真实审批点击 / 结果弹窗用),并填充共享 cookies。"""
|
||||
_ensure_oa_cookies()
|
||||
browser = ChromiumPage()
|
||||
cookies = _load_shared_oa_cookies()
|
||||
if cookies:
|
||||
browser.set.cookies(cookies)
|
||||
return browser
|
||||
|
||||
password_input = page.ele('tag:input@name=j_password')
|
||||
if not password_input:
|
||||
raise RuntimeError("未找到密码输入框")
|
||||
password_input.input(final_password)
|
||||
page.wait(0.5)
|
||||
|
||||
login_button = page.ele('.lui_login_button_div_c')
|
||||
if not login_button:
|
||||
raise RuntimeError("未找到登录按钮")
|
||||
login_button.click()
|
||||
page.wait(0.5)
|
||||
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
if target_url_keyword in page.url:
|
||||
logger.info("登录成功!当前 URL: %s", page.url)
|
||||
return page
|
||||
time.sleep(0.5)
|
||||
|
||||
error_elem = page.ele('.error-msg') or page.ele('.alert-danger')
|
||||
if error_elem:
|
||||
logger.warning("登录失败,提示: %s", error_elem.text)
|
||||
raise RuntimeError(f"登录超时,当前 URL: {page.url}")
|
||||
|
||||
except Exception as e:
|
||||
page.quit()
|
||||
raise RuntimeError(f"登录过程出错: {e}")
|
||||
# ==================== 登录(共享) ====================
|
||||
# 登录态统一由「37duOA登录」影刀自定义指令维护(见 yingdao/share/oa_login.py),
|
||||
# 本脚本通过 build_session()/build_browser() 复用共享 cookies,不再内联账号密码登录代码;
|
||||
# 无待办单据时不启动浏览器(build_session 纯接口即可),仅在确有单据时才开浏览器。
|
||||
|
||||
|
||||
# ==================== SSO 解析 ====================
|
||||
@@ -713,19 +660,6 @@ def resolve_sso_params(browser, sso_url, wait_timeout=20):
|
||||
|
||||
|
||||
# ==================== 审批引擎 ====================
|
||||
def _get_browser_and_session(subject):
|
||||
saved_session = load_saved_session()
|
||||
if saved_session is not None and is_session_valid(saved_session, subject):
|
||||
logger.info("复用已保存的登录会话,跳过登录")
|
||||
browser = create_browser_with_saved_cookies()
|
||||
return browser, saved_session, False
|
||||
|
||||
browser = oa_login()
|
||||
session = init_session_from_page(browser)
|
||||
save_browser_cookies(browser)
|
||||
return browser, session, True
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(OALoginExpiredError,))
|
||||
def _fetch_documents(session, subject):
|
||||
return get_documents(session, subject=subject)
|
||||
@@ -823,420 +757,24 @@ def show_rpa_result_popup(page: ChromiumPage,
|
||||
time.sleep(stay_seconds)
|
||||
|
||||
|
||||
|
||||
# ==================== 钉钉推送(OCR 视觉方案内联,保持单文件自包含) ====================
|
||||
# 内联自 app/utils/dingtalk_sender.py(视觉方案),相比旧固定坐标模拟大幅提升稳定性:
|
||||
# 窗口查找排除 0 尺寸阴影/辅助窗口,只认主窗口;多策略激活(快捷键→Win32 API→组合);
|
||||
# 搜索框/标签/输入框全部通过 OCR 校验后再操作。
|
||||
_DT_TIMEOUT = 8
|
||||
_DT_SEARCH_RETRY = 3
|
||||
_DT_RETRY_TIMES = 3
|
||||
_DT_TOP_HEIGHT_RATIO = 0.18
|
||||
|
||||
_dt_ocr = None
|
||||
# ==================== 推送消息生成(不发送,交由推送指令) ====================
|
||||
# 本脚本不发送任何消息:仅把审批结果拼成文本消息(默认群消息,只含 text;
|
||||
# 传 push_type="person" 时生成含 target 的单聊消息),经 main() 把纯文本写入影刀全局变量 messages。
|
||||
|
||||
|
||||
def _dt_get_ocr():
|
||||
"""获取 RapidOCR 实例(单例;若模块已初始化 _ocr_engine 则复用,避免重复加载模型)。"""
|
||||
global _dt_ocr
|
||||
# 用 globals().get 而非直接读 _dt_ocr:避免个别运行环境/旧 pyc 下模块级 _dt_ocr 未定义时抛 NameError
|
||||
_dt_ocr = globals().get("_dt_ocr")
|
||||
if _dt_ocr is None:
|
||||
_dt_ocr = globals().get("_ocr_engine") or RapidOCR()
|
||||
return _dt_ocr
|
||||
def _build_push_messages(texts, push_type="group", target=None):
|
||||
"""把文本列表转成推送消息列表(字典列表)。
|
||||
|
||||
|
||||
def _dt_get_process_name_by_pid(pid):
|
||||
"""根据进程 ID 获取进程名称,失败返回 None"""
|
||||
try:
|
||||
return psutil.Process(pid).name()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _dt_find_dingtalk_window(include_hidden=True):
|
||||
"""查找钉钉“主窗口”句柄(排除 0 尺寸阴影/辅助窗口,只认 DingTalk 进程或主标题)。"""
|
||||
def has_valid_rect(hwnd):
|
||||
try:
|
||||
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
|
||||
return (right - left) > 0 and (bottom - top) > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def is_main_title(hwnd):
|
||||
return win32gui.GetWindowText(hwnd) in ('钉钉', 'DingTalk')
|
||||
|
||||
candidates = []
|
||||
def enum_callback(hwnd, _):
|
||||
if not include_hidden and not win32gui.IsWindowVisible(hwnd):
|
||||
return True
|
||||
title = win32gui.GetWindowText(hwnd)
|
||||
if title == '钉钉' or title == 'DingTalk':
|
||||
candidates.append(hwnd)
|
||||
return True
|
||||
try:
|
||||
_, pid = win32process.GetWindowThreadProcessId(hwnd)
|
||||
proc_name = _dt_get_process_name_by_pid(pid)
|
||||
if proc_name and proc_name.lower() == 'dingtalk.exe':
|
||||
candidates.append(hwnd)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
win32gui.EnumWindows(enum_callback, None)
|
||||
|
||||
valid = [h for h in candidates if has_valid_rect(h)]
|
||||
if not valid:
|
||||
return None
|
||||
for h in valid:
|
||||
if is_main_title(h) and win32gui.IsWindowVisible(h):
|
||||
return h
|
||||
for h in valid:
|
||||
if is_main_title(h):
|
||||
return h
|
||||
for h in valid:
|
||||
if win32gui.IsWindowVisible(h):
|
||||
return h
|
||||
return valid[0]
|
||||
|
||||
|
||||
def _dt_activate_window(hwnd):
|
||||
"""强制激活窗口(最小化、隐藏、托盘均可恢复)"""
|
||||
if win32gui.IsIconic(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
|
||||
time.sleep(0.3)
|
||||
if not win32gui.IsWindowVisible(hwnd):
|
||||
win32gui.ShowWindow(hwnd, win32con.SW_SHOW)
|
||||
time.sleep(0.3)
|
||||
win32gui.SetForegroundWindow(hwnd)
|
||||
win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_KEYUP, 0)
|
||||
time.sleep(0.3)
|
||||
|
||||
|
||||
def _dt_get_window_rect(hwnd):
|
||||
"""获取窗口矩形 (left, top, right, bottom)"""
|
||||
return win32gui.GetWindowRect(hwnd)
|
||||
|
||||
|
||||
def _dt_is_dingtalk_main_visible():
|
||||
"""钉钉主窗口当前是否可见"""
|
||||
hwnd = _dt_find_dingtalk_window(include_hidden=True)
|
||||
return bool(hwnd) and win32gui.IsWindowVisible(hwnd)
|
||||
|
||||
|
||||
def _dt_is_dingtalk_foreground():
|
||||
"""钉钉主窗口是否已处于最前"""
|
||||
fg = win32gui.GetForegroundWindow()
|
||||
if not fg:
|
||||
return False
|
||||
title = win32gui.GetWindowText(fg) or ""
|
||||
return '钉钉' in title or 'DingTalk' in title
|
||||
|
||||
|
||||
def _dt_capture_region(x, y, w, h):
|
||||
"""截取屏幕指定区域,若区域无效则返回 None"""
|
||||
if w <= 0 or h <= 0:
|
||||
logger.warning("截图区域无效: (%s, %s, %s, %s),跳过", x, y, w, h)
|
||||
return None
|
||||
img = ImageGrab.grab(bbox=(x, y, x + w, y + h))
|
||||
if img is None or img.size[0] == 0 or img.size[1] == 0:
|
||||
logger.warning("抓取图像为空")
|
||||
return None
|
||||
return img
|
||||
|
||||
|
||||
def _dt_ocr_image(img):
|
||||
"""对图像进行 OCR 识别,返回 (text, (x1,y1,x2,y2)) 列表"""
|
||||
if img is None:
|
||||
return []
|
||||
img_np = np.array(img)
|
||||
result, _ = _dt_get_ocr()(img_np)
|
||||
ocr_data = []
|
||||
if result is not None:
|
||||
for box, text, score in result:
|
||||
xs = [p[0] for p in box]
|
||||
ys = [p[1] for p in box]
|
||||
x1, y1 = min(xs), min(ys)
|
||||
x2, y2 = max(xs), max(ys)
|
||||
ocr_data.append((text, (x1, y1, x2, y2)))
|
||||
return ocr_data
|
||||
|
||||
|
||||
def _dt_find_text_center(ocr_data, target_text):
|
||||
"""在 OCR 结果中查找包含 target_text 的文本框,返回中心坐标 (x, y)"""
|
||||
for text, (x1, y1, x2, y2) in ocr_data:
|
||||
if target_text in text:
|
||||
return (x1 + x2) // 2, (y1 + y2) // 2
|
||||
return None
|
||||
|
||||
|
||||
def _dt_wait_for_tab(hwnd, expected_tab, timeout=_DT_TIMEOUT):
|
||||
"""循环检测窗口顶部是否出现 expected_tab 标签(如“联系人”或“群组”)。"""
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO))
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
if _dt_find_text_center(ocr_data, expected_tab):
|
||||
logger.info("检测到'%s'标签", expected_tab)
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
logger.warning("未检测到'%s'标签", expected_tab)
|
||||
return False
|
||||
|
||||
|
||||
def _dt_is_chat_opened(hwnd, target_name):
|
||||
"""截取窗口顶部区域,OCR识别是否有目标名称"""
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO))
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
for text, _ in ocr_data:
|
||||
if target_name in text:
|
||||
logger.debug("标题识别到: '%s'", text)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _dt_search_and_open(hwnd, target_name, chat_type="联系人"):
|
||||
"""搜索并打开指定的联系人或群组会话。"""
|
||||
_dt_activate_window(hwnd)
|
||||
for attempt in range(_DT_SEARCH_RETRY):
|
||||
pyautogui.hotkey('ctrl', 'shift', 'f')
|
||||
time.sleep(0.8)
|
||||
pyautogui.hotkey('ctrl', 'a')
|
||||
pyautogui.press('delete')
|
||||
pyperclip.copy(target_name)
|
||||
pyautogui.hotkey('ctrl', 'v')
|
||||
time.sleep(0.5)
|
||||
pyautogui.press('enter')
|
||||
logger.info("搜索 '%s' (尝试 %d)", target_name, attempt + 1)
|
||||
time.sleep(0.8)
|
||||
if _dt_wait_for_tab(hwnd, chat_type, timeout=3):
|
||||
break
|
||||
else:
|
||||
pyautogui.press('esc')
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
logger.error("搜索框未正常打开")
|
||||
return False
|
||||
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO))
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
pos = _dt_find_text_center(ocr_data, chat_type)
|
||||
if pos:
|
||||
cx, cy = pos
|
||||
pyautogui.click(left + cx, top + cy)
|
||||
logger.info("点击'%s'标签", chat_type)
|
||||
else:
|
||||
logger.warning("未识别'%s'标签", chat_type)
|
||||
time.sleep(0.5)
|
||||
|
||||
pyautogui.press('enter')
|
||||
logger.info("打开第一个匹配项")
|
||||
time.sleep(1.5)
|
||||
|
||||
start = time.time()
|
||||
while time.time() - start < _DT_TIMEOUT:
|
||||
if _dt_is_chat_opened(hwnd, target_name):
|
||||
logger.info("成功进入会话 '%s'", target_name)
|
||||
return True
|
||||
_dt_activate_window(hwnd)
|
||||
time.sleep(0.5)
|
||||
logger.warning("未检测到会话名 '%s'", target_name)
|
||||
return False
|
||||
|
||||
|
||||
def _dt_find_input_box_by_ocr(hwnd):
|
||||
"""通过OCR识别“请输入消息”等提示文字,返回屏幕坐标"""
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
bottom_region_top = top + int(height * 0.6)
|
||||
bottom_region_height = int(height * 0.4)
|
||||
img = _dt_capture_region(left, bottom_region_top, width, bottom_region_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
keywords = ["请输入消息", "发送消息", "输入消息", "说点什么"]
|
||||
for keyword in keywords:
|
||||
pos = _dt_find_text_center(ocr_data, keyword)
|
||||
if pos:
|
||||
cx, cy = pos
|
||||
screen_x = left + cx
|
||||
screen_y = bottom_region_top + cy
|
||||
logger.info("定位输入框: '%s' 坐标 (%s, %s)", keyword, screen_x, screen_y)
|
||||
return screen_x, screen_y
|
||||
logger.warning("未识别到输入框提示")
|
||||
return None
|
||||
|
||||
|
||||
def _dt_focus_input_box(hwnd):
|
||||
"""定位并点击输入框,使其获得焦点"""
|
||||
input_pos = _dt_find_input_box_by_ocr(hwnd)
|
||||
if input_pos:
|
||||
pyautogui.click(input_pos[0], input_pos[1])
|
||||
return True
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
pyautogui.click(left + width // 2, top + height - 60)
|
||||
logger.warning("使用固定坐标点击输入框")
|
||||
return False
|
||||
|
||||
|
||||
def _dt_send_hotkey_to_activate():
|
||||
"""模拟按下全局快捷键 Ctrl+Alt+D 以激活钉钉窗口"""
|
||||
logger.info("尝试快捷键 Ctrl+Alt+D 激活")
|
||||
pyautogui.hotkey('ctrl', 'alt', 'd')
|
||||
time.sleep(0.8)
|
||||
|
||||
|
||||
def _dt_is_dingtalk_activated(hwnd, target_name=None):
|
||||
"""通过 OCR 检测钉钉窗口是否已激活到前台(主界面可见)。"""
|
||||
try:
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
width = right - left
|
||||
height = bottom - top
|
||||
if width <= 0 or height <= 0:
|
||||
return False
|
||||
top_height = max(50, int(height * 0.18))
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
if img is None:
|
||||
return False
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
if target_name:
|
||||
for text, _ in ocr_data:
|
||||
if target_name in text:
|
||||
return True
|
||||
main_keywords = ["搜索或提问", "消息", "未读", "搜索", "提问"]
|
||||
for kw in main_keywords:
|
||||
for text, _ in ocr_data:
|
||||
if kw in text:
|
||||
return True
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.warning("激活检测异常: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def _dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10):
|
||||
"""多策略确保钉钉窗口激活到前台(快捷键→Win32 API→组合)。"""
|
||||
def wait_for_valid_rect(hwnd, max_wait=1.5):
|
||||
end = time.time() + max_wait
|
||||
while time.time() < end:
|
||||
left, top, right, bottom = _dt_get_window_rect(hwnd)
|
||||
if (right - left) > 0 and (bottom - top) > 0:
|
||||
return True
|
||||
time.sleep(0.2)
|
||||
return False
|
||||
|
||||
def find_current():
|
||||
return _dt_find_dingtalk_window(include_hidden=True) or hwnd
|
||||
|
||||
def verify(hwnd):
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
if _dt_is_dingtalk_activated(hwnd, target_name=None):
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
if _dt_is_dingtalk_foreground():
|
||||
logger.info("钉钉已在最前,跳过激活")
|
||||
return True
|
||||
|
||||
if not _dt_is_dingtalk_main_visible():
|
||||
_dt_send_hotkey_to_activate()
|
||||
cur = find_current()
|
||||
if cur and wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("快捷键激活成功")
|
||||
win32gui.SetForegroundWindow(cur)
|
||||
return True
|
||||
logger.warning("快捷键后窗口尺寸无效")
|
||||
else:
|
||||
logger.info("窗口已可见,跳过切换快捷键(避免将其隐藏)")
|
||||
|
||||
logger.info("尝试 Win32 API 激活")
|
||||
cur = find_current()
|
||||
if cur:
|
||||
_dt_activate_window(cur)
|
||||
if wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("API激活成功")
|
||||
return True
|
||||
logger.warning("API后窗口尺寸无效")
|
||||
|
||||
logger.info("组合激活")
|
||||
if not _dt_is_dingtalk_main_visible():
|
||||
_dt_send_hotkey_to_activate()
|
||||
time.sleep(0.5)
|
||||
cur = find_current()
|
||||
if cur:
|
||||
_dt_activate_window(cur)
|
||||
time.sleep(1)
|
||||
if wait_for_valid_rect(cur) and verify(cur):
|
||||
logger.info("组合激活成功")
|
||||
return True
|
||||
|
||||
raise RuntimeError("所有激活策略失败")
|
||||
|
||||
|
||||
def _dt_find_hwnd_or_raise():
|
||||
"""查找钉钉窗口,失败时给出可读的错误信息。"""
|
||||
hwnd = _dt_find_dingtalk_window(include_hidden=True)
|
||||
if not hwnd:
|
||||
dingtalk_running = any(p.name().lower() == 'dingtalk.exe' for p in psutil.process_iter())
|
||||
if not dingtalk_running:
|
||||
raise RuntimeError("钉钉进程未运行,请手动启动并登录")
|
||||
else:
|
||||
raise RuntimeError("找到进程但无窗口,请手动激活")
|
||||
return hwnd
|
||||
|
||||
|
||||
def _dt_send_text_to_person(name, text):
|
||||
"""向指定联系人发送文本(OCR 视觉方案):查找窗口→多策略激活→搜索打开会话→定位输入框→粘贴发送。"""
|
||||
if not text or not text.strip():
|
||||
raise ValueError("text 不能为空")
|
||||
|
||||
for attempt in range(_DT_RETRY_TIMES):
|
||||
try:
|
||||
hwnd = _dt_find_hwnd_or_raise()
|
||||
_dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10)
|
||||
hwnd = _dt_find_dingtalk_window(include_hidden=True) or hwnd
|
||||
|
||||
if not _dt_search_and_open(hwnd, name, "联系人"):
|
||||
raise RuntimeError("打开联系人会话失败")
|
||||
|
||||
_dt_focus_input_box(hwnd)
|
||||
time.sleep(0.3)
|
||||
|
||||
pyperclip.copy(text)
|
||||
pyautogui.hotkey('ctrl', 'v')
|
||||
time.sleep(0.2)
|
||||
pyautogui.press('enter')
|
||||
logger.info("发送成功:%s...", text[:30])
|
||||
return True
|
||||
|
||||
except RuntimeError as e:
|
||||
logger.error(str(e))
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error("第%d次尝试失败:%s", attempt + 1, e)
|
||||
time.sleep(2)
|
||||
|
||||
raise RuntimeError(f"重试 {_DT_RETRY_TIMES} 次后失败")
|
||||
|
||||
|
||||
def _send_dingtalk_text(target, text):
|
||||
"""推送文本到钉钉联系人(OCR 视觉方案,与 app/utils/dingtalk_sender.py 行为一致)。"""
|
||||
_dt_send_text_to_person(target, text)
|
||||
push_type 推送类型:"group" 群消息(仅 text,钉钉群机器人 webhook 推送);
|
||||
"person" 单聊(含 target,钉钉联系人 OCR 推送)。
|
||||
"""
|
||||
messages = []
|
||||
for text in texts:
|
||||
msg = {"text": text}
|
||||
if push_type == "person":
|
||||
msg["target"] = target
|
||||
messages.append(msg)
|
||||
return messages
|
||||
|
||||
|
||||
def build_push_summary(results, subject=""):
|
||||
@@ -1294,29 +832,6 @@ def build_push_summary(results, subject=""):
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def push_report(report, subject=""):
|
||||
"""推送审批报告到钉钉联系人(env 控制,失败不影响主流程)。"""
|
||||
load_dotenv()
|
||||
if not report or not report.strip():
|
||||
logger.info("[%s] 无推送内容(无通过项),跳过钉钉推送", subject)
|
||||
return False
|
||||
enabled = os.getenv("dingtalk_notify_enabled", "false").lower() == "true"
|
||||
if not enabled:
|
||||
logger.info("[%s] 钉钉推送未开启(dingtalk_notify_enabled!=true),跳过", subject)
|
||||
return False
|
||||
target = os.getenv("dingtalk_notify_target", "").strip()
|
||||
if not target:
|
||||
logger.warning("[%s] 未配置 dingtalk_notify_target,跳过钉钉推送", subject)
|
||||
return False
|
||||
try:
|
||||
_send_dingtalk_text(target, report)
|
||||
logger.info("[%s] 审批报告已推送至钉钉: %s", subject, target)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.warning("[%s] 钉钉推送失败: %s", subject, e)
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 真实审批提交 ====================
|
||||
# 影刀环境无 .env 文件,开关直接写死在代码中;如需临时关闭自动审批改为 False
|
||||
APPROVE_ENABLED = True
|
||||
@@ -1397,16 +912,34 @@ def submit_approval(page, decision):
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
|
||||
|
||||
def run_flow(subject, validate_doc, generate_report):
|
||||
def run_flow(subject, validate_doc, generate_report, push_type="group", target=None):
|
||||
"""加班审批主流程;返回生成的推送消息列表(字典列表,本脚本不发送)。
|
||||
|
||||
push_type 推送类型:"group" 群消息(钉钉群机器人 webhook);"person" 单聊(钉钉联系人 OCR 推送)。
|
||||
target 单聊推送目标(联系人),仅 push_type="person" 时使用。
|
||||
"""
|
||||
logger.info("%s审批流程开始", subject)
|
||||
|
||||
# 运行中遇 OA 登录态失效(待办/表单接口返回登录页):删除 cookie、自动重新登录并重跑一遍(最多 2 轮)
|
||||
# 运行中遇 OA 登录态失效(待办/表单接口返回登录页):调用共享登录指令强制重登并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session, _ = _get_browser_and_session(subject)
|
||||
# 先用纯接口 SessionPage(不开浏览器)拉待办;无单据则全程不启动浏览器
|
||||
session = build_session(subject)
|
||||
browser = None
|
||||
try:
|
||||
docs = _fetch_documents(session, subject)
|
||||
logger.info("共获取%s待办 %d 条", subject, len(docs))
|
||||
|
||||
# 无待办单据:不开浏览器,直接生成提示消息返回
|
||||
if not docs:
|
||||
logger.info("%s无待审批单据,跳过浏览器操作", subject)
|
||||
push_messages = _build_push_messages([f"暂无待审批的{subject}单据"], push_type, target)
|
||||
logger.info("%s审批流程结束,共处理 0 条(无单据)", subject)
|
||||
return push_messages
|
||||
|
||||
# 有单据才启动浏览器:SSO 跳转解析 / 真实审批提交 / 结果弹窗
|
||||
browser = build_browser(subject)
|
||||
refresh_session_cookies(session, browser)
|
||||
|
||||
results = []
|
||||
for doc in docs:
|
||||
try:
|
||||
@@ -1422,6 +955,8 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
else:
|
||||
logger.info("决策为%s,暂不自动提交审批(待人工处理)", result.get("decision"))
|
||||
results.append(result)
|
||||
logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"])
|
||||
# 弹出结果提示:通过=绿勾,其余(驳回/人工复核/失败)=红叉,停留便于演示
|
||||
# 必须放在审批提交之后:全屏弹窗会遮挡审批按钮,导致真实点击被拦截
|
||||
try:
|
||||
@@ -1432,8 +967,6 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
results.append(result)
|
||||
logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"])
|
||||
except Exception as e:
|
||||
logger.error("处理单据失败: %s, 错误: %s", doc.get("title"), str(e))
|
||||
results.append({
|
||||
@@ -1446,26 +979,31 @@ def run_flow(subject, validate_doc, generate_report):
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
# 先推送摘要到钉钉
|
||||
push_report(build_push_summary(results, subject), subject)
|
||||
|
||||
# 有驳回/人工复核/失败时,再推送完整报告(含明细表格)
|
||||
# 生成推送消息文本(本脚本不发送,交由流程/推送指令):
|
||||
# 摘要 + 有驳回/人工复核/失败/超期时追加完整报告(含明细)
|
||||
texts = []
|
||||
summary = build_push_summary(results, subject)
|
||||
if summary:
|
||||
texts.append(summary)
|
||||
has_detail = any(r.get("decision") != "通过" for r in results)
|
||||
if has_detail:
|
||||
push_report(report, subject)
|
||||
texts.append(report)
|
||||
# 无任何待办/结果时也生成一条提示消息,避免静默不推送
|
||||
if not texts:
|
||||
texts.append(f"暂无待审批的{subject}单据")
|
||||
push_messages = _build_push_messages(texts, push_type, target)
|
||||
|
||||
save_browser_cookies(browser)
|
||||
logger.info("%s审批流程结束,共处理 %d 条", subject, len(results))
|
||||
return report
|
||||
return push_messages
|
||||
except OALoginExpiredError as e:
|
||||
logger.warning("OA 登录态失效: %s", e)
|
||||
if login_attempt == 0:
|
||||
# cookies 由共享登录指令维护,这里仅强制重登(重写共享 cookies)后重跑
|
||||
try:
|
||||
if os.path.exists(COOKIE_FILE):
|
||||
os.remove(COOKIE_FILE)
|
||||
logger.info("已删除失效 cookie,自动重新登录后重跑")
|
||||
except Exception:
|
||||
pass
|
||||
_ensure_oa_cookies(force=True)
|
||||
logger.info("已强制调用共享登录指令重登,重新跑一遍")
|
||||
except Exception as e2:
|
||||
logger.error("强制重登失败: %s", e2)
|
||||
continue
|
||||
raise
|
||||
finally:
|
||||
@@ -2110,9 +1648,35 @@ def generate_report(results):
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def main():
|
||||
"""加班审批:登录 -> 查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告"""
|
||||
run_flow(subject="加班", validate_doc=validate_doc, generate_report=generate_report)
|
||||
def main(push_type="group", target=None):
|
||||
"""加班审批:查待办 -> 解析SSO -> 获取表单 -> 校验 -> 报告 -> 生成推送消息。...
|
||||
|
||||
本脚本不发送任何消息:仅生成待推送消息(返回列表并写入影刀全局变量 messages),
|
||||
由「37du钉钉群机器人推送」/「37du钉钉推送」指令消费。
|
||||
|
||||
Args:
|
||||
push_type: 推送类型 "group"(默认,群消息,全局变量 messages 为纯文本直接发送)
|
||||
/ "person"(单聊,返回列表含 target,交由 OCR 单聊推送指令)
|
||||
target: 单聊推送目标(联系人),仅 push_type="person" 时使用
|
||||
"""
|
||||
push_type = str(push_type or "group").lower()
|
||||
if push_type == "person" and not target:
|
||||
logger.warning("push_type=person 但未提供 target,已按群消息(group)处理")
|
||||
push_type = "group"
|
||||
push_messages = run_flow(
|
||||
subject="加班",
|
||||
validate_doc=validate_doc,
|
||||
generate_report=generate_report,
|
||||
push_type=push_type,
|
||||
target=target,
|
||||
)
|
||||
# 写入影刀全局变量 messages(纯文本,多段用空行分隔),
|
||||
# 供「37du钉钉群机器人推送」指令直接读取发送;本地独立运行时静默跳过
|
||||
_set_glv("messages", "\n\n".join(
|
||||
str(m.get("text", "") or "").strip()
|
||||
for m in push_messages if str(m.get("text", "") or "").strip()
|
||||
))
|
||||
return push_messages
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -0,0 +1,161 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: dingtalk_robot.py
|
||||
@Description: 钉钉群机器人推送(影刀自定义指令模块源码,单一真源)。
|
||||
使用方式:main("需要推送的通知文本") 即可,标题/颜色等均可选。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 dingtalk_robot,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加一个流程参数(文本类型,如 text),并勾选「参数可见」;
|
||||
4. 保存并「发版」;在需要钉钉群推送的应用中「获取指令」并安装;
|
||||
5. 流程中拖入该指令,把业务脚本输出的文本直接传给 text 参数即可。
|
||||
|
||||
推送原理(HTTP Webhook,零第三方依赖,仅标准库):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
|
||||
|
||||
约定:
|
||||
- 影刀运行环境无 .env 读取,故推送地址/加签密钥/页脚署名直接内联在下方
|
||||
「默认配置」区(单一真源),改推送目标时改常量即可;
|
||||
- 页脚署名默认 "小芒 任务调度平台":
|
||||
注意:钉钉机器人若配置了"自定义关键词"安全校验,
|
||||
页脚署名需包含该关键词(如 小芒)才会被接受。
|
||||
|
||||
入口:
|
||||
main(text, title='消息通知', status='info', webhook='', secret='', server_name='')
|
||||
第一个参数传通知文本即可,其余可选。
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
# ==================== 默认配置(改推送目标改这里) ====================
|
||||
DEFAULT_WEBHOOK = (
|
||||
'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
)
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '小芒 任务调度平台'
|
||||
DEFAULT_TIMEOUT = 10 # HTTP 请求超时秒数
|
||||
DEFAULT_RETRY_TIMES = 3 # 失败重试次数(含首次)
|
||||
|
||||
# 通知状态 → 标题颜色
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff', # 蓝色
|
||||
'success': '#00b300', # 绿色
|
||||
'warning': '#ff9900', # 橙色
|
||||
'error': '#ff0000', # 红色
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""钉钉群机器人推送器。"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError('webhook 不能为空')
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
print(f"[WARN] 推送失败(第 {attempt + 1}/{DEFAULT_RETRY_TIMES} 次):{e}")
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def send(self, title, content, status='info', server_name=''):
|
||||
"""发送统一通知(Markdown:标题按状态着色,多行内容转引用块,带页脚)。"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n内容详情:\n"
|
||||
for line in content.strip().splitlines():
|
||||
line = line.strip()
|
||||
if line:
|
||||
# 行尾两个空格 + 换行:钉钉 markdown 单个 \n 不换行,必须用硬换行才分行显示
|
||||
text += f"> {line} \n"
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
text += f"\n\n---\n\n###### {display_name} | {now}"
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
print(f"[INFO] 钉钉机器人推送通知 [{status}]: {title}")
|
||||
self._post(payload)
|
||||
|
||||
|
||||
# ==================== 影刀自定义指令入口 ====================
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name=''):
|
||||
"""
|
||||
影刀自定义指令「37du钉钉群机器人推送」调用入口。
|
||||
只需把要推送的通知文本传进来即可,例如:
|
||||
|
||||
main("订单同步失败,错误原因:接口超时")
|
||||
|
||||
可选参数:
|
||||
title: 消息标题(默认 消息通知)
|
||||
status: info|success|warning|error,决定标题颜色(默认 info)
|
||||
webhook: 机器人 webhook(缺省用内联默认值)
|
||||
secret: 加签密钥(缺省用内联默认值)
|
||||
server_name: 页脚署名(缺省用内联默认值)
|
||||
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
try:
|
||||
if not text or not str(text).strip():
|
||||
return {'success': False, 'message': '通知文本不能为空'}
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
robot.send(str(title), str(text), status=status, server_name=server_name)
|
||||
return {'success': True, 'message': f'已推送通知 [{status}]:{title}'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
text = '测试消息:钉钉机器人连接正常。'
|
||||
print(main(text))
|
||||
@@ -1,24 +1,26 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: dingtalk_sender.py
|
||||
@Description: 钉钉推送自定义指令(影刀编码版 Python 模块源码,单一真源)。
|
||||
@Description: 钉钉联系人推送自定义指令(影刀编码版 Python 模块源码,单一真源)。
|
||||
作为「37du钉钉推送」影刀自定义指令的模块源码,
|
||||
供所有需要钉钉推送的影刀脚本/流程复用(周考勤、请假审批、加班审批、人事变动等),
|
||||
供所有需要钉钉单人推送的影刀脚本/流程复用(周考勤、请假审批、加班审批、人事变动等),
|
||||
避免每个脚本各自内联 OCR 视觉发送逻辑。
|
||||
仅推送「联系人」(单聊);群消息已改用钉钉群机器人(webhook)推送,
|
||||
见同目录 dingtalk_robot.py(「37du钉钉群机器人推送」指令)。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 dingtalk_sender,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 params(字典类型,dict),或分别增加 target/text/chat_type 三个参数;
|
||||
3. 增加流程参数 params(字典类型,dict),或分别增加 target/text 两个参数;
|
||||
4. 保存并「发版」;在需要钉钉推送的应用中「获取指令」并安装;
|
||||
5. 在流程中拖入该指令,把业务脚本输出的参数传入(两种方式任选):
|
||||
方式A(推荐):流程中先拼一个字典变量(如 {"target": "张三", "text": "..."}),
|
||||
作为 params 整体传入;
|
||||
方式B:分别传 target、text 变量(chat_type 可选),指令内部自动拼成字典;
|
||||
方式B:分别传 target、text 变量,指令内部自动拼成字典;
|
||||
指令返回 JSON:{"success": bool, "message": str},可在后续流程中判断是否重试。
|
||||
|
||||
推送原理(OCR 视觉方案,与 app/utils/dingtalk_sender.py 一致):
|
||||
查找钉钉窗口 → 多策略激活到前台 → Ctrl+Shift+F 搜索会话 → OCR 定位输入框
|
||||
查找钉钉窗口 → 多策略激活到前台 → Ctrl+Shift+F 搜索联系人 → OCR 定位输入框
|
||||
→ 粘贴文本 → 回车发送。
|
||||
|
||||
依赖(影刀「Python包管理」安装;启动校验不懒加载):
|
||||
@@ -30,10 +32,11 @@
|
||||
args = {
|
||||
"target": "联系人搜索关键字(支持工号,避免同名误选)",
|
||||
"text": "要发送的文本内容",
|
||||
"chat_type": "联系人|群组(可选,默认 联系人)",
|
||||
"display_name": "会话标题校验名(可选;钉钉标题显示姓名,target 用工号时传姓名校验)",
|
||||
}
|
||||
通过流程参数传入(支持整字典 params 或分别传 target/text/chat_type)
|
||||
通过流程参数传入(支持整字典 params 或分别传 target/text)
|
||||
messages 批量模式下,消息含 target 走 OCR 单聊;不含 target 视为群消息,
|
||||
自动改由钉钉群机器人(dingtalk_robot)webhook 推送。
|
||||
返回 JSON 安全 dict:{"success": bool, "message": str}
|
||||
|
||||
python dingtalk_sender.py 目标 文本 独立运行(等价于 main({"target": ..., "text": ...}))
|
||||
@@ -264,8 +267,8 @@ def _dt_is_chat_opened(hwnd, target_name):
|
||||
return False
|
||||
|
||||
|
||||
def _dt_search_and_open(hwnd, target_name, chat_type="联系人", verify_name=None):
|
||||
"""搜索并打开指定的联系人或群组会话。
|
||||
def _dt_search_and_open(hwnd, target_name, verify_name=None):
|
||||
"""搜索并打开指定联系人的会话(仅单聊;群消息改用钉钉群机器人 webhook 推送)。
|
||||
|
||||
target_name 为搜索关键字(支持工号,避免同名人员误选,如搜索 10086);
|
||||
verify_name 为打开会话后校验标题用的名称(钉钉会话标题显示的是联系人姓名
|
||||
@@ -283,7 +286,7 @@ def _dt_search_and_open(hwnd, target_name, chat_type="联系人", verify_name=No
|
||||
pyautogui.press('enter')
|
||||
logger.info("搜索 '%s' (尝试 %d)", target_name, attempt + 1)
|
||||
time.sleep(0.8)
|
||||
if _dt_wait_for_tab(hwnd, chat_type, timeout=3):
|
||||
if _dt_wait_for_tab(hwnd, "联系人", timeout=3):
|
||||
break
|
||||
else:
|
||||
pyautogui.press('esc')
|
||||
@@ -298,13 +301,13 @@ def _dt_search_and_open(hwnd, target_name, chat_type="联系人", verify_name=No
|
||||
top_height = max(40, int(height * _DT_TOP_HEIGHT_RATIO))
|
||||
img = _dt_capture_region(left, top, width, top_height)
|
||||
ocr_data = _dt_ocr_image(img)
|
||||
pos = _dt_find_text_center(ocr_data, chat_type)
|
||||
pos = _dt_find_text_center(ocr_data, "联系人")
|
||||
if pos:
|
||||
cx, cy = pos
|
||||
pyautogui.click(left + cx, top + cy)
|
||||
logger.info("点击'%s'标签", chat_type)
|
||||
logger.info("点击'联系人'标签")
|
||||
else:
|
||||
logger.warning("未识别'%s'标签", chat_type)
|
||||
logger.warning("未识别'联系人'标签")
|
||||
time.sleep(0.5)
|
||||
|
||||
pyautogui.press('enter')
|
||||
@@ -461,8 +464,8 @@ def _dt_find_hwnd_or_raise():
|
||||
return hwnd
|
||||
|
||||
|
||||
def _dt_send_text_to_person(name, text, chat_type="联系人", display_name=None):
|
||||
"""向指定联系人/群发送文本(OCR 视觉方案):查找窗口→多策略激活→搜索打开会话→定位输入框→粘贴发送。
|
||||
def _dt_send_text_to_person(name, text, display_name=None):
|
||||
"""向指定联系人发送文本(OCR 视觉方案):查找窗口→多策略激活→搜索打开会话→定位输入框→粘贴发送。
|
||||
name 为搜索关键字(支持工号);display_name 为会话标题校验名(钉钉标题显示姓名,
|
||||
同名人时传姓名用于校验;不传则用 name 校验),二者分离避免同名误选。
|
||||
"""
|
||||
@@ -475,8 +478,8 @@ def _dt_send_text_to_person(name, text, chat_type="联系人", display_name=None
|
||||
_dt_ensure_activate_dingtalk(hwnd, target_name=None, timeout=10)
|
||||
hwnd = _dt_find_dingtalk_window(include_hidden=True) or hwnd
|
||||
|
||||
if not _dt_search_and_open(hwnd, name, chat_type, display_name):
|
||||
raise RuntimeError("打开%s会话失败" % chat_type)
|
||||
if not _dt_search_and_open(hwnd, name, display_name):
|
||||
raise RuntimeError("打开联系人会话失败")
|
||||
|
||||
_dt_focus_input_box(hwnd)
|
||||
time.sleep(0.3)
|
||||
@@ -498,26 +501,38 @@ def _dt_send_text_to_person(name, text, chat_type="联系人", display_name=None
|
||||
raise RuntimeError("重试 %d 次后失败" % _DT_RETRY_TIMES)
|
||||
|
||||
|
||||
def send_dingtalk_text(target, text, chat_type="联系人", display_name=None):
|
||||
"""推送文本到钉钉联系人/群(OCR 视觉方案)。供业务脚本 import 调用。
|
||||
def send_dingtalk_text(target, text, display_name=None):
|
||||
"""推送文本到钉钉联系人(OCR 视觉方案,仅单聊)。供业务脚本 import 调用。
|
||||
target 为搜索关键字(支持工号);display_name 为会话标题校验名(可选,同名人传姓名)。
|
||||
群消息请改用 dingtalk_robot(钉钉群机器人 webhook)推送。
|
||||
"""
|
||||
return _dt_send_text_to_person(target, text, chat_type, display_name)
|
||||
return _dt_send_text_to_person(target, text, display_name)
|
||||
|
||||
|
||||
# ==================== 影刀自定义指令入口 ====================
|
||||
def _send_one(msg):
|
||||
"""发送单条消息,返回 {success: bool, message: str}。msg 为 {target, text, chat_type?, display_name?} 字典。"""
|
||||
"""发送单条消息,返回 {success: bool, message: str}。msg 为 {target?, text, display_name?} 字典。
|
||||
|
||||
- 含 target:钉钉联系人 OCR 推送(单聊);
|
||||
- 不含 target:视为群消息,改用钉钉群机器人(webhook)推送(替换原 OCR 群聊)。
|
||||
"""
|
||||
target = str((msg or {}).get("target", "") or "").strip()
|
||||
text = str((msg or {}).get("text", "") or "")
|
||||
chat_type = str((msg or {}).get("chat_type", "") or "联系人").strip() or "联系人"
|
||||
display_name = str((msg or {}).get("display_name", "") or "").strip() or None
|
||||
if not target:
|
||||
return {"success": False, "message": "参数 target 不能为空"}
|
||||
if not text.strip():
|
||||
return {"success": False, "message": "参数 text 不能为空"}
|
||||
if not target:
|
||||
# 群消息:交由钉钉群机器人(webhook)推送
|
||||
try:
|
||||
import dingtalk_robot
|
||||
except ImportError:
|
||||
return {"success": False, "message": "未加载群机器人模块(dingtalk_robot.py),无法推送群消息"}
|
||||
try:
|
||||
return dingtalk_robot.main(text)
|
||||
except Exception as e:
|
||||
return {"success": False, "message": f"群机器人推送失败:{e}"}
|
||||
try:
|
||||
send_dingtalk_text(target, text, chat_type, display_name)
|
||||
send_dingtalk_text(target, text, display_name)
|
||||
return {"success": True, "message": f"已向 {target} 发送成功"}
|
||||
except Exception as e:
|
||||
return {"success": False, "message": str(e)}
|
||||
@@ -527,9 +542,10 @@ def main(args):
|
||||
"""
|
||||
影刀自定义指令「37du钉钉推送」调用入口。
|
||||
args: dict,通过流程变量传入(影刀变量支持传字典/列表):
|
||||
方式A(批量,推荐):args = {"messages": [{target, text, chat_type?}, ...]}
|
||||
方式A(批量,推荐):args = {"messages": [{target?, text, display_name?}, ...]}
|
||||
messages 为「字典列表」,逐条发送并返回汇总结果;
|
||||
方式B(单条):args = {"params": {target, text, chat_type?}} 或
|
||||
含 target 走 OCR 单聊;不含 target 视为群消息,改用钉钉群机器人推送;
|
||||
方式B(单条):args = {"params": {target, text}} 或
|
||||
{"target":..., "text":...};
|
||||
返回: dict
|
||||
单条: {success: bool, message: str}
|
||||
@@ -561,7 +577,12 @@ def main(args):
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 仅本地自测连通性。影刀中会直接调用 main(args) 并通过流程变量传参,不会走这里。
|
||||
# 批量测试:流程变量 messages = 字典列表,每条含 target/text,main 逐条发送并汇总。
|
||||
_messages = [{"target": "夏一平", "text": "【37du钉钉推送·测试1】你好,这是一条连通性测试消息。"},{"target": "夏一平", "text": "【37du钉钉推送·测试2】你好,这是第二条测试消息。"}]
|
||||
# 批量测试:流程变量 messages = 字典列表,含 target 走 OCR 单聊;
|
||||
# 不含 target 视为群消息,交由钉钉群机器人(webhook)推送。
|
||||
_messages = [
|
||||
{"target": "夏一平", "text": "【37du钉钉推送·测试1】你好,这是一条连通性测试消息。"},
|
||||
{"target": "夏一平", "text": "【37du钉钉推送·测试2】你好,这是第二条测试消息。"},
|
||||
{"text": "【37du钉钉推送·群消息测试】你好,这是一条群机器人测试消息。"},
|
||||
]
|
||||
result = main({"messages": _messages})
|
||||
print("最终结果:", result)
|
||||
Reference in New Issue
Block a user