feat(hrbp): 完成HRBP加班审批系统全链路开发
新增: 1. 新增依赖包chinese_calendar,完善.gitignore会话存储配置 2. 新增完整测试套件与项目初始化文件 3. 实现延时/休息日/法定假日加班审批规则(参考aa.md文档) 4. 新增排班、打卡、请假数据获取与解析工具 5. 完善会话管理与持久化存储逻辑 6. 实现格式化审批报告生成功能 修改: 1. 调整请假校验函数签名以传入会话对象 2. 更新审批流程调用逻辑适配新校验函数 3. 重构cookie存储路径与目录创建逻辑 4. 优化日志输出级别与调试信息
This commit is contained in:
+2
-1
@@ -26,7 +26,8 @@ ENV/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.oa_cookies.json
|
||||
# 各平台会话 cookies 持久化目录(OA / 其他平台共用,按平台名分文件)
|
||||
app/service/.sessions/
|
||||
|
||||
# ---------- IDE ----------
|
||||
.idea/
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
一、延时加班
|
||||
(一)驳回门槛(任一不满足直接驳回)
|
||||
1. 日期匹配规则:加班开始时间所属日期 = 加班申请日期。当日开始、次日结束的跨天加班,按开始时间判定日期,视为符合要求。
|
||||
2. 时长达标规则:以「申请结束时间 - 申请开始时间」计算申请加班总时长,统一执行以下计时标准:
|
||||
◦ 不足1小时的,直接驳回;
|
||||
◦ 满1小时及以上的,超出1小时的部分按0.5小时为单位向下取整累加,不足0.5小时的部分不计入有效时长。
|
||||
◦ 跨天延时加班的总时长统一套用上述取整规则,不按日期分段计算。
|
||||
3. 区间合规校验:申请开始时间 ≥ 当日规定下班时间,且申请结束时间 ≤ 当日实际下班打卡时间;超出该区间的申请直接驳回。
|
||||
(二)弹性到岗兑换规则(仅影响结算时长,不影响审批通过与否)
|
||||
员工可使用当日加班时长等额兑换次日晚到时长,兑换额度、校验规则如下:
|
||||
1. 弹性额度D计算规则
|
||||
◦ 计算基准:以当日实际下班打卡时间为准,与申请结束时间无关。
|
||||
◦ 触发条件:实际下班打卡时间 < 23:00 时,弹性额度 D=0,不可兑换次日晚到。
|
||||
◦ 额度计算公式:实际下班打卡时间 ≥ 23:00 时,基础兑换额度1小时;超出23:00的部分,按0.5小时为单位向下取整,每满0.5小时累加0.5小时额度。
|
||||
公式:D = 1 + FLOOR( (实际下班打卡时间 - 23:00) / 0.5小时 ) × 0.5小时
|
||||
2. 次日场景分支校验
|
||||
对申请日的次日进行判断,符合以下任一情形的,不触发弹性兑换校验,仅校验当日申请与打卡、请假数据匹配(次日为休息且存在加班申请的,同步核实上班打卡记录):
|
||||
① 次日排班为“休息”或无排班;
|
||||
② 次日排班数据获取失败;
|
||||
③ 次日有请假时段覆盖09:00(任意假期类型)。
|
||||
不属于以上情形的正常工作日,按次日实际打卡时间P进行校验:
|
||||
① 无次日打卡记录:不触发弹性兑换校验,仅校验当日数据;
|
||||
② P ≤ 09:00:无晚到,无需兑换,直接通过;
|
||||
③ 09:00 < P ≤ 09:00+D:实际晚到时长 = P - 09:00,不足1小时按1小时计算;
|
||||
校验规则:申请加班时长 + 实际晚到时长 ≤ 申请加班时间至实际打卡的总自然时长,不符合则驳回;
|
||||
④ P > 09:00+D:可兑换的晚到时长最高按D计算,超出D的晚到部分按考勤迟到规则处理,不影响本次加班审批;
|
||||
校验规则:申请加班时长 + D ≤ 申请加班时间至实际打卡的总自然时长,不符合则驳回。
|
||||
---
|
||||
二、休息日加班
|
||||
(一)适用范围
|
||||
1. 周末休息日加班;
|
||||
2. 除春节外的其余法定节假日加班,统一按本规则执行。
|
||||
(二)审批条件(全部满足则通过,任一不满足即驳回)
|
||||
1. 申请有效:申请加班时长 > 0;
|
||||
2. 打卡完整:申请对应时段内有完整的上班打卡、下班打卡记录;跨次日0点的连续加班,下班打卡可在次日,只要时段连续、覆盖申请时段,即视为打卡完整;
|
||||
3. 排班匹配:申请当日排班显示为休息;
|
||||
4. 时长达标:上下班打卡的自然时间间隔(含午休、用餐等自然时长)满足申报档位要求:
|
||||
◦ 申报0.5天:打卡间隔 ≥ 4小时
|
||||
◦ 申报1天:打卡间隔 ≥ 9小时
|
||||
◦ 申报1.5天:打卡间隔 ≥ 13小时
|
||||
◦ 申报2天:打卡间隔 ≥ 18小时
|
||||
以此类推,每增加0.5天,对应时长要求增加4小时。
|
||||
---
|
||||
三、法定假日加班(仅春节法定节假日适用)
|
||||
1. 基础审批规则与休息日加班完全一致;
|
||||
2. 额外校验:申请日期必须为春节法定节假日;春节假期内的调休休息日,不适用本规则,按休息日加班规则执行。
|
||||
---
|
||||
+4
-1
@@ -1,6 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: app
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:00
|
||||
@Description: 应用主包
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
"""
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:00
|
||||
@Description: HRBP 审批服务包:oa(OA 系统公共模块)+ flows(业务流程:请假/加班等)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:00
|
||||
@Description: OA 系统模块:包含 common(公共组件)、leave(请假流程)、work_overtime(加班流程)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
"""
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:00
|
||||
@Description: OA 系统公共模块:登录、会话管理、接口调用、解析
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
@@ -131,7 +131,7 @@ def _fetch_doc_detail(browser, session, doc: Dict[str, Any]) -> Dict[str, Any]:
|
||||
|
||||
def run_flow(
|
||||
subject: str,
|
||||
validate_doc: Callable[[Dict[str, Any]], Dict[str, Any]],
|
||||
validate_doc: Callable[[Dict[str, Any], Any], Dict[str, Any]],
|
||||
generate_report: Callable[[List[Dict[str, Any]]], str],
|
||||
) -> str:
|
||||
"""
|
||||
@@ -139,7 +139,7 @@ def run_flow(
|
||||
|
||||
Args:
|
||||
subject: 待办标题关键字,如 "加班" / "请假"
|
||||
validate_doc: 单张单据的校验函数(业务规则在各自模块实现)
|
||||
validate_doc: 单张单据的校验函数,签名为 (doc, session) -> result
|
||||
generate_report: 校验结果报告生成函数
|
||||
|
||||
Returns:
|
||||
@@ -157,7 +157,7 @@ def run_flow(
|
||||
for doc in docs:
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail)
|
||||
result = validate_doc(doc_detail, session)
|
||||
results.append(result)
|
||||
logger.info(
|
||||
"已校验: %s - %s -> %s",
|
||||
|
||||
@@ -12,12 +12,35 @@
|
||||
# 待办列表等后台接口在 oa 域名;流程引擎/表单/考勤等 RedseaPlatform 接口在 hr 域名
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
# 待办列表接口(oa 域名):按标题关键字查询当前账号的待办单据,用于抓取请假/加班等待审批流程
|
||||
TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
||||
# 待办类型编码:"13" 对应需人工处理的审批类待办
|
||||
FD_TYPE = "13"
|
||||
|
||||
# OA 流程接口(hr 域名)
|
||||
# 通过 taskId 获取流程表单 ID(formId),用于后续拉取表单详情
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
# 表单引擎接口:通过 businessKey + formId 获取审批单的表单数据(如加班日期、申请人等)
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
|
||||
# 排班接口(hr 域名,按员工 + 年月查询当月排班)
|
||||
PAIBAN_URL = f"{HR_BASE_URL}/RedseaPlatform/KqCount.mc"
|
||||
|
||||
# 考勤打卡明细接口(hr 域名,按员工 + 日期范围查询原始打卡记录)
|
||||
KQ_DATA_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId_all/getExecuteResult.mc"
|
||||
|
||||
# 请假记录接口(hr 域名,按员工 + 日期范围查询请假明细)
|
||||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||||
|
||||
# ---------- 加班审批规则常量(对应 aa.md 审批规则) ----------
|
||||
# 次日正常上班时间 T(固定 09:00)
|
||||
WORK_START_TIME = "09:00"
|
||||
# 当日规定下班时间(固定 18:00,用于区间合规校验)
|
||||
WORK_END_TIME = "18:00"
|
||||
# 弹性额度触发阈值:实际下班打卡时间 >= 该时刻才计算弹性额度 D
|
||||
FLEX_TRIGGER_TIME = "23:00"
|
||||
# 延时加班有效时长门槛:不足该小时数直接驳回
|
||||
OT_MIN_HOURS = 1
|
||||
|
||||
# ---------- 分页 ----------
|
||||
DEFAULT_PAGE_SIZE = 15
|
||||
|
||||
@@ -24,9 +24,9 @@ except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
try:
|
||||
from .config import BASE_URL, HR_BASE_URL, TODO_LIST_URL, DEFAULT_PAGE_SIZE, FD_TYPE, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL
|
||||
from .config import BASE_URL, HR_BASE_URL, TODO_LIST_URL, DEFAULT_PAGE_SIZE, FD_TYPE, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL, KQ_DATA_URL, LEAVE_RECORD_URL, PAIBAN_URL
|
||||
except ImportError:
|
||||
from config import BASE_URL, HR_BASE_URL, TODO_LIST_URL, DEFAULT_PAGE_SIZE, FD_TYPE, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL
|
||||
from config import BASE_URL, HR_BASE_URL, TODO_LIST_URL, DEFAULT_PAGE_SIZE, FD_TYPE, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL, KQ_DATA_URL, LEAVE_RECORD_URL, PAIBAN_URL
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -209,7 +209,7 @@ def get_wf_activity_by_task_id(
|
||||
f"WfActivity 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}"
|
||||
)
|
||||
|
||||
logger.info("WfActivity 返回: %s", json_data)
|
||||
logger.debug("WfActivity 返回: %s", json_data)
|
||||
return json_data
|
||||
|
||||
|
||||
@@ -324,7 +324,7 @@ def get_attendance_html(
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
url = f"{HR_BASE_URL}/RedseaPlatform/KqCount.mc?method=geRenPaibanByMonth"
|
||||
url = f"{PAIBAN_URL}?method=geRenPaibanByMonth"
|
||||
data = {
|
||||
"type": "2",
|
||||
"staffId": staff_id,
|
||||
@@ -352,3 +352,181 @@ def get_attendance_html(
|
||||
if not html:
|
||||
raise RuntimeError("排班接口未返回 caleHtml 字段")
|
||||
return html
|
||||
|
||||
|
||||
# ---------- 考勤打卡明细接口 ----------
|
||||
def get_attendance_records(
|
||||
session: SessionPage,
|
||||
staff_id: str,
|
||||
start_date: str,
|
||||
end_date: str
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
查询员工某时间段的原始打卡明细。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
staff_id: 员工 UUID
|
||||
start_date: 查询起始日期 "YYYY-MM-DD"
|
||||
end_date: 查询结束日期 "YYYY-MM-DD"
|
||||
|
||||
Returns:
|
||||
打卡记录列表(接口返回的 jsonList,每条含 kq_time / status / time_order 等)
|
||||
- status: "1"=上班打卡, "5"=下班打卡, "6"=重复打卡
|
||||
- time_order: "1"=上班时段, "2"=下班时段
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
params = {
|
||||
"staff_id": staff_id,
|
||||
"rootId": "",
|
||||
"countId": "",
|
||||
"bc_date": start_date,
|
||||
"bc_date_end": end_date,
|
||||
"begin": start_date,
|
||||
"end": end_date,
|
||||
}
|
||||
logger.info("获取打卡明细: staff_id=%s, %s 至 %s", staff_id, start_date, end_date)
|
||||
|
||||
session.get(KQ_DATA_URL, params=params)
|
||||
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}")
|
||||
|
||||
records = json_data.get("jsonList", [])
|
||||
logger.info("打卡明细返回 %d 条", len(records))
|
||||
return records
|
||||
|
||||
|
||||
# ---------- 请假记录接口 ----------
|
||||
def fetch_leave_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"
|
||||
end_date: 查询结束日期 "YYYY-MM-DD"
|
||||
page_no: 页码(从1开始)
|
||||
page_size: 每页条数
|
||||
sub_type: 假期类型编码,默认 "-1" 表示全部
|
||||
|
||||
Returns:
|
||||
接口返回的 data 字段字典,包含 total / pageCount / list
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
data = {
|
||||
"sub_type": sub_type,
|
||||
"staff_id": staff_id,
|
||||
"begin_date": begin_date,
|
||||
"end_date": end_date,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"pageSize": str(page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": str(page_no),
|
||||
}
|
||||
logger.info("获取请假记录: staff_id=%s, %s 至 %s, 第%d页", staff_id, begin_date, end_date, page_no)
|
||||
|
||||
session.post(LEAVE_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_leave_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:
|
||||
请假记录列表,每条包含:
|
||||
- staff_id: 员工ID
|
||||
- staff_name: 员工姓名
|
||||
- leave_businessKey: 审批单号
|
||||
- sub_type: 假期类型编码
|
||||
- vacation_type_name: 假期名称
|
||||
- leave_reason: 请假原因
|
||||
- leave_days: 请假天数
|
||||
- leave_hours: 请假小时
|
||||
- start_time: 开始时间
|
||||
- end_time: 结束时间
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
all_records: List[Dict[str, Any]] = []
|
||||
|
||||
# 请求第一页,获取总条数与总页数
|
||||
page_info = fetch_leave_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_leave_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
|
||||
|
||||
@@ -11,7 +11,9 @@
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
from typing import Dict, List
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
||||
|
||||
@@ -82,6 +84,59 @@ def get_work_days_in_range(
|
||||
return work_days
|
||||
|
||||
|
||||
# ---------- 打卡明细汇总 ----------
|
||||
def summarize_attendance_records(records: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
按日汇总员工打卡明细:每天取最早打卡和最晚打卡。
|
||||
|
||||
实际接口返回的打卡记录 status 多为 "6"、time_order 为 null,
|
||||
无法据其区分上下班,因此直接按 bc_date 分组后取时间最早和最晚的打卡。
|
||||
|
||||
Args:
|
||||
records: get_attendance_records 返回的原始打卡列表
|
||||
|
||||
Returns:
|
||||
每日汇总列表,每项含:
|
||||
- staff_id / staff_name / dept_name / post_name / attend_date
|
||||
- first_check_in: 当日最早打卡时间(字符串,无则 None)
|
||||
- last_check_out: 当日最晚打卡时间(字符串,仅1条时为 None,含跨天凌晨)
|
||||
"""
|
||||
time_format = "%Y-%m-%d %H:%M:%S"
|
||||
|
||||
# 按 (staff_id, bc_date) 分组,取每天最早和最晚的打卡
|
||||
group_map: Dict[tuple, List[Dict[str, Any]]] = defaultdict(list)
|
||||
|
||||
for item in records:
|
||||
staff_id = item.get("staff_id", "")
|
||||
bc_day = item.get("bc_date", "")
|
||||
if not staff_id or not bc_day:
|
||||
continue
|
||||
|
||||
try:
|
||||
kq_dt = datetime.strptime(item["kq_time"], time_format)
|
||||
except (KeyError, ValueError):
|
||||
continue
|
||||
|
||||
group_map[(staff_id, bc_day)].append({**item, "_dt": kq_dt})
|
||||
|
||||
summary: List[Dict[str, Any]] = []
|
||||
for (sid, day), items in group_map.items():
|
||||
items.sort(key=lambda x: x["_dt"])
|
||||
base = items[0]
|
||||
row = {
|
||||
"staff_id": sid,
|
||||
"staff_name": base.get("staff_name", ""),
|
||||
"dept_name": base.get("DEPT_ORG_NAME", ""),
|
||||
"post_name": base.get("POST_ALIAS_NAME", ""),
|
||||
"attend_date": day,
|
||||
"first_check_in": items[0]["kq_time"],
|
||||
"last_check_out": items[-1]["kq_time"] if len(items) > 1 else None,
|
||||
}
|
||||
summary.append(row)
|
||||
|
||||
return summary
|
||||
|
||||
|
||||
# ---------- 使用示例(测试用) ----------
|
||||
if __name__ == "__main__":
|
||||
from utils.logger import setup_logging
|
||||
@@ -98,3 +153,15 @@ if __name__ == "__main__":
|
||||
|
||||
work = get_work_days_in_range(result, "2026-08-01", "2026-08-03")
|
||||
logger.info("工作日: %s", work)
|
||||
|
||||
# 测试打卡汇总
|
||||
sample_records = [
|
||||
{"staff_id": "S001", "staff_name": "张三", "bc_date": "2026-08-02",
|
||||
"kq_time": "2026-08-02 08:50:00", "status": "1", "time_order": "1",
|
||||
"DEPT_ORG_NAME": "技术部", "POST_ALIAS_NAME": "工程师"},
|
||||
{"staff_id": "S001", "staff_name": "张三", "bc_date": "2026-08-02",
|
||||
"kq_time": "2026-08-03 00:30:00", "status": "5", "time_order": "2",
|
||||
"DEPT_ORG_NAME": "技术部", "POST_ALIAS_NAME": "工程师"},
|
||||
]
|
||||
summary = summarize_attendance_records(sample_records)
|
||||
logger.info("打卡汇总: %s", summary)
|
||||
|
||||
@@ -24,8 +24,10 @@ except ImportError:
|
||||
ChromiumPage = None
|
||||
SessionPage = None
|
||||
|
||||
# 登录 cookies 持久化文件(复用登录态,免重复登录)
|
||||
COOKIE_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '.oa_cookies.json')
|
||||
# 登录 cookies 持久化目录:服务层统一管理各平台会话文件,文件名按平台区分
|
||||
# 如 oa_cookies.json / xxx_cookies.json,便于后续扩展其他平台
|
||||
_SESSIONS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
|
||||
|
||||
def init_session_from_page(
|
||||
@@ -92,6 +94,7 @@ def save_browser_cookies(browser_page: ChromiumPage, path: str = COOKIE_FILE) ->
|
||||
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)
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:00
|
||||
@Description: 请假审批流程包
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
"""
|
||||
|
||||
@@ -6,9 +6,6 @@
|
||||
@CreateTime: 2026-08-05 21:21
|
||||
@Description: 请假审批流程入口(审批引擎见 common/approval_flow.py,校验规则见 validator.py,报告见 reporter.py)
|
||||
@Version: 1.2.0
|
||||
|
||||
@Usage:
|
||||
python -m hrbp.oa.leave.leave_approval
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
def validate_doc(doc: Dict[str, Any]) -> Dict[str, Any]:
|
||||
def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]:
|
||||
"""
|
||||
校验单张请假单据,返回审批决策。
|
||||
|
||||
@@ -20,6 +20,7 @@ def validate_doc(doc: Dict[str, Any]) -> Dict[str, Any]:
|
||||
Args:
|
||||
doc: 单据信息,含基本信息(title/creator/time/detail_url)
|
||||
和审批引擎已获取的 taskId/businessKey/formId/formData(表单详情)
|
||||
session: 已登录的 SessionPage 对象(用于调用排班接口)
|
||||
|
||||
Returns:
|
||||
校验结果,包含审批决策
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.work_overtime
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:00
|
||||
@Description: 加班审批流程包
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
"""
|
||||
|
||||
@@ -6,9 +6,6 @@
|
||||
@CreateTime: 2026-08-05 21:22
|
||||
@Description: 加班审批流程入口(审批引擎见 common/approval_flow.py,校验规则见 validator.py,报告见 reporter.py)
|
||||
@Version: 1.4.0
|
||||
|
||||
@Usage:
|
||||
python -m hrbp.oa.work_overtime.overtime_approval
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.work_overtime.parser
|
||||
@FileName: parser.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 09:30
|
||||
@Description: 加班表单解析模块(解析 WorkformEngine 返回的 result,提取关键字段并转换为中文描述)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from typing import Any, Dict
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
||||
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# 加班类型映射
|
||||
OT_TYPE_MAP = {
|
||||
"1": "延时加班",
|
||||
"2": "法定假日加班",
|
||||
"3": "休息日加班",
|
||||
}
|
||||
|
||||
# 补贴类型映射
|
||||
SUBSIDY_TYPE_MAP = {
|
||||
"1": "转调休",
|
||||
"2": "转补贴",
|
||||
}
|
||||
|
||||
|
||||
def parse_overtime_form(result: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
解析加班表单数据,提取关键字段并将代码转换为中文描述。
|
||||
|
||||
注意:入参为 oa_api.get_business_data 返回的 result 字段(state 校验已在
|
||||
get_business_data 内完成),即审批引擎 doc['formData']。
|
||||
|
||||
Args:
|
||||
result: WorkformEngine 返回的 result 字典(含 ot_type / staff_name 等)
|
||||
|
||||
Returns:
|
||||
包含加班关键字段的字典(中文键名);找不到映射时保留原始代码值
|
||||
"""
|
||||
# 获取原始类型代码
|
||||
ot_type_code = result.get("ot_type")
|
||||
subsidy_type_code = result.get("subsidy_type")
|
||||
|
||||
overtime_info = {
|
||||
"加班人员ID": result.get("staff_id"),
|
||||
"加班人员": result.get("staff_name"),
|
||||
"所属部门": result.get("dept_org_name"),
|
||||
"加班类型": OT_TYPE_MAP.get(ot_type_code, ot_type_code),
|
||||
"补贴类型": SUBSIDY_TYPE_MAP.get(subsidy_type_code, subsidy_type_code),
|
||||
"加班日期": result.get("ot_date"),
|
||||
"加班开始时间": result.get("start_time"),
|
||||
"加班结束时间": result.get("end_time"),
|
||||
"加班时长(小时)": result.get("ot_hour"),
|
||||
"加班天数(天)": result.get("ot_day"),
|
||||
"系统判断加班时长(小时)": result.get("judge_ot_hour"),
|
||||
"系统判断加班天数(天)": result.get("judge_ot_day"),
|
||||
"附件": result.get("file"),
|
||||
}
|
||||
|
||||
# 拼接系统判定的加班时间段
|
||||
judge_start = result.get("judge_start_time")
|
||||
judge_end = result.get("judge_end_time")
|
||||
if judge_start and judge_end:
|
||||
overtime_info["系统判定加班时间"] = f"{judge_start} 至 {judge_end}"
|
||||
else:
|
||||
overtime_info["系统判定加班时间"] = None
|
||||
|
||||
return overtime_info
|
||||
|
||||
|
||||
# ---------- 使用示例(测试用) ----------
|
||||
if __name__ == "__main__":
|
||||
from utils.logger import setup_logging
|
||||
setup_logging()
|
||||
|
||||
# 示例 result(WorkformEngine 返回的 result 字段)
|
||||
sample_result = {
|
||||
"dept_org_name": "网络项目小组",
|
||||
"end_time": "2026-08-03 00:00",
|
||||
"judge_end_time": "2026-08-03 00:00:00",
|
||||
"judge_ot_hour": 6.0,
|
||||
"judge_start_time": "2026-08-02 18:00:00",
|
||||
"ot_date": "2026-08-02",
|
||||
"ot_hour": 6.0,
|
||||
"ot_type": "1",
|
||||
"staff_id": "572e6cce-7a9f-11ec-b449-000c296f9469",
|
||||
"staff_name": "黄俊林",
|
||||
"start_time": "2026-08-02 18:00",
|
||||
"subsidy_type": "2",
|
||||
"file": "ccc1d3ef-175a-4105-a8a8-0e63ed88d7bd",
|
||||
}
|
||||
|
||||
parsed = parse_overtime_form(sample_result)
|
||||
logger.info("===== 加班信息解析结果 =====")
|
||||
for key, value in parsed.items():
|
||||
logger.info("%s: %s", key, value)
|
||||
@@ -4,18 +4,46 @@
|
||||
@FileName: reporter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:35
|
||||
@Description: 加班流程报告模块,生成审批报告
|
||||
@Version: 1.0.0
|
||||
@Description: 加班流程报告模块,生成审批报告(详细数据版,供自测阶段人工复核)
|
||||
@Version: 1.3.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
|
||||
def _format_detail(idx: int, r: Dict[str, Any]) -> str:
|
||||
"""
|
||||
格式化单条记录的详细信息:展示全部解析数据,最后是判断结果。
|
||||
所有键值对左对齐,方便人工逐项核对。
|
||||
"""
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
|
||||
# 收集全部要展示的键值对:先数据,后判断结果
|
||||
items: List[tuple] = list(info.items())
|
||||
items.append(("审批结果", r.get("decision", "")))
|
||||
if r.get("note"):
|
||||
items.append(("说明", r.get("note", "")))
|
||||
if r.get("error"):
|
||||
items.append(("错误", r.get("error", "")))
|
||||
|
||||
max_key = max((len(k) for k, _ in items), default=0)
|
||||
|
||||
lines = [
|
||||
f"#{idx} 申请人: {r.get('creator', '')} | {r.get('title', '')}",
|
||||
"-" * 60,
|
||||
]
|
||||
for key, value in items:
|
||||
lines.append(f" {key:<{max_key}} : {value}")
|
||||
lines.append("-" * 60)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
"""
|
||||
根据校验结果生成加班审批报告。
|
||||
根据校验结果生成加班审批报告(详细数据版)。
|
||||
|
||||
TODO: 按实际报告格式完善(与请假报告不同,含加班时长等字段)。
|
||||
每条记录展示全部解析数据(人员、日期、起止时间、时长、排班、打卡、
|
||||
申报天数、计算结果等),最后是审批结果和说明,供自测阶段人工复核。
|
||||
|
||||
Args:
|
||||
results: validate_doc 返回的校验结果列表
|
||||
@@ -23,7 +51,32 @@ def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
lines = ["加班审批报告", "=" * 30]
|
||||
for r in results:
|
||||
lines.append(f"{r.get('creator', '')} | {r.get('title', '')} | {r.get('decision', '')}")
|
||||
return "\n".join(lines)
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "不通过"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
lines = [
|
||||
"加班审批报告",
|
||||
"=" * 60,
|
||||
f"共 {len(results)} 单:通过 {len(passed)},不通过 {len(rejected)},处理失败 {len(failed)}",
|
||||
"",
|
||||
]
|
||||
|
||||
if rejected:
|
||||
lines.append("【审批未通过名单】")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
lines.append(_format_detail(i, r))
|
||||
lines.append("")
|
||||
|
||||
if passed:
|
||||
lines.append("【审批通过名单】")
|
||||
for i, r in enumerate(passed, 1):
|
||||
lines.append(_format_detail(i, r))
|
||||
lines.append("")
|
||||
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
lines.append(_format_detail(i, r))
|
||||
|
||||
return "\n".join(lines)
|
||||
@@ -4,30 +4,444 @@
|
||||
@FileName: validator.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:35
|
||||
@Description: 加班流程校验模块(审批规则:驳回/人工复核/通过)
|
||||
@Version: 1.0.0
|
||||
@Description: 加班流程校验模块(按 aa.md 审批规则:延时加班/休息日加班/法定假日加班,判定通过/不通过)
|
||||
@Version: 3.0.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
||||
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
try:
|
||||
from .parser import parse_overtime_form
|
||||
from ..common.oa_api import (
|
||||
get_attendance_html,
|
||||
get_attendance_records,
|
||||
get_leave_records,
|
||||
)
|
||||
from ..common.parser import parse_attendance_html, summarize_attendance_records
|
||||
from ..common.config import (
|
||||
WORK_START_TIME,
|
||||
WORK_END_TIME,
|
||||
FLEX_TRIGGER_TIME,
|
||||
OT_MIN_HOURS,
|
||||
)
|
||||
except ImportError:
|
||||
from parser import parse_overtime_form
|
||||
from common.oa_api import (
|
||||
get_attendance_html,
|
||||
get_attendance_records,
|
||||
get_leave_records,
|
||||
)
|
||||
from common.parser import parse_attendance_html, summarize_attendance_records
|
||||
from common.config import (
|
||||
WORK_START_TIME,
|
||||
WORK_END_TIME,
|
||||
FLEX_TRIGGER_TIME,
|
||||
OT_MIN_HOURS,
|
||||
)
|
||||
|
||||
|
||||
def validate_doc(doc: Dict[str, Any]) -> Dict[str, Any]:
|
||||
# ---------- 通用工具 ----------
|
||||
def _parse_dt(value: Any) -> Optional[datetime]:
|
||||
"""解析 "YYYY-MM-DD HH:MM[:SS]" 格式时间,失败返回 None"""
|
||||
if not value:
|
||||
return None
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M"):
|
||||
try:
|
||||
return datetime.strptime(str(value), fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _calc_delayed_hours(start: datetime, end: datetime) -> float:
|
||||
"""
|
||||
校验单张加班单据,返回审批决策。
|
||||
延时加班计时:1小时起算,超过1小时的部分按0.5小时累加,不足0.5小时舍去。
|
||||
不足1小时返回0。
|
||||
|
||||
TODO: 加班审批规则在此实现(与请假规则不同,依据加班时长、时段等判定通过/驳回/人工复核)。
|
||||
示例:1.0->1.0, 1.4->1.0, 1.5->1.5, 1.9->1.5, 2.0->2.0, 2.3->2.0, 2.5->2.5
|
||||
"""
|
||||
total = (end - start).total_seconds() / 3600
|
||||
if total < 1:
|
||||
return 0.0
|
||||
return 1.0 + math.floor((total - 1) / 0.5) * 0.5
|
||||
|
||||
|
||||
def _calc_flex_d(actual_checkout: datetime, flex_trigger: datetime) -> float:
|
||||
"""
|
||||
弹性额度 D 计算(基于实际下班打卡时间):
|
||||
实际下班打卡 >= 23:00 时,D = 1 + floor((打卡-23:00)/0.5) * 0.5
|
||||
"""
|
||||
return 1.0 + math.floor((actual_checkout - flex_trigger).total_seconds() / 1800) * 0.5
|
||||
|
||||
|
||||
def _calc_day_ot_threshold(days: float) -> float:
|
||||
"""
|
||||
休息日/法定假日加班打卡间隔阈值:8 * days + int(days)。
|
||||
0.5天->4h, 1天->9h, 1.5天->13h, 2天->18h, 2.5天->22h
|
||||
"""
|
||||
return 8.0 * days + int(days)
|
||||
|
||||
|
||||
def _next_day(date_str: str) -> str:
|
||||
"""日期字符串 +1 天"""
|
||||
d = datetime.strptime(date_str, "%Y-%m-%d")
|
||||
return (d + timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _is_spring_festival(date_str: str) -> bool:
|
||||
"""
|
||||
判断日期是否为春节法定节假日(初一至初三)。
|
||||
|
||||
用 chinese_calendar 的 get_holiday_detail 判断 holiday_name == 'Spring Festival',
|
||||
且 is_in_lieu=False(排除调休日),且非周末(排除正常周末)。
|
||||
判定失败时按非春节处理(优雅降级)。
|
||||
"""
|
||||
try:
|
||||
import chinese_calendar as cc
|
||||
date = datetime.strptime(date_str, "%Y-%m-%d").date()
|
||||
is_holiday, holiday_name = cc.get_holiday_detail(date)
|
||||
return (is_holiday
|
||||
and holiday_name == 'Spring Festival'
|
||||
and not cc.is_in_lieu(date)
|
||||
and date.weekday() < 5)
|
||||
except Exception as e:
|
||||
logger.warning("春节法定假日判定失败(%s): %s", date_str, str(e))
|
||||
return False
|
||||
|
||||
|
||||
# ---------- 排班 / 打卡 / 请假查询 ----------
|
||||
def _get_shift(session: Any, staff_id: str, date_str: str) -> str:
|
||||
"""获取指定日期员工的排班班次(自动处理跨月)"""
|
||||
if not date_str or not staff_id:
|
||||
return "未知"
|
||||
try:
|
||||
year = int(date_str[:4])
|
||||
month = int(date_str[5:7])
|
||||
html = get_attendance_html(session, staff_id, year, month)
|
||||
attendance = parse_attendance_html(html)
|
||||
return attendance.get(date_str, "无排班")
|
||||
except Exception as e:
|
||||
logger.warning("获取排班失败(%s): %s", date_str, str(e))
|
||||
return "获取失败"
|
||||
|
||||
|
||||
def _check_attendance(session: Any, staff_id: str, ot_date: str) -> Dict[str, Any]:
|
||||
"""查询员工在加班日期的排班班次"""
|
||||
return {"加班当天班次": _get_shift(session, staff_id, ot_date)}
|
||||
|
||||
|
||||
def _check_punch_records(session: Any, staff_id: str, ot_date: str) -> Dict[str, Any]:
|
||||
"""
|
||||
查询员工在加班日及次日的打卡明细,按日汇总。
|
||||
|
||||
加班常跨天(如 18:00 至次日 00:00),下班打卡可能落在次日,因此查询
|
||||
范围扩展到 ot_date 次日;次日最早打卡用于延时加班的弹性到岗兑换判定。
|
||||
"""
|
||||
if not ot_date or not staff_id:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"打卡备注": "缺少加班日期或员工ID"}
|
||||
|
||||
start = datetime.strptime(ot_date, "%Y-%m-%d")
|
||||
next_day = (start + timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
|
||||
try:
|
||||
records = get_attendance_records(session, staff_id, ot_date, next_day)
|
||||
summary = summarize_attendance_records(records)
|
||||
day_summary = next((r for r in summary if r["attend_date"] == ot_date), None)
|
||||
next_summary = next((r for r in summary if r["attend_date"] == next_day), None)
|
||||
if not day_summary and not next_summary:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"打卡备注": "当天及次日无打卡记录"}
|
||||
return {
|
||||
"当日最早打卡": day_summary["first_check_in"] if day_summary else None,
|
||||
"当日最晚打卡": day_summary["last_check_out"] if day_summary else None,
|
||||
"次日最早打卡": next_summary["first_check_in"] if next_summary else None,
|
||||
"打卡备注": "",
|
||||
}
|
||||
except Exception as e:
|
||||
logger.warning("获取打卡明细失败: %s", str(e))
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"打卡备注": f"获取失败: {e}"}
|
||||
|
||||
|
||||
def _check_leave_covers_morning(session: Any, staff_id: str, date_str: str) -> bool:
|
||||
"""
|
||||
判断指定日期是否有请假覆盖早上上班时间(用于弹性兑换触发判定)。
|
||||
|
||||
只要任意请假区间覆盖了当日 WORK_START_TIME(如 09:00),即视为早上无需到岗,
|
||||
不触发弹性兑换。查询范围向前一天扩展,确保能查到跨天请假。
|
||||
"""
|
||||
prev_day = (datetime.strptime(date_str, "%Y-%m-%d") - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
try:
|
||||
records = get_leave_records(session, staff_id, prev_day, date_str)
|
||||
except Exception as e:
|
||||
logger.warning("获取请假记录失败: %s", str(e))
|
||||
return False
|
||||
|
||||
morning = datetime.strptime(f"{date_str} {WORK_START_TIME}", "%Y-%m-%d %H:%M")
|
||||
for r in records:
|
||||
start = _parse_dt(r.get("start_time"))
|
||||
end = _parse_dt(r.get("end_time"))
|
||||
if start and end and start <= morning <= end:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
# ---------- 规则一:延时加班 ----------
|
||||
def _validate_delayed(
|
||||
info: Dict[str, Any], punch: Dict[str, Any], session: Any, staff_id: str
|
||||
) -> tuple:
|
||||
"""
|
||||
延时加班审批(按 aa.md 规则一):
|
||||
|
||||
(一)驳回门槛:
|
||||
1. 日期匹配:加班开始时间所属日期 = 申请加班日期;
|
||||
2. 时长达标:1小时起算,超1小时按0.5h累加,不足1h驳回;
|
||||
3. 区间合规:开始时间 >= 规定下班时间(18:00),结束时间 <= 实际下班打卡时间。
|
||||
|
||||
(二)弹性到岗兑换(仅影响结算,校验不通过则驳回):
|
||||
D 基于实际下班打卡时间计算,>= 23:00 时 D = 1 + floor((打卡-23:00)/0.5)*0.5。
|
||||
次日休息/请假覆盖09:00/无打卡 -> 不触发兑换。
|
||||
正常工作日按次日打卡 P 校验:P<=09:00 不扣;09:00<P<=09:00+D 扣 ceil(P-09:00);
|
||||
P>09:00+D 扣 D。兑换校验:加班时长+晚到 <= 加班开始到次日打卡的总自然时长。
|
||||
"""
|
||||
ot_date = info.get("加班日期")
|
||||
start = _parse_dt(info.get("加班开始时间"))
|
||||
end = _parse_dt(info.get("加班结束时间"))
|
||||
actual_checkout = _parse_dt(punch.get("当日最晚打卡"))
|
||||
reasons = []
|
||||
|
||||
# 1. 日期校验
|
||||
if start is None:
|
||||
reasons.append("加班开始时间缺失")
|
||||
elif start.strftime("%Y-%m-%d") != ot_date:
|
||||
reasons.append(f"加班开始日期({start:%Y-%m-%d})与申请加班日期({ot_date})不一致")
|
||||
|
||||
# 2. 时长校验
|
||||
hours = None
|
||||
if end is None:
|
||||
reasons.append("加班结束时间缺失")
|
||||
elif start is not None:
|
||||
hours = _calc_delayed_hours(start, end)
|
||||
if hours < OT_MIN_HOURS:
|
||||
reasons.append(f"加班时长为{hours:g}小时,不足{OT_MIN_HOURS}小时")
|
||||
|
||||
# 3. 区间合规校验:开始 >= 规定下班时间,结束 <= 实际下班打卡时间
|
||||
work_end = datetime.strptime(f"{ot_date} {WORK_END_TIME}", "%Y-%m-%d %H:%M")
|
||||
if start is not None and start < work_end:
|
||||
reasons.append(f"申请开始时间({start:%H:%M})早于规定下班时间({WORK_END_TIME})")
|
||||
if end is not None:
|
||||
if actual_checkout is None:
|
||||
reasons.append("当日无下班打卡记录,无法校验区间合规")
|
||||
elif end > actual_checkout:
|
||||
reasons.append(
|
||||
f"申请结束时间({end:%H:%M})晚于实际下班打卡时间({actual_checkout:%H:%M:%S})"
|
||||
)
|
||||
|
||||
info["计算加班时长(小时)"] = hours
|
||||
if reasons:
|
||||
info["弹性扣减(小时)"] = 0
|
||||
info["有效加班时长(小时)"] = hours
|
||||
info["弹性额度D(小时)"] = 0
|
||||
return "不通过", ";".join(reasons)
|
||||
|
||||
# 4. 弹性到岗兑换(仅影响结算时长)
|
||||
deduction = 0.0
|
||||
flex_note = ""
|
||||
d_hours = 0.0
|
||||
flex_trigger = datetime.strptime(f"{ot_date} {FLEX_TRIGGER_TIME}", "%Y-%m-%d %H:%M")
|
||||
|
||||
if actual_checkout is not None and actual_checkout >= flex_trigger:
|
||||
d_hours = _calc_flex_d(actual_checkout, flex_trigger)
|
||||
next_day = _next_day(ot_date)
|
||||
next_shift = _get_shift(session, staff_id, next_day)
|
||||
|
||||
if next_shift in ("休息", "无排班"):
|
||||
flex_note = f"次日({next_day})为休息日,不触发弹性兑换"
|
||||
elif next_shift in ("获取失败", "未知"):
|
||||
flex_note = f"次日({next_day})排班获取失败,不触发弹性兑换"
|
||||
elif _check_leave_covers_morning(session, staff_id, next_day):
|
||||
flex_note = f"次日({next_day})请假覆盖早上上班时间,不触发弹性兑换"
|
||||
else:
|
||||
work_start = datetime.strptime(f"{next_day} {WORK_START_TIME}", "%Y-%m-%d %H:%M")
|
||||
p = _parse_dt(punch.get("次日最早打卡"))
|
||||
|
||||
if p is None:
|
||||
flex_note = f"次日({next_day})无打卡记录,不触发弹性兑换"
|
||||
elif p <= work_start:
|
||||
flex_note = f"次日打卡({p:%H:%M})准时或提前,无需兑换"
|
||||
else:
|
||||
# 有晚到,校验:加班时长 + 晚到 <= 加班开始到次日打卡的总自然时长
|
||||
total_natural = (p - start).total_seconds() / 3600
|
||||
|
||||
if p <= work_start + timedelta(hours=d_hours):
|
||||
# 09:00 < P <= 09:00+D:晚到时长 = ceil(P-09:00),不足1h按1h
|
||||
late_hours = max(1, math.ceil((p - work_start).total_seconds() / 3600))
|
||||
if hours + late_hours > total_natural:
|
||||
info["弹性扣减(小时)"] = 0
|
||||
info["有效加班时长(小时)"] = hours
|
||||
info["弹性额度D(小时)"] = d_hours
|
||||
return "不通过", (
|
||||
f"弹性兑换校验不通过:申请加班{hours:g}h + 晚到{late_hours}h "
|
||||
f"> 总自然时长{total_natural:.1f}h"
|
||||
)
|
||||
deduction = float(late_hours)
|
||||
flex_note = f"次日打卡({p:%H:%M})晚到,兑换{late_hours}小时"
|
||||
else:
|
||||
# P > 09:00+D:兑换额度最高按D,超出部分交考勤处理
|
||||
if hours + d_hours > total_natural:
|
||||
info["弹性扣减(小时)"] = 0
|
||||
info["有效加班时长(小时)"] = hours
|
||||
info["弹性额度D(小时)"] = d_hours
|
||||
return "不通过", (
|
||||
f"弹性兑换校验不通过:申请加班{hours:g}h + 兑换额度{d_hours:g}h "
|
||||
f"> 总自然时长{total_natural:.1f}h"
|
||||
)
|
||||
deduction = float(d_hours)
|
||||
flex_note = (
|
||||
f"次日打卡({p:%H:%M})超出弹性区间(D={d_hours:g}h),"
|
||||
f"按D兑换,超出部分交考勤处理"
|
||||
)
|
||||
else:
|
||||
if actual_checkout is not None:
|
||||
flex_note = f"实际下班打卡({actual_checkout:%H:%M})早于{FLEX_TRIGGER_TIME},弹性额度D=0"
|
||||
|
||||
effective = max(0.0, float(hours) - deduction)
|
||||
info["弹性扣减(小时)"] = deduction
|
||||
info["有效加班时长(小时)"] = effective
|
||||
info["弹性额度D(小时)"] = d_hours
|
||||
note = f"审批通过,有效加班时长{effective:g}小时"
|
||||
if flex_note:
|
||||
note += f"({flex_note})"
|
||||
return "通过", note
|
||||
|
||||
|
||||
# ---------- 规则二/三:休息日 / 法定假日加班 ----------
|
||||
def _validate_day_ot(
|
||||
info: Dict[str, Any],
|
||||
punch: Dict[str, Any],
|
||||
session: Any,
|
||||
staff_id: str,
|
||||
require_holiday: bool,
|
||||
) -> tuple:
|
||||
"""
|
||||
休息日/法定假日加班审批(任一条件不满足即不通过):
|
||||
- 排班显示为休息;
|
||||
- 法定假日(仅春节):申请日期必须为春节法定节假日;
|
||||
- 加班时长 > 0;
|
||||
- 当天有上下班打卡;
|
||||
- 打卡时间间隔满足申报天数(0.5天>=4h, 1天>=9h, 1.5天>=13h, 2天>=18h...)。
|
||||
"""
|
||||
ot_date = info.get("加班日期")
|
||||
reasons = []
|
||||
|
||||
# 排班须显示为休息;排班获取失败/未知时优雅降级
|
||||
shift = info.get("加班当天班次", "")
|
||||
if shift not in ("休息", "获取失败", "未知", "无排班"):
|
||||
reasons.append(f"当天排班为'{shift}',非休息日")
|
||||
|
||||
if require_holiday and not _is_spring_festival(ot_date):
|
||||
reasons.append(f"{ot_date}不在春节法定节假日列表中")
|
||||
|
||||
# 加班时长 > 0
|
||||
ot_hour = info.get("加班时长(小时)") or info.get("系统判断加班时长(小时)")
|
||||
try:
|
||||
ot_hour = float(ot_hour)
|
||||
except (TypeError, ValueError):
|
||||
ot_hour = 0.0
|
||||
if ot_hour <= 0:
|
||||
reasons.append("加班时长为0或缺失")
|
||||
|
||||
# 当天有上下班打卡,且打卡时间间隔满足申报天数
|
||||
first = _parse_dt(punch.get("当日最早打卡"))
|
||||
last = _parse_dt(punch.get("当日最晚打卡"))
|
||||
interval = None
|
||||
if first is None or last is None:
|
||||
reasons.append("当天缺少上班或下班打卡")
|
||||
else:
|
||||
interval = (last - first).total_seconds() / 3600
|
||||
|
||||
apply_days = info.get("加班天数(天)") or info.get("系统判断加班天数(天)")
|
||||
try:
|
||||
apply_days = float(apply_days)
|
||||
except (TypeError, ValueError):
|
||||
apply_days = 0.0
|
||||
if apply_days <= 0:
|
||||
reasons.append("申报天数缺失或为0")
|
||||
elif interval is not None:
|
||||
threshold = _calc_day_ot_threshold(apply_days)
|
||||
if interval < threshold:
|
||||
reasons.append(
|
||||
f"打卡间隔{interval:.2f}小时不足申报{apply_days:g}天所需的{threshold:g}小时"
|
||||
)
|
||||
|
||||
info["打卡时间间隔(小时)"] = interval
|
||||
info["申报天数(天)"] = apply_days
|
||||
if reasons:
|
||||
return "不通过", ";".join(reasons)
|
||||
return "通过", f"审批通过(申报{apply_days:g}天,打卡间隔{interval:.2f}小时)"
|
||||
|
||||
|
||||
# ---------- 主入口 ----------
|
||||
def validate_doc(doc: Dict[str, Any], session: Any) -> Dict[str, Any]:
|
||||
"""
|
||||
校验单张加班单据,返回审批决策(通过 / 不通过)。
|
||||
|
||||
按加班类型分派规则:
|
||||
ot_type=1 延时加班;
|
||||
ot_type=3 休息日加班;
|
||||
ot_type=2 法定假日加班(仅春节法定节假日走规则三,非春节按休息日规则执行)。
|
||||
|
||||
Args:
|
||||
doc: 单据信息,含基本信息(title/creator/time/detail_url)
|
||||
和审批引擎已获取的 taskId/businessKey/formId/formData(表单详情)
|
||||
session: 已登录的 SessionPage 对象(用于调用排班/打卡/请假接口)
|
||||
|
||||
Returns:
|
||||
校验结果,包含审批决策
|
||||
校验结果,包含审批决策、原因说明及解析后的加班信息
|
||||
"""
|
||||
form_data = doc.get("formData", {}) or {}
|
||||
overtime_info = parse_overtime_form(form_data)
|
||||
|
||||
staff_id = overtime_info.get("加班人员ID")
|
||||
ot_date = overtime_info.get("加班日期")
|
||||
|
||||
attendance_info = _check_attendance(session, staff_id, ot_date)
|
||||
punch_info = _check_punch_records(session, staff_id, ot_date)
|
||||
overtime_info.update(attendance_info)
|
||||
overtime_info.update(punch_info)
|
||||
|
||||
ot_type_code = str(form_data.get("ot_type") or "")
|
||||
if ot_type_code == "1":
|
||||
decision, note = _validate_delayed(overtime_info, punch_info, session, staff_id)
|
||||
elif ot_type_code == "3":
|
||||
decision, note = _validate_day_ot(
|
||||
overtime_info, punch_info, session, staff_id, require_holiday=False
|
||||
)
|
||||
elif ot_type_code == "2":
|
||||
# 法定假日加班:仅春节法定节假日适用规则三,非春节按休息日规则执行
|
||||
require_holiday = _is_spring_festival(ot_date)
|
||||
decision, note = _validate_day_ot(
|
||||
overtime_info, punch_info, session, staff_id, require_holiday=require_holiday
|
||||
)
|
||||
else:
|
||||
decision, note = "不通过", f"无法识别加班类型: {ot_type_code}"
|
||||
|
||||
return {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"decision": "pending", # pending: 规则未实现,默认待处理
|
||||
"note": "加班校验规则待补充",
|
||||
"decision": decision,
|
||||
"note": note,
|
||||
"overtime_info": overtime_info,
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: utils
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:00
|
||||
@Description: 项目级通用工具包
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
"""
|
||||
|
||||
+2
-1
@@ -1,2 +1,3 @@
|
||||
DrissionPage
|
||||
python-dotenv
|
||||
python-dotenv
|
||||
chinese_calendar
|
||||
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:30
|
||||
@Description: 测试区域,存放各模块/接口的连通性与功能测试脚本
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:30
|
||||
@Description: HRBP OA 系统接口连通性测试
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -0,0 +1,90 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp._helpers
|
||||
@FileName: _helpers.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:30
|
||||
@Description: 测试共享辅助:统一 sys.path 设置、登录态获取(优先复用已保存 cookies)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
# ---------- 统一 sys.path:项目根 + app/ ----------
|
||||
# 项目根加进来后可用 from app.service.hrbp... 形式 import
|
||||
# app/ 加进来兼容业务模块内部的 from utils.xxx / from hrbp.oa... 写法
|
||||
_PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
_APP_DIR = os.path.join(_PROJECT_ROOT, 'app')
|
||||
for _p in (_PROJECT_ROOT, _APP_DIR):
|
||||
if _p not in sys.path:
|
||||
sys.path.insert(0, _p)
|
||||
|
||||
# 初始化日志(测试脚本共用)
|
||||
from utils.logger import setup_logging, get_logger # noqa: E402
|
||||
|
||||
setup_logging()
|
||||
logger = get_logger("tests.hrbp")
|
||||
|
||||
|
||||
def get_logged_in_session(subject: str = "加班"):
|
||||
"""
|
||||
获取已登录的 (browser, session),优先复用本地保存的 cookies,
|
||||
失效或不存在时触发完整登录并保存。
|
||||
|
||||
所有需要登录态的接口测试都应通过此函数获取会话,避免重复登录。
|
||||
|
||||
Args:
|
||||
subject: 待办主题关键字,用于校验会话有效性(默认 "加班")
|
||||
|
||||
Returns:
|
||||
(browser, session):browser 为 ChromiumPage,session 为 SessionPage
|
||||
"""
|
||||
from app.service.hrbp.oa.common.session_manager import (
|
||||
load_saved_session,
|
||||
is_session_valid,
|
||||
oa_login, # noqa: F401 (保留便于调试时直接登录)
|
||||
init_session_from_page,
|
||||
save_browser_cookies,
|
||||
create_browser_with_saved_cookies,
|
||||
)
|
||||
from app.service.hrbp.oa.common.login import oa_login as _oa_login
|
||||
|
||||
# 1. 尝试复用已保存的 cookies
|
||||
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
|
||||
|
||||
# 2. 复用失败则完整登录
|
||||
logger.info("无可用会话,执行完整登录")
|
||||
browser = _oa_login()
|
||||
session = init_session_from_page(browser)
|
||||
save_browser_cookies(browser)
|
||||
return browser, session
|
||||
|
||||
|
||||
def pick_first_todo(session, subject: str = "加班"):
|
||||
"""
|
||||
从待办列表取第一条单据,供后续 SSO / 表单详情测试使用。
|
||||
|
||||
Returns:
|
||||
单据字典(含 detail_url 等),无待办时返回 None
|
||||
"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_documents
|
||||
|
||||
docs = get_documents(session, subject=subject)
|
||||
if not docs:
|
||||
logger.warning("无[%s]待办,无法继续后续测试", subject)
|
||||
return None
|
||||
logger.info("取到 %d 条待办,用第一条做后续测试: %s", len(docs), docs[0].get("title"))
|
||||
return docs[0]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 自检:登录并拉取一条待办
|
||||
browser, session = get_logged_in_session()
|
||||
doc = pick_first_todo(session)
|
||||
if doc:
|
||||
logger.info("自检通过,待办示例: %s", doc.get("title"))
|
||||
@@ -0,0 +1,49 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp.test_01_login_session
|
||||
@FileName: test_01_login_session.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:35
|
||||
@Description: 连通性测试①——登录态获取 + 会话复用 + 待办列表接口
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
|
||||
from tests.hrbp._helpers import get_logged_in_session, logger # noqa: E402
|
||||
|
||||
|
||||
def test_session_reuse():
|
||||
"""测试:复用已保存 cookies 构建会话(无 cookies 时触发登录)"""
|
||||
browser, session = get_logged_in_session(subject="加班")
|
||||
assert session is not None, "会话获取失败"
|
||||
logger.info("[通过] 会话获取成功")
|
||||
return browser, session
|
||||
|
||||
|
||||
def test_todo_list(session, subject: str = "加班"):
|
||||
"""测试:待办列表接口连通性 + 分页解析"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_documents, fetch_todo_page
|
||||
|
||||
# 单页探活
|
||||
page_data = fetch_todo_page(session, subject=subject, page_no=1, page_size=1)
|
||||
total = int(page_data.get("page", {}).get("totalSize", 0))
|
||||
assert total >= 0, "待办总数字段异常"
|
||||
logger.info("[通过] 待办接口连通,总数=%d", total)
|
||||
|
||||
# 完整拉取
|
||||
docs = get_documents(session, subject=subject)
|
||||
logger.info("[通过] 待办解析完成,共 %d 条", len(docs))
|
||||
for d in docs[:3]:
|
||||
logger.info(" - %s | %s | %s", d.get("creator"), d.get("time"), d.get("title"))
|
||||
return docs
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger.info("========== 测试①:登录 + 会话 + 待办列表 ==========")
|
||||
browser, session = test_session_reuse()
|
||||
test_todo_list(session)
|
||||
logger.info("========== 测试①结束 ==========")
|
||||
@@ -0,0 +1,69 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp.test_02_form_detail
|
||||
@FileName: test_02_form_detail.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:40
|
||||
@Description: 连通性测试②——SSO 解析 + WfActivity + WorkformEngine(表单详情链路)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
|
||||
from tests.hrbp._helpers import get_logged_in_session, pick_first_todo, logger # noqa: E402
|
||||
|
||||
|
||||
def test_sso(browser, detail_url: str):
|
||||
"""测试:SSO 链接解析,提取 taskId + businessKey"""
|
||||
from app.service.hrbp.oa.common.sso import resolve_sso_params
|
||||
|
||||
sso_params = resolve_sso_params(browser, detail_url)
|
||||
assert sso_params.get("taskId"), "taskId 提取失败"
|
||||
assert sso_params.get("businessKey"), "businessKey 提取失败"
|
||||
logger.info("[通过] SSO 解析: taskId=%s, businessKey=%s",
|
||||
sso_params["taskId"], sso_params["businessKey"])
|
||||
return sso_params
|
||||
|
||||
|
||||
def test_wf_activity(session, task_id: str):
|
||||
"""测试:WfActivity 接口 → 提取 formId"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_wf_activity_by_task_id, extract_form_id
|
||||
|
||||
data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(data)
|
||||
assert form_id, "formId 提取失败"
|
||||
logger.info("[通过] WfActivity 接口正常,formId=%s", form_id)
|
||||
return form_id
|
||||
|
||||
|
||||
def test_workform_engine(session, business_key: str, form_id: str):
|
||||
"""测试:WorkformEngine 接口 → 表单数据"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_business_data
|
||||
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
assert isinstance(form_data, dict), "表单数据格式异常"
|
||||
# 加班表单应含关键字段
|
||||
assert form_data.get("staff_name"), "表单缺 staff_name"
|
||||
logger.info("[通过] WorkformEngine 接口正常,员工=%s, 加班日期=%s",
|
||||
form_data.get("staff_name"), form_data.get("ot_date"))
|
||||
return form_data
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger.info("========== 测试②:SSO + WfActivity + WorkformEngine ==========")
|
||||
browser, session = get_logged_in_session(subject="加班")
|
||||
doc = pick_first_todo(session, subject="加班")
|
||||
if not doc:
|
||||
logger.error("无待办单据,测试中止")
|
||||
else:
|
||||
from app.service.hrbp.oa.common.session_manager import refresh_session_cookies
|
||||
|
||||
sso_params = test_sso(browser, doc["detail_url"])
|
||||
# SSO 后同步 hr 域 cookie 到 session
|
||||
refresh_session_cookies(session, browser)
|
||||
form_id = test_wf_activity(session, sso_params["taskId"])
|
||||
test_workform_engine(session, sso_params["businessKey"], form_id)
|
||||
logger.info("========== 测试②结束 ==========")
|
||||
@@ -0,0 +1,73 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp.test_03_attendance
|
||||
@FileName: test_03_attendance.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:45
|
||||
@Description: 连通性测试③——排班接口 + 打卡明细接口(考勤类)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
|
||||
from tests.hrbp._helpers import get_logged_in_session, logger # noqa: E402
|
||||
|
||||
# 测试用员工(黄俊林),可按需改成环境变量或从待办单据动态获取
|
||||
TEST_STAFF_ID = "572e6cce-7a9f-11ec-b449-000c296f9469"
|
||||
TEST_DATE = "2026-08-02"
|
||||
|
||||
|
||||
def test_attendance_html(session, staff_id: str, year: int, month: int):
|
||||
"""测试:排班 HTML 接口 + 解析"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_attendance_html
|
||||
from app.service.hrbp.oa.common.parser import parse_attendance_html
|
||||
|
||||
html = get_attendance_html(session, staff_id, year, month)
|
||||
assert html, "排班 HTML 为空"
|
||||
attendance = parse_attendance_html(html)
|
||||
assert isinstance(attendance, dict), "排班解析结果非字典"
|
||||
logger.info("[通过] 排班接口正常,当月解析到 %d 天班次", len(attendance))
|
||||
for date, shift in list(attendance.items())[:5]:
|
||||
logger.info(" %s: %s", date, shift)
|
||||
return attendance
|
||||
|
||||
|
||||
def test_punch_records(session, staff_id: str, start_date: str, end_date: str):
|
||||
"""测试:打卡明细接口 + 按日汇总(迁移自原 test.py)"""
|
||||
from app.service.hrbp.oa.common.oa_api import get_attendance_records
|
||||
from app.service.hrbp.oa.common.parser import summarize_attendance_records
|
||||
|
||||
# 1. 拉取原始打卡明细
|
||||
records = get_attendance_records(session, staff_id, start_date, end_date)
|
||||
assert isinstance(records, list), "打卡明细格式异常"
|
||||
logger.info("[通过] 打卡明细接口正常,返回 %d 条原始记录", len(records))
|
||||
|
||||
# 2. 按日汇总:每日最早上班 / 最晚下班
|
||||
summary = summarize_attendance_records(records)
|
||||
logger.info("[通过] 打卡汇总完成,共 %d 天", len(summary))
|
||||
for row in summary:
|
||||
logger.info(" %s | %s | 最早:%s | 最晚:%s",
|
||||
row.get("attend_date"),
|
||||
row.get("staff_name"),
|
||||
row.get("first_check_in") or "无",
|
||||
row.get("last_check_out") or "无")
|
||||
return summary
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger.info("========== 测试③:排班 + 打卡明细 ==========")
|
||||
browser, session = get_logged_in_session(subject="加班")
|
||||
|
||||
year = int(TEST_DATE[:4])
|
||||
month = int(TEST_DATE[5:7])
|
||||
test_attendance_html(session, TEST_STAFF_ID, year, month)
|
||||
|
||||
# 打卡查询范围:当天 + 次日(覆盖跨天凌晨下班)
|
||||
from datetime import datetime, timedelta
|
||||
end = (datetime.strptime(TEST_DATE, "%Y-%m-%d") + timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
test_punch_records(session, TEST_STAFF_ID, TEST_DATE, end)
|
||||
|
||||
logger.info("========== 测试③结束 ==========")
|
||||
@@ -0,0 +1,94 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: tests.hrbp.test_04_parsers
|
||||
@FileName: test_04_parsers.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-06 10:50
|
||||
@Description: 连通性测试④——纯解析函数(无需登录,离线测试)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
|
||||
from tests.hrbp._helpers import logger # noqa: E402
|
||||
|
||||
|
||||
def test_attendance_html_parse():
|
||||
"""测试:排班 HTML 解析 + 工作日计算"""
|
||||
from app.service.hrbp.oa.common.parser import parse_attendance_html, get_work_days_in_range
|
||||
|
||||
html = """
|
||||
<a class='cale_a' data-temp="2026-08-01">休息</a>
|
||||
<a class='cale_a' data-temp="2026-08-02">正常</a>
|
||||
<a class='cale_a' data-temp="2026-08-03">休息</a>
|
||||
"""
|
||||
result = parse_attendance_html(html)
|
||||
assert result == {"2026-08-01": "休息", "2026-08-02": "正常", "2026-08-03": "休息"}
|
||||
|
||||
work_days = get_work_days_in_range(result, "2026-08-01", "2026-08-03")
|
||||
assert work_days == ["2026-08-02"], f"工作日计算错误: {work_days}"
|
||||
logger.info("[通过] 排班 HTML 解析 + 工作日计算")
|
||||
|
||||
|
||||
def test_attendance_summary():
|
||||
"""测试:打卡明细按日汇总(含跨天凌晨下班)"""
|
||||
from app.service.hrbp.oa.common.parser import summarize_attendance_records
|
||||
|
||||
records = [
|
||||
{"staff_id": "S001", "staff_name": "张三", "bc_date": "2026-08-02",
|
||||
"kq_time": "2026-08-02 08:50:00", "status": "1", "time_order": "1",
|
||||
"DEPT_ORG_NAME": "技术部", "POST_ALIAS_NAME": "工程师"},
|
||||
{"staff_id": "S001", "staff_name": "张三", "bc_date": "2026-08-02",
|
||||
"kq_time": "2026-08-02 12:00:00", "status": "5", "time_order": "2",
|
||||
"DEPT_ORG_NAME": "技术部", "POST_ALIAS_NAME": "工程师"},
|
||||
{"staff_id": "S001", "staff_name": "张三", "bc_date": "2026-08-02",
|
||||
"kq_time": "2026-08-03 00:30:00", "status": "5", "time_order": "2",
|
||||
"DEPT_ORG_NAME": "技术部", "POST_ALIAS_NAME": "工程师"},
|
||||
{"staff_id": "S001", "staff_name": "张三", "bc_date": "2026-08-02",
|
||||
"kq_time": "2026-08-02 19:00:00", "status": "6", "time_order": "1",
|
||||
"DEPT_ORG_NAME": "技术部", "POST_ALIAS_NAME": "工程师"}, # 重复打卡,应过滤
|
||||
]
|
||||
summary = summarize_attendance_records(records)
|
||||
assert len(summary) == 1, f"汇总天数错误: {len(summary)}"
|
||||
row = summary[0]
|
||||
assert row["first_check_in"] == "2026-08-02 08:50:00"
|
||||
assert row["last_check_out"] == "2026-08-03 00:30:00" # 跨天最晚
|
||||
logger.info("[通过] 打卡汇总(含跨天 + 过滤重复): 最早=%s, 最晚=%s",
|
||||
row["first_check_in"], row["last_check_out"])
|
||||
|
||||
|
||||
def test_overtime_form_parse():
|
||||
"""测试:加班表单解析 + 类型映射"""
|
||||
from app.service.hrbp.oa.work_overtime.parser import parse_overtime_form
|
||||
|
||||
form_data = {
|
||||
"staff_id": "572e6cce-7a9f-11ec-b449-000c296f9469",
|
||||
"staff_name": "黄俊林",
|
||||
"dept_org_name": "网络项目小组",
|
||||
"ot_type": "1", # → 延时加班
|
||||
"subsidy_type": "2", # → 转补贴
|
||||
"ot_date": "2026-08-02",
|
||||
"start_time": "2026-08-02 18:00",
|
||||
"end_time": "2026-08-03 00:00",
|
||||
"ot_hour": 6.0,
|
||||
"judge_ot_hour": 6.0,
|
||||
"judge_start_time": "2026-08-02 18:00:00",
|
||||
"judge_end_time": "2026-08-03 00:00:00",
|
||||
"file": "ccc1d3ef-175a-4105-a8a8-0e63ed88d7bd",
|
||||
}
|
||||
info = parse_overtime_form(form_data)
|
||||
assert info["加班人员ID"] == "572e6cce-7a9f-11ec-b449-000c296f9469"
|
||||
assert info["加班类型"] == "延时加班", f"类型映射错误: {info['加班类型']}"
|
||||
assert info["补贴类型"] == "转补贴"
|
||||
assert info["系统判定加班时间"] == "2026-08-02 18:00:00 至 2026-08-03 00:00:00"
|
||||
logger.info("[通过] 加班表单解析 + 类型映射: %s", info["加班类型"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logger.info("========== 测试④:纯解析函数(离线) ==========")
|
||||
test_attendance_html_parse()
|
||||
test_attendance_summary()
|
||||
test_overtime_form_parse()
|
||||
logger.info("========== 测试④结束 ==========")
|
||||
Reference in New Issue
Block a user