Files
syops/docs/superpowers/plans/2026-09-27-integration-call-logs.md
T
hugo e750fa8602 feat(integration-connector): database 传输类型、两步绑定编排与调用日志捕获查询
- 新增 database 传输:直连 MySQL/Oracle/SQLServer/PostgreSQL 执行绑定 SQL(新增 pymysql/pymssql 驱动依赖)
- 绑定支持 steps_json 多步编排:每步独立传输调用与审计,无 steps 的既有绑定走单步兼容路径
- 客户端实例校验 connector_type ∈ rest/soap/database,database 强制 db_kind 白名单,非 database 置空
- 三个传输层捕获线级事实(最终 SQL/渲染后 XML/原始响应)随调用记录落库,引擎可选透传 business_ref 业务锚点
- 新增调用日志查询 API(列表/详情/同 operation 步骤时间线,仅管理员)与管理端「调用日志」tab:筛选、双栏对照、外部工具复现命令
- 迁移 tt7a/tta9/tt5b:连接器类型枚举、绑定 steps_json、放开 calls 操作唯一约束
- 说明:wire_json 列迁移挂链尾(依赖域表迁移),随后续批次单独落地
2026-09-27 18:05:08 +08:00

1063 lines
51 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 集成调用日志(wire 捕获 + 查询 API + 前台展示)实施计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 集成连接器每次能力调用在传输层捕获"线级事实"(database=最终 SQL+绑定+行数;soap=endpoint+渲染后 XML+原始响应;rest=method/URL/headers/body+原始响应),落库 `wire_json`,并提供管理端「调用日志」查询页(筛选 + 步骤时间线 + 原始/归一化双栏 + 外部工具复现命令)。
**Architecture:** 三层。① 记录增强:三个传输层执行时在返回 dict 上附加保留键 `_wire`,引擎 `_record_call` 取出并写入 `integration_calls.wire_json`(新列,Alembic 迁移);同迁移加可选业务锚点列 `business_ref`(VARCHAR(128)+索引),引擎入口可选透传、不传为 NULL(现有消费者零改动);② 查询 API:`GET /api/integration-connector/calls`(分页+筛选)与 `GET /calls/{id}`(全量+同 operation_id 时间线),全部 `require_admin`;③ 前台:admin 集成连接器页新增「调用日志」tab(列表+筛选+详情抽屉,能力无关的通用展示)。
**Tech Stack:** Flask + SQLAlchemy 2.0 + Alembic;Vue 3 `<script setup>` + TypeScript + TailwindCSS(沿 admin 既有 tab 页模式);vitest / pytest。
**Spec:** 本计划自包含(设计定稿于 2026-09-27 会话:能力无关通用日志;wire 按连接类型捕获;不含 business_ref——用户明确本期不做;不做页内重放与自动清理)。
## Global Constraints
- 日志永不落明文凭据:soap/rest 文本一律过 `mask_secrets(text, credential)`;headers 凭据键值脱敏后展示。
- 单字段截断上限 20000 字符(`_WIRE_TEXT_LIMIT`),截断尾缀 `...[truncated]`。
- 表结构变更必须配套 Alembic 迁移(upgrade + downgrade)。
- 前端新增文案必须 zh-CN / zh-TW / en / th 四语言同步(admin.json `integrationConnector` 命名空间)。
- API 一律 `@require_admin` + `ok()` envelope;错误码 `INTEGRATION.*`。
- wire 为能力无关通用结构;禁止出现任何业务领域专有字段。
- 历史存量调用 `wire_json` 为 NULL,前端如实展示「无线级详情」,不回填。
- 提交信息 Conventional Commits;前端改动必须 `npm run build` 通过。
---
## File Structure
```
backend/
migrations/versions/wd7e8f9a0b1c_add_integration_calls_wire_json.py # 新建(迁移)
app/models/integration_connector.py # 修改(wire_json 列)
app/services/integration_connector/engine.py # 修改(_record_call 写 wire_json;business_ref 全链透传)
app/services/in_transit_transfer/capability_client.py # 修改(create_transfer 可选 business_ref 参数)
app/services/in_transit_transfer/execution_service.py # 修改(_execute_document 传 business_ref=doc_no)
app/services/integration_connector/transports/database.py # 修改(_run_execute/_run_query 附加 _wire)
app/services/integration_connector/transports/soap.py # 修改(call 附加 _wire)
app/services/integration_connector/transports/rest.py # 修改(call 附加 _wire)
app/api/integration_connector.py # 修改(/calls 列表 + 详情)
tests/services/integration_connector/test_database_transport.py # 修改(wire 断言)
tests/services/integration_connector/test_soap_transport.py # 修改(wire 断言)
tests/services/integration_connector/test_rest_transport.py # 修改(wire 断言)
tests/services/integration_connector/test_engine.py # 修改(wire_json 落库断言)
tests/api/test_integration_connector_api.py # 修改(calls 查询端点测试)
frontend/src/features/admin/modules/integration-connector/
api/integration-connector.api.ts # 修改(calls 查询封装)
types/integration-connector.types.ts # 修改(wire/调用行类型)
utils/integration-call-replay.ts # 新建(curl/SQL 复现命令生成)
utils/integration-call-replay.spec.ts # 新建(复现命令单测)
components/IntegrationCallLogsPanel.vue # 新建(列表+筛选+抽屉)
IntegrationCallLogsPanel.spec.ts # 新建(面板测试)
IntegrationConnectorPage.vue # 修改(挂 calls tab)
frontend/src/locales/{zh-CN,zh-TW,en,th}/admin.json # 修改(integrationConnector.callLogs.*)
```
---
### Task 1: 迁移 + 模型列 wire_json
**Files:**
- Create: `backend/migrations/versions/wd7e8f9a0b1c_add_integration_calls_wire_json.py`
- Modify: `backend/app/models/integration_connector.py`(IntegrationCall 增列)
**Interfaces:**
- Produces: `IntegrationCall.wire_json: dict | None`(后续 Task 2-4 写入、Task 5 读取)。
- [ ] **Step 1: 确认当前迁移 head**
```bash
cd backend && ./.venv/Scripts/python.exe -m flask db heads
```
以输出值作为新迁移的 `down_revision`(下例按 `vc6a7b8c9d0e` 书写,若 head 不同则以实际为准替换)。
- [ ] **Step 2: 写迁移文件**
```python
"""Add integration_calls.wire_json.
Revision ID: wd7e8f9a0b1c
Revises: vc6a7b8c9d0e
Create Date: 2026-09-27 00:00:00.000000
用途:集成调用审计增列 wire_json(传输层线级事实)与 business_ref(通用业务
锚点:调用方透传的业务单号/任务号,能力无关,不传为 NULL)。
依赖:integration_calls 表。
逻辑:均可空;历史行保持 NULL(前端如实展示「无线级详情」,不回填)。
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = "wd7e8f9a0b1c"
down_revision = "vc6a7b8c9d0e"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("integration_calls", sa.Column("wire_json", sa.JSON(), nullable=True))
op.add_column("integration_calls",
sa.Column("business_ref", sa.String(length=128), nullable=True))
op.create_index("ix_integration_calls_business_ref", "integration_calls", ["business_ref"])
def downgrade() -> None:
op.drop_index("ix_integration_calls_business_ref", table_name="integration_calls")
op.drop_column("integration_calls", "business_ref")
op.drop_column("integration_calls", "wire_json")
```
- [ ] **Step 3: 模型增列**
在 `app/models/integration_connector.py` 的 `IntegrationCall` 内 `trace_id` 列之后追加:
```python
# 线级事实(database 最终 SQL/绑定/行数;soap endpoint+XML;rest HTTP 往返)。
# 可空:历史行与未捕获场景为 NULL,前台如实展示。
wire_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
# 通用业务锚点:调用方透传的业务单号/任务号(能力无关;不传为 NULL)。
business_ref: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
```
- [ ] **Step 4: 执行迁移并验证**
```bash
./.venv/Scripts/python.exe -m flask db upgrade
./.venv/Scripts/python.exe -m pytest tests/services/integration_connector -q
```
Expected: 迁移成功;既有 connector 测试全绿(模型加列不破坏行为)。
---
### Task 2: database 传输层 wire 捕获
**Files:**
- Modify: `backend/app/services/integration_connector/transports/database.py`(`_run_execute` / `_run_query`)
- Test: `backend/tests/services/integration_connector/test_database_transport.py`
**Interfaces:**
- Consumes: 既有 `_apply_identifiers` / `_filter_statement_binds`(本文件)。
- Produces: 返回 dict 携带保留键 `_wire`:`{'kind': 'database', 'statements': [{'phase','sql','binds','rowcount'}...], 'rowcount': int}`(execute);`{'kind': 'database', 'statements': [{'phase':'query','sql','binds'}], 'rows': [...]}`(query)。引擎(Task 4)据此写 `wire_json`。
- [ ] **Step 1: 写失败测试**
在 `test_database_transport.py` 末尾追加(沿用文件内 `FakeConn`/`FakeCursor`/`_client`/`_iface_execute` 夹具):
```python
def test_execute_attaches_wire_with_final_sql_and_binds(monkeypatch):
"""execute 返回的 _wire 必须带标识符替换后的最终 SQL、逐语句绑定与行数。"""
conn = FakeConn()
_patch_driver(monkeypatch, 'mysql', lambda **kw: conn)
transport = DatabaseTransport()
result = transport.call(
client=_client(),
interface=_iface_execute(
pre=['DELETE FROM t WHERE batch=:batch'],
bulk={'sql': 'INSERT INTO t (batch, sku) VALUES (:batch, :sku)', 'rows_param': 'lines'},
post=[],
),
request={'params': {'batch': 'B1', 'lines': [{'sku': 'S1'}]}},
)
wire = result['_wire']
assert wire['kind'] == 'database'
assert [s['phase'] for s in wire['statements']] == ['pre', 'bulk']
assert wire['statements'][0]['sql'] == 'DELETE FROM t WHERE batch=:batch'
assert wire['statements'][0]['binds'] == {'batch': 'B1'}
assert wire['statements'][1]['sql'] == 'INSERT INTO t (batch, sku) VALUES (:batch, :sku)'
assert wire['statements'][1]['binds'] == {'batch': 'B1', 'sku': 'S1'}
assert 'rowcount' in wire
def test_query_attaches_wire_with_sql_and_rows(monkeypatch):
cursor = FakeCursor(rows=[('S1', 10)], description=[('sku',), ('qty',)])
conn = FakeConn(cursor)
_patch_driver(monkeypatch, 'postgresql', lambda **kw: conn)
transport = DatabaseTransport()
result = transport.call(
client=_client(endpoint='pg.invalid:5432/inv', db_kind='postgresql'),
interface=_iface_query('SELECT sku AS sku, qty AS qty FROM t WHERE wh=:wh'),
request={'params': {'wh': 'HUB'}},
)
assert result['_wire']['kind'] == 'database'
assert result['_wire']['statements'][0]['sql'] == 'SELECT sku AS sku, qty AS qty FROM t WHERE wh=:wh'
assert result['_wire']['rows'] == [{'sku': 'S1', 'qty': 10}]
```
- [ ] **Step 2: 跑测试确认失败**
```bash
./.venv/Scripts/python.exe -m pytest tests/services/integration_connector/test_database_transport.py -q -k wire
```
Expected: FAIL(KeyError: '_wire')。
- [ ] **Step 3: 实现 `_run_execute` wire 捕获**
`database.py` 顶部常量区追加:
```python
# wire 单文本字段截断上限(防大报文撑爆审计列)。
_WIRE_TEXT_LIMIT = 20000
```
`_run_execute` 改为(在既有逻辑上收集 statements 并附加 `_wire`):
```python
statements: list[dict] = []
# [STEP 2] pre 语句(按语句引用过滤后的基础参数)
for stmt in list(sql_spec.get('pre') or []):
sql = _apply_identifiers(str(stmt), identifiers=identifiers, params=params)
cursor.execute(sql, _filter_statement_binds(base, sql))
statements.append({'phase': 'pre', 'sql': sql,
'binds': _filter_statement_binds(base, sql),
'rowcount': int(getattr(cursor, 'rowcount', 0) or 0)})
# [STEP 3] bulk:行与基础参数合并,行内键覆盖;合并后再剔标识符键
if bulk:
bulk_sql = _apply_identifiers(
str(bulk.get('sql') or ''), identifiers=identifiers, params=params,
)
raw_rows = params.get(rows_param) if rows_param else None
if not isinstance(raw_rows, list):
raise InputInvalidError(
f'bulk.rows_param must resolve to a list: {rows_param!r}',
details={'rows_param': rows_param},
)
merged_rows = [
_strip_identifier_keys({**base_raw, **dict(row or {})}, identifiers)
for row in raw_rows
]
cursor.executemany(
bulk_sql,
[_filter_statement_binds(row, bulk_sql) for row in merged_rows],
)
statements.append({'phase': 'bulk', 'sql': bulk_sql,
'binds': merged_rows[0] if merged_rows else {},
'rowcount': int(getattr(cursor, 'rowcount', 0) or 0),
'row_count': len(merged_rows)})
# [STEP 4] post 语句
for stmt in list(sql_spec.get('post') or []):
sql = _apply_identifiers(str(stmt), identifiers=identifiers, params=params)
cursor.execute(sql, _filter_statement_binds(base, sql))
statements.append({'phase': 'post', 'sql': sql,
'binds': _filter_statement_binds(base, sql),
'rowcount': int(getattr(cursor, 'rowcount', 0) or 0)})
conn.commit()
return {'status': 'success',
'_wire': {'kind': 'database', 'statements': statements,
'rowcount': sum(s.get('rowcount', 0) for s in statements)}}
```
- [ ] **Step 4: 实现 `_run_query` wire 捕获**
```python
raw_sql = str(sql_spec.get('sql') or '').strip()
if not raw_sql:
raise InputInvalidError('query mode requires sql.sql')
sql = _apply_identifiers(raw_sql, identifiers=identifiers, params=params)
binds = _filter_statement_binds(
_strip_identifier_keys(params, identifiers), sql)
cursor.execute(sql, binds)
rows = _rows_as_dicts(cursor)
return {'status': 'success', 'rows': rows,
'_wire': {'kind': 'database',
'statements': [{'phase': 'query', 'sql': sql, 'binds': binds}],
'rows': rows[:_WIRE_TEXT_LIMIT]}}
```
- [ ] **Step 5: 跑测试确认通过**
```bash
./.venv/Scripts/python.exe -m pytest tests/services/integration_connector/test_database_transport.py -q
```
Expected: PASS(既有 27+ 测试不受影响——`_wire` 为附加键,既有断言取具体键不冲突)。
---
### Task 3: soap + rest 传输层 wire 捕获
**Files:**
- Modify: `backend/app/services/integration_connector/transports/soap.py`(`call`)
- Modify: `backend/app/services/integration_connector/transports/rest.py`(`call`)
- Test: `backend/tests/services/integration_connector/test_soap_transport.py`、`test_rest_transport.py`
**Interfaces:**
- Produces: 返回 dict 保留键 `_wire`:
- soap:`{'kind':'soap','method','url','soap_action','request_body'(masked),'http_status','response_body'(masked,≤20000)}`
- rest:`{'kind':'rest','method','url','headers'(masked),'request_body','http_status','response_body'(masked,≤20000)}`
- [ ] **Step 1: 写失败测试**
`test_soap_transport.py` 既有夹具风格(假 http_request 返回固定 text)追加:
```python
def test_call_attaches_wire_with_url_body_and_response():
captured = {}
def fake_http(method, url, **kwargs):
captured['method'], captured['url'], captured['kwargs'] = method, url, kwargs
return FakeResponse(text='<Envelope><Body><ok>1</ok></Body></Envelope>', status_code=200)
transport = SoapTransport(http_request=fake_http)
result = transport.call(
client={'config_json': {'endpoint': 'http://erp/WS?wsdl', 'timeout_seconds': 30},
'credential': {'username': 'u', 'password': 'p'}},
interface={'request_spec_json': {'method': 'POST', 'soap': {
'action': 'do.it',
'body_template': '<Env><a>{credential_username}</a><b>{v}</b></Env>'}}},
request={'params': {'v': '1'}},
)
wire = result['_wire']
assert wire['kind'] == 'soap'
assert wire['method'] == 'POST'
assert wire['url'] == 'http://erp/WS?wsdl'
assert wire['soap_action'] == '"do.it"'
assert wire['request_body'] == '<Env><a>u</a><b>1</b></Env>'
assert wire['http_status'] == 200
assert 'Envelope' in wire['response_body']
def test_call_wire_masks_credential_in_body():
def fake_http(method, url, **kwargs):
return FakeResponse(text='<Envelope/>', status_code=200)
transport = SoapTransport(http_request=fake_http)
result = transport.call(
client={'config_json': {'endpoint': 'http://erp/WS'}, 'credential': {'password': 'sup3r'}},
interface={'request_spec_json': {'soap': {'action': '', 'body_template': '<p>{credential_password}</p>'}}},
request={'params': {}},
)
assert 'sup3r' not in result['_wire']['request_body']
```
(`FakeResponse` 若文件内已有同名替身则复用;没有则定义 `text`/`status_code`/`raise_for_status` 三件套。)
`test_rest_transport.py` 同风格追加:
```python
def test_call_attaches_wire_with_method_url_headers_body(monkeypatch):
captured = {}
def fake_http(method, url, **kwargs):
captured.update(method=method, url=url, kwargs=kwargs)
return FakeResponse(text='{"ok": true}', status_code=200)
transport = RestTransport(http_request=fake_http)
result = transport.call(
client={'config_json': {'endpoint': 'http://api', 'headers': {'X-App': 'hxops'}}},
interface={'request_spec_json': {'method': 'POST', 'path': 'v1/things'}},
request={'body': {'a': 1}},
)
wire = result['_wire']
assert wire['kind'] == 'rest'
assert wire['method'] == 'POST'
assert wire['url'] == 'http://api/v1/things'
assert wire['http_status'] == 200
assert '"a": 1' in wire['request_body'] or wire['request_body'] == '{"a":1}'
```
- [ ] **Step 2: 跑测试确认失败**(KeyError: '_wire')
- [ ] **Step 3: 实现 soap wire**
`soap.py` 顶部:`_WIRE_TEXT_LIMIT = 20000`。`call()` 内在 `response = self._http_request(...)` 之后、返回之前构造 wire;两个 return 分支都附加:
```python
response = self._http_request(
method, url, data=body.encode('utf-8'), headers=headers,
timeout=int(config.get('timeout_seconds') or 60),
)
http_status = int(getattr(response, 'status_code', 0))
response_text = mask_secrets(str(getattr(response, 'text', '') or ''), client.get('credential'))
wire = {'kind': 'soap', 'method': method, 'url': url,
'soap_action': headers['SOAPAction'],
'request_body': mask_secrets(body, client.get('credential')),
'http_status': http_status,
'response_body': response_text[:_WIRE_TEXT_LIMIT]}
if http_status >= 400:
return {
'status': 'business_failed',
'code': f"HTTP_{http_status}",
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
'_wire': wire,
}
try:
parsed = _parse_soap_payload(response_text)
except ET.ParseError:
return {'status': 'technical_failed', 'code': 'NON_XML',
'message': response_text[:500], '_wire': wire}
parsed['_wire'] = wire
return parsed
```
(原 `response_text = mask_secrets(...)` 上移到分支之前——保持既有 NON_XML / HTTP≥400 行为不变,仅附加 `_wire`。)
- [ ] **Step 4: 实现 rest wire**
`rest.py` `call()` 同样在 http 调用后构造:
```python
response = self._http_request(
method, url, json=request.get('body'), headers=headers,
timeout=int(config.get('timeout_seconds') or 60),
)
http_status = int(getattr(response, 'status_code', 0))
response_text = str(getattr(response, 'text', '') or '')
request_body = json.dumps(request.get('body'), ensure_ascii=False, default=str) \
if request.get('body') is not None else ''
wire = {'kind': 'rest', 'method': method, 'url': url,
'headers': mask_secrets(json.dumps(headers, ensure_ascii=False, default=str),
client.get('credential')),
'request_body': request_body,
'http_status': http_status,
'response_body': mask_secrets(response_text, client.get('credential'))[:_WIRE_TEXT_LIMIT]}
```
(`_WIRE_TEXT_LIMIT = 20000` 加在 rest.py 顶部;返回的各分支 dict 一律附加 `'_wire': wire`——含 HTTP≥400 分支与成功分支。)
- [ ] **Step 5: 跑测试确认通过**
```bash
./.venv/Scripts/python.exe -m pytest tests/services/integration_connector/test_soap_transport.py tests/services/integration_connector/test_rest_transport.py -q
```
Expected: PASS。
---
### Task 4: 引擎落库 wire_json + business_ref 透传
**Files:**
- Modify: `backend/app/services/integration_connector/engine.py`(`call`/`_call_read`/`_call_write`/`_record_call`)
- Modify: `backend/app/services/in_transit_transfer/capability_client.py`(`create_transfer` 可选参数)
- Modify: `backend/app/services/in_transit_transfer/execution_service.py`(`_execute_document` 传参)
- Test: `backend/tests/services/integration_connector/test_engine.py`
**Interfaces:**
- Consumes: Task 2/3 的 `_wire` 保留键。
- Produces: `IntegrationCall.wire_json` 与 `business_ref` 落库;`CapabilityGateway.call(..., business_ref: str | None = None)`;`CapabilityClient.create_transfer(..., business_ref: str | None = None)`(Task 5 API 直接读列)。
- [ ] **Step 1: 写失败测试**
`test_engine.py` 中任一既有"执行后落 IntegrationCall"的测试旁追加断言/用例(沿用其既有 mock 传输夹具;传输替身的返回 dict 附 `'_wire': {'kind': 'database', 'rowcount': 1}`):
```python
def test_record_call_persists_wire_json(app, ...):
# 沿用该文件既有引擎执行替身路径执行一次 create/query 能力
...
call = IntegrationCall.query.order_by(IntegrationCall.id.desc()).first()
assert call.wire_json == {'kind': 'database', 'rowcount': 1}
# wire 不混入响应摘要
assert '_wire' not in (call.response_summary_json or {})
def test_call_persists_business_ref(app, ...):
# 沿用同上替身路径:business_ref 透传落库;不传时为 NULL(现有消费者零改动)。
... # execute(..., business_ref='TGHX1-OR-26092600002')
call = IntegrationCall.query.order_by(IntegrationCall.id.desc()).first()
assert call.business_ref == 'TGHX1-OR-26092600002'
```
- [ ] **Step 2: 跑测试确认失败**(wire_json 为 None)
- [ ] **Step 3: 实现**
`engine.call` 签名追加 `business_ref: str | None = None` 并透传 `_call_read/_call_write` → `_record_call`(各签名同步加参);`_record_call` 内,构造 `IntegrationCall` 之前:
```python
raw_dict = dict(raw) if isinstance(raw, dict) else {}
wire = raw_dict.pop('_wire', None)
```
`IntegrationCall(...)` 增参 `wire_json=wire if isinstance(wire, dict) else None`、`business_ref=business_ref`;`response_summary_json=sanitize(raw or {})` 改为 `sanitize(raw_dict or {})`(防 `_wire` 混入响应摘要)。
`capability_client.create_transfer` 追加可选参 `business_ref: str | None = None` 并透传 `self._gateway().call(..., business_ref=business_ref)`;`execution_service._execute_document` 的 create_transfer 调用追加 `business_ref=doc.doc_no`(单号即业务锚点;query_inventory 读能力不传)。
- [ ] **Step 4: 跑测试确认通过**
```bash
./.venv/Scripts/python.exe -m pytest tests/services/integration_connector/test_engine.py tests/services/integration_connector/test_engine_steps.py -q
```
Expected: PASS。
---
### Task 5: 查询 API(列表 + 详情)
**Files:**
- Modify: `backend/app/api/integration_connector.py`
- Test: `backend/tests/api/test_integration_connector_api.py`
**Interfaces:**
- Produces:
- `GET /api/integration-connector/calls?capability=&interface_code=&client_code=&connector_type=&status=&operation_id=&trace_id=&keyword=&date_from=&date_to=&page=&page_size=` → `ok({total, page, page_size, items:[{id, created_at, capability, operation_id, trace_id, status, elapsed_ms, client_code, interface_code, connector_type, step_index, step_count}]})`
- `GET /api/integration-connector/calls/<int:call_id>` → `ok({call:{...全量含 wire_json/request/response/binding_snapshot}, timeline:[同 operation_id 各步摘要]})`
- `keyword`:对 `request_summary_json` 文本化后模糊匹配(`CAST(json AS VARCHAR) ILIKE`)。
- [ ] **Step 1: 写失败测试**
`test_integration_connector_api.py` 追加(沿用该文件既有 admin 登录/建行夹具;造 2 条 operation 相同的 IntegrationCall):
```python
def test_list_calls_filters_by_interface_and_keyword(client, admin_headers):
# 造数:同一 operation_id 两条(stage 成功 + ws 失败),另一条无关能力
...
resp = client.get('/api/integration-connector/calls?interface_code=erp-ws-submit-transfer',
headers=admin_headers)
body = resp.get_json()['data']
assert body['total'] == 1
assert body['items'][0]['interface_code'] == 'erp-ws-submit-transfer'
def test_list_calls_keyword_searches_request_summary(client, admin_headers):
resp = client.get('/api/integration-connector/calls?keyword=TGHX1-OR-26092600002',
headers=admin_headers)
assert resp.get_json()['data']['total'] >= 1
def test_call_detail_returns_wire_and_timeline(client, admin_headers):
call = IntegrationCall.query.order_by(IntegrationCall.id.desc()).first()
resp = client.get(f'/api/integration-connector/calls/{call.id}', headers=admin_headers)
data = resp.get_json()['data']
assert data['call']['id'] == call.id
assert data['call']['wire_json'] is None or isinstance(data['call']['wire_json'], dict)
assert len(data['timeline']) >= 1
```
- [ ] **Step 2: 跑测试确认失败**(404)
- [ ] **Step 3: 实现端点**
`app/api/integration_connector.py` 追加(imports:`cast, String` from sqlalchemy;`IntegrationCall` from app.models.integration_connector):
```python
@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})
```
(`IntegrationCall` 若未在文件头 imports 中则补 `from app.models.integration_connector import IntegrationCall`。)
- [ ] **Step 4: 跑测试确认通过**
```bash
./.venv/Scripts/python.exe -m pytest tests/api/test_integration_connector_api.py -q
```
Expected: PASS。
---
### Task 6: 前端类型 + API 封装
**Files:**
- Modify: `frontend/src/features/admin/modules/integration-connector/types/integration-connector.types.ts`
- Modify: `frontend/src/features/admin/modules/integration-connector/api/integration-connector.api.ts`
**Interfaces:**
- Produces: `IntegrationCallRow` / `IntegrationCallDetail` 类型与 `listIntegrationCalls(filters)` / `getIntegrationCall(id)`(Task 7 面板消费)。
- [ ] **Step 1: 类型追加**(types 文件末尾)
```typescript
/** 集成调用日志行(GET /calls 列表项;字段全部能力无关通用口径)。 */
export interface IntegrationCallLogRow {
id: number;
created_at: string | null;
capability: string;
operation_id: string;
trace_id: string;
status: string;
elapsed_ms: number;
business_ref: string | null;
client_code: string | null;
interface_code: string | null;
connector_type: string | null;
step_index: number | null;
step_count: number | null;
}
/** 线级事实(按连接类型二选一;database=SQL/绑定/行数,soap/rest=HTTP 往返)。 */
export interface IntegrationCallWire {
kind: 'database' | 'soap' | 'rest';
statements?: { phase: string; sql: string; binds: Record<string, unknown>; rowcount?: number; row_count?: number }[];
rowcount?: number;
rows?: unknown[];
method?: string;
url?: string;
soap_action?: string;
headers?: string;
request_body?: string;
http_status?: number;
response_body?: string;
}
/** 调用全量详情(GET /calls/{id};含同 operation_id 步骤时间线)。 */
export interface IntegrationCallDetail {
call: {
id: number;
created_at: string | null;
capability: string;
operation_id: string;
trace_id: string;
status: string;
elapsed_ms: number;
business_ref: string | null;
binding_snapshot_json: Record<string, unknown>;
request_summary_json: Record<string, unknown>;
response_summary_json: Record<string, unknown>;
wire_json: IntegrationCallWire | null;
};
timeline: { id: number; step_index: number | null; step_count: number | null; interface_code: string | null; status: string; elapsed_ms: number }[];
}
/** 列表查询条件(全部可选;后端缺省口径 page=1/page_size=20)。 */
export interface IntegrationCallFilters {
capability?: string;
interface_code?: string;
client_code?: string;
connector_type?: string;
status?: string;
operation_id?: string;
trace_id?: string;
keyword?: string;
business_ref?: string;
date_from?: string;
date_to?: string;
page?: number;
page_size?: number;
}
```
- [ ] **Step 2: API 封装追加**(api 文件末尾)
```typescript
// ---- 调用日志 ----
/** 集成调用日志分页查询(能力无关;keyword 对请求摘要 JSON 模糊)。 */
export const listIntegrationCalls = (filters: IntegrationCallFilters = {}) =>
requestJson<{ total: number; page: number; page_size: number; items: IntegrationCallLogRow[] }>(
`${BASE}/calls`,
{ ...auth(), params: filters },
);
/** 调用全量详情(含 wire_json 与同 operation_id 步骤时间线)。 */
export const getIntegrationCall = (id: number) =>
requestJson<IntegrationCallDetail>(`${BASE}/calls/${id}`, auth());
```
(types import 行补 `IntegrationCallDetail, IntegrationCallFilters, IntegrationCallLogRow`;`requestJson` 是否原生支持 `params` 以 `@/shared/api/client` 实际签名为准——若不支持则手工拼 querystring:`const qs = new URLSearchParams(...).toString()`。)
---
### Task 7: 前端「调用日志」面板(含框线图)
**Files:**
- Create: `frontend/src/features/admin/modules/integration-connector/utils/integration-call-replay.ts`
- Create: `frontend/src/features/admin/modules/integration-connector/utils/integration-call-replay.spec.ts`
- Create: `frontend/src/features/admin/modules/integration-connector/components/IntegrationCallLogsPanel.vue`
- Create: `frontend/src/features/admin/modules/integration-connector/IntegrationCallLogsPanel.spec.ts`
**Interfaces:**
- Consumes: Task 6 的 `listIntegrationCalls` / `getIntegrationCall` / 类型。
- Produces: 面板组件(Task 8 挂到页面 tab)。
#### 框线图 1:列表页(tab「调用日志」激活态)
```
┌────────────────────────────────────────────────────────────────────────────────┐
│ 集成连接器 │
│ [客户端] [接口定义] [绑定] [凭据] [能力] [●调用日志] │
├────────────────────────────────────────────────────────────────────────────────┤
│ ▍筛选(全部可选,回车/点查询生效) │
│ ┌──────────────┐ ┌──────────────┐ ┌────────────┐ ┌────────────┐ ┌───────────┐ │
│ │ 接口编码 ▼ │ │ 客户端编码 ▼ │ │ 连接类型 ▼ │ │ 状态 ▼ │ │operation_id│ │
│ └──────────────┘ └──────────────┘ └────────────┘ └────────────┘ └───────────┘ │
│ ┌────────────────────────┐ │
│ │ 业务单号 business_ref │ │
│ └────────────────────────┘ │
│ ┌──────────────────────────┐ ┌──────────────┐ ┌──────────────┐ ┌────┐ ┌────┐ │
│ │ 参数关键字(模糊搜请求内容) │ │ 执行时间起 │ │ 执行时间止 │ │查询│ │重置│ │
│ └──────────────────────────┘ └──────────────┘ └──────────────┘ └────┘ └────┘ │
│────────────────────────────────────────────────────────────────────────────────│
│ ▍调用记录(共 {total} 条) │
│ ┌──┬───────────────┬──────────────────────────────┬──────────────┬─────┬─────┬──────┐
│ │# │ 时间(本地) │ 能力 / 接口 │ 单号(op 前8位) │ 步骤 │ 状态 │ 耗时 │
│ ├──┼───────────────┼──────────────────────────────┼──────────────┼─────┼─────┼──────┤
│ │261│ 09-27 00:29:22│ in_transit_transfer.create… │erp-ws-sub… │ 1/2 │✗失败│ 324ms│←点击
│ │260│ 09-27 00:29:21│ …create_transfer │submit-stage… │ 0/2 │✓成功│2366ms│
│ │… │ │ │ │ │ │ │
│ └──┴───────────────┴──────────────────────────────┴──────────────┴─────┴─────┴──────┘
│ ‹ 上一页 第1/7页 下一页 › │
└────────────────────────────────────────────────────────────────────────────────┘
```
#### 框线图 2:详情抽屉(点列表行后右侧滑出)
```
┌───────────────────────────────────────────────────────────────────────┐
│ 调用详情 #261 [✕ 关闭] │
│ 能力: in_transit_transfer.create_transfer 状态: ✗ 失败 耗时: 324ms │
│ operation: op-cbf5… [复制] trace: ic-244f… [复制] │
│───────────────────────────────────────────────────────────────────────│
│ 步骤时间线(同一次能力调用 N 步): │
│ ● step0 submit-stage-table ──✓成功── ● step1 erp-ws-submit ──✗失败 │
│───────────────────────────────────────────────────────────────────────│
│ ▍请求 │
│ ┌─ 线级请求(wire)────────────────────┐ ┌─ 业务参数(归一化)──────────┐ │
│ │ method/url/soap_action/headers │ │ { │ │
│ │ ── request_body ── │ │ "doc_no": "TGHX1-OR-…", │ │
│ │ <soapenv:Envelope>…完整 XML…</…> │ │ "lines": [ … ] │ │
│ │ │ │ } │ │
│ │ [复制 body] [复制 curl] │ │ [复制 JSON] │ │
│ └──────────────────────────────────────┘ └────────────────────────────┘ │
│ ▍响应 │
│ ┌─ 原始报文 ───────────────────────────┐ ┌─ 归一化 JSON ────────────────┐ │
│ │ HTTP 200 │ │ { "Execution": {…}, │ │
│ │ <soapenv:Envelope>…响应 XML…</…> │ │ "ResponseContent": {…} } │ │
│ │ [复制原始报文] │ │ [复制 JSON] │ │
│ └──────────────────────────────────────┘ └─────────────────────────────┘ │
│ (database 类型时:请求区为 pre/bulk/post 三段最终 SQL + 绑定首行 + 行数; │
│ [复制 SQL] 生成绑定已内联的可执行版;写入类自动包事务并红字提示) │
└───────────────────────────────────────────────────────────────────────┘
```
- [ ] **Step 1: 复现命令生成函数 + 单测**
`utils/integration-call-replay.ts`:
```typescript
/**
* 集成调用复现命令生成(wire → 外部工具可直接执行的文本)。
* 逻辑:soap/rest 生成 curl(凭据位为 ***REDACTED***,需手工替换);
* database 生成绑定已内联的 SQL(写入类包事务并标注警示)。
*/
import type { IntegrationCallWire } from '../types/integration-connector.types';
const REDACTED = '***REDACTED***';
function shellQuote(value: string): string {
return `'${value.replaceAll("'", `'\\''`)}'`;
}
/**
* 拼接 curl 多行命令并剥离末段尾随续行符(修复 I1:末行若以 `\` 结尾,
* 粘贴进 bash 会进入 PS2 续行等待,破坏「可直接执行」承诺)。
*/
function joinCurlCommand(lines: string[]): string {
return lines.filter(Boolean).join('\n').replace(/ \\$/, '');
}
export function buildCurl(wire: IntegrationCallWire): string {
if (wire.kind === 'soap') {
return joinCurlCommand([
`curl -X ${wire.method || 'POST'} ${shellQuote(wire.url || '')} \\`,
` -H 'Content-Type: text/xml; charset=utf-8' \\`,
` -H ${shellQuote(`SOAPAction: ${wire.soap_action || '""'}`)} \\`,
` --data-binary ${shellQuote(wire.request_body || '')}`,
]);
}
const headers = wire.headers
? (JSON.parse(wire.headers) as Record<string, string>)
: {};
const headerLines = Object.entries(headers)
.map(([k, v]) => ` -H ${shellQuote(`${k}: ${v === '***' ? REDACTED : v}`)} \\`)
.join('\n');
const bodyPart = wire.request_body
? ` -d ${shellQuote(wire.request_body)} \\`
: '';
return joinCurlCommand([
`curl -X ${wire.method || 'GET'} ${shellQuote(wire.url || '')} \\`,
headerLines,
bodyPart,
]);
}
function quoteLiteral(value: unknown): string {
if (value === null || value === undefined) return 'NULL';
if (typeof value === 'number') return String(value);
return `'${String(value).replaceAll("'", "''")}'`;
}
export function inlineBinds(sql: string, binds: Record<string, unknown>): string {
return sql.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, (raw, name: string) =>
name in binds ? quoteLiteral(binds[name]) : raw);
}
export function buildSqlReplay(wire: IntegrationCallWire): string {
const statements = (wire.statements || [])
.map((s) => (s.phase === 'bulk'
? `-- bulk(绑定取首行;全量行由应用逐行 executemany)\n${inlineBinds(s.sql, s.binds || {})}`
: inlineBinds(s.sql, s.binds || {})));
const isWrite = statements.some((s) => /^\s*(INSERT|UPDATE|DELETE|MERGE)/im.test(s));
const body = statements.join(';\n\n');
return isWrite ? `-- ⚠ 写入语句:请确认目标环境后再执行\nBEGIN;\n${body};\nROLLBACK; -- 确认后改为 COMMIT` : `${body};`;
}
```
`utils/integration-call-replay.spec.ts`:覆盖 soap curl(含 SOAPAction 引号)、rest curl(headers 展开)、inlineBinds(含 `it doesn't` 转义)、buildSqlReplay 写入类包事务四例(vitest,断言字符串包含关键片段)。
- [ ] **Step 2: 面板组件**
`components/IntegrationCallLogsPanel.vue`(核心结构,样式沿用 Tailwind 既有 admin 表格口径;`v-model` 均本地态):
```vue
<script setup lang="ts">
/**
* 集成调用日志面板:筛选(接口/客户端/连接类型/状态/operation_id/trace_id/
* 参数关键字/时间起止)→ 分页列表 → 行点击开详情抽屉(步骤时间线 +
* 线级/归一化双栏 + 复现命令复制)。能力无关通用口径。
*/
import { onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '@/shared/composables/useMessage';
import { getIntegrationCall, listIntegrationCalls } from '../api/integration-connector.api';
import type { IntegrationCallDetail, IntegrationCallFilters, IntegrationCallLogRow } from '../types/integration-connector.types';
import { buildCurl, buildSqlReplay } from '../utils/integration-call-replay';
const { t } = useI18n();
const { error: notifyError } = useMessage();
const filters = ref<IntegrationCallFilters>({});
const items = ref<IntegrationCallLogRow[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = 20;
const loading = ref(false);
const detail = ref<IntegrationCallDetail | null>(null);
async function load() {
loading.value = true;
try {
const data = await listIntegrationCalls({ ...filters.value, page: page.value, page_size: pageSize });
items.value = data.items;
total.value = data.total;
} catch (e) {
notifyError(e instanceof Error ? e.message : String(e));
} finally {
loading.value = false;
}
}
function resetFilters() {
filters.value = {};
page.value = 1;
void load();
}
async function openDetail(row: IntegrationCallLogRow) {
try {
detail.value = await getIntegrationCall(row.id);
} catch (e) {
notifyError(e instanceof Error ? e.message : String(e));
}
}
function copy(text: string): void {
void navigator.clipboard.writeText(text);
notifySuccess(t('admin.integrationConnector.callLogs.copied'));
}
const { success: notifySuccess } = useMessage();
function replayCommand(): string {
const wire = detail.value?.call.wire_json;
if (!wire) return '';
return wire.kind === 'database' ? buildSqlReplay(wire) : buildCurl(wire);
}
onMounted(load);
</script>
```
模板区按框线图实现:筛选条(input/select 绑 `filters` 各键,连接类型/状态下拉为固定枚举值)+ 表格 + 分页 + `<transition>` 抽屉(`v-if="detail"`,stepper 用 `detail.timeline` 渲染,双栏 `<pre>` 展示 `wire_json` 与 `request/response_summary_json`,复制按钮调 `copy()`/`replayCommand()`)。
- [ ] **Step 3: 面板测试**
`IntegrationCallLogsPanel.spec.ts`:mock `../api/integration-connector.api`(`listIntegrationCalls` 返回 2 行、`getIntegrationCall` 返回含 wire_json 的详情),断言:挂载即拉列表;填 interface_code 点查询→带参调用;点行→抽屉出现且呈现 wire 文本;soap wire 时出现「复制 curl」。用例如 4 个。
- [ ] **Step 4: 跑面板与复现命令测试**
```bash
npx vitest run src/features/admin/modules/integration-connector
```
Expected: PASS。
---
### Task 8: 页面挂 tab + i18n 四语言
**Files:**
- Modify: `frontend/src/features/admin/modules/integration-connector/IntegrationConnectorPage.vue`(TabKey/tabs/模板分支)
- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/admin.json`
- [ ] **Step 1: 页面挂 tab**
`TabKey` 增 `'calls'`;`tabs` 数组追加 `{ key: 'calls', labelKey: 'admin.integrationConnector.tabs.calls' }`;模板区按既有 tab 分支模式追加:
```vue
<IntegrationCallLogsPanel v-else-if="activeTab === 'calls'" />
```
(import 该组件;capability 只读 tab 的分支模式即参照。)
- [ ] **Step 2: i18n 四语言**(admin.json `integrationConnector` 命名空间内)
zh-CN(zh-TW/en/th 同键异文;en 关键词:Call logs / Interface / Client / Connector type / Status / Operation ID / Trace ID / Keyword in request / Time from / Time to / Query / Reset / Time / Capability / Step / Elapsed / Copy / Close / No wire details (historical record)):
```json
"tabs": { "calls": "调用日志" },
"callLogs": {
"title": "调用记录",
"filterInterface": "接口编码",
"filterClient": "客户端编码",
"filterConnector": "连接类型",
"filterStatus": "状态",
"filterOperationId": "operation_id",
"filterTraceId": "trace_id",
"filterKeyword": "参数关键字(模糊搜请求内容)",
"dateFrom": "执行时间起",
"dateTo": "执行时间止",
"query": "查询",
"reset": "重置",
"colTime": "时间",
"colCapability": "能力",
"colInterface": "接口",
"colStep": "步骤",
"colStatus": "状态",
"colElapsed": "耗时",
"detailTitle": "调用详情",
"timeline": "步骤时间线",
"request": "请求",
"response": "响应",
"wire": "线级请求(wire)",
"rawPayload": "原始报文",
"normalized": "业务参数(归一化)",
"copyBody": "复制 body",
"copyCurl": "复制 curl",
"copySql": "复制 SQL",
"copyRaw": "复制原始报文",
"copyJson": "复制 JSON",
"copyOperationId": "复制 operation_id",
"copied": "已复制",
"noWire": "无线级详情(历史记录)",
"sqlWriteWarning": "⚠ 写入语句:请确认目标环境后再执行"
}
```
(th 文案可参照既有 admin.json 泰语条目风格直译。)
- [ ] **Step 3: 验证**
```bash
npm run build && npx vitest run src/features/admin
```
Expected: 类型检查 + build 通过;admin 相关 spec 全绿(IntegrationConnectorPage.spec 若断言 tab 数量需同步 +1)。
---
### Task 9: 全量回归
- [ ] **Step 1: 后端**
```bash
./.venv/Scripts/python.exe -m pytest tests/services/integration_connector tests/api/test_integration_connector_api.py -q
```
- [ ] **Step 2: 前端**
```bash
npm run build && npx vitest run src/features/admin
```
Expected: 全绿。人工验收:起本地栈 → 管理端「集成连接器 → 调用日志」→ 触发一次在途调拨重试 → 刷新列表可见新调用 → 打开 step1 详情 → 验证原始 XML/curl/单号等要素齐全。
---
## Self-Review
- **Spec coverage**:wire 捕获(Task 2/3)→ 落库(Task 1/4)→ API(Task 5)→ 前台(Task 6/7/8)→ 回归(Task 9)全覆盖;用户要求四项(前台查看/原始调用内容+SQL/返回报文+执行结果/外部工具复现)分别由 Task 7 抽屉、Task 2/3 wire、Task 3 response_body、Task 7 复现命令满足。
- **Placeholder 扫描**:无 TBD;迁移 down_revision 以 `flask db heads` 实测值为准(显式动作步骤,非占位)。
- **类型一致性**:`IntegrationCallWire`/`IntegrationCallDetail`/`IntegrationCallFilters`(Task 6)与 Task 7 面板、Task 5 API 返回键一致。