644 lines
27 KiB
Python
644 lines
27 KiB
Python
"""审批流转状态机。
|
||
|
||
覆盖老系统的或签/会签/退回/审批意见,并补上业务上一直接受不了但老系统没有的行为:
|
||
依次审批、加签、转办、撤回、同一审批人自动跳过、超时提醒。
|
||
|
||
一条铁律:**审批看的是送审时冻结的那一版数据**(``revision_id`` + ``snapshot_id``),
|
||
发起人之后怎么改草稿都不影响正在跑的审批。老系统靠"提交时把 temp 表搬到正式表"
|
||
间接实现了这件事,但代价是草稿和正式共用一套表名、两套查询。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
from datetime import datetime, timedelta
|
||
from typing import Any
|
||
|
||
from sqlalchemy import select, update
|
||
from sqlalchemy.orm import Session
|
||
|
||
from ...envelope import ApiError
|
||
from ...models import (
|
||
Action,
|
||
ApprovalFlow,
|
||
ApprovalInstance,
|
||
ApprovalNode,
|
||
ApprovalRecord,
|
||
ApprovalTask,
|
||
FlowStatus,
|
||
InstanceStatus,
|
||
NodeType,
|
||
Project,
|
||
Revision,
|
||
RevisionStatus,
|
||
SignType,
|
||
TaskStatus,
|
||
)
|
||
from . import candidates as candidate_resolver
|
||
from .flow import match_flow, node_condition_passes, ordered_nodes
|
||
|
||
|
||
class ApprovalError(ApiError):
|
||
def __init__(self, code: str, message: str) -> None:
|
||
super().__init__(code, message, http_status=400)
|
||
|
||
|
||
def submit(
|
||
db: Session,
|
||
*,
|
||
module: str,
|
||
project: Project,
|
||
revision: Revision,
|
||
snapshot_id: int | None,
|
||
submitter: Any,
|
||
variables: dict[str, Any] | None = None,
|
||
comment: str = "",
|
||
previous_instance_id: int | None = None,
|
||
self_selected: dict[str, list[int]] | None = None,
|
||
) -> ApprovalInstance:
|
||
"""发起一次审批。找不到匹配流程时直接报错,不允许"静默通过"。"""
|
||
payload = dict(variables or {})
|
||
payload.setdefault("project_id", project.id)
|
||
payload.setdefault("project_type", project.type)
|
||
payload.setdefault("underwritten_mode", project.underwritten_mode)
|
||
payload.setdefault("submitter_id", submitter.id)
|
||
payload.setdefault("org_unit_id", project.org_unit_id or submitter.org_unit_id)
|
||
|
||
flow = match_flow(db, module, payload)
|
||
if flow is None:
|
||
raise ApprovalError(
|
||
"flow_not_matched",
|
||
"没有找到匹配的审批流程,请联系管理员在「审批流程配置」中为该业务发布一条流程",
|
||
)
|
||
if flow.status != FlowStatus.PUBLISHED:
|
||
raise ApprovalError("flow_not_published", f"流程「{flow.name}」尚未发布")
|
||
|
||
nodes = ordered_nodes(flow)
|
||
if not nodes:
|
||
raise ApprovalError("flow_empty", f"流程「{flow.name}」没有可用节点")
|
||
|
||
instance = ApprovalInstance(
|
||
flow_id=flow.id,
|
||
flow_key=flow.key,
|
||
flow_name=flow.name,
|
||
flow_version=flow.version,
|
||
business_module=module,
|
||
project_id=project.id,
|
||
project_name=project.name,
|
||
revision_id=revision.id,
|
||
snapshot_id=snapshot_id,
|
||
status=InstanceStatus.REVIEWING,
|
||
submitter_id=submitter.id,
|
||
submitter_name=submitter.display_name or submitter.account,
|
||
submitter_org_id=submitter.org_unit_id,
|
||
variables_json=json.dumps(payload, ensure_ascii=False),
|
||
runtime_json=json.dumps({"completed": [], "selected": self_selected or {}}),
|
||
previous_instance_id=previous_instance_id,
|
||
)
|
||
db.add(instance)
|
||
db.flush()
|
||
|
||
_record(db, instance, node_key="", node_name="", action=Action.SUBMIT,
|
||
operator=submitter, comment=comment)
|
||
|
||
revision.status = RevisionStatus.REVIEWING
|
||
revision.submitted_at = datetime.now()
|
||
|
||
_advance(db, instance, submitter.id, start_from_order=-1)
|
||
db.flush()
|
||
return instance
|
||
|
||
|
||
def pending_tasks(db: Session, account_id: int, *, module: str | None = None) -> list[ApprovalTask]:
|
||
statement = (
|
||
select(ApprovalTask)
|
||
.join(ApprovalInstance, ApprovalInstance.id == ApprovalTask.instance_id)
|
||
.where(ApprovalTask.assignee_id == account_id, ApprovalTask.status == TaskStatus.PENDING,
|
||
ApprovalInstance.status == InstanceStatus.REVIEWING)
|
||
)
|
||
if module:
|
||
statement = statement.where(ApprovalInstance.business_module == module)
|
||
return list(db.execute(statement.order_by(ApprovalTask.id.desc())).scalars().all())
|
||
|
||
|
||
def act(
|
||
db: Session,
|
||
*,
|
||
task: ApprovalTask,
|
||
actor: Any,
|
||
action: str,
|
||
comment: str = "",
|
||
target_ids: list[int] | None = None,
|
||
rollback_to: str = "",
|
||
) -> ApprovalInstance:
|
||
"""处理一条待办。"""
|
||
instance = db.get(ApprovalInstance, task.instance_id)
|
||
if instance is None:
|
||
raise ApprovalError("instance_missing", "审批实例不存在")
|
||
if instance.status != InstanceStatus.REVIEWING:
|
||
raise ApprovalError("instance_closed", "该审批已经结束,无法再操作")
|
||
if task.status != TaskStatus.PENDING:
|
||
raise ApprovalError("task_handled", "这条待办已经被处理过了")
|
||
if task.assignee_id != actor.id:
|
||
raise ApprovalError("not_assignee", "这条待办不属于你")
|
||
|
||
node = _node_of(db, instance, task.node_key)
|
||
if action in (Action.REJECT, Action.ROLLBACK) and node.reject_comment_required and not comment.strip():
|
||
raise ApprovalError("comment_required", "审批不通过时必须填写审批意见")
|
||
if action == Action.APPROVE and node.comment_required and not comment.strip():
|
||
raise ApprovalError("comment_required", "该节点要求填写审批意见")
|
||
|
||
if action == Action.APPROVE:
|
||
return _approve(db, instance, task, node, actor, comment)
|
||
if action == Action.REJECT:
|
||
return _reject(db, instance, task, node, actor, comment)
|
||
if action == Action.ROLLBACK:
|
||
return _rollback(db, instance, task, node, actor, comment, rollback_to)
|
||
if action == Action.TRANSFER:
|
||
return _transfer(db, instance, task, node, actor, comment, target_ids or [])
|
||
if action == Action.ADD_SIGN:
|
||
return _add_sign(db, instance, task, node, actor, comment, target_ids or [])
|
||
if action == Action.REMIND:
|
||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.REMIND,
|
||
operator=actor, comment=comment, target_names=_names(db, [task.assignee_id]))
|
||
db.flush()
|
||
return instance
|
||
raise ApprovalError("unsupported_action", f"不支持的审批动作:{action}")
|
||
|
||
|
||
def withdraw(db: Session, *, instance: ApprovalInstance, actor: Any, comment: str = "") -> ApprovalInstance:
|
||
"""撤回:只有还没任何人处理过时才允许,避免把已经表过态的审批抹掉。"""
|
||
if instance.status != InstanceStatus.REVIEWING:
|
||
raise ApprovalError("instance_closed", "审批已结束,无法撤回")
|
||
if instance.submitter_id != actor.id:
|
||
raise ApprovalError("not_submitter", "只有发起人可以撤回")
|
||
acted = db.execute(
|
||
select(ApprovalTask.id).where(
|
||
ApprovalTask.instance_id == instance.id,
|
||
ApprovalTask.status.in_([TaskStatus.DONE, TaskStatus.TRANSFERRED]),
|
||
).limit(1)
|
||
).scalar()
|
||
if acted:
|
||
raise ApprovalError("already_handled", "已有人处理,不能撤回,请联系当前审批人退回")
|
||
|
||
_cancel_pending(db, instance.id)
|
||
instance.status = InstanceStatus.WITHDRAWN
|
||
instance.finished_at = datetime.now()
|
||
_record(db, instance, node_key=instance.current_node_key, node_name=instance.current_node_name,
|
||
action=Action.WITHDRAW, operator=actor, comment=comment)
|
||
_release_revision(db, instance, RevisionStatus.WITHDRAWN)
|
||
db.flush()
|
||
return instance
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 内部:节点推进
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _approve(db: Session, instance: ApprovalInstance, task: ApprovalTask, node: ApprovalNode,
|
||
actor: Any, comment: str) -> ApprovalInstance:
|
||
task.status = TaskStatus.DONE
|
||
task.action = Action.APPROVE
|
||
task.comment = comment
|
||
task.acted_at = datetime.now()
|
||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.APPROVE,
|
||
operator=actor, comment=comment)
|
||
|
||
runtime = _runtime(instance)
|
||
if actor is not None:
|
||
runtime["completed_assignees"] = sorted(
|
||
set(runtime.get("completed_assignees", [])) | {int(actor.id)}
|
||
)
|
||
|
||
if node.sign_type == SignType.ANY:
|
||
_cancel_siblings(db, instance.id, node.node_key, keep_id=task.id)
|
||
return _finish_node(db, instance, node, runtime)
|
||
|
||
remaining = db.execute(
|
||
select(ApprovalTask.id).where(
|
||
ApprovalTask.instance_id == instance.id,
|
||
ApprovalTask.node_key == node.node_key,
|
||
ApprovalTask.status == TaskStatus.PENDING,
|
||
)
|
||
).scalars().all()
|
||
|
||
if remaining:
|
||
_save_runtime(instance, runtime)
|
||
db.flush()
|
||
return instance
|
||
return _finish_node(db, instance, node, runtime)
|
||
|
||
|
||
def _finish_node(db: Session, instance: ApprovalInstance, node: ApprovalNode,
|
||
runtime: dict[str, Any]) -> ApprovalInstance:
|
||
"""节点通过后的去向:显式 next 优先,否则按 order 往后走。"""
|
||
completed = set(runtime.get("completed", []))
|
||
completed.add(node.node_key)
|
||
runtime["completed"] = sorted(completed)
|
||
runtime["completed_assignees"] = runtime.get("completed_assignees", [])
|
||
_save_runtime(instance, runtime)
|
||
|
||
nodes = ordered_nodes(db.get(ApprovalFlow, instance.flow_id))
|
||
if node.next_node_key:
|
||
target = next((item for item in nodes if item.node_key == node.next_node_key), None)
|
||
if target is None:
|
||
raise ApprovalError("flow_broken", f"节点「{node.name}」的去向不存在")
|
||
order_before = target.order_number - 1
|
||
else:
|
||
order_before = node.order_number
|
||
|
||
return _advance(db, instance, instance.submitter_id, start_from_order=order_before,
|
||
skip_keys=completed)
|
||
|
||
|
||
def _advance(db: Session, instance: ApprovalInstance, submitter_id: int, *, start_from_order: int,
|
||
skip_keys: set[str] | None = None) -> ApprovalInstance:
|
||
"""从 ``start_from_order`` 之后找第一个需要人处理的节点并派任务。
|
||
|
||
条件不成立的节点直接跳过并留痕;抄送节点只记流水不阻塞。
|
||
"""
|
||
flow = db.get(ApprovalFlow, instance.flow_id)
|
||
nodes = ordered_nodes(flow)
|
||
variables = json.loads(instance.variables_json or "{}")
|
||
runtime = _runtime(instance)
|
||
skip_keys = set(skip_keys or runtime.get("completed", []))
|
||
project = db.get(Project, instance.project_id)
|
||
|
||
for node in nodes:
|
||
if node.order_number <= start_from_order:
|
||
continue
|
||
if node.node_type == NodeType.END:
|
||
break
|
||
if node.node_key in skip_keys:
|
||
continue
|
||
if not node_condition_passes(node, variables):
|
||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.AUTO_SKIP,
|
||
operator_id=submitter_id, operator_name="系统", comment="条件不满足,自动跳过该节点")
|
||
continue
|
||
if node.node_type == NodeType.CC:
|
||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.CC,
|
||
operator_id=submitter_id, operator_name="系统", comment="抄送")
|
||
continue
|
||
|
||
resolved = candidate_resolver.resolve(
|
||
db, node,
|
||
submitter_id=submitter_id,
|
||
project=project,
|
||
variables=variables,
|
||
previous_assignees=runtime.get("completed_assignees", []),
|
||
)
|
||
picked = resolved.ids
|
||
selected = (runtime.get("selected") or {}).get(node.node_key)
|
||
if selected:
|
||
allowed = set(selected)
|
||
picked = [item for item in picked if item in allowed] or list(allowed)
|
||
|
||
if flow.auto_skip_duplicate and picked:
|
||
already = set(runtime.get("completed_assignees", []))
|
||
overlapping = [item for item in picked if item in already]
|
||
if overlapping and len(overlapping) == len(picked) and node.sign_type != SignType.ALL:
|
||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.AUTO_SKIP,
|
||
operator_id=submitter_id, operator_name="系统",
|
||
comment="审批人与前序节点相同,自动跳过:" + "、".join(resolved.names))
|
||
skip_keys.add(node.node_key)
|
||
continue
|
||
picked = [item for item in picked if item not in already] or picked
|
||
|
||
if not picked:
|
||
if node.empty_strategy == "skip":
|
||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.AUTO_SKIP,
|
||
operator_id=submitter_id, operator_name="系统",
|
||
comment="未解析到审批人,按节点配置跳过" + (";" + ";".join(resolved.notes) if resolved.notes else ""))
|
||
continue
|
||
if node.empty_strategy == "admin":
|
||
admin = _fallback_admin(db)
|
||
if admin:
|
||
picked = [admin.id]
|
||
# 必须把兜底人放回 resolved,否则 _create_tasks 取不到姓名,
|
||
# 待办列表和流程详情上会显示成"未指派"
|
||
if admin not in resolved.accounts:
|
||
resolved.accounts.append(admin)
|
||
resolved.notes.append(f"已转交系统管理员 {admin.display_name or admin.account}")
|
||
if not picked:
|
||
raise ApprovalError(
|
||
"no_candidate",
|
||
f"节点「{node.name}」没有找到审批人"
|
||
+ (":" + ";".join(resolved.notes) if resolved.notes else ""),
|
||
)
|
||
|
||
instance.current_node_key = node.node_key
|
||
instance.current_node_name = node.name
|
||
created = _create_tasks(db, instance, node, resolved, picked, submitter_id)
|
||
if created == 0:
|
||
skip_keys.add(node.node_key)
|
||
continue
|
||
runtime["completed"] = sorted(set(runtime.get("completed", [])))
|
||
_save_runtime(instance, runtime)
|
||
db.flush()
|
||
return instance
|
||
|
||
return _finish(db, instance, InstanceStatus.APPROVED)
|
||
|
||
|
||
def _create_tasks(db: Session, instance: ApprovalInstance, node: ApprovalNode,
|
||
resolved: candidate_resolver.Resolved, picked: list[int], submitter_id: int) -> int:
|
||
"""按空签方式建待办。依次审批只建第一个人。"""
|
||
names = {account.id: (account.display_name or account.account) for account in resolved.accounts}
|
||
due = datetime.now() + timedelta(hours=node.timeout_hours) if node.timeout_hours else None
|
||
if node.sign_type == SignType.ORDER:
|
||
first = picked[0]
|
||
db.add(ApprovalTask(
|
||
instance_id=instance.id, node_key=node.node_key, node_name=node.name,
|
||
sign_type=node.sign_type, assignee_id=first, assignee_name=names.get(first, ""),
|
||
order_in_node=1, due_at=due,
|
||
))
|
||
runtime = _runtime(instance)
|
||
runtime["order_cursor"] = {node.node_key: 1, **runtime.get("order_cursor", {})}
|
||
runtime["order_queue"] = {node.node_key: picked, **runtime.get("order_queue", {})}
|
||
_save_runtime(instance, runtime)
|
||
return 1
|
||
|
||
for index, account_id in enumerate(picked):
|
||
db.add(ApprovalTask(
|
||
instance_id=instance.id, node_key=node.node_key, node_name=node.name,
|
||
sign_type=node.sign_type, assignee_id=account_id, assignee_name=names.get(account_id, ""),
|
||
order_in_node=(index + 1) * 10, due_at=due,
|
||
))
|
||
return len(picked)
|
||
|
||
|
||
def _reject(db: Session, instance: ApprovalInstance, task: ApprovalTask, node: ApprovalNode,
|
||
actor: Any, comment: str) -> ApprovalInstance:
|
||
task.status = TaskStatus.DONE
|
||
task.action = Action.REJECT
|
||
task.comment = comment
|
||
task.acted_at = datetime.now()
|
||
_cancel_siblings(db, instance.id, node.node_key, keep_id=task.id)
|
||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.REJECT,
|
||
operator=actor, comment=comment)
|
||
|
||
if node.reject_to in ("", "end"):
|
||
return _finish(db, instance, InstanceStatus.REJECTED)
|
||
if node.reject_to == "initiator":
|
||
_cancel_pending(db, instance.id)
|
||
return _finish(db, instance, InstanceStatus.REJECTED, returned_to_initiator=True)
|
||
return _move_back_to(db, instance, node.reject_to, actor, comment)
|
||
|
||
|
||
def _rollback(db: Session, instance: ApprovalInstance, task: ApprovalTask, node: ApprovalNode,
|
||
actor: Any, comment: str, target: str) -> ApprovalInstance:
|
||
"""退回到指定节点。允许的目标由节点的 ``rollback_keys_json`` 白名单控制。"""
|
||
allowed = json.loads(node.rollback_keys_json or "[]")
|
||
if target in ("", "initiator"):
|
||
task.status = TaskStatus.DONE
|
||
task.action = Action.ROLLBACK
|
||
task.comment = comment
|
||
task.acted_at = datetime.now()
|
||
_cancel_pending(db, instance.id)
|
||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.ROLLBACK,
|
||
operator=actor, comment=comment, rollback_to="initiator")
|
||
return _finish(db, instance, InstanceStatus.REJECTED, returned_to_initiator=True)
|
||
if allowed and target not in allowed:
|
||
raise ApprovalError("rollback_forbidden", "该节点不允许退回到所选节点")
|
||
|
||
task.status = TaskStatus.DONE
|
||
task.action = Action.ROLLBACK
|
||
task.comment = comment
|
||
task.acted_at = datetime.now()
|
||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.ROLLBACK,
|
||
operator=actor, comment=comment, rollback_to=target)
|
||
return _move_back_to(db, instance, target, actor, comment)
|
||
|
||
|
||
def _move_back_to(db: Session, instance: ApprovalInstance, target_key: str, actor: Any,
|
||
comment: str) -> ApprovalInstance:
|
||
"""把流程拉回更早的节点:清掉那之后的完成记录与待办。"""
|
||
flow = db.get(ApprovalFlow, instance.flow_id)
|
||
nodes = ordered_nodes(flow)
|
||
target = next((item for item in nodes if item.node_key == target_key), None)
|
||
if target is None:
|
||
raise ApprovalError("flow_broken", f"退回去向 {target_key} 不存在")
|
||
|
||
_cancel_pending(db, instance.id)
|
||
runtime = _runtime(instance)
|
||
runtime["completed"] = [key for key in runtime.get("completed", [])
|
||
if _order_of(nodes, key) < target.order_number]
|
||
_save_runtime(instance, runtime)
|
||
return _advance(db, instance, instance.submitter_id, start_from_order=target.order_number - 1)
|
||
|
||
|
||
def _transfer(db: Session, instance: ApprovalInstance, task: ApprovalTask, node: ApprovalNode,
|
||
actor: Any, comment: str, target_ids: list[int]) -> ApprovalInstance:
|
||
if not target_ids:
|
||
raise ApprovalError("target_required", "转办必须指定接手人")
|
||
from ...models import Account
|
||
|
||
targets = db.execute(
|
||
select(Account).where(Account.id.in_(target_ids), Account.is_deleted.is_(False))
|
||
).scalars().all()
|
||
if not targets:
|
||
raise ApprovalError("target_missing", "转办目标不存在或已停用")
|
||
|
||
task.status = TaskStatus.TRANSFERRED
|
||
task.action = Action.TRANSFER
|
||
task.comment = comment
|
||
task.acted_at = datetime.now()
|
||
for account in targets:
|
||
db.add(ApprovalTask(
|
||
instance_id=instance.id, node_key=node.node_key, node_name=node.name,
|
||
sign_type=node.sign_type, assignee_id=account.id,
|
||
assignee_name=account.display_name or account.account,
|
||
origin_assignee_id=actor.id, order_in_node=task.order_in_node, due_at=task.due_at,
|
||
))
|
||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.TRANSFER,
|
||
operator=actor, comment=comment,
|
||
target_names="、".join(a.display_name or a.account for a in targets))
|
||
db.flush()
|
||
return instance
|
||
|
||
|
||
def _add_sign(db: Session, instance: ApprovalInstance, task: ApprovalTask, node: ApprovalNode,
|
||
actor: Any, comment: str, target_ids: list[int]) -> ApprovalInstance:
|
||
"""加签:被加签人也要处理,加签人自己的那条待办保留。"""
|
||
if not target_ids:
|
||
raise ApprovalError("target_required", "加签必须指定人员")
|
||
from ...models import Account
|
||
|
||
targets = db.execute(
|
||
select(Account).where(Account.id.in_(target_ids), Account.is_deleted.is_(False))
|
||
).scalars().all()
|
||
if not targets:
|
||
raise ApprovalError("target_missing", "加签目标不存在或已停用")
|
||
existing = set(db.execute(
|
||
select(ApprovalTask.assignee_id).where(
|
||
ApprovalTask.instance_id == instance.id,
|
||
ApprovalTask.node_key == node.node_key,
|
||
ApprovalTask.status == TaskStatus.PENDING,
|
||
)
|
||
).scalars().all())
|
||
for account in targets:
|
||
if account.id in existing:
|
||
continue
|
||
db.add(ApprovalTask(
|
||
instance_id=instance.id, node_key=node.node_key, node_name=node.name,
|
||
sign_type=SignType.ALL, assignee_id=account.id,
|
||
assignee_name=account.display_name or account.account,
|
||
origin_assignee_id=actor.id, order_in_node=5,
|
||
))
|
||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.ADD_SIGN,
|
||
operator=actor, comment=comment,
|
||
target_names="、".join(a.display_name or a.account for a in targets))
|
||
db.flush()
|
||
return instance
|
||
|
||
|
||
def _finish(db: Session, instance: ApprovalInstance, status: str,
|
||
*, returned_to_initiator: bool = False) -> ApprovalInstance:
|
||
instance.status = status
|
||
instance.finished_at = datetime.now()
|
||
if status == InstanceStatus.APPROVED:
|
||
instance.current_node_key = ""
|
||
instance.current_node_name = "结束"
|
||
_release_revision(db, instance, RevisionStatus.APPROVED)
|
||
elif returned_to_initiator:
|
||
instance.current_node_name = "已退回发起人"
|
||
_release_revision(db, instance, RevisionStatus.REJECTED)
|
||
else:
|
||
_release_revision(db, instance, RevisionStatus.REJECTED)
|
||
runtime = _runtime(instance)
|
||
runtime["returned_to_initiator"] = returned_to_initiator
|
||
_save_runtime(instance, runtime)
|
||
db.flush()
|
||
return instance
|
||
|
||
|
||
def _release_revision(db: Session, instance: ApprovalInstance, status: str) -> None:
|
||
if not instance.revision_id:
|
||
return
|
||
revision = db.get(Revision, instance.revision_id)
|
||
if revision is None:
|
||
return
|
||
revision.status = status
|
||
revision.decided_at = datetime.now()
|
||
|
||
|
||
def sweep_timeouts(db: Session, *, now: datetime | None = None) -> dict[str, int]:
|
||
"""定时任务:超时提醒或自动通过。"""
|
||
now = now or datetime.now()
|
||
tasks = db.execute(
|
||
select(ApprovalTask).where(
|
||
ApprovalTask.status == TaskStatus.PENDING,
|
||
ApprovalTask.due_at.isnot(None),
|
||
ApprovalTask.due_at < now,
|
||
)
|
||
).scalars().all()
|
||
reminded = auto = 0
|
||
for task in tasks:
|
||
instance = db.get(ApprovalInstance, task.instance_id)
|
||
if instance is None or instance.status != InstanceStatus.REVIEWING:
|
||
continue
|
||
node = _node_of(db, instance, task.node_key)
|
||
if node.timeout_action == "remind":
|
||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.TIMEOUT,
|
||
operator_id=None, operator_name="系统", comment=f"{task.assignee_name} 超时未处理,已催办")
|
||
reminded += 1
|
||
elif node.timeout_action == "auto_approve":
|
||
_approve(db, instance, task, node, None, "超时自动通过")
|
||
auto += 1
|
||
db.flush()
|
||
return {"reminded": reminded, "auto_approved": auto}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 小工具
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _order_of(nodes: list[ApprovalNode], key: str) -> int:
|
||
for node in nodes:
|
||
if node.node_key == key:
|
||
return node.order_number
|
||
return 0
|
||
|
||
|
||
def _node_of(db: Session, instance: ApprovalInstance, node_key: str) -> ApprovalNode:
|
||
node = db.execute(
|
||
select(ApprovalNode).where(ApprovalNode.flow_id == instance.flow_id, ApprovalNode.node_key == node_key)
|
||
).scalars().first()
|
||
if node is None:
|
||
raise ApprovalError("flow_broken", f"流程节点 {node_key} 已被删除,请联系管理员")
|
||
return node
|
||
|
||
|
||
def _runtime(instance: ApprovalInstance) -> dict[str, Any]:
|
||
try:
|
||
data = json.loads(instance.runtime_json or "{}")
|
||
except json.JSONDecodeError:
|
||
return {}
|
||
return data if isinstance(data, dict) else {}
|
||
|
||
|
||
def _save_runtime(instance: ApprovalInstance, runtime: dict[str, Any]) -> None:
|
||
instance.runtime_json = json.dumps(runtime, ensure_ascii=False)
|
||
|
||
|
||
def _cancel_siblings(db: Session, instance_id: int, node_key: str, *, keep_id: int) -> None:
|
||
db.execute(
|
||
update(ApprovalTask)
|
||
.where(ApprovalTask.instance_id == instance_id, ApprovalTask.node_key == node_key,
|
||
ApprovalTask.status == TaskStatus.PENDING, ApprovalTask.id != keep_id)
|
||
.values(status=TaskStatus.SKIPPED, acted_at=datetime.now())
|
||
)
|
||
|
||
|
||
def _cancel_pending(db: Session, instance_id: int) -> None:
|
||
db.execute(
|
||
update(ApprovalTask)
|
||
.where(ApprovalTask.instance_id == instance_id, ApprovalTask.status == TaskStatus.PENDING)
|
||
.values(status=TaskStatus.CANCELED, acted_at=datetime.now())
|
||
)
|
||
|
||
|
||
def _fallback_admin(db: Session):
|
||
from ...models import Account, Status
|
||
|
||
return db.execute(
|
||
select(Account).where(Account.is_system_admin.is_(True), Account.is_deleted.is_(False),
|
||
Account.status == Status.ACTIVE).order_by(Account.id).limit(1)
|
||
).scalars().first()
|
||
|
||
|
||
def _names(db: Session, ids: list[int]) -> str:
|
||
from ...models import Account
|
||
|
||
if not ids:
|
||
return ""
|
||
rows = db.execute(select(Account.display_name, Account.account).where(Account.id.in_(ids))).all()
|
||
return "、".join(name or account for name, account in rows)
|
||
|
||
|
||
def _record(db: Session, instance: ApprovalInstance, *, node_key: str, node_name: str, action: str,
|
||
operator: Any = None, operator_id: int | None = None, operator_name: str = "",
|
||
comment: str = "", target_names: str = "", rollback_to: str = "") -> int:
|
||
if operator is not None:
|
||
operator_id = getattr(operator, "id", operator_id)
|
||
operator_name = getattr(operator, "display_name", None) or operator_name or ""
|
||
record = ApprovalRecord(
|
||
instance_id=instance.id,
|
||
project_id=instance.project_id,
|
||
business_module=instance.business_module,
|
||
node_key=node_key,
|
||
node_name=node_name,
|
||
action=action,
|
||
action_label=Action.LABELS.get(action, action),
|
||
operator_id=operator_id,
|
||
operator_name=operator_name,
|
||
target_names=target_names,
|
||
comment=comment,
|
||
rollback_to_node=rollback_to,
|
||
)
|
||
db.add(record)
|
||
db.flush()
|
||
return record.id
|