feat: HRBP OA 人事审批服务包(请假/加班流程框架)
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa
|
||||
@Description: OA 系统公共模块:登录、会话管理、接口调用、解析
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -0,0 +1,20 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.config
|
||||
@FileName: config.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:09
|
||||
@Description: OA/HR 系统配置,集中管理接口地址、待办类型、分页大小等常量
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
# ---------- OA 系统 ----------
|
||||
BASE_URL = "https://oa.37du.co"
|
||||
TODO_LIST_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
||||
FD_TYPE = "13" # 待办类型:13 代表请假/加班单据(根据实际调整)
|
||||
|
||||
# ---------- HR 系统 ----------
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
|
||||
# ---------- 分页 ----------
|
||||
DEFAULT_PAGE_SIZE = 15
|
||||
@@ -0,0 +1,113 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.login
|
||||
@FileName: login.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-04 17:34
|
||||
@Description: 自动登录 OA 系统
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from DrissionPage import ChromiumPage
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
import time
|
||||
|
||||
|
||||
def oa_login(
|
||||
username: str = None,
|
||||
password: str = None,
|
||||
timeout: float = 10,
|
||||
wait_after_load: float = 2,
|
||||
) -> ChromiumPage:
|
||||
"""
|
||||
自动登录 OA 系统,返回已登录的 ChromiumPage 对象。
|
||||
|
||||
参数:
|
||||
username: 登录用户名,若不提供则从环境变量 oa_login_username 读取
|
||||
password: 登录密码,若不提供则从环境变量 oa_login_password 读取
|
||||
|
||||
timeout: URL 跳转等待超时(秒,默认 10)
|
||||
wait_after_load: 页面加载后的额外等待时间(秒,默认 2)
|
||||
|
||||
返回:
|
||||
登录成功后的 ChromiumPage 对象
|
||||
|
||||
异常:
|
||||
若登录失败或关键元素未找到,抛出 RuntimeError
|
||||
"""
|
||||
# 加载 .env 环境变量(默认读取当前工作目录下的 .env)
|
||||
load_dotenv()
|
||||
|
||||
# 获取配置,参数优先于环境变量
|
||||
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()
|
||||
# page.set.window.max()
|
||||
|
||||
try:
|
||||
# 访问登录页面
|
||||
page.get(login_url)
|
||||
time.sleep(wait_after_load) # 等待页面初步加载
|
||||
|
||||
# 定位并填写用户名
|
||||
username_input = page.ele('tag:input@name=j_username')
|
||||
if not username_input:
|
||||
raise RuntimeError("未找到用户名输入框")
|
||||
username_input.input(final_username)
|
||||
|
||||
page.wait(0.5)
|
||||
|
||||
# 定位并填写密码
|
||||
password_input = page.ele('tag:input@name=j_password')
|
||||
if not password_input:
|
||||
raise RuntimeError("未找到密码输入框")
|
||||
password_input.input(final_password)
|
||||
|
||||
page.wait(0.5)
|
||||
|
||||
# 定位并点击登录按钮
|
||||
login_button = page.ele('.lui_login_button_div_c')
|
||||
if not login_button:
|
||||
raise RuntimeError("未找到登录按钮")
|
||||
login_button.click()
|
||||
|
||||
page.wait(0.5)
|
||||
|
||||
# ---------- 轮询检测 URL ----------
|
||||
start = time.time()
|
||||
while time.time() - start < timeout: # timeout 默认 10 秒
|
||||
if target_url_keyword in page.url:
|
||||
print(f"登录成功!当前 URL: {page.url}")
|
||||
return page
|
||||
time.sleep(0.5)
|
||||
|
||||
# 超时处理
|
||||
error_elem = page.ele('.error-msg') or page.ele('.alert-danger')
|
||||
if error_elem:
|
||||
print(f"登录失败,提示: {error_elem.text}")
|
||||
raise RuntimeError(f"登录超时,当前 URL: {page.url}")
|
||||
|
||||
except Exception as e:
|
||||
# 若发生异常,可选择关闭浏览器并重新抛出
|
||||
page.quit()
|
||||
raise RuntimeError(f"登录过程出错: {e}")
|
||||
|
||||
|
||||
# ---------- 使用示例 ----------
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
page = oa_login()
|
||||
except RuntimeError as e:
|
||||
print(e)
|
||||
@@ -0,0 +1,219 @@
|
||||
# -*- 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", "")
|
||||
# 移除 <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))
|
||||
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
|
||||
@@ -0,0 +1,153 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.parser
|
||||
@FileName: parser.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:10
|
||||
@Description: 解析模块(处理 SSO 302 跳转、HTML 排班表格解析)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from DrissionPage import SessionPage
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
import re
|
||||
from typing import Dict, List
|
||||
|
||||
|
||||
# ---------- SSO 跳转解析 ----------
|
||||
def extract_real_url_and_params(session: SessionPage, sso_url: str) -> Dict[str, str]:
|
||||
"""
|
||||
访问 SSO 链接,从 302 重定向的 Location 头中提取真实详情页 URL,
|
||||
并解析出 taskId 和 businessKey。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
sso_url: SSO 跳转链接(完整 URL)
|
||||
|
||||
Returns:
|
||||
包含 taskId 和 businessKey 的字典
|
||||
|
||||
Raises:
|
||||
RuntimeError: 非 30x 状态码、无 Location 头或参数缺失
|
||||
"""
|
||||
print(f"🔗 解析 SSO: {sso_url}")
|
||||
|
||||
# 禁止自动重定向,仅获取响应头
|
||||
session.get(sso_url, allow_redirects=False)
|
||||
resp = session.response
|
||||
|
||||
if resp.status_code not in (301, 302, 303, 307, 308):
|
||||
raise RuntimeError(f"SSO 链接未返回重定向状态码,实际: {resp.status_code}")
|
||||
|
||||
location = resp.headers.get("Location")
|
||||
if not location:
|
||||
raise RuntimeError("重定向响应中未找到 Location 头")
|
||||
|
||||
# 补全为绝对 URL(若为相对路径)
|
||||
if not location.startswith(("http://", "https://")):
|
||||
if location.startswith("/"):
|
||||
parsed = urlparse(sso_url)
|
||||
base = f"{parsed.scheme}://{parsed.netloc}"
|
||||
location = base + location
|
||||
else:
|
||||
raise RuntimeError(f"无法解析相对路径 Location: {location}")
|
||||
|
||||
print(f"📍 真实详情页 URL: {location}")
|
||||
|
||||
# 解析查询参数
|
||||
parsed = urlparse(location)
|
||||
params = parse_qs(parsed.query)
|
||||
|
||||
task_id = params.get("taskId", [None])[0]
|
||||
business_key = params.get("businessKey", [None])[0]
|
||||
|
||||
if not task_id or not business_key:
|
||||
raise RuntimeError(f"详情页 URL 缺少 taskId 或 businessKey: {location}")
|
||||
|
||||
return {"taskId": task_id, "businessKey": business_key}
|
||||
|
||||
|
||||
# ---------- 排班 HTML 解析 ----------
|
||||
def parse_attendance_html(html: str) -> Dict[str, str]:
|
||||
"""
|
||||
解析排班 HTML 表格,提取每个日期的班次名称。
|
||||
|
||||
示例 HTML 片段:
|
||||
<a class='cale_a' ... data-temp='2026-08-01' ...>正常</a>
|
||||
或 <a ...>休息</a>
|
||||
|
||||
Args:
|
||||
html: 排班接口返回的 HTML 字符串
|
||||
|
||||
Returns:
|
||||
字典:{日期字符串: 班次名称}
|
||||
例如:{"2026-08-01": "正常", "2026-08-02": "休息"}
|
||||
"""
|
||||
# 正则匹配 <a> 标签中的 data-temp 和文本内容
|
||||
pattern = r'<a[^>]*data-temp="([^"]+)"[^>]*>([^<]+)</a>'
|
||||
matches = re.findall(pattern, html)
|
||||
|
||||
result = {}
|
||||
for date, shift in matches:
|
||||
# 去除可能的空格
|
||||
date_clean = date.strip()
|
||||
shift_clean = shift.strip()
|
||||
result[date_clean] = shift_clean
|
||||
return result
|
||||
|
||||
|
||||
def get_work_days_in_range(
|
||||
attendance_dict: Dict[str, str],
|
||||
start_date: str,
|
||||
end_date: str
|
||||
) -> List[str]:
|
||||
"""
|
||||
根据排班字典和请假起止日期,返回请假区间内所有非“休息”的日期列表。
|
||||
|
||||
Args:
|
||||
attendance_dict: 由 parse_attendance_html 返回的字典
|
||||
start_date: 请假开始日期,格式 "YYYY-MM-DD"
|
||||
end_date: 请假结束日期,格式 "YYYY-MM-DD"
|
||||
|
||||
Returns:
|
||||
非休息日的日期字符串列表(格式 "YYYY-MM-DD")
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
start = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
end = datetime.strptime(end_date, "%Y-%m-%d")
|
||||
|
||||
work_days = []
|
||||
current = start
|
||||
while current <= end:
|
||||
date_str = current.strftime("%Y-%m-%d")
|
||||
shift = attendance_dict.get(date_str, "")
|
||||
# 如果该日期没有排班信息,或明确为“休息”,视为休息日
|
||||
if shift != "休息" and shift != "":
|
||||
work_days.append(date_str)
|
||||
current += timedelta(days=1)
|
||||
return work_days
|
||||
|
||||
|
||||
# ---------- 使用示例(测试用) ----------
|
||||
if __name__ == "__main__":
|
||||
# 测试 SSO 解析(需要有效的 session)
|
||||
# from hrbp.oa.login import oa_login
|
||||
# from hrbp.oa.session_manager import init_session_from_page
|
||||
# browser = oa_login()
|
||||
# session = init_session_from_page(browser)
|
||||
# sso_url = "https://oa.37du.co/sso/..." # 替换为实际链接
|
||||
# params = extract_real_url_and_params(session, sso_url)
|
||||
# print(params)
|
||||
|
||||
# 测试 HTML 解析
|
||||
sample_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(sample_html)
|
||||
print(result) # {'2026-08-01': '休息', '2026-08-02': '正常', '2026-08-03': '休息'}
|
||||
|
||||
work = get_work_days_in_range(result, "2026-08-01", "2026-08-03")
|
||||
print(work) # ['2026-08-02']
|
||||
@@ -0,0 +1,61 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.session_manager
|
||||
@FileName: session_manager.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 10:30
|
||||
@Description: 从 ChromiumPage 提取 Cookies,生成 SessionPage 供后台请求
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from DrissionPage import ChromiumPage, SessionPage
|
||||
|
||||
|
||||
def init_session_from_page(
|
||||
browser_page: ChromiumPage,
|
||||
copy_headers: bool = True
|
||||
) -> SessionPage:
|
||||
"""
|
||||
从已登录的 ChromiumPage 中提取 cookies 和 headers,
|
||||
创建并返回一个可直接发送后台请求的 SessionPage 对象。
|
||||
|
||||
Args:
|
||||
browser_page: 已登录的 ChromiumPage 实例
|
||||
copy_headers: 是否复制浏览器的 User-Agent 等头部信息(默认 True)
|
||||
|
||||
Returns:
|
||||
已设置好 cookies 和 headers 的 SessionPage 对象
|
||||
"""
|
||||
session = SessionPage()
|
||||
|
||||
# 1. 获取浏览器 cookies(字典形式)
|
||||
cookies_dict = browser_page.cookies()
|
||||
if cookies_dict:
|
||||
session.set.cookies(cookies_dict)
|
||||
print(f"✅ 已复制 {len(cookies_dict)} 个 Cookies 到 SessionPage")
|
||||
else:
|
||||
print("⚠️ 未获取到 Cookies,请确认浏览器已登录")
|
||||
|
||||
# 2. 可选复制 headers(主要是 User-Agent,防止被反爬)
|
||||
if copy_headers:
|
||||
headers = {
|
||||
"User-Agent": browser_page.run_js("return navigator.userAgent;")
|
||||
}
|
||||
session.set.headers(headers)
|
||||
print(f"✅ 已复制 User-Agent: {headers['User-Agent'][:50]}...")
|
||||
|
||||
# 3. 可额外设置默认超时、重试等
|
||||
session.set.timeout(10) # 全局超时 10 秒
|
||||
|
||||
return session
|
||||
|
||||
|
||||
# 便捷函数:直接从已登录的浏览器提取会话,一步到位
|
||||
def create_session_from_login() -> SessionPage:
|
||||
"""
|
||||
如果希望快速测试,可直接调用 oa_login() 获取浏览器,
|
||||
再提取 SessionPage。
|
||||
"""
|
||||
from .login import oa_login
|
||||
browser = oa_login()
|
||||
return init_session_from_page(browser)
|
||||
@@ -0,0 +1,64 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave.leave_approval
|
||||
@FileName: leave_approval.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:21
|
||||
@Description: 请假审批流程最终调用模块:登录 → 会话 → 拉取请假待办 → 逐单校验 → 生成报告
|
||||
@Version: 1.1.0
|
||||
|
||||
@Usage:
|
||||
python -m hrbp.oa.leave.leave_approval
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from ...intelligent_retry import retry
|
||||
from ..common.login import oa_login
|
||||
from ..common.session_manager import init_session_from_page
|
||||
from ..common.oa_api import get_documents
|
||||
from .validator import validate_doc
|
||||
from .reporter import generate_report
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@retry(max_attempts=3, delay=2.0)
|
||||
def _login():
|
||||
"""登录 OA(失败自动重试,最多 3 次)"""
|
||||
return oa_login()
|
||||
|
||||
|
||||
@retry(max_attempts=3, delay=1.0)
|
||||
def _fetch_documents(session) -> List[Dict[str, Any]]:
|
||||
"""拉取请假待办单据(失败自动重试,最多 3 次)"""
|
||||
return get_documents(session, subject="请假")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
logger.info("请假审批流程开始")
|
||||
|
||||
browser = _login()
|
||||
session = init_session_from_page(browser)
|
||||
|
||||
docs = _fetch_documents(session)
|
||||
logger.info("共获取请假待办 %d 条", len(docs))
|
||||
|
||||
# 逐单校验(规则在 validator.py 中实现)
|
||||
results = []
|
||||
for doc in docs:
|
||||
result = validate_doc(doc)
|
||||
results.append(result)
|
||||
logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"])
|
||||
|
||||
# 生成报告(格式在 reporter.py 中实现)
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
logger.info("请假审批流程结束,共处理 %d 条", len(results))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,29 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave.reporter
|
||||
@FileName: reporter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:11
|
||||
@Description: 请假流程报告模块,生成审批报告
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
|
||||
def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
"""
|
||||
根据校验结果生成请假审批报告。
|
||||
|
||||
TODO: 按实际报告格式完善(导出 Excel/文件等)。
|
||||
|
||||
Args:
|
||||
results: validate_doc 返回的校验结果列表
|
||||
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
lines = ["请假审批报告", "=" * 30]
|
||||
for r in results:
|
||||
lines.append(f"{r.get('creator', '')} | {r.get('title', '')} | {r.get('decision', '')}")
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,32 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.leave.validator
|
||||
@FileName: validator.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:11
|
||||
@Description: 请假流程校验模块(审批规则:驳回/人工复核/通过)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
def validate_doc(doc: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
校验单张请假单据,返回审批决策。
|
||||
|
||||
TODO: 请假审批规则在此实现(依据排班、假期类型、请假时长等判定通过/驳回/人工复核)。
|
||||
|
||||
Args:
|
||||
doc: 单据信息(title/creator/time/detail_url)
|
||||
|
||||
Returns:
|
||||
校验结果,包含审批决策
|
||||
"""
|
||||
return {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"decision": "pending", # pending: 规则未实现,默认待处理
|
||||
"note": "请假校验规则待补充",
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.work_overtime.overtime_approval
|
||||
@FileName: overtime_approval.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:22
|
||||
@Description: 加班审批流程最终调用模块:登录 → 会话 → 拉取加班待办 → 逐单校验 → 生成报告
|
||||
@Version: 1.1.0
|
||||
|
||||
@Usage:
|
||||
python -m hrbp.oa.work_overtime.overtime_approval
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from ...intelligent_retry import retry
|
||||
from ..common.login import oa_login
|
||||
from ..common.session_manager import init_session_from_page
|
||||
from ..common.oa_api import get_documents
|
||||
from .validator import validate_doc
|
||||
from .reporter import generate_report
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@retry(max_attempts=3, delay=2.0)
|
||||
def _login():
|
||||
"""登录 OA(失败自动重试,最多 3 次)"""
|
||||
return oa_login()
|
||||
|
||||
|
||||
@retry(max_attempts=3, delay=1.0)
|
||||
def _fetch_documents(session) -> List[Dict[str, Any]]:
|
||||
"""拉取加班待办单据(失败自动重试,最多 3 次)"""
|
||||
return get_documents(session, subject="加班")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
logger.info("加班审批流程开始")
|
||||
|
||||
browser = _login()
|
||||
session = init_session_from_page(browser)
|
||||
|
||||
docs = _fetch_documents(session)
|
||||
logger.info("共获取加班待办 %d 条", len(docs))
|
||||
|
||||
# 逐单校验(规则在 validator.py 中实现)
|
||||
results = []
|
||||
for doc in docs:
|
||||
result = validate_doc(doc)
|
||||
results.append(result)
|
||||
logger.info("已校验: %s - %s -> %s", result["creator"], result["title"], result["decision"])
|
||||
|
||||
# 生成报告(格式在 reporter.py 中实现)
|
||||
report = generate_report(results)
|
||||
print("\n" + report)
|
||||
|
||||
logger.info("加班审批流程结束,共处理 %d 条", len(results))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,29 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.work_overtime.reporter
|
||||
@FileName: reporter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:35
|
||||
@Description: 加班流程报告模块,生成审批报告
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List
|
||||
|
||||
|
||||
def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
"""
|
||||
根据校验结果生成加班审批报告。
|
||||
|
||||
TODO: 按实际报告格式完善(与请假报告不同,含加班时长等字段)。
|
||||
|
||||
Args:
|
||||
results: validate_doc 返回的校验结果列表
|
||||
|
||||
Returns:
|
||||
报告文本
|
||||
"""
|
||||
lines = ["加班审批报告", "=" * 30]
|
||||
for r in results:
|
||||
lines.append(f"{r.get('creator', '')} | {r.get('title', '')} | {r.get('decision', '')}")
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,32 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.work_overtime.validator
|
||||
@FileName: validator.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:35
|
||||
@Description: 加班流程校验模块(审批规则:驳回/人工复核/通过)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
def validate_doc(doc: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
校验单张加班单据,返回审批决策。
|
||||
|
||||
TODO: 加班审批规则在此实现(与请假规则不同,依据加班时长、时段等判定通过/驳回/人工复核)。
|
||||
|
||||
Args:
|
||||
doc: 单据信息(title/creator/time/detail_url)
|
||||
|
||||
Returns:
|
||||
校验结果,包含审批决策
|
||||
"""
|
||||
return {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"decision": "pending", # pending: 规则未实现,默认待处理
|
||||
"note": "加班校验规则待补充",
|
||||
}
|
||||
Reference in New Issue
Block a user