985 lines
49 KiB
Python
985 lines
49 KiB
Python
"""写回模板与发件箱接口 -- 三层配置里的 L2(模板)与发件箱的读、重推、确认。
|
||
|
||
分寸和数据源、额度一致:**改映射要 ``design:integration``,读模板列表只要登录**(流程设计
|
||
器要把模板列成下拉给人挑)。发件箱的读与重推同样要权限码——重推是往上游写数据的手,
|
||
不是谁都能点的按钮。
|
||
|
||
预览和试跑分开是刻意的:预览只渲染不发送,什么时候点都安全;试跑真发一次,所以要显式
|
||
确认(影子数据源除外)。配错一行映射的代价是上游多一张凭证,这个区别必须体现在界面上。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import re
|
||
from datetime import datetime
|
||
from types import SimpleNamespace
|
||
from typing import Any
|
||
|
||
from fastapi import APIRouter, Depends, Query
|
||
from sqlalchemy import or_, select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import models, schemas
|
||
from ..db import get_db
|
||
from ..deps import CurrentUser, current_user, require_permission
|
||
from ..envelope import bad_request, not_found, ok
|
||
from ..engine import engine
|
||
from ..service import autofill, fetch, mapping, outbox
|
||
|
||
router = APIRouter(tags=["integration"])
|
||
|
||
CODE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
||
METHODS = ("GET", "POST", "PUT", "PATCH", "DELETE")
|
||
#: 列表一次最多回这么多条:发件箱只增不减,不设上限能一次拖垮浏览器
|
||
LIST_LIMIT = 300
|
||
|
||
|
||
def get_template(db: Session, code: str) -> models.Integration | None:
|
||
"""按编码取模板(编码是 L3 与发件箱里唯一被记下来的引用)。"""
|
||
if not code:
|
||
return None
|
||
return db.execute(
|
||
select(models.Integration).where(models.Integration.code == str(code).strip())
|
||
).scalar_one_or_none()
|
||
|
||
|
||
def _stamp(value: datetime | None) -> str:
|
||
return value.strftime("%Y-%m-%d %H:%M:%S") if value else ""
|
||
|
||
|
||
def _view(row: models.Integration) -> dict:
|
||
return {
|
||
"id": row.id,
|
||
"code": row.code,
|
||
"name": row.name,
|
||
"enabled": row.enabled,
|
||
"source": row.source,
|
||
"bizForm": row.biz_form,
|
||
"triggerEvent": row.trigger_event,
|
||
# 「什么时候发」里终态那几条(办结 / 终止 / 作废,可以多选也可以空着)。
|
||
# 界面上勾的是这一格;上面那一格是给它留的兼容读法,也是旧写法 activity 的落脚点。
|
||
"triggerEvents": list(mapping.terminal_events_of(row)),
|
||
"eventKey": row.event_key,
|
||
"refireOnRevisit": bool(getattr(row, "refire_revisit", False)),
|
||
"sendCondition": dict(row.send_condition or {}),
|
||
"payload": dict(row.payload or {}),
|
||
"idemRule": row.idem_rule,
|
||
"resultWrite": list(row.result_write or []),
|
||
"onFailure": row.on_failure,
|
||
"failRoute": row.fail_route,
|
||
"retries": row.retries,
|
||
"maxAgeHours": row.max_age_hours,
|
||
"reversalCode": row.reversal_code,
|
||
"reconCode": row.recon_code,
|
||
"sample": dict(row.sample or {}),
|
||
"remark": row.remark,
|
||
"creatorName": row.creator_name,
|
||
"updateTime": _stamp(getattr(row, "update_time", None)),
|
||
# 报文是**出域数据**(设计文档 §13):这份清单让配模板的人当场看见
|
||
# "这一条会把表单里哪几格发给外部系统",而不是等上线后被安全同事问出来
|
||
"outFields": mapping.out_fields_of(row.payload),
|
||
}
|
||
|
||
|
||
def _message_view(row: models.OutboundMessage, *, full: bool = False) -> dict:
|
||
item = {
|
||
"id": row.id,
|
||
"source": row.source,
|
||
"integration": row.integration,
|
||
"event": row.event,
|
||
"eventKey": row.event_key,
|
||
# 哪一个时刻触发的(到达 / 通过后 / 退回 / 撤回);三条终态与手工送审是空串。
|
||
# 文案也一并给出去:这份说法后端只有一处(mapping.TRIGGER_LABELS),界面别再翻一遍
|
||
"phase": str(row.phase or ""),
|
||
"phaseLabel": mapping.TRIGGER_LABELS.get(str(row.phase or ""), ""),
|
||
# 退回那一刻还要写明**退到哪一环**、**这一退是谁按的**:发件箱那一行说得出具体的落点
|
||
# 与通道,运维才知道这条回声该不该发。升级前入队的老报文没这两格,一律回空串。
|
||
"actionTarget": str((row.action_data or {}).get("target") or ""),
|
||
"actionTargetName": str((row.action_data or {}).get("target_name") or ""),
|
||
"actionVia": mapping.goback_via_of((row.action_data or {}).get("via")),
|
||
"actionViaName": mapping.goback_via_name((row.action_data or {}).get("via")),
|
||
"work": row.work,
|
||
"job": row.job,
|
||
"serial": row.serial,
|
||
"title": row.title,
|
||
"revision": row.revision,
|
||
"idem": row.idem,
|
||
"method": row.method,
|
||
"url": row.url,
|
||
"status": row.status,
|
||
"attempts": row.attempts,
|
||
"nextAttemptAt": _stamp(row.next_attempt_at),
|
||
"sentAt": _stamp(row.sent_at),
|
||
"lastError": row.last_error,
|
||
"ms": row.ms,
|
||
"externalRef": row.external_ref,
|
||
"cancels": row.cancels,
|
||
"needsReversal": bool(row.needs_reversal),
|
||
"shadowed": bool(row.shadowed),
|
||
"onFailure": row.on_failure,
|
||
"actorName": row.actor_name,
|
||
"createTime": _stamp(getattr(row, "create_time", None)),
|
||
"updateTime": _stamp(getattr(row, "update_time", None)),
|
||
}
|
||
if full:
|
||
item["payload"] = dict(row.payload or {})
|
||
item["response"] = dict(row.response or {})
|
||
return item
|
||
|
||
|
||
def _clean(body: schemas.IntegrationBody) -> dict:
|
||
"""请求体收成能直接往列上赋的形状,顺手把明显不合法的挡在外面。"""
|
||
event = str(body.trigger_event or "").strip()
|
||
if event not in models.Integration.EVENTS:
|
||
raise bad_request("触发事件不支持:" + event)
|
||
# 「什么时候发」是一份清单。没带这一格的旧客户端与旧导出件按 triggerEvent 那一条算,
|
||
# 于是同一份配置在新老两边存的是同一个意思。
|
||
given = body.trigger_events if "trigger_events" in body.model_fields_set else None
|
||
raw_events = given if given is not None else (
|
||
# 没带这一格的旧客户端与旧导出件按 triggerEvent 那一条算
|
||
[event] if event in models.Integration.TERMINAL_EVENTS else []
|
||
)
|
||
if not isinstance(raw_events, list):
|
||
raise bad_request("「什么时候发」得是一份清单")
|
||
# 认不得的取值在这儿就挡下来,别让它安静地消失在清洗里:清洗只留认识的那几条,
|
||
# 于是"界面上勾了、终态那一刻却没发"会变成一件没人被通知的事(环节的时刻最容易误填进来)
|
||
unknown = [str(item or "").strip() for item in raw_events
|
||
if str(item or "").strip() not in models.Integration.TERMINAL_EVENTS]
|
||
if unknown:
|
||
raise bad_request(f"「什么时候发」里有不支持的取值:{'、'.join(unknown)}"
|
||
"(这一格只有办结 / 终止 / 作废;环节那一刻发在流程设计器的挂载上配)")
|
||
events = mapping.normalize_terminal_events(raw_events)
|
||
if event == models.Integration.EVENT_ACTIVITY and events:
|
||
raise bad_request("这条模板还写着旧写法「到达某环节」,不能再勾终态:两个时刻会各发一次、"
|
||
"两条报文幂等键不同,上游会当成两笔。先用界面下方那个按钮把它搬到环节上,"
|
||
"再勾终态那几条")
|
||
failure = str(body.on_failure or "").strip() or models.Integration.FAILURE_CONTINUE
|
||
if failure not in models.Integration.FAILURE_POLICIES:
|
||
raise bad_request("失败策略不支持:" + failure)
|
||
if not isinstance(body.payload, dict):
|
||
raise bad_request("映射配置得是一个对象")
|
||
method = str(body.payload.get("method") or "POST").upper()
|
||
if method not in METHODS:
|
||
raise bad_request(f"请求方法只支持 {'、'.join(METHODS)}")
|
||
if not isinstance(body.result_write, list):
|
||
raise bad_request("响应回写得是一个数组")
|
||
retries = int(body.retries or 0)
|
||
if not 0 <= retries <= 20:
|
||
raise bad_request("重试次数需要在 0-20 之间")
|
||
return {
|
||
"name": str(body.name or "").strip(),
|
||
"enabled": bool(body.enabled),
|
||
"source": str(body.source or "").strip(),
|
||
"biz_form": str(body.biz_form or "").strip(),
|
||
# 新形状是这份清单。终态可以多选,也可以一条都不勾——不勾就是"时机还没定":
|
||
# 这条模板要么被挂在某个流程环节上(那一刻才谈得上时机),要么只在集成页人工重推。
|
||
"trigger_events": events,
|
||
# 老的那一格照旧写:清单第一条给老读法(列表按事件筛、导出件、别处的提示文案)留着;
|
||
# 清单为空时,旧的环节声明还留着就写 activity,否则写 manual(= 自己不自动发)。
|
||
"trigger_event": events[0] if events else (
|
||
event if event == models.Integration.EVENT_ACTIVITY else models.Integration.EVENT_MANUAL
|
||
),
|
||
# 只有旧写法「到达某环节」需要环节 id,其它时候带着它只会让人误以为还在生效
|
||
"event_key": str(body.event_key or "").strip()
|
||
if event == models.Integration.EVENT_ACTIVITY else "",
|
||
# 「重复到达时重发」管的是环节那一刻的报文(发件箱里 event=activity 那一类)。
|
||
# 挂在环节上的模板也算这一类,所以不能拿模板自己勾了什么触发点当开关——以前这一格
|
||
# 只在「到达某环节」时留值,挂到环节上、自己写着办结时的那批模板根本勾不上这一项。
|
||
"refire_revisit": bool(body.refire_revisit),
|
||
# 「哪些单才发」:没写出有效规则一律落成空 dict,别让空壳条件冒充"只发一部分"
|
||
"send_condition": mapping.clean_condition(body.send_condition),
|
||
"payload": {**body.payload, "method": method},
|
||
"idem_rule": str(body.idem_rule or "").strip(),
|
||
"result_write": [item for item in body.result_write if isinstance(item, dict)],
|
||
"on_failure": failure,
|
||
"fail_route": str(body.fail_route or "").strip(),
|
||
"retries": retries,
|
||
"max_age_hours": max(0, int(body.max_age_hours or 0)),
|
||
"reversal_code": str(body.reversal_code or "").strip(),
|
||
"recon_code": str(body.recon_code or "").strip(),
|
||
"remark": str(body.remark or "").strip(),
|
||
}
|
||
|
||
|
||
def _draft(body: schemas.IntegrationBody) -> models.Integration:
|
||
"""一份**没保存**的模板,给校验 / 预览 / 试跑用:先试对再存,不是先存再试错。"""
|
||
draft = models.Integration(code=str(body.code or "draft"), name=str(body.name or "待预览模板"))
|
||
for column, value in _clean(body).items():
|
||
setattr(draft, column, value)
|
||
return draft
|
||
|
||
|
||
def _problems(db: Session, draft: models.Integration) -> list[str]:
|
||
"""结构、引用、字段口径一次查完。与表单 ``form_problems`` 同一做派。"""
|
||
source = fetch.get_source(db, draft.source)
|
||
fields = autofill.form_fields(db, draft.biz_form) if draft.biz_form else None
|
||
payload = {
|
||
"code": draft.code,
|
||
"name": draft.name,
|
||
"source": draft.source,
|
||
"trigger_event": draft.trigger_event,
|
||
"triggerEvents": list(draft.trigger_events or []),
|
||
"eventKey": draft.event_key,
|
||
"refireOnRevisit": bool(getattr(draft, "refire_revisit", False)),
|
||
"condition": dict(draft.send_condition or {}),
|
||
"onFailure": draft.on_failure,
|
||
"failRoute": draft.fail_route,
|
||
"idemRule": draft.idem_rule,
|
||
"payload": dict(draft.payload or {}),
|
||
"resultWrite": list(draft.result_write or []),
|
||
}
|
||
problems = mapping.problems(db, payload, fields=fields, source=source)
|
||
if draft.reversal_code:
|
||
reversal = get_template(db, draft.reversal_code)
|
||
if reversal is None:
|
||
problems.append(f"冲销模板不存在:{draft.reversal_code}")
|
||
elif reversal.code == draft.code:
|
||
problems.append("冲销模板不能是它自己")
|
||
if draft.recon_code and get_template(db, draft.recon_code) is None:
|
||
problems.append(f"对账模板不存在:{draft.recon_code}")
|
||
return problems
|
||
|
||
|
||
def _checked(db: Session, draft: models.Integration) -> None:
|
||
problems = _problems(db, draft)
|
||
if problems:
|
||
raise bad_request("写回模板还有问题:" + ";".join(problems[:6]), reason="DESIGN_INVALID")
|
||
|
||
|
||
def _preview_activity(db: Session, work) -> Any:
|
||
"""预览与试跑里的 ``{activity.x}``:按这张单**此刻停着的那一环**算。
|
||
|
||
一条模板能挂在好几个环节上,预览时并没有"哪一个触发点"这个事实,所以拿真单当前
|
||
那一环替它——要校验挂在某个环节上的效果,就挑一张正停在那一环的单来预览。
|
||
手工填的那份数据没有单据行,那一格渲染成空串。
|
||
"""
|
||
node = str(getattr(work, "activity", "") or "").strip()
|
||
return db.get(models.Activity, node) if node else None
|
||
|
||
|
||
def _render_target(db: Session, body: schemas.IntegrationRenderBody) -> tuple[models.Integration, Any, dict]:
|
||
"""渲染要用的(模板, 单据, 表单数据)。单据可以是真实单,也可以是手工填的那一份。"""
|
||
draft = _draft(body.template) if body.template is not None else None
|
||
if draft is None:
|
||
stored = get_template(db, body.code)
|
||
if stored is None:
|
||
raise not_found("写回模板不存在")
|
||
draft = stored
|
||
work = None
|
||
if body.work_id:
|
||
work = db.get(models.Work, body.work_id) or db.get(models.WorkCompleted, body.work_id)
|
||
if work is None:
|
||
raise not_found("要用来预览的单据不存在")
|
||
elif body.data:
|
||
# 手工填的数据没有"单据行",给一个空壳让 {work.x} / {auto:serial} 渲染成空而不是报错
|
||
work = SimpleNamespace(id="", job="", serial="", title="", process="",
|
||
process_name="", creator="", creator_person="",
|
||
creator_identity="", creator_unit="")
|
||
data = dict(body.data) if body.data else dict(getattr(work, "data", None) or {})
|
||
return draft, work, data
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# L2:写回模板
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
@router.get("/design/integrations")
|
||
def list_templates(
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
keyword: str = Query(""),
|
||
bizForm: str = Query("", alias="bizForm"), # noqa: N803 - 对外保持驼峰
|
||
event: str = Query(""),
|
||
enabledOnly: str = Query("", alias="enabledOnly"), # noqa: N803
|
||
) -> dict:
|
||
# 读列表只要登录:流程设计器要把模板列成下拉给人挑
|
||
stmt = select(models.Integration)
|
||
text = str(keyword or "").strip()
|
||
if text:
|
||
like = f"%{text}%"
|
||
stmt = stmt.where(or_(models.Integration.code.like(like), models.Integration.name.like(like)))
|
||
if bizForm:
|
||
stmt = stmt.where(models.Integration.biz_form == bizForm)
|
||
# 三条终态现在是一份清单,比不了标量;环节与手工那两档仍旧读老的那一格
|
||
filter_terminal = event in models.Integration.TERMINAL_EVENTS
|
||
if event and not filter_terminal:
|
||
stmt = stmt.where(models.Integration.trigger_event == event)
|
||
if enabledOnly.lower() in ("1", "true", "yes"):
|
||
stmt = stmt.where(models.Integration.enabled.is_(True))
|
||
rows = db.execute(stmt.order_by(models.Integration.code).limit(LIST_LIMIT)).scalars().all()
|
||
if filter_terminal:
|
||
rows = [row for row in rows if event in mapping.terminal_events_of(row)]
|
||
return ok([_view(row) for row in rows])
|
||
|
||
|
||
@router.get("/design/integrations/options")
|
||
def template_options(
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
bizForm: str = Query("", alias="bizForm"), # noqa: N803
|
||
) -> dict:
|
||
"""给流程设计器的那个下拉:只给启用中的模板。"""
|
||
stmt = select(models.Integration).where(models.Integration.enabled.is_(True))
|
||
if bizForm:
|
||
stmt = stmt.where(models.Integration.biz_form.in_([bizForm, ""]))
|
||
rows = db.execute(stmt.order_by(models.Integration.code)).scalars().all()
|
||
return ok([{
|
||
"code": row.code,
|
||
"name": row.name,
|
||
"source": row.source,
|
||
"triggerEvent": row.trigger_event,
|
||
"triggerEvents": list(mapping.terminal_events_of(row)),
|
||
"eventKey": row.event_key,
|
||
"bizForm": row.biz_form,
|
||
"onFailure": row.on_failure,
|
||
"remark": row.remark,
|
||
} for row in rows])
|
||
|
||
|
||
@router.get("/design/integrations/activity-options")
|
||
def activity_options(
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
keyword: str = Query(""),
|
||
) -> dict:
|
||
"""模板页那个「到达某环节」的下拉:以前是一格自由文本,填错 id 就是静默不发。
|
||
|
||
环节 id 是每条流程自己的主键,人记不住也不该记:这里按「流程 / 环节」摊开来让人挑。
|
||
不按环节类型筛——挂在人工环节最常见,挂在结束 / 汇聚上同样有意义("走到这里就该通知上游"),
|
||
类型只是原样带回界面上标一下,不替人做主。
|
||
"""
|
||
stmt = select(models.Activity, models.Process.name).join(
|
||
models.Process, models.Process.id == models.Activity.process
|
||
)
|
||
text = str(keyword or "").strip()
|
||
if text:
|
||
like = f"%{text}%"
|
||
stmt = stmt.where(or_(models.Activity.name.like(like), models.Process.name.like(like)))
|
||
rows = db.execute(stmt.order_by(models.Process.name, models.Activity.order_number).limit(500)).all()
|
||
return ok([
|
||
{"value": activity.id, "label": f"{process_name} / {activity.name}",
|
||
"process": str(process_name or ""), "activity": activity.name, "type": activity.type}
|
||
for activity, process_name in rows
|
||
])
|
||
|
||
|
||
def audit(db: Session) -> list[dict]:
|
||
"""全库写回配置体检:哪一条现在**真的**不会发、哪一条会发两遍。
|
||
|
||
为什么要有这一份(口径见 ``docs/node-writeback-config.md`` §9.5):保存时才验的那把尺子
|
||
只管得到"这一次保存的那一条"。环节 id 是每条流程自己的主键,复制流程、恢复版本、
|
||
导到另一套环境都会换掉它,模板上那句「到达某环节」就此指向一个不存在的环节——不报错、
|
||
不入队、发件箱一条记录都不留;环节挂载里点名的模板可以早被删了,终态勾选也可以和挂载
|
||
两头点名(凭证开两张)。这些行躺在库里照常运行,只有走到那一刻才发现。
|
||
|
||
这里**不另写一套判断**:模板那一格走 ``_problems``(与保存模板同一把尺子,含环节 id
|
||
还在不在),环节挂载走 ``mapping.mount_problems``(与保存流程同一把尺子)。两处都是
|
||
设计期的配置表,几十行的量,全库过一遍也就几十次查询,这个钱值得花。
|
||
"""
|
||
items: list[dict] = []
|
||
for row in db.scalars(select(models.Integration).order_by(models.Integration.code)):
|
||
problems = _problems(db, row)
|
||
if problems:
|
||
items.append({"kind": "template", "code": str(row.code or ""),
|
||
"name": str(row.name or row.code or ""), "process": "",
|
||
"problems": problems})
|
||
for process in db.scalars(select(models.Process).order_by(models.Process.name)):
|
||
activities = list(db.scalars(
|
||
select(models.Activity).where(models.Activity.process == process.id)))
|
||
# 没挂写回的流程一次都不问:绝大多数流程压根不碰上游
|
||
if not any(mapping.mount_of(activity) for activity in activities):
|
||
continue
|
||
route_refs = [value for item in db.execute(
|
||
select(models.Route.id, models.Route.name).where(models.Route.process == process.id)
|
||
).all() for value in item]
|
||
problems = mapping.mount_problems(
|
||
db, activities, route_refs, engine.goback_universe_for(db, str(process.id or "")))
|
||
if problems:
|
||
items.append({"kind": "mount", "code": "", "name": str(process.name or process.id),
|
||
"process": str(process.id or ""), "problems": problems})
|
||
return items
|
||
|
||
|
||
@router.get("/design/integrations/audit", dependencies=[
|
||
Depends(require_permission("design:integration"))])
|
||
def audit_templates(db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)) -> dict:
|
||
"""集成页顶部那条「配置体检」:整个写回配置里现在带着病的行,一次摊开。
|
||
|
||
读接口,不要改东西的权限:体检报告是给人看的,看得见病不该先有一把手术刀。
|
||
"""
|
||
items = audit(db)
|
||
return ok({"count": sum(len(item["problems"]) for item in items), "items": items})
|
||
|
||
|
||
def _activity_names(db: Session, activity_id: str) -> dict:
|
||
"""环节 id -> 界面要的那一小段(流程名 / 环节名 / 类型)。环节已经不在了返回空 dict。"""
|
||
if not activity_id:
|
||
return {}
|
||
hit = db.execute(
|
||
select(models.Activity, models.Process.name)
|
||
.join(models.Process, models.Process.id == models.Activity.process)
|
||
.where(models.Activity.id == activity_id)
|
||
).first()
|
||
if hit is None:
|
||
return {"value": activity_id, "label": "这个环节已经不在了", "process": "",
|
||
"activity": "", "type": "", "missing": True}
|
||
activity, process_name = hit
|
||
return {
|
||
"value": str(activity.id or ""),
|
||
"label": f"{process_name} / {activity.name}",
|
||
"process": str(activity.process or ""),
|
||
"processName": str(process_name or ""),
|
||
"activity": activity.name,
|
||
"type": activity.type,
|
||
}
|
||
|
||
|
||
@router.get("/design/integrations/{code}/firing")
|
||
def template_firing(code: str, db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)) -> dict:
|
||
"""这条模板**实际上**会在哪些时刻发出去:勾的终态 + 被挂在哪些环节的哪一时刻。
|
||
|
||
"什么时候发"是两处绑定的结果——终态勾在模板上,环节那一刻挂在流程上(L3)。配模板的人
|
||
在这一步只知道自己要发什么,所以界面要能看到合并后的答案,而不是自己回流程里回忆一遍。
|
||
这份清单同时是"这条模板还没有任何触发点"唯一的可见处:那一格留空不是错误,是还没定时机。
|
||
|
||
挂在哪些环节上只能扫一遍环节配置(那是一段 JSON,没有索引可走):``oa_activity`` 是
|
||
设计期的配置表,与 ``hub_refs`` 扫审批人引用同一做法,在 Python 里过一遍。
|
||
"""
|
||
row = get_template(db, code)
|
||
if row is None:
|
||
raise not_found("写回模板不存在")
|
||
mounts: list[dict] = []
|
||
rows = db.execute(
|
||
select(models.Activity, models.Process.name)
|
||
.join(models.Process, models.Process.id == models.Activity.process)
|
||
.order_by(models.Process.name, models.Activity.order_number, models.Activity.id)
|
||
).all()
|
||
# 落点筛子存的是环节 id,回显要念出环节叫什么:这一屏扫的就是全库环节,现成有一份名字
|
||
activity_names = {str(item.id or ""): str(item.name or item.id or "") for item, _ in rows}
|
||
for activity, process_name in rows:
|
||
mount = mapping.mount_of(activity)
|
||
if not mount:
|
||
continue
|
||
blocks = mapping.mount_blocks(mount)
|
||
labels = [str(activity.name or activity.id)] if len(blocks) == 1 else \
|
||
[f"{activity.name or activity.id} · 第 {index + 1} 条规则" for index in range(len(blocks))]
|
||
for label, block in zip(labels, blocks):
|
||
if code not in [name for name, _ in mapping.mount_entries(block)]:
|
||
continue
|
||
triggers = mapping.mount_triggers(block)
|
||
# 「本环节被退回时」还要按落点与来源各筛一道,两格都没筛 = 任何退回都发
|
||
to_tokens = mapping.mount_goback_to(block)
|
||
via_tokens = mapping.mount_goback_via(block)
|
||
mounts.append({
|
||
"process": str(activity.process or ""),
|
||
"processName": str(process_name or ""),
|
||
"activity": str(activity.id or ""),
|
||
"activityName": label,
|
||
"activityType": str(activity.type or ""),
|
||
# 一条规则可以勾好几个时刻:trigger 仍旧给第一个(旧界面读它),
|
||
# triggers / triggerText 才是完整答案
|
||
"trigger": triggers[0],
|
||
"triggers": triggers,
|
||
"triggerText": mapping.trigger_text(triggers),
|
||
"goBackTo": to_tokens,
|
||
"goBackToText": mapping.goback_text(to_tokens, activity_names) if to_tokens else "",
|
||
"goBackVia": via_tokens,
|
||
"goBackViaText": mapping.goback_via_text(via_tokens) if via_tokens else "",
|
||
})
|
||
declared = mapping.declared_activity_of(row)
|
||
return ok({
|
||
"terminalEvents": list(mapping.terminal_events_of(row)),
|
||
# 旧写法:模板自己点名了一个环节。新的环节时机不再从这儿走,界面上标着"旧写法"给出入口
|
||
"declaredActivity": _activity_names(db, declared) if declared else None,
|
||
"mounts": mounts,
|
||
})
|
||
|
||
|
||
def _mount_append(mount: dict, code: str, trigger: str) -> dict:
|
||
"""把一个模板编码加进环节挂载,尽量不改已有的形状。
|
||
|
||
只有一条规则时继续平铺(与流程设计器写回的那份形状一致),要新增一条不同时刻的规则
|
||
才换成 ``blocks``——口径见 ``docs/node-writeback-config.md`` §2。
|
||
"""
|
||
# 先抄一份再改:mount_of 交回来的是环节 config 里那个对象本身,
|
||
# 就地加一格会让"校验没过、这次不写"的路径也把自己弄脏
|
||
mount = dict(mount or {})
|
||
raw_blocks = mount.get("blocks")
|
||
blocks = [dict(block) for block in raw_blocks if isinstance(block, dict)] \
|
||
if isinstance(raw_blocks, list) and raw_blocks else []
|
||
same = [block for block in (blocks or [mount]) if trigger in mapping.mount_triggers(block)]
|
||
if same:
|
||
target = same[0]
|
||
target["integrations"] = list(target.get("integrations") or []) + [code]
|
||
return {"blocks": blocks} if blocks else target
|
||
fresh = {"integrations": [code], "trigger": trigger}
|
||
if blocks:
|
||
return {"blocks": [*blocks, fresh]}
|
||
# 平铺那一块的时刻不一样:留着它,另起一块(正好两块,这才换形状)
|
||
return {"blocks": [dict(mount), fresh]}
|
||
|
||
|
||
@router.post("/design/integrations/{code}/mount", dependencies=[
|
||
Depends(require_permission("design:integration")),
|
||
Depends(require_permission("design:process")),
|
||
])
|
||
def mount_on_activity(
|
||
code: str, body: schemas.IntegrationMountBody, db: Session = Depends(get_db)
|
||
) -> dict:
|
||
"""把旧写法「到达某环节」搬到流程环节上:写挂载与撤声明在同一事务里,中间不留空档。
|
||
|
||
新配置的环节时机一律在流程设计器里配,不走这个口;它是留给存量配置的出路——模板上存着
|
||
一条流程的环节 id,复制流程、导到别的环境都会换 id,绑在这儿迟早静默失效。
|
||
改的是流程配置,所以要 ``design:integration`` + ``design:process`` 两个权限。
|
||
"""
|
||
row = get_template(db, code)
|
||
if row is None:
|
||
raise not_found("写回模板不存在")
|
||
activity_id = str(body.activity or "").strip()
|
||
activity = db.get(models.Activity, activity_id) if activity_id else None
|
||
if activity is None:
|
||
raise bad_request("要挂到这个环节不存在,先去流程设计器确认一下这个环节还在不在")
|
||
trigger = mapping.trigger_of(body.trigger)
|
||
if trigger not in mapping.TRIGGERS:
|
||
raise bad_request(f"触发时机不支持:{body.trigger}"
|
||
f"(可选 {mapping.trigger_text(mapping.TRIGGERS)})")
|
||
mount = mapping.mount_of(activity)
|
||
if code in mapping.mount_codes(mount):
|
||
raise bad_request(f"这个环节已经挂了模板「{row.name}」,不用再搬一次;要去掉旧声明就到流程设计器改")
|
||
new_mount = _mount_append(mount, code, trigger)
|
||
route_refs = [value for item in db.execute(
|
||
select(models.Route.id, models.Route.name).where(models.Route.process == activity.process)
|
||
).all() for value in item]
|
||
# 校验要看得到"改完之后"的那一段挂载:拿一份只换了 writeback 的副本去过同一把尺子
|
||
probe = SimpleNamespace(id=activity.id, name=activity.name, type=activity.type,
|
||
process=activity.process, form=activity.form,
|
||
config={**(activity.config or {}), "writeback": new_mount})
|
||
problems = mapping.mount_problems(db, [probe], route_refs)
|
||
if problems:
|
||
raise bad_request("挂到这个环节上还有问题:" + ";".join(problems[:4]), reason="DESIGN_INVALID")
|
||
config = activity.config if isinstance(activity.config, dict) else {}
|
||
config["writeback"] = new_mount
|
||
activity.config = config
|
||
row.trigger_event = models.Integration.EVENT_MANUAL
|
||
row.event_key = ""
|
||
db.commit()
|
||
# 环节触发点那份名单变了:不作废的话,刚配好的这一次在别的副本上压根不会入队
|
||
outbox.invalidate_node_triggers()
|
||
return ok({"mounted": True, "activity": _activity_names(db, activity_id), "trigger": trigger})
|
||
|
||
|
||
@router.post("/design/integrations/validate", dependencies=[Depends(require_permission("design:integration"))])
|
||
def validate_template(
|
||
body: schemas.IntegrationRenderBody, db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)
|
||
) -> dict:
|
||
draft = _draft(body.template) if body.template is not None else get_template(db, body.code)
|
||
if draft is None:
|
||
raise not_found("写回模板不存在")
|
||
problems = _problems(db, draft)
|
||
return ok({"valid": not problems, "problems": problems,
|
||
"outFields": mapping.out_fields_of(draft.payload)})
|
||
|
||
|
||
@router.post("/design/integrations/preview", dependencies=[Depends(require_permission("design:integration"))])
|
||
def preview_template(
|
||
body: schemas.IntegrationRenderBody, db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)
|
||
) -> dict:
|
||
"""报文预览:按真实单据(或手工填的一版数据)渲染出将要发送的 JSON,**不发送**。"""
|
||
draft, work, data = _render_target(db, body)
|
||
source = fetch.get_source(db, draft.source)
|
||
if source is None:
|
||
raise bad_request(f"数据源 {draft.source} 不存在,拼不出要发往哪里")
|
||
try:
|
||
method, url, payload = mapping.render_for(
|
||
db, source, draft, data=data, work=work, activity=_preview_activity(db, work))
|
||
except (mapping.RenderError, ValueError) as exc:
|
||
raise bad_request(f"报文没渲染出来:{exc}") from exc
|
||
return ok({"method": method, "url": url, "payload": payload,
|
||
"outFields": mapping.out_fields_of(draft.payload)})
|
||
|
||
|
||
@router.post("/design/integrations/dry-run", dependencies=[Depends(require_permission("design:integration"))])
|
||
def dry_run_template(
|
||
body: schemas.IntegrationDryRunBody,
|
||
user: CurrentUser = Depends(current_user),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
"""试跑:真发一次,报文与响应留在模板上给同行照着抄。
|
||
|
||
真发就是往上游写数据,所以要 ``confirmSend`` 显式确认;影子数据源没这个风险,直接放行。
|
||
这一趟**不进发件箱**——它是配置期的验证,不该混进"这张单发过几次"的台账里。
|
||
"""
|
||
draft, work, data = _render_target(db, body)
|
||
_checked(db, draft)
|
||
source = fetch.get_source(db, draft.source)
|
||
if source is None:
|
||
raise bad_request(f"数据源 {draft.source} 不存在,拼不出要发往哪里")
|
||
method, url, payload = mapping.render_for(
|
||
db, source, draft, data=data, work=work, activity=_preview_activity(db, work))
|
||
if source.shadow or source.provider == models.DataSource.PROVIDER_MOCK:
|
||
return ok({"sent": False, "shadow": True, "method": method, "url": url, "payload": payload,
|
||
"message": "这张数据源开了影子模式(或走样例通道),报文只渲染没真发出去"})
|
||
if not body.confirm_send:
|
||
return ok({"sent": False, "method": method, "url": url, "payload": payload,
|
||
"message": "这一步会真的往上游写数据。确认无误再点一次「确认发送」"})
|
||
headers = {"Content-Type": "application/json",
|
||
outbox.IDEM_HEADER: f"dryrun:{draft.code}:{int(datetime.now().timestamp())}",
|
||
**{str(k): str(v) for k, v in (source.headers or {}).items()},
|
||
**fetch.auth_headers(source)}
|
||
try:
|
||
status, text = fetch.http_request(
|
||
method, url, json.dumps(payload, ensure_ascii=False).encode("utf-8"), headers,
|
||
max(1, int(source.timeout_seconds or 10)),
|
||
)
|
||
except Exception as exc:
|
||
raise bad_request(f"没打到 {url}:{fetch.friendly_error(exc)}") from exc
|
||
success, message, ref = outbox.judge(source, status, text)
|
||
sample = {"at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "by": user.display_name,
|
||
"method": method, "url": url, "payload": payload, "httpStatus": status,
|
||
"body": text[:2000], "ok": success, "error": message, "ref": ref}
|
||
stored = get_template(db, draft.code)
|
||
if stored is not None:
|
||
stored.sample = sample
|
||
db.commit()
|
||
return ok({"sent": True, "ok": success, "message": message, "externalRef": ref, **sample})
|
||
|
||
|
||
@router.get("/design/integrations/export", dependencies=[Depends(require_permission("design:integration"))])
|
||
def export_templates(
|
||
db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)
|
||
) -> dict:
|
||
"""导出 L1 + L2 一套 JSON。
|
||
|
||
密钥**不在导出里**(只进不出的约定):导入之后要重新填一次密钥和地址,这正是
|
||
"测试环境配好、生产导入只换密钥和域名"的正确形状。
|
||
"""
|
||
rows = db.execute(select(models.Integration).order_by(models.Integration.code)).scalars().all()
|
||
codes = {row.source for row in rows if row.source}
|
||
sources = db.execute(
|
||
select(models.DataSource).where(models.DataSource.code.in_(codes or [""]))
|
||
).scalars().all() if codes else []
|
||
return ok({
|
||
"version": 1,
|
||
"exportedAt": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
||
"integrations": [_view(row) for row in rows],
|
||
"dataSources": [fetch.view(row) for row in sources],
|
||
"note": "密钥不随导出走;导入后请在新环境重新填密钥与接口地址",
|
||
})
|
||
|
||
|
||
@router.post("/design/integrations/import", dependencies=[Depends(require_permission("design:integration"))])
|
||
def import_templates(
|
||
body: schemas.IntegrationImportBody,
|
||
user: CurrentUser = Depends(current_user),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
"""导入模板:已存在的编码按 mode 决定跳过还是覆盖,逐条校验,有问题的单独报出来。"""
|
||
if not body.items:
|
||
raise bad_request("没有要导入的模板")
|
||
mode = str(body.mode or "skip").strip()
|
||
if mode not in ("skip", "overwrite"):
|
||
raise bad_request("导入方式只支持 skip(跳过已存在)或 overwrite(覆盖已存在)")
|
||
created = updated = 0
|
||
rejected: list[dict] = []
|
||
for item in body.items:
|
||
code = str((item or {}).get("code") or "").strip()
|
||
if not CODE_RE.match(code):
|
||
rejected.append({"code": code, "reason": "编码只能用字母、数字、下划线和中划线"})
|
||
continue
|
||
try:
|
||
event_in = str((item or {}).get("triggerEvent") or "completed")
|
||
payload = {
|
||
"code": code,
|
||
"name": (item or {}).get("name") or code,
|
||
"enabled": (item or {}).get("enabled", True),
|
||
"source": (item or {}).get("source") or "",
|
||
"bizForm": (item or {}).get("bizForm") or "",
|
||
"triggerEvent": event_in,
|
||
# 「什么时候发」是一份清单:导出件里有这一格就照搬;老导出件没有这一格,
|
||
# 就按 triggerEvent 那一条算——省得一份旧导出件导进来把终态触发导没了
|
||
"triggerEvents": (item or {}).get("triggerEvents") or (
|
||
[event_in] if event_in in models.Integration.TERMINAL_EVENTS else []
|
||
),
|
||
"eventKey": (item or {}).get("eventKey") or "",
|
||
# 「重复到达时重发」也得跟着搬环境:漏了它,测试环境上勾好的重发口径
|
||
# 到生产就悄悄变成"只发一次",而对面的记录还躺着旧值。导出件里这一格的
|
||
# 名字跟着读接口走(refireOnRevisit),手写的那份爱写短的 refireRevisit,两种都认
|
||
"refireRevisit": bool((item or {}).get("refireOnRevisit")
|
||
or (item or {}).get("refireRevisit")),
|
||
# 条件不跟着搬环境,测试配好的"只发这一类单"到生产就变成每张单都发,
|
||
# 这是会真打到上游的那种错,不能靠导出漏掉(导出件里这个键叫 sendCondition,
|
||
# 手写的那份习惯写短的 condition,两种都认)
|
||
"sendCondition": (item or {}).get("sendCondition") or (item or {}).get("condition") or {},
|
||
"payload": (item or {}).get("payload") or {},
|
||
"idemRule": (item or {}).get("idemRule") or "",
|
||
"resultWrite": (item or {}).get("resultWrite") or [],
|
||
"onFailure": (item or {}).get("onFailure") or "continue",
|
||
"failRoute": (item or {}).get("failRoute") or "",
|
||
"retries": (item or {}).get("retries") or 5,
|
||
"maxAgeHours": (item or {}).get("maxAgeHours") or 0,
|
||
"reversalCode": (item or {}).get("reversalCode") or "",
|
||
"reconCode": (item or {}).get("reconCode") or "",
|
||
"remark": (item or {}).get("remark") or "",
|
||
}
|
||
draft = _draft(schemas.IntegrationBody.model_validate(payload))
|
||
draft.code = code
|
||
except Exception as exc:
|
||
rejected.append({"code": code, "reason": str(exc)})
|
||
continue
|
||
existing = get_template(db, code)
|
||
if existing is not None and mode == "skip":
|
||
rejected.append({"code": code, "reason": "这个编码已经存在(选了跳过)"})
|
||
continue
|
||
problems = _problems(db, draft)
|
||
if problems:
|
||
rejected.append({"code": code, "reason": ";".join(problems[:3])})
|
||
continue
|
||
if existing is None:
|
||
draft.id = models.new_id()
|
||
draft.creator = user.person_id
|
||
draft.creator_name = user.display_name
|
||
db.add(draft)
|
||
created += 1
|
||
else:
|
||
for column, value in _clean(schemas.IntegrationBody.model_validate(payload)).items():
|
||
setattr(existing, column, value)
|
||
updated += 1
|
||
db.commit()
|
||
if created or updated:
|
||
outbox.invalidate_node_triggers()
|
||
return ok({"created": created, "updated": updated, "rejected": rejected})
|
||
|
||
|
||
@router.post("/design/integrations", dependencies=[Depends(require_permission("design:integration"))])
|
||
def create_template(
|
||
body: schemas.IntegrationBody,
|
||
user: CurrentUser = Depends(current_user),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
code = str(body.code or "").strip()
|
||
if not CODE_RE.match(code):
|
||
raise bad_request("模板编码只能用字母、数字、下划线和中划线,且不能为空")
|
||
if not str(body.name or "").strip():
|
||
raise bad_request("模板名称不能为空")
|
||
if get_template(db, code) is not None:
|
||
raise bad_request(f"模板编码已存在: {code}")
|
||
draft = _draft(body)
|
||
draft.code = code
|
||
_checked(db, draft)
|
||
draft.id = models.new_id()
|
||
draft.creator = user.person_id
|
||
draft.creator_name = user.display_name
|
||
db.add(draft)
|
||
db.commit()
|
||
outbox.invalidate_node_triggers()
|
||
return ok(_view(draft))
|
||
|
||
|
||
@router.patch("/design/integrations/{code}", dependencies=[Depends(require_permission("design:integration"))])
|
||
def update_template(
|
||
code: str,
|
||
body: schemas.IntegrationBody,
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
) -> dict:
|
||
row = get_template(db, code)
|
||
if row is None:
|
||
raise not_found("写回模板不存在")
|
||
draft = _draft(body)
|
||
draft.code = code
|
||
_checked(db, draft)
|
||
for column, value in _clean(body).items():
|
||
setattr(row, column, value)
|
||
db.commit()
|
||
outbox.invalidate_node_triggers()
|
||
return ok(_view(row))
|
||
|
||
|
||
@router.delete("/design/integrations/{row_id}", dependencies=[Depends(require_permission("design:integration"))])
|
||
def delete_template(
|
||
row_id: str, db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)
|
||
) -> dict:
|
||
row = db.get(models.Integration, row_id)
|
||
if row is None:
|
||
raise not_found("写回模板不存在")
|
||
hits = processes_using(db, row.code)
|
||
if hits:
|
||
raise bad_request(f"这个模板正被{'、'.join(hits[:5])}挂在环节上,先把流程上的挂载去掉再删")
|
||
db.delete(row)
|
||
db.commit()
|
||
outbox.invalidate_node_triggers()
|
||
return ok({"deleted": True})
|
||
|
||
|
||
def processes_using(db: Session, code: str) -> list[str]:
|
||
"""哪些流程把这条模板挂在了环节上。删模板之前要提醒,不然线上会当场少发一条。"""
|
||
if not code:
|
||
return []
|
||
rows = db.execute(
|
||
select(models.Activity.process, models.Activity.config).where(
|
||
models.Activity.config.isnot(None)
|
||
)
|
||
).all()
|
||
processes: list[str] = []
|
||
for process_id, config in rows:
|
||
mount = config.get("writeback") if isinstance(config, dict) else None
|
||
if not isinstance(mount, dict):
|
||
continue
|
||
# 认两种写法(纯编码 / 带条件的对象):漏认一种就等于让被挂着的模板能被删掉
|
||
if code in mapping.mount_codes(mount):
|
||
name = db.get(models.Process, process_id)
|
||
processes.append(name.name if name else process_id)
|
||
return list(dict.fromkeys(processes))
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 发件箱:发出去的报文到底怎么样了
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
@router.get("/design/outbox/attention", dependencies=[Depends(require_permission("design:integration"))])
|
||
def outbox_attention(db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)) -> dict:
|
||
bundle = outbox.needs_attention(db)
|
||
return ok({
|
||
"attention": [_message_view(row) for row in bundle["attention"]],
|
||
"pendingReversal": [_message_view(row) for row in bundle["pendingReversal"]],
|
||
})
|
||
|
||
|
||
@router.get("/design/outbox/stats", dependencies=[Depends(require_permission("design:integration"))])
|
||
def outbox_stats(db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)) -> dict:
|
||
"""集成页顶部那块健康区:成功率、在途、死信、结果未知、是否正在静默。"""
|
||
return ok(outbox.stats(db))
|
||
|
||
|
||
@router.get("/design/outbox", dependencies=[Depends(require_permission("design:integration"))])
|
||
def list_outbox(
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
status: str = Query(""),
|
||
source: str = Query(""),
|
||
integration: str = Query(""),
|
||
keyword: str = Query(""),
|
||
work: str = Query(""),
|
||
) -> dict:
|
||
stmt = select(models.OutboundMessage)
|
||
if status:
|
||
stmt = stmt.where(models.OutboundMessage.status == status)
|
||
if source:
|
||
stmt = stmt.where(models.OutboundMessage.source == source)
|
||
if integration:
|
||
stmt = stmt.where(models.OutboundMessage.integration == integration)
|
||
if work:
|
||
stmt = stmt.where(models.OutboundMessage.work == work)
|
||
text = str(keyword or "").strip()
|
||
if text:
|
||
like = f"%{text}%"
|
||
stmt = stmt.where(or_(models.OutboundMessage.serial.like(like),
|
||
models.OutboundMessage.title.like(like),
|
||
models.OutboundMessage.job.like(like)))
|
||
rows = db.execute(
|
||
stmt.order_by(models.OutboundMessage.create_time.desc()).limit(LIST_LIMIT)
|
||
).scalars().all()
|
||
return ok([_message_view(row) for row in rows])
|
||
|
||
|
||
@router.get("/design/outbox/{message_id}", dependencies=[Depends(require_permission("design:integration"))])
|
||
def read_outbox(
|
||
message_id: str, db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)
|
||
) -> dict:
|
||
row = db.get(models.OutboundMessage, message_id)
|
||
if row is None:
|
||
raise not_found("这条报文不存在")
|
||
return ok(_message_view(row, full=True))
|
||
|
||
|
||
@router.post("/design/outbox/{message_id}/replay", dependencies=[Depends(require_permission("design:integration"))])
|
||
def replay_outbox(
|
||
message_id: str,
|
||
body: schemas.OutboxReplayBody,
|
||
user: CurrentUser = Depends(current_user),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
"""人工重推:改完模板之后**按新模板重新渲染**再发,修订版 +1。
|
||
|
||
记原因进操作日志口径里(§13:所有手工重推要留操作人与原因)。
|
||
"""
|
||
if not str(body.reason or "").strip():
|
||
raise bad_request("重推要写一句为什么:这条是要进上游账的,改了什么总得有人能查")
|
||
row = outbox.replay(db, message_id, actor=user, reason=body.reason)
|
||
if row is None:
|
||
raise not_found("这条报文不存在")
|
||
if row.status != models.OutboundMessage.STATUS_PENDING:
|
||
db.commit()
|
||
raise bad_request(row.last_error or "这条报文没能重新渲染出来")
|
||
db.commit()
|
||
return ok(_message_view(row, full=True))
|
||
|
||
|
||
@router.post("/design/outbox/{message_id}/confirm", dependencies=[Depends(require_permission("design:integration"))])
|
||
def confirm_outbox(
|
||
message_id: str,
|
||
body: schemas.OutboxConfirmBody,
|
||
user: CurrentUser = Depends(current_user),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
"""结果未知的人工确认:问过上游了,在这里落定,别让它一直悬着。"""
|
||
if not str(body.note or "").strip() and not body.ok:
|
||
raise bad_request("判它失败要写一句凭什么")
|
||
row = db.get(models.OutboundMessage, message_id)
|
||
if row is None:
|
||
raise not_found("这条报文不存在")
|
||
# 只有"发过、没拿到可判定的答复"才需要人来确认。别的状态各有自己的出口
|
||
# (失败等退避、死信走重推),在这里被人工改掉的后果是台账对不上。
|
||
if row.status != models.OutboundMessage.STATUS_UNKNOWN:
|
||
raise bad_request("只有「结果未知」的报文需要人工确认,这条现在是 " + row.status)
|
||
row = outbox.confirm_result(db, message_id, ok=bool(body.ok), note=body.note.strip(), actor=user)
|
||
db.commit()
|
||
return ok(_message_view(row, full=True))
|
||
|
||
|
||
@router.get("/design/integrations/{code}/samples", dependencies=[Depends(require_permission("design:integration"))])
|
||
def template_samples(
|
||
code: str, db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)
|
||
) -> dict:
|
||
"""预览用的候选单据:绑定的那张表单下最近的几张单(在途的和已办结的都要,
|
||
已经办结的才是真正会触发写回的那种)。"""
|
||
row = get_template(db, code)
|
||
if row is None:
|
||
raise not_found("写回模板不存在")
|
||
if not row.biz_form:
|
||
raise bad_request("模板还没绑定表单,不知道要拿哪张单来预览")
|
||
limit = 15
|
||
running = db.execute(
|
||
select(models.Work.id, models.Work.serial, models.Work.title, models.Work.status)
|
||
.where(models.Work.form == row.biz_form)
|
||
.order_by(models.Work.start_time.desc()).limit(limit)
|
||
).all()
|
||
finished = db.execute(
|
||
select(models.WorkCompleted.id, models.WorkCompleted.serial, models.WorkCompleted.title,
|
||
models.WorkCompleted.status)
|
||
.where(models.WorkCompleted.form == row.biz_form)
|
||
.order_by(models.WorkCompleted.finish_time.desc()).limit(limit)
|
||
).all()
|
||
return ok([
|
||
{"id": item[0], "serial": item[1], "title": item[2], "status": item[3],
|
||
"stage": "在途" if index == 0 else "已办结"}
|
||
for index, group in enumerate((running, finished)) for item in group
|
||
])
|
||
|
||
|
||
@router.get("/design/integrations/{code}/messages", dependencies=[Depends(require_permission("design:integration"))])
|
||
def template_messages(
|
||
code: str, db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)
|
||
) -> dict:
|
||
"""某个模板最近发过哪些报文(模板页里的"报文历史",排错不靠猜)。"""
|
||
rows = db.execute(
|
||
select(models.OutboundMessage)
|
||
.where(models.OutboundMessage.integration == code)
|
||
.order_by(models.OutboundMessage.create_time.desc())
|
||
.limit(50)
|
||
).scalars().all()
|
||
return ok([_message_view(row) for row in rows])
|