hr_sdk: ledger.export_advance_pay 增强;workflow 新增 list_supervised/task_ids/form_info/export_detail(全部流程详细数据 38 列,含收款银行/账号)。 printkit: registry 支持按部门名(humanresource/it)解析打印机,供 XQ0012 选机。
373 lines
16 KiB
Python
373 lines
16 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""审批流程(待办单据)接口:列表 / 表单业务数据 / 流程详细数据导出。
|
||
|
||
用法::
|
||
|
||
from hr_sdk import HrClient, workflow
|
||
|
||
client = HrClient(ctx.get_session("hr"))
|
||
docs = workflow.list_docs(client, subject="请假") # 待办单据
|
||
form = workflow.form_data(client, docs[0]["businessKey"], docs[0]["formId"])
|
||
|
||
# 「任务流程 → 导出全部流程详细数据」(异步导出,38 列固定字段)
|
||
tids = workflow.task_ids(client, process_id)
|
||
workflow.export_detail(client, task_ids=tids[0], table="bpm_cq37du_test_00027",
|
||
wfwork_form_id=form_id, output_path="全部流程详细数据.xls")
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from typing import Dict, List, Optional, Sequence, Union
|
||
from urllib.parse import urlencode
|
||
|
||
from .config import HR_BASE_URL, REDSEA
|
||
from .errors import ApiError, HrError
|
||
|
||
WE_PROCESS_QUERY_URL = f"{REDSEA}/WeProcess.mc?method=getProcessAndData"
|
||
WF_ACTIVITY_URL = f"{REDSEA}/WfActivity.mc"
|
||
WORKFORM_ENGINE_URL = f"{REDSEA}/WorkformEngine.mc"
|
||
DETAIL_URL_PREFIX = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc?method=goToWorkFlow"
|
||
|
||
# ---- 流程详细数据导出(we_process_export.js → exportCustomSqlData) ----
|
||
#: 会话绑定页(WS 异步导出前必须访问并注册 ws/bridge)
|
||
WE_PROCESS_PAGE_URL = (f"{REDSEA}/jsp/workFlow/processRun/weProcess/we_process_div_new.jsp"
|
||
f"?1=1&menuName=%E4%BB%BB%E5%8A%A1%E6%B5%81%E7%A8%8B")
|
||
#: 异步导出入口(method 必须在 query string,body 走 form 字段;由 export_detail 拼参数)
|
||
WE_PROCESS_EXPORT_URL = f"{REDSEA}/WeProcess.mc"
|
||
#: processId → 该流程全部 taskId
|
||
TASK_BY_PROCESS_URL = f"{REDSEA}/getPageAjax/sql_query_taskId_byProcessID/CoreRequest.mc"
|
||
WORKFORM_QUERY_URL = f"{REDSEA}/WfWorkform.mc?method=query"
|
||
#: 流程监控 → 全部流程(按标题/办结状态/日期区间筛选,返回 processId 列表)
|
||
SUPERVISE_URL = f"{REDSEA}/WeProcess/queryWeProcessAllProcessPageBySupervise.mc"
|
||
|
||
#: 流程监控固定筛选条件(集团 + 全部分类;实测 2026-11)
|
||
SUPERVISE_DEFAULTS = {
|
||
"supervise_id": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||
"BELONG_STRU_ID": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||
"stru_tree_code": "cq37du",
|
||
"belongUnitStruName": "集团",
|
||
"state": "monitor_all",
|
||
}
|
||
|
||
#: 导出文件名 / sheet 名
|
||
DETAIL_EXPORT_TITLE = "全部流程详细数据"
|
||
|
||
#: 导出列定义(colCode:列名[:枚举配置],与前端 param 完全一致,顺序即列顺序)
|
||
DETAIL_FIELDS = (
|
||
"WE_PROCESS_SERIAL_NUMBER:流水号,TASK_TITLE:流程标题,processName:流程名称,"
|
||
"PROCESS_CREATE_USER_NAME:申请人,PROCESS_CREATE_USER_BASECODE:申请人工号,"
|
||
"TASK_START_TIME:申请时间,TASK_END_TIME:办结时间,DURATION_TIME:办理时长,"
|
||
"TASK_CREATE_TIME:任务发送时间,ACTIVITY_NAME:当前环节,TIMEDIFF:超时,"
|
||
"PROCESS_STATE:流程状态,pay_way:收款方式:ShouKuanFangShi_sp_cq37du,reporter:提报人,"
|
||
"base_code:工号,"
|
||
"post_name:岗位,tech_code:技师工号,"
|
||
"type_name:职位序列:sql_Core_Post_pt_post_type_Select_v3,unit_name:所属单位,"
|
||
"staff_name:姓名,report_date:提报日期,shoukuanren:收款人,"
|
||
"advance_money:已预支金额,advance_month:预支工资年月,"
|
||
"org_full_path:组织全路径,reporter_unit:提报单位,"
|
||
"advance_money1:申请预支金额,advance_reason:预支原因,"
|
||
"shoukuanyinhang:收款银行,shoukuanzhanghao:收款账号,file:附件,"
|
||
"base_id:员工id,dept_id:部门id,main_id:预生成主键,reporter_id:提报人id,"
|
||
"dept_org_four:四级部门,org_type_code:所属部门组织类型:pt_org_type_module_conf,"
|
||
"principal_staff_name:组织负责人"
|
||
)
|
||
|
||
DEFAULT_PAGE_SIZE = 100
|
||
MAX_PAGES = 20
|
||
|
||
|
||
# ==================== 待办列表 ====================
|
||
|
||
def fetch_page(client, subject: str, *, page_no: int = 1,
|
||
page_size: int = DEFAULT_PAGE_SIZE) -> dict:
|
||
"""拉一页待办(title 按标题模糊匹配 ``subject``)。"""
|
||
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 = client.request_json("POST", WE_PROCESS_QUERY_URL, data=params, label="WeProcess")
|
||
return client.check_state(data, "WeProcess")
|
||
|
||
|
||
def parse_docs(data: dict) -> List[dict]:
|
||
"""解析待办行为单据字典;``detail_url`` 用 ``reqType=WAIT``(待办审批视图)。"""
|
||
docs = []
|
||
for row in data.get("jsonList") or data.get("datas") or []:
|
||
task_id = str(row.get("taskId") or "").strip()
|
||
business_key = str(row.get("businessKey") or "").strip()
|
||
if not task_id or not business_key:
|
||
continue
|
||
form_id = str(row.get("formId") or "")
|
||
process_id = str(row.get("processId") or "")
|
||
docs.append({
|
||
"title": str(row.get("title") or "").strip(),
|
||
"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": (f"{DETAIL_URL_PREFIX}&formId={form_id}"
|
||
f"&businessKey={business_key}&processId={process_id}"
|
||
f"&taskId={task_id}&reqType=WAIT&headType=&systemId="),
|
||
})
|
||
return docs
|
||
|
||
|
||
def list_docs(client, subject: str, *, page_size: int = DEFAULT_PAGE_SIZE,
|
||
max_pages: int = MAX_PAGES) -> List[dict]:
|
||
"""分页拉全部待办并按 ``taskId`` 去重。``subject`` 如 ``请假`` / ``加班``。"""
|
||
all_docs: List[dict] = []
|
||
for page_no in range(1, max_pages + 1):
|
||
data = fetch_page(client, subject, page_no=page_no, page_size=page_size)
|
||
page_docs = parse_docs(data)
|
||
client.log(f"[INFO] 待办第 {page_no} 页 {len(page_docs)} 条")
|
||
all_docs.extend(page_docs)
|
||
if len(page_docs) < page_size:
|
||
break
|
||
|
||
seen, unique = set(), []
|
||
for doc in all_docs:
|
||
key = doc.get("taskId") or doc.get("detail_url")
|
||
if key in seen:
|
||
continue
|
||
seen.add(key)
|
||
unique.append(doc)
|
||
if len(unique) != len(all_docs):
|
||
client.log(f"[WARN] 待办去重:{len(all_docs)} → {len(unique)}")
|
||
return unique
|
||
|
||
|
||
# ==================== 单据详情 ====================
|
||
|
||
def activity(client, task_id: str) -> dict:
|
||
"""按 taskId 取流程活动信息(含 formId/businessKey)。"""
|
||
data = client.request_json("POST", f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId",
|
||
data={"taskId": task_id}, label="WfActivity")
|
||
return client.check_state(data, "WfActivity")
|
||
|
||
|
||
def form_data(client, business_key: str, form_id: str) -> Dict[str, object]:
|
||
"""取表单业务数据(``result`` 字典)。"""
|
||
data = client.request_json("POST", f"{WORKFORM_ENGINE_URL}?method=getBusinessDate",
|
||
data={"businessKey": business_key, "formId": form_id},
|
||
label="WorkformEngine")
|
||
client.check_state(data, "WorkformEngine")
|
||
result = data.get("result")
|
||
if not isinstance(result, dict):
|
||
from .errors import ApiError
|
||
raise ApiError(f"WorkformEngine 未返回 result 字典:{str(data)[:200]}", payload=data)
|
||
return result
|
||
|
||
|
||
def detail_url(form_id: str = "", business_key: str = "", process_id: str = "",
|
||
task_id: str = "") -> str:
|
||
"""构造待办审批详情页地址(需要人工点击时用)。"""
|
||
return (f"{DETAIL_URL_PREFIX}&formId={form_id}&businessKey={business_key}"
|
||
f"&processId={process_id}&taskId={task_id}&reqType=WAIT&headType=&systemId=")
|
||
|
||
|
||
# ==================== 流程详细数据导出 ====================
|
||
|
||
def task_ids(client, process_id: str) -> List[str]:
|
||
"""按 ``processId`` 取该流程下的全部 ``TASK_ID``(一个流程多个环节任务)。
|
||
|
||
前端同样用它(``getTaskIdByProcessId``):导出只要其中任意一条即可,
|
||
因为表单业务字段是进程级的,各任务行的差异只在「任务发送时间/超时」。
|
||
"""
|
||
pid = str(process_id or "").strip()
|
||
if not pid:
|
||
return []
|
||
data = client.request_json("POST", TASK_BY_PROCESS_URL,
|
||
data={"processId": pid}, label="CoreRequest")
|
||
out = []
|
||
for item in data.get("datas") or []:
|
||
tid = str((item or {}).get("TASK_ID") or "").strip()
|
||
if tid:
|
||
out.append(tid)
|
||
return out
|
||
|
||
|
||
def form_info(client, form_id: str) -> Dict[str, str]:
|
||
"""按 ``formId`` 取表单定义:``{"formId","table","pk","name"}``。
|
||
|
||
``table`` 是导出的 ``table``(tableCode),``pk`` 是 ``pk``(businessKeycode)。
|
||
"""
|
||
fid = str(form_id or "").strip()
|
||
if not fid:
|
||
raise ApiError("form_info:formId 不能为空")
|
||
data = client.request_json("POST", WORKFORM_QUERY_URL, data={"form_ids": fid},
|
||
label="WfWorkform")
|
||
client.check_state(data, "WfWorkform")
|
||
items = data.get("jsonList") or []
|
||
if not items:
|
||
raise ApiError(f"未查到表单定义:{fid}")
|
||
j = items[0] or {}
|
||
info = {
|
||
"formId": str(j.get("formId") or fid),
|
||
"table": str(j.get("tableCode") or ""),
|
||
"pk": str(j.get("businessKeycode") or "main_id"),
|
||
"name": str(j.get("tableName") or ""),
|
||
}
|
||
if not info["table"]:
|
||
raise ApiError(f"表单「{fid}」没有配置表名/视图名,无法导出")
|
||
return info
|
||
|
||
|
||
def supervised_page(client, *, title: str = "", begin_date: str = "", end_date: str = "",
|
||
current_state: str = "COMPLETED", page_no: int = 1,
|
||
page_size: int = 50, process_type: str = "",
|
||
sort_name: str = "start_time", sort_type: str = "desc") -> dict:
|
||
"""拉一页「流程监控 → 全部流程」,返回 ``{"rows","count","pageCount","pageNo"}``。
|
||
|
||
Args:
|
||
title: 流程标题模糊匹配(如 ``预支``)
|
||
begin_date / end_date: 申请时间区间 ``YYYY-MM-DD``(两端闭区间)
|
||
current_state: ``COMPLETED``(已办结)/ ``RUNNING`` / 留空=不限
|
||
page_no / page_size: 页码 / 每页条数
|
||
process_type: 流程分类(留空=全部)
|
||
"""
|
||
params = dict(SUPERVISE_DEFAULTS)
|
||
params.update({
|
||
"start": str(max(0, (page_no - 1) * page_size)),
|
||
"pageNo": str(page_no), "pageSize": str(page_size),
|
||
"sortName": sort_name, "sortType": sort_type,
|
||
"commonQuery": "[]", "we_not_draft": "",
|
||
"begin_date": begin_date or "", "end_date": end_date or "",
|
||
"process_type": process_type, "current_state": current_state or "",
|
||
"title": title or "",
|
||
})
|
||
data = client.request_json("POST", SUPERVISE_URL, data=params, label="WeProcess")
|
||
rows = []
|
||
for row in data.get("datas") or []:
|
||
row = row or {}
|
||
pid = str(row.get("PROCESS_ID") or "").strip()
|
||
if not pid:
|
||
continue
|
||
rows.append({
|
||
"processId": pid,
|
||
"formId": str(row.get("FORM_ID") or "").strip(),
|
||
"businessKey": str(row.get("BUSINESS_KEY") or "").strip(),
|
||
"title": str(row.get("TITLE") or "").strip(),
|
||
"processName": str(row.get("PROCESS_NAME") or "").strip(),
|
||
"staffNo": str(row.get("PROCESS_CREATE_USER_BASECODE") or "").strip(),
|
||
"serial": str(row.get("SERIAL_NUMBER") or "").strip(),
|
||
"state": str(row.get("CURRENT_STATE") or "").strip(),
|
||
"startTime": str(row.get("START_TIME") or "").strip(),
|
||
"endTime": str(row.get("END_TIME") or "").strip(),
|
||
})
|
||
return {"rows": rows, "count": int(data.get("count") or 0),
|
||
"pageCount": int(data.get("pageCount") or 0), "pageNo": page_no}
|
||
|
||
|
||
def list_supervised(client, *, title: str = "", begin_date: str = "", end_date: str = "",
|
||
current_state: str = "COMPLETED", page_size: int = 50,
|
||
max_pages: int = MAX_PAGES, process_type: str = "") -> List[dict]:
|
||
"""分页拉全「流程监控 → 全部流程」,按 ``processId`` 去重。
|
||
|
||
该接口只给流程级字段(无 taskId);要导出「全部流程详细数据」需再按
|
||
:func:`task_ids` 反查 taskId。
|
||
"""
|
||
all_rows: List[dict] = []
|
||
for page_no in range(1, max_pages + 1):
|
||
page = supervised_page(client, title=title, begin_date=begin_date,
|
||
end_date=end_date, current_state=current_state,
|
||
page_no=page_no, page_size=page_size,
|
||
process_type=process_type)
|
||
page_rows = page["rows"]
|
||
client.log(f"[INFO] 流程监控第 {page_no} 页 {len(page_rows)} 条")
|
||
all_rows.extend(page_rows)
|
||
if not page_rows or (page["pageCount"] and page_no >= page["pageCount"]):
|
||
break
|
||
if len(page_rows) < page_size:
|
||
break
|
||
|
||
seen, unique = set(), []
|
||
for row in all_rows:
|
||
key = row["processId"]
|
||
if key in seen:
|
||
continue
|
||
seen.add(key)
|
||
unique.append(row)
|
||
if len(unique) != len(all_rows):
|
||
client.log(f"[WARN] 流程监控去重:{len(all_rows)} → {len(unique)}")
|
||
return unique
|
||
|
||
|
||
def export_detail(client, *, task_ids: Union[str, Sequence[str]], table: str,
|
||
wfwork_form_id: str, output_path: str, pk: str = "main_id",
|
||
title_name: str = DETAIL_EXPORT_TITLE,
|
||
timeout: Optional[int] = None) -> str:
|
||
"""导出「全部流程详细数据」(38 列固定字段),返回落盘路径。
|
||
|
||
Args:
|
||
client: :class:`hr_sdk.client.HrClient`
|
||
task_ids: 一个或多个 taskId(多个用逗号/列表);同一表单下可一次导出多行
|
||
table: ``form_info()["table"]``
|
||
wfwork_form_id: 表单 id(台账「表单id」列 = 页面勾选行的 ``formId``)
|
||
output_path: 目标文件(服务端实际返回 xlsx,但文件名惯例为 .xls)
|
||
pk: ``form_info()["pk"]``
|
||
title_name: 导出标题(= 文件名/sheet 名前缀)
|
||
timeout: 等待服务端生成文件的上限(秒)
|
||
|
||
Raises:
|
||
HrError: taskIds/table 缺失,或导出失败
|
||
SessionExpiredError: 登录态失效
|
||
"""
|
||
from . import export as export_mod
|
||
|
||
ids = task_ids if isinstance(task_ids, str) else ",".join(str(t) for t in task_ids)
|
||
ids = ",".join(x.strip() for x in ids.split(",") if x.strip())
|
||
if not ids:
|
||
raise HrError("export_detail:taskIds 为空,无法导出流程详细数据")
|
||
if not table or not wfwork_form_id:
|
||
raise HrError("export_detail:缺少 table / wfworkFormId,无法导出流程详细数据")
|
||
|
||
query = urlencode({"method": "exportWetaskWithForm", "titleName": title_name})
|
||
params = {
|
||
"param": DETAIL_FIELDS,
|
||
"taskIds": ids,
|
||
"ftl_list_taskIds": ids,
|
||
"table": table,
|
||
"pk": pk or "main_id",
|
||
"wfworkformId": wfwork_form_id,
|
||
}
|
||
return export_mod.export_table(client, page_url=WE_PROCESS_PAGE_URL,
|
||
export_url=f"{WE_PROCESS_EXPORT_URL}?{query}",
|
||
params=params, output_path=output_path,
|
||
timeout=timeout)
|
||
|
||
|
||
__all__ = [
|
||
"DEFAULT_PAGE_SIZE",
|
||
"DETAIL_EXPORT_TITLE",
|
||
"DETAIL_FIELDS",
|
||
"DETAIL_URL_PREFIX",
|
||
"MAX_PAGES",
|
||
"SUPERVISE_DEFAULTS",
|
||
"SUPERVISE_URL",
|
||
"TASK_BY_PROCESS_URL",
|
||
"WE_PROCESS_EXPORT_URL",
|
||
"WE_PROCESS_PAGE_URL",
|
||
"WE_PROCESS_QUERY_URL",
|
||
"WF_ACTIVITY_URL",
|
||
"WORKFORM_ENGINE_URL",
|
||
"WORKFORM_QUERY_URL",
|
||
"activity",
|
||
"detail_url",
|
||
"export_detail",
|
||
"fetch_page",
|
||
"form_data",
|
||
"form_info",
|
||
"list_docs",
|
||
"list_supervised",
|
||
"parse_docs",
|
||
"supervised_page",
|
||
"task_ids",
|
||
]
|