1855 lines
94 KiB
Python
1855 lines
94 KiB
Python
"""环节审批的对外接口 —— 设计器在环节上「定义接口」,第三方服务端按卡调 OA 的审批按钮。
|
||
|
||
设计见 ``docs/node-open-approve-design.md``。它补的是三条既有通道都够不着的那一段:
|
||
第三方后端不经过任何浏览器、直接对某个环节表态。
|
||
|
||
* **配在环节上,不配在表单字段上**:审批按钮属于流程环节,不属于表单的那一格。发起页嵌着
|
||
ERP 的页面、审批的是后面的「财务复核」环,接口就该配在「财务复核」上。
|
||
* **凭据不加新东西**:开放平台那条访问令牌(``task:write``)。细粒度的门由环节的
|
||
开关与应用白名单承担,再发一把「环节专用钥匙」只会两套密钥各漂一份。
|
||
* **出口不由第三方指定**:它只能表达三种结论(同意 / 不同意 / 提交),OA 按这一环真实存在
|
||
的出口做最长匹配——复用嵌入回写那套 :func:`embed_session.decision_kind` /
|
||
:func:`embed_session.match_route`,两头的判据必须是同一把尺,宁可在改图后当场报错,
|
||
也不静默走错分支。
|
||
|
||
本模块是纯判定层:配置合并、发布前体检、接口卡片、字段筛与意见渲染都在这里,
|
||
端点(``api/openapi.py``)与事件信封(``engine._notify_task``)都从这里取值。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from datetime import datetime, timedelta
|
||
from types import SimpleNamespace
|
||
from typing import Any, Iterable
|
||
|
||
from sqlalchemy import or_, select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import dbconfig, models
|
||
from ..envelope import bad_request
|
||
from . import autofill, embed_session, numbering, openauth, quota, threshold
|
||
|
||
#: 环节配置里的键名(设计器与库同一份)
|
||
CONFIG_KEY = "openApprove"
|
||
#: 流程级默认档的列名
|
||
PROCESS_KEY = "open_approve"
|
||
|
||
#: 表态的三种结论:与嵌入回写同一份清单,不另立
|
||
DECISIONS = embed_session.DECISIONS
|
||
DECISION_LABELS = embed_session.DECISION_LABELS
|
||
|
||
#: 确认模式:confirm = 备好待处理人点头(默认);auto = 当场办掉
|
||
CONFIRM_MODES = ("confirm", "auto")
|
||
|
||
#: 端点地址里那一段的写法:放的是**流程编号**(单子上印的那个号),不是内部 id。
|
||
#: 设计期还没有单据可填,卡片上就留这个占位;事件信封与定位都带着真单过来,填真号。
|
||
WORK_REF_PLACEHOLDER = "{流程编号}"
|
||
|
||
#: 意见模板只认这两个占位:多一个占位就多一种解析歧义
|
||
_PLACEHOLDER = re.compile(r"\{([^{}]*)\}")
|
||
|
||
|
||
# --------------------------------------------------------------------------- 配置合并
|
||
|
||
|
||
def node_config_of(config: dict | None) -> dict:
|
||
"""环节整份 ``config`` 里那格 ``openApprove``;形状不对一律当没配。
|
||
|
||
生效的那一份**只有这一格**——拿整份 ``config`` 去判 ``enabled`` 会永远判成假
|
||
(``enabled`` 在 ``openApprove`` 底下,不在顶层),不报错,只是横幅再也不亮。
|
||
"""
|
||
value = (config or {}).get(CONFIG_KEY)
|
||
return dict(value) if isinstance(value, dict) else {}
|
||
|
||
|
||
def node_config(activity: models.Activity | None) -> dict:
|
||
"""环节上那份 ``config.openApprove``;没有就是空档。"""
|
||
if activity is None:
|
||
return {}
|
||
return node_config_of(activity.config or {})
|
||
|
||
|
||
#: 「流程那一侧」的两种来源:实库那行 ``models.Process``(引擎判定、锁状态那几条),
|
||
#: 或命中设计缓存时手上仅有的那份 ``ProcessDefinition``(详情页报文)——两边带着同一份
|
||
#: ``open_approve``,所以合并口径只有一把尺。
|
||
ProcessLike = Any
|
||
|
||
|
||
def process_defaults(process: ProcessLike | None) -> dict:
|
||
"""流程级默认档;没有就是空档。"""
|
||
value = getattr(process, PROCESS_KEY, None) if process is not None else None
|
||
return dict(value) if isinstance(value, dict) else {}
|
||
|
||
|
||
def merge_defaults(process_level: dict | None, node_level: dict | None) -> dict:
|
||
"""两份配置合成生效的那一份:流程默认打底,环节显式配置逐键覆盖。"""
|
||
merged = dict(process_level or {})
|
||
merged.update(node_level or {})
|
||
return merged
|
||
|
||
|
||
def effective_config(process: ProcessLike | None, activity: models.Activity | Any | None) -> dict:
|
||
"""环节这一环**实际生效**的配置:流程默认打底,环节显式配置逐键覆盖。
|
||
|
||
口径与 ``approval_config`` 一致(``dedupAhead`` 那套):环节写了哪个键就认哪个键,
|
||
没写的键继承流程默认。所以「流程默认开着、这一环显式关掉」是真的关,
|
||
不是被默认档又翻回来。合并这一步只有 :func:`merge_defaults` 一处。
|
||
"""
|
||
return merge_defaults(process_defaults(process), node_config(activity))
|
||
|
||
|
||
def is_enabled(config: dict | None) -> bool:
|
||
return bool((config or {}).get("enabled"))
|
||
|
||
|
||
def confirm_mode(config: dict | None) -> str:
|
||
mode = str((config or {}).get("confirm") or "confirm").strip().lower()
|
||
return mode if mode in CONFIRM_MODES else "confirm"
|
||
|
||
|
||
def allowed_apps(config: dict | None) -> list[str]:
|
||
"""空表与填表是两种口径:空 = 任何持 task:write 的应用,非空 = 只认名单。"""
|
||
value = (config or {}).get("apps")
|
||
if not isinstance(value, list):
|
||
return []
|
||
return [str(item).strip() for item in value if str(item or "").strip()]
|
||
|
||
|
||
#: 开始环节那一档:这一环还没有单据时,第三方这一次表态就**替发起人发起并提交**。
|
||
#: 判据与落点在 ``api/openapi._begin_start_from_decide``,设计见 docs/node-open-approve-design.md §4.6.2
|
||
AUTO_START_KEY = "autoStart"
|
||
|
||
|
||
def auto_start_enabled(config: dict | None) -> bool:
|
||
"""「没有单据时代为发起」开没开。默认**关**。
|
||
|
||
开着它,"OA 认不出这张单"就不再是一句拒绝,而是一次代发。这件事的代价要摊开说:
|
||
号抄错的那个下午,库里会多出一张没人填过的单。所以这一档让设计者自己勾,
|
||
不由引擎替他决定——与 :data:`LOCK_KEY` 那一层"通道闸不是能力开关"同一分寸。
|
||
"""
|
||
value = (config or {}).get(AUTO_START_KEY)
|
||
if isinstance(value, bool):
|
||
return value
|
||
return str(value or "").strip().lower() in {"1", "true", "yes", "on"}
|
||
|
||
|
||
def decisions_map(config: dict | None) -> dict[str, str]:
|
||
value = (config or {}).get("decisions")
|
||
if not isinstance(value, dict):
|
||
return {}
|
||
# 键与值都归一化:decision_kind 按小写查表,键不归一永远查不中;
|
||
# 值归一成三种结论,配歪的(映到出口名那种)在发布体检里点名
|
||
return {str(key).strip().casefold(): str(val).strip().casefold()
|
||
for key, val in value.items() if str(key).strip()}
|
||
|
||
|
||
def sample_result_word(config: dict | None, *, activity: Any | bool = False) -> str:
|
||
"""卡片样例里那格 ``result`` 填哪个词:这一环真认得的那个。
|
||
|
||
``activity`` 为真(或直接给开始环节那一环)时只挑**翻得出「提交」**的词——开始环节
|
||
只有那一颗钮,给个 agree 出去的样例本身就是一次 400。优先念配置里原始那个写法
|
||
(对方要照抄的是自己发的那种大小写),没配过就退回内置写法。
|
||
"""
|
||
want_submit = activity is True or str(getattr(activity, "type", "") or "") == "begin"
|
||
raw = (config or {}).get("decisions")
|
||
words = raw if isinstance(raw, dict) else {}
|
||
if want_submit:
|
||
wanted = "submit"
|
||
else:
|
||
wanted = "agree"
|
||
for word, kind in words.items():
|
||
if str(kind).strip().casefold() == wanted and str(word).strip():
|
||
return str(word).strip()
|
||
# 表里没有现成的:拿内置写法。没配对照表时这三个词本来就直接命中
|
||
return "SUBMITTED" if want_submit else "APPROVED"
|
||
|
||
|
||
def routes_map(config: dict | None) -> dict[str, str]:
|
||
"""这一环把每种结论**钉**到哪条出口上:``{agree: "同意", refuse: "退回修改", submit: "提交"}``。
|
||
|
||
钉住的意思是:第三方说「驳回」,这一环就必然走「退回修改」那条线回到它指着的那一步——
|
||
不再靠出口名猜。配置它的人(OA 设计者)比第三方更清楚这一环驳回该落到哪一步;
|
||
没钉的结论仍走 :func:`embed_session.match_route` 的按名匹配,两档不冲突。
|
||
"""
|
||
value = (config or {}).get("routes")
|
||
if not isinstance(value, dict):
|
||
return {}
|
||
return {str(key).strip().lower(): str(val).strip()
|
||
for key, val in value.items() if str(key).strip() and str(val).strip()}
|
||
|
||
|
||
def opinion_templates(config: dict | None) -> dict[str, str]:
|
||
value = (config or {}).get("opinion")
|
||
if not isinstance(value, dict):
|
||
return {}
|
||
return {str(key).strip().lower(): str(val) for key, val in value.items() if str(val or "").strip()}
|
||
|
||
|
||
# --------------------------------------------------------------------------- OA 按钮锁定
|
||
#
|
||
# 上面那一层解决的是「第三方按得动 OA 的审批按钮」,这一层管的是**另一侧**:表态既然
|
||
# 交出去了,OA 界面里那几颗钮(提交 / 审批 / 退回 / 撤回)就不该还点得动——两边各批一遍,
|
||
# 第三方那条 ``bizKey`` 回来撞上 ``alreadyHandled``,两边的账从此对不上。
|
||
# 设计见 ``docs/node-oa-lock-design.md``。
|
||
#
|
||
# 三条分寸与外面那一层同源:锁是**通道闸**不是能力开关(外部那三条路一律不受影响)、
|
||
# 判据只在引擎一处(靠界面少放一颗按钮不叫闸)、锁不制造死角(每处都说清去哪儿办,
|
||
# 兜底留给流程监控的干预面板)。
|
||
|
||
#: ``openApprove`` 底下那一段的键名
|
||
LOCK_KEY = "oaLock"
|
||
|
||
#: 认得的六颗钮。``handle`` / ``start`` / ``goBack`` / ``recall`` 是表态那几颗,
|
||
#: ``addTask`` / ``transfer`` 只是把待办挪到别人手上,默认不锁
|
||
LOCK_ACTIONS = ("handle", "start", "goBack", "recall", "addTask", "transfer")
|
||
#: 默认锁的正是表态那四颗:勾这个开关的人要说的是一句话,不是六次点击
|
||
LOCK_ACTIONS_DEFAULT = ("handle", "start", "goBack", "recall")
|
||
#: 每颗钮在界面上的动词,挡住时那句话用它
|
||
LOCK_VERBS = {
|
||
"handle": "表态",
|
||
"start": "提交",
|
||
"goBack": "退回",
|
||
"recall": "撤回",
|
||
"addTask": "加签",
|
||
"transfer": "转办",
|
||
}
|
||
|
||
#: 开始环节只有一颗钮:**提交**。``handle``(处理面板上按出口提交)与 ``start``
|
||
#: (停在开始环节那一单的提交,以及发起页那颗「发起」)在这一环说的是同一件事,
|
||
#: 勾了其中一颗就算两颗都勾了——否则「退回发起人」那一单与发起页就成了彼此的漏洞:
|
||
#: 同一颗钮,一条路挡住、另一条没挡住,人只会觉得这锁时灵时不灵。
|
||
BEGIN_SUBMIT_ACTIONS = ("handle", "start")
|
||
|
||
#: 谁来按这颗钮:与 ``engine.VIA_*`` 同值。默认 ``oa`` = OA 界面,认锁(fail-safe:
|
||
#: 新调用方漏传就是「锁住」这一边);外部三条通道显式改口,不受锁影响。
|
||
VIA_OA = "oa"
|
||
VIA_OA_CONFIRM = "oa_confirm"
|
||
VIA_OPEN = "open"
|
||
VIA_EMBED = "embed"
|
||
#: 只有 OA 界面那两条通道认锁
|
||
OA_VIAS = (VIA_OA, VIA_OA_CONFIRM)
|
||
|
||
|
||
def lock_of(config: dict | None) -> dict:
|
||
"""这一段配的 ``oaLock``;形状不对一律当没配(脏配置不该把整条审批页拖崩)。"""
|
||
value = (config or {}).get(LOCK_KEY)
|
||
return dict(value) if isinstance(value, dict) else {}
|
||
|
||
|
||
def allow_confirm(config: dict | None) -> bool:
|
||
"""第三方备好的表态还要不要在 OA 里点头。默认要——``confirm`` 模式本来就靠它落地。"""
|
||
return bool(lock_of(config).get("allowConfirm", True))
|
||
|
||
|
||
def lock_enabled(config: dict | None) -> bool:
|
||
"""锁只在这一环真开了外部审批时才有意义:没开外部审批的锁算没开(发布时点名)。"""
|
||
return is_enabled(config) and bool(lock_of(config).get("enabled"))
|
||
|
||
|
||
def locked_actions(config: dict | None) -> tuple[str, ...]:
|
||
"""这一环锁了哪几颗。**空 = 默认那一组**,不是「一颗都不锁」——设计器会把勾了的
|
||
显式写出来,空值只可能来自手改 JSON 或 API 直配,那种场合按「交给外部了」理解。"""
|
||
value = lock_of(config).get("actions")
|
||
if not isinstance(value, list):
|
||
return LOCK_ACTIONS_DEFAULT
|
||
picked = tuple(dict.fromkeys(
|
||
str(item).strip() for item in value if str(item).strip() in LOCK_ACTIONS
|
||
))
|
||
return picked or LOCK_ACTIONS_DEFAULT
|
||
|
||
|
||
def locks_action(config: dict | None, action: str, *, activity_type: str = "") -> bool:
|
||
"""这一环锁没锁这颗钮。
|
||
|
||
开始环节上 ``handle`` 与 ``start`` 是同一颗「提交」(见 :data:`BEGIN_SUBMIT_ACTIONS`),
|
||
勾了任一颗就算两颗都锁上;别的环节各管各的。
|
||
"""
|
||
picked = set(locked_actions(config))
|
||
if action in picked:
|
||
return True
|
||
return (activity_type == "begin" and action in BEGIN_SUBMIT_ACTIONS
|
||
and bool(picked & set(BEGIN_SUBMIT_ACTIONS)))
|
||
|
||
|
||
def app_names(db: Session, codes: Iterable[str]) -> dict[str, str]:
|
||
"""应用编码 → 应用名。那句「去哪儿办」报一串编码没人看得懂。"""
|
||
wanted = {str(code).strip() for code in codes if str(code or "").strip()}
|
||
if not wanted:
|
||
return {}
|
||
rows = db.execute(
|
||
select(models.OpenApp.code, models.OpenApp.name).where(models.OpenApp.code.in_(wanted))
|
||
).all()
|
||
return {str(code): str(name or "").strip()
|
||
for code, name in rows if str(name or "").strip()}
|
||
|
||
|
||
def names_for(db: Session, configs: Iterable[dict | None]) -> dict[str, str]:
|
||
"""一批外部审批配置里出现过的应用编码,一次查库翻成名字(逐环节算那句说明用)。"""
|
||
codes: set[str] = set()
|
||
for config in configs:
|
||
codes.update(allowed_apps(config))
|
||
return app_names(db, codes)
|
||
|
||
|
||
def lock_where(config: dict | None, *, names: dict[str, str] | None = None) -> str:
|
||
"""这一环的表态在哪儿发生:署名前缀 → 白名单里那个应用的名字 → 「外部系统」。"""
|
||
note = str((config or {}).get("note") or "").strip()
|
||
if note:
|
||
return note
|
||
for code in allowed_apps(config):
|
||
name = str((names or {}).get(code) or "").strip()
|
||
if name:
|
||
return name
|
||
return "外部系统"
|
||
|
||
|
||
def lock_text(config: dict | None, *, names: dict[str, str] | None = None) -> str:
|
||
"""给人看的那句横幅。``text`` 空就按 ``where`` 自动拼:口径只在后端这一处,
|
||
前端不再推第二遍(``gate`` 那两处为了逐字对齐要盯两个文件,这里一份就够)。"""
|
||
custom = str(lock_of(config).get("text") or "").strip()
|
||
if custom:
|
||
return custom
|
||
return f"这一环的审批在 {lock_where(config, names=names)} 里进行,OA 里只读。"
|
||
|
||
|
||
def lock_view(
|
||
config: dict | None, *, names: dict[str, str] | None = None, activity_type: str = ""
|
||
) -> dict:
|
||
"""随环节简报一起回的那一块:锁没锁、锁了哪几颗、去哪儿办、那句说明。
|
||
|
||
``actions`` 给的是**运行时口径**,不是配置原文:开始环节上 ``handle`` 与 ``start``
|
||
是同一颗「提交」,勾了任一颗这里就回两颗(见 :data:`BEGIN_SUBMIT_ACTIONS`)。
|
||
界面照这一格置灰按钮,它不必自己再推一遍。
|
||
"""
|
||
on = lock_enabled(config)
|
||
picked = set(locked_actions(config)) if on else set()
|
||
if on and activity_type == "begin" and picked & set(BEGIN_SUBMIT_ACTIONS):
|
||
picked |= set(BEGIN_SUBMIT_ACTIONS)
|
||
return {
|
||
"locked": on,
|
||
"actions": [item for item in LOCK_ACTIONS if item in picked],
|
||
"allowConfirm": allow_confirm(config),
|
||
"where": lock_where(config, names=names),
|
||
"text": lock_text(config, names=names),
|
||
}
|
||
|
||
|
||
def lock_block(
|
||
config: dict | None,
|
||
*,
|
||
action: str,
|
||
via: str,
|
||
activity_name: str = "",
|
||
names: dict[str, str] | None = None,
|
||
starting: bool = False,
|
||
activity_type: str = "",
|
||
) -> str:
|
||
"""这颗钮此刻点不点得动:点得动回空串,点不动回那句给人看的话。纯函数,不连库。
|
||
|
||
``via`` 是外部通道(``open`` / ``embed``)时永远放行——那三条路本来就是交出去的
|
||
那一半表态;``oa_confirm`` 认的是 ``allowConfirm`` 那一栏,不是 ``actions``。
|
||
|
||
``starting`` 只改说法不改判据:同一颗 ``start``,按在**还没建出来的那张单**上就是
|
||
发起页那颗「发起」(按下去=建单+提交一起),按在**已经停在开始环节的那一单**上
|
||
才是「提交」。两句要分开写——对着一个还不存在的单说"这张单还停在开始环节",
|
||
听话的人只会回头去找那张单。
|
||
|
||
``activity_type`` 只为开始环节那一颗「提交」而存在:那一环上 ``handle`` 与 ``start``
|
||
算同一颗钮(见 :data:`BEGIN_SUBMIT_ACTIONS`)。
|
||
"""
|
||
if via not in OA_VIAS or not lock_enabled(config):
|
||
return ""
|
||
place = lock_where(config, names=names)
|
||
name = f"「{activity_name}」" if activity_name else ""
|
||
if via == VIA_OA_CONFIRM:
|
||
if allow_confirm(config):
|
||
return ""
|
||
return (f"环节{name}的外部审批关掉了「外部表态仍可在 OA 确认」,这条横幅本来不该出现。"
|
||
f"请到 {place} 里看这一环的结论;要人在 OA 里点头,就把确认模式改成自动办理。")
|
||
if not locks_action(config, action, activity_type=activity_type):
|
||
return ""
|
||
if activity_type == "begin" and action in BEGIN_SUBMIT_ACTIONS:
|
||
action = "start" # 这一环上它就叫「提交」,句子照这一颗说
|
||
verb = LOCK_VERBS.get(action, "表态")
|
||
if action == "start":
|
||
if starting:
|
||
return (f"开始环节{name}的提交已交给外部系统({place}),OA 里发起不了——"
|
||
f"「发起」按的就是那一颗「提交」。请到 {place} 里发起这张单。")
|
||
return (f"这张单还停在开始环节{name},提交这件事已交给外部系统({place}),OA 里提交不了。"
|
||
f"请到 {place} 里提交这张单;需要 OA 这边改动,请到流程监控里干预。")
|
||
return (f"环节{name}的审批已交给外部系统({place}),OA 里不能{verb}。"
|
||
f"请到 {place} 里办理;需要 OA 这边改动,请到流程监控里干预。")
|
||
|
||
|
||
def check(
|
||
db: Session, process_id: str, activity, *, action: str, via: str = VIA_OA,
|
||
process: object = None, starting: bool = False
|
||
) -> str:
|
||
"""这一环的通道闸:判一次,回给人看的那句话(空串 = 放行)。
|
||
|
||
``activity`` 与 ``process`` 是谁**由调用方决定**,这一句自己不再回库猜:引擎那条路交上来
|
||
的是这张单出发时那一版(:func:`app.engine.definition.for_work` 的冻结定义 + 它身上的环节
|
||
节点),于是中途改图改不到一张在走的单;界面侧的展示(详情页那几颗钮)仍按实库那行算,
|
||
说的也是"设计现在长这样"。两个都不传(``process=None`` 且 ``process_id`` 为空)就当没配。
|
||
|
||
抛什么异常交给调用方:引擎抛 ``EngineError`` 收成 400,界面把同一句摆成横幅,
|
||
两边读的是同一把尺。
|
||
"""
|
||
if via not in OA_VIAS:
|
||
return ""
|
||
if process is None:
|
||
process = db.get(models.Process, process_id) if process_id else None
|
||
config = effective_config(process, activity)
|
||
if not lock_enabled(config):
|
||
return ""
|
||
return lock_block(config, action=action, via=via,
|
||
activity_name=str(getattr(activity, "name", "") or ""),
|
||
names=names_for(db, [config]), starting=starting,
|
||
activity_type=str(getattr(activity, "type", "") or ""))
|
||
|
||
|
||
def lock_problems(config: dict | None, *, activity=None) -> list[str]:
|
||
"""锁上之后把自己锁死的配法(不带环节名那半句,调用方自己加前缀)。
|
||
|
||
只认「表态那一颗被锁掉」的环节:没锁 ``handle`` / ``start`` 时 OA 里还有人办得动,
|
||
下面那两条死路都不成立。
|
||
"""
|
||
if not lock_enabled(config):
|
||
return []
|
||
begin = str(getattr(activity, "type", "") or "") == "begin"
|
||
action = "start" if begin else "handle"
|
||
if not locks_action(config, action, activity_type=str(getattr(activity, "type", "") or "")):
|
||
return []
|
||
verb = LOCK_VERBS[action]
|
||
out: list[str] = []
|
||
if confirm_mode(config) == "confirm" and not allow_confirm(config):
|
||
out.append(f"锁掉了{verb},又关掉了「外部表态仍可在 OA 确认」:"
|
||
"第三方备好的表态在 OA 里没人能点头(要么把确认模式改成自动办理,要么留着那句确认)")
|
||
if not decisions_map(config):
|
||
out.append(f"锁掉了{verb},却一个「对方词 → 结论」都没配:这一环没有任何表态通路")
|
||
return out
|
||
|
||
|
||
def lock_states_for_process(db: Session, process_id: str) -> dict[str, dict]:
|
||
"""一条流程上每个环节**此刻**的锁状态:详情页逐环节标 ``oa_lock`` 用,一次查库。
|
||
|
||
读的是实库那行环节配置与流程默认档,**不是**单据冻结的那一版设计:这一格是闸口不是
|
||
图纸,管理员当场把外部审批关掉,详情页那句「这一环的审批在外部系统里进行」就得当场
|
||
不出现,否则界面拦着人、引擎却还收得住(判据同 :func:`check`)。
|
||
环节配置与流程默认档只在这里各取一列,合并仍走 :func:`merge_defaults` 那一把尺。
|
||
形状与 :func:`lock_view` 一字不差。
|
||
"""
|
||
if not process_id:
|
||
return {}
|
||
rows = db.execute(
|
||
select(models.Activity.id, models.Activity.type, models.Activity.config,
|
||
models.Process.open_approve)
|
||
.join(models.Process, models.Process.id == models.Activity.process)
|
||
.where(models.Activity.process == process_id)
|
||
).all()
|
||
if not rows:
|
||
return {}
|
||
configs = {str(aid): merge_defaults(process_level, node_config_of(node_cfg))
|
||
for aid, _kind, node_cfg, process_level in rows}
|
||
names = names_for(db, configs.values())
|
||
return {
|
||
str(aid): lock_view(configs[str(aid)], names=names, activity_type=str(kind or ""))
|
||
for aid, kind, _cfg, _level in rows
|
||
}
|
||
|
||
|
||
def lock_flags(db: Session, pairs: Iterable[tuple[str, str]]) -> dict[tuple[str, str], dict]:
|
||
"""一批(流程 id, 环节 id)的锁状态:列表页逐行标注用,一次查库。
|
||
|
||
判据与 :func:`check` 同一条,``blockers`` 里按动作各存一句——已办列表要的
|
||
「这一环的审批在外部系统,OA 里不能撤回」就是从这儿取的。
|
||
"""
|
||
needed = {(str(process or ""), str(activity or "")) for process, activity in pairs if str(activity or "")}
|
||
if not needed:
|
||
return {}
|
||
activity_ids = {activity_id for _, activity_id in needed}
|
||
process_ids = {process_id for process_id, _ in needed if process_id}
|
||
activities = {
|
||
row.id: row for row in db.execute(
|
||
select(models.Activity).where(models.Activity.id.in_(activity_ids))
|
||
).scalars().all()
|
||
}
|
||
processes: dict[str, models.Process] = {}
|
||
if process_ids:
|
||
processes = {
|
||
row.id: row for row in db.execute(
|
||
select(models.Process).where(models.Process.id.in_(process_ids))
|
||
).scalars().all()
|
||
}
|
||
names = names_for(db, [effective_config(processes.get(key[0]), activities.get(key[1]))
|
||
for key in needed])
|
||
out: dict[tuple[str, str], dict] = {}
|
||
for key in needed:
|
||
activity = activities.get(key[1])
|
||
config = effective_config(processes.get(key[0]), activity)
|
||
kind = str(getattr(activity, "type", "") or "")
|
||
view = lock_view(config, names=names, activity_type=kind)
|
||
who = str(getattr(activity, "name", "") or "")
|
||
view["blockers"] = {
|
||
action: lock_block(config, action=action, via=VIA_OA, activity_name=who, names=names,
|
||
activity_type=kind)
|
||
for action in view["actions"]
|
||
}
|
||
out[key] = view
|
||
return out
|
||
|
||
|
||
# --------------------------------------------------------------------------- 开始环节专用判据
|
||
|
||
|
||
def begin_problems(config: dict | None) -> list[str]:
|
||
"""开始环节的表态只有一颗钮:**提交**。映到同意 / 不同意、钉到同意 / 不同意出口的
|
||
配置在这里没有落点,点名出来(不带环节名的那半句,调用方自己加名前缀)。
|
||
|
||
不在 DECISIONS 里的词不在此重复点名——通用那把尺已经报过「只能映到三种结论」,
|
||
同一处报两遍只会把真正的错冲淡。
|
||
"""
|
||
out: list[str] = []
|
||
for word, kind in decisions_map(config).items():
|
||
normalized = str(kind).strip().lower()
|
||
if normalized in DECISIONS and normalized != "submit":
|
||
out.append(f"决策词「{word}」映到「{kind}」没有可走的出口")
|
||
for kind in routes_map(config):
|
||
if kind in DECISIONS and kind != "submit":
|
||
out.append(f"出口钉配「{DECISION_LABELS.get(kind, kind)}」没有可钉的出口")
|
||
return out
|
||
|
||
|
||
# --------------------------------------------------------------------------- 发布前体检
|
||
|
||
|
||
def process_id_of(process: models.Process | None, activity: models.Activity | None) -> str:
|
||
"""这一环挂在哪条流程下。
|
||
|
||
优先认调用方递进来的 ``process``:环节有两种来路,保存流程时是库里的 ORM 行(有
|
||
``process`` 这一列),发布校验时是设计稿节点
|
||
(:class:`app.engine.definition.ActivityNode`,身上没有这一列)。直接摸环节的属性
|
||
在后一种来路上会抛 ``AttributeError``,把整次校验打成 500。
|
||
"""
|
||
return str(getattr(process, "id", "") or "") or str(getattr(activity, "process", "") or "")
|
||
|
||
|
||
def form_id_of(process: models.Process | None, activity: models.Activity | None) -> str:
|
||
"""这一环用的那张表单:环节自己绑的优先,没绑沿用流程默认表单。与引擎取表单同口径。"""
|
||
if activity is not None and str(activity.form or "").strip():
|
||
return str(activity.form).strip()
|
||
if process is not None and str(process.latest_form or "").strip():
|
||
return str(process.latest_form).strip()
|
||
return ""
|
||
|
||
|
||
def _guarded_keys(fields: list[dict]) -> dict[str, str]:
|
||
"""挂阈值 / 额度的字段 → 它挂的是什么。这些格子改的是审批走向,外部表态一律拒收。"""
|
||
out: dict[str, str] = {}
|
||
for item, _cfg in threshold.threshold_fields(fields):
|
||
out[str(item.get("key") or "")] = "阈值"
|
||
for item, _cfg in quota.quota_fields(fields):
|
||
out.setdefault(str(item.get("key") or ""), "额度")
|
||
return out
|
||
|
||
|
||
def problems(db: Session, process: models.Process | None, activity: models.Activity | None) -> list[str]:
|
||
"""这一环的外部审批配置有没有配错:发布时点名,别让流程走到那一环才发现。
|
||
|
||
只体检「开着」的配置:关着的环节什么都不会发生,报它反而把真正的错冲淡。
|
||
"""
|
||
config = effective_config(process, activity)
|
||
if not is_enabled(config):
|
||
# 没开外部审批却把锁打开:这一环既没人能办、也没有外部通道,配了等于自己堵死自己
|
||
if lock_of(config).get("enabled"):
|
||
return [f"环节「{activity.name if activity is not None else ''}」"
|
||
"没开外部审批却打开了 OA 按钮锁定:锁上之后这一环没人办得动"]
|
||
return []
|
||
out: list[str] = []
|
||
name = activity.name if activity is not None else ""
|
||
out.extend(f"环节「{name}」{item}" for item in lock_problems(config, activity=activity))
|
||
|
||
for word, kind in decisions_map(config).items():
|
||
if str(kind).strip().lower() not in DECISIONS:
|
||
out.append(
|
||
f"环节「{name}」决策词「{word}」只能映到 agree / refuse / submit,现在是「{kind}」"
|
||
)
|
||
|
||
# 开始环节的表态只有一颗钮:提交。映到同意 / 不同意、钉到同意 / 不同意出口的词,
|
||
# 在开始环节没有可落的地方——发布时就点名,别让第三方第一次调用才撞上「无解」。
|
||
if activity is not None and activity.type == "begin":
|
||
out.extend(f"环节「{name}」是开始环节,第三方在这里只能提交单据:{item}"
|
||
for item in begin_problems(config))
|
||
elif auto_start_enabled(config):
|
||
out.append(f"环节「{name}」不是开始环节,勾了「没有单据时代为发起」也不会生效"
|
||
"(那颗钮只有开始环节有)")
|
||
|
||
fields = autofill.form_fields(db, form_id_of(process, activity))
|
||
known = {str(item.get("key") or "") for item in fields}
|
||
guarded = _guarded_keys(fields)
|
||
value = config.get("fields")
|
||
keys = [str(item).strip() for item in value if str(item or "").strip()] if isinstance(value, list) else []
|
||
for key in keys:
|
||
if key not in known:
|
||
out.append(f"环节「{name}」可写字段 {key} 不在这张表单里")
|
||
elif key in guarded:
|
||
out.append(f"环节「{name}」字段 {key} 挂了{guarded[key]},挂审批走向的格子不收外部写")
|
||
|
||
for kind, template in opinion_templates(config).items():
|
||
if kind not in DECISIONS:
|
||
out.append(f"环节「{name}」意见模板「{kind}」不是认识的结论(agree / refuse / submit)")
|
||
continue
|
||
for match in _PLACEHOLDER.finditer(template):
|
||
token = str(match.group(1) or "").strip()
|
||
if token != "serial" and not (token.startswith("form.") and token[5:].strip()):
|
||
out.append(f"环节「{name}」意见模板只认 {{serial}} 与 {{form.字段名}},「{{{token}}}」不在其列")
|
||
|
||
# 钉住的出口必须真在这一环的出线上:钉到一条不存在的线上,等于给第三方写了一张
|
||
# 永远兑不了的票——保存时点名,别等第一次调用才撞上「出口不存在」。
|
||
if activity is not None:
|
||
# 流程编号只从 process 拿(见 process_id_of);环节 id 本身全局唯一,
|
||
# 认不出归属流程时至少还能按环节查,不至于把真实存在的出口报成「没有这条出口」。
|
||
stmt = select(models.Route.name).where(models.Route.from_activity == activity.id)
|
||
pid = process_id_of(process, activity)
|
||
if pid:
|
||
stmt = stmt.where(models.Route.process == pid)
|
||
names = set(db.execute(stmt).scalars().all())
|
||
for kind, wanted in routes_map(config).items():
|
||
if kind not in DECISIONS:
|
||
out.append(f"环节「{name}」出口钉配「{kind}」不是认识的结论(agree / refuse / submit)")
|
||
elif wanted not in names:
|
||
out.append(f"环节「{name}」把「{DECISION_LABELS.get(kind, kind)}」钉到出口「{wanted}」,这一环没有这条出口(现有:{'、'.join(sorted(names)) or '无'})")
|
||
return out
|
||
|
||
|
||
# --------------------------------------------------------------------------- 接口卡片
|
||
|
||
|
||
def interface_path(work_ref: str, activity_id: str) -> str:
|
||
"""这一环那条端点的**主写法**:单号与环节 id 各占一段,两段都由对方现取。
|
||
|
||
第一段放**流程编号**(单子上印的那个号),不是流程定义的内部 id——对方手里有的是
|
||
前者,``oa_process.id`` 那种 32 位内部号他们既拿不到也不该去抄。第二段环节 id 是
|
||
**参数**而不是常量:卡片、事件信封、``locate`` 每次都把当前那一环递出去,对方照抄
|
||
那一个值即可。于是删掉重拖出新环节、串行流程中途加一个也开了接口的环节,都不会把
|
||
结论落到隔壁环头上,也不会让一条抄死的地址悬在半空。设计期没有单据,
|
||
单号那一段留 :data:`WORK_REF_PLACEHOLDER` 占位。
|
||
"""
|
||
return f"POST /api/v1/open/nodes/{str(work_ref or '').strip() or WORK_REF_PLACEHOLDER}/{activity_id}/decide"
|
||
|
||
|
||
def interface_path_current(work_ref: str) -> str:
|
||
"""主写法的省事版(挂在 ``alt`` 上):地址里只写这张单的号,环节由 OA 认。
|
||
|
||
少传一段的代价是"哪一环"改由 OA 在**调用那一刻**决定:按这张单此刻停着的那几一环
|
||
找,只有唯一一环开着审批接口、且对当前应用开口,才替它按下那颗钮;不止一环就回候选,
|
||
让对方改用 :func:`interface_path` 点名——赌错一环就办到另一环头上,这一把不值得赌。
|
||
另一条口径也要对接方知道:报文晚到时单子可能已经流到下一个同样开了接口的环节,
|
||
这一次表态就落在那一环上(幂等按环节记,换个环节不算重复)。所以主写法仍是点名环节那条。
|
||
"""
|
||
return f"POST /api/v1/open/nodes/{str(work_ref or '').strip() or WORK_REF_PLACEHOLDER}/decide"
|
||
|
||
|
||
#: 第三方对接外部审批要用的**全套**接口:卡片里那一栏、事件与定位递出的那份、对接文档
|
||
#: 里的清单,都从这一处生成。只写 decide 一条是不够的——对方拿到地址还得知道令牌去哪换、
|
||
#: 单号与 activityId 去哪取、反悔了走哪条,缺一样就得回来问一次。
|
||
#: 顺序就是动手顺序:换令牌 → 取参数 → 按那颗钮 → 收尾对账。``scope`` 为空的那条
|
||
#: 是换令牌本身,它还不需要令牌。
|
||
THIRD_PARTY_APIS: tuple[dict, ...] = (
|
||
{"method": "POST", "path": "/api/v1/open/token", "scope": "",
|
||
"when": "先用 app_key / app_secret 换访问令牌,下面每一条都要带上它;临期重取(有效期看响应 expiresIn)"},
|
||
{"method": "POST", "path": "/api/v1/open/nodes/locate", "scope": "task:read",
|
||
"when": "不订阅事件时用它取参数:拿单号或查找字段,回这张单当前停在哪个流程哪个环节"
|
||
"(默认这份很轻;带 \"detail\": \"full\" 才连这张卡片与全套清单一起回)"},
|
||
{"method": "GET", "path": "/api/v1/open/tasks?identity={身份}", "scope": "task:read",
|
||
"when": "查某个人的待办;这一环是会签(多条未办待办)时,用它点名替哪一条表态"},
|
||
{"method": "POST", "path": "/api/v1/open/works", "scope": "work:write",
|
||
"when": "这张单由第三方发起时才用;响应里的 work.serial 就是地址上那一段流程编号"},
|
||
{"method": "GET", "path": "/api/v1/open/works/{job}", "scope": "work:read",
|
||
"when": "查这张单的流转与审批记录,两边对账;响应里的 handled[].id 就是撤回已办要点的那个号"},
|
||
{"method": "POST", "path": "/api/v1/open/works/{job}/terminate", "scope": "work:write",
|
||
"when": "第三方那边作废了这张单,同步到 OA 终止"},
|
||
{"method": "POST", "path": "/api/v1/open/tasks/completed/{已办id}/recall", "scope": "task:write",
|
||
"when": "第三方收回给过的结论,撤回那条已办;后续环节已有人办过就撤不动"},
|
||
)
|
||
|
||
#: 开始环节那一档的建单说明。这颗钮是「提交」,而提交要有张停着的单才按得动——
|
||
#: 第三方最常踩的就是拿自己那套单号直接来表态,OA 这头连单都还没有(真实来路:报销回
|
||
#: AGREE + 自己排的 FYBX 号,回回撞在 NODE_LOCATE_NOT_FOUND 上)。卡片是对方唯一照抄的
|
||
#: 那份,这一句不写在这里,他就只能从 400 里猜。
|
||
WORKS_WHEN_BEGIN = (
|
||
'这张单由第三方发起时才用;**开始环节这一步必须先调它**:带 "hold": true 建一张停在'
|
||
'开始环节的单(表单校验、编号、闸门都过完,就是不流转),再拿响应里的 work.serial 或 '
|
||
'work.job 当下面 decide 地址上那一段——自己那套单号在这里认不出。这一步也带 bizKey'
|
||
'(那趟嵌页面的预受理号 PRE…)防重复建单。不带 hold 就是当场提交出去,'
|
||
'那一步已经做完,不必再 decide')
|
||
|
||
#: 这一环那条 decide 在清单里的说明。它是这一趟的主活,位置排在「取参数」之后。
|
||
DECIDE_WHEN = ("按下这一环的审批按钮:这一趟的主活。环节那一段填这一环的 activityId,"
|
||
"每次调用前从 locate 或事件信封里现取——它是设计期产物,环节删掉重拖就是"
|
||
"一个新号,抄死在自己代码里迟早对不上(alt 是省掉那一段的写法,环节由 OA 认,"
|
||
"代价是报文晚到时可能办到下一个开了接口的环节上);"
|
||
"出口走哪条线由这一环的钉配说了算,第三方只说结论")
|
||
|
||
#: 表态之后两边怎么对上账:订阅这些事件(推)。不想维护常驻 webhook 就改走上面的
|
||
#: locate(拉),两条路是加法不是替换,凭据同一把访问令牌。
|
||
CARD_EVENTS: tuple[tuple[str, str], ...] = (
|
||
("task.arrived", "走到这一环了:信封里带待办号与这张卡片,收到就知道该出手"),
|
||
("task.completed", "这一环已由人从 OA 界面办掉:不用再表态"),
|
||
("work.completed", "单据办结"),
|
||
("work.terminated", "单据终止"),
|
||
("work.canceled", "单据作废"),
|
||
)
|
||
|
||
|
||
def integration_apis(interface: str, *, alt: str = "", begin: bool = False) -> list[dict]:
|
||
"""第三方那一份接口清单:把这一环那条 decide 插在「取参数」与「收尾对账」之间。
|
||
|
||
``interface`` 收的是卡片里那条写法(带方法名),这里把方法与地址拆开摆,对方
|
||
拼 HTTP 请求不用去切字符串。``scopeLabel`` 一并给出(与开放平台勾选项同一份文案),
|
||
对方看卡片就知道要给这个应用开哪一档权限,不必回头翻文档。
|
||
|
||
``alt`` 是同一件事的省事写法(省掉环节那一段,环节由 OA 认):摆在同一行里递出去,
|
||
嫌多传一个参数的对接方直接照抄它,不必回来问一次。
|
||
"""
|
||
method, _, path = str(interface or "").partition(" ")
|
||
rows = [dict(item) for item in THIRD_PARTY_APIS]
|
||
if begin:
|
||
for row in rows:
|
||
if row.get("path") == "/api/v1/open/works":
|
||
row["when"] = WORKS_WHEN_BEGIN
|
||
decide = {"method": method or "POST", "path": path, "scope": "task:write", "when": DECIDE_WHEN}
|
||
if alt:
|
||
decide["alt"] = str(alt).partition(" ")[2]
|
||
rows.insert(2, decide)
|
||
return [{**row, "scopeLabel": openauth.SCOPE_LABELS.get(str(row.get("scope") or ""), "")}
|
||
for row in rows]
|
||
|
||
|
||
def card_events() -> list[dict]:
|
||
"""卡片里那份事件清单:订阅它们就不必轮询定位。"""
|
||
return [{"event": key, "when": when} for key, when in CARD_EVENTS]
|
||
|
||
|
||
def card(
|
||
process: models.Process | None,
|
||
activity: models.Activity | None,
|
||
*,
|
||
work: models.Work | None = None,
|
||
db: Session | None = None,
|
||
) -> dict:
|
||
"""这一环的审批接口长什么样:设计器页签里展示的那张、事件信封里递出的这份、
|
||
对接文档里的示例,都从这一处生成——三处各写一份的文档一定会漂。
|
||
|
||
``work`` 给了就按那张单把样例里的单号填上(事件信封走这条);没给就是设计期
|
||
的空白样例。
|
||
"""
|
||
if activity is None:
|
||
return {}
|
||
config = effective_config(process, activity)
|
||
if not is_enabled(config):
|
||
return {}
|
||
# 那一段填的是这张单的号:编号没排出来(编号时机晚或这条流程不编号)就退回 job 号,
|
||
# 两处都认得,别为了凑一个空号让对方照着占位自己拼。
|
||
serial = str(getattr(work, "serial", "") or "") if work is not None else ""
|
||
job = str(getattr(work, "job", "") or "") if work is not None else ""
|
||
# 主地址点名环节:环节那一段是**每次调用现取的参数**,卡片把它填成这一环的真号,
|
||
# 对方照抄一次就够,改图换号时从 locate 或事件信封里重新取,不会把结论办到隔壁环上。
|
||
# 省掉那一段的短地址一并挂在 alt / interfaceCurrent 上,两条一直通着。
|
||
interface = interface_path(serial or job, activity.id)
|
||
current = interface_path_current(serial or job)
|
||
activity_type = str(getattr(activity, "type", "") or "")
|
||
is_begin = activity_type == "begin"
|
||
lock = lock_view(config, names=names_for(db, [config]) if db is not None else None,
|
||
activity_type=activity_type)
|
||
return {
|
||
"interface": interface,
|
||
"interfaceCurrent": current,
|
||
# 兼容旧卡片:这个键一直指"点名环节那条",如今主地址就是那条,同值留着不删人
|
||
"interfaceActivity": interface,
|
||
"header": "Authorization: Bearer {开放平台访问令牌}",
|
||
# 全套对接接口与事件订阅:对方拿这一份就能自己跑通,不必再要一份会漂的文档
|
||
"apis": integration_apis(interface, alt=current, begin=is_begin),
|
||
"events": card_events(),
|
||
"confirm": confirm_mode(config),
|
||
# 开始环节这一档:认不出这张单时,这一趟是被拒绝还是被代发(§4.6.2)
|
||
"autoStart": auto_start_enabled(config),
|
||
# OA 侧那几颗钮锁没锁:这一格是给对方**程序**读的硬约束——true 意味着 OA 里不会
|
||
# 有人点,这一环只能等回调(confirm 模式下那条横幅也不会有人来点头,除非
|
||
# oaLock.allowConfirm 开着)。比文案有用,对方照这一格决定要不要挂重试。
|
||
"oaLocked": lock["locked"],
|
||
"oaLock": lock,
|
||
"decisions": decisions_map(config),
|
||
"routes": routes_map(config),
|
||
"fields": allowed_write_fields(config),
|
||
"sample": {
|
||
"work": serial,
|
||
# 样例是对方照抄的那一格,得给这一环真认得的词:开始环节摆一个 APPROVED
|
||
# 出去,抄的人当场撞墙(APPROVED 在那里没有出口,那颗钮只认提交)
|
||
"result": sample_result_word(config, activity=is_begin),
|
||
"bizKey": "",
|
||
"data": {},
|
||
},
|
||
}
|
||
|
||
|
||
def allowed_write_fields(config: dict | None) -> list[str]:
|
||
value = (config or {}).get("fields")
|
||
if not isinstance(value, list):
|
||
return []
|
||
return [str(item).strip() for item in value if str(item or "").strip()]
|
||
|
||
|
||
# --------------------------------------------------------------------------- 事件信封
|
||
|
||
|
||
def task_info(task: models.Task) -> dict:
|
||
"""待办本身:信封里给的那份。信封走签名 webhook,给号不泄密。"""
|
||
return {
|
||
"id": task.id,
|
||
"identity": task.identity,
|
||
"identityName": task.identity_name,
|
||
"dueAt": task.expire_time.strftime("%Y-%m-%d %H:%M:%S") if task.expire_time else "",
|
||
"routes": list(task.route_name_list or []),
|
||
}
|
||
|
||
|
||
def task_arrived_extra(
|
||
db: Session,
|
||
work: models.Work,
|
||
activity: models.Activity | None,
|
||
tasks: list[models.Task],
|
||
) -> dict:
|
||
"""``task.arrived`` 信封里要补的那两样:待办本身 + 开了外部审批的接口卡片。
|
||
|
||
对方收到「轮到财务复核了」就该拿到动手需要的全部东西,不该再翻文档、挨个查待办。
|
||
"""
|
||
extra: dict = {}
|
||
if len(tasks) == 1:
|
||
extra["task"] = task_info(tasks[0])
|
||
else:
|
||
extra["tasks"] = [task_info(item) for item in tasks]
|
||
try:
|
||
# 卡片说的是"这一环的接口怎么调",得与引擎放行时用的那一版一致:冻结定义身上带着
|
||
# 流程默认档(open_approve),环节那一份调用方已经按同一版交进来了。
|
||
node_card = card(_definition_of(db, work) or db.get(models.Process, work.process),
|
||
activity, work=work, db=db)
|
||
except Exception: # noqa: BLE001 - 卡片是加法:取不到卡也不该把待办信息弄丢
|
||
node_card = None
|
||
if node_card:
|
||
extra["openApprove"] = node_card
|
||
return extra
|
||
|
||
|
||
# --------------------------------------------------------------------------- 拉取式定位(不订阅事件)
|
||
#
|
||
# 事件订阅(task.arrived)是"推":OA 主动把卡片递过去。但对方系统跑在自己的定时任务里、
|
||
# 不想维护一条常驻 webhook 时,可以反过来"拉":拿他那边已知的业务字段(设计器里配的
|
||
# 「查找字段」)或单号,调 ``POST /open/nodes/locate`` 把这张单**当前停在哪个环节**、
|
||
# activityId / 待办 / 接口卡片一并取回(卡片里那条端点已把这张单的流程编号填好),照抄就能调 decide。
|
||
#
|
||
# 两条路是加法不是替换:推的(事件)与拉的(定位)各管各的,凭据同一把(访问令牌)。
|
||
|
||
|
||
def lookup_fields(config: dict | None) -> list[str]:
|
||
"""这一环让第三方拿哪几格来定位单据:``openApprove.lookup`` 里配的那些表单字段名。
|
||
|
||
与可写白名单(``fields``)是两码事:``fields`` 是表态时能**写**进表单的格子,
|
||
``lookup`` 是**用来找到这张单**的业务标识。两者可以重叠(同一个号既当查找键又回填),
|
||
但用途不同,分开配。``serial`` 与 ``job`` 永远可用,不必配。
|
||
"""
|
||
value = (config or {}).get("lookup")
|
||
if not isinstance(value, list):
|
||
return []
|
||
return [str(item).strip() for item in value if str(item or "").strip()]
|
||
|
||
|
||
def configured_lookup_fields(db: Session) -> set[str]:
|
||
"""全库「开着外部审批的环节」配过的查找字段之并集,加两个永远可用的特殊号。
|
||
|
||
这是拉取定位的**闸**:没被任何环节配过查找键的字段不允许拿来当查询条件——
|
||
否则这条端点就成了"拿任意表单字段枚举在跑哪些单"的探针。``serial`` / ``job`` 恒在内。
|
||
"""
|
||
out = {"serial", "job"}
|
||
for activity in db.execute(select(models.Activity)).scalars().all():
|
||
cfg = node_config(activity)
|
||
if not is_enabled(cfg):
|
||
continue
|
||
out.update(lookup_fields(cfg))
|
||
for process in db.execute(select(models.Process)).scalars().all():
|
||
cfg = process_defaults(process)
|
||
if not is_enabled(cfg):
|
||
continue
|
||
out.update(lookup_fields(cfg))
|
||
return out
|
||
|
||
|
||
def locate_work_by_keys(db: Session, keys: dict[str, Any], *, allowed: set[str]) -> tuple[models.Work | None, list[models.Work]]:
|
||
"""按配置过的业务字段找那张**在跑**的单。指不出来就不猜。
|
||
|
||
回 ``(None, 候选)`` 的三种情况调用方都得把话说明白:
|
||
* 字段没配成查找键 —— 400,点名哪个字段没开过;
|
||
* 一张都没对上 —— 404,这张单不在跑(或号给错);
|
||
* 对上了不止一张 —— 400,把候选念回去让对方收窄,不赌哪一张。
|
||
"""
|
||
cleaned = {str(k).strip(): v for k, v in (keys or {}).items() if str(k).strip()}
|
||
if not cleaned:
|
||
raise bad_request("至少带一格查找字段,或改带单号(work)", reason="NODE_LOCATE_EMPTY")
|
||
unknown = [key for key in cleaned if key not in allowed]
|
||
if unknown:
|
||
raise bad_request(
|
||
"这些字段没被任何环节配成查找键,不能拿来定位:" + "、".join(unknown),
|
||
reason="NODE_LOCATE_FIELD_NOT_CONFIGURED",
|
||
)
|
||
rows = list(db.execute(
|
||
select(models.Work).where(models.Work.status == "running")
|
||
.order_by(models.Work.start_time.desc(), models.Work.id)
|
||
).scalars().all())
|
||
matches = [row for row in rows if _data_matches(row, cleaned)]
|
||
if not matches:
|
||
return None, []
|
||
if len(matches) == 1:
|
||
return matches[0], []
|
||
return None, matches
|
||
|
||
|
||
def _data_matches(work: models.Work, cleaned: dict[str, Any]) -> bool:
|
||
"""这张单的表单数据里,每一格查找键的值都跟给的对得上才算中。按字符串比,别把类型玩出歧义。"""
|
||
data = dict(getattr(work, "data", None) or {})
|
||
for key, value in cleaned.items():
|
||
if str(data.get(key, "") or "") != str(value or ""):
|
||
return False
|
||
return True
|
||
|
||
|
||
def _archived_ref(db: Session, ref: str) -> dict | None:
|
||
"""``oa_work`` 里没有的那张单,是不是已经搬进归档表了。是就如实回它落在哪一档。
|
||
|
||
办结 / 终止 / 作废的那一刻,``oa_work`` 那行被搬进 ``oa_work_completed`` 并删掉——
|
||
拿着 job / 单号来定位的对方不该只听到一句冷冰冰的「不存在」,得知道它是办结了、
|
||
被终止了还是被作废了。
|
||
"""
|
||
value = str(ref or "").strip()
|
||
if not value:
|
||
return None
|
||
row = db.execute(select(models.WorkCompleted).where(models.WorkCompleted.job == value)).scalar_one_or_none()
|
||
if row is None:
|
||
rows = db.execute(select(models.WorkCompleted).where(models.WorkCompleted.serial == value)).scalars().all()
|
||
if len(rows) != 1:
|
||
return None
|
||
row = rows[0]
|
||
label = {"completed": "办结", "terminated": "终止", "canceled": "作废"}.get(row.status, row.status)
|
||
return {
|
||
"found": True,
|
||
"work": {
|
||
"job": row.job, "id": row.id, "serial": row.serial,
|
||
"title": row.title, "status": row.status,
|
||
"process": row.process, "processName": getattr(row, "process_name", "") or "",
|
||
},
|
||
"pending": False,
|
||
"note": f"这张单已{label}并归档,这一趟不用再表态",
|
||
}
|
||
|
||
|
||
#: ``detail=brief``(默认)那一份只留这几块:对方拼地址要的号、以及还能不能表态
|
||
_BRIEF_KEYS = ("process", "activity", "pending", "note")
|
||
|
||
|
||
def brief_view(payload: dict) -> dict:
|
||
"""定位响应的那份**瘦身版**:只留「是哪张单、停在哪个环节、还能不能表态」。
|
||
|
||
那张 ``openApprove`` 卡片是整个响应里最沉的一块(一整套接口清单 + 事件订阅 +
|
||
决策词表),而它是**配一次看一次**的东西,不该跟着每次表态前的定位跑几十趟。
|
||
对方动手要的两个号都在 ``process.id`` 与 ``activity.id`` 里,地址自己拼得出来;
|
||
真要那条填好号的现成地址与全套清单,带 ``detail=full`` 再取。
|
||
``work`` 只留三个号——按查找字段定位时总得知道对上的是哪一张单。
|
||
"""
|
||
work = payload.get("work") or {}
|
||
out: dict[str, Any] = {
|
||
"found": payload.get("found", False),
|
||
"work": {key: work.get(key, "") for key in ("job", "serial", "status")},
|
||
}
|
||
out.update({key: payload[key] for key in _BRIEF_KEYS if key in payload})
|
||
return out
|
||
|
||
|
||
def locate(db: Session, work_ref: str, keys: dict[str, Any] | None,
|
||
detail: str = "brief", app_code: str = "") -> dict:
|
||
"""拉取式定位:给单号或给查找字段,回这张单**现在**停在哪个环节、要办就带什么。
|
||
|
||
``detail`` 只裁**回多少**,不裁判据:``brief``(默认)走 :func:`brief_view` 那份瘦身,
|
||
``full`` 原样回完整响应——里面的 ``openApprove`` 卡片与事件信封里那份、设计器里那张
|
||
**同一处生成**,其中 ``interface`` 就是填好了这张单的流程编号与真实 activityId 的
|
||
那条 decide 端点。单据没在跑、当前这一环没开外部审批,两种模式都如实说清,不硬造卡片。
|
||
"""
|
||
payload = locate_full(db, work_ref, keys, app_code=app_code)
|
||
return brief_view(payload) if str(detail or "").strip().casefold() != "full" else payload
|
||
|
||
|
||
def locate_full(db: Session, work_ref: str, keys: dict[str, Any] | None,
|
||
app_code: str = "") -> dict:
|
||
"""``detail=full`` 那一份:定位 + 待办 + 那张接口卡片,一处不落。"""
|
||
ref = str(work_ref or "").strip()
|
||
if ref:
|
||
try:
|
||
work = find_work(db, ref)
|
||
except WorkRefCollision as exc:
|
||
raise bad_request(
|
||
f"单号「{exc}」对上了不止一张单,请报 job 号", reason="NODE_WORK_AMBIGUOUS") from exc
|
||
elif keys:
|
||
allowed = configured_lookup_fields(db)
|
||
work, candidates = locate_work_by_keys(db, keys, allowed=allowed)
|
||
if work is None and candidates:
|
||
serials = "、".join(str(item.serial or item.job) for item in candidates[:5])
|
||
raise bad_request(
|
||
f"这些查找字段对上了不止一张在跑的单({serials}…),带单号(work)说清是哪张",
|
||
reason="NODE_LOCATE_AMBIGUOUS",
|
||
)
|
||
else:
|
||
raise bad_request("单号(work)与查找字段(keys)至少带一个", reason="NODE_LOCATE_EMPTY")
|
||
|
||
if work is None:
|
||
archived = _archived_ref(db, ref) if ref else None
|
||
if archived is not None:
|
||
return archived
|
||
if ref:
|
||
# 归档那些上面已经如实回过了。还剩两种:这号是 OA 占下但那一趟还没发起,
|
||
# 以及 OA 压根没发出过这个号(第三方自己排了一个号就来表态)
|
||
target = unstarted_target(db, ref, app_code=app_code)
|
||
if target is not None:
|
||
# 这一趟在这一环办得成:定位如实回「还没单,直接 decide 就代发」,
|
||
# 不拿 400 把先 locate 再 decide 的那套流水线挡在门外
|
||
return unstarted_payload(db, ref, target)
|
||
pending = not_started_note(db, ref)
|
||
if pending:
|
||
# 认得出这一趟归哪个开始环节、只是没勾代发:那句拒绝里要点名开关,
|
||
# 否则先定位的人只知道"没这张单",永远不知道还有一档能让它发起来
|
||
hinted = unstarted_target(db, ref, app_code=app_code, require_auto_start=False)
|
||
raise bad_request(pending + ("" if hinted is None else NOT_STARTED_HINT),
|
||
reason=NOT_STARTED_REASON) from None
|
||
raise bad_request(
|
||
f"OA 没有用过「{ref}」这个号(既没在跑,也没归档过)。"
|
||
'多半是这张单还没在 OA 建起来:先 POST /open/works'
|
||
'(要停在开始环节等提交就带 "hold": true),拿回包里的 serial / job 再来表态。'
|
||
"对方自己那套单号不是这里的号——要按它定位,就把那一格配成查找字段走 keys",
|
||
reason="NODE_LOCATE_NOT_FOUND",
|
||
)
|
||
raise bad_request(
|
||
"这些查找字段的值没对上任何一张在跑的单:字段要在环节上配过(查找字段那一格),"
|
||
"值要和单据里存的一字不差;也可以直接报单号(work)或 job 号",
|
||
reason="NODE_LOCATE_NOT_FOUND",
|
||
)
|
||
|
||
work_view = {
|
||
"job": work.job, "id": work.id, "serial": work.serial,
|
||
"title": work.title, "status": work.status,
|
||
"process": work.process, "processName": work.process_name,
|
||
}
|
||
|
||
if work.status != "running":
|
||
label = {"completed": "办结", "terminated": "终止", "canceled": "作废"}.get(work.status, work.status)
|
||
return {
|
||
"found": True, "work": work_view, "pending": False,
|
||
"note": f"这张单已{label}并归档,这一趟不用再表态",
|
||
}
|
||
|
||
definition = _definition_of(db, work)
|
||
activity = (
|
||
(definition.activity(work.activity) if definition is not None else None)
|
||
or (db.get(models.Activity, work.activity) if work.activity else None)
|
||
)
|
||
process = definition if definition is not None else db.get(models.Process, work.process)
|
||
config = effective_config(process, activity)
|
||
pending = pending_tasks(db, work, work.activity) if activity is not None else []
|
||
|
||
payload: dict[str, Any] = {
|
||
"found": True,
|
||
"work": work_view,
|
||
"process": {"id": work.process, "name": work.process_name},
|
||
"activity": {
|
||
"id": activity.id if activity is not None else "",
|
||
"name": activity.name if activity is not None else (work.activity_name or ""),
|
||
},
|
||
"pending": bool(pending),
|
||
}
|
||
|
||
if activity is not None and activity.type == "begin":
|
||
# 开始环节没有待办:这颗钮是「提交」,单据停在这一环就是在等表态或发起人确认
|
||
payload["pending"] = True
|
||
if is_enabled(config):
|
||
payload["note"] = "这张单停在开始环节等提交:第三方表态或发起人确认后才会流转"
|
||
payload["openApprove"] = card(process, activity, work=work, db=db)
|
||
else:
|
||
payload["note"] = "这张单停在开始环节等提交,但这一环没开审批接口(开关没打开)"
|
||
return payload
|
||
|
||
if activity is None or not is_enabled(config):
|
||
payload["note"] = "这一环没开审批接口(开关没打开,或还没走到开了外部审批的那一环)"
|
||
return payload
|
||
|
||
if len(pending) == 1:
|
||
payload["task"] = task_info(pending[0])
|
||
elif len(pending) > 1:
|
||
payload["tasks"] = [task_info(item) for item in pending]
|
||
payload["note"] = "这一环有多条未办待办(会签 / 加签),表态时带上 identity 说清替哪一条"
|
||
else:
|
||
payload["note"] = "这一环还没落待办(单子刚到或正走非人工的那一步)"
|
||
|
||
payload["openApprove"] = card(process, activity, work=work, db=db)
|
||
return payload
|
||
|
||
|
||
# --------------------------------------------------------------------------- 运行时判定
|
||
|
||
|
||
class WorkRefCollision(Exception):
|
||
"""同一个单号落在不止一张单上:认得了号,认不了是哪张。"""
|
||
|
||
|
||
def work_by_trip_alias(db: Session, value: str) -> models.Work | None:
|
||
"""这个号没落在任何单据上,但发起页那一趟后来变成了**另一张单**:照着那一行认回来。
|
||
|
||
第三方那条报销记录只有一个 ``bizKey``,可他们每重开一次发起页,OA 就另占一个号;
|
||
复用早先那一张之后(``api/openapi._begin_start_from_decide``),那个新号没变成单据,
|
||
只记在会话那一行的认领记录里。不认它,对方拿手里仅剩的那个号再定位、再表态,
|
||
都会撞「OA 没用过这个号」——而那句话是假话。
|
||
"""
|
||
ref = str(value or "").strip()
|
||
if not ref:
|
||
return None
|
||
session = embed_session.by_serial(db, ref)
|
||
if str(getattr(session, "status", "") or "") != models.EmbedSession.STATUS_CLAIMED:
|
||
return None
|
||
claimed = str(getattr(session, "claim_job", "") or "")
|
||
if not claimed:
|
||
return None
|
||
return db.execute(select(models.Work).where(models.Work.job == claimed)).scalar_one_or_none()
|
||
|
||
|
||
def find_work(db: Session, work_ref: str) -> models.Work | None:
|
||
"""对方手里的号:单号(serial)或 job 号。两个都认,认不出就认不出。
|
||
|
||
单号只在 job 内唯一、跨流程不保证唯一——同号多于一张时明说撞号,让对方报
|
||
job 号,而不是把选择权交给数据库先扫到谁。
|
||
"""
|
||
value = str(work_ref or "").strip()
|
||
if not value:
|
||
return None
|
||
row = db.execute(select(models.Work).where(models.Work.job == value)).scalar_one_or_none()
|
||
if row is not None:
|
||
return row
|
||
rows = db.execute(select(models.Work).where(models.Work.serial == value)).scalars().all()
|
||
if len(rows) > 1:
|
||
raise WorkRefCollision(value)
|
||
if rows:
|
||
return rows[0]
|
||
return work_by_trip_alias(db, value)
|
||
|
||
|
||
def find_works_named(db: Session, ref: str) -> list[models.Work]:
|
||
"""按对方报的那个号找单子:**流程编号**(``serial``)打头,job 号同样认。
|
||
|
||
与 :func:`find_work` 认的是同一批号,区别只在这里把「撞号」摊开来交给调用方判:
|
||
写在地址里的那一段撞了要说「改报 job 号」,写在报文里的那一位撞了要说别的口径,
|
||
别在这一层替调用方决定措辞。
|
||
"""
|
||
value = str(ref or "").strip()
|
||
if not value:
|
||
return []
|
||
rows = list(db.execute(select(models.Work).where(models.Work.serial == value)).scalars().all())
|
||
if rows:
|
||
return rows
|
||
row = db.execute(select(models.Work).where(models.Work.job == value)).scalar_one_or_none()
|
||
if row is not None:
|
||
return [row]
|
||
aliased = work_by_trip_alias(db, value)
|
||
return [aliased] if aliased is not None else []
|
||
|
||
|
||
#: 这个号 OA 给过、只是那一趟还没发起成单。它与「认不出这个号」必须分开:
|
||
#: 前者唯一该做的是去发起(重试与改号都救不了它),后者该去查自己抄错了号。
|
||
NOT_STARTED_REASON = "NODE_WORK_NOT_STARTED"
|
||
|
||
|
||
def not_started_note(db: Session, work_ref: str) -> str:
|
||
"""这个号是不是 OA 在发起页上占下、却还没发起成单的号:是就回那句人话,不是回空串。
|
||
|
||
第三方手里那个号有两条来路是**在单之前**的:发起页每开一页占一个正式号
|
||
(``oa_embed_session.serial``,对面按它建自己的草稿),以及存下来的草稿
|
||
(``oa_draft.serial``)。这两样都不在 ``Work`` / ``WorkCompleted`` 里,于是
|
||
``locate`` 只认这两张表就会回「OA 没用过这个号」——那是假话,还会把唯一的正事
|
||
(去把这张单发起)挡在门外,对方的机器人就照着"号可能错了"一路重试下去。
|
||
"""
|
||
value = str(work_ref or "").strip()
|
||
if not value:
|
||
return ""
|
||
session = db.execute(
|
||
select(models.EmbedSession).where(
|
||
(models.EmbedSession.serial == value) | (models.EmbedSession.prekey == value))
|
||
).scalars().first()
|
||
draft = db.execute(
|
||
select(models.Draft).where(models.Draft.serial == value)
|
||
).scalars().first()
|
||
if session is None and draft is None:
|
||
return ""
|
||
prekey = str(getattr(session, "prekey", "") or "") if session is not None else ""
|
||
where = "还挂在一份草稿上" if draft is not None else "那一趟还没提交"
|
||
# 报文形状直接写在话里:这一趟的号要保住,就得靠 bizKey 认回同一趟(见 open_start_work
|
||
# 接预留号那一段),少了它对方发出来的就是另一张单、另一个号
|
||
step = (f'(带 "bizKey": "{prekey}" 就是同一趟,这个号不变;再带 "hold": true '
|
||
f'就停在开始环节等第三方表态)'
|
||
if prekey else '(要停在开始环节等第三方表态就带 "hold": true)')
|
||
return (
|
||
f"「{value}」是 OA 在发起页上占下的号,{where},所以还没有在跑的单。"
|
||
f"别重试,先把这张单发起:由第三方发起就调 POST /open/works{step};"
|
||
"由本人发起就让他打开那张发起页提交"
|
||
)
|
||
|
||
|
||
#: 没勾代发时补那一句:开关名与位置写全,先定位的那套流水线才有的可查
|
||
NOT_STARTED_HINT = ("。这一环如果就是要由第三方替发起人提交,去环节配置的「外部审批」里勾上"
|
||
"「没有单据时代为发起」,勾了之后这一句定位会直接把 decide 的地址递给你")
|
||
|
||
|
||
def unstarted_target(db: Session, work_ref: str, app_code: str = "", *,
|
||
require_auto_start: bool = True) -> dict[str, Any] | None:
|
||
"""这个号是 OA 占下、还没发起的那一趟,而它**该由开始环节直接接住**时:回那一环与那一趟。
|
||
|
||
"号在单之前"是正常状态(§4.6.1),可这一档以前只有一句「先建单再来」:第三方那套流水线是
|
||
先 ``locate`` 再 ``decide``,``locate`` 在这里回 400 就等于把整条回写挡死——它连该把
|
||
表态发到哪一环都不知道(生产上就是这么撞的:号是发起页占的,回写日志里只留一句"定位失败")。
|
||
勾了「没有单据时代为发起」(§4.6.2)之后这一趟是办得成的,于是定位也该如实回话。
|
||
|
||
三条判据一条不退,缺任何一条都回 ``None``( caller 照旧回那句「先建单再来」):
|
||
|
||
* 号确实是 **OA 自己排出去的**:按排号那本账认(:func:`numbering.owners_of_serial`),
|
||
对方自己按同样格式排一个号在这里认不出流程,那是**该认不出**;
|
||
* 对出的流程**只有一条**:两条例子一样的流程排出字面相同的号,宁可不猜;
|
||
* 那条流程的开始环节开了外部审批、对当前应用开口,并且**勾了代发**——没勾代发时
|
||
这一趟在这一环真办不成事,回 200 反而是骗人。
|
||
"""
|
||
ref = str(work_ref or "").strip()
|
||
if not ref:
|
||
return None
|
||
session = embed_session.by_prekey(db, ref) or embed_session.by_serial(db, ref)
|
||
process_id = ""
|
||
draft_id = str(getattr(session, "draft", "") or "") if session is not None else ""
|
||
if draft_id:
|
||
process_id = str(getattr(db.get(models.Draft, draft_id), "process", "") or "")
|
||
if not process_id:
|
||
owners = numbering.owners_of_serial(db, str(getattr(session, "serial", "") or "") or ref)
|
||
process_id = owners[0] if len(owners) == 1 else ""
|
||
if not process_id:
|
||
return None
|
||
process = db.get(models.Process, process_id)
|
||
if process is None:
|
||
return None
|
||
activity = db.execute(
|
||
select(models.Activity)
|
||
.where(models.Activity.process == process.id, models.Activity.type == "begin")
|
||
.order_by(models.Activity.order_number)
|
||
).scalars().first()
|
||
if activity is None:
|
||
return None
|
||
config = effective_config(process, activity)
|
||
apps = allowed_apps(config)
|
||
if not is_enabled(config) or (apps and app_code and app_code not in apps):
|
||
return None
|
||
if require_auto_start and not auto_start_enabled(config):
|
||
return None
|
||
return {"process": process, "activity": activity, "config": config, "session": session,
|
||
"autoStart": auto_start_enabled(config)}
|
||
|
||
|
||
def unstarted_payload(db: Session, work_ref: str, target: dict[str, Any]) -> dict[str, Any]:
|
||
"""还没发起的那一趟,定位该回的那一份:**没有单,但这一环认提交,直接表态就代发**。
|
||
|
||
``work.status`` 给的是 ``not_started`` 而不是空串——对方程序按状态分支时,"查无此单"与
|
||
"这单还没发起"必须是两个值,否则它只能去读人话。卡片照常递(``interface`` 里填的就是
|
||
这个号与真 activityId),对方照抄一条 decide 就能把流程发起来。
|
||
"""
|
||
process, activity = target["process"], target["activity"]
|
||
ref = str(work_ref or "").strip()
|
||
holder = SimpleNamespace(serial=ref, job="")
|
||
return {
|
||
"found": True,
|
||
"work": {"job": "", "id": "", "serial": ref, "title": "", "status": "not_started",
|
||
"process": process.id, "processName": process.name},
|
||
"process": {"id": process.id, "name": process.name},
|
||
"activity": {"id": activity.id, "name": activity.name},
|
||
"pending": True,
|
||
"atBegin": True,
|
||
"startedFromDecision": False,
|
||
"openApprove": card(process, activity, work=holder, db=db),
|
||
"note": (f"这张单还没在 OA 发起(「{ref}」是发起页占下的号,那一趟还没提交)。"
|
||
"这一环勾了「没有单据时代为发起」:直接按上面那条 decide 表态,"
|
||
"OA 就替发起人发起这张单并按这一环的确认模式提交,单号不变。"),
|
||
}
|
||
|
||
|
||
def archived_note(db: Session, work_ref: str) -> str:
|
||
"""这个号是不是已经归档的那张单:是就回那句「不用再表态」,不是就回空串。
|
||
|
||
定位那条端点早就如实回话了,表态这条只留一句冷冰冰的「没认出这张单」——机器人对着
|
||
一张办结的单重试,该听到的是"这张单不用再表态",而不是"你号给错了",否则会一直重试。
|
||
只在**认不出号**的时候拿它兜一次,不做提前查单:那条点名环节的端点仍不该是探针。
|
||
"""
|
||
return str((_archived_ref(db, work_ref) or {}).get("note") or "")
|
||
|
||
|
||
def work_from_path(
|
||
db: Session, path_ref: str, body_work: str = "", *, process_id: str = ""
|
||
) -> models.Work:
|
||
"""端点地址里那一段与报文里那一位合起来指认这张单:**流程编号打头**,不要求对方知道内部 id。
|
||
|
||
认的顺序(指不出来就不猜,与 :func:`resolve_task` 同一把尺):
|
||
|
||
1. 地址里那一段当**流程编号**(或 job 号)→ 就是这张单。报文里再报一次 ``work``
|
||
也算,但两处必须指到同一张——各说一张当场点名,赌错一张就办到别人那张单上;
|
||
2. 地址里那一段认不出单 → 它得是这条流程的 id(老卡片上写的就是它),
|
||
那张单改由报文的 ``work`` 指认;两处都没有 → 400 点名要补,不猜;
|
||
3. 地址里那一段既不是号、也不是这条流程的 id → 400 说清是哪一段没认出来,
|
||
不能因为报文里有单就放过它——那等于这一路的门没人看了;
|
||
4. 号对上了但单不归这一环所在的那条流程 → 同样当场点名。流程与环节的从属关系
|
||
以**环节自己记的那条**为准,不采信对方写的号。
|
||
"""
|
||
path = str(path_ref or "").strip()
|
||
body = str(body_work or "").strip()
|
||
legacy_id = bool(process_id) and path == process_id
|
||
|
||
by_path = find_works_named(db, path)
|
||
if len(by_path) > 1:
|
||
raise bad_request(f"流程编号「{path}」对上了不止一张单,请改报 job 号",
|
||
reason="NODE_WORK_AMBIGUOUS")
|
||
work = by_path[0] if by_path else None
|
||
|
||
by_body: list[models.Work] = []
|
||
if body:
|
||
by_body = find_works_named(db, body)
|
||
if len(by_body) > 1:
|
||
raise bad_request(f"单号「{body}」对上了不止一张单,请报 job 号",
|
||
reason="NODE_WORK_AMBIGUOUS")
|
||
if not by_body:
|
||
raise bad_request("这张单不存在", reason="NODE_WORK_NOT_FOUND")
|
||
|
||
if work is not None and by_body and work.id != by_body[0].id:
|
||
raise bad_request(
|
||
f"地址里的「{path}」是「{work.serial or work.job}」,"
|
||
f"报文里的 work 是「{by_body[0].serial or by_body[0].job}」,不是同一张单",
|
||
reason="NODE_PATH_WORK_MISMATCH",
|
||
)
|
||
if work is None:
|
||
pending = not_started_note(db, path)
|
||
if pending:
|
||
raise bad_request(pending, reason=NOT_STARTED_REASON)
|
||
if not legacy_id:
|
||
raise bad_request(
|
||
f"没认出这张单:地址里的「{path}」既不是流程编号也不是 job 号"
|
||
+ (",也不是这一环所在的流程 id" if process_id
|
||
else ";这一条端点只认单子上印的那个号(或 job 号)"),
|
||
reason="NODE_WORK_NOT_FOUND",
|
||
)
|
||
if not by_body:
|
||
raise bad_request(
|
||
f"地址里放的是流程定义 id({path}),光凭它认不出是哪张单:"
|
||
"把流程编号放进地址,或在报文里带上 work(单号 / job 号)",
|
||
reason="NODE_WORK_REQUIRED",
|
||
)
|
||
work = by_body[0]
|
||
|
||
if process_id and work.process != process_id:
|
||
raise bad_request(
|
||
f"这张单属于「{work.process_name or work.process}」,这一环不在那条流程里",
|
||
reason="NODE_PATH_WORK_MISMATCH",
|
||
)
|
||
return work
|
||
|
||
|
||
def route_names(db: Session, process_id: str, activity_id: str) -> list[str]:
|
||
"""这一环真实存在的出口名,按连线顺序。"""
|
||
rows = db.execute(
|
||
select(models.Route)
|
||
.where(models.Route.process == process_id, models.Route.from_activity == activity_id)
|
||
.order_by(models.Route.order_number, models.Route.id)
|
||
).scalars().all()
|
||
return [str(row.name) for row in rows]
|
||
|
||
|
||
def pending_tasks(db: Session, work: models.Work, activity_id: str) -> list[models.Task]:
|
||
return list(
|
||
db.execute(
|
||
select(models.Task)
|
||
.where(models.Task.work == work.id, models.Task.activity == activity_id,
|
||
models.Task.status == "pending")
|
||
.order_by(models.Task.id)
|
||
).scalars().all()
|
||
)
|
||
|
||
|
||
def resolve_task(
|
||
db: Session, work: models.Work, activity_id: str, identity: str = ""
|
||
) -> tuple[models.Task | None, list[models.Task]]:
|
||
"""待办落在哪一条:**指不出来就不猜**。
|
||
|
||
回了 ``(None, 候选)`` 的三种情况调用方都得把候选念回去:
|
||
* 多条待办(会签 / 加签)且没点名——赌错一条就办到别人头上;
|
||
* 点了名但这一环没有这个人——名字照原样回给调用方,别替他认错人;
|
||
* 一条都没有——调用方先问台账「是不是被办掉了」,再决定报"还没轮到"还是"已经办过"。
|
||
"""
|
||
pending = pending_tasks(db, work, activity_id)
|
||
if not pending:
|
||
return None, []
|
||
wanted = str(identity or "").strip()
|
||
if wanted:
|
||
hit = [row for row in pending if row.identity == wanted]
|
||
return (hit[0], pending) if hit else (None, pending)
|
||
return (pending[0], pending) if len(pending) == 1 else (None, pending)
|
||
|
||
|
||
def _definition_of(db: Session, work: models.Work):
|
||
"""这张单出发时那一版设计;读不到(流程被删)回 ``None``,调用方退回实库那几行。"""
|
||
from ..engine import definition as definition_module
|
||
|
||
try:
|
||
return definition_module.for_work(db, work)
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
def current_activities(db: Session, work: models.Work, definition: object = None) -> list[models.Activity]:
|
||
"""这张单**此刻**停着的那几一环,按环节序号排。
|
||
|
||
并行分支会同时停在好几环上,所以这里是一个清单而不是一个。停在开始环节的那种单
|
||
(``hold`` 建出来、还没提交)一条待办都没有,它等的是开始环节那颗提交钮——回的就是开始环节。
|
||
"""
|
||
ids: list[str] = []
|
||
for row in db.execute(
|
||
select(models.Task).where(models.Task.work == work.id, models.Task.status == "pending")
|
||
.order_by(models.Task.id)
|
||
).scalars().all():
|
||
if row.activity not in ids:
|
||
ids.append(str(row.activity))
|
||
if not ids and str(work.activity_type or "") == "begin" and str(work.activity or ""):
|
||
ids = [str(work.activity)]
|
||
out: list[models.Activity] = []
|
||
for aid in ids:
|
||
# 有冻结定义就从它身上取这一环:这一环的配置(开没开外部审批、锁了哪几颗)
|
||
# 必须是这张单在走的那一版,不是别人刚改过的那一版。
|
||
row = (definition.activity(aid) if definition is not None else None) or db.get(models.Activity, aid)
|
||
if row is not None:
|
||
out.append(row)
|
||
out.sort(key=lambda row: (int(row.order_number or 0), str(row.id)))
|
||
return out
|
||
|
||
|
||
def open_targets(
|
||
db: Session, work: models.Work, app_code: str
|
||
) -> tuple[list[models.Activity], list[models.Activity]]:
|
||
"""不点名环节时,这张单此刻**能对当前应用开口**的那几一环。
|
||
|
||
判据与点名环节那条长地址一字不差(:func:`effective_config` / :func:`is_enabled` /
|
||
:func:`allowed_apps`),差别只在这里要替对方把环节找出来。回
|
||
``(都能对上的, 开着但没对这个应用开口的)``:前者不止一条就不猜——并行分支真能同时停在
|
||
两环上,赌错一环就办到另一环头上;后者只用来把话说清楚,是这一环没开接口,
|
||
还是开了没对你开。
|
||
"""
|
||
definition = _definition_of(db, work)
|
||
targets: list[models.Activity] = []
|
||
blocked: list[models.Activity] = []
|
||
for activity in current_activities(db, work, definition):
|
||
config = effective_config(
|
||
definition
|
||
if definition is not None
|
||
else db.get(models.Process, str(getattr(activity, "process", "") or "")),
|
||
activity,
|
||
)
|
||
if not is_enabled(config):
|
||
continue
|
||
apps = allowed_apps(config)
|
||
(targets if not apps or app_code in apps else blocked).append(activity)
|
||
return targets, blocked
|
||
|
||
|
||
def filter_data(data: dict | None, config: dict | None, fields: list[dict]) -> tuple[dict, list[str]]:
|
||
"""表态能带哪几格:白名单之外的一条都不收,挂阈值 / 额度的格子拒收。
|
||
|
||
白名单在**进引擎之前**筛:不在清单里的键连留痕都不进,与回填白名单同一条规矩——
|
||
等引擎去筛不是闸,是装饰。回 ``(收下的, 被丢掉的键名)``,键名给留痕用,值不进日志。
|
||
"""
|
||
incoming = dict(data or {})
|
||
keys = allowed_write_fields(config)
|
||
if not keys:
|
||
return {}, [str(key) for key in incoming] if incoming else []
|
||
guarded = _guarded_keys(fields)
|
||
accepted: dict = {}
|
||
dropped: list[str] = []
|
||
for key, value in incoming.items():
|
||
name = str(key)
|
||
if name in keys and name not in guarded:
|
||
accepted[name] = value
|
||
else:
|
||
dropped.append(name)
|
||
return accepted, dropped
|
||
|
||
|
||
def render_opinion(config: dict | None, kind: str, work: models.Work | None, data: dict | None) -> str:
|
||
"""意见模板渲染:``{serial}`` 与 ``{form.字段名}`` 两个占位,其余原样。
|
||
|
||
模板没配、配的不是这个结论、或者渲染出来是空话,都回空串——让引擎走它自己的
|
||
出口意见口径,别拿一句空的盖掉本来该有的一句话。
|
||
"""
|
||
template = opinion_templates(config).get(str(kind or "").strip().lower())
|
||
if not template:
|
||
return ""
|
||
serial = str(getattr(work, "serial", "") or "") if work is not None else ""
|
||
values = dict(data or {})
|
||
out = []
|
||
last = 0
|
||
for match in _PLACEHOLDER.finditer(template):
|
||
out.append(template[last:match.start()])
|
||
token = str(match.group(1) or "").strip()
|
||
if token == "serial":
|
||
out.append(serial)
|
||
elif token.startswith("form."):
|
||
out.append(str(values.get(token[5:].strip(), "") or ""))
|
||
else:
|
||
out.append(match.group(0))
|
||
last = match.end()
|
||
out.append(template[last:])
|
||
return "".join(out).strip()
|
||
|
||
|
||
# --------------------------------------------------------------------------- 表态台账
|
||
|
||
|
||
STATUS_STAGED = "staged"
|
||
STATUS_HANDLED = "handled"
|
||
STATUS_REJECTED = "rejected"
|
||
STATUS_EXPIRED = "expired"
|
||
|
||
|
||
def ttl_seconds() -> int:
|
||
return max(300, int(dbconfig.value("node_decision_ttl", 86400)))
|
||
|
||
|
||
def find_by_app_biz(db: Session, app: str, activity_id: str, biz_key: str,
|
||
serials: Iterable[str] | None = None) -> models.NodeDecision | None:
|
||
"""按 (哪个应用, 哪一环, 哪一趟 ``bizKey``) 找那次表态:单子还没建起来时唯一的对号处。
|
||
|
||
:func:`find_by_biz` 按 ``(app, work, activity, biz_key)`` 认,代发那一路进来时还没有
|
||
``work`` 可对。少了这一条,对方重试一次就多发一张单——建单这件事一旦没有幂等号,
|
||
代价是库里一堆只差几秒的重复报销单。
|
||
|
||
``serials`` 是**这次调用点名的那几个 OA 单号**(地址里的 ``oa_flow_number`` 与报文里那个
|
||
``work``)。给了它就把范围收到"同一个号"上,因为对方那套流水号是按**报销记录**编的:
|
||
同一条记录他们可以把 OA 发起页重开一次(OA 于是另占一个新号)再回写一次,那是**两趟**,
|
||
不是同一趟的两次重试。不收窄的代价在生产上撞到过(2026-10-27 15:54,``FYBX202610270023``
|
||
那句裸 AGREE 命中了十分钟前 ``FYBX202610270020`` 那条已办的记录):OA 回 200 与第一趟那份
|
||
响应(``alreadyHandled``),对方日志写着 ``writeback succeeded``,而 OA 里那张新单压根没建。
|
||
库里那些没记单号的旧行(``serial`` 是空的)算对得上——收得太窄会把真重试打成重复建单,
|
||
那比多建一张贵。
|
||
"""
|
||
value = str(biz_key or "").strip()
|
||
if not value:
|
||
return None
|
||
stmt = select(models.NodeDecision).where(
|
||
models.NodeDecision.app == str(app or ""),
|
||
models.NodeDecision.activity == str(activity_id or ""),
|
||
models.NodeDecision.biz_key == value,
|
||
)
|
||
wanted = {str(item or "").strip() for item in (serials or ()) if str(item or "").strip()}
|
||
if wanted:
|
||
# 那几条来路都算"点到同一张单":地址里那个号通常是正式单号,但报文里那个 ``work``
|
||
# 可以是 job,老调用方还会直接把单据主键填进来。漏一条,一次正常重试就会被
|
||
# 当成"另一趟",于是凭空多建一张单——那是这一档最贵的错。
|
||
stmt = stmt.where(or_(models.NodeDecision.serial == "",
|
||
models.NodeDecision.serial.in_(wanted),
|
||
models.NodeDecision.job.in_(wanted),
|
||
models.NodeDecision.work.in_(wanted)))
|
||
return db.execute(
|
||
stmt.order_by(models.NodeDecision.create_time.desc(), models.NodeDecision.id.desc())
|
||
).scalars().first()
|
||
|
||
|
||
def find_superseded_by_biz(db: Session, app: str, activity_id: str, biz_key: str,
|
||
*, limit: int = 20) -> models.NodeDecision | None:
|
||
"""同一个 ``bizKey`` 在这一环上的历次表态里,挑出**那一趟还没走完**的那一条。
|
||
|
||
按号分不出趟的时候用得上它:对方重开发起页会另占一个号,那个号与早先那条表态记录
|
||
对不上,可那条记录对应的单还停在开始环节等提交。这里不能"取最近一条"——同一张单被
|
||
重办时台账是就地改写的,``create_time`` 还是第一次那一回,按时间取会挑到别的趟上去;
|
||
判据只有 :func:`decision_superseded` 那三条,逐条试过才算数。
|
||
"""
|
||
value = str(biz_key or "").strip()
|
||
if not value:
|
||
return None
|
||
rows = db.execute(
|
||
select(models.NodeDecision)
|
||
.where(
|
||
models.NodeDecision.app == str(app or ""),
|
||
models.NodeDecision.activity == str(activity_id or ""),
|
||
models.NodeDecision.biz_key == value,
|
||
)
|
||
.order_by(models.NodeDecision.create_time.desc(), models.NodeDecision.id.desc())
|
||
.limit(max(1, int(limit)))
|
||
).scalars().all()
|
||
for row in rows:
|
||
if decision_superseded(db, row):
|
||
return row
|
||
return None
|
||
|
||
|
||
def find_by_biz(
|
||
db: Session, app_code: str, work: models.Work, activity_id: str, biz_key: str
|
||
) -> models.NodeDecision | None:
|
||
"""同一趟的两次表态:幂等记在这张表上,第二次原样回第一次的结果。"""
|
||
value = str(biz_key or "").strip()
|
||
if not value:
|
||
return None
|
||
return db.execute(
|
||
select(models.NodeDecision).where(
|
||
models.NodeDecision.app == app_code,
|
||
models.NodeDecision.work == work.id,
|
||
models.NodeDecision.activity == activity_id,
|
||
models.NodeDecision.biz_key == value,
|
||
)
|
||
).scalars().first()
|
||
|
||
|
||
def staged_for_work(db: Session, work_id: str, activity_id: str) -> list[models.NodeDecision]:
|
||
"""开始环节上挂着的外部表态:没有待办可挂,按单据 + 环节查。过期的就地作废。"""
|
||
rows = list(
|
||
db.execute(
|
||
select(models.NodeDecision)
|
||
.where(
|
||
models.NodeDecision.work == work_id,
|
||
models.NodeDecision.activity == activity_id,
|
||
models.NodeDecision.status == STATUS_STAGED,
|
||
)
|
||
.order_by(models.NodeDecision.id)
|
||
).scalars().all()
|
||
)
|
||
now = datetime.now()
|
||
for row in rows:
|
||
if row.expires_at is not None and row.expires_at <= now:
|
||
row.status = STATUS_EXPIRED
|
||
return [row for row in rows if row.status == STATUS_STAGED]
|
||
|
||
|
||
def staged_for_task(db: Session, task_id: str) -> list[models.NodeDecision]:
|
||
"""这条待办上还挂着哪些没点头的外部表态。过期的当场作废,别让审批页亮着死横幅。"""
|
||
rows = list(
|
||
db.execute(
|
||
select(models.NodeDecision)
|
||
.where(models.NodeDecision.task == task_id, models.NodeDecision.status == STATUS_STAGED)
|
||
.order_by(models.NodeDecision.id)
|
||
).scalars().all()
|
||
)
|
||
now = datetime.now()
|
||
live: list[models.NodeDecision] = []
|
||
for row in rows:
|
||
if row.expires_at is not None and row.expires_at <= now:
|
||
row.status = STATUS_EXPIRED
|
||
live.append(row)
|
||
else:
|
||
live.append(row)
|
||
return [row for row in rows if row.status == STATUS_STAGED]
|
||
|
||
|
||
def view(row: models.NodeDecision) -> dict:
|
||
return {
|
||
"id": row.id,
|
||
"app": row.app,
|
||
"appName": row.app_name,
|
||
# 对方原话那一格与请求同名:发进来什么,回显就是什么
|
||
"result": row.decision,
|
||
"kind": row.kind,
|
||
"kindLabel": DECISION_LABELS.get(row.kind, row.kind),
|
||
"route": row.route,
|
||
"opinion": row.opinion,
|
||
"data": dict(row.data or {}),
|
||
"bizKey": row.biz_key,
|
||
# 这条表态自己的走到哪一步了(staged / handled / rejected / expired)——
|
||
# 叫 state 不叫 status,是为了跟同一个响应里的 work.status(单据在不在跑)分开
|
||
"state": row.status,
|
||
"createTime": row.create_time.strftime("%Y-%m-%d %H:%M:%S") if row.create_time else "",
|
||
"expireTime": row.expires_at.strftime("%Y-%m-%d %H:%M:%S") if row.expires_at else "",
|
||
}
|
||
|
||
|
||
def work_of_decision(db: Session, row: models.NodeDecision) -> models.Work | None:
|
||
"""那次表态记的是哪张单:先按单据主键,认不出再按 job 号(代发那一路两样都记着)。"""
|
||
work = db.get(models.Work, str(row.work or "")) if str(row.work or "") else None
|
||
if work is None and str(row.job or ""):
|
||
work = db.execute(select(models.Work).where(models.Work.job == row.job)).scalars().first()
|
||
return work
|
||
|
||
|
||
def decision_expired(row: models.NodeDecision) -> bool:
|
||
"""停着等点头的那一条过没过有效期(过期的表态已经不生效了,与 ``rejected`` 同权)。"""
|
||
return row.expires_at is not None and row.expires_at <= datetime.now()
|
||
|
||
|
||
def decision_superseded(db: Session, row: models.NodeDecision) -> bool:
|
||
"""这一次进来的 ``bizKey`` 是不是已经**翻篇**:那次表态救不回这一趟,得让它重办。
|
||
|
||
原本的分寸是"一个 bizKey 一辈子只办一次",它默认对方每次表态编一个新号。而 ``reimb``
|
||
那一套流水号是按**报销记录**编的(``RE-20261027-005`` 这种,一条记录一辈子一个号),
|
||
退回去改、被驳回之后重新提交,用的都还是同一个号——那条分寸在这一路撑不住:
|
||
15:44 代发提交、15:48 发起人退回开始环节、16:26 对方按原号再推一次,OA 只回一句
|
||
"这个 bizKey 已经办过了",这张单就永远停在开始环节出不去了,而对方日志写着 succeeded。
|
||
|
||
三条判据同时成立才算翻篇,少一条都可能把一次正常重试打成第二次表态:
|
||
|
||
* 那张单还在跑,而且**又停回当初表态那一环**(被退回 / 被驳回钉回来 / 已办被撤回);
|
||
* 那一环此刻确实在等人做点什么——人工环节看有没有待办,开始环节停在起点就是等提交;
|
||
* 那次表态已经不生效:办掉的(那一次已经消费掉了)、被处理人驳回的、过期作废的。
|
||
还停在审批页上等点头的那一条不算,它该原样回放,别让人对着两条横幅挑一条。
|
||
"""
|
||
if row.status == STATUS_STAGED and not decision_expired(row):
|
||
return False
|
||
work = work_of_decision(db, row)
|
||
if work is None or str(work.status or "") != "running":
|
||
return False
|
||
if str(work.activity or "") != str(row.activity or ""):
|
||
return False
|
||
if str(work.activity_type or "") == "begin":
|
||
# 停在起点本身就等于"等人按提交":``hold`` 建的那一单与撤回已办退回起点的单
|
||
# 开始环节上没有待办行,只看待办会把这两种单永远锁死
|
||
return True
|
||
return bool(pending_tasks(db, work, str(row.activity or "")))
|
||
|
||
|
||
def supersede_note(db: Session, row: models.NodeDecision) -> str:
|
||
"""翻篇重办时要在响应里补的那一句(末尾带逗号,与 ``start_note`` 那种拼法一致)。"""
|
||
work = work_of_decision(db, row)
|
||
if work is None:
|
||
return ""
|
||
label = {
|
||
STATUS_HANDLED: "办过一次" + (f"(走的「{row.route or row.kind}」)" if (row.route or row.kind) else ""),
|
||
STATUS_REJECTED: f"被处理人驳回过({row.confirm_name or '无署名'})",
|
||
STATUS_EXPIRED: "过期作废",
|
||
STATUS_STAGED: "停在审批页上等确认,一直等到过期",
|
||
}
|
||
title = str(work.serial or work.job or "")
|
||
where = str(work.activity_name or "") or str(work.activity or "")
|
||
return (f"这个 bizKey 之前在 {title} 这一张上{label.get(row.status, '表过一次态')},"
|
||
f"那张单又退回到「{where}」,这次按新表态重新处理,")
|
||
|
||
|
||
def record(db: Session, base: dict, *, status: str, response: dict | None = None,
|
||
expires_at: datetime | None = None) -> models.NodeDecision:
|
||
"""把这一次表态记进台账:同一个幂等键上已有行就**就地改写**那一行。
|
||
|
||
``(app, work, activity, biz_key)`` 上有唯一键(``uq_node_decision_biz``),而对方那个
|
||
``bizKey`` 会被反复用到同一张单同一环上——退回去改完再提交就是第二次。插新行是
|
||
``IntegrityError``,不记账又会让下一次重试认不回这一趟、凭空多办一次,所以这一行的
|
||
语义跟着变成"这个 bizKey 在这一环上**最近一次**表态":字段、状态、响应快照一起改写,
|
||
上一趟的凭据留在流转流水与已办记录里,不靠这张表。
|
||
"""
|
||
biz = str(base.get("biz_key") or "")
|
||
existing = None
|
||
if biz:
|
||
existing = db.execute(
|
||
select(models.NodeDecision).where(
|
||
models.NodeDecision.app == str(base.get("app") or ""),
|
||
models.NodeDecision.work == str(base.get("work") or ""),
|
||
models.NodeDecision.activity == str(base.get("activity") or ""),
|
||
models.NodeDecision.biz_key == biz,
|
||
).order_by(models.NodeDecision.id.desc())
|
||
).scalars().first()
|
||
if existing is None:
|
||
row = models.NodeDecision(**base, status=status, response=response or {},
|
||
expires_at=expires_at)
|
||
db.add(row)
|
||
return row
|
||
for key, value in base.items():
|
||
setattr(existing, key, value)
|
||
existing.status = status
|
||
existing.response = response or {}
|
||
existing.expires_at = expires_at
|
||
# 上一趟留在这一行上的确认痕迹要抹掉:不然横幅上还写着"某某已确认",说的却是上一次
|
||
existing.confirm_by = ""
|
||
existing.confirm_name = ""
|
||
existing.confirm_at = None
|
||
existing.confirm_note = ""
|
||
return existing
|
||
|
||
|
||
def current_state(db: Session, row: models.NodeDecision) -> str:
|
||
"""那次表态之后,那张单**现在**在哪一环。只给回放那一句用。
|
||
|
||
``bizKey`` 是一次表态的号,办过就永久用掉了,所以回放永远回 200 与第一次那份响应快照。
|
||
生产上撞的正是"这句话不够用":15:44 对方代发并提交了 ``FYBX202610270020``,15:48 发起人
|
||
把那张单退回到开始环节,15:54 对方拿同一个 ``bizKey`` 再回写一次,OA 回 200 与第一次那份
|
||
响应(里面写着"部门主管"),他们日志记成 ``writeback succeeded``,而那张单其实正停在
|
||
开始环节等人和对方任何一方重新提交。现在在哪一环,读一次单据就知道,不该让对方猜。
|
||
"""
|
||
work = work_of_decision(db, row)
|
||
if work is None:
|
||
return ""
|
||
label = {"completed": "已办结归档", "terminated": "已终止", "canceled": "已作废"}
|
||
title = str(work.serial or work.job or "")
|
||
if str(work.status or "") != "running":
|
||
return f"那张单({title})现在{label.get(str(work.status), f'是 {work.status} 状态')}"
|
||
where = str(work.activity_name or "") or str(work.activity or "")
|
||
if str(work.activity or "") != str(row.activity or ""):
|
||
return f"那张单({title})现在在「{where}」"
|
||
# 还停在当初表态那一环,却没有任何待办可表态:这一环没人等,回放了也不会有人推进
|
||
return (f"那张单({title})现在还停在「{where}」,但那一环上没有可表态的待办——"
|
||
"等发起人自己在 OA 提交,或让处理人先把这一环打开")
|
||
|
||
|
||
def replay(row: models.NodeDecision, db: Session | None = None) -> dict:
|
||
"""同一个 ``bizKey`` 再来一次:原样回第一次的结果,重试不变成重复表态。
|
||
|
||
停着的回「已经停在那等确认」;办掉的回办掉那一刻那份响应快照;被驳回 / 作废的
|
||
回一句人话——它不是失败,是"这一趟你已经表态过了,而且那个表态没成"。
|
||
|
||
给了 ``db`` 就把那张单**现在**在哪一环补进那一句(:func:`current_state`):那份快照是
|
||
第一次办的时候拍的,拿它当"现在"会骗人。
|
||
"""
|
||
if row.status == STATUS_STAGED:
|
||
return {
|
||
"staged": True,
|
||
"decisionId": row.id,
|
||
"decision": view(row),
|
||
"route": row.route,
|
||
"activity": row.activity_name,
|
||
"alreadyStaged": True,
|
||
"note": "这个 bizKey 的表态已经在等处理人确认,本次调用没有另起一份",
|
||
}
|
||
if row.status == STATUS_HANDLED:
|
||
payload = dict(row.response or {})
|
||
payload["alreadyHandled"] = True
|
||
payload.setdefault("note", "这个 bizKey 的表态已经办过了,本次调用没有改动任何东西")
|
||
if db is not None:
|
||
hint = current_state(db, row)
|
||
if hint:
|
||
payload["note"] = f"{payload['note']}。{hint}"
|
||
return payload
|
||
note = (
|
||
f"这个 bizKey 的表态已被处理人驳回({row.confirm_name or '无署名'}),本次调用没有改动任何东西"
|
||
if row.status == STATUS_REJECTED
|
||
else "这个 bizKey 的表态已作废,本次调用没有改动任何东西"
|
||
)
|
||
raise bad_request(note, reason="NODE_DECISION_CLOSED")
|
||
|
||
|
||
def invalidate_for_work(db: Session, work_id: str, status: str) -> int:
|
||
"""单据落定(办结 / 终止 / 作废)时,这张单上所有还停着的表态就地作废。
|
||
|
||
同一事务里跑:归档与表态作废要么一起成、要么一起滚,别让审批页亮着一条
|
||
指向死人单据的横幅。返回作废条数;一张单一次表态都没有时这里是安静的一步。
|
||
"""
|
||
from sqlalchemy import update
|
||
|
||
label = {"completed": "办结", "terminated": "终止", "canceled": "作废"}.get(status, status or "落定")
|
||
rows = db.execute(
|
||
update(models.NodeDecision)
|
||
.where(models.NodeDecision.work == work_id, models.NodeDecision.status == STATUS_STAGED)
|
||
.values(status=STATUS_EXPIRED, confirm_note=f"单据已{label},表态一并作废")
|
||
)
|
||
return rows.rowcount or 0
|