feat: 新增打卡明细接口支持,优化加班校验逻辑
1. 新增打卡明细接口封装,支持单页查询与自动分页获取员工真实打卡记录 2. 重构加班校验逻辑,使用打卡明细接口替代原考勤逐日接口的打卡字段,解决跨天打卡归属错误问题 3. 移除过时的打卡时间解析与单条打卡修正逻辑,简化代码维护 4. 优化OA登录脚本,新增requests依赖并完善会话校验逻辑 5. 新增钉钉群机器人推送通用模块,支持多场景通知推送
This commit is contained in:
@@ -1,40 +1,253 @@
|
||||
操作步骤 说明
|
||||
步骤1 登录EHR网页系统
|
||||
步骤2 工作台-处理类-待处理-搜索“请假”单据
|
||||
步骤3 批量获取页面全部待审核单据
|
||||
步骤4 逐条打开单据,调取员工假期额度、休假日期数据
|
||||
步骤5 匹配【判断逻辑】执行自动校验,合规自动通过,不合规自动驳回并回填驳回理由,异常单据单独标记
|
||||
步骤6 批量导出《请假审批自动驳回人员明细清单》《附件人工复核待办清单》,钉钉推送至HRBP
|
||||
步骤7 HR线下根据待办清单人工核查各类假期附件材料
|
||||
判断逻辑
|
||||
"(1)年度福利假 / 事假
|
||||
【RPA 自动校验】请假起止日期剔除周末、法定节假日后的实际休假天数,与单据填写请假天数完全匹配;不匹配直接自动驳回。
|
||||
【人工复核】无强制附件要求。
|
||||
(2)调休假
|
||||
【RPA 自动校验 1】实际休假天数与填报天数一致,不一致驳回;
|
||||
【RPA 自动校验 2】核查员工请假前已登记未使用休息日加班额度,额度不足 / 无前置加班记录自动驳回;
|
||||
【人工复核】无强制附件校验要求。
|
||||
(3)病假
|
||||
【RPA 自动校验 1】实际休假天数与填报天数一致,不一致驳回;
|
||||
【RPA 自动校验 2】校验是否上传附件,无附件直接驳回;
|
||||
【人工复核】附件内容人工核查。
|
||||
(4)特别福利假(婚假 / 丧假 / 产检假)
|
||||
【RPA 自动校验 1】实际休假天数匹配填报天数,不一致驳回;
|
||||
【RPA 自动校验 2】校验是否上传附件,无附件直接驳回;
|
||||
【人工复核】附件内容人工核查。
|
||||
(5)特殊事假
|
||||
【RPA 自动校验 1】实际休假天数与填报天数一致,不一致驳回;
|
||||
【RPA 自动校验 2】校验是否上传对应事由附件,无附件直接驳回;
|
||||
【人工复核】附件内容人工核查。
|
||||
(6)小时特假
|
||||
【RPA 自动校验 1】单次申请时长≤2 小时,超时直接驳回;
|
||||
【RPA 自动校验 2】校验是否上传请假证明附件,无附件直接驳回;
|
||||
【人工复核】附件内容人工核查。"
|
||||
交付物
|
||||
"1.《请假审批自动驳回人员明细清单》:列明员工、假期类型、机器校验驳回项、驳回原因;
|
||||
2.《附件人工复核待办清单》:机器校验全部通过、需 HR 线下核验附件的单据,用于每日人工专项复核。"
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -35,6 +35,12 @@ ATTENDANCE_DAILY_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_count_
|
||||
# 请假记录接口(hr 域名,按员工 + 日期范围查询请假明细)
|
||||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||||
|
||||
# 打卡明细接口(hr 域名,按员工 + 日期范围查询真实打卡明细)
|
||||
# kq_time=真实打卡时间、bc_date=考勤归属日(跨天打卡次日0点~6点归入前一天)、
|
||||
# time_order=上下班类型(1=上班、2=下班)。加班校验用其替代考勤逐日接口的打卡字段,
|
||||
# 避免人工拼接日期导致跨天打卡归属错误。
|
||||
PUNCH_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId/redApiExec.mc"
|
||||
|
||||
# 附件下载接口(hr 域名):按 fileId 下载请假单据附件
|
||||
FILE_DOWNLOAD_URL = f"{HR_BASE_URL}/RedseaPlatform/corePlatformOutUser/fjkFileDownload.mob"
|
||||
# 附件默认保存目录
|
||||
|
||||
@@ -31,6 +31,10 @@ from app.service.hrbp.oa.common.oa_api.leave import (
|
||||
fetch_leave_record_page,
|
||||
get_leave_records,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.punch import (
|
||||
fetch_punch_record_page,
|
||||
get_punch_records,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"oa_request_json",
|
||||
@@ -46,4 +50,6 @@ __all__ = [
|
||||
"get_attendance_daily",
|
||||
"fetch_leave_record_page",
|
||||
"get_leave_records",
|
||||
"fetch_punch_record_page",
|
||||
"get_punch_records",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.common.oa_api
|
||||
@FileName: punch.py
|
||||
@Description: 员工打卡明细接口:单页查询与自动分页。
|
||||
kq_time 为真实打卡时间,bc_date 为考勤归属日(跨天打卡次日0点~6点归入前一天)。
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
try:
|
||||
from DrissionPage import SessionPage
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
from app.service.hrbp.oa.common.config import PUNCH_RECORD_URL, DEFAULT_PAGE_SIZE
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def fetch_punch_record_page(
|
||||
session: SessionPage,
|
||||
staff_id: str,
|
||||
begin_date: str,
|
||||
end_date: str,
|
||||
page_no: int = 1,
|
||||
page_size: int = DEFAULT_PAGE_SIZE,
|
||||
sub_type: str = "-1"
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
请求单页员工打卡明细。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
staff_id: 员工 UUID
|
||||
begin_date: 查询起始日期 "YYYY-MM-DD"(同时作为 bc_date/bc_date_end/begin/end)
|
||||
end_date: 查询结束日期 "YYYY-MM-DD"
|
||||
page_no: 页码(从1开始)
|
||||
page_size: 每页条数
|
||||
sub_type: 类型编码,默认 "-1" 表示全部
|
||||
|
||||
Returns:
|
||||
接口返回的 data 字段字典,包含 total / pageCount / list
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
data = {
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": str(page_no),
|
||||
"pageSize": str(page_size),
|
||||
"staff_id": staff_id,
|
||||
"rootId": "",
|
||||
"countId": "",
|
||||
"bc_date": begin_date,
|
||||
"bc_date_end": end_date,
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"sub_type": sub_type,
|
||||
}
|
||||
logger.info("获取打卡明细: staff_id=%s, %s 至 %s, 第%d页", staff_id, begin_date, end_date, page_no)
|
||||
json_data = oa_request_json(session, "POST", PUNCH_RECORD_URL, data, "打卡明细")
|
||||
|
||||
if json_data.get("success") is not True or json_data.get("code") != 200:
|
||||
raise RuntimeError(f"打卡明细接口返回失败: {json_data}")
|
||||
|
||||
page_info = json_data.get("data")
|
||||
if not isinstance(page_info, dict):
|
||||
raise RuntimeError(f"打卡明细接口未返回 data 字段: {json_data}")
|
||||
return page_info
|
||||
|
||||
|
||||
def get_punch_records(
|
||||
session: SessionPage,
|
||||
staff_id: str,
|
||||
begin_date: str,
|
||||
end_date: str,
|
||||
page_size: int = DEFAULT_PAGE_SIZE,
|
||||
sub_type: str = "-1"
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
查询员工某时间段内的全部打卡明细(自动分页)。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
staff_id: 员工 UUID
|
||||
begin_date: 查询起始日期 "YYYY-MM-DD"
|
||||
end_date: 查询结束日期 "YYYY-MM-DD"
|
||||
page_size: 每页条数
|
||||
sub_type: 类型编码,默认 "-1" 表示全部
|
||||
|
||||
Returns:
|
||||
打卡明细列表,每条包含:
|
||||
- kq_time: 真实打卡时间 "YYYY-MM-DD HH:MM:SS"
|
||||
- bc_date: 考勤归属日 "YYYY-MM-DD"(跨天打卡次日0点~6点归入前一天)
|
||||
- time_order: 上下班类型 "1"=上班 "2"=下班
|
||||
- status: 打卡状态
|
||||
- address: 打卡地点
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
all_records: List[Dict[str, Any]] = []
|
||||
|
||||
# 请求第一页,获取总条数与总页数
|
||||
page_info = fetch_punch_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=page_size, sub_type=sub_type
|
||||
)
|
||||
total = int(page_info.get("total", 0))
|
||||
page_total = int(page_info.get("pageCount", 1))
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("打卡明细总数: %d, 第1页获取 %d 条", total, len(records))
|
||||
|
||||
# 若存在多页,继续翻页
|
||||
if page_total > 1:
|
||||
for p in range(2, page_total + 1):
|
||||
page_info = fetch_punch_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=p, page_size=page_size, sub_type=sub_type
|
||||
)
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records))
|
||||
|
||||
return all_records
|
||||
@@ -21,6 +21,7 @@ from app.service.hrbp.oa.work_overtime.parser import parse_overtime_form
|
||||
from app.service.hrbp.oa.common.oa_api import (
|
||||
get_attendance_daily,
|
||||
get_leave_records,
|
||||
get_punch_records,
|
||||
)
|
||||
from app.service.hrbp.oa.common.config import (
|
||||
WORK_START_TIME,
|
||||
@@ -187,80 +188,21 @@ def _extract_shift_times(daily_records: List[Dict[str, Any]], date_str: str) ->
|
||||
return None, None
|
||||
|
||||
|
||||
def _resolve_single_punch(
|
||||
day_summary: Optional[Dict[str, Any]],
|
||||
shift_begin: Optional[str],
|
||||
shift_end: Optional[str],
|
||||
) -> tuple:
|
||||
"""当天仅一条打卡时,结合班次时段判断它是上班还是下班打卡。
|
||||
|
||||
考勤逐日数据中当天只有一条打卡时 last_check_out 固定为 None,
|
||||
会把唯一一条下班打卡误判成"当日无下班打卡"。这里按打卡时间与班次时段的
|
||||
相对位置修正:晚于班次中点(无班次时段时默认以 12:00 为分界)的打卡视为
|
||||
下班打卡,赋给"当日最晚打卡";否则仍视为上班打卡。
|
||||
|
||||
Returns:
|
||||
(当日最早打卡, 当日最晚打卡) 修正后的元组
|
||||
"""
|
||||
if not day_summary:
|
||||
return None, None
|
||||
first = day_summary.get("first_check_in")
|
||||
last = day_summary.get("last_check_out")
|
||||
if last is not None:
|
||||
return first, last
|
||||
if not first:
|
||||
return None, None
|
||||
t = _parse_dt(first)
|
||||
if t is None:
|
||||
return None, None
|
||||
mins = t.hour * 60 + t.minute
|
||||
mid = 12 * 60
|
||||
if shift_begin and shift_end:
|
||||
try:
|
||||
sb = int(shift_begin[:2]) * 60 + int(shift_begin[3:5])
|
||||
se = int(shift_end[:2]) * 60 + int(shift_end[3:5])
|
||||
mid = (sb + se) // 2
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
if mins >= mid:
|
||||
# 晚于班次中点:视为下班打卡
|
||||
return None, first
|
||||
return first, None
|
||||
|
||||
|
||||
# 每日考勤记录中携带的上下班打卡字段(sb=上班、xb=下班,可能分多个时段)
|
||||
_PUNCH_TIME_FIELDS = ("sb_dk_time", "xb_dk_time", "sb_dk_time2", "xb_dk_time2", "sb_dk_time3", "xb_dk_time3")
|
||||
|
||||
|
||||
def _collect_day_punches(record: Optional[Dict[str, Any]], work_day: str) -> List[str]:
|
||||
"""收集某日考勤记录中的全部上下班打卡时间。
|
||||
|
||||
打卡字段为 "HH:MM:SS"(无打卡为 null),这里拼上日期返回
|
||||
"YYYY-MM-DD HH:MM:SS" 完整时间并升序排序,供最早/最晚打卡提取与 _parse_dt 解析。
|
||||
"""
|
||||
if not record or not work_day:
|
||||
return []
|
||||
punches = []
|
||||
for field in _PUNCH_TIME_FIELDS:
|
||||
v = record.get(field)
|
||||
if v:
|
||||
s = str(v).strip()
|
||||
if s:
|
||||
punches.append(f"{work_day} {s}")
|
||||
punches.sort()
|
||||
return punches
|
||||
|
||||
|
||||
def _check_punch_records(session: Any, staff_id: str, ot_date: str) -> Dict[str, Any]:
|
||||
"""
|
||||
查询员工在加班日及次日的打卡明细,按日汇总。
|
||||
|
||||
加班常跨天(如 18:00 至次日 00:00),下班打卡可能落在次日,因此查询
|
||||
范围扩展到 ot_date 次日;次日最早打卡用于延时加班的弹性到岗兑换判定。
|
||||
另扩展到前一天:提前到岗型延时加班(开始<=6点)的到岗打卡可能被系统归到前一天。
|
||||
加班常跨天(如 18:00 至次日 00:00),下班打卡可能落在次日。打卡明细接口
|
||||
(rf_s_kq_data_queryByStaffId)返回 kq_time=真实打卡时间 与 bc_date=考勤归属日,
|
||||
跨天打卡(次日0点~6点)由系统归入加班当天,无需人工拼接/修正日期。
|
||||
查询范围扩展到 ot_date 前一天与次日:次日最早打卡用于延时加班的弹性到岗兑换判定,
|
||||
前一天最晚打卡用于提前到岗型延时加班(开始<=6点)到岗打卡被归到前一天的情况。
|
||||
|
||||
数据源统一为考勤逐日接口(rf_s_kq_count_leave_yc_day_all),一次调用即可拿到
|
||||
班次起止时间与各时段上下班打卡,替代原打卡流水接口。
|
||||
打卡按上下班类型(time_order:1=上班、2=下班)分类:
|
||||
- 当日最早打卡/次日最早打卡 = 当组最早的上班打卡;
|
||||
- 当日最晚打卡 = 当组最晚的下班打卡(真实下班时间,含跨天归入的下班打卡);
|
||||
- 前一天最晚打卡 = 前一天最晚一条打卡(不限类型,兼容提前到岗型跨天到岗打卡)。
|
||||
班次起止时间仍由考勤逐日接口提供。
|
||||
"""
|
||||
if not ot_date or not staff_id:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
@@ -272,31 +214,46 @@ def _check_punch_records(session: Any, staff_id: str, ot_date: str) -> Dict[str,
|
||||
next_day = (start + timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
|
||||
try:
|
||||
daily = get_attendance_daily(session, staff_id, prev_day, next_day)
|
||||
prev_record = next((r for r in daily if str(r.get("work_day", "")) == prev_day), None)
|
||||
day_record = next((r for r in daily if str(r.get("work_day", "")) == ot_date), None)
|
||||
next_record = next((r for r in daily if str(r.get("work_day", "")) == next_day), None)
|
||||
if not day_record and not next_record and not prev_record:
|
||||
punches = get_punch_records(session, staff_id, prev_day, next_day)
|
||||
if not punches:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
|
||||
"打卡备注": "当天及次日无打卡记录"}
|
||||
# 按考勤归属日 bc_date 分组;time_order:1=上班打卡、2=下班打卡
|
||||
arrivals: Dict[str, List[str]] = {}
|
||||
checkouts: Dict[str, List[str]] = {}
|
||||
all_by_date: Dict[str, List[str]] = {}
|
||||
for r in punches:
|
||||
bd = str(r.get("bc_date", "")).strip()
|
||||
t = str(r.get("kq_time", "")).strip()
|
||||
if not bd or not t:
|
||||
continue
|
||||
all_by_date.setdefault(bd, []).append(t)
|
||||
if str(r.get("time_order", "")).strip() == "1":
|
||||
arrivals.setdefault(bd, []).append(t)
|
||||
elif str(r.get("time_order", "")).strip() == "2":
|
||||
checkouts.setdefault(bd, []).append(t)
|
||||
# 班次起止时间:取当日实际班次时段(如维护早班 08:00-17:00),
|
||||
# 未获取到时由上层回退默认 09:00/18:00;接口失败不影响打卡数据
|
||||
daily = get_attendance_daily(session, staff_id, prev_day, next_day)
|
||||
shift_begin, shift_end = _extract_shift_times(daily, ot_date)
|
||||
# 当日最早/最晚打卡;单条打卡时结合班次时段识别是上班还是下班打卡
|
||||
day_punches = _collect_day_punches(day_record, ot_date)
|
||||
day_summary = {
|
||||
"first_check_in": day_punches[0] if day_punches else None,
|
||||
# 仅1条打卡时 last_check_out 置空,交由 _resolve_single_punch 结合班次时段修正
|
||||
"last_check_out": day_punches[-1] if len(day_punches) > 1 else None,
|
||||
}
|
||||
day_first, day_last = _resolve_single_punch(day_summary, shift_begin, shift_end)
|
||||
|
||||
def _sorted(date_str: str) -> List[str]:
|
||||
return sorted(all_by_date.get(date_str, []))
|
||||
|
||||
# 当日最早/最晚打卡:优先按上下班类型取,缺该类型时回退取当天全部打卡
|
||||
day_all = _sorted(ot_date)
|
||||
day_arrivals = sorted(arrivals.get(ot_date, []))
|
||||
day_checkouts = sorted(checkouts.get(ot_date, []))
|
||||
day_first = day_arrivals[0] if day_arrivals else (day_all[0] if day_all else None)
|
||||
day_last = day_checkouts[-1] if day_checkouts else (day_all[-1] if day_all else None)
|
||||
# 次日最早打卡(弹性兑换用)
|
||||
next_punches = _collect_day_punches(next_record, next_day)
|
||||
next_first = next_punches[0] if next_punches else None
|
||||
next_arrivals = sorted(arrivals.get(next_day, []))
|
||||
next_all = _sorted(next_day)
|
||||
next_first = next_arrivals[0] if next_arrivals else (next_all[0] if next_all else None)
|
||||
# 前一天最晚打卡(提前到岗型加班用)
|
||||
prev_punches = _collect_day_punches(prev_record, prev_day)
|
||||
prev_last = prev_punches[-1] if prev_punches else None
|
||||
prev_all = _sorted(prev_day)
|
||||
prev_last = prev_all[-1] if prev_all else None
|
||||
return {
|
||||
"当日最早打卡": day_first,
|
||||
"当日最晚打卡": day_last,
|
||||
@@ -527,8 +484,8 @@ def _validate_day_ot(
|
||||
- 排班显示为休息;
|
||||
- 法定假日(仅春节):申请日期必须为春节法定节假日;
|
||||
- 加班时长 > 0;
|
||||
- 当天有上下班打卡(跨天打卡处理:当天无打卡时,若次日首条打卡早于6点,
|
||||
视为归属加班当天的跨天有效打卡,不再因缺打卡驳回);
|
||||
- 当天有上下班打卡(打卡明细接口按考勤归属日 bc_date 分组,跨天打卡次日0点~6点
|
||||
已归入加班当天,当日最早/最晚打卡即含跨天下班打卡);
|
||||
- 打卡时间间隔满足申报天数(0.5天>=4h, 1天>=9h, 1.5天>=13h, 2天>=18h...);
|
||||
职能排班半天(0.5天)例外:上午(开始时间<12:00)>=3.5h、下午>=4.5h,整天仍为9h。
|
||||
"""
|
||||
@@ -558,24 +515,14 @@ def _validate_day_ot(
|
||||
if ot_hour <= 0:
|
||||
reasons.append("加班时长为0或缺失")
|
||||
|
||||
# 当天有上下班打卡,且打卡时间间隔满足申报天数
|
||||
# 跨天打卡处理:当天缺打卡时参考次日首条打卡,次日首条早于6点视为归属加班当天
|
||||
# 当天有上下班打卡,且打卡时间间隔满足申报天数。
|
||||
# 打卡明细接口已按考勤归属日 bc_date 分组,跨天打卡(次日0点~6点)归入加班当天,
|
||||
# 因此当日最早/最晚打卡已包含跨天下班打卡,无需再参考次日打卡补全。
|
||||
first = _parse_dt(punch.get("当日最早打卡"))
|
||||
last = _parse_dt(punch.get("当日最晚打卡"))
|
||||
next_first = _parse_dt(punch.get("次日最早打卡"))
|
||||
interval = None
|
||||
if first is None or last is None:
|
||||
if next_first is not None and next_first.hour < CROSS_DAY_BEFORE_HOUR:
|
||||
# 次日首条早于6点 -> 加班当天跨天有效打卡,补全当天缺失的打卡
|
||||
had_punch = (first is not None) or (last is not None)
|
||||
first = first if first is not None else next_first
|
||||
last = last if last is not None else next_first
|
||||
info["跨天打卡"] = "是"
|
||||
# 当天全无打卡时仅凭跨天记录,视为满足"至少一条打卡"要求,不计算间隔
|
||||
if had_punch:
|
||||
interval = (last - first).total_seconds() / 3600
|
||||
else:
|
||||
reasons.append("当天缺少上班或下班打卡")
|
||||
reasons.append("当天缺少上班或下班打卡")
|
||||
else:
|
||||
interval = (last - first).total_seconds() / 3600
|
||||
|
||||
|
||||
@@ -0,0 +1,496 @@
|
||||
# -*- 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)
|
||||
@@ -23,10 +23,13 @@
|
||||
oa_target_url_keyword=OA 登录成功后 URL 关键字
|
||||
oa_login_username=用户名
|
||||
oa_login_password=密码
|
||||
oa_validate_url=(可选)轻量会话校验接口 URL;不配置则仅以 cookies 存在作为复用依据
|
||||
oa_validate_url=(可选)轻量会话校验接口 URL;默认使用 sumTodoCount 待办统计接口
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage python-dotenv
|
||||
pip install DrissionPage requests python-dotenv
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
@@ -36,8 +39,9 @@ import os
|
||||
import json
|
||||
import time
|
||||
|
||||
from DrissionPage import ChromiumPage, SessionPage
|
||||
from DrissionPage import ChromiumPage
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
@@ -55,13 +59,37 @@ def _load_shared_env():
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 注意:必须在读取环境变量前先加载 .env,否则 import 时这些值会被捕获为 None
|
||||
_load_shared_env()
|
||||
LOGIN_URL = os.getenv('oa_login_url')
|
||||
SUCCESS_KEYWORD = os.getenv('oa_target_url_keyword')
|
||||
USERNAME = os.getenv('oa_login_username')
|
||||
PASSWORD = os.getenv('oa_login_password')
|
||||
|
||||
# OA 会话校验接口:cookies 有效时返回 JSON,失效时被重定向到登录页返回 HTML
|
||||
TODO_COUNT_URL = "https://oa.37du.co/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
USERNAME_INPUT = 'tag:input@name=j_username'
|
||||
PASSWORD_INPUT = 'tag:input@name=j_password'
|
||||
LOGIN_BTN = '.lui_login_button_div_c'
|
||||
|
||||
TIMEOUT = 10
|
||||
WAIT_AFTER_LOAD = 2
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化 ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
os.makedirs(_SESSIONS_DIR, exist_ok=True)
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
@@ -75,60 +103,69 @@ def load_cookies():
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||||
def _is_oa_session_valid():
|
||||
"""轻量校验 OA 会话:请求 oa_validate_url,返回 JSON 视为有效。未配置则默认有效。"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip()
|
||||
if not validate_url:
|
||||
return True
|
||||
"""API 轻量校验 OA cookies:请求 oa_validate_url(默认 sumTodoCount 待办统计接口),
|
||||
返回 JSON 视为 cookies 有效;被重定向到登录页返回 HTML 即视为失效。
|
||||
|
||||
与业务脚本(overtime_approval/leave_approval/social_change 等)使用同一套接口与校验逻辑:
|
||||
requests.Session + Chrome UA + 仅注入 37du.co 域 cookies,GET method=sumTodoCount。
|
||||
"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip() or TODO_COUNT_URL
|
||||
try:
|
||||
session = SessionPage()
|
||||
cookies = load_cookies()
|
||||
if cookies:
|
||||
session.set.cookies(cookies)
|
||||
session.set.timeout(10)
|
||||
session.get(validate_url)
|
||||
resp = session.response
|
||||
if resp is None or resp.status_code != 200:
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login(username=None, password=None, timeout=10, wait_after_load=2):
|
||||
def _do_login(timeout=TIMEOUT, wait_after_load=WAIT_AFTER_LOAD):
|
||||
"""打开浏览器完成 OA 账号密码登录,成功保存 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("用户名或密码未提供,请设置环境变量或传入参数")
|
||||
|
||||
page = ChromiumPage()
|
||||
try:
|
||||
page.get(login_url)
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(wait_after_load)
|
||||
|
||||
username_input = page.ele('tag:input@name=j_username')
|
||||
username_input = page.ele(USERNAME_INPUT)
|
||||
if not username_input:
|
||||
raise RuntimeError("未找到用户名输入框")
|
||||
username_input.input(final_username)
|
||||
username_input.input(USERNAME)
|
||||
page.wait(0.5)
|
||||
|
||||
password_input = page.ele('tag:input@name=j_password')
|
||||
password_input = page.ele(PASSWORD_INPUT)
|
||||
if not password_input:
|
||||
raise RuntimeError("未找到密码输入框")
|
||||
password_input.input(final_password)
|
||||
password_input.input(PASSWORD)
|
||||
page.wait(0.5)
|
||||
|
||||
login_button = page.ele('.lui_login_button_div_c')
|
||||
login_button = page.ele(LOGIN_BTN)
|
||||
if not login_button:
|
||||
raise RuntimeError("未找到登录按钮")
|
||||
login_button.click()
|
||||
@@ -136,7 +173,7 @@ def _do_login(username=None, password=None, timeout=10, wait_after_load=2):
|
||||
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
if target_url_keyword in page.url:
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print(f"登录成功!当前 URL: {page.url}")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
@@ -153,29 +190,35 @@ def _do_login(username=None, password=None, timeout=10, wait_after_load=2):
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False, username=None, password=None):
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 OA 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||||
_set_login_state(False)
|
||||
|
||||
if not os.getenv('oa_login_url'):
|
||||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "未配置 oa_login_url 环境变量", "relogin": False}
|
||||
"message": "未配置 oa_login_url / oa_target_url_keyword 环境变量", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "未配置 oa_login_username / oa_login_password 环境变量", "relogin": False}
|
||||
|
||||
if not force:
|
||||
if load_cookies() and _is_oa_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 OA 登录态")
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_oa_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 OA 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
try:
|
||||
_do_login(username=username, password=password)
|
||||
ok = _do_login()
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录失败:{e}", "relogin": False}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
@@ -188,7 +231,11 @@ def main(args):
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
return ensure_login(force=force)
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -81,6 +81,11 @@ WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
# 加班校验统一使用该接口获取排班与打卡,替代原 caleHtml 排班接口与打卡流水接口
|
||||
ATTENDANCE_DAILY_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_count_leave_yc_day_all/redApiExec.mc"
|
||||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||||
# 打卡明细接口(按员工+日期范围返回真实打卡明细)
|
||||
# kq_time=真实打卡时间、bc_date=考勤归属日(跨天打卡次日0点~6点归入前一天)、
|
||||
# time_order=上下班类型(1=上班、2=下班)。加班校验用其替代考勤逐日接口的打卡字段,
|
||||
# 避免人工拼接日期导致跨天打卡归属错误。
|
||||
PUNCH_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId/redApiExec.mc"
|
||||
|
||||
# ---------- 加班审批规则常量 ----------
|
||||
WORK_START_TIME = "09:00"
|
||||
@@ -108,7 +113,9 @@ OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS = 1
|
||||
OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES = 0
|
||||
|
||||
# ---------- 分页 ----------
|
||||
DEFAULT_PAGE_SIZE = 15
|
||||
# 待办接口分页参数名正确应为 pageno/rowsize/pagingtype(fetch_todo_page 已修正);
|
||||
# 每页调大至 100 作为兜底:即便个别场景分页仍异常,一次请求也能尽量拉全,避免丢单
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
|
||||
|
||||
# ==================== 日志(影刀环境用 print 替代 logging) ====================
|
||||
@@ -179,12 +186,16 @@ def fetch_todo_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
"dataType": "todo",
|
||||
"fdType": FD_TYPE,
|
||||
"fdCateId": "",
|
||||
# 防缓存随机数:前端请求带 q.s_raq=<随机小数>,每次刷新
|
||||
"q.s_raq": str(random.random()),
|
||||
"q.fdSubject": subject,
|
||||
# 分页参数必须用 pageno/rowsize/pagingtype:
|
||||
# 用 page.pageNo/page.pageSize 会被服务端忽略,翻页返回重复数据
|
||||
"pageno": page_no,
|
||||
"rowsize": page_size,
|
||||
"pagingtype": "default",
|
||||
"orderby": "fdCreateTime",
|
||||
"ordertype": "down",
|
||||
"page.pageNo": page_no,
|
||||
"page.pageSize": page_size,
|
||||
"__seq": int(time.time() * 1000),
|
||||
}
|
||||
url = f"{TODO_LIST_URL}?{urlencode(params)}"
|
||||
logger.debug("请求第 %d 页: %s", page_no, url)
|
||||
@@ -437,6 +448,76 @@ def get_leave_records(session, staff_id, begin_date, end_date, page_size=DEFAULT
|
||||
return all_records
|
||||
|
||||
|
||||
def fetch_punch_record_page(session, staff_id, begin_date, end_date, page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
"""请求单页员工打卡明细。
|
||||
|
||||
接口: rf_s_kq_data_queryByStaffId/redApiExec.mc
|
||||
返回 data = {total, pageCount, list},list 每条含 kq_time(真实打卡时间)、
|
||||
bc_date(考勤归属日)、time_order(1=上班、2=下班) 等字段。
|
||||
"""
|
||||
data = {
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": str(page_no),
|
||||
"pageSize": str(page_size),
|
||||
"staff_id": staff_id,
|
||||
"rootId": "",
|
||||
"countId": "",
|
||||
"bc_date": begin_date,
|
||||
"bc_date_end": end_date,
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"sub_type": sub_type,
|
||||
}
|
||||
logger.info("获取打卡明细: staff_id=%s, %s 至 %s, 第%d页", staff_id, begin_date, end_date, page_no)
|
||||
|
||||
session.post(PUNCH_RECORD_URL, data=data)
|
||||
resp = session.response
|
||||
if not resp:
|
||||
raise RuntimeError("打卡明细请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"打卡明细接口状态码异常: {resp.status_code}")
|
||||
|
||||
try:
|
||||
json_data = resp.json()
|
||||
except Exception:
|
||||
body = (resp.text or "")[:200]
|
||||
raise RuntimeError(f"打卡明细接口返回非 JSON 数据: {body}")
|
||||
|
||||
if json_data.get("success") is not True or json_data.get("code") != 200:
|
||||
raise RuntimeError(f"打卡明细接口返回失败: {json_data}")
|
||||
|
||||
page_info = json_data.get("data")
|
||||
if not isinstance(page_info, dict):
|
||||
raise RuntimeError(f"打卡明细接口未返回 data 字段: {json_data}")
|
||||
return page_info
|
||||
|
||||
|
||||
def get_punch_records(session, staff_id, begin_date, end_date, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
"""查询员工某时间段内的全部打卡明细(自动分页)。
|
||||
|
||||
返回列表,每条含 kq_time(真实打卡时间 "YYYY-MM-DD HH:MM:SS")、
|
||||
bc_date(考勤归属日)、time_order(1=上班、2=下班)、status、address 等。
|
||||
"""
|
||||
all_records = []
|
||||
page_info = fetch_punch_record_page(session, staff_id, begin_date, end_date, page_no=1, page_size=page_size, sub_type=sub_type)
|
||||
total = int(page_info.get("total", 0))
|
||||
page_total = int(page_info.get("pageCount", 1))
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("打卡明细总数: %d, 第1页获取 %d 条", total, len(records))
|
||||
|
||||
if page_total > 1:
|
||||
for p in range(2, page_total + 1):
|
||||
page_info = fetch_punch_record_page(session, staff_id, begin_date, end_date, page_no=p, page_size=page_size, sub_type=sub_type)
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records))
|
||||
|
||||
return all_records
|
||||
|
||||
|
||||
# ==================== 加班表单解析 ====================
|
||||
OT_TYPE_MAP = {"1": "延时加班", "2": "法定假日加班", "3": "休息日加班"}
|
||||
SUBSIDY_TYPE_MAP = {"1": "转调休", "2": "转补贴"}
|
||||
@@ -1511,66 +1592,6 @@ def _extract_shift_times(daily_records, date_str):
|
||||
return None, None
|
||||
|
||||
|
||||
def _resolve_single_punch(day_summary, shift_begin, shift_end):
|
||||
"""当天仅一条打卡时,结合班次时段判断它是上班还是下班打卡。
|
||||
|
||||
考勤逐日数据中当天只有一条打卡时 last_check_out 固定为 None,
|
||||
会把唯一一条下班打卡误判成"当日无下班打卡"。这里按打卡时间与班次时段的
|
||||
相对位置修正:晚于班次中点(无班次时段时默认以 12:00 为分界)的打卡视为
|
||||
下班打卡,赋给"当日最晚打卡";否则仍视为上班打卡。
|
||||
|
||||
Returns:
|
||||
(当日最早打卡, 当日最晚打卡) 修正后的元组
|
||||
"""
|
||||
if not day_summary:
|
||||
return None, None
|
||||
first = day_summary.get("first_check_in")
|
||||
last = day_summary.get("last_check_out")
|
||||
if last is not None:
|
||||
return first, last
|
||||
if not first:
|
||||
return None, None
|
||||
t = _parse_dt(first)
|
||||
if t is None:
|
||||
return None, None
|
||||
mins = t.hour * 60 + t.minute
|
||||
mid = 12 * 60
|
||||
if shift_begin and shift_end:
|
||||
try:
|
||||
sb = int(shift_begin[:2]) * 60 + int(shift_begin[3:5])
|
||||
se = int(shift_end[:2]) * 60 + int(shift_end[3:5])
|
||||
mid = (sb + se) // 2
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
if mins >= mid:
|
||||
# 晚于班次中点:视为下班打卡
|
||||
return None, first
|
||||
return first, None
|
||||
|
||||
|
||||
# 每日考勤记录中携带的上下班打卡字段(sb=上班、xb=下班,可能分多个时段)
|
||||
_PUNCH_TIME_FIELDS = ("sb_dk_time", "xb_dk_time", "sb_dk_time2", "xb_dk_time2", "sb_dk_time3", "xb_dk_time3")
|
||||
|
||||
|
||||
def _collect_day_punches(record, work_day):
|
||||
"""收集某日考勤记录中的全部上下班打卡时间。
|
||||
|
||||
打卡字段为 "HH:MM:SS"(无打卡为 null),这里拼上日期返回
|
||||
"YYYY-MM-DD HH:MM:SS" 完整时间并升序排序,供最早/最晚打卡提取与 _parse_dt 解析。
|
||||
"""
|
||||
if not record or not work_day:
|
||||
return []
|
||||
punches = []
|
||||
for field in _PUNCH_TIME_FIELDS:
|
||||
v = record.get(field)
|
||||
if v:
|
||||
s = str(v).strip()
|
||||
if s:
|
||||
punches.append(f"{work_day} {s}")
|
||||
punches.sort()
|
||||
return punches
|
||||
|
||||
|
||||
def _check_punch_records(session, staff_id, ot_date):
|
||||
if not ot_date or not staff_id:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
@@ -1582,34 +1603,48 @@ def _check_punch_records(session, staff_id, ot_date):
|
||||
next_day = (start + timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
|
||||
try:
|
||||
# 统一调用考勤逐日接口一次,即可拿到班次名/班次起止时间/上下班打卡,
|
||||
# 替代原排班日历接口与打卡流水接口;范围扩到前一天是为了兼容提前到岗型
|
||||
# 加班(开始<=6点)到岗打卡被归到前一天的情况。
|
||||
daily = get_attendance_daily(session, staff_id, prev_day, next_day)
|
||||
prev_record = next((r for r in daily if str(r.get("work_day", "")) == prev_day), None)
|
||||
day_record = next((r for r in daily if str(r.get("work_day", "")) == ot_date), None)
|
||||
next_record = next((r for r in daily if str(r.get("work_day", "")) == next_day), None)
|
||||
if not day_record and not next_record and not prev_record:
|
||||
# 打卡明细接口返回 kq_time=真实打卡时间 与 bc_date=考勤归属日,
|
||||
# 跨天打卡(次日0点~6点)由系统归入加班当天,无需人工拼接/修正日期;
|
||||
# 范围扩到前一天是为了兼容提前到岗型加班(开始<=6点)到岗打卡被归到前一天的情况。
|
||||
punches = get_punch_records(session, staff_id, prev_day, next_day)
|
||||
if not punches:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
|
||||
"打卡备注": "当天及次日无打卡记录"}
|
||||
# 班次起止时间:取当日实际班次时段(如维护早班 08:00-17:00),
|
||||
# 未获取到时由上层回退默认 09:00/18:00;接口失败不影响打卡数据
|
||||
# 按考勤归属日 bc_date 分组;time_order:1=上班打卡、2=下班打卡
|
||||
arrivals = {}
|
||||
checkouts = {}
|
||||
all_by_date = {}
|
||||
for r in punches:
|
||||
bd = str(r.get("bc_date", "")).strip()
|
||||
t = str(r.get("kq_time", "")).strip()
|
||||
if not bd or not t:
|
||||
continue
|
||||
all_by_date.setdefault(bd, []).append(t)
|
||||
if str(r.get("time_order", "")).strip() == "1":
|
||||
arrivals.setdefault(bd, []).append(t)
|
||||
elif str(r.get("time_order", "")).strip() == "2":
|
||||
checkouts.setdefault(bd, []).append(t)
|
||||
# 班次起止时间仍由考勤逐日接口提供;未获取到时由上层回退默认 09:00/18:00
|
||||
daily = get_attendance_daily(session, staff_id, prev_day, next_day)
|
||||
shift_begin, shift_end = _extract_shift_times(daily, ot_date)
|
||||
# 当日最早/最晚打卡;单条打卡时结合班次时段识别是上班还是下班打卡
|
||||
day_punches = _collect_day_punches(day_record, ot_date)
|
||||
day_summary = {
|
||||
"first_check_in": day_punches[0] if day_punches else None,
|
||||
# 仅1条打卡时 last_check_out 置空,交由 _resolve_single_punch 结合班次时段修正
|
||||
"last_check_out": day_punches[-1] if len(day_punches) > 1 else None,
|
||||
}
|
||||
day_first, day_last = _resolve_single_punch(day_summary, shift_begin, shift_end)
|
||||
|
||||
def _sorted(date_str):
|
||||
return sorted(all_by_date.get(date_str, []))
|
||||
|
||||
# 当日最早/最晚打卡:优先按上下班类型取,缺该类型时回退取当天全部打卡
|
||||
day_all = _sorted(ot_date)
|
||||
day_arrivals = sorted(arrivals.get(ot_date, []))
|
||||
day_checkouts = sorted(checkouts.get(ot_date, []))
|
||||
day_first = day_arrivals[0] if day_arrivals else (day_all[0] if day_all else None)
|
||||
day_last = day_checkouts[-1] if day_checkouts else (day_all[-1] if day_all else None)
|
||||
# 次日最早打卡(弹性兑换用)
|
||||
next_punches = _collect_day_punches(next_record, next_day)
|
||||
next_first = next_punches[0] if next_punches else None
|
||||
next_arrivals = sorted(arrivals.get(next_day, []))
|
||||
next_all = _sorted(next_day)
|
||||
next_first = next_arrivals[0] if next_arrivals else (next_all[0] if next_all else None)
|
||||
# 前一天最晚打卡(提前到岗型加班用)
|
||||
prev_punches = _collect_day_punches(prev_record, prev_day)
|
||||
prev_last = prev_punches[-1] if prev_punches else None
|
||||
prev_all = _sorted(prev_day)
|
||||
prev_last = prev_all[-1] if prev_all else None
|
||||
return {
|
||||
"当日最早打卡": day_first,
|
||||
"当日最晚打卡": day_last,
|
||||
@@ -1827,20 +1862,11 @@ def _validate_day_ot(info, punch, session, staff_id, require_holiday):
|
||||
|
||||
first = _parse_dt(punch.get("当日最早打卡"))
|
||||
last = _parse_dt(punch.get("当日最晚打卡"))
|
||||
next_first = _parse_dt(punch.get("次日最早打卡"))
|
||||
interval = None
|
||||
# 打卡明细接口已按考勤归属日 bc_date 分组,跨天打卡(次日0点~6点)归入加班当天,
|
||||
# 因此当日最早/最晚打卡已包含跨天下班打卡,无需再参考次日打卡补全。
|
||||
if first is None or last is None:
|
||||
# 跨天打卡处理:当天缺打卡时参考次日首条打卡,次日首条早于6点视为归属加班当天
|
||||
if next_first is not None and next_first.hour < CROSS_DAY_BEFORE_HOUR:
|
||||
had_punch = (first is not None) or (last is not None)
|
||||
first = first if first is not None else next_first
|
||||
last = last if last is not None else next_first
|
||||
info["跨天打卡"] = "是"
|
||||
# 当天全无打卡时仅凭跨天记录,视为满足"至少一条打卡"要求,不计算间隔
|
||||
if had_punch:
|
||||
interval = (last - first).total_seconds() / 3600
|
||||
else:
|
||||
reasons.append("当天缺少上班或下班打卡")
|
||||
reasons.append("当天缺少上班或下班打卡")
|
||||
else:
|
||||
interval = (last - first).total_seconds() / 3600
|
||||
|
||||
|
||||
Reference in New Issue
Block a user