新增: 1. 新增依赖包chinese_calendar,完善.gitignore会话存储配置 2. 新增完整测试套件与项目初始化文件 3. 实现延时/休息日/法定假日加班审批规则(参考aa.md文档) 4. 新增排班、打卡、请假数据获取与解析工具 5. 完善会话管理与持久化存储逻辑 6. 实现格式化审批报告生成功能 修改: 1. 调整请假校验函数签名以传入会话对象 2. 更新审批流程调用逻辑适配新校验函数 3. 重构cookie存储路径与目录创建逻辑 4. 优化日志输出级别与调试信息
533 lines
16 KiB
Python
533 lines
16 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@Module: hrbp.oa.oa_api
|
||
@FileName: oa_api.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-08-05 17:10
|
||
@Description: OA/HR 系统 API 模块,负责调用系统接口(待办列表、流程引擎、表单、排班等)
|
||
@Version: 1.3.1
|
||
"""
|
||
|
||
import os
|
||
import sys
|
||
import time
|
||
import re
|
||
from typing import List, Dict, Any
|
||
from urllib.parse import urlencode
|
||
|
||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', '..', '..'))
|
||
|
||
from utils.logger import get_logger
|
||
try:
|
||
from DrissionPage import SessionPage
|
||
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, 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, KQ_DATA_URL, LEAVE_RECORD_URL, PAIBAN_URL
|
||
|
||
logger = get_logger(__name__)
|
||
|
||
|
||
# ---------- 获取待处理单据列表 ----------
|
||
def fetch_todo_page(
|
||
session: SessionPage,
|
||
subject: str,
|
||
page_no: int = 1,
|
||
page_size: int = DEFAULT_PAGE_SIZE
|
||
) -> Dict[str, Any]:
|
||
"""
|
||
请求单页待办列表数据。
|
||
|
||
Args:
|
||
session: 已登录的 SessionPage 对象
|
||
subject: 待办标题关键字,如 "请假" / "加班"
|
||
page_no: 页码(从1开始)
|
||
page_size: 每页条数
|
||
|
||
Returns:
|
||
接口返回的 JSON 字典
|
||
|
||
Raises:
|
||
RuntimeError: 请求失败或状态码异常
|
||
"""
|
||
params = {
|
||
"method": "list",
|
||
"dataType": "todo",
|
||
"fdType": FD_TYPE, # 待办类型(请假/加班)
|
||
"fdCateId": "",
|
||
"q.fdSubject": subject, # 按标题关键字过滤(请假/加班)
|
||
"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)
|
||
|
||
session.get(url)
|
||
resp = session.response
|
||
if not resp:
|
||
raise RuntimeError("请求失败,未获取到响应")
|
||
if resp.status_code != 200:
|
||
raise RuntimeError(f"接口请求失败,状态码: {resp.status_code}")
|
||
try:
|
||
return resp.json()
|
||
except Exception:
|
||
raise RuntimeError("接口返回非 JSON 数据,请检查参数或登录状态")
|
||
|
||
|
||
def parse_todo_list(data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||
"""
|
||
解析接口返回的 JSON,提取每张单据的关键信息。
|
||
|
||
Args:
|
||
data: 接口返回的 JSON
|
||
|
||
Returns:
|
||
单据列表,每项包含:
|
||
- title: 标题(去除 HTML 标签)
|
||
- creator: 发起人
|
||
- time: 接收时间(字符串)
|
||
- detail_url: SSO 跳转链接(完整 URL)
|
||
"""
|
||
datas = data.get("datas", [])
|
||
if not datas:
|
||
return []
|
||
|
||
docs = []
|
||
for row in datas:
|
||
# 1. 标题
|
||
title_cell = next((c for c in row if c["col"] == "todo.subject4View"), {})
|
||
title_raw = title_cell.get("value", "")
|
||
# 移除 <span class="subjecthead"> 标签,仅保留内容
|
||
match = re.search(r'<span class="subjecthead"[^>]*>(.*?)</span>', title_raw, re.DOTALL)
|
||
title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip()
|
||
|
||
# 2. 发起人
|
||
creator_cell = next((c for c in row if c["col"] == "docCreatorName"), {})
|
||
creator = creator_cell.get("value", "")
|
||
|
||
# 3. 接收时间
|
||
time_cell = next((c for c in row if c["col"] == "fdCreateTime"), {})
|
||
time_str = time_cell.get("value", "")
|
||
|
||
# 4. SSO 跳转链接(补全为完整 URL)
|
||
href_cell = next((c for c in row if c["col"] == "tr_href"), {})
|
||
detail_url = href_cell.get("value", "")
|
||
if detail_url and not detail_url.startswith(("http://", "https://")):
|
||
detail_url = BASE_URL + detail_url
|
||
|
||
docs.append({
|
||
"title": title,
|
||
"creator": creator,
|
||
"time": time_str,
|
||
"detail_url": detail_url,
|
||
})
|
||
return docs
|
||
|
||
|
||
def get_documents(
|
||
session: SessionPage,
|
||
subject: str,
|
||
page_size: int = DEFAULT_PAGE_SIZE
|
||
) -> List[Dict[str, Any]]:
|
||
"""
|
||
主入口:获取所有待处理单据(自动分页)。
|
||
|
||
请假与加班流程逻辑一致,仅通过 subject 关键字区分。
|
||
|
||
Args:
|
||
session: 已登录的 SessionPage 对象(已设置 cookies)
|
||
subject: 待办标题关键字,如 "请假" / "加班"
|
||
page_size: 每页条数(默认15)
|
||
|
||
Returns:
|
||
所有单据的列表
|
||
"""
|
||
all_docs = []
|
||
|
||
# 请求第一页,获取总条数
|
||
data = fetch_todo_page(session, subject, page_no=1, page_size=page_size)
|
||
total = int(data.get("page", {}).get("totalSize", 0))
|
||
logger.info("总待办[%s]条数: %d", subject, total)
|
||
|
||
# 解析第一页
|
||
docs = parse_todo_list(data)
|
||
all_docs.extend(docs)
|
||
logger.info("第 1 页获取 %d 条", len(docs))
|
||
|
||
# 若总条数超过单页,继续翻页
|
||
if total > page_size:
|
||
total_pages = (total + page_size - 1) // page_size
|
||
for p in range(2, total_pages + 1):
|
||
data = fetch_todo_page(session, subject, page_no=p, page_size=page_size)
|
||
docs = parse_todo_list(data)
|
||
all_docs.extend(docs)
|
||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(docs), len(all_docs))
|
||
|
||
return all_docs
|
||
|
||
|
||
# ---------- WfActivity 接口:通过 taskId 获取 formId ----------
|
||
def get_wf_activity_by_task_id(
|
||
session: SessionPage,
|
||
task_id: str
|
||
) -> Dict[str, Any]:
|
||
"""
|
||
通过 taskId 调用 WfActivity 接口获取 formId。
|
||
|
||
Args:
|
||
session: 已登录的 SessionPage 对象
|
||
task_id: SSO 解析得到的 taskId
|
||
|
||
Returns:
|
||
接口返回的 JSON 字典,包含 formId 等信息
|
||
|
||
Raises:
|
||
RuntimeError: 请求失败或响应异常
|
||
"""
|
||
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
|
||
data = {"taskId": task_id}
|
||
logger.info("获取 formId: taskId=%s", task_id)
|
||
|
||
session.post(url, data=data)
|
||
resp = session.response
|
||
if not resp:
|
||
raise RuntimeError("WfActivity 请求失败,未获取到响应")
|
||
if resp.status_code != 200:
|
||
raise RuntimeError(f"WfActivity 接口状态码异常: {resp.status_code}")
|
||
|
||
try:
|
||
json_data = resp.json()
|
||
except Exception:
|
||
body = (resp.text or "")[:200]
|
||
raise RuntimeError(
|
||
f"WfActivity 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}"
|
||
)
|
||
|
||
logger.debug("WfActivity 返回: %s", json_data)
|
||
return json_data
|
||
|
||
|
||
def extract_form_id(wf_activity_data: Dict[str, Any]) -> str:
|
||
"""
|
||
从 WfActivity 接口返回数据中提取 formId。
|
||
|
||
Args:
|
||
wf_activity_data: get_wf_activity_by_task_id 返回的 JSON
|
||
|
||
Returns:
|
||
formId 字符串
|
||
|
||
Raises:
|
||
ValueError: 未找到 formId
|
||
"""
|
||
# 常见 formId 字段路径:顶层,以及 data / result 子对象
|
||
form_id = (
|
||
wf_activity_data.get("formId")
|
||
or wf_activity_data.get("FormId")
|
||
or wf_activity_data.get("form_id")
|
||
)
|
||
if not form_id:
|
||
for key in ("data", "result"):
|
||
data_obj = wf_activity_data.get(key, {})
|
||
if isinstance(data_obj, dict):
|
||
form_id = (
|
||
data_obj.get("formId")
|
||
or data_obj.get("FormId")
|
||
or data_obj.get("form_id")
|
||
)
|
||
if form_id:
|
||
break
|
||
|
||
if not form_id:
|
||
raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}")
|
||
|
||
logger.info("提取到 formId: %s", form_id)
|
||
return form_id
|
||
|
||
|
||
# ---------- WorkformEngine 接口:获取加班申请表单数据 ----------
|
||
def get_business_data(
|
||
session: SessionPage,
|
||
business_key: str,
|
||
form_id: str
|
||
) -> Dict[str, Any]:
|
||
"""
|
||
通过 businessKey 和 formId 调用 WorkformEngine 接口获取加班申请表单数据。
|
||
|
||
Args:
|
||
session: 已登录的 SessionPage 对象
|
||
business_key: SSO 解析得到的 businessKey
|
||
form_id: 从 WfActivity 接口获取的 formId
|
||
|
||
Returns:
|
||
表单详细数据字典(接口响应的 result 字段,如 ot_date/staff_name 等)
|
||
|
||
Raises:
|
||
RuntimeError: 请求失败或响应异常
|
||
"""
|
||
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
|
||
data = {
|
||
"businessKey": business_key,
|
||
"formId": form_id,
|
||
}
|
||
logger.info("获取加班表单: businessKey=%s, formId=%s", business_key, form_id)
|
||
|
||
session.post(url, data=data)
|
||
resp = session.response
|
||
if not resp:
|
||
raise RuntimeError("WorkformEngine 请求失败,未获取到响应")
|
||
if resp.status_code != 200:
|
||
raise RuntimeError(f"WorkformEngine 接口状态码异常: {resp.status_code}")
|
||
|
||
try:
|
||
json_data = resp.json()
|
||
except Exception:
|
||
body = (resp.text or "")[:200]
|
||
raise RuntimeError(
|
||
f"WorkformEngine 接口返回非 JSON 数据(状态码 {resp.status_code}): {body}"
|
||
)
|
||
|
||
# 表单详情在 result 字段中(如 ot_date / staff_name 等)
|
||
result = json_data.get("result")
|
||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||
raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}")
|
||
|
||
logger.info("WorkformEngine 返回成功")
|
||
return result
|
||
|
||
|
||
# ---------- 排班接口 ----------
|
||
def get_attendance_html(
|
||
session: SessionPage,
|
||
staff_id: str,
|
||
year: int,
|
||
month: int
|
||
) -> str:
|
||
"""
|
||
获取指定员工某月的排班 HTML。
|
||
|
||
Args:
|
||
session: 已登录的 SessionPage 对象
|
||
staff_id: 员工 UUID
|
||
year: 年份(如 2026)
|
||
month: 月份(1-12)
|
||
|
||
Returns:
|
||
排班表格的 HTML 字符串(从返回 JSON 的 caleHtml 字段提取)
|
||
|
||
Raises:
|
||
RuntimeError: 请求失败或响应异常
|
||
"""
|
||
url = f"{PAIBAN_URL}?method=geRenPaibanByMonth"
|
||
data = {
|
||
"type": "2",
|
||
"staffId": staff_id,
|
||
"year": str(year),
|
||
"month": str(month)
|
||
}
|
||
logger.info("获取排班: %s %d-%02d", staff_id, year, month)
|
||
|
||
session.post(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:
|
||
raise RuntimeError("排班接口返回非 JSON 数据")
|
||
|
||
if json_data.get("success") != "true":
|
||
raise RuntimeError(f"排班接口返回失败: {json_data}")
|
||
|
||
html = json_data.get("caleHtml")
|
||
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
|