1. 新增考勤异常查询与导出模块,支持当月异常拉取、Excel导出、钉钉推送提醒 2. 完善请假/加班流程解析与校验,新增附件下载、OCR核验能力 3. 新增银行卡信息校验模块,支持在职/离职员工工资卡数据核对与异常导出 4. 新增通用OCR工具模块,支持病假/婚假/产检假附件关键词检测与日期提取 5. 新增门店请休假异常名单、银行卡检查等需求文档 6. 重构部分现有模块代码,优化配置与接口调用逻辑 7. 新增测试文件与工具类,完善项目基础能力
593 lines
18 KiB
Python
593 lines
18 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.4.0
|
||
"""
|
||
|
||
import time
|
||
import re
|
||
import os
|
||
from typing import List, Dict, Any, Optional
|
||
from urllib.parse import urlencode, unquote
|
||
|
||
from app.utils.logger import get_logger
|
||
try:
|
||
from DrissionPage import SessionPage
|
||
except ImportError:
|
||
SessionPage = None
|
||
|
||
from app.service.hrbp.oa.common.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, FILE_DOWNLOAD_URL, ATTACHMENT_SAVE_DIR
|
||
|
||
logger = get_logger(__name__)
|
||
|
||
|
||
def download_attachment(
|
||
session: SessionPage,
|
||
file_id: str,
|
||
save_dir: str = ATTACHMENT_SAVE_DIR,
|
||
) -> Optional[str]:
|
||
"""
|
||
根据附件 fileId 从 OA 下载请假单据附件。
|
||
|
||
Args:
|
||
session: 已登录的 SessionPage 对象(已带登录 Cookie)
|
||
file_id: 附件 fileId(表单 result.file 字段值,即下载链接里的 fileId)
|
||
save_dir: 保存目录(默认 downloads)
|
||
|
||
Returns:
|
||
保存的完整文件路径;失败返回 None
|
||
"""
|
||
if not file_id:
|
||
logger.warning("附件 fileId 为空,跳过下载")
|
||
return None
|
||
|
||
os.makedirs(save_dir, exist_ok=True)
|
||
url = f"{FILE_DOWNLOAD_URL}?fileId={file_id}"
|
||
logger.info("下载附件: fileId=%s", file_id)
|
||
|
||
try:
|
||
session.get(url)
|
||
resp = session.response
|
||
except Exception as e:
|
||
logger.warning("附件请求失败(fileId=%s): %s", file_id, e)
|
||
return None
|
||
|
||
if not resp or resp.status_code != 200:
|
||
logger.warning("附件下载失败: HTTP %s (fileId=%s)", resp.status_code, file_id)
|
||
return None
|
||
|
||
# 从 Content-Disposition 解析真实文件名(可能带 UTF-8'' 编码)
|
||
filename = None
|
||
cd = resp.headers.get("Content-Disposition", "")
|
||
if "filename=" in cd:
|
||
raw = cd.split("filename=")[-1].strip().strip('"')
|
||
if raw.startswith("UTF-8''"):
|
||
raw = unquote(raw.split("UTF-8''", 1)[1])
|
||
if raw:
|
||
filename = raw
|
||
|
||
# 解析不到文件名时,用 fileId 兜底,并按 Content-Type 补扩展名
|
||
if not filename:
|
||
filename = file_id
|
||
ct = (resp.headers.get("Content-Type") or "").split(";")[0].strip().lower()
|
||
ext_map = {
|
||
"image/png": ".png",
|
||
"image/jpeg": ".jpg",
|
||
"application/pdf": ".pdf",
|
||
"application/octet-stream": ".bin",
|
||
}
|
||
filename += ext_map.get(ct, ".bin")
|
||
|
||
# 清理非法字符,防止路径注入
|
||
filename = "".join(c for c in filename if c not in '\\/:*?"<>|')
|
||
path = os.path.join(save_dir, filename)
|
||
with open(path, "wb") as f:
|
||
f.write(resp.content)
|
||
logger.info("附件已下载: %s", path)
|
||
return path
|
||
|
||
|
||
# ---------- 获取待处理单据列表 ----------
|
||
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
|