# -*- 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.1.0 """ from DrissionPage import SessionPage import time import re from typing import List, Dict, Any from urllib.parse import urlencode from .config import BASE_URL, TODO_LIST_URL, DEFAULT_PAGE_SIZE, FD_TYPE, HR_BASE_URL # ---------- 获取待处理单据列表 ---------- 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)}" print(f"🌐 请求第 {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", "") # 移除 标签,仅保留内容 match = re.search(r']*>(.*?)', 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)) print(f"📊 总待办[{subject}]条数: {total}") # 解析第一页 docs = parse_todo_list(data) all_docs.extend(docs) print(f"第 1 页获取 {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) print(f"第 {p} 页获取 {len(docs)} 条,累计 {len(all_docs)} 条") return all_docs # ---------- 后续扩展接口(占位,供后续实现) ---------- # def get_form_id(session: SessionPage, task_id: str) -> str: # """获取 formId""" # pass # def get_form_data(session: SessionPage, business_key: str, form_id: str) -> Dict: # """获取表单详情""" # pass # ---------- 排班接口 ---------- 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"{HR_BASE_URL}/RedseaPlatform/KqCount.mc?method=geRenPaibanByMonth" data = { "type": "2", "staffId": staff_id, "year": str(year), "month": str(month) } print(f"📅 获取排班: {staff_id} {year}-{month:02d}") 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