Files
aibridge/modules/workflow.py
T
2026-05-18 09:28:15 +08:00

2022 lines
91 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.
"""工作流模块
对应前端源码:
api/workFlow/task.ts - 流程任务/审批操作
api/workFlow/template.ts - 流程模板/版本/Webhook
api/workFlow/formDesign.ts - 表单设计
api/workFlow/flowDelegate.ts - 流程委托
api/workFlow/flowMonitor.ts - 流程监控
api/workFlow/trigger.ts - 触发器
views/workFlow/workFlowForm/dynamicForm/ - 动态表单发起
views/workFlow/components/FlowParser.vue - 流程解析/事件分发
views/onlineDev/flowEngine/ - 流程设计器
components/FlowProcess/ - BPMN 流程组件
jnpf-bpmn/lib/helper/defaultXml.ts - 默认 BPMN XML 模板
jnpf-bpmn/lib/utils/nodeUtil.ts - 节点工具(自动网关等)
"""
import json
import urllib.parse
from typing import Any, Dict, List, Optional
from aibridge.client import JNPFClient
from aibridge.models import APIResponse
class WorkflowAPI:
"""工作流 API"""
def __init__(self, client: JNPFClient):
self._client = client
self._task_prefix = "/api/workflow/task"
self._operator_prefix = "/api/workflow/operator"
self._template_prefix = "/api/workflow/template"
self._comment_prefix = "/api/workflow/comment"
self._webhook_prefix = "/api/workflow/Hooks"
self._delegate_prefix = "/api/workflow/FlowDelegate"
self._monitor_prefix = "/api/workflow/FlowMonitor"
self._trigger_prefix = "/api/workflow/Trigger"
self._form_design_prefix = "/api/workflow/FormDesign"
# ==================== 流程任务 ====================
def get_launch_list(self, data: dict = None) -> APIResponse:
"""获取流程发起列表"""
return self._client.request("GET", self._task_prefix, params=data)
def get_task_info(self, task_id: str, data: dict = None) -> APIResponse:
"""获取待我审批详情"""
return self._client.request("GET", f"{self._task_prefix}/{task_id}", params=data)
def create(self, data: dict) -> APIResponse:
"""新建流程发起(填写表单并发起)"""
return self._client.request("POST", self._task_prefix, data=data)
def update(self, data: dict) -> APIResponse:
"""更新流程发起"""
task_id = data.get("id")
return self._client.request("PUT", f"{self._task_prefix}/{task_id}", data=data)
def delete(self, task_id: str) -> APIResponse:
"""删除流程发起"""
return self._client.request("DELETE", f"{self._task_prefix}/{task_id}")
def launch_recall(self, task_id: str, data: dict = None) -> APIResponse:
"""流程发起撤回"""
return self._client.request("PUT", f"{self._task_prefix}/Recall/{task_id}", data=data or {})
def revoke(self, task_id: str, data: dict = None) -> APIResponse:
"""流程发起撤销"""
return self._client.request("PUT", f"{self._task_prefix}/Revoke/{task_id}", data=data or {})
def press(self, task_id: str) -> APIResponse:
"""流程发起催办"""
return self._client.request("POST", f"{self._task_prefix}/Press/{task_id}")
def get_event_log(self, task_id: str) -> APIResponse:
"""获取事件日志"""
return self._client.request("GET", f"{self._task_prefix}/{task_id}/EventLog")
def get_task_user_list(self, data: dict) -> APIResponse:
"""获取流程实例相关人员(分页)"""
return self._client.request("GET", f"{self._task_prefix}/TaskUserList/{data['taskId']}", params=data)
def get_sub_flow_info(self, node_code: str, flow_id: str) -> APIResponse:
"""查看子流程"""
return self._client.request("GET", f"{self._task_prefix}/SubFlowInfo",
params={"taskId": flow_id, "nodeCode": node_code})
def get_start_form_info(self, task_id: str) -> APIResponse:
"""查看发起节点表单"""
return self._client.request("GET", f"{self._task_prefix}/ViewStartForm/{task_id}")
def retry_outside(self, node_id: str) -> APIResponse:
"""外部节点重试"""
return self._client.request("GET", f"{self._task_prefix}/Hooks/Retry/{node_id}")
# ==================== 审批操作 ====================
def get_before_list(self, category: str, data: dict = None) -> APIResponse:
"""获取待我审核列表"""
return self._client.request("GET", f"{self._operator_prefix}/List/{category}", params=data)
def audit(self, operator_id: str, data: dict) -> APIResponse:
"""审核(同意/拒绝)"""
return self._client.request("POST", f"{self._operator_prefix}/Audit/{operator_id}", data=data)
def sign(self, operator_id: str) -> APIResponse:
"""签收"""
return self.batch_sign({"ids": [operator_id], "type": 0})
def cancel_sign(self, operator_id: str) -> APIResponse:
"""退签"""
return self.batch_sign({"ids": [operator_id], "type": 1})
def batch_sign(self, data: dict) -> APIResponse:
"""批量签收/退签"""
return self._client.request("POST", f"{self._operator_prefix}/Sign", data=data)
def handle(self, operator_id: str) -> APIResponse:
"""开始办理"""
return self.batch_handle({"ids": [operator_id]})
def batch_handle(self, data: dict) -> APIResponse:
"""批量办理"""
return self._client.request("POST", f"{self._operator_prefix}/Transact", data=data)
def save_audit(self, operator_id: str, data: dict) -> APIResponse:
"""暂存审批"""
return self._client.request("POST", f"{self._operator_prefix}/SaveAudit/{operator_id}", data=data)
def assist(self, operator_id: str, data: dict) -> APIResponse:
"""协办"""
return self._client.request("POST", f"{self._operator_prefix}/Assist/{operator_id}", data=data)
def save_assist(self, operator_id: str, data: dict) -> APIResponse:
"""协办保存"""
return self._client.request("POST", f"{self._operator_prefix}/AssistSave/{operator_id}", data=data)
def audit_recall(self, operator_id: str, data: dict) -> APIResponse:
"""撤回审核"""
return self._client.request("POST", f"{self._operator_prefix}/Recall/{operator_id}", data=data)
def transfer(self, operator_id: str, data: dict) -> APIResponse:
"""转审"""
return self._client.request("POST", f"{self._operator_prefix}/Transfer/{operator_id}", data=data)
def back(self, operator_id: str, data: dict) -> APIResponse:
"""退回审核"""
return self._client.request("POST", f"{self._operator_prefix}/SendBack/{operator_id}", data=data)
def get_back_node_list(self, operator_id: str) -> APIResponse:
"""获取退回下拉接口"""
return self._client.request("GET", f"{self._operator_prefix}/SendBackNodeList/{operator_id}")
def free_approver(self, operator_id: str, data: dict) -> APIResponse:
"""加签"""
return self._client.request("POST", f"{self._operator_prefix}/AddSign/{operator_id}", data=data)
def reduce_approver(self, operator_id: str, data: dict) -> APIResponse:
"""减签"""
return self._client.request("POST", f"{self._operator_prefix}/ReduceApprover/{operator_id}", data=data)
def get_candidate_user(self, data: dict) -> APIResponse:
"""获取候选人列表"""
operator_id = data.pop("operatorId", 0)
return self._client.request("POST", f"{self._operator_prefix}/CandidateUser/{operator_id}", data=data)
def get_candidates(self, operator_id: str, data: dict) -> APIResponse:
"""判断是否有候选人"""
return self._client.request("POST", f"{self._operator_prefix}/CandidateNode/{operator_id}", data=data)
def batch_operation(self, data: dict) -> APIResponse:
"""批量审批(0-通过 1-退回 2-转审)"""
return self._client.request("POST", f"{self._operator_prefix}/BatchOperation", data=data)
def get_batch_candidate(self, data: dict = None) -> APIResponse:
"""获取批量审批候选人"""
return self._client.request("GET", f"{self._operator_prefix}/BatchCandidate", params=data)
def get_batch_flow_selector(self) -> APIResponse:
"""获取批量审批流程"""
return self._client.request("GET", f"{self._operator_prefix}/BatchFlowSelector")
def get_batch_version_selector(self, flow_id: str) -> APIResponse:
"""获取批量审批流程版本"""
return self._client.request("GET", f"{self._operator_prefix}/BatchVersionSelector/{flow_id}")
def get_batch_node_selector(self, flow_id: str) -> APIResponse:
"""获取批量审批流程节点"""
return self._client.request("GET", f"{self._operator_prefix}/BatchNodeSelector/{flow_id}")
def get_batch_node(self, flow_id: str, node_code: str) -> APIResponse:
"""获取批量审批流程节点属性"""
return self._client.request("GET", f"{self._operator_prefix}/BatchNode",
params={"flowId": flow_id, "nodeCode": node_code})
def check_info(self, task_operator_id: str, op_type: str) -> APIResponse:
"""判断是否有查看权限"""
return self._client.request("GET", f"{self._operator_prefix}/{task_operator_id}/Info",
params={"opType": op_type})
def get_record_list(self, task_id: str, node_id: str) -> APIResponse:
"""进度节点经办列表"""
return self._client.request("GET", f"{self._operator_prefix}/RecordList",
params={"taskId": task_id, "nodeId": node_id})
def get_circulate_list(self, task_id: str, node_id: str) -> APIResponse:
"""抄送人员"""
return self._client.request("GET", f"{self._operator_prefix}/CirculateList",
params={"taskId": task_id, "nodeId": node_id})
# ==================== 流程模板 ====================
def get_template_list(self, data: dict = None) -> APIResponse:
"""获取流程模板列表(分页)"""
return self._client.request("GET", self._template_prefix, params=data)
def get_flow_list(self, form_id: str) -> APIResponse:
"""通过表单 ID 获取流程列表"""
return self._client.request("GET", f"{self._template_prefix}/{form_id}/FlowList")
def create_template(self, data: dict) -> APIResponse:
"""新建流程模板"""
return self._client.request("POST", self._template_prefix, data=data)
def update_template(self, data: dict) -> APIResponse:
"""修改流程模板"""
template_id = data.get("id")
return self._client.request("PUT", f"{self._template_prefix}/{template_id}", data=data)
def get_template_info(self, template_id: str) -> APIResponse:
"""获取流程模板信息"""
return self._client.request("GET", f"{self._template_prefix}/{template_id}")
def delete_template(self, template_id: str) -> APIResponse:
"""删除流程模板"""
return self._client.request("DELETE", f"{self._template_prefix}/{template_id}")
def copy_template(self, template_id: str) -> APIResponse:
"""复制流程模板"""
return self._client.request("POST", f"{self._template_prefix}/{template_id}/Actions/Copy")
def export_template(self, template_id: str) -> APIResponse:
"""导出流程模板"""
return self._client.request("GET", f"{self._template_prefix}/{template_id}/Actions/Export")
def save_flow(self, data: dict) -> APIResponse:
"""保存流程设计"""
return self._client.request("POST", f"{self._template_prefix}/Save", data=data)
def get_flow_info(self, flow_id: str) -> APIResponse:
"""获取流程引擎设计详情(含 flowNodes 中各节点的 formId)
注意:参数 flow_id 是 templateJson 实体 ID(即 version_id / flowId),
不是 template_id。可通过 get_version_list(template_id) 获取 version_id。
后端对应 TemplateJsonServiceImpl.getInfoVo(flowId)。
"""
return self._client.request("GET", f"{self._template_prefix}/Info/{flow_id}")
def get_version_list(self, template_id: str) -> APIResponse:
"""获取流程引擎版本列表"""
return self._client.request("GET", f"{self._template_prefix}/Version/{template_id}")
def delete_version(self, version_id: str) -> APIResponse:
"""删除流程版本"""
return self._client.request("DELETE", f"{self._template_prefix}/Info/{version_id}")
def copy_version(self, version_id: str) -> APIResponse:
"""新增流程版本"""
return self._client.request("POST", f"{self._template_prefix}/Info/{version_id}")
def get_flow_selector(self, data: dict = None) -> APIResponse:
"""列表流程列表(分页)"""
return self._client.request("GET", f"{self._template_prefix}/Selector", params=data)
def get_flow_form_info(self, template_id: str) -> APIResponse:
"""获取流程发起节点表单信息(小流程ID)"""
return self._client.request("GET", f"{self._template_prefix}/{template_id}/FormInfo")
def get_flow_start_form_info(self, template_id: str) -> APIResponse:
"""获取流程发起节点表单信息(大流程ID)"""
return self._client.request("GET", f"{self._template_prefix}/StartForm/{template_id}")
def get_flow_start_form_id(self, template_id: str) -> APIResponse:
"""获取流程版本ID和发起节点表单ID(大流程ID)"""
return self._client.request("GET", f"{self._template_prefix}/StartFormId/{template_id}")
def get_tree_list(self, form_type: str = "") -> APIResponse:
"""所属流程列表(树形)"""
return self._client.request("GET", f"{self._template_prefix}/TreeList",
params={"formType": form_type})
def change_type(self, template_id: str) -> APIResponse:
"""简单流程切换为标准流程"""
return self._client.request("PUT", f"{self._template_prefix}/{template_id}/UpdateType")
def get_collect_flow_list(self, data: dict = None) -> APIResponse:
"""获取收藏流程列表"""
return self._client.request("GET", f"{self._template_prefix}/getCommonFlowList", params=data)
def set_collect_flow(self, template_id: str) -> APIResponse:
"""收藏/取消收藏流程"""
return self._client.request("POST", f"{self._template_prefix}/SetCommonFlow/{template_id}")
def up_down_shelf(self, data: dict) -> APIResponse:
"""上架/下架"""
template_id = data.get("id")
return self._client.request("PUT", f"{self._template_prefix}/{template_id}/UpDownShelf", data=data)
def get_decision_parameter(self, template_id: str) -> APIResponse:
"""获取决策参数"""
return self._client.request("GET", f"{self._template_prefix}/{template_id}/DecisionParameter")
# ==================== 流程评论 ====================
def get_comment_list(self, data: dict) -> APIResponse:
"""获取流程评论列表"""
return self._client.request("GET", self._comment_prefix, params=data)
def create_comment(self, data: dict) -> APIResponse:
"""新建流程评论"""
return self._client.request("POST", self._comment_prefix, data=data)
def delete_comment(self, comment_id: str) -> APIResponse:
"""删除流程评论"""
return self._client.request("DELETE", f"{self._comment_prefix}/{comment_id}")
# ==================== Webhook ====================
def get_webhook_url(self, data: dict) -> APIResponse:
"""获取 Webhook URL"""
return self._client.request("GET", f"{self._webhook_prefix}/getUrl", params=data)
def get_webhook_params(self, random_str: str) -> APIResponse:
"""获取 Webhook 字段"""
return self._client.request("GET", f"{self._webhook_prefix}/getParams/{random_str}")
def webhook_start(self, flow_id: str, random_str: str) -> APIResponse:
"""Webhook 开启接收请求"""
return self._client.request("GET", f"{self._webhook_prefix}/{flow_id}/start/{random_str}")
# ==================== 流程委托 ====================
def get_delegate_list(self, data: dict = None) -> APIResponse:
"""获取流程委托列表"""
return self._client.request("GET", self._delegate_prefix, params=data)
# ==================== 流程监控 ====================
def get_monitor_list(self, data: dict = None) -> APIResponse:
"""获取流程监控列表"""
return self._client.request("GET", self._monitor_prefix, params=data)
# ==================== 高级便捷方法 ====================
@staticmethod
def build_simple_flow_xml() -> str:
"""获取简单流程默认 BPMN XML
来源: jnpf-bpmn/lib/helper/defaultXml.ts -> simpleDefaultXml
结构: StartEvent(Event_0oz4pwh) -> UserTask(Activity_1qf73gq) -> EndEvent(Event_0zlhfee)
Returns:
URL 编码后的 BPMN XML 字符串(后端 saveFlow 接口期望的格式)
"""
xml = """<?xml version="1.0" encoding="UTF-8"?>
<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="sample-diagram" targetNamespace="http://www.flowable.org/processdef" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd">
<bpmn2:process id="Process_1" name="" isExecutable="true">
<bpmn2:startEvent id="Event_0oz4pwh" >
<bpmn2:outgoing>Flow_1iadlmn</bpmn2:outgoing>
</bpmn2:startEvent>
<bpmn2:userTask id="Activity_1qf73gq">
<bpmn2:incoming>Flow_1iadlmn</bpmn2:incoming>
<bpmn2:outgoing>Flow_1kz1x8a</bpmn2:outgoing>
</bpmn2:userTask>
<bpmn2:sequenceFlow id="Flow_1iadlmn" sourceRef="Event_0oz4pwh" targetRef="Activity_1qf73gq" />
<bpmn2:endEvent id="Event_0zlhfee">
<bpmn2:incoming>Flow_1kz1x8a</bpmn2:incoming>
</bpmn2:endEvent>
<bpmn2:sequenceFlow id="Flow_1kz1x8a" sourceRef="Activity_1qf73gq" targetRef="Event_0zlhfee" />
</bpmn2:process>
<bpmndi:BPMNDiagram id="BPMNDiagram_1">
<bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="Process_1">
<bpmndi:BPMNShape id="Event_0oz4pwh_di" bpmnElement="Event_0oz4pwh">
<dc:Bounds x="675" y="75" width="90" height="32" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="Activity_1qf73gq_di" bpmnElement="Activity_1qf73gq">
<dc:Bounds x="620" y="227" width="200" height="88" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="Event_0zlhfee_di" bpmnElement="Event_0zlhfee">
<dc:Bounds x="675" y="435" width="90" height="32" />
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="Flow_1iadlmn_di" bpmnElement="Flow_1iadlmn">
<di:waypoint x="720" y="107" />
<di:waypoint x="720" y="227" />
<bpmndi:BPMNLabel>
<dc:Bounds x="706" y="181" width="28" height="28" />
</bpmndi:BPMNLabel>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="Flow_1kz1x8a_di" bpmnElement="Flow_1kz1x8a">
<di:waypoint x="720" y="315" />
<di:waypoint x="720" y="435" />
<bpmndi:BPMNLabel>
<dc:Bounds x="706" y="361" width="28" height="28" />
</bpmndi:BPMNLabel>
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</bpmn2:definitions>"""
return urllib.parse.quote(xml)
@staticmethod
def build_simple_flow_nodes(
form_id: str,
form_name: str = "",
approver_name: str = "部门审批",
approver_user_ids: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""构建简单流程的 flowNodes 配置
参考: FlowProcess/src/helper/config.ts 中的 defaultGlobalForm/defaultStartForm/defaultApproverForm/defaultEndForm
Args:
form_id: 关联的可视化开发表单 ID
form_name: 表单名称
approver_name: 审批节点名称
approver_user_ids: 审批人用户 ID 列表
Returns:
flowNodes 字典
"""
approvers = [
{"id": uid, "type": "user"}
for uid in (approver_user_ids or [])
]
return {
"global": {
"type": "global",
"nodeId": "global",
"allFormMap": {},
"allDecisionMap": {},
"formId": form_id,
"titleType": 0,
"defaultContent": "{发起用户名}的{流程名称}",
"titleContent": "",
"hasSign": False,
"hasRevoke": False,
"hasComment": True,
"hasCommentDeletedTips": True,
"hasSignFor": False,
"hasAloneConfigureForms": False,
"hasContinueAfterReject": False,
"hasInitiatorPressOverdueNode": True,
"autoSubmitConfig": {
"adjacentNodeApproverRepeated": False,
"ApproverHasApproval": False,
"initiatorApproverRepeated": False,
},
"recallRule": 1,
"errorRule": 1,
"errorRuleUser": [],
"fileConfig": {"on": False, "permissionType": 1, "path": "", "templateId": ""},
"globalParameterList": [],
"publicParameterList": [],
"approvalFieldList": [],
"isShowConditions": True,
"showNameType": 0,
"connectList": ["Flow_1iadlmn", "Flow_1kz1x8a"],
},
"Event_0oz4pwh": {
"type": "start",
"nodeId": "Event_0oz4pwh",
"nodeName": "流程发起",
"formId": form_id,
"formName": form_name,
"formOperates": [],
"divideRule": "inclusion",
"printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"},
"timeLimitConfig": {"on": 0, "nodeLimit": 0, "duringDeal": 24},
"noticeConfig": {"on": 0, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5},
"overTimeConfig": {"on": 0, "firstOver": 0, "overTimeDuring": 2, "overNotice": True, "overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False, "overEventTime": 5},
"waitMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"endMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"commentMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"approveMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"rejectMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"backMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"copyMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"overTimeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"noticeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"initFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"endFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"flowRecallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"freeNode": False,
},
"Activity_1qf73gq": {
"type": "approver",
"nodeId": "Activity_1qf73gq",
"nodeName": approver_name,
"formId": form_id,
"formName": form_name,
"formOperates": [],
"assignList": [],
"assigneeType": 6,
"approverType": 1,
"managerApproverType": 1,
"managerLevel": 1,
"formFieldType": 1,
"formField": "",
"approverNodeId": "",
"prevNodeList": [],
"approvers": approvers,
"approversSortList": [],
"extraRule": 1,
"counterSign": 0,
"counterSignConfig": {
"auditType": 1, "auditRatio": 100, "auditNum": 1,
"rejectType": 0, "rejectRatio": 10, "rejectNum": 1,
"calculateType": 1,
},
"circulateUser": [],
"extraCopyRule": 1,
"isCustomCopy": False,
"isInitiatorCopy": False,
"isFormFieldCopy": False,
"copyFormFieldType": 1,
"copyFormField": "",
"hasOpinion": True,
"opinionRequired": False,
"hasSign": False,
"hasFile": False,
"hasApprovalField": False,
"approvalField": [],
"hasAuditBtn": True,
"auditBtnText": "同意",
"hasRejectBtn": True,
"rejectBtnText": "拒绝",
"hasBackBtn": False,
"backBtnText": "退回",
"hasFreeApproverBtn": False,
"freeApproverBtnText": "加签",
"hasReduceApproverBtn": False,
"reduceApproverBtnText": "减签",
"hasTransferBtn": False,
"transferBtnText": "转审",
"hasAssistBtn": False,
"assistBtnText": "协办",
"hasSaveAuditBtn": False,
"saveAuditBtnText": "暂存",
"backType": 1,
"backNodeCode": 0,
"customBtns": [],
"auxiliaryInfo": [],
"printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"},
"parameterList": [],
"hasAutoApprover": False,
"autoAuditRule": {"conditions": [], "matchLogic": "and"},
"autoRejectRule": {"conditions": [], "matchLogic": "and"},
"divideRule": "inclusion",
"interfaceConfig": {"interfaceId": "", "interfaceName": "", "templateJson": []},
"approveMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"rejectMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"backMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"copyMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"overTimeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"noticeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"content": "",
"timeLimitConfig": {"on": 2, "nodeLimit": 0, "duringDeal": 24, "formField": ""},
"overTimeConfig": {
"on": 2, "firstOver": 0, "overTimeDuring": 2, "overNotice": True,
"overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False,
"overEventTime": 5, "overAutoTransfer": False, "overAutoTransferTime": 2,
"overTimeType": 6, "interfaceId": "", "interfaceName": "", "templateJson": [],
"reApprovers": "", "overTimeExtraRule": 3,
},
"noticeConfig": {"on": 2, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5},
"approveFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"rejectFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"backFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"recallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"overTimeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"noticeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"isCandidates": False,
"approversConfig": {"start": 1, "end": 1, "level": 2, "originLevel": 1},
"approvalNumber": 1,
"oneSelfEndApproval": True,
"freeNode": False,
},
"Event_0zlhfee": {
"type": "end",
"nodeId": "Event_0zlhfee",
"nodeName": "结束节点",
"endParameterList": [],
},
}
def create_simple_flow(
self,
full_name: str,
en_code: str,
form_id: str,
approver_user_ids: List[str],
form_name: str = "",
flow_type: int = 1,
description: str = "",
icon: str = "icon-ym icon-ym-flow",
release_immediately: bool = True,
) -> Dict[str, str]:
"""一键创建简单流程模板并保存设计
整合 create_template + get_version_list + save_flow 三个步骤。
Args:
full_name: 流程名称
en_code: 流程编码
form_id: 关联的可视化开发表单 ID
approver_user_ids: 审批人用户 ID 列表
form_name: 表单名称(显示用)
flow_type: 流程类型 0=标准 1=简单 2=任务 3=自由 4=决策
description: 流程说明
icon: 流程图标
release_immediately: 是否立即发布(type=1 in saveFlow)
Returns:
dict: {
"template_id": 模板 ID,
"version_id": 版本 ID,
}
Raises:
RuntimeError: 任一步骤失败
"""
# 1. 创建模板(必须包含 flowXml/flowNodes/flowConfig,
# 否则后端 flowUtil.create() 解析 flowNodes 时 NPE,
# 导致 templateJson 条目未创建,后续 save_flow 报 "数据不存在")
flow_xml = self.build_simple_flow_xml()
flow_nodes = self.build_simple_flow_nodes(form_id, form_name, approver_user_ids=approver_user_ids)
flow_config = json.dumps({"visibleType": 1}, ensure_ascii=False)
resp = self.create_template({
"fullName": full_name,
"enCode": en_code,
"type": flow_type,
"category": "",
"icon": icon,
"iconBackground": "#008cff",
"showType": 0,
"sortCode": 0,
"description": description,
"flowXml": flow_xml,
"flowNodes": flow_nodes,
"flowConfig": flow_config,
})
if not resp.success:
raise RuntimeError(f"创建流程模板失败: {resp.msg}")
template_id = resp.id
# 2. 获取版本 ID
resp = self.get_version_list(template_id)
if not resp.success or not resp.data:
raise RuntimeError(f"获取版本列表失败: {resp.msg}")
version_id = resp.data[0]["id"]
# 3. 保存流程设计(复用已构建的 flowXml/flowNodes/flowConfig)
resp = self.save_flow({
"id": template_id,
"flowId": version_id,
"flowXml": flow_xml,
"flowNodes": flow_nodes,
"flowConfig": flow_config,
"type": 1 if release_immediately else 0,
})
if not resp.success:
raise RuntimeError(f"保存流程设计失败: {resp.msg}")
return {
"template_id": template_id,
"version_id": version_id,
}
def launch_task(self, flow_version_id: str, form_data: dict,
urgent: int = 1, draft: bool = False) -> APIResponse:
"""快捷发起流程
Args:
flow_version_id: 流程版本 ID(通过 get_version_list 获取)
form_data: 表单数据(dict 直接传给后端,后端 FlowHandleModel.formData 为 Map<String, Object>)
urgent: 紧急程度 1=普通
draft: 是否暂存(False=直接提交)
Returns:
APIResponse: 包含任务 ID
"""
data = {
"flowId": flow_version_id,
"status": 0 if draft else 1,
"flowUrgent": urgent,
"isFlow": 1, # 使用整数 1 而非布尔值 True,避免 Java 反序列化失败
"formData": form_data,
}
return self.create(data)
def approve(self, operator_id: str, opinion: str = "同意") -> APIResponse:
"""快捷审批通过
Args:
operator_id: 待审批操作 ID(从 get_before_list 获取的 taskOperatorId)
opinion: 审批意见
Returns:
APIResponse
"""
return self.audit(operator_id, {
"status": 1, # 1=同意
"handleOpinion": opinion,
"sign": "",
})
def reject(self, operator_id: str, opinion: str = "不同意") -> APIResponse:
"""快捷审批拒绝
Args:
operator_id: 待审批操作 ID
opinion: 审批意见
Returns:
APIResponse
"""
return self.audit(operator_id, {
"status": 2, # 2=拒绝
"handleOpinion": opinion,
"sign": "",
})
def get_pending_tasks(self, page: int = 1, page_size: int = 20) -> List[dict]:
"""快捷获取待审批列表
Args:
page: 页码
page_size: 每页数量
Returns:
任务列表
"""
resp = self.get_before_list("1", {
"currentPage": page,
"pageSize": page_size,
})
if not resp.success:
return []
return resp.data.get("list", [])
# ==================== 标准流程 (type=0) ====================
@staticmethod
def build_standard_flow_xml() -> str:
"""获取标准流程默认 BPMN XML
标准流程只有一个空的 StartEvent,用户需要在流程设计器中自行添加节点和连线。
不需要 URL 编码(后端直接解析 XML 字符串)。
Returns:
BPMN XML 字符串
"""
return """<?xml version="1.0" encoding="UTF-8"?>
<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" id="sample-diagram" targetNamespace="http://www.flowable.org/processdef" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd">
<bpmn2:process id="Process_1" isExecutable="true">
<bpmn2:startEvent id="Event_04q7xii" />
</bpmn2:process>
<bpmndi:BPMNDiagram id="BPMNDiagram_1">
<bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="Process_1">
<bpmndi:BPMNShape id="Event_04q7xii_di" bpmnElement="Event_04q7xii">
<dc:Bounds x="145" y="304" width="90" height="32" />
</bpmndi:BPMNShape>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</bpmn2:definitions>"""
@staticmethod
def build_standard_flow_nodes(
form_id: str,
form_name: str = "",
) -> Dict[str, Any]:
"""构建标准流程的 flowNodes 配置
标准流程只有一个发起节点,用户需要在流程设计器中自行添加审批节点。
Args:
form_id: 关联的可视化开发表单 ID
form_name: 表单名称
Returns:
flowNodes 字典
"""
return {
"global": {
"type": "global",
"nodeId": "global",
"allFormMap": {},
"allDecisionMap": {},
"formId": form_id,
"titleType": 0,
"defaultContent": "{发起用户名}的{流程名称}",
"titleContent": "",
"hasSign": False,
"hasRevoke": False,
"hasComment": True,
"hasCommentDeletedTips": True,
"hasSignFor": False,
"hasAloneConfigureForms": False,
"hasContinueAfterReject": False,
"hasInitiatorPressOverdueNode": True,
"autoSubmitConfig": {
"adjacentNodeApproverRepeated": False,
"ApproverHasApproval": False,
"initiatorApproverRepeated": False,
},
"recallRule": 1,
"errorRule": 1,
"errorRuleUser": [],
"fileConfig": {"on": False, "permissionType": 1, "path": "", "templateId": ""},
"globalParameterList": [],
"publicParameterList": [],
"approvalFieldList": [],
"isShowConditions": True,
"showNameType": 0,
"connectList": [],
},
"Event_04q7xii": {
"type": "start",
"nodeId": "Event_04q7xii",
"nodeName": "流程发起",
"formId": form_id,
"formName": form_name,
"formOperates": [],
"divideRule": "inclusion",
"printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"},
"timeLimitConfig": {"on": 0, "nodeLimit": 0, "duringDeal": 24},
"noticeConfig": {"on": 0, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5},
"overTimeConfig": {"on": 0, "firstOver": 0, "overTimeDuring": 2, "overNotice": True, "overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False, "overEventTime": 5},
"waitMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"endMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"commentMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"approveMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"rejectMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"backMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"copyMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"overTimeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"noticeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"initFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"endFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"flowRecallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"freeNode": False,
},
}
def create_standard_flow(
self,
full_name: str,
en_code: str,
form_id: str,
form_name: str = "",
description: str = "",
icon: str = "icon-ym icon-ym-flow",
) -> Dict[str, str]:
"""创建标准流程模板
标准流程只有一个发起节点,用户需要在流程设计器中自行添加审批节点和连线。
Args:
full_name: 流程名称
en_code: 流程编码
form_id: 关联的可视化开发表单 ID
form_name: 表单名称(显示用)
description: 流程说明
icon: 流程图标
Returns:
dict: {
"template_id": 模板 ID,
"version_id": 版本 ID,
}
"""
flow_xml = self.build_standard_flow_xml()
flow_nodes = self.build_standard_flow_nodes(form_id, form_name)
flow_config = json.dumps({"visibleType": 1}, ensure_ascii=False)
resp = self.create_template({
"fullName": full_name,
"enCode": en_code,
"type": 0, # 标准流程
"category": "",
"icon": icon,
"iconBackground": "#008cff",
"showType": 0,
"sortCode": 0,
"description": description,
"flowXml": flow_xml,
"flowNodes": flow_nodes,
"flowConfig": flow_config,
})
if not resp.success:
raise RuntimeError(f"创建标准流程模板失败: {resp.msg}")
template_id = resp.id
resp = self.get_version_list(template_id)
if not resp.success or not resp.data:
raise RuntimeError(f"获取版本列表失败: {resp.msg}")
version_id = resp.data[0]["id"]
resp = self.save_flow({
"id": template_id,
"flowId": version_id,
"flowXml": flow_xml,
"flowNodes": flow_nodes,
"flowConfig": flow_config,
"type": 0,
})
if not resp.success:
raise RuntimeError(f"保存流程设计失败: {resp.msg}")
return {
"template_id": template_id,
"version_id": version_id,
}
# ==================== 任务流程 (type=2) ====================
@staticmethod
def build_task_flow_xml() -> str:
"""获取任务流程默认 BPMN XML
任务流程结构: StartEvent -> UserTask -> EndEvent(与简单流程相同,但节点类型不同)
需要 URL 编码。
Returns:
URL 编码后的 BPMN XML 字符串
"""
xml = """<?xml version="1.0" encoding="UTF-8"?>
<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="sample-diagram" targetNamespace="http://www.flowable.org/processdef" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd">
<bpmn2:process id="Process_1" name="" isExecutable="true">
<bpmn2:startEvent id="Event_0oz4pwh" >
<bpmn2:outgoing>Flow_1iadlmn</bpmn2:outgoing>
</bpmn2:startEvent>
<bpmn2:userTask id="Activity_1qf73gq">
<bpmn2:incoming>Flow_1iadlmn</bpmn2:incoming>
<bpmn2:outgoing>Flow_1kz1x8a</bpmn2:outgoing>
</bpmn2:userTask>
<bpmn2:sequenceFlow id="Flow_1iadlmn" sourceRef="Event_0oz4pwh" targetRef="Activity_1qf73gq" />
<bpmn2:endEvent id="Event_0zlhfee">
<bpmn2:incoming>Flow_1kz1x8a</bpmn2:incoming>
</bpmn2:endEvent>
<bpmn2:sequenceFlow id="Flow_1kz1x8a" sourceRef="Activity_1qf73gq" targetRef="Event_0zlhfee" />
</bpmn2:process>
<bpmndi:BPMNDiagram id="BPMNDiagram_1">
<bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="Process_1">
<bpmndi:BPMNShape id="Event_0oz4pwh_di" bpmnElement="Event_0oz4pwh">
<dc:Bounds x="675" y="75" width="90" height="32" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="Activity_1qf73gq_di" bpmnElement="Activity_1qf73gq">
<dc:Bounds x="620" y="227" width="200" height="88" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="Event_0zlhfee_di" bpmnElement="Event_0zlhfee">
<dc:Bounds x="675" y="435" width="90" height="32" />
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="Flow_1iadlmn_di" bpmnElement="Flow_1iadlmn">
<di:waypoint x="720" y="107" />
<di:waypoint x="720" y="227" />
<bpmndi:BPMNLabel>
<dc:Bounds x="706" y="181" width="28" height="28" />
</bpmndi:BPMNLabel>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="Flow_1kz1x8a_di" bpmnElement="Flow_1kz1x8a">
<di:waypoint x="720" y="315" />
<di:waypoint x="720" y="435" />
<bpmndi:BPMNLabel>
<dc:Bounds x="706" y="361" width="28" height="28" />
</bpmndi:BPMNLabel>
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</bpmn2:definitions>"""
return urllib.parse.quote(xml)
@staticmethod
def build_task_flow_nodes(
form_id: str,
form_name: str = "",
handler_name: str = "任务处理",
handler_user_ids: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""构建任务流程的 flowNodes 配置
任务流程与简单流程类似,但节点类型为 'processing'(办理节点)而非 'approver'(审批节点)。
Args:
form_id: 关联的可视化开发表单 ID
form_name: 表单名称
handler_name: 任务节点名称
handler_user_ids: 任务处理人用户 ID 列表
Returns:
flowNodes 字典
"""
handlers = [
{"id": uid, "type": "user"}
for uid in (handler_user_ids or [])
]
return {
"global": {
"type": "global",
"nodeId": "global",
"allFormMap": {},
"allDecisionMap": {},
"formId": form_id,
"titleType": 0,
"defaultContent": "{发起用户名}的{流程名称}",
"titleContent": "",
"hasSign": False,
"hasRevoke": False,
"hasComment": True,
"hasCommentDeletedTips": True,
"hasSignFor": False,
"hasAloneConfigureForms": False,
"hasContinueAfterReject": False,
"hasInitiatorPressOverdueNode": True,
"autoSubmitConfig": {
"adjacentNodeApproverRepeated": False,
"ApproverHasApproval": False,
"initiatorApproverRepeated": False,
},
"recallRule": 1,
"errorRule": 1,
"errorRuleUser": [],
"fileConfig": {"on": False, "permissionType": 1, "path": "", "templateId": ""},
"globalParameterList": [],
"publicParameterList": [],
"approvalFieldList": [],
"isShowConditions": True,
"showNameType": 0,
"connectList": ["Flow_1iadlmn", "Flow_1kz1x8a"],
},
"Event_0oz4pwh": {
"type": "start",
"nodeId": "Event_0oz4pwh",
"nodeName": "流程发起",
"formId": form_id,
"formName": form_name,
"formOperates": [],
"divideRule": "inclusion",
"printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"},
"timeLimitConfig": {"on": 0, "nodeLimit": 0, "duringDeal": 24},
"noticeConfig": {"on": 0, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5},
"overTimeConfig": {"on": 0, "firstOver": 0, "overTimeDuring": 2, "overNotice": True, "overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False, "overEventTime": 5},
"waitMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"endMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"commentMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"approveMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"rejectMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"backMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"copyMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"overTimeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"noticeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"initFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"endFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"flowRecallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"freeNode": False,
},
"Activity_1qf73gq": {
"type": "processing",
"nodeId": "Activity_1qf73gq",
"nodeName": handler_name,
"formId": form_id,
"formName": form_name,
"formOperates": [],
"assignList": [],
"assigneeType": 6,
"approverType": 1,
"managerApproverType": 1,
"managerLevel": 1,
"formFieldType": 1,
"formField": "",
"approverNodeId": "",
"prevNodeList": [],
"approvers": handlers,
"approversSortList": [],
"extraRule": 1,
"counterSign": 0,
"counterSignConfig": {
"auditType": 1, "auditRatio": 100, "auditNum": 1,
"rejectType": 0, "rejectRatio": 10, "rejectNum": 1,
"calculateType": 1,
},
"circulateUser": [],
"extraCopyRule": 1,
"isCustomCopy": False,
"isInitiatorCopy": False,
"isFormFieldCopy": False,
"copyFormFieldType": 1,
"copyFormField": "",
"hasOpinion": True,
"opinionRequired": False,
"hasSign": False,
"hasFile": False,
"hasApprovalField": False,
"approvalField": [],
"hasAuditBtn": True,
"auditBtnText": "确认办理",
"hasBackBtn": False,
"backBtnText": "退回",
"hasTransferBtn": False,
"transferBtnText": "转办",
"hasSaveAuditBtn": False,
"saveAuditBtnText": "暂存",
"backType": 1,
"backNodeCode": 0,
"customBtns": [],
"auxiliaryInfo": [],
"printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"},
"parameterList": [],
"hasAutoApprover": False,
"autoAuditRule": {"conditions": [], "matchLogic": "and"},
"autoRejectRule": {"conditions": [], "matchLogic": "and"},
"divideRule": "inclusion",
"interfaceConfig": {"interfaceId": "", "interfaceName": "", "templateJson": []},
"backMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"copyMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"overTimeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"noticeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"content": "",
"timeLimitConfig": {"on": 2, "nodeLimit": 0, "duringDeal": 24, "formField": ""},
"overTimeConfig": {
"on": 2, "firstOver": 0, "overTimeDuring": 2, "overNotice": True,
"overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False,
"overEventTime": 5, "overAutoTransfer": False, "overAutoTransferTime": 2,
"overTimeType": 6, "interfaceId": "", "interfaceName": "", "templateJson": [],
"reApprovers": "", "overTimeExtraRule": 3,
},
"noticeConfig": {"on": 2, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5},
"overTimeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"noticeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"isCandidates": False,
"approversConfig": {"start": 1, "end": 1, "level": 2, "originLevel": 1},
"approvalNumber": 1,
"oneSelfEndApproval": True,
"freeNode": False,
},
"Event_0zlhfee": {
"type": "end",
"nodeId": "Event_0zlhfee",
"nodeName": "结束节点",
"endParameterList": [],
},
}
def create_task_flow(
self,
full_name: str,
en_code: str,
form_id: str,
handler_user_ids: List[str],
form_name: str = "",
description: str = "",
icon: str = "icon-ym icon-ym-flow",
) -> Dict[str, str]:
"""创建任务流程模板
任务流程与简单流程类似,但使用办理节点(processing)而非审批节点(approver)。
Args:
full_name: 流程名称
en_code: 流程编码
form_id: 关联的可视化开发表单 ID
handler_user_ids: 任务处理人用户 ID 列表
form_name: 表单名称
description: 流程说明
icon: 流程图标
Returns:
dict: {
"template_id": 模板 ID,
"version_id": 版本 ID,
}
"""
flow_xml = self.build_task_flow_xml()
flow_nodes = self.build_task_flow_nodes(form_id, form_name, handler_user_ids=handler_user_ids)
flow_config = json.dumps({"visibleType": 1}, ensure_ascii=False)
resp = self.create_template({
"fullName": full_name,
"enCode": en_code,
"type": 2, # 任务流程
"category": "",
"icon": icon,
"iconBackground": "#008cff",
"showType": 0,
"sortCode": 0,
"description": description,
"flowXml": flow_xml,
"flowNodes": flow_nodes,
"flowConfig": flow_config,
})
if not resp.success:
raise RuntimeError(f"创建任务流程模板失败: {resp.msg}")
template_id = resp.id
resp = self.get_version_list(template_id)
if not resp.success or not resp.data:
raise RuntimeError(f"获取版本列表失败: {resp.msg}")
version_id = resp.data[0]["id"]
resp = self.save_flow({
"id": template_id,
"flowId": version_id,
"flowXml": flow_xml,
"flowNodes": flow_nodes,
"flowConfig": flow_config,
"type": 0,
})
if not resp.success:
raise RuntimeError(f"保存流程设计失败: {resp.msg}")
return {
"template_id": template_id,
"version_id": version_id,
}
# ==================== 自由流程 (type=3) ====================
@staticmethod
def build_free_flow_xml() -> str:
"""获取自由流程默认 BPMN XML
自由流程与简单流程结构相同(StartEvent -> UserTask -> EndEvent),
但节点 ID 不同,且布局为横向。
需要 URL 编码。
Returns:
URL 编码后的 BPMN XML 字符串
"""
xml = """<?xml version="1.0" encoding="UTF-8"?>
<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="sample-diagram" targetNamespace="http://www.flowable.org/processdef" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd">
<bpmn2:process id="Process_1" isExecutable="true">
<bpmn2:startEvent id="Event_04q7xii">
<bpmn2:outgoing>Flow_026otk8</bpmn2:outgoing>
</bpmn2:startEvent>
<bpmn2:userTask id="Activity_0x7jbm1">
<bpmn2:incoming>Flow_026otk8</bpmn2:incoming>
<bpmn2:outgoing>Flow_0hyov7e</bpmn2:outgoing>
</bpmn2:userTask>
<bpmn2:sequenceFlow id="Flow_026otk8" sourceRef="Event_04q7xii" targetRef="Activity_0x7jbm1">
</bpmn2:sequenceFlow>
<bpmn2:endEvent id="Event_06nxded">
<bpmn2:incoming>Flow_0hyov7e</bpmn2:incoming>
</bpmn2:endEvent>
<bpmn2:sequenceFlow id="Flow_0hyov7e" sourceRef="Activity_0x7jbm1" targetRef="Event_06nxded">
</bpmn2:sequenceFlow>
</bpmn2:process>
<bpmndi:BPMNDiagram id="BPMNDiagram_1">
<bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="Process_1">
<bpmndi:BPMNShape id="Event_04q7xii_di" bpmnElement="Event_04q7xii">
<dc:Bounds x="145" y="304" width="90" height="32" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="Activity_0x7jbm1_di" bpmnElement="Activity_0x7jbm1">
<dc:Bounds x="395" y="276" width="200" height="88" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="Event_06nxded_di" bpmnElement="Event_06nxded">
<dc:Bounds x="755" y="304" width="90" height="32" />
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="Flow_026otk8_di" bpmnElement="Flow_026otk8">
<di:waypoint x="235" y="320" />
<di:waypoint x="395" y="320" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="Flow_0hyov7e_di" bpmnElement="Flow_0hyov7e">
<di:waypoint x="595" y="320" />
<di:waypoint x="755" y="320" />
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</bpmn2:definitions>"""
return urllib.parse.quote(xml)
@staticmethod
def build_free_flow_nodes(
form_id: str,
form_name: str = "",
approver_name: str = "自由审批",
approver_user_ids: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""构建自由流程的 flowNodes 配置
自由流程使用自由节点(freeNode: true),允许自由选择后续审批人。
Args:
form_id: 关联的可视化开发表单 ID
form_name: 表单名称
approver_name: 审批节点名称
approver_user_ids: 审批人用户 ID 列表
Returns:
flowNodes 字典
"""
approvers = [
{"id": uid, "type": "user"}
for uid in (approver_user_ids or [])
]
return {
"global": {
"type": "global",
"nodeId": "global",
"allFormMap": {},
"allDecisionMap": {},
"formId": form_id,
"titleType": 0,
"defaultContent": "{发起用户名}的{流程名称}",
"titleContent": "",
"hasSign": False,
"hasRevoke": False,
"hasComment": True,
"hasCommentDeletedTips": True,
"hasSignFor": False,
"hasAloneConfigureForms": False,
"hasContinueAfterReject": False,
"hasInitiatorPressOverdueNode": True,
"autoSubmitConfig": {
"adjacentNodeApproverRepeated": False,
"ApproverHasApproval": False,
"initiatorApproverRepeated": False,
},
"recallRule": 1,
"errorRule": 1,
"errorRuleUser": [],
"fileConfig": {"on": False, "permissionType": 1, "path": "", "templateId": ""},
"globalParameterList": [],
"publicParameterList": [],
"approvalFieldList": [],
"isShowConditions": True,
"showNameType": 0,
"connectList": ["Flow_026otk8", "Flow_0hyov7e"],
},
"Event_04q7xii": {
"type": "start",
"nodeId": "Event_04q7xii",
"nodeName": "流程发起",
"formId": form_id,
"formName": form_name,
"formOperates": [],
"divideRule": "inclusion",
"printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"},
"timeLimitConfig": {"on": 0, "nodeLimit": 0, "duringDeal": 24},
"noticeConfig": {"on": 0, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5},
"overTimeConfig": {"on": 0, "firstOver": 0, "overTimeDuring": 2, "overNotice": True, "overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False, "overEventTime": 5},
"waitMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"endMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"commentMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"approveMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"rejectMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"backMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"copyMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"overTimeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"noticeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"initFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"endFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"flowRecallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"freeNode": False,
},
"Activity_0x7jbm1": {
"type": "free",
"nodeId": "Activity_0x7jbm1",
"nodeName": approver_name,
"approvalNumber": 10,
"oneSelfEndApproval": True,
"formId": form_id,
"formName": form_name,
"formOperates": [],
"assignList": [],
"assigneeType": 6,
"approverType": 1,
"managerApproverType": 1,
"managerLevel": 1,
"formFieldType": 1,
"formField": "",
"approverNodeId": "",
"prevNodeList": [],
"approvers": approvers,
"approversSortList": [],
"extraRule": 1,
"counterSign": 0,
"counterSignConfig": {
"auditType": 1, "auditRatio": 100, "auditNum": 1,
"rejectType": 0, "rejectRatio": 10, "rejectNum": 1,
"calculateType": 1,
},
"circulateUser": [],
"extraCopyRule": 1,
"isCustomCopy": False,
"isInitiatorCopy": False,
"isFormFieldCopy": False,
"copyFormFieldType": 1,
"copyFormField": "",
"hasOpinion": True,
"opinionRequired": False,
"hasSign": False,
"hasFile": False,
"hasApprovalField": False,
"approvalField": [],
"hasAuditBtn": True,
"auditBtnText": "同意",
"hasRejectBtn": True,
"rejectBtnText": "拒绝",
"hasBackBtn": False,
"backBtnText": "退回",
"hasFreeApproverBtn": True,
"freeApproverBtnText": "加签",
"hasReduceApproverBtn": False,
"reduceApproverBtnText": "减签",
"hasTransferBtn": False,
"transferBtnText": "转审",
"hasAssistBtn": False,
"assistBtnText": "协办",
"hasSaveAuditBtn": False,
"saveAuditBtnText": "暂存",
"backType": 1,
"backNodeCode": 0,
"customBtns": [],
"auxiliaryInfo": [],
"printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"},
"parameterList": [],
"hasAutoApprover": False,
"autoAuditRule": {"conditions": [], "matchLogic": "and"},
"autoRejectRule": {"conditions": [], "matchLogic": "and"},
"divideRule": "inclusion",
"interfaceConfig": {"interfaceId": "", "interfaceName": "", "templateJson": []},
"approveMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"rejectMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"backMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"copyMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"overTimeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"noticeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"content": "",
"timeLimitConfig": {"on": 2, "nodeLimit": 0, "duringDeal": 24, "formField": ""},
"overTimeConfig": {
"on": 2, "firstOver": 0, "overTimeDuring": 2, "overNotice": True,
"overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False,
"overEventTime": 5, "overAutoTransfer": False, "overAutoTransferTime": 2,
"overTimeType": 6, "interfaceId": "", "interfaceName": "", "templateJson": [],
"reApprovers": "", "overTimeExtraRule": 3,
},
"noticeConfig": {"on": 2, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5},
"approveFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"rejectFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"backFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"recallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"overTimeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"noticeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"isCandidates": False,
"approversConfig": {"start": 1, "end": 1, "level": 2, "originLevel": 1},
"approvalNumber": 10,
"oneSelfEndApproval": True,
"freeNode": True,
},
"Event_06nxded": {
"type": "end",
"nodeId": "Event_06nxded",
"nodeName": "结束节点",
"endParameterList": [],
},
}
def create_free_flow(
self,
full_name: str,
en_code: str,
form_id: str,
approver_user_ids: Optional[List[str]] = None,
form_name: str = "",
description: str = "",
icon: str = "icon-ym icon-ym-flow",
) -> Dict[str, str]:
"""创建自由流程模板
自由流程使用自由节点,允许在审批过程中动态添加审批人。
Args:
full_name: 流程名称
en_code: 流程编码
form_id: 关联的可视化开发表单 ID
approver_user_ids: 审批人用户 ID 列表(可选,初始审批人)
form_name: 表单名称
description: 流程说明
icon: 流程图标
Returns:
dict: {
"template_id": 模板 ID,
"version_id": 版本 ID,
}
"""
flow_xml = self.build_free_flow_xml()
flow_nodes = self.build_free_flow_nodes(form_id, form_name, approver_user_ids=approver_user_ids)
flow_config = json.dumps({"visibleType": 1}, ensure_ascii=False)
resp = self.create_template({
"fullName": full_name,
"enCode": en_code,
"type": 3, # 自由流程
"category": "",
"icon": icon,
"iconBackground": "#008cff",
"showType": 0,
"sortCode": 0,
"description": description,
"flowXml": flow_xml,
"flowNodes": flow_nodes,
"flowConfig": flow_config,
})
if not resp.success:
raise RuntimeError(f"创建自由流程模板失败: {resp.msg}")
template_id = resp.id
resp = self.get_version_list(template_id)
if not resp.success or not resp.data:
raise RuntimeError(f"获取版本列表失败: {resp.msg}")
version_id = resp.data[0]["id"]
resp = self.save_flow({
"id": template_id,
"flowId": version_id,
"flowXml": flow_xml,
"flowNodes": flow_nodes,
"flowConfig": flow_config,
"type": 0,
})
if not resp.success:
raise RuntimeError(f"保存流程设计失败: {resp.msg}")
return {
"template_id": template_id,
"version_id": version_id,
}
# ==================== 决策流程 (type=4) ====================
@staticmethod
def build_decision_flow_xml() -> str:
"""获取决策流程默认 BPMN XML
决策流程结构: StartEvent -> ExclusiveGateway -> UserTask (多个) -> EndEvent
需要 URL 编码。
Returns:
URL 编码后的 BPMN XML 字符串
"""
xml = """<?xml version="1.0" encoding="UTF-8"?>
<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="sample-diagram" targetNamespace="http://www.flowable.org/processdef" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd">
<bpmn2:process id="Process_1" name="" isExecutable="true">
<bpmn2:startEvent id="Event_1" >
<bpmn2:outgoing>Flow_1</bpmn2:outgoing>
</bpmn2:startEvent>
<bpmn2:exclusiveGateway id="Gateway_1" >
<bpmn2:incoming>Flow_1</bpmn2:incoming>
<bpmn2:outgoing>Flow_2a</bpmn2:outgoing>
<bpmn2:outgoing>Flow_2b</bpmn2:outgoing>
</bpmn2:exclusiveGateway>
<bpmn2:sequenceFlow id="Flow_1" sourceRef="Event_1" targetRef="Gateway_1" />
<bpmn2:sequenceFlow id="Flow_2a" sourceRef="Gateway_1" targetRef="Activity_1">
<bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression">${condition_a}</bpmn2:conditionExpression>
</bpmn2:sequenceFlow>
<bpmn2:sequenceFlow id="Flow_2b" sourceRef="Gateway_1" targetRef="Activity_2">
<bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression">${condition_b}</bpmn2:conditionExpression>
</bpmn2:sequenceFlow>
<bpmn2:userTask id="Activity_1">
<bpmn2:incoming>Flow_2a</bpmn2:incoming>
<bpmn2:outgoing>Flow_3</bpmn2:outgoing>
</bpmn2:userTask>
<bpmn2:userTask id="Activity_2">
<bpmn2:incoming>Flow_2b</bpmn2:incoming>
<bpmn2:outgoing>Flow_4</bpmn2:outgoing>
</bpmn2:userTask>
<bpmn2:sequenceFlow id="Flow_3" sourceRef="Activity_1" targetRef="Event_end" />
<bpmn2:sequenceFlow id="Flow_4" sourceRef="Activity_2" targetRef="Event_end" />
<bpmn2:endEvent id="Event_end">
<bpmn2:incoming>Flow_3</bpmn2:incoming>
<bpmn2:incoming>Flow_4</bpmn2:incoming>
</bpmn2:endEvent>
</bpmn2:process>
<bpmndi:BPMNDiagram id="BPMNDiagram_1">
<bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="Process_1">
<bpmndi:BPMNShape id="Event_1_di" bpmnElement="Event_1">
<dc:Bounds x="180" y="200" width="90" height="32" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="Gateway_1_di" bpmnElement="Gateway_1">
<dc:Bounds x="355" y="195" width="50" height="50" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="Activity_1_di" bpmnElement="Activity_1">
<dc:Bounds x="520" y="100" width="200" height="88" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="Activity_2_di" bpmnElement="Activity_2">
<dc:Bounds x="520" y="300" width="200" height="88" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="Event_end_di" bpmnElement="Event_end">
<dc:Bounds x="850" y="200" width="90" height="32" />
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="Flow_1_di" bpmnElement="Flow_1">
<di:waypoint x="270" y="216" />
<di:waypoint x="355" y="220" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="Flow_2a_di" bpmnElement="Flow_2a">
<di:waypoint x="380" y="195" />
<di:waypoint x="380" y="144" />
<di:waypoint x="520" y="144" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="Flow_2b_di" bpmnElement="Flow_2b">
<di:waypoint x="380" y="245" />
<di:waypoint x="380" y="344" />
<di:waypoint x="520" y="344" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="Flow_3_di" bpmnElement="Flow_3">
<di:waypoint x="720" y="144" />
<di:waypoint x="850" y="144" />
<di:waypoint x="895" y="200" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="Flow_4_di" bpmnElement="Flow_4">
<di:waypoint x="720" y="344" />
<di:waypoint x="850" y="344" />
<di:waypoint x="895" y="232" />
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</bpmn2:definitions>"""
return urllib.parse.quote(xml)
@staticmethod
def build_decision_flow_nodes(
form_id: str,
form_name: str = "",
branch_a_name: str = "分支A审批",
branch_b_name: str = "分支B审批",
branch_a_user_ids: Optional[List[str]] = None,
branch_b_user_ids: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""构建决策流程的 flowNodes 配置
决策流程使用排他网关,根据条件选择不同的审批分支。
Args:
form_id: 关联的可视化开发表单 ID
form_name: 表单名称
branch_a_name: 分支A节点名称
branch_b_name: 分支B节点名称
branch_a_user_ids: 分支A审批人用户 ID 列表
branch_b_user_ids: 分支B审批人用户 ID 列表
Returns:
flowNodes 字典
"""
approvers_a = [{"id": uid, "type": "user"} for uid in (branch_a_user_ids or [])]
approvers_b = [{"id": uid, "type": "user"} for uid in (branch_b_user_ids or [])]
return {
"global": {
"type": "global",
"nodeId": "global",
"allFormMap": {},
"allDecisionMap": {},
"formId": form_id,
"titleType": 0,
"defaultContent": "{发起用户名}的{流程名称}",
"titleContent": "",
"hasSign": False,
"hasRevoke": False,
"hasComment": True,
"hasCommentDeletedTips": True,
"hasSignFor": False,
"hasAloneConfigureForms": False,
"hasContinueAfterReject": False,
"hasInitiatorPressOverdueNode": True,
"autoSubmitConfig": {
"adjacentNodeApproverRepeated": False,
"ApproverHasApproval": False,
"initiatorApproverRepeated": False,
},
"recallRule": 1,
"errorRule": 1,
"errorRuleUser": [],
"fileConfig": {"on": False, "permissionType": 1, "path": "", "templateId": ""},
"globalParameterList": [],
"publicParameterList": [],
"approvalFieldList": [],
"isShowConditions": True,
"showNameType": 1,
"connectList": ["Flow_1", "Flow_2a", "Flow_2b", "Flow_3", "Flow_4"],
},
"Event_1": {
"type": "start",
"nodeId": "Event_1",
"nodeName": "流程发起",
"formId": form_id,
"formName": form_name,
"formOperates": [],
"divideRule": "inclusion",
"printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"},
"timeLimitConfig": {"on": 0, "nodeLimit": 0, "duringDeal": 24},
"noticeConfig": {"on": 0, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5},
"overTimeConfig": {"on": 0, "firstOver": 0, "overTimeDuring": 2, "overNotice": True, "overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False, "overEventTime": 5},
"waitMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"endMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"commentMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"approveMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"rejectMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"backMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"copyMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"overTimeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"noticeMsgConfig": {"on": 3, "msgId": "", "msgName": "", "templateJson": []},
"initFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"endFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"flowRecallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"freeNode": False,
},
"Gateway_1": {
"type": "gateway",
"nodeId": "Gateway_1",
"nodeName": "条件路由",
"divideRule": "exclusive",
"gatewayType": "exclusive",
},
"Flow_2a": {
"type": "connect",
"nodeId": "Flow_2a",
"nodeName": "条件A",
"conditions": [
{"fieldName": "condition_a", "symbol": "==", "fieldValue": True}
],
"matchLogic": "and",
"isDefault": False,
},
"Flow_2b": {
"type": "connect",
"nodeId": "Flow_2b",
"nodeName": "条件B",
"conditions": [
{"fieldName": "condition_b", "symbol": "==", "fieldValue": True}
],
"matchLogic": "and",
"isDefault": True,
},
"Activity_1": {
"type": "approver",
"nodeId": "Activity_1",
"nodeName": branch_a_name,
"formId": form_id,
"formName": form_name,
"formOperates": [],
"assignList": [],
"assigneeType": 6,
"approverType": 1,
"managerApproverType": 1,
"managerLevel": 1,
"formFieldType": 1,
"formField": "",
"approverNodeId": "",
"prevNodeList": [],
"approvers": approvers_a,
"approversSortList": [],
"extraRule": 1,
"counterSign": 0,
"counterSignConfig": {
"auditType": 1, "auditRatio": 100, "auditNum": 1,
"rejectType": 0, "rejectRatio": 10, "rejectNum": 1,
"calculateType": 1,
},
"circulateUser": [],
"extraCopyRule": 1,
"isCustomCopy": False,
"isInitiatorCopy": False,
"isFormFieldCopy": False,
"copyFormFieldType": 1,
"copyFormField": "",
"hasOpinion": True,
"opinionRequired": False,
"hasSign": False,
"hasFile": False,
"hasApprovalField": False,
"approvalField": [],
"hasAuditBtn": True,
"auditBtnText": "同意",
"hasRejectBtn": True,
"rejectBtnText": "拒绝",
"hasBackBtn": False,
"backBtnText": "退回",
"hasFreeApproverBtn": False,
"freeApproverBtnText": "加签",
"hasReduceApproverBtn": False,
"reduceApproverBtnText": "减签",
"hasTransferBtn": False,
"transferBtnText": "转审",
"hasAssistBtn": False,
"assistBtnText": "协办",
"hasSaveAuditBtn": False,
"saveAuditBtnText": "暂存",
"backType": 1,
"backNodeCode": 0,
"customBtns": [],
"auxiliaryInfo": [],
"printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"},
"parameterList": [],
"hasAutoApprover": False,
"autoAuditRule": {"conditions": [], "matchLogic": "and"},
"autoRejectRule": {"conditions": [], "matchLogic": "and"},
"divideRule": "exclusive",
"interfaceConfig": {"interfaceId": "", "interfaceName": "", "templateJson": []},
"approveMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"rejectMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"backMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"copyMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"overTimeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"noticeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"content": "",
"timeLimitConfig": {"on": 2, "nodeLimit": 0, "duringDeal": 24, "formField": ""},
"overTimeConfig": {
"on": 2, "firstOver": 0, "overTimeDuring": 2, "overNotice": True,
"overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False,
"overEventTime": 5, "overAutoTransfer": False, "overAutoTransferTime": 2,
"overTimeType": 6, "interfaceId": "", "interfaceName": "", "templateJson": [],
"reApprovers": "", "overTimeExtraRule": 3,
},
"noticeConfig": {"on": 2, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5},
"approveFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"rejectFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"backFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"recallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"overTimeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"noticeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"isCandidates": False,
"approversConfig": {"start": 1, "end": 1, "level": 2, "originLevel": 1},
"approvalNumber": 1,
"oneSelfEndApproval": True,
"freeNode": False,
},
"Activity_2": {
"type": "approver",
"nodeId": "Activity_2",
"nodeName": branch_b_name,
"formId": form_id,
"formName": form_name,
"formOperates": [],
"assignList": [],
"assigneeType": 6,
"approverType": 1,
"managerApproverType": 1,
"managerLevel": 1,
"formFieldType": 1,
"formField": "",
"approverNodeId": "",
"prevNodeList": [],
"approvers": approvers_b,
"approversSortList": [],
"extraRule": 1,
"counterSign": 0,
"counterSignConfig": {
"auditType": 1, "auditRatio": 100, "auditNum": 1,
"rejectType": 0, "rejectRatio": 10, "rejectNum": 1,
"calculateType": 1,
},
"circulateUser": [],
"extraCopyRule": 1,
"isCustomCopy": False,
"isInitiatorCopy": False,
"isFormFieldCopy": False,
"copyFormFieldType": 1,
"copyFormField": "",
"hasOpinion": True,
"opinionRequired": False,
"hasSign": False,
"hasFile": False,
"hasApprovalField": False,
"approvalField": [],
"hasAuditBtn": True,
"auditBtnText": "同意",
"hasRejectBtn": True,
"rejectBtnText": "拒绝",
"hasBackBtn": False,
"backBtnText": "退回",
"hasFreeApproverBtn": False,
"freeApproverBtnText": "加签",
"hasReduceApproverBtn": False,
"reduceApproverBtnText": "减签",
"hasTransferBtn": False,
"transferBtnText": "转审",
"hasAssistBtn": False,
"assistBtnText": "协办",
"hasSaveAuditBtn": False,
"saveAuditBtnText": "暂存",
"backType": 1,
"backNodeCode": 0,
"customBtns": [],
"auxiliaryInfo": [],
"printConfig": {"on": False, "printIds": [], "conditionType": 1, "conditions": [], "matchLogic": "and"},
"parameterList": [],
"hasAutoApprover": False,
"autoAuditRule": {"conditions": [], "matchLogic": "and"},
"autoRejectRule": {"conditions": [], "matchLogic": "and"},
"divideRule": "exclusive",
"interfaceConfig": {"interfaceId": "", "interfaceName": "", "templateJson": []},
"approveMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"rejectMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"backMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"copyMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"overTimeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"noticeMsgConfig": {"on": 2, "msgId": "", "msgName": "", "templateJson": []},
"content": "",
"timeLimitConfig": {"on": 2, "nodeLimit": 0, "duringDeal": 24, "formField": ""},
"overTimeConfig": {
"on": 2, "firstOver": 0, "overTimeDuring": 2, "overNotice": True,
"overAutoApprove": False, "overAutoApproveTime": 5, "overEvent": False,
"overEventTime": 5, "overAutoTransfer": False, "overAutoTransferTime": 2,
"overTimeType": 6, "interfaceId": "", "interfaceName": "", "templateJson": [],
"reApprovers": "", "overTimeExtraRule": 3,
},
"noticeConfig": {"on": 2, "firstOver": 1, "overTimeDuring": 2, "overNotice": True, "overEvent": False, "overEventTime": 5},
"approveFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"rejectFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"backFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"recallFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"overTimeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"noticeFuncConfig": {"on": False, "interfaceId": "", "interfaceName": "", "templateJson": []},
"isCandidates": False,
"approversConfig": {"start": 1, "end": 1, "level": 2, "originLevel": 1},
"approvalNumber": 1,
"oneSelfEndApproval": True,
"freeNode": False,
},
"Event_end": {
"type": "end",
"nodeId": "Event_end",
"nodeName": "结束节点",
"endParameterList": [],
},
}
def create_decision_flow(
self,
full_name: str,
en_code: str,
form_id: str,
branch_a_user_ids: Optional[List[str]] = None,
branch_b_user_ids: Optional[List[str]] = None,
form_name: str = "",
description: str = "",
icon: str = "icon-ym icon-ym-flow",
) -> Dict[str, str]:
"""创建决策流程模板
决策流程使用排他网关,根据条件选择不同的审批分支。
Args:
full_name: 流程名称
en_code: 流程编码
form_id: 关联的可视化开发表单 ID
branch_a_user_ids: 分支A审批人用户 ID 列表
branch_b_user_ids: 分支B审批人用户 ID 列表
form_name: 表单名称
description: 流程说明
icon: 流程图标
Returns:
dict: {
"template_id": 模板 ID,
"version_id": 版本 ID,
}
"""
flow_xml = self.build_decision_flow_xml()
flow_nodes = self.build_decision_flow_nodes(
form_id, form_name,
branch_a_user_ids=branch_a_user_ids,
branch_b_user_ids=branch_b_user_ids,
)
flow_config = json.dumps({"visibleType": 1}, ensure_ascii=False)
resp = self.create_template({
"fullName": full_name,
"enCode": en_code,
"type": 4, # 决策流程
"category": "",
"icon": icon,
"iconBackground": "#008cff",
"showType": 0,
"sortCode": 0,
"description": description,
"flowXml": flow_xml,
"flowNodes": flow_nodes,
"flowConfig": flow_config,
})
if not resp.success:
raise RuntimeError(f"创建决策流程模板失败: {resp.msg}")
template_id = resp.id
resp = self.get_version_list(template_id)
if not resp.success or not resp.data:
raise RuntimeError(f"获取版本列表失败: {resp.msg}")
version_id = resp.data[0]["id"]
resp = self.save_flow({
"id": template_id,
"flowId": version_id,
"flowXml": flow_xml,
"flowNodes": flow_nodes,
"flowConfig": flow_config,
"type": 0,
})
if not resp.success:
raise RuntimeError(f"保存流程设计失败: {resp.msg}")
return {
"template_id": template_id,
"version_id": version_id,
}