529 lines
24 KiB
Python
529 lines
24 KiB
Python
"""审批:待办/已办/我发起的、审批动作、流程配置。"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
from typing import Any
|
||
|
||
from fastapi import APIRouter, Query
|
||
from sqlalchemy.orm import Session
|
||
from pydantic import BaseModel, Field
|
||
from sqlalchemy import func, select
|
||
|
||
from .. import dicts as dict_store
|
||
from ..deps import DbSession, PrincipalOf, assert_project_visible
|
||
from ..envelope import conflict, forbidden, not_found, ok, page
|
||
from ..models import (
|
||
Action,
|
||
ApprovalDelegate,
|
||
ApprovalFlow,
|
||
ApprovalInstance,
|
||
ApprovalNode,
|
||
ApprovalRecord,
|
||
ApprovalTask,
|
||
FlowStatus,
|
||
InstanceStatus,
|
||
NodeType,
|
||
Revision,
|
||
RevisionStatus,
|
||
SignType,
|
||
TaskStatus,
|
||
)
|
||
from ..service.approval import engine as approval_engine
|
||
from ..service.approval import flow as flow_service
|
||
|
||
router = APIRouter(prefix="/approvals", tags=["approvals"])
|
||
|
||
#: 流程设计器里可以手工摆的节点类型(发起节点由系统生成,不给选)
|
||
_CONFIGURABLE_NODE_TYPES = {NodeType.APPROVE, NodeType.CC, NodeType.CONDITION, NodeType.END}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 工作台
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
@router.get("/todo")
|
||
def todo(db: DbSession, current: PrincipalOf, module: str = "",
|
||
pageNo: int = Query(1, ge=1), pageSize: int = Query(20, ge=1, le=200)) -> dict[str, Any]:
|
||
statement = (
|
||
select(ApprovalTask, ApprovalInstance)
|
||
.join(ApprovalInstance, ApprovalInstance.id == ApprovalTask.instance_id)
|
||
.where(ApprovalTask.assignee_id == current.account.id,
|
||
ApprovalTask.status == TaskStatus.PENDING,
|
||
ApprovalInstance.status == InstanceStatus.REVIEWING)
|
||
)
|
||
if module:
|
||
statement = statement.where(ApprovalInstance.business_module == module)
|
||
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
|
||
rows = db.execute(statement.order_by(ApprovalTask.id.desc())
|
||
.offset((pageNo - 1) * pageSize).limit(pageSize)).all()
|
||
return page([
|
||
{
|
||
"taskId": task.id, "instanceId": instance.id,
|
||
"businessModule": instance.business_module,
|
||
"businessModuleLabel": dict_store.label(db, "businessModule", instance.business_module),
|
||
"projectId": instance.project_id, "projectName": instance.project_name,
|
||
"revisionId": instance.revision_id, "snapshotId": instance.snapshot_id,
|
||
"nodeName": task.node_name, "signType": task.sign_type,
|
||
"signTypeLabel": dict_store.label(db, "signType", task.sign_type),
|
||
"submitterName": instance.submitter_name,
|
||
"submittedAt": instance.submitted_at.isoformat(sep=" ", timespec="seconds"),
|
||
"dueAt": task.due_at.isoformat(sep=" ", timespec="seconds") if task.due_at else "",
|
||
}
|
||
for task, instance in rows
|
||
], total, pageNo, pageSize)
|
||
|
||
|
||
@router.get("/done")
|
||
def done(db: DbSession, current: PrincipalOf, module: str = "",
|
||
pageNo: int = Query(1, ge=1), pageSize: int = Query(20, ge=1, le=200)) -> dict[str, Any]:
|
||
statement = (
|
||
select(ApprovalTask, ApprovalInstance)
|
||
.join(ApprovalInstance, ApprovalInstance.id == ApprovalTask.instance_id)
|
||
.where(ApprovalTask.assignee_id == current.account.id,
|
||
ApprovalTask.status.in_([TaskStatus.DONE, TaskStatus.TRANSFERRED]))
|
||
)
|
||
if module:
|
||
statement = statement.where(ApprovalInstance.business_module == module)
|
||
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
|
||
rows = db.execute(statement.order_by(ApprovalTask.acted_at.desc())
|
||
.offset((pageNo - 1) * pageSize).limit(pageSize)).all()
|
||
return page([
|
||
{
|
||
"taskId": task.id, "instanceId": instance.id,
|
||
"businessModuleLabel": dict_store.label(db, "businessModule", instance.business_module),
|
||
"projectId": instance.project_id, "projectName": instance.project_name,
|
||
"snapshotId": instance.snapshot_id,
|
||
"nodeName": task.node_name, "action": task.action,
|
||
"actionLabel": dict_store.label(db, "approvalAction", task.action, task.action),
|
||
"comment": task.comment,
|
||
"instanceStatus": instance.status,
|
||
"instanceStatusLabel": dict_store.label(db, "instanceStatus", instance.status),
|
||
"actedAt": task.acted_at.isoformat(sep=" ", timespec="seconds") if task.acted_at else "",
|
||
}
|
||
for task, instance in rows
|
||
], total, pageNo, pageSize)
|
||
|
||
|
||
@router.get("/created")
|
||
def created(db: DbSession, current: PrincipalOf, module: str = "", status: str = "",
|
||
pageNo: int = Query(1, ge=1), pageSize: int = Query(20, ge=1, le=200)) -> dict[str, Any]:
|
||
statement = select(ApprovalInstance).where(ApprovalInstance.submitter_id == current.account.id)
|
||
if module:
|
||
statement = statement.where(ApprovalInstance.business_module == module)
|
||
if status:
|
||
statement = statement.where(ApprovalInstance.status == status)
|
||
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
|
||
rows = db.execute(statement.order_by(ApprovalInstance.id.desc())
|
||
.offset((pageNo - 1) * pageSize).limit(pageSize)).scalars().all()
|
||
return page([_instance_view(db, row) for row in rows], total, pageNo, pageSize)
|
||
|
||
|
||
@router.get("/monitor")
|
||
def monitor(db: DbSession, current: PrincipalOf, module: str = "", status: str = "",
|
||
keyword: str = "", pageNo: int = Query(1, ge=1),
|
||
pageSize: int = Query(20, ge=1, le=200)) -> dict[str, Any]:
|
||
if not current.permission.can("approval:monitor:view"):
|
||
raise forbidden("缺少权限:approval:monitor:view")
|
||
statement = select(ApprovalInstance)
|
||
if module:
|
||
statement = statement.where(ApprovalInstance.business_module == module)
|
||
if status:
|
||
statement = statement.where(ApprovalInstance.status == status)
|
||
if keyword:
|
||
statement = statement.where(ApprovalInstance.project_name.like(f"%{keyword}%"))
|
||
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
|
||
rows = db.execute(statement.order_by(ApprovalInstance.id.desc())
|
||
.offset((pageNo - 1) * pageSize).limit(pageSize)).scalars().all()
|
||
return page([_instance_view(db, row) for row in rows], total, pageNo, pageSize)
|
||
|
||
|
||
def _instance_view(db: Session, row: ApprovalInstance) -> dict[str, Any]:
|
||
return {
|
||
"id": row.id, "flowName": row.flow_name,
|
||
"businessModule": row.business_module,
|
||
"businessModuleLabel": dict_store.label(db, "businessModule", row.business_module),
|
||
"projectId": row.project_id, "projectName": row.project_name,
|
||
"revisionId": row.revision_id, "snapshotId": row.snapshot_id,
|
||
"status": row.status, "statusLabel": dict_store.label(db, "instanceStatus", row.status),
|
||
"currentNode": row.current_node_name,
|
||
"submitterName": row.submitter_name,
|
||
"submittedAt": row.submitted_at.isoformat(sep=" ", timespec="seconds"),
|
||
"finishedAt": row.finished_at.isoformat(sep=" ", timespec="seconds") if row.finished_at else "",
|
||
}
|
||
|
||
|
||
@router.get("/instances/{instance_id}")
|
||
def instance_detail(instance_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
instance = db.get(ApprovalInstance, instance_id)
|
||
if instance is None:
|
||
raise not_found("审批实例不存在")
|
||
assert_project_visible(db, current, instance.project_id, module=instance.business_module)
|
||
|
||
tasks = db.execute(select(ApprovalTask).where(ApprovalTask.instance_id == instance_id)
|
||
.order_by(ApprovalTask.id)).scalars().all()
|
||
records = db.execute(select(ApprovalRecord).where(ApprovalRecord.instance_id == instance_id)
|
||
.order_by(ApprovalRecord.id)).scalars().all()
|
||
revision = db.get(Revision, instance.revision_id) if instance.revision_id else None
|
||
my_tasks = [task.id for task in tasks
|
||
if task.assignee_id == current.account.id and task.status == TaskStatus.PENDING]
|
||
|
||
return ok({
|
||
"instance": _instance_view(db, instance),
|
||
"canWithdraw": (instance.status == InstanceStatus.REVIEWING
|
||
and instance.submitter_id == current.account.id),
|
||
"myTaskIds": my_tasks,
|
||
"revision": {
|
||
"id": revision.id, "version": revision.version, "status": revision.status,
|
||
"statusLabel": dict_store.label(db, "revisionStatus", revision.status),
|
||
} if revision else None,
|
||
"tasks": [{
|
||
"id": task.id, "nodeName": task.node_name, "assigneeName": task.assignee_name,
|
||
"status": task.status, "action": task.action,
|
||
"statusLabel": dict_store.label(db, "taskStatus", task.status),
|
||
"actionLabel": dict_store.label(db, "approvalAction", task.action), "comment": task.comment,
|
||
"signType": task.sign_type,
|
||
"signTypeLabel": dict_store.label(db, "signType", task.sign_type),
|
||
"orderInNode": task.order_in_node,
|
||
"dueAt": task.due_at.isoformat(sep=" ", timespec="seconds") if task.due_at else "",
|
||
"actedAt": task.acted_at.isoformat(sep=" ", timespec="seconds") if task.acted_at else "",
|
||
} for task in tasks],
|
||
"records": [{
|
||
"id": row.id, "nodeName": row.node_name, "action": row.action,
|
||
"actionLabel": row.action_label, "operatorName": row.operator_name,
|
||
"targetNames": row.target_names, "comment": row.comment,
|
||
"rollbackToNode": row.rollback_to_node,
|
||
"createdAt": row.created_at.isoformat(sep=" ", timespec="seconds"),
|
||
} for row in records],
|
||
})
|
||
|
||
|
||
class ActBody(BaseModel):
|
||
action: str = Field(min_length=1, max_length=24)
|
||
comment: str = ""
|
||
targetIds: list[int] = Field(default_factory=list)
|
||
rollbackTo: str = ""
|
||
|
||
|
||
@router.post("/tasks/{task_id}/act")
|
||
def act(task_id: int, body: ActBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
task = db.get(ApprovalTask, task_id)
|
||
if task is None:
|
||
raise not_found("待办不存在")
|
||
instance = approval_engine.act(
|
||
db, task=task, actor=current.account, action=body.action,
|
||
comment=body.comment, target_ids=body.targetIds, rollback_to=body.rollbackTo,
|
||
)
|
||
db.commit()
|
||
return ok({"instance": _instance_view(db, instance)})
|
||
|
||
|
||
class WithdrawBody(BaseModel):
|
||
comment: str = ""
|
||
|
||
|
||
@router.post("/instances/{instance_id}/withdraw")
|
||
def withdraw(instance_id: int, body: WithdrawBody, *, db: DbSession,
|
||
current: PrincipalOf) -> dict[str, Any]:
|
||
instance = db.get(ApprovalInstance, instance_id)
|
||
if instance is None:
|
||
raise not_found("审批实例不存在")
|
||
approval_engine.withdraw(db, instance=instance, actor=current.account, comment=body.comment)
|
||
db.commit()
|
||
return ok({"instance": _instance_view(db, instance)})
|
||
|
||
|
||
@router.get("/instances/{instance_id}/rollback-targets")
|
||
def rollback_targets(instance_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
"""退回到哪些节点可选,由后端算,前端不猜。"""
|
||
instance = db.get(ApprovalInstance, instance_id)
|
||
if instance is None:
|
||
raise not_found("审批实例不存在")
|
||
completed = set(json.loads(instance.runtime_json or "{}").get("completed", []))
|
||
nodes = flow_service.ordered_nodes(db.get(ApprovalFlow, instance.flow_id))
|
||
current_node = next((node for node in nodes if node.node_key == instance.current_node_key), None)
|
||
allowed = set(json.loads(current_node.rollback_keys_json or "[]")) if current_node else set()
|
||
out = [{"value": "initiator", "label": "退回发起人修改"}]
|
||
for node in nodes:
|
||
if node.node_type != NodeType.APPROVE or node.node_key not in completed:
|
||
continue
|
||
if allowed and node.node_key not in allowed:
|
||
continue
|
||
out.append({"value": node.node_key, "label": f"退回到「{node.name}」"})
|
||
return ok(out)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 流程配置
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class NodeBody(BaseModel):
|
||
nodeKey: str = Field(min_length=1, max_length=64)
|
||
name: str = Field(min_length=1, max_length=128)
|
||
nodeType: str = NodeType.APPROVE
|
||
orderNumber: int = 100
|
||
signType: str = SignType.ANY
|
||
candidates: list[dict[str, Any]] = Field(default_factory=list)
|
||
emptyStrategy: str = "admin"
|
||
condition: str = ""
|
||
nextNodeKey: str = ""
|
||
rejectTo: str = "end"
|
||
rollbackKeys: list[str] = Field(default_factory=list)
|
||
commentRequired: bool = False
|
||
rejectCommentRequired: bool = True
|
||
timeoutHours: int = 0
|
||
timeoutAction: str = "none"
|
||
enabled: bool = True
|
||
remark: str = ""
|
||
|
||
|
||
class FlowBody(BaseModel):
|
||
key: str = Field(min_length=1, max_length=64)
|
||
name: str = Field(min_length=1, max_length=128)
|
||
businessModule: str
|
||
status: str = FlowStatus.DRAFT
|
||
matchExpressions: list[str] = Field(default_factory=list)
|
||
priority: int = 100
|
||
allowSelfSelect: bool = False
|
||
autoSkipDuplicate: bool = True
|
||
remark: str = ""
|
||
nodes: list[NodeBody] = Field(default_factory=list)
|
||
|
||
|
||
@router.get("/flows")
|
||
def list_flows(db: DbSession, current: PrincipalOf, module: str = "") -> dict[str, Any]:
|
||
if not current.permission.can_any(("approval:flow:view", "approval:flow:edit")):
|
||
raise forbidden("缺少权限:approval:flow:view")
|
||
statement = select(ApprovalFlow).where(ApprovalFlow.is_deleted.is_(False))
|
||
if module:
|
||
statement = statement.where(ApprovalFlow.business_module == module)
|
||
rows = db.execute(statement.order_by(ApprovalFlow.business_module, ApprovalFlow.priority,
|
||
ApprovalFlow.id.desc())).scalars().all()
|
||
return ok([{
|
||
"id": row.id, "key": row.key, "name": row.name,
|
||
"businessModule": row.business_module,
|
||
"businessModuleLabel": dict_store.label(db, "businessModule", row.business_module),
|
||
"version": row.version, "status": row.status, "priority": row.priority,
|
||
"matchExpressions": _match_expressions(row.match_json),
|
||
"allowSelfSelect": row.allow_self_select, "autoSkipDuplicate": row.auto_skip_duplicate,
|
||
"remark": row.remark, "nodeCount": len(flow_service.ordered_nodes(row)),
|
||
} for row in rows])
|
||
|
||
|
||
def _match_expressions(raw: str) -> list[str]:
|
||
if not (raw or "").strip():
|
||
return []
|
||
try:
|
||
data = json.loads(raw)
|
||
except json.JSONDecodeError:
|
||
return [raw]
|
||
if isinstance(data, dict):
|
||
return [str(item) for item in (data.get("expressions") or [])]
|
||
return [str(item) for item in data] if isinstance(data, list) else []
|
||
|
||
|
||
@router.get("/flows/options")
|
||
def flow_options(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
if not current.permission.can_any(("approval:flow:view", "approval:flow:edit")):
|
||
raise forbidden("缺少权限:approval:flow:view")
|
||
from ..models import PermRole, Position
|
||
|
||
return ok({
|
||
# 这几组下拉值一律现取字典。前端已经改成直接读字典(DictSelect),这里保留同样的
|
||
# 键只是给还在用这条接口的老调用方兜底——取值和名字都来自同一份,不会对不上。
|
||
"modules": dict_store.options(db, "businessModule"),
|
||
"nodeTypes": [row for row in dict_store.options(db, "nodeType")
|
||
if row["value"] in _CONFIGURABLE_NODE_TYPES],
|
||
"signTypes": dict_store.options(db, "signType"),
|
||
"candidateTypes": dict_store.options(db, "candidateType"),
|
||
"emptyStrategies": dict_store.options(db, "emptyStrategy"),
|
||
"timeoutActions": dict_store.options(db, "timeoutAction"),
|
||
"roles": [{"id": row.id, "name": row.name} for row in
|
||
db.execute(select(PermRole).where(PermRole.is_deleted.is_(False))).scalars().all()],
|
||
"positions": [{"id": row.id, "name": row.name} for row in
|
||
db.execute(select(Position).where(Position.is_deleted.is_(False))).scalars().all()],
|
||
"conditionFields": ["contract_amount", "contribution_profit_rate", "project_type",
|
||
"underwritten_mode", "income_total", "org_unit_id", "submitter_id"],
|
||
})
|
||
|
||
|
||
@router.get("/flows/{flow_id}")
|
||
def get_flow(flow_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
if not current.permission.can_any(("approval:flow:view", "approval:flow:edit")):
|
||
raise forbidden("缺少权限:approval:flow:view")
|
||
flow = db.get(ApprovalFlow, flow_id)
|
||
if flow is None or flow.is_deleted:
|
||
raise not_found("流程不存在")
|
||
return ok({
|
||
"flow": {
|
||
"id": flow.id, "key": flow.key, "name": flow.name,
|
||
"businessModule": flow.business_module, "version": flow.version, "status": flow.status,
|
||
"matchExpressions": _match_expressions(flow.match_json), "priority": flow.priority,
|
||
"allowSelfSelect": flow.allow_self_select, "autoSkipDuplicate": flow.auto_skip_duplicate,
|
||
"remark": flow.remark,
|
||
},
|
||
"nodes": [_node_view(node) for node in flow_service.ordered_nodes(flow)],
|
||
"errors": flow_service.definition_errors(flow),
|
||
})
|
||
|
||
|
||
def _node_view(node: ApprovalNode) -> dict[str, Any]:
|
||
return {
|
||
"id": node.id, "nodeKey": node.node_key, "name": node.name, "nodeType": node.node_type,
|
||
"orderNumber": node.order_number, "signType": node.sign_type,
|
||
"candidates": _loads(node.candidates_json, []),
|
||
"emptyStrategy": node.empty_strategy, "condition": node.condition_json,
|
||
"nextNodeKey": node.next_node_key, "rejectTo": node.reject_to,
|
||
"rollbackKeys": _loads(node.rollback_keys_json, []),
|
||
"commentRequired": node.comment_required, "rejectCommentRequired": node.reject_comment_required,
|
||
"timeoutHours": node.timeout_hours, "timeoutAction": node.timeout_action,
|
||
"enabled": node.enabled, "remark": node.remark,
|
||
}
|
||
|
||
|
||
def _loads(raw: str, default: Any) -> Any:
|
||
try:
|
||
return json.loads(raw or "null")
|
||
except json.JSONDecodeError:
|
||
return default
|
||
|
||
|
||
@router.post("/flows")
|
||
def create_flow(body: FlowBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
if not current.permission.can("approval:flow:edit"):
|
||
raise forbidden("缺少权限:approval:flow:edit")
|
||
flow = ApprovalFlow(
|
||
key=body.key, name=body.name, business_module=body.businessModule,
|
||
status=FlowStatus.DRAFT, # 新建一律是草稿,必须显式发布
|
||
match_json=json.dumps({"expressions": body.matchExpressions}, ensure_ascii=False),
|
||
priority=body.priority, allow_self_select=body.allowSelfSelect,
|
||
auto_skip_duplicate=body.autoSkipDuplicate, remark=body.remark,
|
||
)
|
||
db.add(flow)
|
||
db.flush()
|
||
_replace_nodes(db, flow, body.nodes)
|
||
db.commit()
|
||
return ok({"id": flow.id})
|
||
|
||
|
||
def _replace_nodes(db, flow: ApprovalFlow, nodes: list[NodeBody]) -> None:
|
||
for node in list(flow.nodes):
|
||
db.delete(node)
|
||
db.flush()
|
||
for item in nodes:
|
||
db.add(ApprovalNode(
|
||
flow_id=flow.id, node_key=item.nodeKey, name=item.name, node_type=item.nodeType,
|
||
order_number=item.orderNumber, sign_type=item.signType,
|
||
candidates_json=json.dumps(item.candidates, ensure_ascii=False),
|
||
empty_strategy=item.emptyStrategy, condition_json=item.condition,
|
||
next_node_key=item.nextNodeKey, reject_to=item.rejectTo,
|
||
rollback_keys_json=json.dumps(item.rollbackKeys),
|
||
comment_required=item.commentRequired, reject_comment_required=item.rejectCommentRequired,
|
||
timeout_hours=item.timeoutHours, timeout_action=item.timeoutAction,
|
||
enabled=item.enabled, remark=item.remark,
|
||
))
|
||
db.flush()
|
||
|
||
|
||
@router.put("/flows/{flow_id}")
|
||
def update_flow(flow_id: int, body: FlowBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
if not current.permission.can("approval:flow:edit"):
|
||
raise forbidden("缺少权限:approval:flow:edit")
|
||
flow = db.get(ApprovalFlow, flow_id)
|
||
if flow is None or flow.is_deleted:
|
||
raise not_found("流程不存在")
|
||
if flow.status == FlowStatus.PUBLISHED and body.status != FlowStatus.OFFLINE:
|
||
raise conflict("published_locked",
|
||
"已发布的流程不能直接改。请先下线,或复制成新版本再发布,"
|
||
"否则正在跑的审批会突然换规则。")
|
||
flow.name = body.name
|
||
flow.business_module = body.businessModule
|
||
flow.match_json = json.dumps({"expressions": body.matchExpressions}, ensure_ascii=False)
|
||
flow.priority = body.priority
|
||
flow.allow_self_select = body.allowSelfSelect
|
||
flow.auto_skip_duplicate = body.autoSkipDuplicate
|
||
flow.remark = body.remark
|
||
_replace_nodes(db, flow, body.nodes)
|
||
db.commit()
|
||
return ok({"id": flow.id, "errors": flow_service.definition_errors(flow)})
|
||
|
||
|
||
@router.post("/flows/{flow_id}/publish")
|
||
def publish_flow(flow_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
if not current.permission.can("approval:flow:publish"):
|
||
raise forbidden("缺少权限:approval:flow:publish")
|
||
flow = db.get(ApprovalFlow, flow_id)
|
||
if flow is None or flow.is_deleted:
|
||
raise not_found("流程不存在")
|
||
errors = flow_service.definition_errors(flow)
|
||
if errors:
|
||
raise conflict("definition_invalid", "流程定义有问题,不能发布", {"errors": errors})
|
||
# 同一模块同一时刻只有一条已发布流程会被匹配到,但允许配多条不同条件的
|
||
flow.status = FlowStatus.PUBLISHED
|
||
flow.version = flow.version + 1
|
||
db.commit()
|
||
return ok({"id": flow.id, "version": flow.version})
|
||
|
||
|
||
@router.post("/flows/{flow_id}/offline")
|
||
def offline_flow(flow_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
if not current.permission.can("approval:flow:publish"):
|
||
raise forbidden("缺少权限:approval:flow:publish")
|
||
flow = db.get(ApprovalFlow, flow_id)
|
||
if flow is None or flow.is_deleted:
|
||
raise not_found("流程不存在")
|
||
running = db.execute(
|
||
select(func.count(ApprovalInstance.id)).where(ApprovalInstance.flow_id == flow_id,
|
||
ApprovalInstance.status == InstanceStatus.REVIEWING)
|
||
).scalar() or 0
|
||
flow.status = FlowStatus.OFFLINE
|
||
db.commit()
|
||
return ok({"id": flow.id, "runningInstances": running})
|
||
|
||
|
||
@router.get("/delegates")
|
||
def list_delegates(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
rows = db.execute(select(ApprovalDelegate).where(
|
||
ApprovalDelegate.from_id == current.account.id,
|
||
ApprovalDelegate.is_deleted.is_(False)).order_by(ApprovalDelegate.id.desc())).scalars().all()
|
||
return ok([{
|
||
"id": row.id, "toId": row.to_id, "toName": row.to_name,
|
||
"modules": _loads(row.modules_json, []),
|
||
"validFrom": row.valid_from.isoformat(sep=" ", timespec="minutes") if row.valid_from else "",
|
||
"validTo": row.valid_to.isoformat(sep=" ", timespec="minutes") if row.valid_to else "",
|
||
"enabled": row.enabled, "reason": row.reason,
|
||
} for row in rows])
|
||
|
||
|
||
class DelegateBody(BaseModel):
|
||
toId: int
|
||
modules: list[str] = Field(default_factory=list)
|
||
validFrom: str = ""
|
||
validTo: str = ""
|
||
reason: str = ""
|
||
|
||
|
||
@router.post("/delegates")
|
||
def create_delegate(body: DelegateBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||
from datetime import datetime
|
||
|
||
from ..models import Account
|
||
|
||
target = db.get(Account, body.toId)
|
||
if target is None or target.is_deleted:
|
||
raise not_found("接手人不存在")
|
||
row = ApprovalDelegate(
|
||
from_id=current.account.id, from_name=current.account.display_name,
|
||
to_id=target.id, to_name=target.display_name or target.account,
|
||
modules_json=json.dumps(body.modules), enabled=True, reason=body.reason,
|
||
)
|
||
if body.validFrom:
|
||
row.valid_from = datetime.fromisoformat(body.validFrom)
|
||
if body.validTo:
|
||
row.valid_to = datetime.fromisoformat(body.validTo)
|
||
db.add(row)
|
||
db.commit()
|
||
return ok({"id": row.id})
|