661 lines
29 KiB
Python
661 lines
29 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 ..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,
|
||
"eventKey": row.event_key,
|
||
"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,
|
||
"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)
|
||
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_event": event,
|
||
# 只有「到达某环节」这一种触发需要环节 id,其它事件带着它只会让人误以为还在生效
|
||
"event_key": str(body.event_key or "").strip()
|
||
if event == models.Integration.EVENT_ACTIVITY else "",
|
||
"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,
|
||
"eventKey": draft.event_key,
|
||
"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 _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)
|
||
if event:
|
||
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()
|
||
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,
|
||
"eventKey": row.event_key,
|
||
"bizForm": row.biz_form,
|
||
"onFailure": row.on_failure,
|
||
"remark": row.remark,
|
||
} for row in rows])
|
||
|
||
|
||
@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)
|
||
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)
|
||
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:
|
||
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": (item or {}).get("triggerEvent") or "completed",
|
||
"eventKey": (item or {}).get("eventKey") 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()
|
||
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()
|
||
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()
|
||
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()
|
||
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 [str(item or "").strip() for item in (mount.get("integrations") or [])]:
|
||
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])
|