Files
37duAutomation/plugins/xq0004/data/hr_api.py
T
puddy 843ff244a6 feat: 新增多插件 UI 支持及运行日志集中回传功能
本次提交包含多项功能更新:
1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持
2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储
3. 新增插件分类字段支持,用于场景库分组管理
4. 优化 xq0034/0037/0048 等插件的功能及描述
5. 修复控制面响应兼容问题,支持新旧版本数据格式
6. 新增 xq0033 插件的状态存储模块,用于历史记录管理
7. 优化 CRM 登录窗口模式,支持全屏置顶
2026-10-26 15:42:50 +08:00

349 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""XQ0004 EHR系统加班流程审核 插件 - HR 接口层(由影刀版 overtime_approval.py 接口部分移植)。
链路:
1) WeProcess getProcessAndData 查加班流程待办(含 taskId/businessKey/formId)
2) WfActivity getWfActivityByTaskId 取 formId
3) WorkformEngine getBusinessDate 取加班表单数据
4) rf_s_kq_count_leave_yc_day_all 按员工+日期范围取每日考勤(班次名/班次起止)
5) rf_s_kq_leave_record_SelectByStaffID 取请假记录(弹性兑换前置校验)
6) rf_s_kq_data_queryByStaffId 取打卡明细(kq_time/bc_date/time_order)
插件化改造点(与影刀版差异):
1. 纯 requests 调用(底座注入的 requests.Session),不再用 DrissionPage SessionPage;
2. 登录态失效统一抛 HRSessionExpiredError,由上层提示重新登录(不自动补登);
3. 日志统一转发到 ctx.log(config.logger)。
"""
from ..config import (
logger, retry, require_session,
HR_BASE_URL, WE_PROCESS_QUERY_URL, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL,
GET_CUR_USER_INFO_URL, ATTENDANCE_DAILY_URL, LEAVE_RECORD_URL, PUNCH_RECORD_URL,
DEFAULT_PAGE_SIZE,
)
class HRSessionExpiredError(Exception):
"""HR 登录态失效(接口返回非 JSON 或 Nosession,被重定向到登录页)。"""
def hr_request_json(session, method, url, params, label, timeout=20):
"""POST/GET 请求并校验返回 JSON;非 JSON 视为登录态失效。"""
resp = session.request(method.upper(), url, data=params, timeout=timeout)
resp.raise_for_status()
text = resp.text or ""
if not text or not text.lstrip().startswith(("{", "[")):
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
return resp.json()
def fetch_cur_user_info(session):
"""调用 getCurUserInfo,返回 userId / rootId(treecode)。"""
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
def validate_session(session):
"""校验注入的 HR 登录态有效,返回 current userId。"""
try:
info = fetch_cur_user_info(session)
except HRSessionExpiredError:
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from None
user_id = str(info.get("userId") or "") if isinstance(info, dict) else ""
if not user_id:
raise RuntimeError("HR 登录态无效(getCurUserInfo 未返回 userId),请重新登录 HR")
return user_id
# ==================== 加班流程待办 ====================
def fetch_we_process_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
"""拉一页流程待办(title 按标题模糊匹配)。"""
params = {
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
"struId": "", "rootId": "cq37du", "taskIds": "", "title": subject,
"state": "", "startTime": "", "endTime": "",
"sortType": "desc", "sortName": "CREATE_TIME",
"commonQuery": "[]", "start": str((page_no - 1) * page_size),
"pageNo": str(page_no), "pageSize": str(page_size),
}
data = hr_request_json(session, "POST", WE_PROCESS_QUERY_URL, params, "WeProcess")
if str(data.get("state")) != "1":
if str(data.get("state")) == "Nosession" or "会话过期" in str(data.get("meg", "")):
raise HRSessionExpiredError(f"WeProcess 返回会话过期: {data.get('meg')}")
raise RuntimeError(f"WeProcess 接口返回失败: state={data.get('state')} meg={data.get('meg')}")
return data
def parse_we_process_list(data):
"""解析待办行为单据字典;detail_url 用 reqType=WAIT(待办审批视图,页面才有审批按钮)。"""
docs = []
for row in data.get("jsonList") or data.get("datas") or []:
title = str(row.get("title") or "").strip()
task_id = str(row.get("taskId") or "")
business_key = str(row.get("businessKey") or "")
process_id = str(row.get("processId") or "")
form_id = str(row.get("formId") or "")
if not task_id or not business_key:
logger.warning("跳过缺 taskId/businessKey 的待办行: %s", title)
continue
detail_url = (
f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc?method=goToWorkFlow"
f"&formId={form_id}&businessKey={business_key}&processId={process_id}"
f"&taskId={task_id}&reqType=WAIT&headType=&systemId="
)
docs.append({
"title": title,
"creator": str(row.get("createUserName") or row.get("createUserNameCn") or "").strip(),
"time": str(row.get("createTime") or "").strip(),
"taskId": task_id,
"businessKey": business_key,
"processId": process_id,
"formId": form_id,
"detail_url": detail_url,
})
return docs
def get_documents(session, subject, page_size=DEFAULT_PAGE_SIZE):
"""分页拉取全部待办,按 taskId 去重。"""
all_docs = []
page_no = 1
while page_no <= 20: # 防御性分页上限
data = fetch_we_process_page(session, subject, page_no=page_no, page_size=page_size)
docs = parse_we_process_list(data)
all_docs.extend(docs)
logger.info("第 %d 页获取 %d 条,累计 %d 条", page_no, len(docs), len(all_docs))
if len(docs) < page_size:
break
page_no += 1
seen = set()
unique_docs = []
for doc in all_docs:
key = doc.get("taskId") or doc.get("detail_url") or doc.get("title")
if key in seen:
continue
seen.add(key)
unique_docs.append(doc)
if len(unique_docs) != len(all_docs):
logger.warning("去重前 %d 条,去重后 %d 条(已过滤 %d 条重复单据)",
len(all_docs), len(unique_docs), len(all_docs) - len(unique_docs))
return unique_docs
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
def fetch_documents(session, subject):
return get_documents(session, subject=subject)
# ==================== 表单详情 ====================
def get_wf_activity_by_task_id(session, task_id):
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
logger.info("获取 formId: taskId=%s", task_id)
try:
json_data = hr_request_json(session, "POST", url, {"taskId": task_id}, "WfActivity")
except HRSessionExpiredError:
raise
except Exception as e:
raise RuntimeError(f"WfActivity 接口请求失败: {e}") from e
logger.debug("WfActivity 返回: %s", json_data)
return json_data
def extract_form_id(wf_activity_data):
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
def get_business_data(session, business_key, form_id):
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
logger.info("获取加班表单: businessKey=%s, formId=%s", business_key, form_id)
try:
json_data = hr_request_json(
session, "POST", url,
{"businessKey": business_key, "formId": form_id}, "WorkformEngine")
except HRSessionExpiredError:
raise
except Exception as e:
raise RuntimeError(f"WorkformEngine 接口请求失败: {e}") from e
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
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
def fetch_doc_detail(doc):
"""纯接口取单据详情:taskId/businessKey 直接取自 WeProcess 行(免 SSO 解析)。"""
session = require_session()
task_id = doc.get("taskId")
business_key = doc.get("businessKey")
if not task_id or not business_key:
raise RuntimeError(f"待办行缺 taskId/businessKey: {doc.get('title')}")
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
form_id = extract_form_id(wf_activity_data)
form_data = get_business_data(session, business_key, form_id)
return {**doc, "formId": form_id, "formData": form_data}
# ==================== 每日考勤(排班 + 班次时段) ====================
def get_attendance_daily(session, staff_id, start_date, end_date):
"""按员工+日期范围查询每日考勤(含班次起止时间与上下班打卡)。
kq_status_total 按考勤状态分类返回记录:0=休息日、1=正常班、9=未打卡、11=异常,
需四种状态各查一次,再按 work_day 合并去重,才能同时拿到班次名/班次时段与休息日记录。
"""
by_day = {}
for status in ("0", "1", "9", "11"):
params = {
"staff_id": staff_id,
"begin_date": start_date,
"end_date": end_date,
"kq_status_total": status,
}
logger.info("获取考勤逐日(kq_status_total=%s): staff_id=%s, %s 至 %s",
status, staff_id, start_date, end_date)
try:
json_data = hr_request_json(
session, "POST", ATTENDANCE_DAILY_URL, params, "考勤逐日")
except HRSessionExpiredError:
raise
except Exception as e:
raise RuntimeError(f"考勤逐日接口请求失败: {e}") from e
for r in json_data.get("data", []) or []:
by_day.setdefault(str(r.get("work_day", "")), r)
records = [by_day[k] for k in sorted(by_day)]
logger.info("考勤逐日合并返回 %d 天", len(records))
return records
# ==================== 请假记录 ====================
def fetch_leave_record_page(session, staff_id, begin_date, end_date,
page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
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)
try:
json_data = hr_request_json(session, "POST", LEAVE_RECORD_URL, data, "请假记录")
except HRSessionExpiredError:
raise
except Exception as e:
raise RuntimeError(f"请假记录接口请求失败: {e}") from e
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, staff_id, begin_date, end_date,
page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
all_records = []
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
# ==================== 打卡明细 ====================
def fetch_punch_record_page(session, staff_id, begin_date, end_date,
page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
"""请求单页员工打卡明细(kq_time 真实打卡时间 / bc_date 考勤归属日 / time_order 1上2下)。"""
data = {
"start": str((page_no - 1) * page_size),
"sortType": "",
"sortName": "",
"pageNo": str(page_no),
"pageSize": str(page_size),
"staff_id": staff_id,
"rootId": "",
"countId": "",
"bc_date": begin_date,
"bc_date_end": end_date,
"begin": begin_date,
"end": end_date,
"sub_type": sub_type,
}
logger.info("获取打卡明细: staff_id=%s, %s 至 %s, 第%d页",
staff_id, begin_date, end_date, page_no)
try:
json_data = hr_request_json(session, "POST", PUNCH_RECORD_URL, data, "打卡明细")
except HRSessionExpiredError:
raise
except Exception as e:
raise RuntimeError(f"打卡明细接口请求失败: {e}") from e
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_punch_records(session, staff_id, begin_date, end_date,
page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
"""查询员工某时间段内的全部打卡明细(自动分页)。"""
all_records = []
page_info = fetch_punch_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_punch_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