Merge branch 'hugo-shipping-notice' into test
This commit is contained in:
commit
e35f01bbe9
163 files changed
+21008
-2545
No files matched your search
@@ -3,11 +3,17 @@
|
||||
用途:在途仓自动调拨用户态 API(仓库管理人员)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.core.response、matching_service、deps。
|
||||
逻辑:薄路由层鉴权与参数校验;成功响应统一 envelope(ok + request_id);
|
||||
Phase 1 提供匹配创建(POST /matchings)与进度恢复(GET /matchings/{id})。
|
||||
匹配创建(POST /matchings)与进度恢复(GET /matchings/{id});执行为 D8
|
||||
异步契约(POST /items/execute → 202 queued + run_no,单在提交时组建);
|
||||
result_unknown 单人工重新触发(POST /runs/{run_no}/documents/{doc_no}/
|
||||
retrigger → 202,D11 唯一出口);首页「已执行」区块:已执行单分页查询
|
||||
(GET /documents,只读)与人工关闭失败单(POST /documents/{doc_no}/close,
|
||||
D18 废单不废行)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from functools import wraps
|
||||
from typing import Any
|
||||
|
||||
@@ -22,9 +28,9 @@ from app.services.in_transit_transfer.cancellation import cancel_run
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.excel_export import _MIME, build_exceptions_workbook
|
||||
from app.services.in_transit_transfer.execution_service import (
|
||||
execute_items,
|
||||
get_run,
|
||||
serialize_run_result,
|
||||
prepare_execution,
|
||||
retrigger_document,
|
||||
)
|
||||
from app.services.in_transit_transfer.manual_close_service import manual_close_item, manual_close_items
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
@@ -38,6 +44,8 @@ from app.services.in_transit_transfer.retry_service import (
|
||||
retry_item,
|
||||
)
|
||||
from app.services.in_transit_transfer.serializers import (
|
||||
DOCUMENT_STATUS_GROUPS,
|
||||
serialize_executed_order,
|
||||
serialize_item,
|
||||
serialize_source,
|
||||
serialize_summary,
|
||||
@@ -210,7 +218,11 @@ def download_source_receipt_files_api():
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def get_run_api(run_no: str):
|
||||
"""恢复 Run 最终结果(页面刷新/会话恢复)。"""
|
||||
"""恢复 Run 结果(页面刷新/会话恢复)。
|
||||
|
||||
返回体:result(单号聚合 + exceptions 既有口径)+ orders 调拨单清单
|
||||
(D9 融合卡数据源:调拨单清单=进度=结果,轮询即恢复最新单态)。
|
||||
"""
|
||||
return _ok(get_run(run_no))
|
||||
|
||||
|
||||
@@ -259,18 +271,21 @@ def _require_item_ids(body: Any) -> list[int]:
|
||||
@in_transit_transfer_bp.route("/items/execute", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def execute_items_api():
|
||||
"""按行执行调拨(三层门禁:①存在且可执行 ②行级新鲜度 ③文件版本对账)。
|
||||
"""按行提交执行(D8 异步:202 排队,单在提交时已组建,worker 逐单执行)。
|
||||
|
||||
请求体:{"item_ids": [int]}(匹配卡/待执行池勾选的真实明细行 id)。
|
||||
响应:200 envelope,data 为 run_no / run 状态 / 外部系统 单号聚合结果;
|
||||
响应:202 envelope,data 为 {"run_no", "status": "queued"}(纯库内毫秒级:
|
||||
两道门禁(存在可执行 + 文件版本对账;TTL 新鲜度门禁 2026-09-25 退役)+
|
||||
建 queued Run + 五元组分组建单 + 一次入队);
|
||||
门禁失败 400,error.details 携带对应 id 列表
|
||||
(invalid_item_ids / stale_item_ids / changed_item_ids)。
|
||||
(invalid_item_ids / changed_item_ids)。
|
||||
进度与结果经 GET /runs/{run_no} 轮询恢复(融合卡数据源)。
|
||||
"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
item_ids = _require_item_ids(body)
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
outcome = execute_items(
|
||||
outcome = prepare_execution(
|
||||
item_ids=item_ids,
|
||||
deps=deps,
|
||||
actor_id=user.id,
|
||||
@@ -279,10 +294,234 @@ def execute_items_api():
|
||||
return _ok({
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.status,
|
||||
"result": serialize_run_result(outcome.result),
|
||||
}, status=202)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/documents/<doc_no>/retrigger", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retrigger_document_api(run_no: str, doc_no: str):
|
||||
"""人工重新触发 result_unknown 单(D11 唯一出口,禁止关闭重建)。
|
||||
|
||||
语义:复用本单 doc_no/submit_timestamp,只触发末步(D7②,幂等安全);
|
||||
成功后单/行推进成功族并亮出原单号。人工动作,非自动重试。
|
||||
响应:202 envelope,data 为 {"run_no", "doc_no", "status": "queued"};
|
||||
非 result_unknown 单 → 400(TRANSFER.RETRIGGER_NOT_ALLOWED)。
|
||||
"""
|
||||
user = _require_user()
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
outcome = retrigger_document(
|
||||
run_no=run_no,
|
||||
doc_no=doc_no,
|
||||
deps=deps,
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
request_id=getattr(g, "request_id", None),
|
||||
)
|
||||
return _ok(outcome, status=202)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/documents", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def list_documents_api():
|
||||
"""已执行单分页查询(首页「已执行」区块数据源;只读,不写审计)。
|
||||
|
||||
Query:
|
||||
status_group ∈ {success, failed, executing, result_unknown}(可选,缺省全部;
|
||||
非法 400);date_from/date_to=YYYY-MM-DD(可选,仅作用 orders 列表);
|
||||
page(默认 1);page_size(默认 20,上限 100)。
|
||||
口径:分组计数恒全量(GROUP BY status 对全部单统计,不受筛选影响——
|
||||
失败/结果未知/执行中=未完结即待办,全量才不漏;成功=累计产出);
|
||||
列表 created_at 倒序分页,cancelled 不展示(无产生路径)。
|
||||
响应:{groups, total, page, page_size, orders:[serialize_executed_order 投影]}。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import TransferDocument, TransferInvoiceItem
|
||||
from sqlalchemy import func
|
||||
|
||||
def _parse_date(name: str):
|
||||
"""解析 YYYY-MM-DD 查询参数;空缺省返回 None,非法格式 400。"""
|
||||
raw = (request.args.get(name) or "").strip()
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(raw, "%Y-%m-%d").date()
|
||||
except ValueError as exc:
|
||||
raise ValidationError(f"{name} must be YYYY-MM-DD") from exc
|
||||
|
||||
def _parse_int(name: str, default: int, *, minimum: int, maximum: int | None = None) -> int:
|
||||
"""解析整数查询参数(缺省回默认值;下限钳制必填,上限可选)。"""
|
||||
raw = (request.args.get(name) or "").strip()
|
||||
if not raw:
|
||||
return default
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(f"{name} must be an integer") from exc
|
||||
value = max(minimum, value)
|
||||
if maximum is not None:
|
||||
value = min(maximum, value)
|
||||
return value
|
||||
|
||||
# [STEP 1] 参数校验:status_group 白名单外 400(fail-closed)。
|
||||
status_group = (request.args.get("status_group") or "").strip()
|
||||
if status_group and status_group not in DOCUMENT_STATUS_GROUPS:
|
||||
raise ValidationError(
|
||||
f"status_group must be one of {sorted(DOCUMENT_STATUS_GROUPS)}",
|
||||
)
|
||||
date_from = _parse_date("date_from")
|
||||
date_to = _parse_date("date_to")
|
||||
page = _parse_int("page", 1, minimum=1)
|
||||
page_size = _parse_int("page_size", 20, minimum=1, maximum=100)
|
||||
|
||||
# [STEP 2] 分组计数恒全量:GROUP BY status 对全部单统计,不受任何筛选影响。
|
||||
counts = dict(
|
||||
db.session.query(TransferDocument.status, func.count())
|
||||
.group_by(TransferDocument.status)
|
||||
.all()
|
||||
)
|
||||
groups = {
|
||||
group: sum(counts.get(status, 0) for status in statuses)
|
||||
for group, statuses in DOCUMENT_STATUS_GROUPS.items()
|
||||
}
|
||||
|
||||
# [STEP 3] 列表查询:status_group / created_at 时间窗仅作用列表;
|
||||
# cancelled 恒不展示;created_at 倒序稳定分页(id 兜底同刻排序)。
|
||||
query = TransferDocument.query.filter(TransferDocument.status != "cancelled")
|
||||
if status_group:
|
||||
query = query.filter(TransferDocument.status.in_(DOCUMENT_STATUS_GROUPS[status_group]))
|
||||
if date_from:
|
||||
query = query.filter(TransferDocument.created_at >= datetime(date_from.year, date_from.month, date_from.day))
|
||||
if date_to:
|
||||
window_end = datetime(date_to.year, date_to.month, date_to.day) + timedelta(days=1)
|
||||
query = query.filter(TransferDocument.created_at < window_end)
|
||||
total = query.count()
|
||||
docs = (
|
||||
query.order_by(TransferDocument.created_at.desc(), TransferDocument.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
|
||||
# [STEP 4] items 批量查回(防 N+1),按 document_id 分组后逐单投影。
|
||||
doc_ids = [doc.id for doc in docs]
|
||||
items_by_doc: dict[int, list] = {}
|
||||
if doc_ids:
|
||||
rows = (
|
||||
TransferInvoiceItem.query.filter(TransferInvoiceItem.document_id.in_(doc_ids))
|
||||
.order_by(TransferInvoiceItem.id.asc())
|
||||
.all()
|
||||
)
|
||||
for row in rows:
|
||||
items_by_doc.setdefault(row.document_id, []).append(row)
|
||||
|
||||
return _ok({
|
||||
"groups": groups,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"orders": [serialize_executed_order(doc, items_by_doc.get(doc.id, [])) for doc in docs],
|
||||
})
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/documents/<doc_no>/close", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def close_document_api(doc_no: str):
|
||||
"""人工关闭失败单(D18:语义=A 废单不废行;首页已执行区块/融合卡共用)。
|
||||
|
||||
门禁:仅 business_failed/technical_failed 可关;result_unknown → 400
|
||||
(D11:结果未知单唯一出口=重新触发,禁止「关闭后重建」双单路径);
|
||||
pending/executing → 400(在飞);原因必填;单不存在 404。
|
||||
行为:doc.status='cancelled' + closed_reason=reason;单内 items 全部脱离
|
||||
(document_id=NULL、status→ready_to_execute、清 result_code/result_message
|
||||
——原路由漂移行由执行期既有守卫重新把关);审计事件(actor/reason/
|
||||
前后状态/行数)。
|
||||
效果:cancelled 不在部分唯一索引未完结集 → 组锁释放,同组可另开新单。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import TransferDocument, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.contracts import TRANSFER_MANUAL_CLOSE_REASON_REQUIRED
|
||||
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
reason = str(body.get("reason") or "").strip() if isinstance(body, dict) else ""
|
||||
# [STEP 1] 原因必填(复用人工关闭既有错误码,查重不新增)。
|
||||
if not reason:
|
||||
raise ValidationError(
|
||||
"document close reason is required",
|
||||
code=TRANSFER_MANUAL_CLOSE_REASON_REQUIRED,
|
||||
)
|
||||
doc = TransferDocument.query.filter_by(doc_no=str(doc_no).strip()).first()
|
||||
if doc is None:
|
||||
raise NotFoundError("transfer document not found", code="TRANSFER.DOCUMENT_NOT_FOUND")
|
||||
|
||||
# [STEP 2] 状态门禁:result_unknown 走 retrigger(D11);在飞/已完结单拒绝。
|
||||
if doc.status == "result_unknown":
|
||||
raise ValidationError(
|
||||
"result_unknown order cannot be closed; use retrigger instead (D11)",
|
||||
code="TRANSFER.DOCUMENT_CLOSE_NOT_ALLOWED",
|
||||
)
|
||||
if doc.status not in DOCUMENT_STATUS_GROUPS["failed"]:
|
||||
raise ValidationError(
|
||||
f"order status {doc.status} is not closeable (in-flight or settled)",
|
||||
code="TRANSFER.DOCUMENT_CLOSE_NOT_ALLOWED",
|
||||
)
|
||||
|
||||
# [STEP 3] D18 行脱离:单内 items 全部脱离单(document_id=NULL)回
|
||||
# ready_to_execute(可重新勾选组建新单),行级结果清空。
|
||||
before_status = doc.status
|
||||
items = TransferInvoiceItem.query.filter_by(document_id=doc.id).all()
|
||||
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
for item in items:
|
||||
item.document_id = None
|
||||
item.status = ready_status
|
||||
item.result_code = None
|
||||
item.result_message = None
|
||||
|
||||
# [STEP 4] 单 cancelled + closed_reason 可视留档;组锁随之释放。
|
||||
doc.status = "cancelled"
|
||||
doc.closed_reason = reason
|
||||
|
||||
# [STEP 5] 审计事件(actor/reason/前后状态/行数)后提交。
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_DOCUMENT_CLOSED",
|
||||
aggregate_type="transfer_document",
|
||||
aggregate_id=doc.doc_no,
|
||||
run_no=doc.run.run_no if doc.run_id and doc.run else None,
|
||||
actor_type="user",
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
actor_display=str(getattr(user, "name", "") or ""),
|
||||
request_id=getattr(g, "request_id", None),
|
||||
result="success",
|
||||
before={"status": before_status},
|
||||
after={"status": doc.status, "reason": reason, "item_count": len(items)},
|
||||
))
|
||||
db.session.commit()
|
||||
return _ok({"doc_no": doc.doc_no, "status": doc.status, "released_items": len(items)})
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/documents/<doc_no>/retry", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_document_api(doc_no: str):
|
||||
"""调拨单级重试(失败单一键恢复主路径)。
|
||||
|
||||
门禁:仅 business_failed/technical_failed 可重试;result_unknown → 400
|
||||
(D11 唯一出口=重新触发);pending/executing 在飞拒绝;单不存在 404。
|
||||
行为:单内 blocked 行逐行重查(复用 retry_item,单行隔离)→ 全部 ready 则
|
||||
自动建新 Run 重跑(prepare_execution,D7①分支②复用原单号);任一行仍
|
||||
阻断则不重跑(单是原子单位),阻断明细随响应返回由恢复池兜底。
|
||||
"""
|
||||
from app.services.in_transit_transfer.retry_service import retry_document
|
||||
|
||||
user = _require_user()
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
return _ok(retry_document(
|
||||
doc_no=doc_no, deps=deps,
|
||||
actor_id=user.id if user and user.id else None,
|
||||
request_id=getattr(g, "request_id", None),
|
||||
))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/batch-requery", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def batch_requery_items_api():
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
"""api/integration_connector.py
|
||||
|
||||
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。
|
||||
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway、credential_crypto。
|
||||
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点、
|
||||
连接测试与集成调用日志查询(列表 + 详情 + 同 operation 步骤时间线)。
|
||||
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway、credential_crypto、
|
||||
models.integration_connector.CONNECTOR_TYPES / DB_KINDS(白名单同源)。
|
||||
逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key},
|
||||
拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。
|
||||
客户端实例 connector_type ∈ rest/soap/database;database 时 db_kind 必填且 ∈
|
||||
mysql/oracle/sqlserver/postgresql,非 database 强制置 NULL。
|
||||
接口定义的连接器类型由所属客户端实例服务端推导(单一事实源);接口定义与绑定的
|
||||
状态只经 /publish /unpublish /retire /reopen 动作端点按 CONFIG_STATUS_TRANSITIONS
|
||||
转移(绑定发布附加就绪门禁:接口须已发布且客户端启用);绑定创建/更新做客户端
|
||||
与接口成对校验(接口定义必须属于所选客户端实例,错配即 400)。
|
||||
转移(绑定发布附加就绪门禁:每步接口须已发布且每步客户端启用);绑定以
|
||||
steps_json 有序数组表达一对多配方(每步 interface_code + param_mapping_json),
|
||||
客户端由各步接口归属自带;旧单步字段可合成单元素 steps(兼容窗)。
|
||||
凭据引用状态为两态开关:PUT 仅允许 active/retired(rotating 不可进入,存量可置回
|
||||
active 恢复);接口定义 enabled 冻结忽略传值(可用性只由 status 表达)。
|
||||
凭据引用 db 模式在服务端加密用户名/密码落库,接口响应永不回显明文/密文。
|
||||
@@ -28,10 +33,12 @@ from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import (
|
||||
IntegrationBinding,
|
||||
IntegrationCall,
|
||||
IntegrationClientInstance,
|
||||
IntegrationCredentialReference,
|
||||
IntegrationInterfaceDefinition,
|
||||
)
|
||||
from app.models.integration_connector import CONNECTOR_TYPES, DB_KINDS
|
||||
from app.services.integration_connector.capability import list_capabilities
|
||||
from app.services.integration_connector.credential_types import (
|
||||
build_secret_dict,
|
||||
@@ -40,12 +47,18 @@ from app.services.integration_connector.credential_types import (
|
||||
visible_fields,
|
||||
)
|
||||
from app.services.integration_connector.gateway import get_capability_gateway
|
||||
from app.services.integration_connector.security import CREDENTIAL_KEY_CONFIG_NAME, _DB_SECRET_CODES
|
||||
from app.services.integration_connector.security import (
|
||||
CREDENTIAL_KEY_CONFIG_NAME,
|
||||
_DB_SECRET_CODES,
|
||||
resolve_credential,
|
||||
)
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult, merge_client_config
|
||||
|
||||
integration_connector_bp = Blueprint('integration_connector', __name__)
|
||||
|
||||
VALID_CONNECTOR_TYPES = ('rest', 'soap')
|
||||
# 与模型 CONNECTOR_TYPES / DB_KINDS 同源,禁止本地另维护一份白名单。
|
||||
VALID_CONNECTOR_TYPES = CONNECTOR_TYPES
|
||||
VALID_DB_KINDS = DB_KINDS
|
||||
VALID_STATUSES = ('draft', 'published', 'retired')
|
||||
VALID_SECRET_PROVIDERS = ('db', 'env')
|
||||
# 凭据两态化(UI 可达状态):resolve_credential 只解析 active(fail-closed),「轮换中」
|
||||
@@ -70,6 +83,32 @@ def _require(value, field: str) -> None:
|
||||
raise ValidationError(f'{field} is required', details={'field': field})
|
||||
|
||||
|
||||
def _resolve_db_kind(connector_type: str, raw_db_kind) -> str | None:
|
||||
"""按连接器类型解析 db_kind:database 必填且 ∈ VALID_DB_KINDS;其余强制 NULL。
|
||||
|
||||
Args:
|
||||
connector_type: 已校验的连接器类型。
|
||||
raw_db_kind: 请求体中的 db_kind(可为 None/空串)。
|
||||
|
||||
Returns:
|
||||
合法库种字符串,或非 database 时的 None。
|
||||
|
||||
Raises:
|
||||
ValidationError: database 缺省或未知库种(fail-closed,含历史别名 mssql)。
|
||||
"""
|
||||
if connector_type != 'database':
|
||||
return None
|
||||
kind = str(raw_db_kind or '').strip()
|
||||
if not kind:
|
||||
raise ValidationError('db_kind is required for database connector', details={'field': 'db_kind'})
|
||||
if kind not in VALID_DB_KINDS:
|
||||
raise ValidationError(
|
||||
'invalid db_kind',
|
||||
details={'field': 'db_kind', 'allowed': list(VALID_DB_KINDS)},
|
||||
)
|
||||
return kind
|
||||
|
||||
|
||||
def _require_client(code: str) -> IntegrationClientInstance:
|
||||
"""按编码取客户端实例;不存在即 400(接口定义的连接器类型以其为单一事实源)。"""
|
||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||
@@ -112,7 +151,8 @@ def _validate_binding_pair(client_code, interface_code) -> tuple[IntegrationClie
|
||||
"""绑定成对校验:接口定义必须属于所选客户端实例(接口归属即客户端归属)。
|
||||
|
||||
错配组合会产生「拿 A 客户端的地址/凭据发 B 接口报文」的调用,创建/更新时直接
|
||||
400(fail-fast),不留给调用期 fail-closed。
|
||||
400(fail-fast),不留给调用期 fail-closed。多步绑定时仅用于可选的绑定级
|
||||
client_instance_code 与首步接口的一致性检查。
|
||||
"""
|
||||
client = _require_client(str(client_code).strip())
|
||||
iface = _require_interface(str(interface_code).strip())
|
||||
@@ -129,16 +169,101 @@ def _validate_binding_pair(client_code, interface_code) -> tuple[IntegrationClie
|
||||
return client, iface
|
||||
|
||||
|
||||
def _normalize_binding_steps(body: dict) -> list[dict]:
|
||||
"""校验并归一化绑定 steps_json(非空数组;每步 interface 存在且客户端可用)。
|
||||
|
||||
核心逻辑:优先读 steps_json;缺省时用旧单步字段合成一元素数组(兼容窗)。
|
||||
每步 interface_code 必须存在,其归属客户端必须存在(绑定的客户端实例族);
|
||||
param_mapping_json 须为 dict。返回供落库的 [{interface_code, param_mapping_json}, ...]。
|
||||
|
||||
Args:
|
||||
body: 创建/更新请求体。
|
||||
|
||||
Returns:
|
||||
归一化后的步骤列表(至少一元素)。
|
||||
|
||||
Raises:
|
||||
ValidationError: 空数组、步形状非法、接口不存在、映射非 dict。
|
||||
"""
|
||||
raw = body.get('steps_json')
|
||||
if raw is None:
|
||||
# 兼容窗:旧单步 API 字段 → 单元素 steps
|
||||
iface_code = body.get('interface_definition_code')
|
||||
if not iface_code:
|
||||
raise ValidationError(
|
||||
'steps_json is required',
|
||||
code='INTEGRATION.BINDING_STEPS_INVALID',
|
||||
details={'field': 'steps_json'},
|
||||
)
|
||||
raw = [{
|
||||
'interface_code': iface_code,
|
||||
'param_mapping_json': body.get('param_mapping_json') or {},
|
||||
}]
|
||||
if not isinstance(raw, list) or len(raw) == 0:
|
||||
raise ValidationError(
|
||||
'steps_json must be a non-empty array',
|
||||
code='INTEGRATION.BINDING_STEPS_INVALID',
|
||||
details={'field': 'steps_json'},
|
||||
)
|
||||
|
||||
normalized: list[dict] = []
|
||||
for idx, step in enumerate(raw):
|
||||
if not isinstance(step, dict):
|
||||
raise ValidationError(
|
||||
'each step must be an object',
|
||||
code='INTEGRATION.BINDING_STEPS_INVALID',
|
||||
details={'field': 'steps_json', 'index': idx},
|
||||
)
|
||||
iface_code = step.get('interface_code') or step.get('interface_definition_code')
|
||||
_require(iface_code, f'steps_json[{idx}].interface_code')
|
||||
mapping = step.get('param_mapping_json', step.get('param_mapping', {}))
|
||||
if mapping is None:
|
||||
mapping = {}
|
||||
if not isinstance(mapping, dict):
|
||||
raise ValidationError(
|
||||
'step param_mapping_json must be an object',
|
||||
code='INTEGRATION.BINDING_STEPS_INVALID',
|
||||
details={'field': 'steps_json', 'index': idx, 'key': 'param_mapping_json'},
|
||||
)
|
||||
iface = _require_interface(str(iface_code).strip())
|
||||
# 客户端实例族:接口归属客户端必须存在(跨步可不同客户端,如 database+soap)。
|
||||
_require_client(iface.client_instance_code)
|
||||
normalized.append({
|
||||
'interface_code': iface.code,
|
||||
'param_mapping_json': mapping,
|
||||
})
|
||||
|
||||
# 若请求仍带绑定级 client_instance_code,与首步接口做成对校验(防错配镜像列)。
|
||||
binding_client = body.get('client_instance_code')
|
||||
if binding_client is not None and str(binding_client).strip():
|
||||
_validate_binding_pair(binding_client, normalized[0]['interface_code'])
|
||||
|
||||
return normalized
|
||||
|
||||
|
||||
def _mirror_legacy_binding_columns(steps: list[dict]) -> tuple[str, str, dict]:
|
||||
"""由归一化 steps 镜像旧 NOT NULL 列(首步);P2 删列前保持可写。
|
||||
|
||||
Returns:
|
||||
(client_instance_code, interface_definition_code, param_mapping_json)
|
||||
"""
|
||||
first = steps[0]
|
||||
iface = _require_interface(first['interface_code'])
|
||||
return iface.client_instance_code, iface.code, dict(first.get('param_mapping_json') or {})
|
||||
|
||||
|
||||
def _interface_transition(iface, action: str) -> None:
|
||||
"""按转移表校验并落库接口定义状态;非法动作或源状态不符即 400。"""
|
||||
_apply_status_transition(iface, action, kind='interface')
|
||||
|
||||
|
||||
def _serialize_client(client) -> dict:
|
||||
"""客户端实例序列化(含 database 专列 db_kind;非 database 为 null)。"""
|
||||
return {
|
||||
'id': client.id, 'code': client.code, 'name': client.name,
|
||||
'connector_type': client.connector_type, 'environment': client.environment,
|
||||
'endpoint': client.endpoint, 'timeout_seconds': client.timeout_seconds,
|
||||
'db_kind': client.db_kind,
|
||||
'config_json': client.config_json or {}, 'credential_ref_code': client.credential_ref_code,
|
||||
'enabled': client.enabled,
|
||||
}
|
||||
@@ -156,9 +281,11 @@ def _serialize_interface(iface) -> dict:
|
||||
|
||||
|
||||
def _serialize_binding(binding) -> dict:
|
||||
"""绑定序列化:含 steps_json;旧单步列仍回显(P2 删前列镜像)。"""
|
||||
return {
|
||||
'id': binding.id, 'capability': binding.capability,
|
||||
'context_selector_json': binding.context_selector_json or {},
|
||||
'steps_json': binding.steps_json or [],
|
||||
'param_mapping_json': binding.param_mapping_json or {},
|
||||
'client_instance_code': binding.client_instance_code,
|
||||
'interface_definition_code': binding.interface_definition_code,
|
||||
@@ -276,6 +403,7 @@ def list_client_instances():
|
||||
@integration_connector_bp.route('/client-instances', methods=['POST'])
|
||||
@require_admin
|
||||
def create_client_instance():
|
||||
"""创建客户端实例;database 类型强制校验 db_kind 四库枚举,非 database 置 NULL。"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
connector_type = str(body.get('connector_type') or '').strip()
|
||||
_require(body.get('code'), 'code')
|
||||
@@ -284,11 +412,13 @@ def create_client_instance():
|
||||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||||
if IntegrationClientInstance.query.filter_by(code=body['code']).first():
|
||||
raise ValidationError('client instance code already exists', code='RESOURCE.CONFLICT')
|
||||
db_kind = _resolve_db_kind(connector_type, body.get('db_kind'))
|
||||
client = IntegrationClientInstance(
|
||||
code=str(body['code']).strip(), name=str(body['name']).strip(),
|
||||
connector_type=connector_type, environment=str(body.get('environment') or 'prod').strip(),
|
||||
endpoint=(str(body.get('endpoint') or '').strip() or None),
|
||||
timeout_seconds=(int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None),
|
||||
db_kind=db_kind,
|
||||
config_json=body.get('config_json') or {},
|
||||
credential_ref_code=body.get('credential_ref_code'),
|
||||
enabled=bool(body.get('enabled', True)),
|
||||
@@ -323,7 +453,10 @@ def delete_client_instance(code):
|
||||
@integration_connector_bp.route('/client-instances/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_client_instance(code):
|
||||
"""更新客户端实例(code 不变;可改名称/连接配置/凭据引用/启停)。"""
|
||||
"""更新客户端实例(code 不变;可改名称/连接配置/凭据引用/启停/db_kind)。
|
||||
|
||||
database 类型必填合法 db_kind;切离 database 时强制清空 db_kind。
|
||||
"""
|
||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||
if client is None:
|
||||
raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND')
|
||||
@@ -348,6 +481,9 @@ def update_client_instance(code):
|
||||
client.credential_ref_code = body.get('credential_ref_code')
|
||||
if 'enabled' in body:
|
||||
client.enabled = bool(body.get('enabled', True))
|
||||
# 最终类型决定 db_kind:database 必填合法值;rest/soap 强制 NULL。
|
||||
raw_kind = body['db_kind'] if 'db_kind' in body else client.db_kind
|
||||
client.db_kind = _resolve_db_kind(connector_type, raw_kind)
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_client(client))
|
||||
@@ -482,18 +618,22 @@ def list_bindings():
|
||||
@integration_connector_bp.route('/bindings', methods=['POST'])
|
||||
@require_admin
|
||||
def create_binding():
|
||||
"""创建绑定:成对校验客户端与接口后落库;新建固定落 draft,发布走 /publish 动作端点。"""
|
||||
"""创建绑定:校验 steps_json 后落库;新建固定落 draft,发布走 /publish 动作端点。
|
||||
|
||||
核心逻辑:归一化 steps → 镜像首步到旧列(NOT NULL)→ 落 draft。
|
||||
仍接受旧单步字段(无 steps_json 时合成一元素数组)。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
_require(body.get('capability'), 'capability')
|
||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||||
_require(body.get('interface_definition_code'), 'interface_definition_code')
|
||||
client, iface = _validate_binding_pair(body['client_instance_code'], body['interface_definition_code'])
|
||||
steps = _normalize_binding_steps(body)
|
||||
client_code, iface_code, param_mapping = _mirror_legacy_binding_columns(steps)
|
||||
binding = IntegrationBinding(
|
||||
capability=body['capability'],
|
||||
context_selector_json=body.get('context_selector_json') or {},
|
||||
param_mapping_json=body.get('param_mapping_json') or {},
|
||||
client_instance_code=client.code,
|
||||
interface_definition_code=iface.code,
|
||||
steps_json=steps,
|
||||
param_mapping_json=param_mapping,
|
||||
client_instance_code=client_code,
|
||||
interface_definition_code=iface_code,
|
||||
mapping_version=int(body.get('mapping_version') or 1),
|
||||
priority=int(body.get('priority') or 0),
|
||||
environment=str(body.get('environment') or 'prod').strip(),
|
||||
@@ -508,10 +648,14 @@ def create_binding():
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_binding(binding_id):
|
||||
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间)。
|
||||
"""更新绑定(可改 context / steps_json / 映射版本 / 优先级 / 环境 / 生效区间)。
|
||||
|
||||
状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转);
|
||||
客户端与接口成对校验:以变更后的最终组合为准,接口定义不属于该客户端即 400。
|
||||
状态不在此改写(须经动作端点按转移表流转)。规则(评审修正轮收紧后):
|
||||
[1] steps_json 与旧单步字段(interface_definition_code/param_mapping_json)同 PUT
|
||||
属矛盾载荷 → 400(旧键会被静默忽略、部分生效无提示);
|
||||
[2] 三把旧钥匙(interface_definition_code/param_mapping_json/client_instance_code)
|
||||
任一出现在多步绑定 PUT → 400(兼容窗会合成单元素 steps 回写、静默销毁第 2..n 步);
|
||||
[3] 单步绑定的旧字段 PUT 走兼容窗(换绑接口 / 仅更新首步映射);纯 steps_json PUT 不受限。
|
||||
"""
|
||||
from app import db
|
||||
binding = db.session.get(IntegrationBinding, binding_id)
|
||||
@@ -523,23 +667,83 @@ def update_binding(binding_id):
|
||||
binding.capability = body['capability']
|
||||
if 'context_selector_json' in body:
|
||||
binding.context_selector_json = body.get('context_selector_json') or {}
|
||||
if 'param_mapping_json' in body:
|
||||
binding.param_mapping_json = body.get('param_mapping_json') or {}
|
||||
new_client_code = body.get('client_instance_code')
|
||||
new_iface_code = body.get('interface_definition_code')
|
||||
if new_client_code is not None:
|
||||
_require(new_client_code, 'client_instance_code')
|
||||
if new_iface_code is not None:
|
||||
_require(new_iface_code, 'interface_definition_code')
|
||||
if new_client_code is not None or new_iface_code is not None:
|
||||
_validate_binding_pair(
|
||||
new_client_code if new_client_code is not None else binding.client_instance_code,
|
||||
new_iface_code if new_iface_code is not None else binding.interface_definition_code,
|
||||
|
||||
if 'steps_json' in body:
|
||||
# 评审 P2-2:矛盾载荷 fail-fast——steps_json 分支本会静默忽略旧单步键(部分生效无提示)。
|
||||
# client_instance_code 不在矛盾集:它在 steps_json 分支仍被消费(首步成对校验)。
|
||||
conflicts = sorted(
|
||||
key for key in ('interface_definition_code', 'param_mapping_json') if key in body
|
||||
)
|
||||
if new_client_code is not None:
|
||||
binding.client_instance_code = str(new_client_code).strip()
|
||||
if new_iface_code is not None:
|
||||
binding.interface_definition_code = str(new_iface_code).strip()
|
||||
if conflicts:
|
||||
raise ValidationError(
|
||||
'steps_json PUT cannot carry legacy single-step fields; they would be silently ignored',
|
||||
code='INTEGRATION.BINDING_LEGACY_PUT_REJECTED',
|
||||
details={
|
||||
'fields': conflicts,
|
||||
'conflicting_with': 'steps_json',
|
||||
'hint': 'submit the full ordered recipe via steps_json only',
|
||||
},
|
||||
)
|
||||
merge_body = {
|
||||
'steps_json': body['steps_json'],
|
||||
'client_instance_code': body.get('client_instance_code'),
|
||||
}
|
||||
steps = _normalize_binding_steps(merge_body)
|
||||
client_code, iface_code, param_mapping = _mirror_legacy_binding_columns(steps)
|
||||
binding.steps_json = steps
|
||||
binding.client_instance_code = client_code
|
||||
binding.interface_definition_code = iface_code
|
||||
binding.param_mapping_json = param_mapping
|
||||
elif 'interface_definition_code' in body or 'client_instance_code' in body or 'param_mapping_json' in body:
|
||||
# 评审 P1 守卫:三把旧钥匙(含 client_instance_code)任一出现在多步绑定 PUT,
|
||||
# 都会经兼容窗用旧单步列合成单元素 steps 回写、静默销毁第 2..n 步 → fail-fast 400。
|
||||
legacy_keys = sorted(
|
||||
key for key in ('interface_definition_code', 'param_mapping_json', 'client_instance_code')
|
||||
if key in body
|
||||
)
|
||||
if binding.steps_json and len(binding.steps_json) > 1:
|
||||
raise ValidationError(
|
||||
'legacy single-step fields cannot update a multi-step binding; use steps_json',
|
||||
code='INTEGRATION.BINDING_LEGACY_PUT_REJECTED',
|
||||
details={
|
||||
'fields': legacy_keys,
|
||||
'steps_count': len(binding.steps_json),
|
||||
'hint': 'submit the full ordered recipe via steps_json',
|
||||
},
|
||||
)
|
||||
# 兼容窗:旧单步字段 → 重写/局部更新 steps
|
||||
if (
|
||||
'param_mapping_json' in body
|
||||
and 'interface_definition_code' not in body
|
||||
and 'client_instance_code' not in body
|
||||
and binding.steps_json
|
||||
):
|
||||
steps = [dict(s) if isinstance(s, dict) else s for s in binding.steps_json]
|
||||
first = dict(steps[0])
|
||||
first['param_mapping_json'] = body.get('param_mapping_json') or {}
|
||||
steps[0] = first
|
||||
steps = _normalize_binding_steps({
|
||||
'steps_json': steps,
|
||||
'client_instance_code': binding.client_instance_code,
|
||||
})
|
||||
else:
|
||||
steps = _normalize_binding_steps({
|
||||
'interface_definition_code': body.get(
|
||||
'interface_definition_code', binding.interface_definition_code,
|
||||
),
|
||||
'client_instance_code': body.get(
|
||||
'client_instance_code', binding.client_instance_code,
|
||||
),
|
||||
'param_mapping_json': body.get(
|
||||
'param_mapping_json', binding.param_mapping_json or {},
|
||||
),
|
||||
})
|
||||
client_code, iface_code, param_mapping = _mirror_legacy_binding_columns(steps)
|
||||
binding.steps_json = steps
|
||||
binding.client_instance_code = client_code
|
||||
binding.interface_definition_code = iface_code
|
||||
binding.param_mapping_json = param_mapping
|
||||
|
||||
if body.get('mapping_version') is not None:
|
||||
binding.mapping_version = int(body.get('mapping_version') or 1)
|
||||
if body.get('priority') is not None:
|
||||
@@ -550,7 +754,6 @@ def update_binding(binding_id):
|
||||
binding.effective_from = body['effective_from'] or None
|
||||
if body.get('effective_to') is not None:
|
||||
binding.effective_to = body['effective_to'] or None
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_binding(binding))
|
||||
|
||||
@@ -560,7 +763,7 @@ def update_binding(binding_id):
|
||||
def _do_binding_lifecycle(binding_id: int, action: str):
|
||||
"""动作端点共用体:取绑定 → 按转移表转移 → 落库并回显。
|
||||
|
||||
发布(publish)附加就绪门禁:引用的接口定义须已发布、客户端实例须启用,
|
||||
发布(publish)附加就绪门禁:steps_json 每步接口须已发布、每步客户端须启用,
|
||||
否则 400——避免出现列表「已发布」但调用期永远 fail-closed 的死绑定
|
||||
(与 binding.resolve_binding 的调用期门禁同一语义)。
|
||||
"""
|
||||
@@ -569,17 +772,44 @@ def _do_binding_lifecycle(binding_id: int, action: str):
|
||||
if binding is None:
|
||||
raise NotFoundError('binding not found', code='INTEGRATION.BINDING_NOT_FOUND')
|
||||
if action == 'publish':
|
||||
client = IntegrationClientInstance.query.filter_by(code=binding.client_instance_code).first()
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=binding.interface_definition_code).first()
|
||||
if client is None or iface is None or iface.status != 'published' or not client.enabled:
|
||||
raw_steps = list(binding.steps_json or [])
|
||||
if not raw_steps and binding.interface_definition_code:
|
||||
raw_steps = [{
|
||||
'interface_code': binding.interface_definition_code,
|
||||
'param_mapping_json': binding.param_mapping_json or {},
|
||||
}]
|
||||
if not raw_steps:
|
||||
raise ValidationError(
|
||||
'binding target not ready: interface must be published and client instance enabled',
|
||||
'binding target not ready: steps_json is empty',
|
||||
code='INTEGRATION.BINDING_TARGET_NOT_READY',
|
||||
details={
|
||||
'client_instance_code': binding.client_instance_code,
|
||||
'interface_definition_code': binding.interface_definition_code,
|
||||
},
|
||||
details={'steps_json': []},
|
||||
)
|
||||
for idx, step in enumerate(raw_steps):
|
||||
if not isinstance(step, dict):
|
||||
raise ValidationError(
|
||||
'binding target not ready: invalid step',
|
||||
code='INTEGRATION.BINDING_TARGET_NOT_READY',
|
||||
details={'index': idx},
|
||||
)
|
||||
iface_code = str(step.get('interface_code') or '').strip()
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=iface_code).first()
|
||||
client = (
|
||||
IntegrationClientInstance.query.filter_by(code=iface.client_instance_code).first()
|
||||
if iface is not None else None
|
||||
)
|
||||
if client is None or iface is None or iface.status != 'published' or not client.enabled:
|
||||
raise ValidationError(
|
||||
'binding target not ready: each step interface must be published '
|
||||
'and client instance enabled',
|
||||
code='INTEGRATION.BINDING_TARGET_NOT_READY',
|
||||
details={
|
||||
'index': idx,
|
||||
'interface_code': iface_code,
|
||||
'client_instance_code': getattr(iface, 'client_instance_code', None),
|
||||
'iface_status': getattr(iface, 'status', None),
|
||||
'client_enabled': getattr(client, 'enabled', None),
|
||||
},
|
||||
)
|
||||
_apply_status_transition(binding, action, kind='binding')
|
||||
db.session.commit()
|
||||
return ok(_serialize_binding(binding))
|
||||
@@ -718,8 +948,8 @@ def update_credential_reference(code):
|
||||
def test_connection(code):
|
||||
"""连接测试探针:只证明网络/服务可达(设计文档:连接测试不做业务调用)。
|
||||
|
||||
配置兼容层与 binding.resolve_binding 同源:endpoint/timeout_seconds 独立列
|
||||
拼回 config_json 后再交给 transport,否则存独立列的地址会被误判为未冻结。
|
||||
配置兼容层与 binding.resolve_binding 同源:endpoint/timeout_seconds/db_kind
|
||||
独立列拼回 config_json 后再交给 transport,否则存独立列的地址/库种会被误判为未冻结。
|
||||
"""
|
||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||
if client is None:
|
||||
@@ -735,8 +965,12 @@ def test_connection(code):
|
||||
'config_json': client.config_json or {},
|
||||
'endpoint': client.endpoint,
|
||||
'timeout_seconds': client.timeout_seconds,
|
||||
'db_kind': client.db_kind,
|
||||
}),
|
||||
'credential': {},
|
||||
# 连接测试按设计须证明「网络与认证」可用(数据库直连无凭据无法建连):
|
||||
# 有凭据引用时解析真实凭据(db 解密 / env 注入,与 engine 调用链同源),
|
||||
# 无引用(匿名)为空 dict;解析失败 fail-closed 抛 CredentialUnresolvedError。
|
||||
'credential': resolve_credential(client.credential_ref_code) if client.credential_ref_code else {},
|
||||
}
|
||||
probe = getattr(transport, 'probe', None)
|
||||
if probe is not None:
|
||||
@@ -747,3 +981,82 @@ def test_connection(code):
|
||||
raw = transport.call(client=client_payload, interface={'request_spec_json': {}}, request={})
|
||||
ok_flag = raw.get('status') not in ('business_failed', 'technical_failed', 'timeout', 'result_unknown')
|
||||
return ok({'ok': ok_flag, 'status': 'success' if ok_flag else 'failed', 'result': raw})
|
||||
|
||||
|
||||
# ---- 集成调用日志查询 ----
|
||||
|
||||
@integration_connector_bp.route('/calls', methods=['GET'])
|
||||
@require_admin
|
||||
def list_integration_calls_api():
|
||||
"""集成调用日志分页查询(能力无关通用口径)。
|
||||
|
||||
筛选:capability/interface_code/client_code/connector_type/status/
|
||||
operation_id/trace_id/business_ref 精确;keyword 对请求摘要 JSON 文本模糊;
|
||||
date_from/date_to=YYYY-MM-DD(按 created_at 闭区间,date_to 补全天)。
|
||||
"""
|
||||
from sqlalchemy import cast, String
|
||||
|
||||
args = request.args
|
||||
query = IntegrationCall.query
|
||||
for field in ('capability', 'status', 'operation_id', 'trace_id', 'business_ref'):
|
||||
value = (args.get(field) or '').strip()
|
||||
if value:
|
||||
query = query.filter(getattr(IntegrationCall, field) == value)
|
||||
for json_field in ('interface_code', 'client_code', 'connector_type'):
|
||||
value = (args.get(json_field) or '').strip()
|
||||
if value:
|
||||
query = query.filter(
|
||||
IntegrationCall.binding_snapshot_json[json_field].as_string() == value)
|
||||
keyword = (args.get('keyword') or '').strip()
|
||||
if keyword:
|
||||
query = query.filter(
|
||||
cast(IntegrationCall.request_summary_json, String).ilike(f'%{keyword}%'))
|
||||
date_from = (args.get('date_from') or '').strip()
|
||||
if date_from:
|
||||
query = query.filter(IntegrationCall.created_at >= f'{date_from} 00:00:00')
|
||||
date_to = (args.get('date_to') or '').strip()
|
||||
if date_to:
|
||||
query = query.filter(IntegrationCall.created_at <= f'{date_to} 23:59:59.999999')
|
||||
|
||||
page = max(int(args.get('page') or 1), 1)
|
||||
page_size = min(max(int(args.get('page_size') or 20), 1), 100)
|
||||
total = query.count()
|
||||
rows = (query.order_by(IntegrationCall.id.desc())
|
||||
.offset((page - 1) * page_size).limit(page_size).all())
|
||||
|
||||
def _row(c: IntegrationCall) -> dict:
|
||||
snap = c.binding_snapshot_json or {}
|
||||
return {'id': c.id, 'created_at': c.created_at.isoformat() if c.created_at else None,
|
||||
'capability': c.capability, 'operation_id': c.operation_id,
|
||||
'trace_id': c.trace_id, 'status': c.status, 'elapsed_ms': c.elapsed_ms,
|
||||
'business_ref': c.business_ref,
|
||||
'client_code': snap.get('client_code'), 'interface_code': snap.get('interface_code'),
|
||||
'connector_type': snap.get('connector_type'),
|
||||
'step_index': snap.get('step_index'), 'step_count': snap.get('step_count')}
|
||||
|
||||
return ok({'total': total, 'page': page, 'page_size': page_size,
|
||||
'items': [_row(c) for c in rows]})
|
||||
|
||||
|
||||
@integration_connector_bp.route('/calls/<int:call_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_integration_call_api(call_id: int):
|
||||
"""单条全量(含 wire_json/request/response/绑定快照)+ 同 operation_id 步骤时间线。"""
|
||||
call = IntegrationCall.query.get(call_id)
|
||||
if call is None:
|
||||
raise NotFoundError('integration call not found', code='INTEGRATION.CALL_NOT_FOUND')
|
||||
full = {'id': call.id, 'created_at': call.created_at.isoformat() if call.created_at else None,
|
||||
'capability': call.capability, 'operation_id': call.operation_id,
|
||||
'trace_id': call.trace_id, 'status': call.status, 'elapsed_ms': call.elapsed_ms,
|
||||
'business_ref': call.business_ref,
|
||||
'binding_snapshot_json': call.binding_snapshot_json or {},
|
||||
'request_summary_json': call.request_summary_json or {},
|
||||
'response_summary_json': call.response_summary_json or {},
|
||||
'wire_json': call.wire_json}
|
||||
siblings = (IntegrationCall.query.filter_by(operation_id=call.operation_id)
|
||||
.order_by(IntegrationCall.id.asc()).all())
|
||||
timeline = [{'id': c.id, 'step_index': (c.binding_snapshot_json or {}).get('step_index'),
|
||||
'step_count': (c.binding_snapshot_json or {}).get('step_count'),
|
||||
'interface_code': (c.binding_snapshot_json or {}).get('interface_code'),
|
||||
'status': c.status, 'elapsed_ms': c.elapsed_ms} for c in siblings]
|
||||
return ok({'call': full, 'timeline': timeline})
|
||||
Reference in new issue
Block a user