feat(integration-connector): 绑定参数映射与凭据 DB 加密落库模式

- 绑定新增 param_mapping_json:域参数→接口参数声明式映射(map_response 规范),空对象同名直通
- 凭据引用新增 db 维护模式:secret_ciphertext Fernet 加密落库,主密钥 INTEGRATION_CREDENTIAL_KEY 仅环境注入,与 env 引用模式并存
- 新增 credential_types 凭据形态注册表:代码注册各类型字段清单,UI 动态渲染与 API 组装校验的唯一事实来源
- 移除绑定 context_source_code 独立列,路由条件统一 context_selector_json
- 管理端表单 Modal 重构为 Drawer,新增 JSON 编辑字段组件与页面级测试
- 迁移 rd1/re1 重挂当前唯一 head dd22ee33ff44,维持单 head 链
- settings 移除 IN_TRANSIT_TRANSFER_ERP_* 配置,外部端点/凭据移交连接器客户端实例管理
This commit is contained in:
hugo committed 2026-09-23 00:44:56 +08:00
1 parent 5df204fdea
commit 31591e663e
35 files changed
+4345 -750

No files matched your search

+369 -67
View File
@@ -1,21 +1,30 @@
"""api/integration_connector.py """api/integration_connector.py
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。 用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway。 依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway、credential_crypto。
逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key}, 逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key},
拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。 拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。
接口定义的连接器类型由所属客户端实例服务端推导(单一事实源);接口定义与绑定的
状态只经 /publish /unpublish /retire /reopen 动作端点按 CONFIG_STATUS_TRANSITIONS
转移(绑定发布附加就绪门禁:接口须已发布且客户端启用);绑定创建/更新做客户端
与接口成对校验(接口定义必须属于所选客户端实例,错配即 400)。
凭据引用状态为两态开关:PUT 仅允许 active/retired(rotating 不可进入,存量可置回
active 恢复);接口定义 enabled 冻结忽略传值(可用性只由 status 表达)。
凭据引用 db 模式在服务端加密用户名/密码落库,接口响应永不回显明文/密文。
注意:url_prefix 在 api/__init__.py 注册为 /api/integration-connector(区别于既有 注意:url_prefix 在 api/__init__.py 注册为 /api/integration-connector(区别于既有
/api/integration Dify 文件代理)。 /api/integration Dify 文件代理)。
""" """
from __future__ import annotations from __future__ import annotations
import json
import uuid import uuid
from flask import Blueprint, request from flask import Blueprint, request
from app.core.credential_crypto import CredentialCryptoErrorCodes, decrypt_secret, encrypt_secret
from app.core.decorators import require_admin from app.core.decorators import require_admin
from app.core.errors import NotFoundError, ValidationError from app.core.errors import AppError, NotFoundError, ValidationError
from app.core.response import ok from app.core.response import ok
from app.models import ( from app.models import (
IntegrationBinding, IntegrationBinding,
@@ -23,14 +32,36 @@ from app.models import (
IntegrationCredentialReference, IntegrationCredentialReference,
IntegrationInterfaceDefinition, IntegrationInterfaceDefinition,
) )
from app.services.integration_connector.capability import ensure_capabilities_loaded, list_capabilities from app.services.integration_connector.capability import list_capabilities
from app.services.integration_connector.credential_types import (
build_secret_dict,
get_credential_type,
list_credential_types,
visible_fields,
)
from app.services.integration_connector.gateway import get_capability_gateway from app.services.integration_connector.gateway import get_capability_gateway
from app.services.integration_connector.transports.base import IntegrationCallResult from app.services.integration_connector.security import CREDENTIAL_KEY_CONFIG_NAME, _DB_SECRET_CODES
from app.services.integration_connector.transports.base import IntegrationCallResult, merge_client_config
integration_connector_bp = Blueprint('integration_connector', __name__) integration_connector_bp = Blueprint('integration_connector', __name__)
VALID_CONNECTOR_TYPES = ('rest', 'soap') VALID_CONNECTOR_TYPES = ('rest', 'soap')
VALID_STATUSES = ('draft', 'published', 'retired') VALID_STATUSES = ('draft', 'published', 'retired')
VALID_SECRET_PROVIDERS = ('db', 'env')
# 凭据两态化(UI 可达状态):resolve_credential 只解析 active(fail-closed),「轮换中」
# 现语义等于断供且真实版本化轮换未实现(属 P2),故 PUT 只允许在 active/retired 间切换,
# rotating 不再可进入;存量 rotating 数据保留只读展示,经 PUT 置 active 即恢复。
VALID_CREDENTIAL_UI_STATUSES = ('active', 'retired')
# 配置实体生命周期转移表(接口定义与绑定共用):动作 → (源状态, 目标状态)。状态不再
# 由 PUT 直接改写,只能经动作端点按此表转移(draft→published 发布;published→draft 撤回;
# published→retired 退役;retired→draft 恢复为草稿,作为无版本化阶段的保险阀)。
CONFIG_STATUS_TRANSITIONS = {
'publish': ('draft', 'published'),
'unpublish': ('published', 'draft'),
'retire': ('published', 'retired'),
'reopen': ('retired', 'draft'),
}
def _require(value, field: str) -> None: def _require(value, field: str) -> None:
@@ -39,6 +70,70 @@ def _require(value, field: str) -> None:
raise ValidationError(f'{field} is required', details={'field': field}) raise ValidationError(f'{field} is required', details={'field': field})
def _require_client(code: str) -> IntegrationClientInstance:
"""按编码取客户端实例;不存在即 400(接口定义的连接器类型以其为单一事实源)。"""
client = IntegrationClientInstance.query.filter_by(code=code).first()
if client is None:
raise ValidationError(
'client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND',
details={'client_instance_code': code},
)
return client
def _apply_status_transition(entity, action: str, *, kind: str) -> None:
"""按转移表校验并落库状态;非法动作或源状态不符即 400。"""
transition = CONFIG_STATUS_TRANSITIONS.get(action)
if transition is None:
raise ValidationError(
'unknown lifecycle action', details={'allowed': sorted(CONFIG_STATUS_TRANSITIONS)})
src, dst = transition
if entity.status != src:
raise ValidationError(
f'{kind} status is {entity.status}, cannot {action}',
code='INTEGRATION.ILLEGAL_STATUS_TRANSITION',
details={'action': action, 'from': entity.status, 'to': dst},
)
entity.status = dst
def _require_interface(code: str) -> IntegrationInterfaceDefinition:
"""按编码取接口定义;不存在即 400(绑定成对校验以其所属客户端为准,而非依赖外键报 500)。"""
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
if iface is None:
raise ValidationError(
'interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND',
details={'interface_definition_code': code},
)
return iface
def _validate_binding_pair(client_code, interface_code) -> tuple[IntegrationClientInstance, IntegrationInterfaceDefinition]:
"""绑定成对校验:接口定义必须属于所选客户端实例(接口归属即客户端归属)。
错配组合会产生「拿 A 客户端的地址/凭据发 B 接口报文」的调用,创建/更新时直接
400(fail-fast),不留给调用期 fail-closed。
"""
client = _require_client(str(client_code).strip())
iface = _require_interface(str(interface_code).strip())
if iface.client_instance_code != client.code:
raise ValidationError(
'interface definition does not belong to the selected client instance',
code='INTEGRATION.BINDING_PAIR_MISMATCH',
details={
'client_instance_code': client.code,
'interface_definition_code': iface.code,
'interface_client_instance_code': iface.client_instance_code,
},
)
return client, iface
def _interface_transition(iface, action: str) -> None:
"""按转移表校验并落库接口定义状态;非法动作或源状态不符即 400。"""
_apply_status_transition(iface, action, kind='interface')
def _serialize_client(client) -> dict: def _serialize_client(client) -> dict:
return { return {
'id': client.id, 'code': client.code, 'name': client.name, 'id': client.id, 'code': client.code, 'name': client.name,
@@ -64,7 +159,7 @@ def _serialize_binding(binding) -> dict:
return { return {
'id': binding.id, 'capability': binding.capability, 'id': binding.id, 'capability': binding.capability,
'context_selector_json': binding.context_selector_json or {}, 'context_selector_json': binding.context_selector_json or {},
'context_source_code': binding.context_source_code, 'param_mapping_json': binding.param_mapping_json or {},
'client_instance_code': binding.client_instance_code, 'client_instance_code': binding.client_instance_code,
'interface_definition_code': binding.interface_definition_code, 'interface_definition_code': binding.interface_definition_code,
'mapping_version': binding.mapping_version, 'priority': binding.priority, 'mapping_version': binding.mapping_version, 'priority': binding.priority,
@@ -73,15 +168,59 @@ def _serialize_binding(binding) -> dict:
} }
def _decrypted_secret(cred) -> dict:
"""db 模式下解密凭据字典;密文缺失或主密钥异常时返回空 dict(fail-closed 不炸列表)。"""
if cred.secret_provider != 'db' or not cred.secret_ciphertext:
return {}
try:
raw = decrypt_secret(
cred.secret_ciphertext,
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
codes=_DB_SECRET_CODES,
)
parsed = json.loads(raw)
return parsed if isinstance(parsed, dict) else {}
except AppError:
return {}
def _serialize_credential(cred) -> dict: def _serialize_credential(cred) -> dict:
secret_dict = _decrypted_secret(cred)
return { return {
'id': cred.id, 'code': cred.code, 'secret_ref': cred.secret_ref, 'id': cred.id, 'code': cred.code, 'secret_ref': cred.secret_ref,
'secret_provider': cred.secret_provider, 'credential_type': cred.credential_type, 'secret_provider': cred.secret_provider, 'credential_type': cred.credential_type,
# 非密字段按类型定义回显(如 username);密文字段与密文本身永不回显。
'secret_fields': visible_fields(cred.credential_type, secret_dict),
'has_secret': bool(cred.secret_ciphertext),
'version': cred.version, 'status': cred.status, 'version': cred.version, 'status': cred.status,
'updated_at': cred.updated_at.isoformat() if cred.updated_at else None,
'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None, 'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None,
} }
def _apply_db_secret(cred, body) -> None:
"""db 模式:按凭据类型定义组装字段并加密落库;只改部分字段可沿用解密出的旧值。
类型必须在凭据类型注册表内(fail-closed);合并旧值后必填字段仍缺失即拒绝。
"""
ctype = str(body.get('credential_type') or cred.credential_type or 'password').strip()
if get_credential_type(ctype) is None:
raise ValidationError('unknown credential_type', details={'credential_type': ctype})
cred.credential_type = ctype
current = _decrypted_secret(cred) if cred.secret_ciphertext else {}
values: dict = dict(current)
for key in (field['key'] for field in get_credential_type(ctype)['fields']):
incoming = body.get(key)
if incoming is not None and str(incoming) != '':
values[key] = str(incoming)
merged = build_secret_dict(ctype, values)
cred.secret_ciphertext = encrypt_secret(
json.dumps(merged, ensure_ascii=False),
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
codes=_DB_SECRET_CODES,
)
def _result_to_dict(result: IntegrationCallResult) -> dict: def _result_to_dict(result: IntegrationCallResult) -> dict:
return { return {
'status': result.status, 'status': result.status,
@@ -98,7 +237,6 @@ def _result_to_dict(result: IntegrationCallResult) -> dict:
@integration_connector_bp.route('/capabilities', methods=['GET']) @integration_connector_bp.route('/capabilities', methods=['GET'])
@require_admin @require_admin
def list_capabilities_endpoint(): def list_capabilities_endpoint():
ensure_capabilities_loaded()
data = [{ data = [{
'name': spec.name, 'write': spec.write, 'idempotency': spec.idempotency, 'name': spec.name, 'write': spec.write, 'idempotency': spec.idempotency,
'input_schema': spec.input_schema, 'output_schema': spec.output_schema, 'input_schema': spec.input_schema, 'output_schema': spec.output_schema,
@@ -231,15 +369,15 @@ def create_interface_definition():
code = str(body.get('code') or '').strip() code = str(body.get('code') or '').strip()
_require(code, 'code') _require(code, 'code')
_require(body.get('client_instance_code'), 'client_instance_code') _require(body.get('client_instance_code'), 'client_instance_code')
connector_type = str(body.get('connector_type') or '') # 连接器类型以所选客户端实例为单一事实源(服务端推导落库,忽略请求体传值,
if connector_type not in VALID_CONNECTOR_TYPES: # 杜绝接口与客户端类型不一致);客户端不存在即 400,而非依赖外键报 500。
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)}) client = _require_client(str(body['client_instance_code']).strip())
status = str(body.get('status') or 'draft') status = str(body.get('status') or 'draft')
if status not in VALID_STATUSES: if status not in VALID_STATUSES:
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)}) raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
iface = IntegrationInterfaceDefinition( iface = IntegrationInterfaceDefinition(
code=code, name=str(body.get('name') or code).strip(), code=code, name=str(body.get('name') or code).strip(),
client_instance_code=body['client_instance_code'], connector_type=connector_type, client_instance_code=client.code, connector_type=client.connector_type,
http_method=(str(body.get('http_method') or '').strip().upper() or None), http_method=(str(body.get('http_method') or '').strip().upper() or None),
request_path=(str(body.get('request_path') or '').strip() or None), request_path=(str(body.get('request_path') or '').strip() or None),
request_spec_json=body.get('request_spec_json') or {}, request_spec_json=body.get('request_spec_json') or {},
@@ -247,7 +385,9 @@ def create_interface_definition():
response_mapping_json=body.get('response_mapping_json') or {}, response_mapping_json=body.get('response_mapping_json') or {},
output_schema_json=body.get('output_schema_json') or {}, output_schema_json=body.get('output_schema_json') or {},
version=int(body.get('version') or 1), status=status, version=int(body.get('version') or 1), status=status,
enabled=bool(body.get('enabled', True)), # enabled 冻结:与 status 重复表达可用性且运行时不消费(假开关),请求体传值忽略;
# 可用性只由 status 生命周期表达,列待 P2 版本化迁移时清理。
enabled=True,
) )
from app import db from app import db
db.session.add(iface) db.session.add(iface)
@@ -258,7 +398,11 @@ def create_interface_definition():
@integration_connector_bp.route('/interface-definitions/<code>', methods=['PUT']) @integration_connector_bp.route('/interface-definitions/<code>', methods=['PUT'])
@require_admin @require_admin
def update_interface_definition(code): def update_interface_definition(code):
"""更新接口定义(code 不变;可改模板/入参/回传/出参 Schema、状态、启停)。""" """更新接口定义(code 不变;可改模板/入参/回传/出参 Schema 与所属客户端)。
状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转);
连接器类型由所属客户端实例服务端推导,请求体传值被忽略。
"""
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first() iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
if iface is None: if iface is None:
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND') raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
@@ -268,12 +412,9 @@ def update_interface_definition(code):
iface.name = str(body['name']).strip() iface.name = str(body['name']).strip()
if body.get('client_instance_code') is not None: if body.get('client_instance_code') is not None:
_require(body.get('client_instance_code'), 'client_instance_code') _require(body.get('client_instance_code'), 'client_instance_code')
iface.client_instance_code = body['client_instance_code'] client = _require_client(str(body['client_instance_code']).strip())
if body.get('connector_type') is not None: iface.client_instance_code = client.code
connector_type = str(body['connector_type']) iface.connector_type = client.connector_type
if connector_type not in VALID_CONNECTOR_TYPES:
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
iface.connector_type = connector_type
if 'http_method' in body: if 'http_method' in body:
iface.http_method = str(body.get('http_method') or '').strip().upper() or None iface.http_method = str(body.get('http_method') or '').strip().upper() or None
if 'request_path' in body: if 'request_path' in body:
@@ -283,18 +424,52 @@ def update_interface_definition(code):
setattr(iface, json_field, body.get(json_field) or {}) setattr(iface, json_field, body.get(json_field) or {})
if body.get('version') is not None: if body.get('version') is not None:
iface.version = int(body.get('version') or 1) iface.version = int(body.get('version') or 1)
if body.get('status') is not None:
status = str(body['status'])
if status not in VALID_STATUSES:
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
iface.status = status
if 'enabled' in body:
iface.enabled = bool(body.get('enabled', True))
from app import db from app import db
db.session.commit() db.session.commit()
return ok(_serialize_interface(iface)) return ok(_serialize_interface(iface))
# ---- 接口定义生命周期(状态只经动作端点按转移表流转) ----
def _do_interface_lifecycle(code: str, action: str):
"""动作端点共用体:取接口 → 按转移表转移 → 落库并回显。"""
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
if iface is None:
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
_interface_transition(iface, action)
from app import db
db.session.commit()
return ok(_serialize_interface(iface))
@integration_connector_bp.route('/interface-definitions/<code>/publish', methods=['POST'])
@require_admin
def publish_interface_definition(code):
"""发布接口定义(draft → published):发布后才会被绑定解析选中。"""
return _do_interface_lifecycle(code, 'publish')
@integration_connector_bp.route('/interface-definitions/<code>/unpublish', methods=['POST'])
@require_admin
def unpublish_interface_definition(code):
"""撤回发布(published → draft):临时下线,修正后可重新发布。"""
return _do_interface_lifecycle(code, 'unpublish')
@integration_connector_bp.route('/interface-definitions/<code>/retire', methods=['POST'])
@require_admin
def retire_interface_definition(code):
"""退役(published → retired):该接口引用的所有绑定同时失效。"""
return _do_interface_lifecycle(code, 'retire')
@integration_connector_bp.route('/interface-definitions/<code>/reopen', methods=['POST'])
@require_admin
def reopen_interface_definition(code):
"""恢复为草稿(retired → draft):版本化发布上线前的保险阀,重新走发布流程。"""
return _do_interface_lifecycle(code, 'reopen')
# ---- Binding ---- # ---- Binding ----
@integration_connector_bp.route('/bindings', methods=['GET']) @integration_connector_bp.route('/bindings', methods=['GET'])
@@ -307,23 +482,22 @@ def list_bindings():
@integration_connector_bp.route('/bindings', methods=['POST']) @integration_connector_bp.route('/bindings', methods=['POST'])
@require_admin @require_admin
def create_binding(): def create_binding():
"""创建绑定:成对校验客户端与接口后落库;新建固定落 draft,发布走 /publish 动作端点。"""
body = request.get_json(silent=True) or {} body = request.get_json(silent=True) or {}
_require(body.get('capability'), 'capability') _require(body.get('capability'), 'capability')
_require(body.get('client_instance_code'), 'client_instance_code') _require(body.get('client_instance_code'), 'client_instance_code')
_require(body.get('interface_definition_code'), 'interface_definition_code') _require(body.get('interface_definition_code'), 'interface_definition_code')
status = str(body.get('status') or 'draft') client, iface = _validate_binding_pair(body['client_instance_code'], body['interface_definition_code'])
if status not in VALID_STATUSES:
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
binding = IntegrationBinding( binding = IntegrationBinding(
capability=body['capability'], capability=body['capability'],
context_selector_json=body.get('context_selector_json') or {}, context_selector_json=body.get('context_selector_json') or {},
context_source_code=(str(body.get('context_source_code') or '').strip() or None), param_mapping_json=body.get('param_mapping_json') or {},
client_instance_code=body['client_instance_code'], client_instance_code=client.code,
interface_definition_code=body['interface_definition_code'], interface_definition_code=iface.code,
mapping_version=int(body.get('mapping_version') or 1), mapping_version=int(body.get('mapping_version') or 1),
priority=int(body.get('priority') or 0), priority=int(body.get('priority') or 0),
environment=str(body.get('environment') or 'prod').strip(), environment=str(body.get('environment') or 'prod').strip(),
status=status, status='draft',
) )
from app import db from app import db
db.session.add(binding) db.session.add(binding)
@@ -334,7 +508,11 @@ def create_binding():
@integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT']) @integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT'])
@require_admin @require_admin
def update_binding(binding_id): def update_binding(binding_id):
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间、状态)。""" """更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间)。
状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转);
客户端与接口成对校验:以变更后的最终组合为准,接口定义不属于该客户端即 400。
"""
from app import db from app import db
binding = db.session.get(IntegrationBinding, binding_id) binding = db.session.get(IntegrationBinding, binding_id)
if binding is None: if binding is None:
@@ -345,14 +523,23 @@ def update_binding(binding_id):
binding.capability = body['capability'] binding.capability = body['capability']
if 'context_selector_json' in body: if 'context_selector_json' in body:
binding.context_selector_json = body.get('context_selector_json') or {} binding.context_selector_json = body.get('context_selector_json') or {}
if 'context_source_code' in body: if 'param_mapping_json' in body:
binding.context_source_code = str(body.get('context_source_code') or '').strip() or None binding.param_mapping_json = body.get('param_mapping_json') or {}
if body.get('client_instance_code') is not None: new_client_code = body.get('client_instance_code')
_require(body.get('client_instance_code'), 'client_instance_code') new_iface_code = body.get('interface_definition_code')
binding.client_instance_code = body['client_instance_code'] if new_client_code is not None:
if body.get('interface_definition_code') is not None: _require(new_client_code, 'client_instance_code')
_require(body.get('interface_definition_code'), 'interface_definition_code') if new_iface_code is not None:
binding.interface_definition_code = body['interface_definition_code'] _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 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 body.get('mapping_version') is not None: if body.get('mapping_version') is not None:
binding.mapping_version = int(body.get('mapping_version') or 1) binding.mapping_version = int(body.get('mapping_version') or 1)
if body.get('priority') is not None: if body.get('priority') is not None:
@@ -363,16 +550,69 @@ def update_binding(binding_id):
binding.effective_from = body['effective_from'] or None binding.effective_from = body['effective_from'] or None
if body.get('effective_to') is not None: if body.get('effective_to') is not None:
binding.effective_to = body['effective_to'] or None binding.effective_to = body['effective_to'] or None
if body.get('status') is not None:
status = str(body['status'])
if status not in VALID_STATUSES:
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
binding.status = status
from app import db from app import db
db.session.commit() db.session.commit()
return ok(_serialize_binding(binding)) return ok(_serialize_binding(binding))
# ---- 绑定生命周期(状态只经动作端点按转移表流转) ----
def _do_binding_lifecycle(binding_id: int, action: str):
"""动作端点共用体:取绑定 → 按转移表转移 → 落库并回显。
发布(publish)附加就绪门禁:引用的接口定义须已发布、客户端实例须启用,
否则 400——避免出现列表「已发布」但调用期永远 fail-closed 的死绑定
(与 binding.resolve_binding 的调用期门禁同一语义)。
"""
from app import db
binding = db.session.get(IntegrationBinding, binding_id)
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:
raise ValidationError(
'binding target not ready: interface must be published and client instance enabled',
code='INTEGRATION.BINDING_TARGET_NOT_READY',
details={
'client_instance_code': binding.client_instance_code,
'interface_definition_code': binding.interface_definition_code,
},
)
_apply_status_transition(binding, action, kind='binding')
db.session.commit()
return ok(_serialize_binding(binding))
@integration_connector_bp.route('/bindings/<int:binding_id>/publish', methods=['POST'])
@require_admin
def publish_binding(binding_id):
"""发布绑定(draft → published):发布后才会被绑定解析选中。"""
return _do_binding_lifecycle(binding_id, 'publish')
@integration_connector_bp.route('/bindings/<int:binding_id>/unpublish', methods=['POST'])
@require_admin
def unpublish_binding(binding_id):
"""撤回发布(published → draft):临时下线,修正后可重新发布。"""
return _do_binding_lifecycle(binding_id, 'unpublish')
@integration_connector_bp.route('/bindings/<int:binding_id>/retire', methods=['POST'])
@require_admin
def retire_binding(binding_id):
"""退役(published → retired):绑定退出自动调用。"""
return _do_binding_lifecycle(binding_id, 'retire')
@integration_connector_bp.route('/bindings/<int:binding_id>/reopen', methods=['POST'])
@require_admin
def reopen_binding(binding_id):
"""恢复为草稿(retired → draft):重新走发布流程。"""
return _do_binding_lifecycle(binding_id, 'reopen')
# ---- 凭据引用 ---- # ---- 凭据引用 ----
@integration_connector_bp.route('/credential-references', methods=['GET']) @integration_connector_bp.route('/credential-references', methods=['GET'])
@@ -385,41 +625,87 @@ def list_credential_references():
@integration_connector_bp.route('/credential-references', methods=['POST']) @integration_connector_bp.route('/credential-references', methods=['POST'])
@require_admin @require_admin
def create_credential_reference(): def create_credential_reference():
"""创建凭据引用:db 模式(默认)按凭据类型加密字段落库;env 模式只存配置键名。"""
body = request.get_json(silent=True) or {} body = request.get_json(silent=True) or {}
_require(body.get('code'), 'code') _require(body.get('code'), 'code')
_require(body.get('secret_ref'), 'secret_ref') # 缺省保持 env(兼容既有直连 API 调用);管理端 db 模式显式传 secret_provider='db'。
from app import db provider = str(body.get('secret_provider') or 'env').strip()
if provider not in VALID_SECRET_PROVIDERS:
raise ValidationError('invalid secret_provider', details={'allowed': list(VALID_SECRET_PROVIDERS)})
code = str(body['code']).strip()
if IntegrationCredentialReference.query.filter_by(code=code).first():
raise ValidationError('credential reference code already exists', code='RESOURCE.CONFLICT')
status = str(body.get('status') or 'active')
if status not in ('active', 'rotating', 'retired'):
raise ValidationError('invalid credential status', details={'allowed': ['active', 'rotating', 'retired']})
cred = IntegrationCredentialReference( cred = IntegrationCredentialReference(
code=str(body['code']).strip(), code=code,
secret_ref=str(body['secret_ref']).strip(), secret_ref=str(body.get('secret_ref') or '').strip(),
secret_provider=str(body.get('secret_provider') or 'env').strip(), secret_provider=provider,
credential_type=str(body.get('credential_type') or 'password').strip(), credential_type=str(body.get('credential_type') or 'password').strip(),
version=int(body.get('version') or 1), version=int(body.get('version') or 1),
status=str(body.get('status') or 'active'), status=status,
) )
if provider == 'db':
_apply_db_secret(cred, body)
cred.secret_ref = f'db:{code}'
else:
_require(cred.secret_ref, 'secret_ref')
from app import db
db.session.add(cred) db.session.add(cred)
db.session.commit() db.session.commit()
# 永不回显真实凭据值;只回元数据。 # 永不回显真实凭据值;只回元数据与非密字段。
return ok(_serialize_credential(cred), status=201) return ok(_serialize_credential(cred), status=201)
@integration_connector_bp.route('/credential-references/types', methods=['GET'])
@require_admin
def list_credential_type_specs():
"""凭据类型注册表清单(类型 + 字段定义),供管理端动态渲染表单与占位符提示。"""
return ok(list_credential_types())
@integration_connector_bp.route('/credential-references/<code>', methods=['PUT']) @integration_connector_bp.route('/credential-references/<code>', methods=['PUT'])
@require_admin @require_admin
def update_credential_reference(code): def update_credential_reference(code):
"""更新凭据引用(code 不变;可改 secret_ref/provider/type/status)。只存引用,永不回显明文。""" """更新凭据引用(code 不变);db 模式可只改部分字段(其余沿用旧值),永不回显明文。"""
cred = IntegrationCredentialReference.query.filter_by(code=code).first() cred = IntegrationCredentialReference.query.filter_by(code=code).first()
if cred is None: if cred is None:
raise NotFoundError('credential reference not found', code='INTEGRATION.CREDENTIAL_NOT_FOUND') raise NotFoundError('credential reference not found', code='INTEGRATION.CREDENTIAL_NOT_FOUND')
body = request.get_json(silent=True) or {} body = request.get_json(silent=True) or {}
if body.get('secret_ref') is not None:
_require(body.get('secret_ref'), 'secret_ref')
cred.secret_ref = str(body['secret_ref']).strip()
if body.get('secret_provider') is not None: if body.get('secret_provider') is not None:
cred.secret_provider = str(body['secret_provider']).strip() provider = str(body['secret_provider']).strip()
if body.get('credential_type') is not None: if provider not in VALID_SECRET_PROVIDERS:
cred.credential_type = str(body['credential_type']).strip() raise ValidationError('invalid secret_provider', details={'allowed': list(VALID_SECRET_PROVIDERS)})
cred.secret_provider = provider
if provider == 'env':
# 切回 env 模式时清掉遗留密文,避免失效凭据残留库中。
cred.secret_ciphertext = None
field_keys = tuple(
field['key'] for field in (get_credential_type(
str(body.get('credential_type') or cred.credential_type or 'password')) or {'fields': []}
)['fields']
)
has_secret_input = any(body.get(key) is not None for key in field_keys)
if cred.secret_provider == 'db':
if has_secret_input or body.get('credential_type') is not None or not cred.secret_ciphertext:
_apply_db_secret(cred, body)
cred.secret_ref = f'db:{cred.code}'
else:
if body.get('secret_ref') is not None:
_require(body.get('secret_ref'), 'secret_ref')
cred.secret_ref = str(body['secret_ref']).strip()
if has_secret_input:
raise ValidationError('credential fields only apply to db credentials')
if body.get('status') is not None: if body.get('status') is not None:
cred.status = str(body['status']).strip() # 状态改写冻结为两态开关:仅允许 active/retired(管理端行内开关即走此通道);
# rotating 不可进入——其现语义等于断供(resolve_credential 只解析 active),
# 真实版本化轮换属 P2;存量 rotating 数据经置 active 即恢复。
status = str(body['status']).strip()
if status not in VALID_CREDENTIAL_UI_STATUSES:
raise ValidationError(
'invalid credential status', details={'allowed': list(VALID_CREDENTIAL_UI_STATUSES)})
cred.status = status
from app import db from app import db
db.session.commit() db.session.commit()
return ok(_serialize_credential(cred)) return ok(_serialize_credential(cred))
@@ -430,6 +716,11 @@ def update_credential_reference(code):
@integration_connector_bp.route('/client-instances/<code>/test', methods=['POST']) @integration_connector_bp.route('/client-instances/<code>/test', methods=['POST'])
@require_admin @require_admin
def test_connection(code): def test_connection(code):
"""连接测试探针:只证明网络/服务可达(设计文档:连接测试不做业务调用)。
配置兼容层与 binding.resolve_binding 同源:endpoint/timeout_seconds 独立列
拼回 config_json 后再交给 transport,否则存独立列的地址会被误判为未冻结。
"""
client = IntegrationClientInstance.query.filter_by(code=code).first() client = IntegrationClientInstance.query.filter_by(code=code).first()
if client is None: if client is None:
raise NotFoundError('client instance not found') raise NotFoundError('client instance not found')
@@ -439,9 +730,20 @@ def test_connection(code):
raise ValidationError( raise ValidationError(
'no transport available for client', code='INTEGRATION.TRANSPORT_NOT_FROZEN', 'no transport available for client', code='INTEGRATION.TRANSPORT_NOT_FROZEN',
) )
raw = transport.call( client_payload = {
client={'config_json': client.config_json or {}, 'credential': {}}, 'config_json': merge_client_config({
interface={'request_spec_json': {}}, 'config_json': client.config_json or {},
request={}, 'endpoint': client.endpoint,
) 'timeout_seconds': client.timeout_seconds,
return ok({'ok': True, 'status': raw.get('status') or 'success', 'result': raw}) }),
'credential': {},
}
probe = getattr(transport, 'probe', None)
if probe is not None:
raw = probe(client=client_payload)
ok_flag = bool(raw.get('ok'))
else:
# 测试替身等未实现 probe 的传输:回退 call(空 interface 规格)。
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})
+3 -14
View File
@@ -255,6 +255,8 @@ class Config:
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower() INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE') INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY') INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
# 集成连接器凭据密文的 Fernet 主密钥;只允许由环境变量提供,禁止持久化到数据库。
INTEGRATION_CREDENTIAL_KEY = os.getenv('INTEGRATION_CREDENTIAL_KEY')
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 服务端调用;无尾斜杠,常为内网 IP) # HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 服务端调用;无尾斜杠,常为内网 IP)
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE') HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
@@ -282,27 +284,14 @@ class Config:
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower() SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2')) SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
SHIPPING_NOTICE_WORKER_CONCURRENCY = int(os.getenv('SHIPPING_NOTICE_WORKER_CONCURRENCY', '2')) SHIPPING_NOTICE_WORKER_CONCURRENCY = int(os.getenv('SHIPPING_NOTICE_WORKER_CONCURRENCY', '2'))
# 在途仓自动调拨(独立业务模块)参数;ERP 凭据仅由环境/Secret 注入,未配置时 fail-closed。 # 在途仓自动调拨(独立业务模块)参数;外部系统端点/凭据由集成连接器客户端实例管理。
IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY', '2')) IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY', '2'))
IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY', '2'))
IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY', '1'))
IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS = int(
os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS', '60') or '60'
)
IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS = int(
os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS', '60') or '60'
)
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = int( IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = int(
os.getenv('IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS', '600') or '600' os.getenv('IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS', '600') or '600'
) )
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS', '3') or '3') IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS', '3') or '3')
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5') IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5')
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7') IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7')
# ERP SOAP:WSDL/endpoint 冻结前保持空(SoapErpTransport fail-closed)。
IN_TRANSIT_TRANSFER_ERP_ENDPOINT = os.getenv('IN_TRANSIT_TRANSFER_ERP_ENDPOINT', '').strip()
IN_TRANSIT_TRANSFER_ERP_USERNAME = os.getenv('IN_TRANSIT_TRANSFER_ERP_USERNAME', '').strip()
IN_TRANSIT_TRANSFER_ERP_PASSWORD = os.getenv('IN_TRANSIT_TRANSFER_ERP_PASSWORD', '').strip()
IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG = os.getenv('IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG', '').strip()
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = os.getenv('IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET', 'hxops-transfer').strip() IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = os.getenv('IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET', 'hxops-transfer').strip()
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float( SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420') os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420')
+10 -3
View File
@@ -22,6 +22,7 @@ from sqlalchemy import (
Integer, Integer,
JSON, JSON,
String, String,
Text,
UniqueConstraint, UniqueConstraint,
text, text,
) )
@@ -41,7 +42,7 @@ CONTEXT_SELECTOR_JSON = JSON().with_variant(JSONB(), 'postgresql')
class IntegrationCredentialReference(Base): class IntegrationCredentialReference(Base):
"""凭据引用:只存 secret_ref 键 + 元数据,真实凭据由 Secret 服务注入,绝不落库明文。""" """凭据引用:真实凭据加密落库(db 模式)或引用环境注入键(env 模式),绝不落库明文。"""
__tablename__ = 'integration_credential_references' __tablename__ = 'integration_credential_references'
__table_args__ = ( __table_args__ = (
@@ -55,6 +56,9 @@ class IntegrationCredentialReference(Base):
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(64), nullable=False) code: Mapped[str] = mapped_column(String(64), nullable=False)
secret_ref: Mapped[str] = mapped_column(String(128), nullable=False) secret_ref: Mapped[str] = mapped_column(String(128), nullable=False)
# db 模式:凭据 JSON(如 {"username","password"})的 Fernet 密文;主密钥由
# INTEGRATION_CREDENTIAL_KEY 环境注入。env 模式为空。绝不回显、绝不写日志。
secret_ciphertext: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
secret_provider: Mapped[str] = mapped_column(String(32), nullable=False, default='env', server_default='env') secret_provider: Mapped[str] = mapped_column(String(32), nullable=False, default='env', server_default='env')
credential_type: Mapped[str] = mapped_column(String(32), nullable=False, default='password', server_default='password') credential_type: Mapped[str] = mapped_column(String(32), nullable=False, default='password', server_default='password')
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
@@ -159,9 +163,12 @@ class IntegrationBinding(Base):
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
capability: Mapped[str] = mapped_column(String(128), nullable=False) capability: Mapped[str] = mapped_column(String(128), nullable=False)
# 路由条件(来源/组织/租户等键值对;空对象 = 默认绑定):须为调用 context 的子集才命中。
context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict) context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
# 最常用的 context 匹配键独立列(JSON 保留作兜底)。 # 域参数 → 接口参数的声明式映射(map_response 规范:{接口参数: {expr/template/transform/args}});
context_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) # 空对象 = 域参数同名直通。结构属绑定(capability↔接口的翻译契约),不属接口定义。
# 与 context_selector_json 同用 JSONB variant(PostgreSQL)保持表内 JSON 列类型一致。
param_mapping_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
client_instance_code: Mapped[str] = mapped_column( client_instance_code: Mapped[str] = mapped_column(
ForeignKey('integration_client_instances.code'), nullable=False, ForeignKey('integration_client_instances.code'), nullable=False,
) )
@@ -4,16 +4,21 @@
(客户端 + 接口 + 映射版本),并冻结调用期配置快照。 (客户端 + 接口 + 映射版本),并冻结调用期配置快照。
依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、errors.py。 依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、errors.py。
逻辑:只命中 published + environment 匹配 + 生效区间 + context_selector 是 context 子集; 逻辑:只命中 published + environment 匹配 + 生效区间 + context_selector 是 context 子集;
且接口定义须为 published、客户端实例须 enabled(管理端「发布/退役」「启停」的总开关);
同 context 下 priority 高者优先;无命中抛 BindingNotFoundError(fail-closed)。 同 context 下 priority 高者优先;无命中抛 BindingNotFoundError(fail-closed)。
""" """
from __future__ import annotations from __future__ import annotations
import logging
from dataclasses import dataclass from dataclasses import dataclass
from datetime import datetime, timezone from datetime import datetime, timezone
from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition
from app.services.integration_connector.errors import BindingNotFoundError from app.services.integration_connector.errors import BindingNotFoundError
from app.services.integration_connector.transports.base import merge_client_config
logger = logging.getLogger(__name__)
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -32,6 +37,9 @@ class BindingSnapshot:
request_spec: dict request_spec: dict
response_mapping: dict response_mapping: dict
output_schema: dict output_schema: dict
# 域参数→接口参数映射(空 = 同名直通)与接口入参 Schema(映射结果校验)。
param_mapping: dict
input_schema: dict
def _to_naive(dt: datetime | None) -> datetime | None: def _to_naive(dt: datetime | None) -> datetime | None:
@@ -68,7 +76,8 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
Returns: Returns:
BindingSnapshot。 BindingSnapshot。
Raises: Raises:
BindingNotFoundError: 无可用绑定(fail-closed)。 BindingNotFoundError: 无可用绑定(fail-closed);接口未发布或客户端已停用同样按
无可用绑定处理(与列表「发布/退役」「启停」按钮语义闭环,且不向调用方泄露配置细节)。
""" """
base_now = now or datetime.utcnow() base_now = now or datetime.utcnow()
rows = IntegrationBinding.query.filter_by(capability=capability, environment=environment, status='published').all() rows = IntegrationBinding.query.filter_by(capability=capability, environment=environment, status='published').all()
@@ -81,6 +90,12 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
continue continue
candidates.append((row, selector)) candidates.append((row, selector))
if not candidates: if not candidates:
# fail-closed 必须可排障:区分「一条 published 都没有」与「有但路由选择器/生效窗口不命中」,
# 否则调用方只看到 no binding for capability(2026-09 排障实测痛点)。
logger.warning(
"connector binding miss: capability=%s env=%s published_rows=%s context_keys=%s",
capability, environment, len(rows), sorted((context or {}).keys()),
)
raise BindingNotFoundError(capability=capability) raise BindingNotFoundError(capability=capability)
candidates.sort(key=lambda item: (item[0].priority, len(item[1])), reverse=True) candidates.sort(key=lambda item: (item[0].priority, len(item[1])), reverse=True)
row, selector = candidates[0] row, selector = candidates[0]
@@ -88,15 +103,28 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
client = IntegrationClientInstance.query.filter_by(code=row.client_instance_code).first() client = IntegrationClientInstance.query.filter_by(code=row.client_instance_code).first()
iface = IntegrationInterfaceDefinition.query.filter_by(code=row.interface_definition_code).first() iface = IntegrationInterfaceDefinition.query.filter_by(code=row.interface_definition_code).first()
if client is None or iface is None: if client is None or iface is None:
logger.warning(
"connector binding target missing: capability=%s binding_id=%s client=%s iface=%s",
capability, row.id, row.client_instance_code, row.interface_definition_code,
)
raise BindingNotFoundError(capability=capability)
# fail-closed 门禁:接口未发布(draft/retired)或客户端已停用视同无可用绑定——
# 管理端「发布/退役」「启停」按钮因此具备真实的调用期语义;错误类型与无命中一致。
if iface.status != 'published' or not client.enabled:
logger.warning(
"connector binding gated: capability=%s binding_id=%s iface_status=%s client_enabled=%s",
capability, row.id, iface.status, client.enabled,
)
raise BindingNotFoundError(capability=capability) raise BindingNotFoundError(capability=capability)
# 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费。 # 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费
# (与 transports.base.merge_client_config 同一实现)。
# 优先列值,缺失回退 JSON(config_json / request_spec_json / context_selector_json)。 # 优先列值,缺失回退 JSON(config_json / request_spec_json / context_selector_json)。
config = dict(client.config_json or {}) config = merge_client_config({
if client.endpoint is not None: 'config_json': client.config_json,
config['endpoint'] = client.endpoint 'endpoint': client.endpoint,
if client.timeout_seconds is not None: 'timeout_seconds': client.timeout_seconds,
config['timeout_seconds'] = client.timeout_seconds })
request_spec = dict(iface.request_spec_json or {}) request_spec = dict(iface.request_spec_json or {})
if iface.http_method is not None: if iface.http_method is not None:
@@ -105,8 +133,6 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
request_spec['path'] = iface.request_path request_spec['path'] = iface.request_path
selector = dict(row.context_selector_json or {}) selector = dict(row.context_selector_json or {})
if row.context_source_code is not None and 'source_code' not in selector:
selector['source_code'] = row.context_source_code
return BindingSnapshot( return BindingSnapshot(
capability=row.capability, capability=row.capability,
@@ -121,4 +147,6 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
request_spec=request_spec, request_spec=request_spec,
response_mapping=iface.response_mapping_json or {}, response_mapping=iface.response_mapping_json or {},
output_schema=iface.output_schema_json or {}, output_schema=iface.output_schema_json or {},
param_mapping=row.param_mapping_json or {},
input_schema=iface.input_schema_json or {},
) )
@@ -2,7 +2,9 @@
用途:Capability 强类型契约注册表(能力名称/输入输出 Schema/幂等语义/是否写)。 用途:Capability 强类型契约注册表(能力名称/输入输出 Schema/幂等语义/是否写)。
依赖:app.core.errors、errors.py;纯代码,不依赖 DB。 依赖:app.core.errors、errors.py;纯代码,不依赖 DB。
逻辑:能力必须由代码注册,不能由管理端动态定义;领域只调用已注册能力,未注册 fail-closed。 逻辑:能力必须由代码注册,不能由管理端动态定义;各域契约声明在各域包的
capabilities 模块(如 in_transit_transfer/capabilities.py),由应用组合根
import 完成注册;领域只调用已注册能力,未注册 fail-closed。
""" """
from __future__ import annotations from __future__ import annotations
@@ -12,37 +14,6 @@ from dataclasses import dataclass
from app.core.errors import ValidationError from app.core.errors import ValidationError
from app.services.integration_connector.errors import CapabilityNotFoundError from app.services.integration_connector.errors import CapabilityNotFoundError
# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。
_QUERY_INPUT_SCHEMA: dict = {
"type": "object",
"required": ["invoice_no", "from_warehouse", "to_warehouse", "quantity"],
"properties": {
"invoice_no": {"type": "string"},
"from_warehouse": {"type": "string"},
"to_warehouse": {"type": "string"},
"quantity": {"type": "number"},
},
}
_QUERY_OUTPUT_SCHEMA: dict = {
"type": "object",
"properties": {
"found": {"type": "boolean"},
"quantity": {"type": ["number", "null"]},
},
}
_WRITE_OUTPUT_SCHEMA: dict = {
"type": "object",
"required": ["status"],
"properties": {
"status": {
"type": "string",
"enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"],
},
"document_no": {"type": ["string", "null"]},
"verified_posted": {"type": ["boolean", "null"]},
},
}
@dataclass(frozen=True) @dataclass(frozen=True)
class CapabilitySpec: class CapabilitySpec:
@@ -56,7 +27,6 @@ class CapabilitySpec:
_CAPABILITIES: dict[str, CapabilitySpec] = {} _CAPABILITIES: dict[str, CapabilitySpec] = {}
_LOADED = False
def register_capability(spec: CapabilitySpec) -> CapabilitySpec: def register_capability(spec: CapabilitySpec) -> CapabilitySpec:
@@ -84,42 +54,6 @@ def list_capabilities() -> list[CapabilitySpec]:
return sorted(_CAPABILITIES.values(), key=lambda s: s.name) return sorted(_CAPABILITIES.values(), key=lambda s: s.name)
def ensure_capabilities_loaded() -> None:
"""惰性注册内置能力(幂等);由网关/API 在解析前调用。"""
global _LOADED # noqa: PLW0603
if _LOADED:
return
_LOADED = True
_register_transfer_capabilities()
def _register_transfer_capabilities() -> None:
"""注册在途调拨域内置能力;领域代码只调这些能力,外部系统差异全在连接器层。"""
register_capability(CapabilitySpec(
name="in_transit_transfer.query_inventory",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_QUERY_OUTPUT_SCHEMA,
idempotency="none",
write=False,
))
register_capability(CapabilitySpec(
name="in_transit_transfer.create_transfer",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_WRITE_OUTPUT_SCHEMA,
idempotency="invoice",
write=True,
))
register_capability(CapabilitySpec(
name="in_transit_transfer.verify_duplicate",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_WRITE_OUTPUT_SCHEMA,
idempotency="invoice",
write=False,
))
def reset_capability_registry_for_tests() -> None: def reset_capability_registry_for_tests() -> None:
"""单测隔离:清空注册表并重置加载标记。""" """单测隔离:清空注册表(领域 capabilities 模块可重调其注册函数重建)。"""
global _LOADED # noqa: PLW0603
_CAPABILITIES.clear() _CAPABILITIES.clear()
_LOADED = False
@@ -0,0 +1,79 @@
"""services/integration_connector/credential_types.py
用途:凭据形态注册表——每种凭据类型定义自己的字段清单(键名/是否密文/是否必填),
是 UI 动态渲染与 API 组装/校验的唯一事实来源。
依赖:app.core.errors;纯代码注册表,无 DB/IO。
逻辑:类型由代码注册(与能力注册同哲学),管理端不可动态定义;字段键名即模板
占位符 credential_<key> 的 <key>;新增形态 = 加一个注册条目 + 前端标签,零迁移。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import ValidationError
# 凭据形态注册表:key 为稳定类型编码(credential_type 列值),fields 为字段清单。
# secret=True 的字段加密落库且永不回显;required 在「合并旧值后」仍缺失即拒绝。
CREDENTIAL_TYPE_SPECS: dict[str, dict[str, Any]] = {
"password": {
"fields": [
{"key": "username", "secret": False, "required": True},
{"key": "password", "secret": True, "required": True},
],
},
"token": {
"fields": [
{"key": "token", "secret": True, "required": True},
],
},
"api_key": {
"fields": [
{"key": "api_key", "secret": True, "required": True},
],
},
}
def get_credential_type(credential_type: str) -> dict[str, Any] | None:
"""按类型编码查字段定义;未知类型返回 None(调用方 fail-closed)。"""
return CREDENTIAL_TYPE_SPECS.get(str(credential_type or "").strip())
def list_credential_types() -> list[dict[str, Any]]:
"""返回全部已注册类型及其字段定义(供 GET /credential-references/types)。"""
return [
{"type": type_code, "fields": [dict(field) for field in spec["fields"]]}
for type_code, spec in sorted(CREDENTIAL_TYPE_SPECS.items())
]
def build_secret_dict(credential_type: str, values: dict) -> dict[str, str]:
"""按类型定义从「合并旧值后的提交值」组装凭据字典。
只保留类型定义内的键(未知键丢弃);必填字段缺失抛 ValidationError(fail-closed)。
"""
spec = get_credential_type(credential_type)
if spec is None:
raise ValidationError("unknown credential_type", details={"credential_type": credential_type})
result: dict[str, str] = {}
for field in spec["fields"]:
value = values.get(field["key"])
if value is not None and str(value) != "":
result[field["key"]] = str(value)
missing = [field["key"] for field in spec["fields"] if field["required"] and not result.get(field["key"])]
if missing:
raise ValidationError("required credential fields missing", details={"fields": missing})
return result
def visible_fields(credential_type: str, secret_dict: dict) -> dict[str, str]:
"""按类型定义回显非密字段(secret=True 的字段永不回显)。"""
spec = get_credential_type(credential_type)
if spec is None:
return {}
return {
field["key"]: str(secret_dict[field["key"]])
for field in spec["fields"]
if not field["secret"] and secret_dict.get(field["key"])
}
@@ -1,26 +1,36 @@
"""services/integration_connector/engine.py """services/integration_connector/engine.py
用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→build→call→map→classify→audit。 用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→map-params→call→classify→audit。
依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。 依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。
逻辑:读能力映射校验通过即 success;写能力按原始 status 分类;超时→timeout; 逻辑:域入参先经能力 Schema 校验,再按绑定 param_mapping 翻译为接口参数(对照接口
入参 Schema 校验);凭据按引用解析后以 credential_* 注入传输层;读能力返回
带 status 的失败 dict 时原样分类,其余映射校验通过即 success;
入参非法/无绑定/映射失败/契约未冻结均 fail-closed;result_unknown 不自动重试。 入参非法/无绑定/映射失败/契约未冻结均 fail-closed;result_unknown 不自动重试。
""" """
from __future__ import annotations from __future__ import annotations
import logging
import time import time
import uuid import uuid
from dataclasses import replace from dataclasses import replace
from app import db from app import db
from app.services.integration_connector.binding import BindingSnapshot, resolve_binding from app.services.integration_connector.binding import BindingSnapshot, resolve_binding
from app.services.integration_connector.capability import CapabilitySpec, ensure_capabilities_loaded, get_capability from app.services.integration_connector.capability import CapabilitySpec, get_capability
from app.services.integration_connector.errors import CallFailedError, InputInvalidError from app.services.integration_connector.errors import CallFailedError, InputInvalidError
from app.services.integration_connector.mapping import map_response, schema_errors from app.services.integration_connector.mapping import map_response, schema_errors
from app.services.integration_connector.security import sanitize from app.services.integration_connector.security import resolve_credential, sanitize
from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response from app.services.integration_connector.transports.base import (
RESULT_FAILURE_STATUSES,
IntegrationCallResult,
Transport,
classify_transport_response,
)
from app.models import IntegrationCall from app.models import IntegrationCall
logger = logging.getLogger(__name__)
def build_request(request_spec: dict, config: dict, params: dict) -> dict: def build_request(request_spec: dict, config: dict, params: dict) -> dict:
"""按接口请求规格构造请求:填充 path 占位符,组装 params/body/headers。""" """按接口请求规格构造请求:填充 path 占位符,组装 params/body/headers。"""
@@ -85,34 +95,51 @@ class CapabilityGateway:
environment: str | None = None, environment: str | None = None,
transports: dict[str, Transport] | None = None, transports: dict[str, Transport] | None = None,
) -> IntegrationCallResult: ) -> IntegrationCallResult:
ensure_capabilities_loaded()
spec = get_capability(capability) spec = get_capability(capability)
input_errors = schema_errors(params, spec.input_schema) input_errors = schema_errors(params, spec.input_schema)
if input_errors: if input_errors:
# InputInvalidError 只带 message 不带明细,降级进 result_message 后只剩
# "input invalid";不落日志则字段级原因(required missing/类型不符)永久丢失。
logger.warning(
"connector input invalid: capability=%s errors=%s",
capability, input_errors,
)
raise InputInvalidError(details={'errors': input_errors}) raise InputInvalidError(details={'errors': input_errors})
env = environment or _environment() env = environment or _environment()
snapshot = resolve_binding(capability, context, env) snapshot = resolve_binding(capability, context, env)
# 域参数 → 接口参数翻译:绑定配置了 param_mapping 时按映射引擎执行,
# 结果对照接口入参 Schema 校验;未配置时同名直通(能力入参原样下传)。
params = map_response(snapshot.param_mapping, params, snapshot.input_schema) \
if snapshot.param_mapping else params
transport = (transports or self.transports).get(snapshot.connector_type) transport = (transports or self.transports).get(snapshot.connector_type)
if transport is None: if transport is None:
raise CallFailedError(details={'reason': f'no transport for connector_type={snapshot.connector_type}'}) raise CallFailedError(details={'reason': f'no transport for connector_type={snapshot.connector_type}'})
# 凭据按引用解析(db 密文解密 / env 配置键读取),缺失即 fail-closed。
credential = resolve_credential(snapshot.credential_ref_code) if snapshot.credential_ref_code else {}
request = build_request(snapshot.request_spec, snapshot.config, params) request = build_request(snapshot.request_spec, snapshot.config, params)
trace_id = f'ic-{uuid.uuid4().hex}' trace_id = f'ic-{uuid.uuid4().hex}'
start_ms = int(time.time() * 1000) start_ms = int(time.time() * 1000)
try: try:
raw = transport.call( raw = transport.call(
client={'config_json': snapshot.config, 'credential': {}}, client={'config_json': snapshot.config, 'credential': credential},
interface={'request_spec_json': snapshot.request_spec}, interface={'request_spec_json': snapshot.request_spec},
request=request, request=request,
) )
except TimeoutError: except TimeoutError:
result = IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN', trace_id=trace_id) result = IntegrationCallResult(status='timeout', error_code='EXTERNAL_TIMEOUT_UNKNOWN', trace_id=trace_id)
_record_call(operation_id, capability, snapshot, params, None, result, start_ms, trace_id) _record_call(operation_id, capability, snapshot, params, None, result, start_ms, trace_id)
return result return result
result = classify_transport_response(raw) if spec.write else IntegrationCallResult(status='success') if spec.write:
if not spec.write or result.status in ('success', 'duplicate_success', 'duplicate_unverified'): result = classify_transport_response(raw)
elif isinstance(raw, dict) and raw.get('status') in RESULT_FAILURE_STATUSES:
# 传输层已判失败(HTTP 4xx/5xx、SOAP Fault、非 XML)→ 原样分类,不做输出映射。
result = classify_transport_response(raw)
else:
result = IntegrationCallResult(status='success')
if result.status in ('success', 'duplicate_success', 'duplicate_unverified'):
data = map_response(snapshot.response_mapping, raw, snapshot.output_schema or spec.output_schema) data = map_response(snapshot.response_mapping, raw, snapshot.output_schema or spec.output_schema)
result = replace(result, data=data) result = replace(result, data=data)
result = replace(result, trace_id=trace_id) result = replace(result, trace_id=trace_id)
@@ -2,12 +2,14 @@
用途:声明式映射引擎——把外部原始响应映射为统一结果(提取路径 + 白名单转换 + 输出 Schema 校验)。 用途:声明式映射引擎——把外部原始响应映射为统一结果(提取路径 + 白名单转换 + 输出 Schema 校验)。
依赖:decimal、errors.py;纯函数,无 IO/网络/DB。 依赖:decimal、errors.py;纯函数,无 IO/网络/DB。
逻辑:只允许点路径/数组下标提取与白名单转换函数,禁止任意 Python/JS/SQL; 逻辑:只允许点路径/数组下标提取与白名单转换函数(含 pick 键值取值、template 参数模板、
缺字段且不可满足→MappingInvalidError;输出不合 Schema→MappingInvalidError(fail-closed)。 each 列表逐元素子映射),禁止任意 Python/JS/SQL;缺字段且不可满足→MappingInvalidError;
输出不合 Schema→MappingInvalidError(fail-closed)。
""" """
from __future__ import annotations from __future__ import annotations
import string
from decimal import Decimal from decimal import Decimal
from typing import Any from typing import Any
@@ -50,25 +52,37 @@ def _tokenize(path: str) -> list[str]:
def extract_path(obj: Any, path: str) -> Any: def extract_path(obj: Any, path: str) -> Any:
"""按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。""" """按点路径/数组下标提取;缺任一节点返回 MISSING;路径超长/超深抛 MappingInvalidError。
路径途经重复节点列表(名称段撞上列表)时逐元素收集剩余路径的命中:
全部未命中视为 MISSING,部分命中收集为列表——同一配置在单/多记录
(如多条件查询返回多个 RecordSet)之间不再随机失效。
"""
path = str(path or "") path = str(path or "")
if len(path) > MAX_PATH_LENGTH: if len(path) > MAX_PATH_LENGTH:
raise MappingInvalidError(details={"reason": "path_too_long"}) raise MappingInvalidError(details={"reason": "path_too_long"})
tokens = _tokenize(path) tokens = _tokenize(path)
if len(tokens) > MAX_DEPTH: if len(tokens) > MAX_DEPTH:
raise MappingInvalidError(details={"reason": "path_too_deep"}) raise MappingInvalidError(details={"reason": "path_too_deep"})
cur = obj return _walk(obj, tokens)
for tok in tokens:
if isinstance(cur, list) and tok.isdigit():
idx = int(tok) def _walk(cur: Any, tokens: list[str]) -> Any:
if idx >= len(cur): """按 token 序列递归取值;列表遇名称段做扇出收集(重复节点归一化的路径侧配套)。"""
return MISSING if not tokens:
cur = cur[idx] return cur
elif isinstance(cur, dict) and tok in cur: tok, rest = tokens[0], tokens[1:]
cur = cur[tok] if isinstance(cur, list) and tok.isdigit():
else: idx = int(tok)
if idx >= len(cur):
return MISSING return MISSING
return cur return _walk(cur[idx], rest)
if isinstance(cur, dict) and tok in cur:
return _walk(cur[tok], rest)
if isinstance(cur, list):
collected = [hit for item in cur if (hit := _walk(item, tokens)) is not MISSING]
return collected if collected else MISSING
return MISSING
# ---- 白名单转换函数(纯函数,无 IO/网络/eval) ---- # ---- 白名单转换函数(纯函数,无 IO/网络/eval) ----
@@ -119,6 +133,81 @@ def _if_else(value: Any, condition: str, then: Any, else_: Any) -> Any:
return then if condition == "truthy" and bool(value) else else_ return then if condition == "truthy" and bool(value) else else_
def _pick(value: Any, key_field: str | None = None, key_value: Any = None,
value_field: str | None = None, exists: bool = False, cast: str | None = None) -> Any:
"""从「键值对记录列表」按 key_field==key_value 取值(行转列通用需求)。
Args:
value: 目标列表(每项为 dict,如 XML 归一化后的 Field 列表)。
key_field / key_value: 匹配键字段名与期望值(按字符串比较)。
value_field: 命中后取的字段名;缺省返回整条记录。
exists: True 时返回布尔(是否命中),不取值。
cast: 可选 "decimal" 或 _cast 支持的标量类型。
"""
if value is MISSING:
return MISSING
if key_field is None or key_value is None:
raise MappingInvalidError(details={"reason": "pick_requires_key_field_and_key_value"})
if not isinstance(value, list):
raise MappingInvalidError(details={"reason": "pick_target_not_list"})
for item in value:
if isinstance(item, dict) and str(item.get(key_field)) == str(key_value):
if exists:
return True
found = item.get(value_field) if value_field is not None else item
if cast == "decimal":
return _decimal(found)
return _cast(found, cast) if cast else found
if exists:
return False
return MISSING
def _each(value: Any, fields: dict | None = None) -> Any:
"""对列表逐元素套用子映射,产出 dict 列表(多条外部记录→多行结果的通用需求)。
Args:
value: 目标列表(每项为 dict,如归一化后的 Master 记录列表)。
fields: 子映射 {输出字段: {expr/transform/args}},语义与 map_response 顶层一致:
元素内缺字段按 MISSING 处理(跳过该键),转换函数复用 TRANSFORMS 白名单。
"""
if value is MISSING:
# 目标记录集整体缺失(外部系统对"查无记录"返回空 XML)→ 归一为空列表:
# 空结果是合法答案(如库存查无此批号),交领域层归类为"未找到",
# 不得因输出 Schema 校验 fail-closed 成映射错误。
return []
# XML 重复节点归一化后单条记录是 dict、多条是 list:单记录归一为单元素列表,
# 否则同一配置在单/多记录间会随机 fail-closed。
if isinstance(value, dict):
value = [value]
if not isinstance(value, list):
raise MappingInvalidError(details={"reason": "each_target_not_list"})
out: list[Any] = []
for item in value:
row: dict[str, Any] = {}
for field, spec in (fields or {}).items():
if not isinstance(spec, dict):
raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"})
if "default" in spec:
v: Any = spec["default"]
else:
expr = spec.get("expr")
v = extract_path(item, expr) if expr is not None else MISSING
transform = spec.get("transform")
if transform:
fn = TRANSFORMS.get(transform)
if fn is None:
raise MappingInvalidError(details={"field": field, "reason": f"unknown_transform:{transform}"})
v = fn(v, **(spec.get("args") or {}))
if v is not MISSING:
row[field] = v
if row:
# 全字段缺失的空行(如 Master 节点存在但无 Record 子节点)跳过,
# 避免产出违反行 Schema 的 {} 行;部分缺失仍保留,由行 Schema fail-closed。
out.append(row)
return out
TRANSFORMS: dict[str, Any] = { TRANSFORMS: dict[str, Any] = {
"default": _default, "default": _default,
"fallback": _fallback, "fallback": _fallback,
@@ -127,9 +216,64 @@ TRANSFORMS: dict[str, Any] = {
"enum-map": _enum_map, "enum-map": _enum_map,
"list-map": _list_map, "list-map": _list_map,
"if-else": _if_else, "if-else": _if_else,
"pick": _pick,
"each": _each,
} }
# ---- 参数模板填充(spec 级 "template",对整个参数表渲染,多用于域参数→接口参数翻译)----
def _render_template_value(value: Any, args: dict) -> str:
"""渲染单个占位符值:列表按 list_item_template 逐项渲染后用 separator 连接。
列表项为 dict 时,item_template 的占位符对 item 的键校验(缺失即
template_item_field_missing,fail-closed)并按字段转义渲染,
如 list_item_template = "(img01 = '{material_no}' AND img04 = '{lot_no}')"。
"""
item_template = str(args.get("list_item_template") or "{item}")
separator = str(args.get("separator") if args.get("separator") is not None else ",")
escape = args.get("escape")
def _escape(text: Any) -> str:
text = str(text)
if escape == "quote":
text = text.replace("'", "''")
return text
if isinstance(value, (list, tuple)):
rendered: list[str] = []
for item in value:
if isinstance(item, dict):
placeholders = {f for _, f, _, _ in string.Formatter().parse(item_template) if f}
missing = sorted(p for p in placeholders if p not in item)
if missing:
raise MappingInvalidError(details={"reason": "template_item_field_missing", "field": missing[0]})
rendered.append(item_template.format(**{k: _escape(v) for k, v in item.items()}))
else:
rendered.append(item_template.format(item=_escape(item)))
return separator.join(rendered)
return _escape(value)
def fill_param_template(template: str, params: dict, args: dict | None = None) -> str:
"""按 {param} 占位符对参数表渲染模板(str.format 语义,{{}} 转义字面大括号)。
缺占位符即抛 MappingInvalidError(fail-closed),绝不静默输出空串。
"""
template = str(template or "")
args = args or {}
placeholders = {fname for _, fname, _, _ in string.Formatter().parse(template) if fname}
rendered: dict[str, str] = {}
for name in placeholders:
if name not in (params or {}):
raise MappingInvalidError(details={"reason": "template_param_missing", "param": name})
rendered[name] = _render_template_value(params[name], args)
try:
return template.format(**rendered)
except (KeyError, IndexError, ValueError) as exc:
raise MappingInvalidError(details={"reason": "template_invalid"}) from exc
# ---- 最小 JSON Schema 子集校验(type/required/properties/enum/items)---- # ---- 最小 JSON Schema 子集校验(type/required/properties/enum/items)----
def _matches_type(value: Any, type_spec: Any) -> bool: def _matches_type(value: Any, type_spec: Any) -> bool:
@@ -190,7 +334,10 @@ def map_response(mapping: dict, raw: dict, output_schema: dict) -> dict:
for field, spec in mapping.items(): for field, spec in mapping.items():
if not isinstance(spec, dict): if not isinstance(spec, dict):
raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"}) raise MappingInvalidError(details={"field": field, "reason": "invalid_mapping_spec"})
if "default" in spec: if "template" in spec:
# 参数模板:对整个 raw(参数表)渲染,与单字段 expr 提取互补。
value = fill_param_template(spec["template"], raw, spec.get("args") or {})
elif "default" in spec:
value = spec["default"] value = spec["default"]
else: else:
expr = spec.get("expr") expr = spec.get("expr")
@@ -1,18 +1,32 @@
"""services/integration_connector/security.py """services/integration_connector/security.py
用途:凭据引用解析(fail-closed)与敏感字段脱敏。 用途:凭据引用解析(fail-closed)与敏感字段脱敏。
依赖:IntegrationCredentialReference 模型、current_app.config、errors.py。 依赖:IntegrationCredentialReference 模型、core.credential_crypto、current_app.config、errors.py。
逻辑:凭据只存 secret_ref 引用;解析时读当前环境配置,缺失即抛 CredentialUnresolvedError; 逻辑:db 模式解密 secret_ciphertext(主密钥 INTEGRATION_CREDENTIAL_KEY 环境注入);
sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文。 env 模式按 secret_ref 读当前环境配置,缺失即抛 CredentialUnresolvedError;
sanitize 递归脱敏敏感键;credential_summary 只回元数据,绝不回显明文/密文。
""" """
from __future__ import annotations from __future__ import annotations
import json
from typing import Any from typing import Any
from app.core.credential_crypto import CredentialCryptoErrorCodes, decrypt_secret
from app.core.errors import AppError
from app.models import IntegrationCredentialReference from app.models import IntegrationCredentialReference
from app.services.integration_connector.errors import CredentialUnresolvedError from app.services.integration_connector.errors import CredentialUnresolvedError
# 连接器凭据密文的 Fernet 主密钥配置键与错误码。
CREDENTIAL_KEY_CONFIG_NAME = 'INTEGRATION_CREDENTIAL_KEY'
_DB_SECRET_CODES = CredentialCryptoErrorCodes(
key_missing='INTEGRATION.CREDENTIAL_KEY_MISSING',
key_invalid='INTEGRATION.CREDENTIAL_KEY_INVALID',
secret_empty='INTEGRATION.CREDENTIAL_SECRET_EMPTY',
secret_missing='INTEGRATION.CREDENTIAL_SECRET_MISSING',
secret_invalid='INTEGRATION.CREDENTIAL_SECRET_INVALID',
)
DEFAULT_SENSITIVE_KEYS = frozenset({ DEFAULT_SENSITIVE_KEYS = frozenset({
'password', 'token', 'secret', 'authorization', 'cookie', 'access_key', 'password', 'token', 'secret', 'authorization', 'cookie', 'access_key',
'secret_key', 'credential', 'api_key', 'apikey', 'credentials', 'secret_key', 'credential', 'api_key', 'apikey', 'credentials',
@@ -20,10 +34,10 @@ DEFAULT_SENSITIVE_KEYS = frozenset({
def resolve_credential(credential_ref_code: str) -> dict[str, Any]: def resolve_credential(credential_ref_code: str) -> dict[str, Any]:
"""按凭据引用解析当前环境真实凭据(从 current_app.config[secret_ref] 读取)。 """按凭据引用解析真实凭据(db 解密 / env 配置键),fail-closed。
Raises: Raises:
CredentialUnresolvedError: 引用不存在或 secret_ref 对应配置缺失/为空。 CredentialUnresolvedError: 引用不存在、密文缺失、主密钥缺失/无效或 env 键缺失。
""" """
from flask import current_app from flask import current_app
@@ -32,13 +46,29 @@ def resolve_credential(credential_ref_code: str) -> dict[str, Any]:
).first() ).first()
if cred is None: if cred is None:
raise CredentialUnresolvedError(ref=credential_ref_code) raise CredentialUnresolvedError(ref=credential_ref_code)
if cred.secret_provider == 'db':
if not cred.secret_ciphertext:
raise CredentialUnresolvedError(ref=credential_ref_code)
try:
value = decrypt_secret(
cred.secret_ciphertext,
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
codes=_DB_SECRET_CODES,
)
except AppError as exc:
raise CredentialUnresolvedError(message=str(exc.message)) from exc
try:
parsed = json.loads(value)
except (ValueError, TypeError):
parsed = None
return dict(parsed) if isinstance(parsed, dict) else {'value': value}
secret_ref = cred.secret_ref secret_ref = cred.secret_ref
value = current_app.config.get(secret_ref) if has_app_ctx() else None config_value = current_app.config.get(secret_ref) if has_app_ctx() else None
if value is None or value == '': if config_value is None or config_value == '':
raise CredentialUnresolvedError(ref=secret_ref) raise CredentialUnresolvedError(ref=secret_ref)
if isinstance(value, dict): if isinstance(config_value, dict):
return dict(value) return dict(config_value)
return {'value': value} return {'value': config_value}
def has_app_ctx() -> bool: def has_app_ctx() -> bool:
@@ -4,6 +4,7 @@
依赖:typing.Protocol、dataclass;无 Flask/DB。 依赖:typing.Protocol、dataclass;无 Flask/DB。
逻辑:Transport.call 返回原始 dict;classify_transport_response 把原始响应归一为 逻辑:Transport.call 返回原始 dict;classify_transport_response 把原始响应归一为
IntegrationCallResult(复用调拨六态分类语义)。fail-closed 由各 Transport 抛异常。 IntegrationCallResult(复用调拨六态分类语义)。fail-closed 由各 Transport 抛异常。
probe 为可选实现的连接测试探针(只证明网络可达,不做业务调用)。
""" """
from __future__ import annotations from __future__ import annotations
@@ -18,6 +19,9 @@ RESULT_STATUSES = (
'technical_failed', 'timeout', 'result_unknown', 'technical_failed', 'timeout', 'result_unknown',
) )
# 传输层直接判失败的子集(读能力返回带这些 status 的原始 dict 时不再做输出映射)。
RESULT_FAILURE_STATUSES = ('business_failed', 'technical_failed')
@dataclass(frozen=True) @dataclass(frozen=True)
class IntegrationCallResult: class IntegrationCallResult:
@@ -32,13 +36,44 @@ class IntegrationCallResult:
class Transport(Protocol): class Transport(Protocol):
"""传输层协议:REST/SOAP(后续 RPA/SQL/FILE)。call 返回原始响应 dict。""" """传输层协议:REST/SOAP(后续 RPA/SQL/FILE)。call 返回原始响应 dict。
probe 为可选实现的连接测试探针:只证明网络/服务可达,不要求接口契约;
Admin API 测试端点优先调 probe,未实现时回退 call(空 interface 规格)。
"""
connector_type: str connector_type: str
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]: def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
... ...
def probe(self, *, client: dict) -> dict[str, Any]:
...
def merge_client_config(client: dict) -> dict:
"""把客户端实例独立列(endpoint/timeout_seconds)拼回 config_json 的兼容层。
与 binding.resolve_binding 的列拼回逻辑同源(单一实现),供连接测试等
不经绑定解析、直接消费客户端实例的调用方复用;返回副本,不改入参。
"""
config = dict(client.get('config_json') or {})
if client.get('endpoint') is not None:
config['endpoint'] = client['endpoint']
if client.get('timeout_seconds') is not None:
config['timeout_seconds'] = client['timeout_seconds']
return config
def mask_secrets(text: str, credential: dict | None) -> str:
"""把凭据值从自由文本(错误回显/响应摘要)中替换为 ***,防外泄进审计与日志。"""
result = str(text or '')
for value in (credential or {}).values():
secret = str(value or '')
if secret:
result = result.replace(secret, '***')
return result
def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult: def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult:
"""按原始响应文本归一化结果分类(复用调拨六态分类语义)。 """按原始响应文本归一化结果分类(复用调拨六态分类语义)。
@@ -67,7 +102,7 @@ def classify_transport_response(raw: dict[str, Any]) -> IntegrationCallResult:
error_message=str(raw.get('message') or ''), error_message=str(raw.get('message') or ''),
) )
if status == 'timeout': if status == 'timeout':
return IntegrationCallResult(status='timeout', error_code='ERP_TIMEOUT_UNKNOWN') return IntegrationCallResult(status='timeout', error_code='EXTERNAL_TIMEOUT_UNKNOWN')
if status == 'result_unknown': if status == 'result_unknown':
return IntegrationCallResult(status='result_unknown', error_code='ERP_RESULT_UNKNOWN', document_no=document_no) return IntegrationCallResult(status='result_unknown', error_code='EXTERNAL_RESULT_UNKNOWN', document_no=document_no)
return IntegrationCallResult(status='technical_failed', error_code='ERP_UNKNOWN_RESPONSE') return IntegrationCallResult(status='technical_failed', error_code='ERP_UNKNOWN_RESPONSE')
@@ -4,6 +4,7 @@
依赖:requests(默认注入),可注入 http_request 供测试替身。 依赖:requests(默认注入),可注入 http_request 供测试替身。
逻辑:endpoint 未冻结 fail-closed(TransportNotFrozenError);4xx/5xx 映射为 逻辑:endpoint 未冻结 fail-closed(TransportNotFrozenError);4xx/5xx 映射为
business_failed dict;非 JSON 响应映射为 technical_failed。 business_failed dict;非 JSON 响应映射为 technical_failed。
probe 连接测试探针:GET endpoint,任意 HTTP 响应即算可达(连接异常才算不通)。
""" """
from __future__ import annotations from __future__ import annotations
@@ -13,6 +14,7 @@ from typing import Any, Callable
import requests import requests
from app.services.integration_connector.errors import TransportNotFrozenError from app.services.integration_connector.errors import TransportNotFrozenError
from app.services.integration_connector.transports.base import mask_secrets
HttpRequest = Callable[..., Any] HttpRequest = Callable[..., Any]
@@ -50,7 +52,8 @@ class RestTransport:
return { return {
'status': 'business_failed', 'status': 'business_failed',
'code': f"HTTP_{int(response.status_code)}", 'code': f"HTTP_{int(response.status_code)}",
'message': str(getattr(response, 'text', ''))[:500], # 错误回显可能包含请求内容(含凭据),先脱敏再截断。
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
} }
try: try:
return response.json() return response.json()
@@ -58,5 +61,26 @@ class RestTransport:
return { return {
'status': 'technical_failed', 'status': 'technical_failed',
'code': 'NON_JSON', 'code': 'NON_JSON',
'message': str(getattr(response, 'text', ''))[:500], 'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
} }
def probe(self, *, client: dict) -> dict[str, Any]:
"""连接测试探针:GET endpoint,任意 HTTP 响应(含 4xx/5xx)都证明网络可达。
与 call 的区别:不要求接口契约(method/path),不做业务语义解析;
连接建立失败(DNS/超时/拒绝)才算不通。异常回显先脱敏再截断。
"""
config = client.get('config_json') or {}
endpoint = str(config.get('endpoint') or '').strip()
if not endpoint:
raise TransportNotFrozenError('REST endpoint not frozen (missing endpoint)')
timeout = int(config.get('timeout_seconds') or 60)
try:
response = self._http_request('GET', endpoint, timeout=timeout)
except Exception as exc:
return {'ok': False, 'code': 'CONNECTION_FAILED', 'message': mask_secrets(str(exc)[:500], client.get('credential'))}
return {
'ok': True,
'code': f"HTTP_{int(getattr(response, 'status_code', 0))}",
'message': mask_secrets(str(getattr(response, 'text', ''))[:200], client.get('credential'))[:200],
}
@@ -1,29 +1,215 @@
"""services/integration_connector/transports/soap.py """services/integration_connector/transports/soap.py
用途:SOAP Transport——WSDL/endpoint 未冻结时 fail-closed;真实实现待 WSDL 冻结后落地。 用途:SOAP Transport——按接口消息配置(soap.body_template)生成报文并解析 XML 响应。
依赖:zeep(延时导入);errors.py。 依赖:requests(默认注入)、xml.etree.ElementTree、errors.py。
逻辑:无 wsdl/endpoint → TransportNotFrozenError;冻结后走 zeep.Client(暂 NotImplemented)。 逻辑:endpoint 或 body_template 缺失 → fail-closed(TransportNotFrozenError);
模板占位符从请求参数 + 凭据(credential_* 保留前缀)填充,缺参即失败;
响应按 localname 解析(不绑命名空间前缀),Body 首子节点为业务根,
叶节点文本本身是合法 XML 时递归展开(内嵌转义报文的通用规则);
标准 SOAP 1.1 Fault(faultcode/faultstring)→ business_failed(SOAP 1.2 的
Code/Reason 结构暂只归 business_failed 不提取消息);HTTP ≥400 → business_failed;
非 XML → technical_failed。
probe 连接测试探针:GET WSDL 地址并校验返回 XML(definitions/Envelope 任一即通);
裸服务端点自动补 ?wsdl(SOAP 端点对裸 GET 常返回 404/405/501)。
""" """
from __future__ import annotations from __future__ import annotations
from typing import Any import string
import xml.etree.ElementTree as ET
from typing import Any, Callable
from app.services.integration_connector.errors import TransportNotFrozenError import requests
from app.services.integration_connector.errors import (
InputInvalidError,
TransportNotFrozenError,
)
from app.services.integration_connector.transports.base import mask_secrets
HttpRequest = Callable[..., Any]
# 内嵌转义 XML 的最大递归展开深度(防深嵌套/构造报文拖垮解析)。
MAX_EMBED_DEPTH = 3
def _localname(tag: Any) -> str:
"""去掉命名空间 URI,只取元素/属性的本地名(厂商前缀差异不影响映射路径)。"""
return tag.rsplit('}', 1)[-1] if isinstance(tag, str) else ''
def fill_soap_template(template: str, params: dict, credential: dict) -> str:
"""填充 SOAP 报文模板:{param} 来自请求参数,{credential_*} 来自凭据注入。
Args:
template: 接口配置里的完整报文模板(str.format 语义,{{}} 为字面大括号)。
params: 引擎映射后的接口参数。
credential: resolve_credential 解析出的凭据字典,按 credential_ 前缀注入。
Raises:
InputInvalidError: 占位符无对应值(fail-closed,绝不静默出空串)。
"""
merged: dict[str, Any] = dict(params or {})
# 凭据后注入并覆盖同名占位符:请求参数不得冒充/覆盖 credential_* 值。
for key, value in (credential or {}).items():
merged[f'credential_{key}'] = value
missing = sorted({
field for _, field, _, _ in string.Formatter().parse(template)
if field and field not in merged
})
if missing:
raise InputInvalidError(details={'reason': 'soap_template_param_missing', 'params': missing})
for key, value in merged.items():
# CDATA 内出现 ]]> 会截断报文;模板骨架自身的 CDATA 结束符不受影响,仅查替换值。
if ']]>' in str(value):
raise InputInvalidError(details={'reason': 'soap_cdata_terminator_in_params', 'param': key})
try:
return template.format(**merged)
except (KeyError, IndexError, ValueError) as exc:
# 覆盖裸 {} / 格式规格非法等 str.format 原生异常,统一 fail-closed 语义。
raise InputInvalidError(details={'reason': 'soap_template_invalid'}) from exc
def _element_to_value(elem: ET.Element, embed_depth: int) -> Any:
"""把元素转为通用 dict:属性 → @key;重复同名子元素 → list;叶子文本为值。
叶子文本本身是合法 XML(网关型系统常见的转义内嵌报文)时递归解析并保留内层根标签。
"""
attrs = {f'@{_localname(key)}': value for key, value in elem.attrib.items()}
children = list(elem)
text = (elem.text or '').strip()
if children:
node: dict[str, Any] = dict(attrs)
grouped: dict[str, list[Any]] = {}
for child in children:
name = _localname(child.tag)
grouped.setdefault(name, []).append(_element_to_value(child, embed_depth))
for name, items in grouped.items():
node[name] = items[0] if len(items) == 1 else items
if text:
node['#text'] = text
return node
if text.startswith('<') and embed_depth > 0:
try:
inner = ET.fromstring(text)
except ET.ParseError:
inner = None
if inner is not None:
return {_localname(inner.tag): _element_to_value(inner, embed_depth - 1)}
if not attrs:
return text or None
if text:
return {**attrs, '#text': text}
return attrs
def _parse_soap_payload(text: str) -> dict[str, Any]:
"""解析 SOAP 信封:取 Body 首子元素为业务根并转 dict;检测标准 Fault。"""
root = ET.fromstring(text)
body = None
for node in root.iter():
if _localname(node.tag) == 'Body':
body = node
break
payload = list(body)[0] if body is not None and len(body) else root
for node in payload.iter():
if _localname(node.tag) == 'Fault':
code = message = ''
for child in node.iter():
name = _localname(child.tag)
if name == 'faultcode' and not code:
code = (child.text or '').strip()
if name == 'faultstring' and not message:
message = (child.text or '').strip()
return {
'status': 'business_failed',
'code': code or 'SOAP_FAULT',
'message': message,
}
return {_localname(payload.tag): _element_to_value(payload, MAX_EMBED_DEPTH)}
class SoapTransport: class SoapTransport:
"""SOAP 传输;真实 SOAP 调用待 WSDL 冻结后实现(fail-closed 守卫已就位)。""" """SOAP 传输;http_request 可注入以便单元测试(默认 requests.request)。"""
connector_type = 'soap' connector_type = 'soap'
def __init__(self, http_request: HttpRequest | None = None):
self._http_request = http_request or requests.request
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]: def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
config = client.get('config_json') or {} config = client.get('config_json') or {}
# SOAP 只需一个连接地址(WSDL):WSDL 已含服务端点,不需单独的 REST 式 endpoint。 endpoint = str(config.get('endpoint') or '').strip()
# 该地址存于 config['endpoint'](语义即连接地址);timeout 与 REST 同语义。 if not endpoint:
wsdl = str(config.get('endpoint') or '').strip()
if not wsdl:
raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)') raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)')
# 真实 SOAP 调用(zeep.Client(timeout=int(config.get('timeout_seconds') or 60), ...)) 待 WSDL 冻结后落地。 spec = interface.get('request_spec_json') or {}
raise NotImplementedError('SOAP implementation pending frozen WSDL') soap_spec = spec.get('soap') or {}
template = str(soap_spec.get('body_template') or '').strip()
if not template:
raise TransportNotFrozenError('SOAP contract not frozen (missing soap.body_template)')
body = fill_soap_template(template, request.get('params') or {}, client.get('credential') or {})
headers = {'Content-Type': 'text/xml; charset=utf-8'}
action = str(soap_spec.get('action') or '').strip()
# SOAPAction 头必须存在且按规范带引号(空契约即 '""'):不带引号或缺失
# 会被鼎捷网关以 415 拒绝(2026-09-22 实测)。
headers['SOAPAction'] = f'"{action}"'
method = str(spec.get('method') or 'POST').upper()
path = str(spec.get('path') or '').strip()
url = endpoint.rstrip('/') + '/' + path.lstrip('/') if path else endpoint
response = self._http_request(
method,
url,
data=body.encode('utf-8'),
headers=headers,
timeout=int(config.get('timeout_seconds') or 60),
)
if int(getattr(response, 'status_code', 0)) >= 400:
return {
'status': 'business_failed',
'code': f"HTTP_{int(response.status_code)}",
# 错误回显可能包含请求体(含凭据),先脱敏再截断。
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
}
response_text = mask_secrets(str(getattr(response, 'text', '') or ''), client.get('credential'))
try:
return _parse_soap_payload(response_text)
except ET.ParseError:
return {
'status': 'technical_failed',
'code': 'NON_XML',
'message': response_text[:500],
}
def probe(self, *, client: dict) -> dict[str, Any]:
"""连接测试探针:GET WSDL 地址并校验返回 XML,只证明网络与服务可达。
与 call 的区别:不要求 soap.body_template 契约;根元素为 definitions
(WSDL 地址约定)或 Envelope(直连服务端点约定)任一即算通过。
裸服务端点对 GET 常返回 404/405/501(SOAP 只实现 POST),故未带 query
时自动补 ?wsdl 取服务描述;已带 query(如 ?wsdl)则按原地址探测。
连接失败 / HTTP ≥400 / 非 XML / 根元素不符 → ok=False;错误回显先脱敏。
"""
config = client.get('config_json') or {}
endpoint = str(config.get('endpoint') or '').strip()
if not endpoint:
raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)')
timeout = int(config.get('timeout_seconds') or 60)
probe_url = endpoint if '?' in endpoint else f'{endpoint}?wsdl'
try:
response = self._http_request('GET', probe_url, timeout=timeout)
except Exception as exc:
return {'ok': False, 'code': 'CONNECTION_FAILED', 'message': mask_secrets(str(exc)[:500], client.get('credential'))}
status = int(getattr(response, 'status_code', 0))
text = mask_secrets(str(getattr(response, 'text', '') or '')[:500], client.get('credential'))
if status >= 400:
return {'ok': False, 'code': f'HTTP_{status}', 'message': text}
try:
root = ET.fromstring(str(getattr(response, 'text', '') or ''))
except ET.ParseError:
return {'ok': False, 'code': 'NON_XML', 'message': text}
root_name = _localname(root.tag)
if root_name not in ('definitions', 'Envelope'):
return {'ok': False, 'code': 'NOT_WSDL', 'message': f'unexpected root <{root_name}>'}
return {'ok': True, 'code': f'HTTP_{status}', 'message': f'wsdl root <{root_name}>'}
@@ -0,0 +1,45 @@
"""
backend/migrations/versions/rd1e2f3a4b5c_integration_connector_param_mapping_and_db_credentials.py
用途:集成连接器两项增强——绑定增加参数映射列、凭据引用增加密文列(db 维护模式)。
依赖:Alembic revision dd22ee33ff44(当前唯一 head);integration_bindings / integration_credential_references 已存在。
逻辑:param_mapping_json 承载域参数→接口参数的声明式映射(空对象=同名直通);
secret_ciphertext 承载凭据 JSON 的 Fernet 密文(主密钥 INTEGRATION_CREDENTIAL_KEY
环境注入),与既有 env 引用模式并存(secret_provider 区分)。
Revision ID: rd1e2f3a4b5c
Revises: dd22ee33ff44
Create Date: 2026-09-21 19:00:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = "rd1e2f3a4b5c"
down_revision = "dd22ee33ff44"
branch_labels = None
depends_on = None
# 与 context_selector_json 同类型约定:PostgreSQL 用 JSONB,SQLite/测试用 JSON。
PARAM_MAPPING_JSON = sa.JSON().with_variant(postgresql.JSONB(), 'postgresql')
def upgrade() -> None:
"""绑定加参数映射列;凭据引用加密文列(可空,兼容既有 env 模式行)。"""
op.add_column(
'integration_bindings',
sa.Column('param_mapping_json', PARAM_MAPPING_JSON, nullable=False, server_default=sa.text("'{}'")),
)
op.add_column(
'integration_credential_references',
sa.Column('secret_ciphertext', sa.Text(), nullable=True),
)
def downgrade() -> None:
"""删除两列(param_mapping/密文均可由配置与凭据重新维护,无衍生数据)。"""
op.drop_column('integration_credential_references', 'secret_ciphertext')
op.drop_column('integration_bindings', 'param_mapping_json')
@@ -0,0 +1,31 @@
"""drop integration binding context_source_code
Revision ID: re1f3a4b5c6d
Revises: rd1e2f3a4b5c
Create Date: 2026-09-22 10:00:00.000000
用途:删除 IntegrationBinding.context_source_code 独立列(过度设计一刀切)。
依赖:ix1a2b3c4d5e 加列;rd1e2f3a4b5c 为当前 head。
逻辑:context_source_code 只是 context_selector_json 中 source_code 键的快捷列,
与高级配置(context_selector_json)机制重复;按路由条件统一走
context_selector_json 的约定删列,不设兼容层(框架未上线,无存量数据顾虑)。
"""
from alembic import op
import sqlalchemy as sa
revision = 're1f3a4b5c6d'
down_revision = 'rd1e2f3a4b5c'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""删除绑定表的 context_source_code 快捷列(路由条件统一由 context_selector_json 表达)。"""
op.drop_column('integration_bindings', 'context_source_code')
def downgrade() -> None:
"""回滚:恢复 context_source_code 列(nullable,与拆列迁移 ix1a2b3c4d5e 时的定义一致)。"""
op.add_column('integration_bindings', sa.Column('context_source_code', sa.String(length=64), nullable=True))
@@ -146,6 +146,69 @@ def test_client_instance_test_connection(app, client, admin_headers, fake_gatewa
assert response.get_json()["data"]["ok"] is True assert response.get_json()["data"]["ok"] is True
class ProbeSpyTransport:
"""记录 probe 收到的 client 配置,验证独立列(endpoint/timeout)已拼回 config_json。"""
connector_type = "soap"
def __init__(self):
self.seen = None
def probe(self, *, client):
self.seen = client
return {"ok": True, "code": "HTTP_200", "message": "wsdl root <definitions>"}
def call(self, *, client, interface, request): # pragma: no cover — 走到即失败
self.seen = {"unexpected_call": True}
def test_client_instance_test_connection_merges_endpoint_column(app, client, admin_headers, fake_gateway):
"""连接测试回归:endpoint 存独立列(config_json 为空)时必须拼回配置再探测。
曾因测试端点只透传 config_json,SOAP 客户端误报
'SOAP contract not frozen (missing wsdl/endpoint)'。
"""
created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-SOAP", "name": "soap client", "connector_type": "soap", "environment": "prod",
"endpoint": "https://erp.invalid/wsdl", "timeout_seconds": 45,
"config_json": {},
})
assert created.status_code == 201
spy = ProbeSpyTransport()
fake_gateway.transports["soap"] = spy
response = client.post(f"{API_PREFIX}/client-instances/CLI-SOAP/test", headers=admin_headers)
assert response.status_code == 200
data = response.get_json()["data"]
assert data["ok"] is True
# 独立列值必须出现在传给 transport 的 config_json 里(关键断言)。
assert spy.seen["config_json"]["endpoint"] == "https://erp.invalid/wsdl"
assert spy.seen["config_json"]["timeout_seconds"] == 45
def test_client_instance_test_connection_reports_unreachable(app, client, admin_headers, fake_gateway):
"""probe 探测不通 → 仍 200 但 ok=False(探测结果是业务结果,不是请求错误)。"""
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-DOWN", "name": "down", "connector_type": "rest", "environment": "prod",
"endpoint": "https://down.invalid",
})
class DownTransport:
connector_type = "rest"
def probe(self, *, client):
return {"ok": False, "code": "CONNECTION_FAILED", "message": "connection refused"}
fake_gateway.transports["rest"] = DownTransport()
response = client.post(f"{API_PREFIX}/client-instances/CLI-DOWN/test", headers=admin_headers)
assert response.status_code == 200
data = response.get_json()["data"]
assert data["ok"] is False
assert data["status"] == "failed"
assert data["result"]["code"] == "CONNECTION_FAILED"
def test_update_client_instance(app, client, admin_headers): def test_update_client_instance(app, client, admin_headers):
"""PUT /client-instances/<code> → 200,更新 name/config/enabled。""" """PUT /client-instances/<code> → 200,更新 name/config/enabled。"""
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
@@ -162,13 +225,13 @@ def test_update_client_instance(app, client, admin_headers):
def test_update_interface_definition(app, client, admin_headers): def test_update_interface_definition(app, client, admin_headers):
"""PUT /interface-definitions/<code> → 200,更新模板/回传映射/状态。""" """PUT /interface-definitions/<code> → 200,更新模板/回传映射;body 里的 status 被忽略。"""
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-I", "name": "cli", "connector_type": "rest", "environment": "prod", "code": "CLI-I", "name": "cli", "connector_type": "rest", "environment": "prod",
"config_json": {}, "config_json": {},
}) })
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
"code": "IF-U", "name": "iface", "client_instance_code": "CLI-I", "connector_type": "rest", "code": "IF-U", "name": "iface", "client_instance_code": "CLI-I",
"request_spec_json": {"path": "/v1/old"}, "status": "draft", "request_spec_json": {"path": "/v1/old"}, "status": "draft",
}) })
response = client.put(f"{API_PREFIX}/interface-definitions/IF-U", headers=admin_headers, json={ response = client.put(f"{API_PREFIX}/interface-definitions/IF-U", headers=admin_headers, json={
@@ -177,12 +240,86 @@ def test_update_interface_definition(app, client, admin_headers):
}) })
assert response.status_code == 200 assert response.status_code == 200
data = response.get_json()["data"] data = response.get_json()["data"]
assert data["status"] == "published" # 状态只能经生命周期动作端点流转:PUT 携带 status 不生效,仍为创建时的 draft
assert data["status"] == "draft"
assert data["request_spec_json"] == {"path": "/v1/new"} assert data["request_spec_json"] == {"path": "/v1/new"}
assert data["response_mapping_json"] == {"qty": "data.quantity"}
def test_interface_connector_type_derived_from_client(app, client, admin_headers):
"""连接器类型由所属客户端实例服务端推导:创建/换绑客户端均以客户端为准,body 传值被忽略。"""
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-D1", "name": "soap cli", "connector_type": "soap", "environment": "prod",
"config_json": {},
})
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-D2", "name": "rest cli", "connector_type": "rest", "environment": "prod",
"config_json": {},
})
# 创建:body 误传 rest(与客户端 soap 不一致)→ 落库以客户端为准
created = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
"code": "IF-DERIVE", "name": "iface", "client_instance_code": "CLI-D1",
"connector_type": "rest",
})
assert created.status_code == 201
assert created.get_json()["data"]["connector_type"] == "soap"
# 换绑客户端 → 类型跟随新客户端
updated = client.put(f"{API_PREFIX}/interface-definitions/IF-DERIVE", headers=admin_headers, json={
"client_instance_code": "CLI-D2",
})
assert updated.status_code == 200
assert updated.get_json()["data"]["connector_type"] == "rest"
# 客户端不存在 → 400(而非依赖外键报 500)
missing = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
"code": "IF-NOCLI", "name": "iface", "client_instance_code": "CLI-NOT-EXIST",
})
assert missing.status_code == 400
def test_interface_create_freezes_enabled(app, client, admin_headers):
"""接口定义 enabled 冻结:请求体传值被忽略,可用性只由 status 生命周期表达。"""
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-FE", "name": "cli", "connector_type": "rest", "environment": "prod",
})
created = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
"code": "IF-FE", "name": "iface", "client_instance_code": "CLI-FE", "enabled": False,
})
assert created.status_code == 201
assert created.get_json()["data"]["enabled"] is True
def test_interface_lifecycle_transitions(app, client, admin_headers):
"""发布/撤回/退役/恢复按转移表流转;非法转移与未知动作被拒绝。"""
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-LC", "name": "cli", "connector_type": "rest", "environment": "prod",
"config_json": {},
})
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
"code": "IF-LC", "name": "iface", "client_instance_code": "CLI-LC",
})
def lifecycle(action, code="IF-LC"):
return client.post(f"{API_PREFIX}/interface-definitions/{code}/{action}", headers=admin_headers)
# draft 上直接撤回/退役 → 400(源状态不符)
assert lifecycle("unpublish").status_code == 400
assert lifecycle("retire").status_code == 400
# draft → published → draft(撤回)→ published → retired(退役)→ draft(恢复)
assert lifecycle("publish").get_json()["data"]["status"] == "published"
assert lifecycle("unpublish").get_json()["data"]["status"] == "draft"
assert lifecycle("publish").get_json()["data"]["status"] == "published"
assert lifecycle("retire").get_json()["data"]["status"] == "retired"
# retired 不能直接发布,须经恢复为草稿
illegal = lifecycle("publish")
assert illegal.status_code == 400
assert illegal.get_json()["error"]["code"] == "INTEGRATION.ILLEGAL_STATUS_TRANSITION"
assert lifecycle("reopen").get_json()["data"]["status"] == "draft"
# 接口不存在 → 404
assert lifecycle("publish", code="IF-NOPE").status_code == 404
def test_update_binding(app, client, admin_headers): def test_update_binding(app, client, admin_headers):
"""PUT /bindings/<id> → 200,更新映射版本/优先级/状态。""" """PUT /bindings/<id> → 200,更新映射版本/优先级;状态不经 PUT 改写(走生命周期端点)。"""
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-B", "name": "cli", "connector_type": "rest", "environment": "prod", "code": "CLI-B", "name": "cli", "connector_type": "rest", "environment": "prod",
"config_json": {}, "config_json": {},
@@ -192,7 +329,7 @@ def test_update_binding(app, client, admin_headers):
}) })
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
"capability": "in_transit_transfer.query_inventory", "client_instance_code": "CLI-B", "capability": "in_transit_transfer.query_inventory", "client_instance_code": "CLI-B",
"interface_definition_code": "IF-B", "status": "draft", "interface_definition_code": "IF-B",
}) })
binding_id = created.get_json()["data"]["id"] binding_id = created.get_json()["data"]["id"]
response = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={ response = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={
@@ -202,24 +339,153 @@ def test_update_binding(app, client, admin_headers):
data = response.get_json()["data"] data = response.get_json()["data"]
assert data["priority"] == 5 assert data["priority"] == 5
assert data["mapping_version"] == 2 assert data["mapping_version"] == 2
assert data["status"] == "published" # 请求体携带 status 被忽略:状态只能经 /publish 动作端点流转
assert data["status"] == "draft"
# 发布绑定有就绪门禁:接口定义须先发布
client.post(f"{API_PREFIX}/interface-definitions/IF-B/publish", headers=admin_headers)
published = client.post(f"{API_PREFIX}/bindings/{binding_id}/publish", headers=admin_headers)
assert published.get_json()["data"]["status"] == "published"
def test_binding_create_forces_draft_and_pair_validation(app, client, admin_headers):
"""新建绑定固定落 draft;客户端与接口成对校验(错配/缺失均 400)。"""
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-BC", "name": "cli", "connector_type": "rest", "environment": "prod",
"endpoint": "https://erp.invalid",
})
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-OTHER", "name": "other", "connector_type": "rest", "environment": "prod",
})
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
"code": "IF-BC", "name": "iface", "client_instance_code": "CLI-BC", "connector_type": "rest",
})
# 请求体携带 status / context_source_code 均被忽略:状态走生命周期端点,
# 来源路由条件统一由 context_selector_json 表达(无独立快捷列)
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
"capability": "in_transit_transfer.query_inventory",
"client_instance_code": "CLI-BC", "interface_definition_code": "IF-BC",
"status": "published", "context_source_code": "DBS-AWSBI",
})
assert created.status_code == 201
data = created.get_json()["data"]
assert data["status"] == "draft"
assert "context_source_code" not in data
# 接口定义不属于所选客户端 → 400(fail-fast,不留给调用期)
mismatch = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
"capability": "in_transit_transfer.query_inventory",
"client_instance_code": "CLI-OTHER", "interface_definition_code": "IF-BC",
})
assert mismatch.status_code == 400
assert mismatch.get_json()["error"]["code"] == "INTEGRATION.BINDING_PAIR_MISMATCH"
# 客户端/接口不存在 → 400(而非依赖外键报 500)
assert client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
"capability": "in_transit_transfer.query_inventory",
"client_instance_code": "CLI-NOT-EXIST", "interface_definition_code": "IF-BC",
}).status_code == 400
assert client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
"capability": "in_transit_transfer.query_inventory",
"client_instance_code": "CLI-BC", "interface_definition_code": "IF-NOT-EXIST",
}).status_code == 400
# 更新换绑接口时同样成对校验:以变更后的最终组合为准
binding_id = data["id"]
updated = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={
"client_instance_code": "CLI-OTHER",
})
assert updated.status_code == 400
assert updated.get_json()["error"]["code"] == "INTEGRATION.BINDING_PAIR_MISMATCH"
def test_binding_lifecycle_transitions(app, client, admin_headers):
"""发布/撤回/退役/恢复按转移表流转;发布有就绪门禁(接口须已发布且客户端启用)。"""
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-BLC", "name": "cli", "connector_type": "rest", "environment": "prod",
"config_json": {},
})
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
"code": "IF-BLC", "name": "iface", "client_instance_code": "CLI-BLC",
})
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
"capability": "in_transit_transfer.query_inventory",
"client_instance_code": "CLI-BLC", "interface_definition_code": "IF-BLC",
})
binding_id = created.get_json()["data"]["id"]
def lifecycle(action):
return client.post(f"{API_PREFIX}/bindings/{binding_id}/{action}", headers=admin_headers)
# 接口定义还是草稿 → 发布绑定被就绪门禁拦截(避免发布永不生效的死绑定)
not_ready = lifecycle("publish")
assert not_ready.status_code == 400
assert not_ready.get_json()["error"]["code"] == "INTEGRATION.BINDING_TARGET_NOT_READY"
# 接口发布后:draft → published → draft(撤回)→ published → retired(退役)→ draft(恢复)
client.post(f"{API_PREFIX}/interface-definitions/IF-BLC/publish", headers=admin_headers)
assert lifecycle("publish").get_json()["data"]["status"] == "published"
assert lifecycle("unpublish").get_json()["data"]["status"] == "draft"
assert lifecycle("publish").get_json()["data"]["status"] == "published"
assert lifecycle("retire").get_json()["data"]["status"] == "retired"
# retired 不能直接发布,须经恢复为草稿
illegal = lifecycle("publish")
assert illegal.status_code == 400
assert illegal.get_json()["error"]["code"] == "INTEGRATION.ILLEGAL_STATUS_TRANSITION"
assert lifecycle("reopen").get_json()["data"]["status"] == "draft"
# 绑定不存在 → 404
assert client.post(f"{API_PREFIX}/bindings/999999/publish", headers=admin_headers).status_code == 404
def test_update_credential_reference(app, client, admin_headers): def test_update_credential_reference(app, client, admin_headers):
"""PUT /credential-references/<code> → 200,更新 secret_ref/status,且不回显明文。""" """PUT /credential-references/<code> → 200,更新 secret_ref,且不回显明文。"""
client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={ client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
"code": "CRED-U", "secret_ref": "IN_TRANSIT_ERP_PASSWORD", "code": "CRED-U", "secret_ref": "IN_TRANSIT_ERP_PASSWORD",
}) })
response = client.put(f"{API_PREFIX}/credential-references/CRED-U", headers=admin_headers, json={ response = client.put(f"{API_PREFIX}/credential-references/CRED-U", headers=admin_headers, json={
"secret_ref": "IN_TRANSIT_ERP_PASSWORD_ROTATED", "status": "rotating", "secret_ref": "IN_TRANSIT_ERP_PASSWORD_ROTATED",
}) })
assert response.status_code == 200 assert response.status_code == 200
data = response.get_json()["data"] data = response.get_json()["data"]
assert data["secret_ref"] == "IN_TRANSIT_ERP_PASSWORD_ROTATED" assert data["secret_ref"] == "IN_TRANSIT_ERP_PASSWORD_ROTATED"
assert data["status"] == "rotating"
assert "secret" not in str(data).lower() or data.get("secret") is None assert "secret" not in str(data).lower() or data.get("secret") is None
def test_credential_status_two_state_toggle(app, client, admin_headers):
"""凭据状态两态开关:active/retired 可经 PUT 互切;rotating 不可进入;存量 rotating 可恢复。"""
client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
"code": "CRED-TS", "secret_ref": "IN_TRANSIT_ERP_PASSWORD",
})
# active → retired(停用;解析层只认 active,停用即断流)
retired = client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={
"status": "retired",
})
assert retired.status_code == 200
assert retired.get_json()["data"]["status"] == "retired"
# rotating 不可进入(其现语义等于断供,真实版本化轮换属 P2)
rotating = client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={
"status": "rotating",
})
assert rotating.status_code == 400
# retired → active(恢复启用)
reactivated = client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={
"status": "active",
})
assert reactivated.get_json()["data"]["status"] == "active"
# 存量 rotating 数据(经 create 兼容通道落库)可经 PUT 置回 active 恢复
client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
"code": "CRED-LEGACY", "secret_ref": "LEGACY_KEY", "status": "rotating",
})
recovered = client.put(f"{API_PREFIX}/credential-references/CRED-LEGACY", headers=admin_headers, json={
"status": "active",
})
assert recovered.status_code == 200
assert recovered.get_json()["data"]["status"] == "active"
# 非法状态值 → 400
assert client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={
"status": "bogus",
}).status_code == 400
def test_client_instance_split_columns(app, client, admin_headers): def test_client_instance_split_columns(app, client, admin_headers):
"""POST /client-instances 写 endpoint/timeout_seconds 独立列,config_json 仅存扩展。""" """POST /client-instances 写 endpoint/timeout_seconds 独立列,config_json 仅存扩展。"""
created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
@@ -265,26 +531,101 @@ def test_interface_definition_split_columns(app, client, admin_headers):
assert updated.get_json()["data"]["request_path"] == "/inventory/{invoice_no}" assert updated.get_json()["data"]["request_path"] == "/inventory/{invoice_no}"
def test_binding_split_columns(app, client, admin_headers): # ---- 绑定参数映射 / 凭据 db 模式 ----
"""POST/PUT /bindings 写 context_source_code 独立列并回显。"""
def test_binding_param_mapping_round_trip(app, client, admin_headers):
"""POST/PUT /bindings 透传 param_mapping_json,序列化原样返回。"""
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={ client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-BC", "name": "cli", "connector_type": "rest", "environment": "prod", "code": "CLI-PM", "name": "cli", "connector_type": "rest", "environment": "prod",
"endpoint": "https://erp.invalid", "endpoint": "https://erp.invalid",
}) })
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={ client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
"code": "IF-BC", "name": "iface", "client_instance_code": "CLI-BC", "connector_type": "rest", "code": "IFACE-PM", "name": "iface", "client_instance_code": "CLI-PM", "connector_type": "rest",
}) })
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={ created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
"capability": "in_transit_transfer.query_inventory", "capability": "in_transit_transfer.query_inventory",
"client_instance_code": "CLI-BC", "interface_definition_code": "IF-BC", "client_instance_code": "CLI-PM", "interface_definition_code": "IFACE-PM",
"context_source_code": "DBS-AWSBI", "status": "published", "param_mapping_json": {"organization": {"expr": "external_org"},
"condition": {"template": "img04 = '{invoice_no}'"}},
}) })
assert created.status_code == 201 assert created.status_code == 201
data = created.get_json()["data"] data = created.get_json()["data"]
assert data["context_source_code"] == "DBS-AWSBI" assert data["param_mapping_json"]["organization"] == {"expr": "external_org"}
updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers, json={ updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers,
"context_source_code": "CRANE-SZ", json={"param_mapping_json": {"condition": {"template": "img02 = '{warehouse}'"}}})
})
assert updated.status_code == 200 assert updated.status_code == 200
assert updated.get_json()["data"]["context_source_code"] == "CRANE-SZ" assert updated.get_json()["data"]["param_mapping_json"] == {
"condition": {"template": "img02 = '{warehouse}'"},
}
def test_credential_db_mode_round_trip(app, client, admin_headers):
"""db 模式:按凭据类型加密字段落库;回显非密字段、绝不回显密文;只改密码保留用户名。"""
from cryptography.fernet import Fernet
app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii")
created = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
"code": "CRED-DB", "secret_provider": "db",
"username": "erp_user", "password": "erp_pass",
})
assert created.status_code == 201
data = created.get_json()["data"]
assert data["secret_fields"] == {"username": "erp_user"}
assert data["has_secret"] is True
assert "erp_pass" not in created.get_data(as_text=True)
assert "secret_ciphertext" not in data
updated = client.put(f"{API_PREFIX}/credential-references/CRED-DB", headers=admin_headers,
json={"password": "new_pass"})
assert updated.status_code == 200
data = updated.get_json()["data"]
assert data["secret_fields"] == {"username": "erp_user"} # 只改密码时用户名保留
assert "new_pass" not in updated.get_data(as_text=True)
def test_credential_db_mode_token_type_and_types_endpoint(app, client, admin_headers):
"""token 类型按其字段清单组装;类型清单端点返回注册表。"""
from cryptography.fernet import Fernet
app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii")
types = client.get(f"{API_PREFIX}/credential-references/types", headers=admin_headers)
assert types.status_code == 200
type_names = {item["type"] for item in types.get_json()["data"]}
assert type_names == {"password", "token", "api_key"}
created = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
"code": "CRED-TOKEN", "secret_provider": "db", "credential_type": "token",
"token": "tk-123",
})
assert created.status_code == 201
data = created.get_json()["data"]
assert data["credential_type"] == "token"
assert data["secret_fields"] == {} # token 是密文字段,不回显
assert "tk-123" not in created.get_data(as_text=True)
# token 必填缺失 → 400
missing = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
"code": "CRED-TOKEN2", "secret_provider": "db", "credential_type": "token",
})
assert missing.status_code == 400
def test_credential_db_mode_unknown_type_rejected(app, client, admin_headers):
"""未知凭据类型 → 400(fail-closed)。"""
from cryptography.fernet import Fernet
app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii")
response = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
"code": "CRED-BAD", "secret_provider": "db", "credential_type": "nope",
"username": "u", "password": "p",
})
assert response.status_code == 400
def test_credential_db_mode_requires_username_and_password(app, client, admin_headers):
"""db 模式创建缺用户名或密码 → 400。"""
response = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
"code": "CRED-DB2", "secret_provider": "db", "username": "only-user",
})
assert response.status_code == 400
@@ -3,6 +3,7 @@
用途:验证 Binding 解析与版本冻结——默认/上下文覆盖/优先级/生效区间/状态门禁/fail-closed。 用途:验证 Binding 解析与版本冻结——默认/上下文覆盖/优先级/生效区间/状态门禁/fail-closed。
依赖:IntegrationBinding 等模型、binding.py、errors.py。 依赖:IntegrationBinding 等模型、binding.py、errors.py。
逻辑:只匹配 published + environment + 生效区间 + context_selector 子集; 逻辑:只匹配 published + environment + 生效区间 + context_selector 子集;
接口定义须 published、客户端须 enabled,否则同样 fail-closed;
无命中抛 BindingNotFoundError;快照冻结 interface 版本与配置(调用期冻结,非活表)。 无命中抛 BindingNotFoundError;快照冻结 interface 版本与配置(调用期冻结,非活表)。
""" """
@@ -120,3 +121,43 @@ def test_freeze_versions_in_snapshot(app):
assert snap.credential_ref_code is None assert snap.credential_ref_code is None
assert snap.request_spec.get("path") == "/stock" assert snap.request_spec.get("path") == "/stock"
assert snap.config.get("endpoint") == "https://erp.invalid" assert snap.config.get("endpoint") == "https://erp.invalid"
def test_snapshot_carries_param_mapping_and_input_schema(app):
"""快照冻结绑定参数映射与接口入参 Schema(引擎翻译契约)。"""
db.session.add_all([
_client(),
_interface(input_schema_json={"type": "object", "required": ["condition"]}),
_binding(param_mapping_json={"condition": {"template": "img04 = '{invoice_no}'"}}),
])
db.session.commit()
snap = resolve_binding("in_transit_transfer.query_inventory", {}, "prod")
assert snap.param_mapping == {"condition": {"template": "img04 = '{invoice_no}'"}}
assert snap.input_schema == {"type": "object", "required": ["condition"]}
def test_draft_interface_not_matched(app):
"""接口定义为 draft 时不命中(fail-closed):绑定已发布但接口未发布视同无可用绑定。"""
db.session.add_all([_client(), _interface(status="draft"), _binding()])
db.session.commit()
with pytest.raises(AppError) as exc:
resolve_binding("in_transit_transfer.query_inventory", {}, "prod")
assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND"
def test_retired_interface_not_matched(app):
"""接口定义为 retired 时不命中:退役是引用它的所有绑定的总开关。"""
db.session.add_all([_client(), _interface(status="retired"), _binding()])
db.session.commit()
with pytest.raises(AppError) as exc:
resolve_binding("in_transit_transfer.query_inventory", {}, "prod")
assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND"
def test_disabled_client_not_matched(app):
"""客户端实例停用(enabled=False)时不命中:列表行内启停开关具备调用期语义。"""
db.session.add_all([_client(enabled=False), _interface(), _binding()])
db.session.commit()
with pytest.raises(AppError) as exc:
resolve_binding("in_transit_transfer.query_inventory", {}, "prod")
assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND"
@@ -11,9 +11,7 @@ import pytest
from app.services.integration_connector.capability import ( from app.services.integration_connector.capability import (
CapabilitySpec, CapabilitySpec,
ensure_capabilities_loaded,
get_capability, get_capability,
list_capabilities,
register_capability, register_capability,
reset_capability_registry_for_tests, reset_capability_registry_for_tests,
) )
@@ -47,13 +45,3 @@ def test_get_unregistered_raises_not_found():
get_capability("in_transit_transfer.none") get_capability("in_transit_transfer.none")
assert exc.value.code == "INTEGRATION.CAPABILITY_NOT_FOUND" assert exc.value.code == "INTEGRATION.CAPABILITY_NOT_FOUND"
assert exc.value.http_status == 404 assert exc.value.http_status == 404
def test_ensure_loaded_registers_three_transfer_capabilities():
"""ensure_capabilities_loaded 后注册 3 个在途调拨能力,write 标志正确。"""
ensure_capabilities_loaded()
names = {spec.name for spec in list_capabilities()}
assert {"in_transit_transfer.query_inventory", "in_transit_transfer.create_transfer", "in_transit_transfer.verify_duplicate"}.issubset(names)
assert get_capability("in_transit_transfer.create_transfer").write is True
assert get_capability("in_transit_transfer.query_inventory").write is False
assert get_capability("in_transit_transfer.verify_duplicate").write is False
@@ -0,0 +1,51 @@
"""tests/services/integration_connector/test_credential_types.py
用途:验证凭据类型注册表——字段组装/必填校验/非密回显/未知类型 fail-closed。
依赖:credential_types(纯函数)。
逻辑:build_secret_dict 只保留类型定义内字段且必填齐全;visible_fields 只回显非密字段。
"""
from __future__ import annotations
import pytest
from app.core.errors import AppError
from app.services.integration_connector.credential_types import (
build_secret_dict,
get_credential_type,
list_credential_types,
visible_fields,
)
def test_registry_contains_builtin_types():
"""内置 password/token/api_key 三种类型,字段定义齐全。"""
types = {item["type"] for item in list_credential_types()}
assert types == {"password", "token", "api_key"}
password_fields = {f["key"]: f for f in get_credential_type("password")["fields"]}
assert set(password_fields) == {"username", "password"}
assert password_fields["password"]["secret"] is True
assert password_fields["username"]["secret"] is False
def test_build_secret_dict_keeps_defined_keys_only():
"""只保留类型定义内的键(未知键丢弃),必填齐全。"""
values = {"username": "u", "password": "p", "evil": "x"}
assert build_secret_dict("password", values) == {"username": "u", "password": "p"}
def test_build_secret_dict_missing_required_fail_closed():
"""必填字段缺失 → ValidationError。"""
with pytest.raises(AppError):
build_secret_dict("password", {"username": "u"})
def test_build_secret_dict_unknown_type_fail_closed():
with pytest.raises(AppError):
build_secret_dict("nope", {})
def test_visible_fields_returns_non_secret_only():
assert visible_fields("password", {"username": "u", "password": "p"}) == {"username": "u"}
assert visible_fields("token", {"token": "t"}) == {}
assert visible_fields("nope", {"x": "y"}) == {}
@@ -16,10 +16,20 @@ import pytest
from app import db from app import db
from app.core.errors import AppError from app.core.errors import AppError
from app.models import IntegrationBinding, IntegrationCall, IntegrationClientInstance, IntegrationInterfaceDefinition from app.models import IntegrationBinding, IntegrationCall, IntegrationClientInstance, IntegrationInterfaceDefinition
from app.services.integration_connector.capability import ensure_capabilities_loaded from app.services.in_transit_transfer.capabilities import register_transfer_capabilities
from app.services.integration_connector.capability import reset_capability_registry_for_tests
from app.services.integration_connector.engine import CapabilityGateway from app.services.integration_connector.engine import CapabilityGateway
@pytest.fixture(autouse=True)
def _transfer_capabilities():
"""每用例前重建在途调拨能力注册:能力声明已移至领域包,注册表可能被其他用例 reset。"""
reset_capability_registry_for_tests()
register_transfer_capabilities()
yield
reset_capability_registry_for_tests()
class FakeTransport: class FakeTransport:
"""可注入响应或异常的传输替身。""" """可注入响应或异常的传输替身。"""
@@ -60,14 +70,16 @@ def _seed(capability, *, connector_type="rest", response_mapping=None, output_sc
def _params(**overrides): def _params(**overrides):
values = {"invoice_no": "INV-001", "from_warehouse": "W1", "to_warehouse": "W2", "quantity": 100} values = {
"external_org": "HX-CN01",
"targets": [{"material_no": "M-1", "from_warehouse": "W1", "lot_no": "L-1"}],
}
values.update(overrides) values.update(overrides)
return values return values
def test_call_success_records_integration_call(app): def test_call_success_records_integration_call(app):
"""读能力成功:status=success、data 含映射结果、落 IntegrationCall。""" """读能力成功:status=success、data 含映射结果、落 IntegrationCall。"""
ensure_capabilities_loaded()
_seed("in_transit_transfer.query_inventory") _seed("in_transit_transfer.query_inventory")
fake = FakeTransport({"found": True, "quantity": "100"}) fake = FakeTransport({"found": True, "quantity": "100"})
result = CapabilityGateway(transports={"rest": fake}).call( result = CapabilityGateway(transports={"rest": fake}).call(
@@ -83,7 +95,6 @@ def test_call_success_records_integration_call(app):
def test_call_input_invalid_raises(app): def test_call_input_invalid_raises(app):
"""入参不合输入 Schema → INTEGRATION.INPUT_INVALID。""" """入参不合输入 Schema → INTEGRATION.INPUT_INVALID。"""
ensure_capabilities_loaded()
_seed("in_transit_transfer.query_inventory") _seed("in_transit_transfer.query_inventory")
with pytest.raises(AppError) as exc: with pytest.raises(AppError) as exc:
CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call( CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call(
@@ -95,7 +106,6 @@ def test_call_input_invalid_raises(app):
def test_call_no_binding_raises(app): def test_call_no_binding_raises(app):
"""无可用绑定 → INTEGRATION.BINDING_NOT_FOUND(fail-closed)。""" """无可用绑定 → INTEGRATION.BINDING_NOT_FOUND(fail-closed)。"""
ensure_capabilities_loaded()
with pytest.raises(AppError) as exc: with pytest.raises(AppError) as exc:
CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call( CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call(
capability="in_transit_transfer.query_inventory", context={}, capability="in_transit_transfer.query_inventory", context={},
@@ -106,7 +116,6 @@ def test_call_no_binding_raises(app):
def test_call_write_business_failed(app): def test_call_write_business_failed(app):
"""写能力按原始 status 分类 → business_failed。""" """写能力按原始 status 分类 → business_failed。"""
ensure_capabilities_loaded()
_seed("in_transit_transfer.create_transfer") _seed("in_transit_transfer.create_transfer")
fake = FakeTransport({"status": "business_failed", "code": "E1", "message": "reject"}) fake = FakeTransport({"status": "business_failed", "code": "E1", "message": "reject"})
result = CapabilityGateway(transports={"rest": fake}).call( result = CapabilityGateway(transports={"rest": fake}).call(
@@ -119,7 +128,6 @@ def test_call_write_business_failed(app):
def test_call_transport_timeout_returns_timeout(app): def test_call_transport_timeout_returns_timeout(app):
"""传输超时 → status=timeout。""" """传输超时 → status=timeout。"""
ensure_capabilities_loaded()
_seed("in_transit_transfer.query_inventory") _seed("in_transit_transfer.query_inventory")
result = CapabilityGateway(transports={"rest": FakeTransport(TimeoutError())}).call( result = CapabilityGateway(transports={"rest": FakeTransport(TimeoutError())}).call(
capability="in_transit_transfer.query_inventory", context={}, capability="in_transit_transfer.query_inventory", context={},
@@ -130,7 +138,6 @@ def test_call_transport_timeout_returns_timeout(app):
def test_call_mapping_invalid_raises(app): def test_call_mapping_invalid_raises(app):
"""输出不合输出 Schema → INTEGRATION.MAPPING_INVALID(fail-closed)。""" """输出不合输出 Schema → INTEGRATION.MAPPING_INVALID(fail-closed)。"""
ensure_capabilities_loaded()
_seed("in_transit_transfer.query_inventory", _seed("in_transit_transfer.query_inventory",
output_schema={"type": "object", "required": ["found", "quantity"], output_schema={"type": "object", "required": ["found", "quantity"],
"properties": {"found": {"type": "boolean"}, "quantity": {"type": "number"}}}) "properties": {"found": {"type": "boolean"}, "quantity": {"type": "number"}}})
@@ -145,7 +152,6 @@ def test_call_mapping_invalid_raises(app):
def test_call_result_unknown_no_auto_retry(app): def test_call_result_unknown_no_auto_retry(app):
"""result_unknown 不自动重试:transport 仅被调用一次。""" """result_unknown 不自动重试:transport 仅被调用一次。"""
ensure_capabilities_loaded()
_seed("in_transit_transfer.create_transfer") _seed("in_transit_transfer.create_transfer")
calls = [] calls = []
@@ -160,3 +166,109 @@ def test_call_result_unknown_no_auto_retry(app):
) )
assert result.status == "result_unknown" assert result.status == "result_unknown"
assert len(calls) == 1 assert len(calls) == 1
# ---- 参数映射与凭据注入(P1 绑定翻译契约)----
def _seed_full_params(*, param_mapping=None, input_schema=None, credential_ref=None):
client = IntegrationClientInstance(
code="CLI-P", name="client", connector_type="rest", environment="prod",
config_json={"endpoint": "https://erp.invalid"}, credential_ref_code=credential_ref,
)
iface = IntegrationInterfaceDefinition(
code="IFACE-P", name="iface", client_instance_code="CLI-P", connector_type="rest",
request_spec_json={"method": "GET", "path": "/stock"},
input_schema_json=input_schema or {},
response_mapping_json={"found": {"expr": "found"}, "quantity": {"expr": "quantity", "transform": "decimal"}},
output_schema_json={"type": "object", "properties": {"found": {"type": "boolean"}, "quantity": {"type": "number"}}},
version=1, status="published",
)
db.session.add_all([client, iface])
db.session.flush()
binding = IntegrationBinding(
capability="in_transit_transfer.query_inventory", context_selector_json={},
param_mapping_json=param_mapping or {},
client_instance_code="CLI-P", interface_definition_code="IFACE-P",
mapping_version=1, priority=0, environment="prod", status="published",
)
db.session.add(binding)
db.session.commit()
def test_call_applies_binding_param_mapping(app):
"""绑定配置 param_mapping 时域参数先翻译为接口参数再下传传输层。"""
_seed_full_params(
param_mapping={"organization": {"expr": "external_org"},
"condition": {"template": "{targets}",
"args": {"list_item_template": "img04 = '{lot_no}'", "separator": " OR "}}},
input_schema={"type": "object", "required": ["organization", "condition"],
"properties": {"organization": {"type": "string"}, "condition": {"type": "string"}}},
)
captured = {}
class _Capture(FakeTransport):
def call(self, *, client, interface, request):
captured.update(params=request["params"], interface=interface)
return {"found": True, "quantity": "5"}
result = CapabilityGateway(transports={"rest": _Capture(None)}).call(
capability="in_transit_transfer.query_inventory", context={},
params=_params(external_org="TGHX", targets=[{"material_no": "M-9", "from_warehouse": "W1", "lot_no": "L-9"}]),
operation_id="OP-PM", environment="prod",
)
assert captured["params"] == {"organization": "TGHX", "condition": "img04 = 'L-9'"}
assert result.status == "success"
def test_call_mapped_params_fail_interface_schema(app):
"""映射结果不合接口入参 Schema → INTEGRATION.MAPPING_INVALID(fail-closed)。"""
_seed_full_params(
param_mapping={"organization": {"expr": "external_org"}},
input_schema={"type": "object", "required": ["organization", "condition"],
"properties": {"organization": {"type": "string"}, "condition": {"type": "string"}}},
)
with pytest.raises(AppError) as exc:
CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call(
capability="in_transit_transfer.query_inventory", context={},
params=_params(external_org="TGHX"),
operation_id="OP-PM2", environment="prod",
)
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
def test_call_injects_resolved_credential(app):
"""客户端实例引用凭据时,引擎解析凭据并经 client['credential'] 注入传输层。"""
_seed_full_params(credential_ref="CRED-1")
app.config["CRED1_CFG"] = {"username": "u", "password": "p"}
from app import db as _db
from app.models import IntegrationCredentialReference
_db.session.add(IntegrationCredentialReference(
code="CRED-1", secret_ref="CRED1_CFG", secret_provider="env",
credential_type="password", version=1, status="active",
))
_db.session.commit()
captured = {}
class _Capture(FakeTransport):
def call(self, *, client, interface, request):
captured.update(credential=client["credential"])
return {"found": True, "quantity": "5"}
CapabilityGateway(transports={"rest": _Capture(None)}).call(
capability="in_transit_transfer.query_inventory", context={},
params=_params(), operation_id="OP-CRED", environment="prod",
)
assert captured["credential"] == {"username": "u", "password": "p"}
def test_call_read_capability_failure_passthrough(app):
"""读能力返回带失败 status 的原始 dict 时原样分类,不做输出映射。"""
_seed_full_params()
result = CapabilityGateway(transports={"rest": FakeTransport(
{"status": "business_failed", "code": "HTTP_500", "message": "boom"}
)}).call(
capability="in_transit_transfer.query_inventory", context={},
params=_params(), operation_id="OP-RF", environment="prod",
)
assert result.status == "business_failed"
assert result.error_code == "HTTP_500"
@@ -8,6 +8,7 @@
from __future__ import annotations from __future__ import annotations
import json
from decimal import Decimal from decimal import Decimal
import pytest import pytest
@@ -94,3 +95,246 @@ def test_map_response_enum_violation_raises():
}, },
) )
assert exc.value.code == "INTEGRATION.MAPPING_INVALID" assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
# ---- pick:键值对记录列表取值(XML Field[@name,@value] 归一化的通用消费方式)----
def _field_rows():
return [
{"@name": "img04", "@value": "HOW25071402"},
{"@name": "img11", "@value": "30.000"},
]
def test_pick_returns_value_with_decimal_cast():
mapped = map_response(
{"quantity": {"expr": "rows", "transform": "pick",
"args": {"key_field": "@name", "key_value": "img11", "value_field": "@value", "cast": "decimal"}}},
{"rows": _field_rows()},
{"type": "object", "properties": {"quantity": {"type": "number"}}},
)
assert mapped["quantity"] == Decimal("30.000")
def test_pick_exists_boolean():
mapped = map_response(
{"found": {"expr": "rows", "transform": "pick",
"args": {"key_field": "@name", "key_value": "img04", "exists": True}}},
{"rows": _field_rows()},
{"type": "object", "properties": {"found": {"type": "boolean"}}},
)
assert mapped["found"] is True
mapped_absent = map_response(
{"found": {"expr": "rows", "transform": "pick",
"args": {"key_field": "@name", "key_value": "nope", "exists": True}}},
{"rows": _field_rows()},
{"type": "object", "properties": {"found": {"type": "boolean"}}},
)
assert mapped_absent["found"] is False
def test_pick_requires_list_and_key_args():
with pytest.raises(AppError):
map_response({"q": {"expr": "rows", "transform": "pick", "args": {"key_field": "@name", "key_value": "x"}}},
{"rows": {"not": "a list"}}, {})
with pytest.raises(AppError):
map_response({"q": {"expr": "rows", "transform": "pick", "args": {"key_field": "@name"}}},
{"rows": _field_rows()}, {})
def test_pick_miss_returns_missing_so_field_absent():
mapped = map_response(
{"quantity": {"expr": "rows", "transform": "pick",
"args": {"key_field": "@name", "key_value": "nope", "value_field": "@value"}}},
{"rows": _field_rows()},
{"type": "object", "properties": {"quantity": {"type": "number"}}},
)
assert "quantity" not in mapped
# ---- template:参数模板填充(域参数→接口参数翻译的列表渲染)----
def test_template_renders_list_into_in_clause():
mapped = map_response(
{"condition": {"template": "img02 = '{warehouse}' AND img04 IN ({lots})",
"args": {"list_item_template": "'{item}'", "separator": ",", "escape": "quote"}}},
{"warehouse": "HTP-D43", "lots": ["HOW25071402", "HOW25081302"]},
{"type": "object", "properties": {"condition": {"type": "string"}}},
)
assert mapped["condition"] == "img02 = 'HTP-D43' AND img04 IN ('HOW25071402','HOW25081302')"
def test_template_escapes_single_quotes_in_values():
mapped = map_response(
{"condition": {"template": "img02 = '{warehouse}'", "args": {"escape": "quote"}}},
{"warehouse": "HT'D43"},
{"type": "object", "properties": {"condition": {"type": "string"}}},
)
assert mapped["condition"] == "img02 = 'HT''D43'"
def test_template_missing_param_fail_closed():
with pytest.raises(AppError) as exc:
map_response(
{"condition": {"template": "img04 = '{invoice_no}'"}},
{},
{"type": "object", "properties": {"condition": {"type": "string"}}},
)
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
# ---- dict 项列表模板:域元组列表 → OR 拼接条件(料号+库位+批号批量查询)----
def test_template_renders_dict_items_with_field_refs():
mapped = map_response(
{"condition": {"template": "{targets}",
"args": {"list_item_template": "(img01 = '{material_no}' AND img02 = '{from_warehouse}' AND img04 = '{lot_no}')",
"separator": " OR ", "escape": "quote"}}},
{"targets": [
{"material_no": "M-1", "from_warehouse": "HTP-D43", "lot_no": "LOT-1"},
{"material_no": "M'2", "from_warehouse": "HTP-D49", "lot_no": "LOT-2"},
]},
{"type": "object", "properties": {"condition": {"type": "string"}}},
)
assert mapped["condition"] == (
"(img01 = 'M-1' AND img02 = 'HTP-D43' AND img04 = 'LOT-1') OR "
"(img01 = 'M''2' AND img02 = 'HTP-D49' AND img04 = 'LOT-2')"
)
def test_template_dict_item_missing_field_fail_closed():
with pytest.raises(AppError) as exc:
map_response(
{"condition": {"template": "{targets}",
"args": {"list_item_template": "(img01 = '{material_no}' AND img04 = '{lot_no}')",
"separator": " OR "}}},
{"targets": [{"material_no": "M-1"}]},
{"type": "object", "properties": {"condition": {"type": "string"}}},
)
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
# ---- each:列表逐元素子映射(多条外部记录 → 多行结果)----
def test_each_maps_record_list_via_pick_and_cast():
raw = {"Master": [
{"Record": {"Field": [
{"name": "img01", "value": "M-1"}, {"name": "img02", "value": "W1"},
{"name": "img04", "value": "L-1"}, {"name": "img11", "value": "36"}]}},
{"Record": {"Field": [
{"name": "img01", "value": "M-2"}, {"name": "img02", "value": "W2"},
{"name": "img04", "value": "L-2"}, {"name": "img11", "value": "0"}]}},
]}
mapped = map_response(
{"rows": {"expr": "Master", "transform": "each", "args": {"fields": {
"material_no": {"expr": "Record.Field", "transform": "pick",
"args": {"key_field": "name", "key_value": "img01", "value_field": "value"}},
"lot_no": {"expr": "Record.Field", "transform": "pick",
"args": {"key_field": "name", "key_value": "img04", "value_field": "value"}},
"quantity": {"expr": "Record.Field", "transform": "pick",
"args": {"key_field": "name", "key_value": "img11", "value_field": "value", "cast": "decimal"}},
}}}},
raw,
{"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}},
)
assert mapped["rows"] == [
{"material_no": "M-1", "lot_no": "L-1", "quantity": Decimal("36")},
{"material_no": "M-2", "lot_no": "L-2", "quantity": Decimal("0")},
]
def test_each_single_record_dict_wrapped_to_one_row():
"""XML 归一化单条记录为 dict → 自动包装为单元素列表,不 fail-closed。"""
mapped = map_response(
{"rows": {"expr": "Master", "transform": "each", "args": {"fields": {
"lot_no": {"expr": "Record.Field", "transform": "pick",
"args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}}}}}},
{"Master": {"Record": {"Field": [{"@name": "img04", "@value": "L-1"}]}}},
{"type": "object", "properties": {"rows": {"type": "array"}}},
)
assert mapped["rows"] == [{"lot_no": "L-1"}]
def test_each_missing_target_yields_empty_rows():
"""目标记录集整体缺失(外部系统对"查无记录"返回空 XML)→ 空列表而非 fail-closed。
空结果是合法答案:交领域层归类为"未找到",不因输出 Schema 校验抛映射错误。
"""
mapped = map_response(
{"rows": {"expr": "GetItemStockListResponse.response.Response.ResponseContent.Document.RecordSet.Master",
"transform": "each", "args": {"fields": {
"lot_no": {"expr": "Record.Field", "transform": "pick",
"args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}}}}}},
{"GetItemStockListResponse": {"response": {"Response": {"ResponseContent": {"Document": {}}}}}},
{"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}},
)
assert mapped["rows"] == []
def test_each_skips_items_with_all_fields_missing():
"""Master 存在但无 Record 子节点 → 逐字段全缺失的空行被跳过,不产出违反行 Schema 的 {}。"""
mapped = map_response(
{"rows": {"expr": "Master", "transform": "each", "args": {"fields": {
"lot_no": {"expr": "Record.Field", "transform": "pick",
"args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}}}}}},
{"Master": {"@name": "img_file"}},
{"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}},
)
assert mapped["rows"] == []
def test_each_flattens_repeated_recordset_from_multi_target_query():
"""多条件批量查询返回多个 RecordSet(重复节点列表)→ 路径扇出收集,行全部拉平。
[回归防线 2026-09-22] TIPTOP 对 OR 多目标查询按条件拆多个 RecordSet 返回:
路径遇列表做逐元素收集后 each 正常产出全部行,不得误判为"查无记录"。
"""
raw = json.loads(r"""
{"GetItemStockListResponse": {"response": {"Response": {"ResponseContent": {"Document": {"RecordSet": [
{"@id": "1", "Master": {"@name": "img_file", "Record": {"Field": [
{"@name": "img01", "@value": "M-1"}, {"@name": "img04", "@value": "L-1"},
{"@name": "img10", "@value": "0.000"}]}}},
{"@id": "2", "Master": {"@name": "img_file", "Record": {"Field": [
{"@name": "img01", "@value": "M-2"}, {"@name": "img04", "@value": "L-2"},
{"@name": "img10", "@value": "5.000"}]}}}
]}}}}}
}""")
mapped = map_response(
{"rows": {"expr": "GetItemStockListResponse.response.Response.ResponseContent.Document.RecordSet.Master",
"transform": "each", "args": {"fields": {
"material_no": {"expr": "Record.Field", "transform": "pick",
"args": {"key_field": "@name", "key_value": "img01", "value_field": "@value"}},
"lot_no": {"expr": "Record.Field", "transform": "pick",
"args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}},
"quantity": {"expr": "Record.Field", "transform": "pick",
"args": {"key_field": "@name", "key_value": "img10", "value_field": "@value",
"cast": "decimal"}}}}}},
raw,
{"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}},
)
# [断言意图] 两个条件的记录都进入 rows,数量不足/未找到的判定输入完整。
assert mapped["rows"] == [
{"material_no": "M-1", "lot_no": "L-1", "quantity": Decimal("0.000")},
{"material_no": "M-2", "lot_no": "L-2", "quantity": Decimal("5.000")},
]
def test_each_target_not_list_fail_closed():
with pytest.raises(AppError) as exc:
map_response(
{"rows": {"expr": "Master", "transform": "each", "args": {"fields": {}}}},
{"Master": "not a dict or list"},
{"type": "object", "properties": {"rows": {"type": "array"}}},
)
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
def test_each_unknown_nested_transform_fail_closed():
with pytest.raises(AppError) as exc:
map_response(
{"rows": {"expr": "Master", "transform": "each", "args": {"fields": {
"x": {"expr": "a", "transform": "no_such_fn"}}}}},
{"Master": [{"a": 1}]},
{"type": "object", "properties": {"rows": {"type": "array"}}},
)
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
@@ -84,3 +84,31 @@ def test_split_migration_chains_after_create():
split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py') split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py')
assert split.revision == 'ix1a2b3c4d5e' assert split.revision == 'ix1a2b3c4d5e'
assert split.down_revision == 'iy1a2b3c4d5e' assert split.down_revision == 'iy1a2b3c4d5e'
def test_drop_context_source_code_migration_round_trip():
"""删列迁移承接 head rd1e2f3a4b5c:升级后 context_source_code 消失,回滚后恢复。"""
engine = sa.create_engine('sqlite:///:memory:')
base = _load_migration('integration_connector_migration', 'ic1a2b3c4d5f_add_integration_connector.py')
split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py')
drop = _load_migration(
'integration_binding_drop_source_code_migration',
're1f3a4b5c6d_drop_integration_binding_context_source_code.py',
)
assert drop.revision == 're1f3a4b5c6d'
assert drop.down_revision == 'rd1e2f3a4b5c'
with engine.begin() as connection:
context = MigrationContext.configure(connection)
operations = Operations(context)
for module in (base, split, drop):
module.op = operations
base.upgrade()
split.upgrade()
drop.upgrade()
cols = {item['name'] for item in sa.inspect(connection).get_columns('integration_bindings')}
assert 'context_source_code' not in cols
drop.downgrade()
cols = {item['name'] for item in sa.inspect(connection).get_columns('integration_bindings')}
assert 'context_source_code' in cols
@@ -71,3 +71,59 @@ def test_credential_summary_has_no_plaintext(app):
assert "s3cretLY" not in json.dumps(summary) assert "s3cretLY" not in json.dumps(summary)
assert "svc_user_erp" not in json.dumps(summary) assert "svc_user_erp" not in json.dumps(summary)
assert summary["version"] == 1 assert summary["version"] == 1
# ---- db 模式:密文落库 + 主密钥解密 ----
def _add_db_credential(code="DB-CRED", ciphertext=None):
cred = IntegrationCredentialReference(
code=code, secret_ref=f"db:{code}", secret_provider="db",
credential_type="password", version=1, status="active",
secret_ciphertext=ciphertext,
)
db.session.add(cred)
db.session.commit()
return cred
def _crypto_codes():
from app.core.credential_crypto import CredentialCryptoErrorCodes
return CredentialCryptoErrorCodes(
key_missing="K1", key_invalid="K2", secret_empty="S0", secret_missing="S1", secret_invalid="S2",
)
def test_resolve_credential_db_mode_decrypts(app):
"""db 模式:用 INTEGRATION_CREDENTIAL_KEY 解密密文还原凭据字典。"""
from cryptography.fernet import Fernet
from app.core.credential_crypto import encrypt_secret
app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii")
ciphertext = encrypt_secret(
json.dumps({"username": "u", "password": "p"}),
key_config_name="INTEGRATION_CREDENTIAL_KEY", codes=_crypto_codes(),
)
_add_db_credential(ciphertext=ciphertext)
assert resolve_credential("DB-CRED") == {"username": "u", "password": "p"}
def test_resolve_credential_db_mode_missing_ciphertext_fail_closed(app):
"""db 模式缺密文 → CredentialUnresolvedError。"""
_add_db_credential(ciphertext=None)
with pytest.raises(AppError) as exc:
resolve_credential("DB-CRED")
assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED"
def test_resolve_credential_db_mode_missing_master_key_fail_closed(app):
"""主密钥无效 → 统一折算为 CredentialUnresolvedError(fail-closed)。"""
from cryptography.fernet import Fernet
from app.core.credential_crypto import encrypt_secret
app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii")
ciphertext = encrypt_secret("x", key_config_name="INTEGRATION_CREDENTIAL_KEY", codes=_crypto_codes())
_add_db_credential(ciphertext=ciphertext)
app.config["INTEGRATION_CREDENTIAL_KEY"] = "not-a-valid-key"
with pytest.raises(AppError) as exc:
resolve_credential("DB-CRED")
assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED"
@@ -1,9 +1,10 @@
"""tests/services/integration_connector/test_transports.py """tests/services/integration_connector/test_transports.py
用途:验证 REST/SOAP Transport 的请求构造、业务错误映射与 fail-closed; 用途:验证 REST/SOAP Transport 的请求构造、业务错误映射与 fail-closed;
以及结果分类(classify_transport_response)的六态语义。 连接测试探针(probe)的可达判定;以及结果分类(classify_transport_response)的六态语义。
依赖:transports/base.py、transports/rest.py、transports/soap.py、errors.py。 依赖:transports/base.py、transports/rest.py、transports/soap.py、errors.py。
逻辑:Transport.call 返回原始 dict;分类器把 dict 归一为 IntegrationCallResult。 逻辑:Transport.call 返回原始 dict;分类器把 dict 归一为 IntegrationCallResult。
probe 只做网络可达性探测(REST 任意响应即通;SOAP 校验 WSDL/Envelope 根元素)。
""" """
from __future__ import annotations from __future__ import annotations
@@ -102,3 +103,289 @@ def test_classify_transport_response_states():
assert dup.status == "duplicate_success" assert dup.status == "duplicate_success"
unknown = classify_transport_response({}) unknown = classify_transport_response({})
assert unknown.status == "technical_failed" assert unknown.status == "technical_failed"
# ---- SOAP Transport 实装 ----
_SOAP_TEMPLATE = (
'<?xml version="1.0" encoding="utf-8"?>'
'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
'<soap:Body><fjs:GetItemStockListRequest xmlns:fjs="http://www.dsc.com.tw/tiptop/TIPTOPServiceGateWay">'
'<fjs:request><![CDATA[<Request><Organization name="{organization}"/>'
'<Field name="condition" value="{condition}"/>'
'<Authentication user="{credential_username}" password="{credential_password}"/>'
'</Request>]]></fjs:request></fjs:GetItemStockListRequest></soap:Body></soap:Envelope>'
)
# 带命名空间前缀 + 转义内嵌 XML 的典型网关响应。
_SOAP_RESPONSE = (
'<?xml version="1.0" encoding="UTF-8" standalone="no"?>'
'<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">'
'<SOAP-ENV:Body>'
'<fjs1:GetItemStockListResponse xmlns:fjs1="http://www.dsc.com.tw/tiptop/TIPTOPServiceGateWay">'
'<fjs1:response>&lt;Response&gt;'
'&lt;Execution&gt;&lt;Status code="0" sqlcode="0" description=""/&gt;&lt;/Execution&gt;'
'&lt;ResponseContent&gt;&lt;Parameter/&gt;'
'&lt;Document&gt;&lt;RecordSet id="1"&gt;&lt;Master name="img_file"&gt;&lt;Record&gt;'
'&lt;Field name="img04" value="HOW25071402"/&gt;'
'&lt;Field name="img11" value="30.000"/&gt;'
'&lt;/Record&gt;&lt;/Master&gt;&lt;/RecordSet&gt;&lt;/Document&gt;'
'&lt;/ResponseContent&gt;&lt;/Response&gt;</fjs1:response>'
'</fjs1:GetItemStockListResponse>'
'</SOAP-ENV:Body></SOAP-ENV:Envelope>'
)
def _soap_client(**overrides):
cfg = {"endpoint": "https://erp.invalid/ws", "timeout_seconds": 30}
cfg.update(overrides)
return {"config_json": cfg, "credential": {"username": "u1", "password": "p1"}}
def test_soap_fills_template_with_params_and_credential():
"""模板占位符从请求参数与凭据(credential_* 前缀)填充,按 text/xml POST。"""
captured = {}
def fake_http(method, url, **kw):
captured.update(method=method, url=url, data=kw.get("data"), headers=kw.get("headers"))
return _resp(200, text=_SOAP_RESPONSE)
result = SoapTransport(http_request=fake_http).call(
client=_soap_client(),
interface={"request_spec_json": {"method": "POST", "soap": {"action": "", "body_template": _SOAP_TEMPLATE}}},
request={"params": {"organization": "TGHX", "condition": "img04 IN ('HOW25071402')"}},
)
body = captured["data"].decode("utf-8")
assert captured["method"] == "POST"
assert captured["url"] == "https://erp.invalid/ws"
assert captured["headers"]["Content-Type"].startswith("text/xml")
assert captured["headers"]["SOAPAction"] == '""' # SOAPAction 头恒存在(空契约即带引号空串)
assert 'name="TGHX"' in body
assert "img04 IN ('HOW25071402')" in body
assert 'user="u1"' in body and 'password="p1"' in body
# 内嵌转义 XML 被递归展开,且按 localname 归一化(前缀 fjs1 不出现)。
assert result["GetItemStockListResponse"]["response"]["Response"]["Execution"]["Status"]["@code"] == "0"
fields = result["GetItemStockListResponse"]["response"]["Response"]["ResponseContent"]["Document"]["RecordSet"]["Master"]["Record"]["Field"]
by_name = {f["@name"]: f["@value"] for f in fields}
assert by_name["img11"] == "30.000"
def test_soap_missing_template_param_fail_closed():
"""占位符缺值 → INTEGRATION.INPUT_INVALID(fail-closed,不静默出空串)。"""
from app.core.errors import AppError
transport = SoapTransport(http_request=lambda *a, **k: None)
with pytest.raises(AppError) as exc:
transport.call(
client=_soap_client(),
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
request={"params": {"condition": "x"}}, # 缺 organization
)
assert exc.value.code == "INTEGRATION.INPUT_INVALID"
def test_soap_cdata_terminator_rejected():
"""参数值含 CDATA 终止符 ]]> 时拒绝,防报文被截断。"""
from app.core.errors import AppError
transport = SoapTransport(http_request=lambda *a, **k: None)
with pytest.raises(AppError) as exc:
transport.call(
client=_soap_client(),
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
request={"params": {"organization": "TGHX", "condition": "a]]>b"}},
)
assert exc.value.details.get("reason") == "soap_cdata_terminator_in_params"
def test_soap_fail_closed_without_body_template():
"""endpoint 存在但缺 soap.body_template → 仍 fail-closed。"""
transport = SoapTransport(http_request=lambda *a, **k: None)
with pytest.raises(TransportNotFrozenError):
transport.call(
client=_soap_client(),
interface={"request_spec_json": {"soap": {}}},
request={"params": {}},
)
def test_soap_fault_maps_to_business_failed():
"""标准 SOAP Fault → business_failed dict(faultcode/faultstring 透传)。"""
fault = (
'<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">'
'<SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>soap:Client</faultcode>'
'<faultstring>bad request</faultstring></SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope>'
)
transport = SoapTransport(http_request=lambda *a, **k: _resp(200, text=fault))
result = transport.call(
client=_soap_client(),
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
request={"params": {"organization": "TGHX", "condition": "c"}},
)
assert result["status"] == "business_failed"
assert result["message"] == "bad request"
def test_soap_http_error_and_non_xml():
"""HTTP 5xx → business_failed;200 非 XML → technical_failed(与 REST 同语义)。"""
transport = SoapTransport(http_request=lambda *a, **k: _resp(500, text="boom"))
result = transport.call(
client=_soap_client(),
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
request={"params": {"organization": "T", "condition": "c"}},
)
assert result["status"] == "business_failed" and result["code"] == "HTTP_500"
transport = SoapTransport(http_request=lambda *a, **k: _resp(200, text="<html>not soap"))
result = transport.call(
client=_soap_client(),
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
request={"params": {"organization": "T", "condition": "c"}},
)
assert result["status"] == "technical_failed" and result["code"] == "NON_XML"
def test_soap_error_message_masks_credentials():
"""错误回显(可能含请求体)中的凭据值必须替换为 ***,不得进审计/响应。"""
transport = SoapTransport(http_request=lambda *a, **k: _resp(500, text='echo: password="p1" failed'))
result = transport.call(
client=_soap_client(),
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
request={"params": {"organization": "T", "condition": "c"}},
)
assert result["message"] == 'echo: password="***" failed'
assert "p1" not in result["message"]
def test_soap_params_cannot_shadow_credentials():
"""请求参数不得冒充 credential_* 占位符值(凭据注入永远后写覆盖)。"""
captured = {}
def fake_http(method, url, **kw):
captured.update(data=kw.get("data"))
return _resp(200, text=_SOAP_RESPONSE)
SoapTransport(http_request=fake_http).call(
client=_soap_client(),
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
request={"params": {"organization": "T", "condition": "c", "credential_password": "evil"}},
)
assert 'password="p1"' in captured["data"].decode("utf-8")
assert "evil" not in captured["data"].decode("utf-8")
def test_soap_action_header_sent_when_configured():
"""soap.action 非空时写入 SOAPAction 头。"""
captured = {}
def fake_http(method, url, **kw):
captured.update(headers=kw.get("headers"))
return _resp(200, text=_SOAP_RESPONSE)
SoapTransport(http_request=fake_http).call(
client=_soap_client(),
interface={"request_spec_json": {"soap": {"action": "urn:GetItemStockList", "body_template": _SOAP_TEMPLATE}}},
request={"params": {"organization": "T", "condition": "c"}},
)
assert captured["headers"]["SOAPAction"] == '"urn:GetItemStockList"' # 按规范带引号
# ---- 连接测试探针(probe):只证明网络/服务可达,不做业务调用 ----
_WSDL = (
'<?xml version="1.0" encoding="utf-8"?>'
'<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" targetNamespace="urn:t">'
'</wsdl:definitions>'
)
def test_rest_probe_reachable_on_any_http_response():
"""REST probe:任意 HTTP 响应(含 404)都证明 endpoint 网络可达。"""
captured = {}
def fake_http(method, url, **kw):
captured.update(method=method, url=url)
return _resp(404, text="not found")
result = RestTransport(http_request=fake_http).probe(client=_client())
assert captured["method"] == "GET"
assert captured["url"] == "https://erp.invalid"
assert result["ok"] is True
assert result["code"] == "HTTP_404"
def test_rest_probe_connection_failure_not_ok_and_masked():
"""REST probe:连接异常 → ok=False,异常回显中凭据值脱敏。"""
def fake_http(method, url, **kw):
raise ConnectionError('connect failed with password="p1"')
probe_client = _client()
probe_client["credential"] = {"password": "p1"}
result = RestTransport(http_request=fake_http).probe(client=probe_client)
assert result["ok"] is False
assert result["code"] == "CONNECTION_FAILED"
assert "p1" not in result["message"]
def test_rest_probe_fail_closed_without_endpoint():
"""REST probe:endpoint 未冻结时同样 fail-closed。"""
transport = RestTransport(http_request=lambda *a, **k: None)
with pytest.raises(TransportNotFrozenError):
transport.probe(client={"config_json": {}})
def test_soap_probe_wsdl_and_envelope_reachable():
"""SOAP probe:WSDL(definitions)与直连服务端点(Envelope)根元素均算可达。"""
captured = {}
def fake_http(method, url, **kw):
captured.update(method=method, url=url)
return _resp(200, text=_WSDL)
result = SoapTransport(http_request=fake_http).probe(client=_soap_client())
assert captured["method"] == "GET"
# 裸服务端点自动补 ?wsdl:SOAP 端点对裸 GET 常返回 404/405/501
assert captured["url"] == "https://erp.invalid/ws?wsdl"
assert result["ok"] is True
envelope = (
'<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">'
'<SOAP-ENV:Body/></SOAP-ENV:Envelope>'
)
ok_envelope = SoapTransport(http_request=lambda *a, **k: _resp(200, text=envelope))
assert ok_envelope.probe(client=_soap_client())["ok"] is True
def test_soap_probe_keeps_existing_query():
"""SOAP probe:endpoint 已带 query(如 ?wsdl)时按原地址探测,不重复追加。"""
captured = {}
def fake_http(method, url, **kw):
captured.update(url=url)
return _resp(200, text=_WSDL)
result = SoapTransport(http_request=fake_http).probe(
client=_soap_client(endpoint="https://erp.invalid/web/ws/r/aws_ttsrv2?wsdl"),
)
assert captured["url"] == "https://erp.invalid/web/ws/r/aws_ttsrv2?wsdl"
assert result["ok"] is True
def test_soap_probe_failure_paths():
"""SOAP probe:HTTP 错误/非 XML/根元素不符/连接异常 → ok=False;缺 wsdl fail-closed。"""
http_error = SoapTransport(http_request=lambda *a, **k: _resp(500, text="boom"))
result = http_error.probe(client=_soap_client())
assert result["ok"] is False and result["code"] == "HTTP_500"
not_xml = SoapTransport(http_request=lambda *a, **k: _resp(200, text="<html>broken"))
assert not_xml.probe(client=_soap_client())["code"] == "NON_XML"
wrong_root = SoapTransport(http_request=lambda *a, **k: _resp(200, text="<html></html>"))
assert wrong_root.probe(client=_soap_client())["code"] == "NOT_WSDL"
def unreachable(method, url, **kw):
raise ConnectionError("connection refused")
assert SoapTransport(http_request=unreachable).probe(client=_soap_client())["ok"] is False
with pytest.raises(TransportNotFrozenError):
SoapTransport().probe(client={"config_json": {}})
@@ -2,9 +2,9 @@
| 项目 | 说明 | | 项目 | 说明 |
| --- | --- | | --- | --- |
| 文档版本 | v1.0(首期最小可行设计) | | 文档版本 | v1.1(P0 内核已实现:REST/SOAP 传输、参数映射、凭据 db/env 双模;版本行冻结/分片/WSDL 导入/发布门禁待后续) |
| 日期 | 2026-08-27 | | 日期 | 2026-09-21(v1.0:2026-08-27) |
| 状态 | 设计评审中(未实现) | | 状态 | P0 已实现并交付首个消费者(在途调拨 query_inventory);§7C/§7E/§7F/§9.4 与版本行冻结为后续阶段 |
| 读者 | 平台研发、后端、前端、Agent/集成负责人、ERP/RPA 管理员 | | 读者 | 平台研发、后端、前端、Agent/集成负责人、ERP/RPA 管理员 |
| 关联文档 | [企业集成中心蓝图(完整愿景)](enterprise-integration-center-prototype.md) | | 关联文档 | [企业集成中心蓝图(完整愿景)](enterprise-integration-center-prototype.md) |
| 首个消费者 | 在途仓自动调拨(`in_transit_transfer`) | | 首个消费者 | 在途仓自动调拨(`in_transit_transfer`) |
@@ -23,13 +23,13 @@
## 1. 背景与问题 ## 1. 背景与问题
### 1.1 现状 ### 1.1 现状(2026-09-22 更新:调拨域已完成切换)
在途仓自动调拨当前把 ERP 访问**写死**在代码里: 在途仓自动调拨早期把外部系统访问**写死**在代码里(旧 `erp_adapter.py` / `gateway_adapter.py` 已删除):
- `app/services/in_transit_transfer/erp_adapter.py` 的 `SoapErpTransport` 是唯一传输层,`query_inventory` / `create_transfer` / `verify_duplicate` 三个操作硬编码; - ~~`app/services/in_transit_transfer/erp_adapter.py` 的 `SoapErpTransport` 是唯一传输层~~ 现查询统一走 `capability_client.py::CapabilityClient.query_stock`(组织分组 + 料号/库位/批号元组批量,`external_org` 取自仓库映射),写路径待 Phase 2 接线(fail-closed);
- `app/services/in_transit_transfer/deps.py::_build_erp_adapter()` 固定读取 `IN_TRANSIT_TRANSFER_ERP_*` 配置键并固定构造 SOAP 传输; - ~~`deps.py::_build_erp_adapter()` 固定读取 `IN_TRANSIT_TRANSFER_ERP_*` 配置键~~ 现由 `_build_capability_client()` 装配;`query_inventory` 是首个配置绑定消费者(鼎捷 TOPGP GetItemStockList,SOAP 实测联调通过);
- 没有"按来源/按操作选择哪个外部系统、哪个接口、哪种映射"的注册与路由机制。 - 历史动机:没有"按来源/按操作选择哪个外部系统、哪个接口、哪种映射"的注册与路由机制。
### 1.2 目标 ### 1.2 目标
@@ -85,6 +85,8 @@
> 当前不单独建立 `Connector`、`MessageProfile`、`MappingVersion`、`Fixture` 表,也不把每个 Header、XML 节点或映射字段拆成关系表。接口版本是配置冻结边界:稳定身份、版本、状态、路由、安全和审计字段使用关系列;协议细节、模板、映射和测试引用使用 JSONB。未来只有在出现跨接口复用、独立权限/查询或统计需求时再拆表。 > 当前不单独建立 `Connector`、`MessageProfile`、`MappingVersion`、`Fixture` 表,也不把每个 Header、XML 节点或映射字段拆成关系表。接口版本是配置冻结边界:稳定身份、版本、状态、路由、安全和审计字段使用关系列;协议细节、模板、映射和测试引用使用 JSONB。未来只有在出现跨接口复用、独立权限/查询或统计需求时再拆表。
> **当前实现(2026-09,P1 范围)**:接口定义与客户端实例均带状态/启停字段,且已接入运行时门禁——`resolve_binding` 仅在绑定 `published`、接口定义 `published`、客户端实例 `enabled` 三者同时满足时命中,否则一律 `BindingNotFoundError`(fail-closed)。接口定义与绑定状态只经 `/publish|unpublish|retire|reopen` 动作端点按转移表(draft→published→retired,含撤回与恢复)流转,PUT 不再直接改写状态;绑定发布附加就绪门禁(接口须已发布、客户端须启用,`INTEGRATION.BINDING_TARGET_NOT_READY`),避免发布调用期永不生效的死绑定。接口的连接器类型由所属客户端实例在服务端推导(单一事实源);绑定的客户端与接口在创建/更新时成对校验(接口定义必须属于所选客户端实例,`INTEGRATION.BINDING_PAIR_MISMATCH`)。绑定路由条件统一由 `context_selector_json` 表达(键值对须全部包含于调用上下文才命中;空对象=默认绑定;P1 调用方不传上下文),原 `context_source_code` 快捷列已按过度设计删除(迁移 re1f3a4b5c6d),不设兼容层。凭据引用状态两态化:管理端经行内开关在 active/retired 间切换(`resolve_credential` 只解析 active,停用即断流),`rotating` 不可进入——其现语义等于断供,真实版本化轮换(新旧并存)属 P2;接口定义 `enabled` 冻结忽略传值,可用性只由 status 生命周期表达。版本行冻结、发布后不可变与完整发布门禁(§7F)仍属 P2。
### 3.2 运行时实体(2) ### 3.2 运行时实体(2)
| 实体 | 职责 | | 实体 | 职责 |
@@ -379,6 +381,7 @@ last_verified_at
``` ```
- ClientInstance 引用 `secret_ref`; - ClientInstance 引用 `secret_ref`;
- **已实现的凭据维护双模**:`secret_provider='db'`(管理端默认)——用户名/密码在凭据引用页维护,服务端以 Fernet 主密钥 `INTEGRATION_CREDENTIAL_KEY`(环境注入)加密落库 `secret_ciphertext`,改密免重启,响应只回用户名不回密码/密文;`secret_provider='env'`——兼容模式,只存环境配置键名,真实值由环境注入;
- 切换凭据通过版本更新,**不能覆盖运行中的调用**; - 切换凭据通过版本更新,**不能覆盖运行中的调用**;
- 凭据不回显、不写日志、不进配置快照(复用调拨 `sanitize_snapshot` 思路)。 - 凭据不回显、不写日志、不进配置快照(复用调拨 `sanitize_snapshot` 思路)。
@@ -464,6 +467,7 @@ verify_duplicate # 确认重复 Invoice 对应原单
- 模型:`app/models/integration_connector.py`(ClientInstance / 按版本存储的 InterfaceDefinition / Binding / CredentialReference / IntegrationCall;异步能力启用后再增加 IntegrationAsyncTask) - 模型:`app/models/integration_connector.py`(ClientInstance / 按版本存储的 InterfaceDefinition / Binding / CredentialReference / IntegrationCall;异步能力启用后再增加 IntegrationAsyncTask)
- 服务:`app/services/integration_connector/`(`capability.py` / `binding.py` / `engine.py` / `mapping.py` / `transports/rest.py` / `transports/soap.py` / `descriptors.py` / `security.py`) - 服务:`app/services/integration_connector/`(`capability.py` / `binding.py` / `engine.py` / `mapping.py` / `transports/rest.py` / `transports/soap.py` / `descriptors.py` / `security.py`)
- 域能力声明:`app/services/<domain>/capabilities.py`(如 `in_transit_transfer/capabilities.py`;框架只留注册/校验机制,域契约随域代码版本化,应用组合根每次 `create_app` 幂等注册,2026-09-22 起)
- API:`app/api/integration_connector.py`(Admin CRUD + 能力调用端点 + 工具清单) - API:`app/api/integration_connector.py`(Admin CRUD + 能力调用端点 + 工具清单)
- Admin UI:`frontend/src/features/admin/modules/integration-connector/`(客户端配置作业) - Admin UI:`frontend/src/features/admin/modules/integration-connector/`(客户端配置作业)
- 迁移:Alembic 新迁移,挂在当前 head 后 - 迁移:Alembic 新迁移,挂在当前 head 后
@@ -0,0 +1,136 @@
/**
* features/admin/modules/integration-connector/IntegrationConnectorPage.spec.ts
* 用途:锁定凭据引用列表的重设计列——类型/账号/来源/启停开关,以及能力清单 tab 的激活与注册表渲染;
* 不再出现内部实现列(secret_ref 原文)与无行动价值的「更新时间」列。
* 依赖:vi.mock(useIntegrationConnectorAdmin)、@vue/test-utils、i18n。
* 逻辑:mock composable 返回固定 fixture(password 账密 + token 两条),断言
* 列表按类型标签/非密账号/来源本地化与布尔启停开关渲染。
*/
import { describe, expect, it, vi } from 'vitest';
import { defineComponent, h, ref } from 'vue';
import { mount } from '@vue/test-utils';
import { createMemoryHistory, createRouter } from 'vue-router';
import i18n from '@/i18n';
import IntegrationConnectorPage from './IntegrationConnectorPage.vue';
import { createEmptyBindingForm, createEmptyClientInstanceForm, createEmptyCredentialReferenceForm, createEmptyInterfaceDefinitionForm } from './types/integration-connector.types';
const mockState = vi.hoisted(() => {
const capabilities = [
{ name: 'in_transit_transfer.create_transfer', write: true, idempotency: 'invoice' },
{ name: 'in_transit_transfer.query_inventory', write: false, idempotency: 'none' },
{ name: 'in_transit_transfer.verify_duplicate', write: false, idempotency: 'invoice' },
];
const bindings = [
{
id: 1, capability: 'in_transit_transfer.query_inventory', context_selector_json: {},
client_instance_code: '1001', interface_definition_code: 'IF-A',
mapping_version: 1, priority: 0, environment: 'prod',
effective_from: null, effective_to: null, status: 'published',
},
];
const credentials = [
{
id: 1, code: 'tiptop-erp', secret_ref: 'db:tiptop-erp', secret_provider: 'db',
credential_type: 'password', secret_fields: { username: 'tiptop' }, has_secret: true,
version: 1, status: 'active', updated_at: '2026-09-21T18:30:00', last_verified_at: null,
},
{
id: 2, code: 'wms-token', secret_ref: 'db:wms-token', secret_provider: 'env',
credential_type: 'token', secret_fields: {}, has_secret: true,
version: 1, status: 'rotating', updated_at: null, last_verified_at: null,
},
];
const noop = () => vi.fn();
return { credentials, capabilities, bindings };
});
vi.mock('./composables/useIntegrationConnectorAdmin', () => ({
useIntegrationConnectorAdmin: () => ({
clients: ref([]), interfaces: ref([]), bindings: ref(mockState.bindings),
credentials: ref(mockState.credentials), capabilities: ref(mockState.capabilities), credentialTypes: ref([]),
isLoading: ref(false), activeEntity: ref('credential'), showFormModal: ref(false), isSaving: ref(false),
clientForm: ref(createEmptyClientInstanceForm()),
interfaceForm: ref(createEmptyInterfaceDefinitionForm()),
bindingForm: ref(createEmptyBindingForm()),
credentialForm: ref(createEmptyCredentialReferenceForm()),
showCallModal: ref(false), callCapability: ref(''), callParamsText: ref(''), callContextText: ref(''),
callResult: ref(null), callBusy: ref(false),
testingClientCode: ref(''), testResultText: ref(''),
lifecycleBusy: ref(false),
loadAll: vi.fn(), openCreateModal: vi.fn(), openEditModal: vi.fn(), closeFormModal: vi.fn(),
saveActive: vi.fn(), testConnection: vi.fn(), openCallModal: vi.fn(), closeCallModal: vi.fn(),
runCall: vi.fn(), deleteClient: vi.fn(), toggleClient: vi.fn(), toggleCredential: vi.fn(),
changeInterfaceLifecycle: vi.fn(), changeBindingLifecycle: vi.fn(),
}),
}));
function mountPage() {
const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/:pathMatch(.*)*', component: { template: '<div/>' } }] });
const Harness = defineComponent({
setup() {
return () => h('div', { style: 'width: 1400px' }, [h(IntegrationConnectorPage)]);
},
});
return mount(Harness, { global: { plugins: [i18n, router] } });
}
describe('IntegrationConnectorPage credential list', () => {
it('按重设计列渲染:类型徽标 + 非密账号 + 来源徽标 + 启停开关,不再显示 secret_ref 原文', () => {
const wrapper = mountPage();
const text = wrapper.text();
// password 类型:类型标签 + 非密账号(username 值)+ 来源本地化;状态不走文字(开关 + 悬停提示)
expect(text).toContain('tiptop-erp');
expect(text).toContain('账密');
expect(text).toContain('tiptop');
expect(text).toContain('界面维护(加密保存)');
// token 类型:非密字段为空显示占位;env 来源显示 Secret 键名
expect(text).toContain('wms-token');
expect(text).toContain('令牌');
// 内部实现列不再出现:db: 前缀的 secret_ref 原文不渲染
expect(wrapper.findAll('td').some((td) => td.text() === 'db:tiptop-erp')).toBe(false);
// 「更新时间」列已移除:updated_at 只是行保存时间,非最后轮换/验证时间,无行动价值
expect(text).not.toContain('2026-09-21 18:30');
expect(text).not.toContain('更新时间');
// 布尔启停走行内开关(与客户端实例一致),开关后不带状态文字,精确状态走悬停提示
expect(wrapper.findAll('[data-testid="credential-status-toggle"]').length).toBe(2);
expect(wrapper.find('[data-testid="credential-status"]').exists()).toBe(false);
expect(text).not.toContain('启用中');
expect(text).not.toContain('轮换中');
// 表头与客户端实例一致为「启用」(布尔开关列);「状态」留给接口/绑定的多状态徽章列
expect(wrapper.findAll('th').some((th) => th.text() === '启用')).toBe(true);
});
it('能力清单 tab 可激活:渲染注册能力(写/幂等)与调用入口,新增按钮隐藏', async () => {
const wrapper = mountPage();
const capTab = wrapper.findAll('[role="tab"]').find((b) => b.text() === '能力清单')!;
await capTab.trigger('click');
// tab 进入选中态(此前 selectTab 对 capability 直接 return,点击无效)
expect(capTab.attributes('aria-selected')).toBe('true');
const text = wrapper.text();
// 中文名称为主行,注册名保留为次行(绑定引用用精确标识)
expect(text).toContain('创建调拨单');
expect(text).toContain('在途库存查询');
expect(text).toContain('防重校验');
expect(text).toContain('in_transit_transfer.query_inventory');
expect(text).toContain('in_transit_transfer.create_transfer');
// 写入/幂等本地化:不再出现原始 yes/no 与 invoice/none
expect(wrapper.findAll('td').some((td) => td.text() === '是')).toBe(true);
expect(wrapper.findAll('td').some((td) => td.text() === '否')).toBe(true);
expect(text).toContain('按单据号幂等');
expect(text).not.toContain('yes');
expect(text).not.toContain('invoice');
// 只读清单:无「新增」入口;每行提供「调用」按钮(打开手动调用弹窗)
expect(wrapper.findAll('button').some((b) => b.text().includes('新增'))).toBe(false);
expect(wrapper.findAll('button').some((b) => b.text().includes('调用'))).toBe(true);
});
it('绑定列表能力列渲染「中文名 + 注册名」两行', async () => {
const wrapper = mountPage();
const bindTab = wrapper.findAll('[role="tab"]').find((b) => b.text() === '绑定')!;
await bindTab.trigger('click');
const text = wrapper.text();
// 能力引用列与客户端/接口引用列同款:中文名主行 + 注册名次行
expect(text).toContain('在途库存查询');
expect(text).toContain('in_transit_transfer.query_inventory');
});
});
@@ -1,28 +1,39 @@
<!-- <!--
features/admin/modules/integration-connector/IntegrationConnectorPage.vue features/admin/modules/integration-connector/IntegrationConnectorPage.vue
用途:集成连接器管理页——四个配置实体(客户端实例/接口定义/绑定/凭据引用)tab 列表 + 用途:集成连接器管理页——四个配置实体(客户端实例/接口定义/绑定/凭据引用)tab 列表 +
能力清单与手动调用测试;创建/编辑弹窗 + 连接测试。 能力清单与手动调用测试;创建/编辑抽屉 + 行内连接测试。
依赖:useIntegrationConnectorAdmin、两个弹窗组件、useI18n。 依赖:useIntegrationConnectorAdmin、抽屉与调用测试弹窗组件、useI18n。
逻辑:按 tab 展示列表与「新增」;配置「绑定」是让自动调拨跑起来的最小闭环核心。 逻辑:按 tab 展示列表与「新增」;客户端列表展示类型/环境徽章、行内启停开关与
连接测试结果(徽章 + 可展开详情);接口定义与绑定列表均以状态徽章 + 生命周期行内
按钮(发布/撤回/退役/恢复,绑定发布由后端就绪门禁校验接口已发布且客户端启用)
驱动状态,表单内状态只读;凭据列表布尔启停走行内开关
(与客户端实例一致,表头同为「启用」,开关不带状态文字,精确状态走悬停提示);
能力清单为只读注册表(能力中文名为主行 + 注册名次行,写入/幂等本地化,未注册翻译兜底原值);
接口/绑定列表的客户端与接口
引用列统一展示「名称 + 编码」两行;类型/环境/状态取值均本地化,
未知值兜底原样显示;配置「绑定」是让自动调拨跑起来的最小闭环核心。
--> -->
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted } from 'vue'; import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { Plus, Edit, Trash2, Plug, PlayCircle } from 'lucide-vue-next'; import { Plus, Edit, Trash2, Plug, PlayCircle } from 'lucide-vue-next';
import IntegrationConnectorFormModal from './components/IntegrationConnectorFormModal.vue'; import IntegrationConnectorFormDrawer from './components/IntegrationConnectorFormDrawer.vue';
import IntegrationCapabilityCallModal from './components/IntegrationCapabilityCallModal.vue'; import IntegrationCapabilityCallModal from './components/IntegrationCapabilityCallModal.vue';
import { CONNECTOR_TYPE_OPTIONS, ENVIRONMENT_OPTIONS } from './types/integration-connector.types';
import { useIntegrationConnectorAdmin } from './composables/useIntegrationConnectorAdmin'; import { useIntegrationConnectorAdmin } from './composables/useIntegrationConnectorAdmin';
const { t } = useI18n(); const { t } = useI18n();
const { const {
clients, interfaces, bindings, credentials, capabilities, clients, interfaces, bindings, credentials, capabilities, credentialTypes,
isLoading, activeEntity, showFormModal, isSaving, isLoading, activeEntity, showFormModal, isSaving,
clientForm, interfaceForm, bindingForm, credentialForm, clientForm, interfaceForm, bindingForm, credentialForm,
showCallModal, callCapability, callParamsText, callContextText, callResult, callBusy, showCallModal, callCapability, callParamsText, callContextText, callResult, callBusy,
testResultText, testingClientCode, testResults,
lifecycleBusy,
loadAll, openCreateModal, openEditModal, closeFormModal, saveActive, loadAll, openCreateModal, openEditModal, closeFormModal, saveActive,
testConnection, openCallModal, closeCallModal, runCall, deleteClient, testConnection, toggleClient, toggleCredential, openCallModal, closeCallModal, runCall, deleteClient,
changeInterfaceLifecycle, changeBindingLifecycle,
} = useIntegrationConnectorAdmin(); } = useIntegrationConnectorAdmin();
onMounted(() => { void loadAll(); }); onMounted(() => { void loadAll(); });
@@ -35,16 +46,110 @@ const tabs: Array<{ key: TabKey; labelKey: string }> = [
{ key: 'credential', labelKey: 'admin.integrationConnector.tabs.credential' }, { key: 'credential', labelKey: 'admin.integrationConnector.tabs.credential' },
{ key: 'capability', labelKey: 'admin.integrationConnector.tabs.capability' }, { key: 'capability', labelKey: 'admin.integrationConnector.tabs.capability' },
]; ];
const activeTab = computed<TabKey>(() => (activeEntity.value === 'credential' ? 'credential' : activeEntity.value)); // 当前激活 tab:页面本地状态(capability 为只读注册表 tab,不属于可编辑实体);
// 初始取 activeEntity,保证携带实体态进入页面时列表与 tab 一致。
const activeTab = ref<TabKey>(activeEntity.value);
const clientOptions = computed(() => clients.value.map((c) => ({ code: c.code, name: c.name }))); /** 客户端选项带 connector_type:接口表单联动展示连接器类型用。 */
const interfaceOptions = computed(() => interfaces.value.map((i) => ({ code: i.code, name: i.name }))); const clientOptions = computed(() => clients.value.map((c) => ({ code: c.code, name: c.name, connector_type: c.connector_type })));
/** 接口选项带 client_instance_code:绑定表单联动带出并锁定客户端实例用。 */
const interfaceOptions = computed(() => interfaces.value.map((i) => ({ code: i.code, name: i.name, client_instance_code: i.client_instance_code })));
const capabilityOptions = computed(() => capabilities.value.map((c) => ({ name: c.name }))); const capabilityOptions = computed(() => capabilities.value.map((c) => ({ name: c.name })));
const credentialOptions = computed(() => credentials.value.map((c) => ({ code: c.code })));
/** 编码 → 名称(列表引用列展示「名称 + 编码」用);编码无对应记录时回退空串,由模板兜底显示编码。 */
function clientNameOf(code: string) {
return clients.value.find((c) => c.code === code)?.name ?? '';
}
function interfaceNameOf(code: string) {
return interfaces.value.find((i) => i.code === code)?.name ?? '';
}
/** 行内展开测试详情的客户端编码(同一时刻至多展开一行)。 */
const expandedTestCode = ref('');
/** 连接器类型本地化标签;未注册类型兜底原样显示(不写死类型集合)。 */
function connectorTypeLabel(value: string) {
const opt = CONNECTOR_TYPE_OPTIONS.find((item) => item.value === value);
return opt ? t(opt.labelKey) : value;
}
/** 环境本地化标签;未知值兜底原样显示。 */
function envLabel(value: string) {
return (ENVIRONMENT_OPTIONS as readonly string[]).includes(value)
? t(`admin.integrationConnector.envLabels.${value}`)
: value;
}
/** 状态本地化标签;未知值兜底原样显示。 */
function statusLabel(value: string) {
return t(`admin.integrationConnector.statusLabels.${value}`, value);
}
/** 能力本地化标签;未注册翻译的能力兜底原值(能力名含点号,i18n 按嵌套路径组织)。 */
function capabilityLabelOf(name: string) {
return t(`admin.integrationConnector.capabilityLabels.${name}`, name);
}
/** 幂等语义本地化标签;未知值兜底原样显示。 */
function idempotencyLabel(value: string) {
return t(`admin.integrationConnector.idempotencyLabels.${value}`, value);
}
/** 凭据来源本地化标签(db=界面维护/加密保存,env=环境注入);与状态共用 statusLabels。 */
function secretProviderLabel(value: string) {
return statusLabel(value);
}
/** 凭据类型本地化标签;未注册类型兜底原样显示(不写死类型集合)。 */
function credentialTypeLabel(value: string) {
return t(`admin.integrationConnector.credentialTypeLabels.${value}`, value);
}
/** 账号列文本:db 模式显示非密字段值(类型定义驱动);env 模式显示 Secret 键名。 */
function credentialAccountText(row: { secret_provider: string; secret_fields: Record<string, string>; secret_ref: string }) {
if (row.secret_provider === 'env') return row.secret_ref;
const values = Object.values(row.secret_fields ?? {}).filter(Boolean);
return values.length ? values.join(' / ') : '—';
}
/** 状态徽标配色:启用中绿 / 轮换中橙 / 其余中性。 */
function statusBadgeClass(value: string) {
if (value === 'active' || value === 'published') return 'bg-emerald-50 text-emerald-700';
if (value === 'rotating') return 'bg-amber-50 text-amber-700';
return 'bg-surface-soft text-secondary';
}
/** 行内测试结果(无结果返回 null,供模板 v-if 使用)。 */
function testResultOf(code: string) {
return testResults.value[code] ?? null;
}
/** 测试徽章配色:成功绿 / 失败红。 */
function testBadgeClass(code: string) {
return testResultOf(code)?.ok
? 'bg-green-100 text-green-700 hover:bg-green-200'
: 'bg-red-100 text-red-700 hover:bg-red-200';
}
/** 测试徽章文案。 */
function testBadgeText(code: string) {
return testResultOf(code)?.ok
? t('admin.integrationConnector.testOkBadge')
: t('admin.integrationConnector.testFailBadge');
}
/** 展开行详情文本:原因码 · 脱敏消息。 */
function testDetailText(code: string) {
const r = testResultOf(code);
if (!r) return '';
return r.message ? `${r.code} · ${r.message}` : r.code;
}
function selectTab(key: TabKey) { function selectTab(key: TabKey) {
// capability tab 只读展示,不进入表单实体;其余映射到可编辑实体。 activeTab.value = key;
if (key === 'capability') return; // capability tab 只读展示注册表(无新增/表单入口),activeEntity 保持最后一个可编辑实体供抽屉复用。
activeEntity.value = key; if (key !== 'capability') activeEntity.value = key;
} }
</script> </script>
@@ -91,40 +196,92 @@ function selectTab(key: TabKey) {
<table class="admin-table"> <table class="admin-table">
<thead> <thead>
<tr> <tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.connectorType') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.connectorType') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.environment') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.environment') }}</th>
<th class="px-6 py-4 text-right text-xs w-40">{{ t('admin.integrationConnector.headers.actions') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.endpoint') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.fields.enabled') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.testStatus') }}</th>
<th class="px-6 py-4 text-right text-xs w-36">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr v-if="clients.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr> <tr v-if="clients.length === 0"><td colspan="7" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in clients" :key="row.code"> <template v-for="row in clients" :key="row.code">
<td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td> <tr>
<td class="px-6 py-4 text-sm text-secondary">{{ row.name }}</td> <td class="px-6 py-4">
<td class="px-6 py-4 text-sm text-secondary">{{ row.connector_type }}</td> <p class="text-sm font-medium text-primary">{{ row.name }}</p>
<td class="px-6 py-4 text-sm text-secondary">{{ row.environment }}</td> <p class="text-xs text-muted mono mt-0.5">{{ row.code }}</p>
<td class="px-6 py-4 text-right"> </td>
<div class="inline-flex items-center gap-1"> <td class="px-6 py-4">
<button type="button" class="p-2 rounded-lg text-muted hover:bg-brand-50 hover:text-brand-600" :title="t('admin.integrationConnector.test')" @click="testConnection(row.code)"> <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-surface-soft text-secondary">{{ connectorTypeLabel(row.connector_type) }}</span>
<Plug class="w-4 h-4" /> </td>
<td class="px-6 py-4">
<span
class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium"
:class="row.environment === 'prod' ? 'bg-green-100 text-green-700' : row.environment === 'test' ? 'bg-amber-100 text-amber-700' : 'bg-surface-soft text-secondary'"
>{{ envLabel(row.environment) }}</span>
</td>
<td class="px-6 py-4 max-w-[240px]">
<span v-if="row.endpoint" class="block truncate text-xs font-mono text-secondary" :title="row.endpoint">{{ row.endpoint }}</span>
<span v-else class="text-xs text-muted">—</span>
</td>
<td class="px-6 py-4">
<button
type="button"
role="switch"
:aria-checked="row.enabled"
:title="t('admin.integrationConnector.fields.enabled')"
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors"
:class="row.enabled ? 'bg-brand-600' : 'bg-slate-300'"
data-testid="client-toggle"
:disabled="lifecycleBusy"
@click="toggleClient(row)"
>
<span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform" :class="row.enabled ? 'translate-x-4' : 'translate-x-0.5'" />
</button> </button>
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('client', row)"> </td>
<Edit class="w-4 h-4" /> <td class="px-6 py-4">
<span v-if="testingClientCode === row.code" class="text-xs text-muted">{{ t('admin.integrationConnector.msg.testing') }}</span>
<button
v-else-if="testResultOf(row.code)"
type="button"
class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium"
:class="testBadgeClass(row.code)"
:title="t('admin.integrationConnector.testDetailToggle')"
data-testid="client-test-badge"
@click="expandedTestCode = expandedTestCode === row.code ? '' : row.code"
>
{{ testBadgeText(row.code) }}
</button> </button>
<button type="button" class="p-2 rounded-lg text-muted hover:bg-red-50 hover:text-red-600" :title="t('admin.delete')" @click="deleteClient(row.code)"> <span v-else class="text-xs text-muted">—</span>
<Trash2 class="w-4 h-4" /> </td>
</button> <td class="px-6 py-4 text-right">
</div> <div class="inline-flex items-center gap-1">
</td> <button type="button" class="p-2 rounded-lg text-muted hover:bg-brand-50 hover:text-brand-600" :title="t('admin.integrationConnector.test')" @click="testConnection(row.code)">
</tr> <Plug class="w-4 h-4" />
</button>
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('client', row)">
<Edit class="w-4 h-4" />
</button>
<button type="button" class="p-2 rounded-lg text-muted hover:bg-red-50 hover:text-red-600" :title="t('admin.delete')" @click="deleteClient(row)">
<Trash2 class="w-4 h-4" />
</button>
</div>
</td>
</tr>
<!-- 测试详情展开行:原因码 + 脱敏消息 -->
<tr v-if="expandedTestCode === row.code && testResultOf(row.code)">
<td colspan="7" class="px-6 py-3 bg-surface-soft" data-testid="client-test-detail">
<p class="text-xs font-mono text-secondary break-all">{{ testDetailText(row.code) }}</p>
</td>
</tr>
</template>
</tbody> </tbody>
</table> </table>
<p v-if="testResultText" class="mt-3 rounded-lg bg-surface-soft p-3 text-xs font-mono text-secondary whitespace-pre-wrap break-all">{{ testResultText }}</p>
</div> </div>
<!-- 接口定义 --> <!-- 接口定义:状态徽章 + 生命周期行内按钮(发布/撤回/退役/恢复,后端转移表校验) -->
<div v-else-if="activeTab === 'interface'" class="admin-table-wrap"> <div v-else-if="activeTab === 'interface'" class="admin-table-wrap">
<table class="admin-table"> <table class="admin-table">
<thead> <thead>
@@ -132,8 +289,8 @@ function selectTab(key: TabKey) {
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.name') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.clientInstance') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.clientInstance') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.status') }}</th> <th class="px-6 py-4 text-left text-xs w-28">{{ t('admin.integrationConnector.headers.status') }}</th>
<th class="px-6 py-4 text-right text-xs w-24">{{ t('admin.integrationConnector.headers.actions') }}</th> <th class="px-6 py-4 text-right text-xs w-48">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -141,10 +298,48 @@ function selectTab(key: TabKey) {
<tr v-for="row in interfaces" :key="row.code"> <tr v-for="row in interfaces" :key="row.code">
<td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td> <td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.name }}</td> <td class="px-6 py-4 text-sm text-secondary">{{ row.name }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.client_instance_code }}</td> <td class="px-6 py-4">
<td class="px-6 py-4 text-sm text-secondary">{{ row.status }}</td> <p class="text-sm text-primary">{{ clientNameOf(row.client_instance_code) || row.client_instance_code }}</p>
<p class="text-xs text-muted mono mt-0.5">{{ row.client_instance_code }}</p>
</td>
<td class="px-6 py-4">
<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium" :class="statusBadgeClass(row.status)" data-testid="interface-status">{{ statusLabel(row.status) }}</span>
</td>
<td class="px-6 py-4 text-right"> <td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1"> <div class="inline-flex items-center gap-1">
<!-- 生命周期按钮按当前状态显隐:draft→发布;published→撤回+退役;retired→恢复;按钮不换行防窄列折字 -->
<button
v-if="row.status === 'draft'"
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-brand-600 hover:bg-brand-50 disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="interface-publish"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row, 'publish')"
>{{ t('admin.integrationConnector.lifecycle.publish') }}</button>
<template v-else-if="row.status === 'published'">
<button
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-secondary hover:bg-surface-soft disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="interface-unpublish"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row, 'unpublish')"
>{{ t('admin.integrationConnector.lifecycle.unpublish') }}</button>
<button
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-amber-600 hover:bg-amber-50 disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="interface-retire"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row, 'retire')"
>{{ t('admin.integrationConnector.lifecycle.retire') }}</button>
</template>
<button
v-else-if="row.status === 'retired'"
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-secondary hover:bg-surface-soft disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="interface-reopen"
:disabled="lifecycleBusy"
@click="changeInterfaceLifecycle(row, 'reopen')"
>{{ t('admin.integrationConnector.lifecycle.reopen') }}</button>
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('interface', row)"> <button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('interface', row)">
<Edit class="w-4 h-4" /> <Edit class="w-4 h-4" />
</button> </button>
@@ -155,7 +350,7 @@ function selectTab(key: TabKey) {
</table> </table>
</div> </div>
<!-- 绑定 --> <!-- 绑定:状态徽章 + 生命周期行内按钮(发布/撤回/退役/恢复,后端转移表 + 发布就绪门禁校验) -->
<div v-else-if="activeTab === 'binding'" class="admin-table-wrap"> <div v-else-if="activeTab === 'binding'" class="admin-table-wrap">
<table class="admin-table"> <table class="admin-table">
<thead> <thead>
@@ -163,19 +358,64 @@ function selectTab(key: TabKey) {
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.capability') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.capability') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.clientInstance') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.clientInstance') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.interfaceDef') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.interfaceDef') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.status') }}</th> <th class="px-6 py-4 text-left text-xs w-28">{{ t('admin.integrationConnector.headers.status') }}</th>
<th class="px-6 py-4 text-right text-xs w-24">{{ t('admin.integrationConnector.headers.actions') }}</th> <th class="px-6 py-4 text-right text-xs w-48">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr v-if="bindings.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr> <tr v-if="bindings.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in bindings" :key="row.id"> <tr v-for="row in bindings" :key="row.id">
<td class="px-6 py-4 text-sm font-medium text-primary">{{ row.capability }}</td> <!-- 能力引用列与客户端/接口引用列同款「名称 + 编码」两行;无中文翻译时只显注册名避免重复 -->
<td class="px-6 py-4 text-sm text-secondary">{{ row.client_instance_code }}</td> <td class="px-6 py-4">
<td class="px-6 py-4 text-sm text-secondary">{{ row.interface_definition_code }}</td> <p class="text-sm text-primary">{{ capabilityLabelOf(row.capability) }}</p>
<td class="px-6 py-4 text-sm text-secondary">{{ row.status }}</td> <p v-if="capabilityLabelOf(row.capability) !== row.capability" class="text-xs text-muted mono mt-0.5">{{ row.capability }}</p>
</td>
<td class="px-6 py-4">
<p class="text-sm text-primary">{{ clientNameOf(row.client_instance_code) || row.client_instance_code }}</p>
<p class="text-xs text-muted mono mt-0.5">{{ row.client_instance_code }}</p>
</td>
<td class="px-6 py-4">
<p class="text-sm text-primary">{{ interfaceNameOf(row.interface_definition_code) || row.interface_definition_code }}</p>
<p class="text-xs text-muted mono mt-0.5">{{ row.interface_definition_code }}</p>
</td>
<td class="px-6 py-4">
<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium" :class="statusBadgeClass(row.status)" data-testid="binding-status">{{ statusLabel(row.status) }}</span>
</td>
<td class="px-6 py-4 text-right"> <td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1"> <div class="inline-flex items-center gap-1">
<!-- 生命周期按钮按当前状态显隐:draft→发布;published→撤回+退役;retired→恢复;按钮不换行防窄列折字 -->
<button
v-if="row.status === 'draft'"
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-brand-600 hover:bg-brand-50 disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="binding-publish"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row, 'publish')"
>{{ t('admin.integrationConnector.lifecycle.publish') }}</button>
<template v-else-if="row.status === 'published'">
<button
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-secondary hover:bg-surface-soft disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="binding-unpublish"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row, 'unpublish')"
>{{ t('admin.integrationConnector.lifecycle.unpublish') }}</button>
<button
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-amber-600 hover:bg-amber-50 disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="binding-retire"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row, 'retire')"
>{{ t('admin.integrationConnector.lifecycle.retire') }}</button>
</template>
<button
v-else-if="row.status === 'retired'"
type="button"
class="whitespace-nowrap px-2 py-1 rounded-md text-xs font-medium text-secondary hover:bg-surface-soft disabled:opacity-50 disabled:cursor-not-allowed"
data-testid="binding-reopen"
:disabled="lifecycleBusy"
@click="changeBindingLifecycle(row, 'reopen')"
>{{ t('admin.integrationConnector.lifecycle.reopen') }}</button>
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('binding', row)"> <button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('binding', row)">
<Edit class="w-4 h-4" /> <Edit class="w-4 h-4" />
</button> </button>
@@ -192,19 +432,40 @@ function selectTab(key: TabKey) {
<thead> <thead>
<tr> <tr>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.code') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.secretRef') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.connectorType') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.account') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.secretProvider') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.secretProvider') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.status') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.fields.enabled') }}</th>
<th class="px-6 py-4 text-right text-xs w-24">{{ t('admin.integrationConnector.headers.actions') }}</th> <th class="px-6 py-4 text-right text-xs w-32">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr v-if="credentials.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr> <tr v-if="credentials.length === 0"><td colspan="6" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in credentials" :key="row.code"> <tr v-for="row in credentials" :key="row.code">
<td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td> <td class="px-6 py-4 text-sm font-medium text-primary mono">{{ row.code }}</td>
<td class="px-6 py-4 text-sm text-secondary mono">{{ row.secret_ref }}</td> <td class="px-6 py-4 text-sm">
<td class="px-6 py-4 text-sm text-secondary">{{ row.secret_provider }}</td> <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-surface-soft text-secondary">{{ credentialTypeLabel(row.credential_type) }}</span>
<td class="px-6 py-4 text-sm text-secondary">{{ row.status }}</td> </td>
<td class="px-6 py-4 text-sm text-secondary mono">{{ credentialAccountText(row) }}</td>
<td class="px-6 py-4 text-sm">
<span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium bg-surface-soft text-secondary" :title="row.secret_provider === 'db' ? statusLabel('db') : row.secret_ref">{{ secretProviderLabel(row.secret_provider) }}</span>
</td>
<td class="px-6 py-4">
<!-- 行内启停开关:布尔语义,与客户端实例开关完全同款(含 title 用同一 i18n 键);rotating 视为启用侧,点击即停用;解析层只认 active,停用即断流 -->
<button
type="button"
role="switch"
:aria-checked="row.status !== 'retired'"
:title="t('admin.integrationConnector.fields.enabled')"
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors"
:class="row.status !== 'retired' ? 'bg-brand-600' : 'bg-slate-300'"
data-testid="credential-status-toggle"
:disabled="lifecycleBusy"
@click="toggleCredential(row)"
>
<span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform" :class="row.status !== 'retired' ? 'translate-x-4' : 'translate-x-0.5'" />
</button>
</td>
<td class="px-6 py-4 text-right"> <td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1"> <div class="inline-flex items-center gap-1">
<button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('credential', row)"> <button type="button" class="p-2 rounded-lg text-muted hover:bg-surface-soft hover:text-secondary" :title="t('admin.edit')" @click="openEditModal('credential', row)">
@@ -231,9 +492,13 @@ function selectTab(key: TabKey) {
<tbody> <tbody>
<tr v-if="capabilities.length === 0"><td colspan="4" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr> <tr v-if="capabilities.length === 0"><td colspan="4" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in capabilities" :key="row.name"> <tr v-for="row in capabilities" :key="row.name">
<td class="px-6 py-4 text-sm font-medium text-primary">{{ row.name }}</td> <!-- 中文名称为主行,注册名作为精确标识(绑定引用用)保留为次行;无中文翻译时只显注册名避免重复 -->
<td class="px-6 py-4 text-sm text-secondary">{{ row.write ? 'yes' : 'no' }}</td> <td class="px-6 py-4">
<td class="px-6 py-4 text-sm text-secondary">{{ row.idempotency }}</td> <p class="text-sm font-medium text-primary">{{ capabilityLabelOf(row.name) }}</p>
<p v-if="capabilityLabelOf(row.name) !== row.name" class="text-xs text-muted mono mt-0.5">{{ row.name }}</p>
</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.write ? t('admin.integrationConnector.writeLabels.yes') : t('admin.integrationConnector.writeLabels.no') }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ idempotencyLabel(row.idempotency) }}</td>
<td class="px-6 py-4 text-right"> <td class="px-6 py-4 text-right">
<button type="button" class="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-medium text-brand-600 hover:bg-brand-50" @click="openCallModal(row.name)"> <button type="button" class="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-medium text-brand-600 hover:bg-brand-50" @click="openCallModal(row.name)">
<PlayCircle class="w-4 h-4" /> <PlayCircle class="w-4 h-4" />
@@ -246,7 +511,7 @@ function selectTab(key: TabKey) {
</div> </div>
</template> </template>
<IntegrationConnectorFormModal <IntegrationConnectorFormDrawer
:visible="showFormModal" :visible="showFormModal"
:active-entity="activeEntity" :active-entity="activeEntity"
:client-form="clientForm" :client-form="clientForm"
@@ -257,6 +522,8 @@ function selectTab(key: TabKey) {
:client-options="clientOptions" :client-options="clientOptions"
:interface-options="interfaceOptions" :interface-options="interfaceOptions"
:capability-options="capabilityOptions" :capability-options="capabilityOptions"
:credential-type-options="credentialTypes"
:credential-options="credentialOptions"
@close="closeFormModal" @close="closeFormModal"
@save="saveActive" @save="saveActive"
/> />
@@ -13,6 +13,7 @@ import type {
IntegrationCapabilityRow, IntegrationCapabilityRow,
IntegrationClientInstanceRow, IntegrationClientInstanceRow,
IntegrationCredentialReferenceRow, IntegrationCredentialReferenceRow,
IntegrationCredentialTypeSpec,
IntegrationInterfaceDefinitionRow, IntegrationInterfaceDefinitionRow,
} from '../types/integration-connector.types'; } from '../types/integration-connector.types';
@@ -74,6 +75,13 @@ export const updateIntegrationInterfaceDefinition = (code: string, payload: Reco
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload), method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
}); });
/** 接口定义生命周期动作(publish/unpublish/retire/reopen);状态只能经此流转。 */
export const changeIntegrationInterfaceLifecycle = (code: string, action: 'publish' | 'unpublish' | 'retire' | 'reopen') =>
requestJson<IntegrationInterfaceDefinitionRow>(
`${BASE}/interface-definitions/${encodeURIComponent(code)}/${action}`,
{ method: 'POST', ...jsonAuth(), body: JSON.stringify({}) },
);
// ---- 绑定 ---- // ---- 绑定 ----
export const listIntegrationBindings = () => export const listIntegrationBindings = () =>
@@ -89,11 +97,21 @@ export const updateIntegrationBinding = (id: number, payload: Record<string, unk
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload), method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
}); });
/** 绑定生命周期动作(publish/unpublish/retire/reopen);状态只能经此流转。 */
export const changeIntegrationBindingLifecycle = (id: number, action: 'publish' | 'unpublish' | 'retire' | 'reopen') =>
requestJson<IntegrationBindingRow>(
`${BASE}/bindings/${id}/${action}`,
{ method: 'POST', ...jsonAuth(), body: JSON.stringify({}) },
);
// ---- 凭据引用 ---- // ---- 凭据引用 ----
export const listIntegrationCredentialReferences = () => export const listIntegrationCredentialReferences = () =>
requestJson<IntegrationCredentialReferenceRow[]>(`${BASE}/credential-references`, auth()); requestJson<IntegrationCredentialReferenceRow[]>(`${BASE}/credential-references`, auth());
export const listIntegrationCredentialTypes = () =>
requestJson<IntegrationCredentialTypeSpec[]>(`${BASE}/credential-references/types`, auth());
export const createIntegrationCredentialReference = (payload: Record<string, unknown>) => export const createIntegrationCredentialReference = (payload: Record<string, unknown>) =>
requestJson<IntegrationCredentialReferenceRow>(`${BASE}/credential-references`, { requestJson<IntegrationCredentialReferenceRow>(`${BASE}/credential-references`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload), method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
@@ -0,0 +1,410 @@
/**
* features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.spec.ts
* 用途:锁定表单按连接器类型动态显示字段——REST 显示超时/HTTP方法/请求路径,
* SOAP 显示 WSDL;以及抽屉化后的 JSON 编辑字段(格式化/失焦校验)、
* 脏检查关闭确认与 Esc 关闭行为。
* 依赖:@vue/test-utils、vitest、i18n。
* 逻辑:切换 connector_type 断言字段可见性;对 JsonTextareaField 断言格式化改写
* 与非法 JSON 提示;mock window.confirm 断言脏表单关闭拦截与放行。
*/
import { mount, enableAutoUnmount } from '@vue/test-utils';
import { afterEach, describe, expect, it, vi } from 'vitest';
import i18n from '@/i18n';
import IntegrationConnectorFormDrawer from './IntegrationConnectorFormDrawer.vue';
import JsonTextareaField from './JsonTextareaField.vue';
import {
createEmptyClientInstanceForm,
createEmptyInterfaceDefinitionForm,
createEmptyBindingForm,
createEmptyCredentialReferenceForm,
type InterfaceDefinitionFormState,
} from '../types/integration-connector.types';
enableAutoUnmount(afterEach);
function mountDrawer(overrides: Partial<Record<string, unknown>> = {}) {
return mount(IntegrationConnectorFormDrawer, {
props: {
visible: true,
activeEntity: 'client',
clientForm: createEmptyClientInstanceForm(),
interfaceForm: createEmptyInterfaceDefinitionForm(),
bindingForm: createEmptyBindingForm(),
credentialForm: createEmptyCredentialReferenceForm(),
isSaving: false,
clientOptions: [],
interfaceOptions: [],
capabilityOptions: [],
credentialTypeOptions: [
{ type: 'password', fields: [
{ key: 'username', secret: false, required: true },
{ key: 'password', secret: true, required: true },
] },
{ type: 'token', fields: [{ key: 'token', secret: true, required: true }] },
],
...overrides,
},
global: { plugins: [i18n] },
});
}
describe('IntegrationConnectorFormDrawer connector-type fields', () => {
it('REST 默认显示接口地址与超时字段', () => {
const wrapper = mountDrawer();
expect(wrapper.find('[data-testid="client-endpoint"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="client-timeout"]').exists()).toBe(true);
});
it('切换到 SOAP 后连接地址 label 变为 WSDL,超时仍显示;同一 endpoint 字段', async () => {
const wrapper = mountDrawer();
await wrapper.find('[data-testid="client-connector-type"]').setValue('soap');
await wrapper.vm.$nextTick();
// 连接地址仍是同一 client-endpoint 字段,仅 label 变 WSDL
expect(wrapper.find('[data-testid="client-endpoint"]').exists()).toBe(true);
// 超时在 SOAP 下也显示
expect(wrapper.find('[data-testid="client-timeout"]').exists()).toBe(true);
const labels = wrapper.findAll('label').map((l) => l.text());
expect(labels.some((t) => t.includes('WSDL'))).toBe(true);
});
it('接口定义 REST 显示 HTTP 方法与请求路径', () => {
const wrapper = mountDrawer({ activeEntity: 'interface' });
const labels = wrapper.findAll('label').map((l) => l.text());
expect(labels.some((t) => t.includes('HTTP 方法'))).toBe(true);
expect(labels.some((t) => t.includes('请求路径'))).toBe(true);
});
it('接口定义:选客户端实例后编码自动建议为「客户端编码-名称slug」,连接器类型为同款禁用下拉随客户端联动', async () => {
const interfaceForm = createEmptyInterfaceDefinitionForm();
interfaceForm.name = '鼎捷TOPGP库存查询GetItemStockList';
const wrapper = mountDrawer({
activeEntity: 'interface',
interfaceForm,
clientOptions: [{ code: '1001', name: '鼎捷TOPGP', connector_type: 'soap' }],
});
await wrapper.find('[data-testid="interface-client"]').setValue('1001');
// 编码留空 → 按客户端编码 + 名称 slug 自动建议
expect(interfaceForm.code).toBe('1001-topgp-getitemstocklist');
// 连接器类型与客户端实例同款下拉控件,仅禁用只读:随所选客户端联动展示
const typeSelect = wrapper.find('[data-testid="interface-connector-type"]');
expect(typeSelect.text()).toContain('SOAP');
expect(typeSelect.attributes('disabled')).toBeDefined();
// 只渲染当前类型单项,不提供其他选项(不可改选)
expect(typeSelect.findAll('option').length).toBe(1);
});
it('接口定义:状态在底部操作条以状态胶囊只读展示(悬停承载说明),无启用勾选', () => {
const interfaceForm = createEmptyInterfaceDefinitionForm();
interfaceForm.status = 'published';
const wrapper = mountDrawer({ activeEntity: 'interface', interfaceForm });
// 操作条只放安静的状态指示器:彩点胶囊,不放表单控件与多行文案;长说明走悬停 title
const chip = wrapper.find('[data-testid="lifecycle-status-chip"]');
expect(chip.exists()).toBe(true);
expect(chip.text()).toContain('已发布');
expect(chip.attributes('title')).toContain('发布');
// 启用勾选已移除
expect(wrapper.findAll('input[type="checkbox"]').length).toBe(0);
});
it('绑定:无来源实例编码字段,状态在底部操作条以禁用下拉只读展示', () => {
const wrapper = mountDrawer({ activeEntity: 'binding' });
const labels = wrapper.findAll('label').map((l) => l.text());
// 来源快捷列已删除:路由条件统一走高级配置 JSON
expect(labels.some((t) => t.includes('来源实例编码'))).toBe(false);
// 状态胶囊在底部操作条(转移只经列表生命周期按钮)
const chip = wrapper.find('[data-testid="lifecycle-status-chip"]');
expect(chip.exists()).toBe(true);
expect(chip.attributes('title')).toContain('发布');
});
it('绑定:选定接口定义后客户端实例自动带出并锁定', async () => {
const bindingForm = createEmptyBindingForm();
const wrapper = mountDrawer({
activeEntity: 'binding',
bindingForm,
clientOptions: [
{ code: '1001', name: '鼎捷TOPGP' },
{ code: '2001', name: '另一实例' },
],
interfaceOptions: [{ code: '1001-iface', name: '接口A', client_instance_code: '1001' }],
});
// 未选接口定义前客户端实例可维护
expect(wrapper.find('[data-testid="binding-client"]').attributes('disabled')).toBeUndefined();
await wrapper.find('[data-testid="binding-interface"]').setValue('1001-iface');
// 选定接口定义后:客户端实例按接口归属联动带出且锁定
expect(bindingForm.client_instance_code).toBe('1001');
expect(wrapper.find('[data-testid="binding-client"]').attributes('disabled')).toBeDefined();
});
it('绑定能力下拉选项本地化:有翻译显示「中文名(注册名)」,无翻译兜底注册名', () => {
const wrapper = mountDrawer({
activeEntity: 'binding',
capabilityOptions: [
{ name: 'in_transit_transfer.query_inventory' },
{ name: 'unknown.capability' },
],
});
// 能力下拉是绑定表单首个 select;选项不再出现原始注册名裸文案
const capabilitySelect = wrapper.find('select');
expect(capabilitySelect.findAll('option').map((o) => o.text())).toEqual([
'在途库存查询(in_transit_transfer.query_inventory)',
'unknown.capability',
]);
});
});
describe('IntegrationConnectorFormDrawer JSON fields', () => {
function findJsonField(wrapper: ReturnType<typeof mountDrawer>, labelPart: string) {
const field = wrapper
.findAllComponents(JsonTextareaField)
.find((w) => String(w.props('label')).includes(labelPart));
expect(field, `未找到 label 含 ${labelPart} 的 JSON 字段`).toBeDefined();
return field!;
}
it('接口定义 4 个 JSON 字段纵向全宽堆叠渲染', () => {
const wrapper = mountDrawer({ activeEntity: 'interface' });
const labels = wrapper.findAllComponents(JsonTextareaField).map((w) => String(w.props('label')));
expect(labels.some((t) => t.includes('请求模板'))).toBe(true);
expect(labels.some((t) => t.includes('入参 Schema'))).toBe(true);
expect(labels.some((t) => t.includes('回传映射'))).toBe(true);
expect(labels.some((t) => t.includes('出参 Schema'))).toBe(true);
});
it('格式化按钮将合法 JSON pretty-print 写回表单 state', async () => {
const interfaceForm: InterfaceDefinitionFormState = createEmptyInterfaceDefinitionForm();
const wrapper = mountDrawer({ activeEntity: 'interface', interfaceForm });
const field = findJsonField(wrapper, '请求模板');
await field!.find('[data-testid="json-textarea"]').setValue('{"method":"POST","params":["erp_org"]}');
await field!.find('[data-testid="json-format-button"]').trigger('click');
// 断言格式化结果写回父级表单对象(v-model 链路)
expect(interfaceForm.request_spec_json).toBe('{\n "method": "POST",\n "params": [\n "erp_org"\n ]\n}');
});
it('非法 JSON 失焦后显示红字提示,格式化不改写内容', async () => {
const interfaceForm: InterfaceDefinitionFormState = createEmptyInterfaceDefinitionForm();
const wrapper = mountDrawer({ activeEntity: 'interface', interfaceForm });
const field = findJsonField(wrapper, '请求模板');
const textarea = field!.find('[data-testid="json-textarea"]');
await textarea.setValue('{ invalid');
expect(field!.find('[data-testid="json-error"]').exists()).toBe(false);
await textarea.trigger('blur');
// 失焦后才提示,输入过程中不打断
expect(field!.find('[data-testid="json-error"]').exists()).toBe(true);
expect(field!.find('[data-testid="json-error"]').text()).toContain('JSON 格式无效');
// 非法时格式化按钮不改写内容
await field!.find('[data-testid="json-format-button"]').trigger('click');
expect(interfaceForm.request_spec_json).toBe('{ invalid');
});
it('客户端实例与绑定实体的 JSON 字段同样启用格式化能力', () => {
const clientWrapper = mountDrawer({ activeEntity: 'client' });
expect(findJsonField(clientWrapper, '连接配置').find('[data-testid="json-format-button"]').exists()).toBe(true);
const bindingWrapper = mountDrawer({ activeEntity: 'binding' });
expect(findJsonField(bindingWrapper, '高级路由条件').find('[data-testid="json-format-button"]').exists()).toBe(true);
});
});
describe('IntegrationConnectorFormDrawer close guard', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('抽屉带 dialog 语义且打开时渲染标题', () => {
const wrapper = mountDrawer({ activeEntity: 'client' });
const dialog = wrapper.find('[role="dialog"]');
expect(dialog.exists()).toBe(true);
expect(dialog.attributes('aria-modal')).toBe('true');
expect(dialog.attributes('aria-label')).toContain('客户端实例');
});
it('干净表单点击遮罩直接关闭,不弹确认', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
const wrapper = mountDrawer();
await wrapper.find('[data-testid="connector-form-drawer"]').trigger('click');
expect(wrapper.emitted('close')).toHaveLength(1);
expect(confirmSpy).not.toHaveBeenCalled();
});
it('脏表单关闭先确认:拒绝则留在抽屉,允许才 emit close', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
const wrapper = mountDrawer();
await wrapper.find('[data-testid="client-endpoint"]').setValue('https://erp.example.com');
await wrapper.find('[data-testid="connector-form-drawer"]').trigger('click');
// 用户拒绝关闭 → 不 emit
expect(confirmSpy).toHaveBeenCalledTimes(1);
expect(wrapper.emitted('close')).toBeUndefined();
confirmSpy.mockReturnValue(true);
await wrapper.find('[data-testid="connector-form-drawer"]').trigger('click');
// 用户确认放弃 → 放行关闭
expect(wrapper.emitted('close')).toHaveLength(1);
});
it('Esc 关闭走同一确认入口(脏表单拒绝时不关闭)', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
const wrapper = mountDrawer();
await wrapper.find('[data-testid="client-endpoint"]').setValue('https://erp.example.com');
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
expect(confirmSpy).toHaveBeenCalledTimes(1);
expect(wrapper.emitted('close')).toBeUndefined();
// 干净表单 Esc 直接关闭
const cleanWrapper = mountDrawer();
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
expect(cleanWrapper.emitted('close')).toHaveLength(1);
});
});
describe('IntegrationConnectorFormDrawer credential modes', () => {
it('db 模式按类型动态渲染字段(secret 字段为密码框),不显示 Secret 引用键', () => {
const wrapper = mountDrawer({ activeEntity: 'credential' });
const username = wrapper.find('[data-testid="credential-field-username"]');
const password = wrapper.find('[data-testid="credential-field-password"]');
expect(username.exists()).toBe(true);
expect(password.exists()).toBe(true);
expect(password.attributes('type')).toBe('password');
expect(username.attributes('type')).toBe('text');
expect(wrapper.find('[data-testid="credential-secret-ref"]').exists()).toBe(false);
// 占位符提示列出该类型提供的 credential_* 键
expect(wrapper.text()).toContain('{credential_username}');
expect(wrapper.text()).toContain('{credential_password}');
});
it('编辑态密文字段显示留空保持原值提示', () => {
const form = { ...createEmptyCredentialReferenceForm(), id: 7, fields: { username: 'erp_user' } };
const wrapper = mountDrawer({ activeEntity: 'credential', credentialForm: form });
const password = wrapper.find('[data-testid="credential-field-password"]');
expect(password.attributes('placeholder')).toContain('留空');
expect((wrapper.find('[data-testid="credential-field-username"]').element as HTMLInputElement).value).toBe('erp_user');
});
it('切换凭据类型到 token 后按新类型渲染字段', async () => {
const wrapper = mountDrawer({ activeEntity: 'credential' });
await wrapper.find('[data-testid="credential-type"]').setValue('token');
expect(wrapper.find('[data-testid="credential-field-token"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="credential-field-username"]').exists()).toBe(false);
expect(wrapper.text()).toContain('{credential_token}');
});
it('切到 env 模式只显示 Secret 引用键,隐藏类型字段', async () => {
const wrapper = mountDrawer({ activeEntity: 'credential' });
await wrapper.find('[data-testid="credential-provider"]').setValue('env');
expect(wrapper.find('[data-testid="credential-secret-ref"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="credential-field-username"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="credential-field-password"]').exists()).toBe(false);
});
});
describe('IntegrationConnectorFormDrawer credential identity freeze', () => {
it('新建态:类型/来源下拉选项本地化渲染(与列表徽章一致),状态不进表单,无只读信息区', () => {
const wrapper = mountDrawer({ activeEntity: 'credential' });
const typeOptions = wrapper.find('[data-testid="credential-type"]').findAll('option');
expect(typeOptions.map((o) => o.text())).toEqual(['账密', '令牌']);
const providerOptions = wrapper.find('[data-testid="credential-provider"]').findAll('option');
expect(providerOptions.map((o) => o.text())).toEqual(['界面维护(加密保存)', '环境变量']);
// 状态由列表生命周期按钮流转,凭据表单只有来源/类型两个下拉
expect(wrapper.findAll('select').length).toBe(2);
// 新建态没有只读信息区
expect(wrapper.find('[data-testid="credential-meta"]').exists()).toBe(false);
// 正文分组:基本信息 + 凭据值
expect(wrapper.text()).toContain('基本信息');
expect(wrapper.text()).toContain('凭据值');
});
it('编辑态:编码/类型/来源以同款禁用表单控件只读展示(不用徽章形态),启用开关在底部操作条', () => {
const form = { ...createEmptyCredentialReferenceForm(), id: 7, code: 'tiptop-erp', credential_type: 'password', secret_provider: 'db', status: 'active' };
const wrapper = mountDrawer({ activeEntity: 'credential', credentialForm: form });
// 与新建态同款正常控件、禁用只读:编码输入框 + 来源/类型下拉(本地化文案,不出现裸枚举)
const codeInput = wrapper.find('[data-testid="credential-code"]');
expect((codeInput.element as HTMLInputElement).disabled).toBe(true);
expect((codeInput.element as HTMLInputElement).value).toBe('tiptop-erp');
const providerSelect = wrapper.find('[data-testid="credential-provider"]');
expect(providerSelect.attributes('disabled')).toBeDefined();
expect(providerSelect.text()).toContain('界面维护(加密保存)');
const typeSelect = wrapper.find('[data-testid="credential-type"]');
expect(typeSelect.attributes('disabled')).toBeDefined();
expect(typeSelect.text()).toContain('账密');
// 状态 = 底部操作条启用开关(随保存生效),悬停 title 说明停用断流后果
const row = wrapper.find('[data-testid="credential-enabled-row"]');
expect(row.exists()).toBe(true);
expect(row.text()).toContain('随保存操作生效');
const switchBtn = wrapper.find('[data-testid="credential-enabled-switch"]');
expect(switchBtn.attributes('aria-checked')).toBe('true');
expect(switchBtn.attributes('title')).toContain('立即失败');
// 变更路径一句话提示
expect(wrapper.text()).toContain('以上信息创建后不可更改');
});
it('凭据值段占位符逐个以代码徽章展示', () => {
const wrapper = mountDrawer({ activeEntity: 'credential' });
const chips = wrapper.findAll('[data-testid="credential-placeholder-chip"]');
expect(chips.map((c) => c.text())).toEqual(['{credential_username}', '{credential_password}']);
});
});
describe('IntegrationConnectorFormDrawer client form redesign', () => {
it('名称失焦且编码为空时自动建议 kebab-case 编码;已填编码不被覆盖', async () => {
const clientForm = createEmptyClientInstanceForm();
const wrapper = mountDrawer({ clientForm });
await wrapper.find('[data-testid="client-name"]').setValue('ERP X');
await wrapper.find('[data-testid="client-name"]').trigger('blur');
expect(clientForm.code).toBe('erp-x');
await wrapper.find('[data-testid="client-name"]').setValue('Another Name');
await wrapper.find('[data-testid="client-name"]').trigger('blur');
expect(clientForm.code).toBe('erp-x');
});
it('编辑态编码锁定不可改,类型/环境下拉本地化渲染', async () => {
const clientForm = { ...createEmptyClientInstanceForm(), id: 3, code: 'erp-x' };
const wrapper = mountDrawer({ clientForm });
const code = wrapper.find('[data-testid="client-code"]');
expect((code.element as HTMLInputElement).disabled).toBe(true);
const typeOptions = wrapper.find('[data-testid="client-connector-type"]').findAll('option');
expect(typeOptions.map((o) => o.text())).toEqual(['REST API', 'SOAP 服务']);
const envOptions = wrapper.find('[data-testid="client-environment"]').findAll('option');
expect(envOptions.map((o) => o.text())).toEqual(['开发', '测试', '生产']);
});
it('凭据引用为下拉选择(含「无(匿名访问)」空项),高级配置按类型给出生效键提示', async () => {
const wrapper = mountDrawer({
credentialOptions: [{ code: 'tiptop-erp' }, { code: 'wms-token' }],
});
const credOptions = wrapper.find('[data-testid="client-credential-ref"]').findAll('option');
expect(credOptions.map((o) => o.text())).toEqual(['无(匿名访问)', 'tiptop-erp', 'wms-token']);
// REST:高级配置提示列出生效键 headers
expect(wrapper.text()).toContain('"headers"');
// 切到 SOAP:提示变为「暂无额外生效键」语义
await wrapper.find('[data-testid="client-connector-type"]').setValue('soap');
expect(wrapper.text()).toContain('暂无额外生效的配置键');
});
it('启用开关置于底部操作条左侧:小字注明随保存生效,点击翻转 state,非客户端实体不渲染', async () => {
const clientForm = createEmptyClientInstanceForm();
const wrapper = mountDrawer({ clientForm });
const row = wrapper.find('[data-testid="client-enabled-row"]');
// 启用不再是表单体里的孤行复选框,而是底部操作条左侧的 role="switch" 开关
expect(row.exists()).toBe(true);
expect(wrapper.findAll('input[type="checkbox"]').length).toBe(0);
const switchBtn = wrapper.find('[data-testid="client-enabled-switch"]');
expect(switchBtn.attributes('role')).toBe('switch');
// 小字「随保存操作生效」与列表行内开关的即时生效区分;悬停 title 携带停用后果
expect(row.text()).toContain('随保存操作生效');
expect(switchBtn.attributes('title')).toContain('连接测试不受影响');
// 默认启用;点击翻转表单 state,aria 状态同步
expect(clientForm.enabled).toBe(true);
await switchBtn.trigger('click');
expect(clientForm.enabled).toBe(false);
expect(switchBtn.attributes('aria-checked')).toBe('false');
// 凭据实体渲染自己的启用开关(同一底部形态),客户端开关行不出现
const credWrapper = mountDrawer({ activeEntity: 'credential' });
expect(credWrapper.find('[data-testid="client-enabled-row"]').exists()).toBe(false);
expect(credWrapper.find('[data-testid="credential-enabled-row"]').exists()).toBe(true);
// 接口/绑定不渲染启用开关,改为底部状态只读下拉
const ifaceWrapper = mountDrawer({ activeEntity: 'interface' });
expect(ifaceWrapper.find('[data-testid="client-enabled-row"]').exists()).toBe(false);
expect(ifaceWrapper.find('[data-testid="lifecycle-status-row"]').exists()).toBe(true);
});
});
@@ -0,0 +1,565 @@
<!--
features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.vue
用途:集成连接器四实体(客户端实例/接口定义/绑定/凭据引用)创建与编辑抽屉。
依赖:activeEntity 对应的表单 state、useI18n、JsonTextareaField。
逻辑:由 IntegrationConnectorPage 打开;按 activeEntity 渲染对应字段,客户端实例
表单按「基本信息 → 连接配置 → 高级」分组,启用开关置于底部操作条左侧(随保存生效,悬停显示停用后果);
客户端编码留空时按名称自动建议、
接口编码留空时按「客户端实例编码-名称」自动建议(均可手改,已填不覆盖,编辑态编码锁定);
客户端实例的连接器类型/环境/凭据引用均为下拉(选项来自模块常量与凭据列表,未知值兜底);
接口定义的连接器类型随所选客户端实例联动只读展示(提交由后端以客户端为准推导);
绑定的客户端实例随所选接口定义联动带出并锁定(接口归属即客户端归属);
绑定表单的能力下拉选项本地化为「中文名(注册名)」(未注册翻译兜底注册名);
接口与绑定的状态均为只读徽章(发布/退役走列表生命周期按钮),四个 JSON 契约字段常显不折叠;
凭据引用:状态不进表单(由列表生命周期按钮流转);编辑态以「基本信息」只读信息区
展示编码/类型/来源/状态(label+值行,与接口定义只读字段同款式),新建态下拉选项
文案本地化与列表一致;高级配置帮助文案按连接器类型的生效键动态切换。
JSON 配置字段统一走 JsonTextareaField;提交 emit save。右侧抽屉承载(表单长、JSON 面积大),
带未保存离开确认(脏检查)、Esc 关闭与 dialog aria 语义。
-->
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import JsonTextareaField from './JsonTextareaField.vue';
import {
CONNECTOR_CONFIG_KEYS,
CONNECTOR_TYPE_OPTIONS,
ENVIRONMENT_OPTIONS,
suggestClientCode,
suggestInterfaceCode,
} from '../types/integration-connector.types';
import type {
BindingFormState,
ClientInstanceFormState,
CredentialReferenceFormState,
InterfaceDefinitionFormState,
} from '../types/integration-connector.types';
const props = defineProps<{
visible: boolean;
activeEntity: 'client' | 'interface' | 'binding' | 'credential';
clientForm: ClientInstanceFormState;
interfaceForm: InterfaceDefinitionFormState;
bindingForm: BindingFormState;
credentialForm: CredentialReferenceFormState;
isSaving: boolean;
/** 客户端实例选项:connector_type 供接口表单联动展示连接器类型。 */
clientOptions: Array<{ code: string; name: string; connector_type?: string }>;
/** 接口定义选项:client_instance_code 供绑定表单联动带出客户端实例。 */
interfaceOptions: Array<{ code: string; name: string; client_instance_code?: string }>;
capabilityOptions: Array<{ name: string }>;
credentialTypeOptions: Array<{ type: string; fields: Array<{ key: string; secret: boolean; required: boolean }> }>;
/** 凭据引用选项(客户端表单下拉用);缺省渲染为空列表。 */
credentialOptions?: Array<{ code: string }>;
}>();
const emit = defineEmits<{
close: [];
save: [];
}>();
const { t } = useI18n();
const panelRef = ref<HTMLElement | null>(null);
/** 打开时刻的表单快照,用于脏检查(表单均为扁平原始值,stringify 比对可靠)。 */
const initialSnapshot = ref('');
const entityTitle = computed(() => t(`admin.integrationConnector.tabs.${props.activeEntity}`));
/** 抽屉顶部提示按实体区分(客户端表单提示编码用途;其余实体提示与自身相关的关键规则)。 */
const entityHint = computed(() => t(`admin.integrationConnector.formHints.${props.activeEntity}`));
/** 名称失焦时若编码仍为空,按名称自动建议(已手填的编码不覆盖;编辑态编码锁定)。 */
function onClientNameBlur() {
if (!props.clientForm.code.trim()) {
props.clientForm.code = suggestClientCode(props.clientForm.name);
}
}
/** 连接器类型本地化标签;未注册类型兜底原样显示(不写死类型集合)。 */
function connectorTypeLabel(value: string) {
const opt = CONNECTOR_TYPE_OPTIONS.find((item) => item.value === value);
return opt ? t(opt.labelKey) : value;
}
/** 状态本地化标签;未知值兜底原样显示。 */
function statusLabel(value: string) {
return t(`admin.integrationConnector.statusLabels.${value}`, value);
}
/** 引用型下拉选项文案:「名称(编码)」;无名称时兜底编码本身(凭据类实体无名称字段)。 */
function optionLabel(name: string, code: string) {
return name ? `${name}(${code})` : code;
}
/** 能力本地化标签;未注册翻译兜底原值(能力名含点号,i18n 按嵌套路径组织)。 */
function capabilityLabel(name: string) {
return t(`admin.integrationConnector.capabilityLabels.${name}`, name);
}
/** 能力下拉选项文案:有中文翻译时「中文名(注册名)」,否则注册名本身(避免重复)。 */
function capabilityOptionLabel(name: string) {
const label = capabilityLabel(name);
return label === name ? name : `${label}(${name})`;
}
/** 接口编码仍为空且已选客户端实例时,按「客户端编码-名称」补建议(已手填不覆盖)。 */
function suggestInterfaceCodeIfEmpty() {
const form = props.interfaceForm;
if (form.code.trim() || !form.client_instance_code) return;
const suggested = suggestInterfaceCode(form.client_instance_code, form.name);
if (suggested) form.code = suggested;
}
/** 接口名称失焦:编码仍为空则补建议。 */
function onInterfaceNameBlur() {
suggestInterfaceCodeIfEmpty();
}
/** 切换接口的客户端实例:联动展示其连接器类型(仅展示,提交由后端以客户端为准推导),并补编码建议。 */
function onInterfaceClientChange() {
const selected = props.clientOptions.find((item) => item.code === props.interfaceForm.client_instance_code);
if (selected?.connector_type === 'rest' || selected?.connector_type === 'soap') {
props.interfaceForm.connector_type = selected.connector_type;
}
suggestInterfaceCodeIfEmpty();
}
/**
* 切换绑定的接口定义:联动带出其所属客户端实例并锁定(接口归属即客户端归属)。
* 后端创建/更新仍做成对校验(INTEGRATION.BINDING_PAIR_MISMATCH)兜底直连 API 的场景。
*/
function onBindingInterfaceChange() {
const selected = props.interfaceOptions.find((item) => item.code === props.bindingForm.interface_definition_code);
if (selected?.client_instance_code) {
props.bindingForm.client_instance_code = selected.client_instance_code;
}
}
/** 高级配置示例(JSON 属代码示例,不入 i18n——字面大括号会破坏 vue-i18n 消息编译)。 */
const CLIENT_CONFIG_EXAMPLE = '{ "headers": { "X-Tenant": "AWSBI" } }';
/** 高级配置帮助文案:按连接器类型列出当前生效键;无生效键时明确说明透传语义。 */
const clientConfigHint = computed(() => {
const keys = CONNECTOR_CONFIG_KEYS[props.clientForm.connector_type] ?? [];
if (keys.length) {
return t('admin.integrationConnector.advancedHints.withKeys', { keys: keys.map((k) => `"${k}"`).join('、') });
}
return t('admin.integrationConnector.advancedHints.none');
});
/** 当前所选凭据类型的字段定义(来自后端注册表;未加载时回退空)。 */
const credentialTypeSpec = computed(() => {
if (props.activeEntity !== 'credential') return null;
return props.credentialTypeOptions.find((item) => item.type === props.credentialForm.credential_type) ?? null;
});
/** 该凭据类型提供的模板占位符(credential_<key>)清单,供接口模板作者参考。 */
const credentialPlaceholderKeys = computed(() =>
(credentialTypeSpec.value?.fields ?? []).map((field) => `{credential_${field.key}}`),
);
function credentialFieldLabel(key: string) {
return t(`admin.integrationConnector.credentialFields.${key}`, key);
}
/** 凭据引用编辑态判定:编辑时编码/类型/来源渲染为禁用表单控件(行业惯例:凭据形态创建后不可变)。 */
const isCredentialEdit = computed(() => Boolean(props.credentialForm.id));
/** 凭据启用态:两态开关(active/retired;rotating 存量视为启用侧,点击即停用)。 */
const credentialEnabled = computed(() => props.credentialForm.status !== 'retired');
/** 凭据 footer 启用开关翻转:active↔retired,随「保存更改」一并提交(PUT 仅接受这两值)。 */
function toggleCredentialEnabled() {
props.credentialForm.status = props.credentialForm.status === 'retired' ? 'active' : 'retired';
}
/** 接口/绑定生命周期状态(footer 只读展示;转移只经列表生命周期按钮,表单不可改)。 */
const lifecycleStatus = computed(() =>
props.activeEntity === 'interface' ? props.interfaceForm.status : props.bindingForm.status,
);
/** 状态胶囊配色:已发布绿 / 其余中性(与列表状态徽章同规则;未知值兜底中性)。 */
const lifecycleChipClass = computed(() => {
if (lifecycleStatus.value === 'published') return 'bg-emerald-50 text-emerald-700';
return 'bg-surface-soft text-secondary';
});
/** 凭据类型本地化标签;未注册类型兜底原样显示(不写死类型集合)。 */
function credentialTypeLabel(value: string) {
return t(`admin.integrationConnector.credentialTypeLabels.${value}`, value);
}
/** 凭据来源本地化标签(与列表徽章共用 statusLabels.db/env)。 */
function credentialProviderLabel(value: string) {
return t(`admin.integrationConnector.statusLabels.${value}`, value);
}
const activeForm = computed(() => {
if (props.activeEntity === 'client') return props.clientForm;
if (props.activeEntity === 'interface') return props.interfaceForm;
if (props.activeEntity === 'binding') return props.bindingForm;
return props.credentialForm;
});
/** 表单相对打开时是否有变更;有变更时关闭需用户确认,防误触丢数据。 */
const isDirty = computed(() => JSON.stringify(activeForm.value) !== initialSnapshot.value);
/** 统一关闭入口:脏表单先弹确认,取消则留在抽屉。 */
function requestClose() {
if (isDirty.value && !window.confirm(t('admin.integrationConnector.msg.unsavedConfirm'))) return;
emit('close');
}
/** Esc 关闭走同一确认入口。 */
function onKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') requestClose();
}
watch(
() => props.visible,
(visible) => {
if (visible) {
initialSnapshot.value = JSON.stringify(activeForm.value);
document.addEventListener('keydown', onKeydown);
void nextTick(() => panelRef.value?.focus());
} else {
document.removeEventListener('keydown', onKeydown);
}
},
{ immediate: true },
);
onBeforeUnmount(() => document.removeEventListener('keydown', onKeydown));
</script>
<template>
<div
v-if="visible"
class="fixed inset-0 z-50 flex justify-end bg-overlay"
data-testid="connector-form-drawer"
@click.self="requestClose"
>
<aside
ref="panelRef"
tabindex="-1"
role="dialog"
aria-modal="true"
:aria-label="entityTitle"
class="h-full w-full max-w-4xl flex flex-col bg-surface shadow-2xl outline-none"
>
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-default shrink-0">
<h3 class="section-title">{{ entityTitle }}</h3>
<p class="section-desc mt-1">{{ entityHint }}</p>
</div>
<div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto flex-1">
<!-- 客户端实例:基本信息 → 连接配置 → 高级 三段式 -->
<template v-if="activeEntity === 'client'">
<div class="space-y-4">
<h4 class="text-xs font-bold uppercase tracking-wide text-muted">{{ t('admin.integrationConnector.sections.basic') }}</h4>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.name') }}</label>
<input v-model="clientForm.name" type="text" class="input-field text-sm" data-testid="client-name" @blur="onClientNameBlur" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.code') }}</label>
<input v-model="clientForm.code" type="text" class="input-field text-sm font-mono" :disabled="Boolean(clientForm.id)" data-testid="client-code" />
<p class="text-xs text-muted">{{ t('admin.integrationConnector.fields.codeHint') }}</p>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.connectorType') }}</label>
<select v-model="clientForm.connector_type" class="input-field text-sm" data-testid="client-connector-type">
<option v-for="opt in CONNECTOR_TYPE_OPTIONS" :key="opt.value" :value="opt.value">{{ t(opt.labelKey) }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.environment') }}</label>
<select v-model="clientForm.environment" class="input-field text-sm" data-testid="client-environment">
<option v-for="env in ENVIRONMENT_OPTIONS" :key="env" :value="env">{{ t(`admin.integrationConnector.envLabels.${env}`) }}</option>
</select>
</div>
</div>
</div>
<div class="space-y-4">
<h4 class="text-xs font-bold uppercase tracking-wide text-muted">{{ t('admin.integrationConnector.sections.connection') }}</h4>
<!-- 连接地址:endpoint 合一字段;label 按连接器类型显示(REST=接口地址,SOAP=WSDL 地址) -->
<div class="space-y-1.5">
<label class="label-field">{{ clientForm.connector_type === 'soap' ? t('admin.integrationConnector.fields.wsdl') : t('admin.integrationConnector.fields.endpoint') }}</label>
<input v-model="clientForm.endpoint" type="text" class="input-field text-sm" :placeholder="t(clientForm.connector_type === 'soap' ? 'admin.integrationConnector.placeholders.wsdl' : 'admin.integrationConnector.placeholders.endpoint')" data-testid="client-endpoint" />
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.timeout') }}</label>
<input v-model="clientForm.timeout_seconds" type="number" class="input-field text-sm" min="0" data-testid="client-timeout" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.credentialRef') }}</label>
<select v-model="clientForm.credential_ref_code" class="input-field text-sm" data-testid="client-credential-ref">
<option value="">{{ t('admin.integrationConnector.fields.credentialNone') }}</option>
<option v-for="opt in credentialOptions || []" :key="opt.code" :value="opt.code">{{ opt.code }}</option>
</select>
<p class="text-xs text-muted">{{ t('admin.integrationConnector.fields.credentialRefHint') }}</p>
</div>
</div>
</div>
<details class="rounded-lg border border-slate-200 px-3 py-2">
<summary class="cursor-pointer text-xs font-bold text-secondary">{{ t('admin.integrationConnector.sections.advanced') }}</summary>
<div class="mt-2 space-y-2">
<p class="text-xs text-muted">{{ clientConfigHint }}</p>
<JsonTextareaField
v-model="clientForm.config_json"
:label="t('admin.integrationConnector.fields.configJson')"
:placeholder="CLIENT_CONFIG_EXAMPLE"
/>
</div>
</details>
</template>
<!-- 接口定义:编码自动建议 + 类型随客户端联动(只读徽章)+ 接口契约 JSON 常显 + 状态只读徽章 -->
<template v-else-if="activeEntity === 'interface'">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.name') }}</label>
<input v-model="interfaceForm.name" type="text" class="input-field text-sm" data-testid="interface-name" @blur="onInterfaceNameBlur" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.code') }}</label>
<input v-model="interfaceForm.code" type="text" class="input-field text-sm font-mono" :disabled="Boolean(interfaceForm.id)" data-testid="interface-code" />
<p class="text-xs text-muted">{{ t('admin.integrationConnector.fields.codeHintInterface') }}</p>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.clientInstance') }}</label>
<select v-model="interfaceForm.client_instance_code" class="input-field text-sm" data-testid="interface-client" @change="onInterfaceClientChange">
<option v-for="opt in clientOptions" :key="opt.code" :value="opt.code">{{ optionLabel(opt.name, opt.code) }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.connectorType') }}</label>
<!-- 与客户端实例同款下拉控件、仅禁用只读:类型随客户端实例自动确定(后端以其为单一事实源推导),不可单独修改 -->
<select
:value="interfaceForm.connector_type"
class="input-field text-sm disabled:opacity-70"
disabled
data-testid="interface-connector-type"
>
<option :value="interfaceForm.connector_type">{{ connectorTypeLabel(interfaceForm.connector_type) }}</option>
</select>
<p class="text-xs text-muted">{{ t('admin.integrationConnector.fields.connectorTypeHint') }}</p>
</div>
</div>
<div v-if="interfaceForm.connector_type === 'rest'" class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.httpMethod') }}</label>
<select v-model="interfaceForm.http_method" class="input-field text-sm">
<option value="">—</option>
<option value="GET">GET</option>
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="DELETE">DELETE</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.requestPath') }}</label>
<input v-model="interfaceForm.request_path" type="text" class="input-field text-sm font-mono" :placeholder="t('admin.integrationConnector.placeholders.requestPath')" />
</div>
</div>
<!-- 接口契约(请求模板/入参 Schema/回传映射/出参 Schema)即接口定义本体:常显纵向全宽,不再折叠 -->
<div class="space-y-4">
<h4 class="text-xs font-bold uppercase tracking-wide text-muted">{{ t('admin.integrationConnector.sections.contract') }}</h4>
<JsonTextareaField v-model="interfaceForm.request_spec_json" :label="t('admin.integrationConnector.fields.requestSpec')" />
<JsonTextareaField v-model="interfaceForm.input_schema_json" :label="t('admin.integrationConnector.fields.inputSchema')" />
<JsonTextareaField v-model="interfaceForm.response_mapping_json" :label="t('admin.integrationConnector.fields.responseMapping')" />
<JsonTextareaField v-model="interfaceForm.output_schema_json" :label="t('admin.integrationConnector.fields.outputSchema')" />
</div>
<!-- 状态不进表单正文:以底部操作条只读下拉展示(转移只经列表生命周期按钮) -->
</template>
<!-- 绑定:客户端实例随接口定义联动锁定;状态为只读徽章(发布/退役走列表生命周期按钮) -->
<template v-else-if="activeEntity === 'binding'">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.capability') }}</label>
<select v-model="bindingForm.capability" class="input-field text-sm">
<option v-for="cap in capabilityOptions" :key="cap.name" :value="cap.name">{{ capabilityOptionLabel(cap.name) }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.environment') }}</label>
<select v-model="bindingForm.environment" class="input-field text-sm">
<option v-for="env in ENVIRONMENT_OPTIONS" :key="env" :value="env">{{ t(`admin.integrationConnector.envLabels.${env}`) }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.clientInstance') }}</label>
<!-- 已选接口定义即锁定:客户端实例由接口定义归属唯一确定,不可单独维护 -->
<select v-model="bindingForm.client_instance_code" class="input-field text-sm disabled:opacity-70" :disabled="Boolean(bindingForm.interface_definition_code)" data-testid="binding-client">
<option v-for="opt in clientOptions" :key="opt.code" :value="opt.code">{{ optionLabel(opt.name, opt.code) }}</option>
</select>
<p class="text-xs text-muted">{{ t('admin.integrationConnector.fields.bindingClientHint') }}</p>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.interfaceDef') }}</label>
<select v-model="bindingForm.interface_definition_code" class="input-field text-sm" data-testid="binding-interface" @change="onBindingInterfaceChange">
<option v-for="opt in interfaceOptions" :key="opt.code" :value="opt.code">{{ optionLabel(opt.name, opt.code) }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.mappingVersion') }}</label>
<input v-model.number="bindingForm.mapping_version" type="number" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.priority') }}</label>
<input v-model.number="bindingForm.priority" type="number" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.effectiveFrom') }}</label>
<input v-model="bindingForm.effective_from" type="datetime-local" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.effectiveTo') }}</label>
<input v-model="bindingForm.effective_to" type="datetime-local" class="input-field text-sm" />
</div>
</div>
<details class="rounded-lg border border-slate-200 px-3 py-2">
<summary class="cursor-pointer text-xs font-bold text-secondary">{{ t('admin.integrationConnector.advancedConfig') }}</summary>
<div class="mt-2 space-y-2">
<JsonTextareaField v-model="bindingForm.context_selector_json" :label="t('admin.integrationConnector.fields.contextSelector')" />
<p class="text-xs text-muted">{{ t('admin.integrationConnector.fields.contextSelectorHint') }}</p>
<JsonTextareaField v-model="bindingForm.param_mapping_json" :label="t('admin.integrationConnector.fields.paramMapping')" />
<p class="text-xs text-muted">{{ t('admin.integrationConnector.fields.paramMappingHint') }}</p>
</div>
</details>
<!-- 状态不进表单正文:以底部操作条只读下拉展示(转移只经列表生命周期按钮) -->
</template>
<!-- 凭据引用:基本信息统一为正常表单控件(编辑态禁用只读,不用徽章形态);状态经底部启用开关随保存生效 -->
<template v-else>
<div class="space-y-4">
<h4 class="text-xs font-bold uppercase tracking-wide text-muted">{{ t('admin.integrationConnector.sections.basic') }}</h4>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.code') }}</label>
<input v-model="credentialForm.code" type="text" class="input-field text-sm font-mono disabled:opacity-70" :disabled="isCredentialEdit" data-testid="credential-code" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.secretProvider') }}</label>
<!-- 编辑态禁用:db↔env 切换会让存量密文变孤儿数据或调用期晚失败,变更须新建引用 -->
<select v-model="credentialForm.secret_provider" class="input-field text-sm disabled:opacity-70" :disabled="isCredentialEdit" data-testid="credential-provider">
<option value="db">{{ credentialProviderLabel('db') }}</option>
<option value="env">{{ credentialProviderLabel('env') }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.credentialType') }}</label>
<!-- 编辑态禁用:类型决定密文字段结构,中途改类型会使存量密文失效,变更须新建引用 -->
<select
v-model="credentialForm.credential_type"
class="input-field text-sm disabled:opacity-70"
:disabled="isCredentialEdit || credentialForm.secret_provider !== 'db'"
data-testid="credential-type"
>
<option v-for="spec in credentialTypeOptions" :key="spec.type" :value="spec.type">{{ credentialTypeLabel(spec.type) }}</option>
</select>
</div>
</div>
<p v-if="isCredentialEdit" class="text-xs text-muted">{{ t('admin.integrationConnector.formHints.credentialImmutable') }}</p>
</div>
<!-- 凭据值段:db 按类型动态渲染(secret 字段加密落库不回显,编辑留空 = 保持旧值);env 只登记配置键名 -->
<div class="space-y-4">
<h4 class="text-xs font-bold uppercase tracking-wide text-muted">{{ t('admin.integrationConnector.sections.credentialValues') }}</h4>
<template v-if="credentialForm.secret_provider === 'db'">
<div v-if="credentialTypeSpec" class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div v-for="field in credentialTypeSpec.fields" :key="field.key" class="space-y-1.5">
<label class="label-field">
{{ credentialFieldLabel(field.key) }}
<span v-if="!field.secret" class="text-xs text-muted">({{ t('admin.integrationConnector.fields.visibleField') }})</span>
</label>
<input
v-model="credentialForm.fields[field.key]"
:type="field.secret ? 'password' : 'text'"
class="input-field text-sm"
:autocomplete="field.secret ? 'new-password' : 'off'"
:placeholder="field.secret && credentialForm.id ? t('admin.integrationConnector.placeholders.passwordKeep') : ''"
:data-testid="`credential-field-${field.key}`"
/>
</div>
</div>
<!-- 模板占位符以代码徽章逐个展示,供接口模板作者复制 -->
<div v-if="credentialPlaceholderKeys.length" class="flex flex-wrap items-center gap-2 text-xs text-muted">
<span>{{ t('admin.integrationConnector.msg.credentialPlaceholdersHint') }}</span>
<code
v-for="key in credentialPlaceholderKeys"
:key="key"
class="rounded bg-surface-soft px-1.5 py-0.5 font-mono text-[11px] text-secondary"
data-testid="credential-placeholder-chip"
>{{ key }}</code>
</div>
</template>
<div v-else class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.secretRef') }}</label>
<input v-model="credentialForm.secret_ref" type="text" class="input-field text-sm" data-testid="credential-secret-ref" />
</div>
</div>
</template>
</div>
<div class="admin-modal-footer">
<!-- 启用开关置于操作条左侧(仅客户端实体):内容区滚动时始终可见;
小字「随保存操作生效」与列表行内开关的即时生效区分,悬停 title 显示停用的调用期后果 -->
<div v-if="activeEntity === 'client'" class="mr-auto flex items-center gap-2.5" data-testid="client-enabled-row">
<button
type="button"
role="switch"
:aria-checked="clientForm.enabled"
:title="t('admin.integrationConnector.fields.enabledHint')"
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors"
:class="clientForm.enabled ? 'bg-brand-600' : 'bg-slate-300'"
data-testid="client-enabled-switch"
@click="clientForm.enabled = !clientForm.enabled"
>
<span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform" :class="clientForm.enabled ? 'translate-x-4' : 'translate-x-0.5'" />
</button>
<span class="whitespace-nowrap text-sm font-medium text-secondary">{{ t('admin.integrationConnector.fields.enabled') }}</span>
<span class="whitespace-nowrap text-xs text-muted">{{ t('admin.integrationConnector.fields.enabledFooterHint') }}</span>
</div>
<!-- 凭据启用开关:同一底部形态;翻转 active↔retired,随「保存更改」提交(停用即断流,title 说明后果) -->
<div v-else-if="activeEntity === 'credential'" class="mr-auto flex items-center gap-2.5" data-testid="credential-enabled-row">
<button
type="button"
role="switch"
:aria-checked="credentialEnabled"
:title="t('admin.integrationConnector.fields.credentialEnabledHint')"
class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors"
:class="credentialEnabled ? 'bg-brand-600' : 'bg-slate-300'"
data-testid="credential-enabled-switch"
@click="toggleCredentialEnabled"
>
<span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform" :class="credentialEnabled ? 'translate-x-4' : 'translate-x-0.5'" />
</button>
<span class="whitespace-nowrap text-sm font-medium text-secondary">{{ t('admin.integrationConnector.fields.enabled') }}</span>
<span class="whitespace-nowrap text-xs text-muted">{{ t('admin.integrationConnector.fields.enabledFooterHint') }}</span>
</div>
<!-- 接口/绑定生命周期状态:安静的状态指示器(彩点胶囊 + 悬停承载长说明)——
操作条不放表单控件与多行文案,转移入口在列表行内按钮 -->
<div v-else-if="activeEntity === 'interface' || activeEntity === 'binding'" class="mr-auto flex items-center gap-2" data-testid="lifecycle-status-row">
<span class="whitespace-nowrap text-xs text-muted">{{ t('admin.integrationConnector.fields.status') }}</span>
<span
class="inline-flex items-center gap-1.5 whitespace-nowrap rounded-full px-2.5 py-1 text-xs font-medium"
:class="lifecycleChipClass"
:title="t('admin.integrationConnector.fields.statusHint')"
data-testid="lifecycle-status-chip"
>
<span class="h-1.5 w-1.5 rounded-full bg-current" />
{{ statusLabel(lifecycleStatus) }}
</span>
</div>
<button type="button" class="btn-ghost" @click="requestClose">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-70" :disabled="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.save') + '...' : t('admin.save') }}
</button>
</div>
</aside>
</div>
</template>
@@ -1,96 +0,0 @@
/**
* features/admin/modules/integration-connector/components/IntegrationConnectorFormModal.spec.ts
* 用途:锁定表单按连接器类型动态显示字段——REST 显示超时/HTTP方法/请求路径,
* SOAP 显示 WSDL;关键字段从 JSON 拆出独立输入框,JSON 收进高级配置折叠。
* 依赖:@vue/test-utils、i18n。
* 逻辑:切换 connector_type 后断言对应字段的可见性;高级配置折叠默认收起。
*/
import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import i18n from '@/i18n';
import IntegrationConnectorFormModal from './IntegrationConnectorFormModal.vue';
import {
createEmptyClientInstanceForm,
createEmptyInterfaceDefinitionForm,
createEmptyBindingForm,
createEmptyCredentialReferenceForm,
} from '../types/integration-connector.types';
function mountModal() {
return mount(IntegrationConnectorFormModal, {
props: {
visible: true,
activeEntity: 'client',
clientForm: createEmptyClientInstanceForm(),
interfaceForm: createEmptyInterfaceDefinitionForm(),
bindingForm: createEmptyBindingForm(),
credentialForm: createEmptyCredentialReferenceForm(),
isSaving: false,
clientOptions: [],
interfaceOptions: [],
capabilityOptions: [],
},
global: { plugins: [i18n] },
});
}
describe('IntegrationConnectorFormModal connector-type fields', () => {
it('REST 默认显示接口地址与超时字段', () => {
const wrapper = mountModal();
expect(wrapper.find('[data-testid="client-endpoint"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="client-timeout"]').exists()).toBe(true);
});
it('切换到 SOAP 后连接地址 label 变为 WSDL,超时仍显示;同一 endpoint 字段', async () => {
const wrapper = mountModal();
await wrapper.find('[data-testid="client-connector-type"]').setValue('soap');
await wrapper.vm.$nextTick();
// 连接地址仍是同一 client-endpoint 字段,仅 label 变 WSDL
expect(wrapper.find('[data-testid="client-endpoint"]').exists()).toBe(true);
// 超时在 SOAP 下也显示
expect(wrapper.find('[data-testid="client-timeout"]').exists()).toBe(true);
const labels = wrapper.findAll('label').map((l) => l.text());
expect(labels.some((t) => t.includes('WSDL'))).toBe(true);
});
it('接口定义 REST 显示 HTTP 方法与请求路径', () => {
const wrapper = mount(IntegrationConnectorFormModal, {
props: {
visible: true,
activeEntity: 'interface',
clientForm: createEmptyClientInstanceForm(),
interfaceForm: createEmptyInterfaceDefinitionForm(),
bindingForm: createEmptyBindingForm(),
credentialForm: createEmptyCredentialReferenceForm(),
isSaving: false,
clientOptions: [],
interfaceOptions: [],
capabilityOptions: [],
},
global: { plugins: [i18n] },
});
const labels = wrapper.findAll('label').map((l) => l.text());
expect(labels.some((t) => t.includes('HTTP 方法'))).toBe(true);
expect(labels.some((t) => t.includes('请求路径'))).toBe(true);
});
it('绑定显示来源实例编码独立字段', () => {
const wrapper = mount(IntegrationConnectorFormModal, {
props: {
visible: true,
activeEntity: 'binding',
clientForm: createEmptyClientInstanceForm(),
interfaceForm: createEmptyInterfaceDefinitionForm(),
bindingForm: createEmptyBindingForm(),
credentialForm: createEmptyCredentialReferenceForm(),
isSaving: false,
clientOptions: [],
interfaceOptions: [],
capabilityOptions: [],
},
global: { plugins: [i18n] },
});
const labels = wrapper.findAll('label').map((l) => l.text());
expect(labels.some((t) => t.includes('来源实例编码'))).toBe(true);
});
});
@@ -1,277 +0,0 @@
<!--
features/admin/modules/integration-connector/components/IntegrationConnectorFormModal.vue
用途:集成连接器四实体(客户端实例/接口定义/绑定/凭据引用)创建与编辑弹窗。
依赖:activeEntity 对应的表单 state、useI18n。
逻辑:由 IntegrationConnectorPage 打开;按 activeEntity 渲染对应字段;提交 emit save。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type {
BindingFormState,
ClientInstanceFormState,
CredentialReferenceFormState,
InterfaceDefinitionFormState,
} from '../types/integration-connector.types';
const props = defineProps<{
visible: boolean;
activeEntity: 'client' | 'interface' | 'binding' | 'credential';
clientForm: ClientInstanceFormState;
interfaceForm: InterfaceDefinitionFormState;
bindingForm: BindingFormState;
credentialForm: CredentialReferenceFormState;
isSaving: boolean;
clientOptions: Array<{ code: string; name: string }>;
interfaceOptions: Array<{ code: string; name: string }>;
capabilityOptions: Array<{ name: string }>;
}>();
const emit = defineEmits<{
close: [];
save: [];
}>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
<div class="admin-modal-panel max-w-2xl max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">{{ t(`admin.integrationConnector.tabs.${activeEntity}`) }}</h3>
<p class="section-desc mt-1">{{ t('admin.integrationConnector.formHint') }}</p>
</div>
<div class="px-5 sm:px-8 py-5 space-y-5 overflow-y-auto">
<!-- 客户端实例 -->
<template v-if="activeEntity === 'client'">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.code') }}</label>
<input v-model="clientForm.code" type="text" class="input-field text-sm" :disabled="Boolean(clientForm.id)" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.name') }}</label>
<input v-model="clientForm.name" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.connectorType') }}</label>
<select v-model="clientForm.connector_type" class="input-field text-sm" data-testid="client-connector-type">
<option value="rest">rest</option>
<option value="soap">soap</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.environment') }}</label>
<input v-model="clientForm.environment" type="text" class="input-field text-sm" />
</div>
</div>
<!-- 连接地址:endpoint 合一字段;label 按连接器类型显示(REST=接口地址,SOAP=WSDL 地址) -->
<div class="space-y-1.5">
<label class="label-field">{{ clientForm.connector_type === 'soap' ? t('admin.integrationConnector.fields.wsdl') : t('admin.integrationConnector.fields.endpoint') }}</label>
<input v-model="clientForm.endpoint" type="text" class="input-field text-sm" :placeholder="t(clientForm.connector_type === 'soap' ? 'admin.integrationConnector.placeholders.wsdl' : 'admin.integrationConnector.placeholders.endpoint')" data-testid="client-endpoint" />
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.timeout') }}</label>
<input v-model="clientForm.timeout_seconds" type="number" class="input-field text-sm" min="0" data-testid="client-timeout" />
</div>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.credentialRef') }}</label>
<input v-model="clientForm.credential_ref_code" type="text" class="input-field text-sm" />
</div>
<details class="rounded-lg border border-slate-200 px-3 py-2">
<summary class="cursor-pointer text-xs font-bold text-secondary">{{ t('admin.integrationConnector.advancedConfig') }}</summary>
<div class="mt-2 space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.configJson') }}</label>
<textarea v-model="clientForm.config_json" rows="6" class="input-field text-sm font-mono" spellcheck="false" />
</div>
</details>
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
<input v-model="clientForm.enabled" type="checkbox" class="w-4 h-4 rounded text-brand-600 border-default" />
{{ t('admin.integrationConnector.fields.enabled') }}
</label>
</template>
<!-- 接口定义 -->
<template v-else-if="activeEntity === 'interface'">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.code') }}</label>
<input v-model="interfaceForm.code" type="text" class="input-field text-sm" :disabled="Boolean(interfaceForm.id)" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.name') }}</label>
<input v-model="interfaceForm.name" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.clientInstance') }}</label>
<select v-model="interfaceForm.client_instance_code" class="input-field text-sm">
<option v-for="opt in clientOptions" :key="opt.code" :value="opt.code">{{ opt.code }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.connectorType') }}</label>
<select v-model="interfaceForm.connector_type" class="input-field text-sm">
<option value="rest">rest</option>
<option value="soap">soap</option>
</select>
</div>
</div>
<div v-if="interfaceForm.connector_type === 'rest'" class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.httpMethod') }}</label>
<select v-model="interfaceForm.http_method" class="input-field text-sm">
<option value="">—</option>
<option value="GET">GET</option>
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="DELETE">DELETE</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.requestPath') }}</label>
<input v-model="interfaceForm.request_path" type="text" class="input-field text-sm font-mono" :placeholder="t('admin.integrationConnector.placeholders.requestPath')" />
</div>
</div>
<details class="rounded-lg border border-slate-200 px-3 py-2">
<summary class="cursor-pointer text-xs font-bold text-secondary">{{ t('admin.integrationConnector.advancedConfig') }}</summary>
<div class="mt-2 grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.requestSpec') }}</label>
<textarea v-model="interfaceForm.request_spec_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.inputSchema') }}</label>
<textarea v-model="interfaceForm.input_schema_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.responseMapping') }}</label>
<textarea v-model="interfaceForm.response_mapping_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.outputSchema') }}</label>
<textarea v-model="interfaceForm.output_schema_json" rows="5" class="input-field text-sm font-mono" spellcheck="false" />
</div>
</div>
</details>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.status') }}</label>
<select v-model="interfaceForm.status" class="input-field text-sm">
<option value="draft">draft</option>
<option value="published">published</option>
<option value="retired">retired</option>
</select>
</div>
<div class="flex items-end pb-1">
<label class="inline-flex items-center gap-2 text-sm text-secondary cursor-pointer">
<input v-model="interfaceForm.enabled" type="checkbox" class="w-4 h-4 rounded text-brand-600 border-default" />
{{ t('admin.integrationConnector.fields.enabled') }}
</label>
</div>
</div>
</template>
<!-- 绑定 -->
<template v-else-if="activeEntity === 'binding'">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.capability') }}</label>
<select v-model="bindingForm.capability" class="input-field text-sm">
<option v-for="cap in capabilityOptions" :key="cap.name" :value="cap.name">{{ cap.name }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.environment') }}</label>
<input v-model="bindingForm.environment" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.clientInstance') }}</label>
<select v-model="bindingForm.client_instance_code" class="input-field text-sm">
<option v-for="opt in clientOptions" :key="opt.code" :value="opt.code">{{ opt.code }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.interfaceDef') }}</label>
<select v-model="bindingForm.interface_definition_code" class="input-field text-sm">
<option v-for="opt in interfaceOptions" :key="opt.code" :value="opt.code">{{ opt.code }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.mappingVersion') }}</label>
<input v-model.number="bindingForm.mapping_version" type="number" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.priority') }}</label>
<input v-model.number="bindingForm.priority" type="number" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.effectiveFrom') }}</label>
<input v-model="bindingForm.effective_from" type="datetime-local" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.effectiveTo') }}</label>
<input v-model="bindingForm.effective_to" type="datetime-local" class="input-field text-sm" />
</div>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.contextSourceCode') }}</label>
<input v-model="bindingForm.context_source_code" type="text" class="input-field text-sm" :placeholder="t('admin.integrationConnector.placeholders.contextSourceCode')" />
</div>
<details class="rounded-lg border border-slate-200 px-3 py-2">
<summary class="cursor-pointer text-xs font-bold text-secondary">{{ t('admin.integrationConnector.advancedConfig') }}</summary>
<div class="mt-2 space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.contextSelector') }}</label>
<textarea v-model="bindingForm.context_selector_json" rows="4" class="input-field text-sm font-mono" spellcheck="false" />
</div>
</details>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.status') }}</label>
<select v-model="bindingForm.status" class="input-field text-sm">
<option value="draft">draft</option>
<option value="published">published</option>
<option value="retired">retired</option>
</select>
</div>
</template>
<!-- 凭据引用 -->
<template v-else>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.code') }}</label>
<input v-model="credentialForm.code" type="text" class="input-field text-sm" :disabled="Boolean(credentialForm.id)" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.secretRef') }}</label>
<input v-model="credentialForm.secret_ref" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.secretProvider') }}</label>
<input v-model="credentialForm.secret_provider" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.credentialType') }}</label>
<input v-model="credentialForm.credential_type" type="text" class="input-field text-sm" />
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.fields.status') }}</label>
<select v-model="credentialForm.status" class="input-field text-sm">
<option value="active">active</option>
<option value="rotating">rotating</option>
<option value="retired">retired</option>
</select>
</div>
</div>
</template>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
<button type="button" class="btn-primary disabled:opacity-70" :disabled="isSaving" @click="emit('save')">
{{ isSaving ? t('admin.save') + '...' : t('admin.save') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,82 @@
<!--
features/admin/modules/integration-connector/components/JsonTextareaField.vue
用途:JSON 配置字段统一编辑器——全宽等宽 textarea + 格式化按钮 + 失焦即时校验,
供本模块四实体表单(请求模板/Schema/映射/连接配置/上下文选择器)复用。
依赖:useI18n。
逻辑:v-model 承载 JSON 文本(由父级表单 state 持有);失焦时校验,非法显示红字
提示;「格式化」仅在合法 JSON 时 pretty-print 改写,非法时只提示不改写内容。
空值视为合法(与保存链路 parseJsonField 的「空串返回 {}」一致)。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
const props = defineProps<{
/** 字段标签,同时用于错误提示中的字段名。 */
label: string;
modelValue: string;
/** 可选占位示例(如高级配置的生效键示例),空内文时展示。 */
placeholder?: string;
}>();
const emit = defineEmits<{
'update:modelValue': [value: string];
}>();
const { t } = useI18n();
const touched = ref(false);
/** 是否为合法 JSON 对象文本;空串合法。 */
const isValid = computed(() => {
const trimmed = props.modelValue.trim();
if (!trimmed) return true;
try {
const parsed = JSON.parse(trimmed);
return Boolean(parsed) && typeof parsed === 'object' && !Array.isArray(parsed);
} catch {
return false;
}
});
function onBlur() {
touched.value = true;
}
/** 格式化(pretty-print);内容为空或非法时仅标记已触碰以显示校验提示。 */
function format() {
touched.value = true;
if (!isValid.value || !props.modelValue.trim()) return;
emit('update:modelValue', JSON.stringify(JSON.parse(props.modelValue.trim()), null, 2));
}
</script>
<template>
<div class="space-y-1.5">
<div class="flex items-center justify-between gap-2">
<label class="label-field">{{ label }}</label>
<button
type="button"
class="text-xs font-medium text-brand-600 hover:text-brand-700 disabled:opacity-50 disabled:cursor-not-allowed"
:disabled="!modelValue.trim()"
data-testid="json-format-button"
@click="format"
>
{{ t('admin.integrationConnector.formatJson') }}
</button>
</div>
<textarea
:value="modelValue"
rows="12"
class="input-field text-sm font-mono leading-5"
spellcheck="false"
:placeholder="placeholder"
data-testid="json-textarea"
@input="emit('update:modelValue', ($event.target as HTMLTextAreaElement).value)"
@blur="onBlur"
/>
<p v-if="touched && !isValid" class="text-xs text-red-600" data-testid="json-error">
{{ t('admin.integrationConnector.invalidJsonHint') }}
</p>
</div>
</template>
@@ -21,10 +21,13 @@ const api = vi.hoisted(() => ({
listIntegrationInterfaceDefinitions: vi.fn(), listIntegrationInterfaceDefinitions: vi.fn(),
createIntegrationInterfaceDefinition: vi.fn(), createIntegrationInterfaceDefinition: vi.fn(),
updateIntegrationInterfaceDefinition: vi.fn(), updateIntegrationInterfaceDefinition: vi.fn(),
changeIntegrationInterfaceLifecycle: vi.fn(),
listIntegrationBindings: vi.fn(), listIntegrationBindings: vi.fn(),
createIntegrationBinding: vi.fn(), createIntegrationBinding: vi.fn(),
updateIntegrationBinding: vi.fn(), updateIntegrationBinding: vi.fn(),
changeIntegrationBindingLifecycle: vi.fn(),
listIntegrationCredentialReferences: vi.fn(), listIntegrationCredentialReferences: vi.fn(),
listIntegrationCredentialTypes: vi.fn(),
createIntegrationCredentialReference: vi.fn(), createIntegrationCredentialReference: vi.fn(),
updateIntegrationCredentialReference: vi.fn(), updateIntegrationCredentialReference: vi.fn(),
listIntegrationCapabilities: vi.fn(), listIntegrationCapabilities: vi.fn(),
@@ -55,6 +58,7 @@ describe('useIntegrationConnectorAdmin', () => {
api.listIntegrationInterfaceDefinitions.mockResolvedValue([]); api.listIntegrationInterfaceDefinitions.mockResolvedValue([]);
api.listIntegrationBindings.mockResolvedValue([]); api.listIntegrationBindings.mockResolvedValue([]);
api.listIntegrationCredentialReferences.mockResolvedValue([]); api.listIntegrationCredentialReferences.mockResolvedValue([]);
api.listIntegrationCredentialTypes.mockResolvedValue([]);
api.listIntegrationCapabilities.mockResolvedValue([]); api.listIntegrationCapabilities.mockResolvedValue([]);
const c = makeHarness(); const c = makeHarness();
await c.loadAll(); await c.loadAll();
@@ -65,14 +69,14 @@ describe('useIntegrationConnectorAdmin', () => {
it('新建客户端实例:关键字段独立列 + config_json 解析为对象并 POST', async () => { it('新建客户端实例:关键字段独立列 + config_json 解析为对象并 POST', async () => {
const c = makeHarness(); const c = makeHarness();
c.openCreateModal('client'); c.openCreateModal('client');
c.clientForm.value.code = 'ERP-X'; c.clientForm.value.code = 'erp-x';
c.clientForm.value.name = 'ERP X'; c.clientForm.value.name = 'ERP X';
c.clientForm.value.endpoint = 'https://x.invalid'; c.clientForm.value.endpoint = 'https://x.invalid';
c.clientForm.value.timeout_seconds = '90'; c.clientForm.value.timeout_seconds = '90';
c.clientForm.value.config_json = '{"headers":{"X-Tenant":"A"}}'; c.clientForm.value.config_json = '{"headers":{"X-Tenant":"A"}}';
await c.saveActive(); await c.saveActive();
expect(api.createIntegrationClientInstance).toHaveBeenCalledWith({ expect(api.createIntegrationClientInstance).toHaveBeenCalledWith({
code: 'ERP-X', name: 'ERP X', connector_type: 'rest', environment: 'prod', code: 'erp-x', name: 'ERP X', connector_type: 'rest', environment: 'prod',
endpoint: 'https://x.invalid', timeout_seconds: 90, endpoint: 'https://x.invalid', timeout_seconds: 90,
config_json: { headers: { 'X-Tenant': 'A' } }, credential_ref_code: null, enabled: true, config_json: { headers: { 'X-Tenant': 'A' } }, credential_ref_code: null, enabled: true,
}); });
@@ -81,7 +85,7 @@ describe('useIntegrationConnectorAdmin', () => {
it('编辑客户端实例:有 id 走 PUT', async () => { it('编辑客户端实例:有 id 走 PUT', async () => {
const c = makeHarness(); const c = makeHarness();
c.openEditModal('client', { c.openEditModal('client', {
id: 1, code: 'ERP-X', name: 'old', connector_type: 'rest', environment: 'prod', id: 1, code: 'erp-x', name: 'old', connector_type: 'rest', environment: 'prod',
config_json: {}, credential_ref_code: null, enabled: true, config_json: {}, credential_ref_code: null, enabled: true,
}); });
c.clientForm.value.name = 'new'; c.clientForm.value.name = 'new';
@@ -92,22 +96,41 @@ describe('useIntegrationConnectorAdmin', () => {
it('非法 JSON 字段触发拦截且不调 API', async () => { it('非法 JSON 字段触发拦截且不调 API', async () => {
const c = makeHarness(); const c = makeHarness();
c.openCreateModal('client'); c.openCreateModal('client');
c.clientForm.value.code = 'ERP-X'; c.clientForm.value.code = 'erp-x';
c.clientForm.value.name = 'ERP X'; c.clientForm.value.name = 'ERP X';
c.clientForm.value.config_json = '{bad json'; c.clientForm.value.config_json = '{bad json';
await c.saveActive(); await c.saveActive();
expect(api.createIntegrationClientInstance).not.toHaveBeenCalled(); expect(api.createIntegrationClientInstance).not.toHaveBeenCalled();
}); });
it('客户端实例必填:缺 code 不调 API', async () => { it('客户端实例必填:缺名称不调 API', async () => {
const c = makeHarness(); const c = makeHarness();
c.openCreateModal('client'); c.openCreateModal('client');
c.clientForm.value.name = 'ERP X'; c.clientForm.value.code = 'erp-x';
await c.saveActive(); await c.saveActive();
expect(api.createIntegrationClientInstance).not.toHaveBeenCalled(); expect(api.createIntegrationClientInstance).not.toHaveBeenCalled();
}); });
it('绑定:必填校验与 POST payload', async () => { it('编码留空时按名称自动生成 kebab-case 并提交', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.name = 'ERP X';
await c.saveActive();
expect(api.createIntegrationClientInstance).toHaveBeenCalledWith(
expect.objectContaining({ code: 'erp-x', name: 'ERP X' }),
);
});
it('编码格式非法(大写/下划线)时不调 API', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.name = 'ERP X';
c.clientForm.value.code = 'Bad_Code';
await c.saveActive();
expect(api.createIntegrationClientInstance).not.toHaveBeenCalled();
});
it('绑定:必填校验与 POST payload(状态与来源快捷列不随表单提交)', async () => {
const c = makeHarness(); const c = makeHarness();
c.openCreateModal('binding'); c.openCreateModal('binding');
c.bindingForm.value.capability = 'in_transit_transfer.query_inventory'; c.bindingForm.value.capability = 'in_transit_transfer.query_inventory';
@@ -116,25 +139,134 @@ describe('useIntegrationConnectorAdmin', () => {
await c.saveActive(); await c.saveActive();
expect(api.createIntegrationBinding).toHaveBeenCalledWith({ expect(api.createIntegrationBinding).toHaveBeenCalledWith({
capability: 'in_transit_transfer.query_inventory', context_selector_json: {}, capability: 'in_transit_transfer.query_inventory', context_selector_json: {},
context_source_code: null, param_mapping_json: {},
client_instance_code: 'CLI-A', interface_definition_code: 'IF-A',
mapping_version: 1, priority: 0, environment: 'prod',
effective_from: null, effective_to: null,
});
const payload = api.createIntegrationBinding.mock.calls[0][0] as Record<string, unknown>;
// 状态走列表生命周期按钮;客户端实例随接口定义联动(仍随 payload 提交)
expect(payload).not.toHaveProperty('status');
expect(payload).not.toHaveProperty('context_source_code');
});
it('绑定生命周期:publish 调动作端点并刷新绑定列表', async () => {
const c = makeHarness();
api.changeIntegrationBindingLifecycle.mockResolvedValue({});
api.listIntegrationBindings.mockResolvedValue([]);
c.bindings.value = [{
id: 7, capability: 'in_transit_transfer.query_inventory', context_selector_json: {},
client_instance_code: 'CLI-A', interface_definition_code: 'IF-A', client_instance_code: 'CLI-A', interface_definition_code: 'IF-A',
mapping_version: 1, priority: 0, environment: 'prod', mapping_version: 1, priority: 0, environment: 'prod',
effective_from: null, effective_to: null, status: 'draft', effective_from: null, effective_to: null, status: 'draft',
}); }];
await c.changeBindingLifecycle(c.bindings.value[0], 'publish');
expect(api.changeIntegrationBindingLifecycle).toHaveBeenCalledWith(7, 'publish');
expect(api.listIntegrationBindings).toHaveBeenCalled();
}); });
it('凭据引用:创建 payload 不含明文 secret', async () => { it('接口定义:编码留空按「客户端编码-名称」建议;payload 不含 connector_type/status/enabled', async () => {
const c = makeHarness();
c.openCreateModal('interface');
c.interfaceForm.value.name = '鼎捷TOPGP库存查询GetItemStockList';
c.interfaceForm.value.client_instance_code = '1001';
await c.saveActive();
expect(api.createIntegrationInterfaceDefinition).toHaveBeenCalledWith(
expect.objectContaining({ code: '1001-topgp-getitemstocklist', client_instance_code: '1001' }),
);
const payload = api.createIntegrationInterfaceDefinition.mock.calls[0][0] as Record<string, unknown>;
// 类型由后端按客户端推导、状态走生命周期按钮:均不随表单 payload 提交
expect(payload).not.toHaveProperty('connector_type');
expect(payload).not.toHaveProperty('status');
expect(payload).not.toHaveProperty('enabled');
});
it('接口定义生命周期:publish 调动作端点并刷新接口列表', async () => {
const c = makeHarness();
api.changeIntegrationInterfaceLifecycle.mockResolvedValue({});
api.listIntegrationInterfaceDefinitions.mockResolvedValue([]);
c.interfaces.value = [{
id: 9, code: 'IF-LC', name: 'iface', client_instance_code: 'CLI-A', connector_type: 'rest',
http_method: null, request_path: null, request_spec_json: {}, input_schema_json: {},
response_mapping_json: {}, output_schema_json: {}, version: 1, status: 'draft', enabled: true,
}];
await c.changeInterfaceLifecycle(c.interfaces.value[0], 'publish');
expect(api.changeIntegrationInterfaceLifecycle).toHaveBeenCalledWith('IF-LC', 'publish');
expect(api.listIntegrationInterfaceDefinitions).toHaveBeenCalled();
});
it('凭据引用 env 模式:创建 payload 只含 secret_ref,不含明文 secret', async () => {
const c = makeHarness(); const c = makeHarness();
c.openCreateModal('credential'); c.openCreateModal('credential');
c.credentialForm.value.secret_provider = 'env';
c.credentialForm.value.code = 'CRED-A'; c.credentialForm.value.code = 'CRED-A';
c.credentialForm.value.secret_ref = 'IN_TRANSIT_ERP_PASSWORD'; c.credentialForm.value.secret_ref = 'IN_TRANSIT_ERP_PASSWORD';
await c.saveActive(); await c.saveActive();
expect(api.createIntegrationCredentialReference).toHaveBeenCalledWith({ expect(api.createIntegrationCredentialReference).toHaveBeenCalledWith({
code: 'CRED-A', secret_ref: 'IN_TRANSIT_ERP_PASSWORD', secret_provider: 'env', code: 'CRED-A', secret_provider: 'env',
credential_type: 'password', status: 'active',
secret_ref: 'IN_TRANSIT_ERP_PASSWORD',
});
});
it('凭据引用 db 模式:创建 payload 按类型字段组装,不含 secret_ref', async () => {
const c = makeHarness();
c.credentialTypes.value = [
{ type: 'password', fields: [
{ key: 'username', secret: false, required: true },
{ key: 'password', secret: true, required: true },
] },
];
c.openCreateModal('credential');
c.credentialForm.value.code = 'CRED-DB';
c.credentialForm.value.fields = { username: 'erp_user', password: 'erp_pass' };
await c.saveActive();
expect(api.createIntegrationCredentialReference).toHaveBeenCalledWith({
code: 'CRED-DB', secret_provider: 'db',
credential_type: 'password', status: 'active',
username: 'erp_user', password: 'erp_pass',
});
});
it('凭据引用 db 模式:编辑时全部字段留空 → payload 不带凭据键(仅元数据)', async () => {
const c = makeHarness();
c.credentialTypes.value = [{ type: 'password', fields: [
{ key: 'username', secret: false, required: true },
{ key: 'password', secret: true, required: true },
] }];
c.openCreateModal('credential');
c.credentialForm.value.id = 9;
c.credentialForm.value.code = 'CRED-DB';
c.credentialForm.value.fields = {};
await c.saveActive();
expect(api.updateIntegrationCredentialReference).toHaveBeenCalledWith('CRED-DB', {
code: 'CRED-DB', secret_provider: 'db',
credential_type: 'password', status: 'active', credential_type: 'password', status: 'active',
}); });
}); });
it('凭据引用 db 模式:新建缺必填字段 → 不调 API', async () => {
const c = makeHarness();
c.credentialTypes.value = [{ type: 'password', fields: [
{ key: 'username', secret: false, required: true },
{ key: 'password', secret: true, required: true },
] }];
c.openCreateModal('credential');
c.credentialForm.value.code = 'CRED-DB';
c.credentialForm.value.fields = { username: 'only-user' };
await c.saveActive();
expect(api.createIntegrationCredentialReference).not.toHaveBeenCalled();
});
it('凭据引用 db 模式:类型未注册 → 不调 API', async () => {
const c = makeHarness();
c.openCreateModal('credential');
c.credentialForm.value.code = 'CRED-X';
c.credentialForm.value.credential_type = 'unknown';
await c.saveActive();
expect(api.createIntegrationCredentialReference).not.toHaveBeenCalled();
});
it('连接测试与能力调用走对应 API', async () => { it('连接测试与能力调用走对应 API', async () => {
const c = makeHarness(); const c = makeHarness();
api.testIntegrationClientConnection.mockResolvedValue({ ok: true }); api.testIntegrationClientConnection.mockResolvedValue({ ok: true });
@@ -145,4 +277,102 @@ describe('useIntegrationConnectorAdmin', () => {
await c.runCall(); await c.runCall();
expect(api.callIntegrationCapability).toHaveBeenCalled(); expect(api.callIntegrationCapability).toHaveBeenCalled();
}); });
it('连接测试结果按行存放:probe 失败归 ok=false 并带原因码', async () => {
const c = makeHarness();
api.testIntegrationClientConnection.mockResolvedValue({
ok: false, status: 'failed', result: { ok: false, code: 'HTTP_502', message: 'bad gateway' },
});
await c.testConnection('CLI-A');
expect(c.testResults.value['CLI-A']).toEqual({ ok: false, code: 'HTTP_502', message: 'bad gateway' });
});
it('行内启停:切换调用 PUT,失败自动回滚', async () => {
const c = makeHarness();
api.updateIntegrationClientInstance.mockRejectedValue(new Error('network down'));
const row = { code: 'CLI-A', enabled: true };
await c.toggleClient(row);
expect(api.updateIntegrationClientInstance).toHaveBeenCalledWith('CLI-A', { enabled: false });
expect(row.enabled).toBe(true);
api.updateIntegrationClientInstance.mockResolvedValue({});
await c.toggleClient(row);
expect(row.enabled).toBe(false);
});
it('凭据状态行内切换:只传 status 调 PUT,rotating 视为启用侧,失败回滚', async () => {
const c = makeHarness();
api.updateIntegrationCredentialReference.mockResolvedValue({});
const row = { code: 'CRED-A', status: 'active' };
await c.toggleCredential(row);
expect(api.updateIntegrationCredentialReference).toHaveBeenCalledWith('CRED-A', { status: 'retired' });
expect(row.status).toBe('retired');
// rotating 非停用态:点击即停用
const rotating = { code: 'CRED-B', status: 'rotating' };
await c.toggleCredential(rotating);
expect(api.updateIntegrationCredentialReference).toHaveBeenCalledWith('CRED-B', { status: 'retired' });
// 停用态点击切回启用;失败时回滚保持停用
api.updateIntegrationCredentialReference.mockRejectedValue(new Error('network down'));
await c.toggleCredential(row);
expect(row.status).toBe('retired');
});
it('删除客户端实例需确认:拒绝不调 API,确认才删', async () => {
const c = makeHarness();
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
await c.deleteClient({ code: 'CLI-A', name: '客户端A' });
expect(confirmSpy).toHaveBeenCalledTimes(1);
expect(api.deleteIntegrationClientInstance).not.toHaveBeenCalled();
confirmSpy.mockReturnValue(true);
await c.deleteClient({ code: 'CLI-A', name: '客户端A' });
expect(api.deleteIntegrationClientInstance).toHaveBeenCalledWith('CLI-A');
vi.restoreAllMocks();
});
it('接口退役需确认:拒绝不调 API,确认才调', async () => {
const c = makeHarness();
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
api.changeIntegrationInterfaceLifecycle.mockResolvedValue({});
api.listIntegrationInterfaceDefinitions.mockResolvedValue([]);
c.interfaces.value = [{
id: 3, code: 'IF-R', name: 'iface', client_instance_code: 'CLI-A', connector_type: 'rest',
http_method: null, request_path: null, request_spec_json: {}, input_schema_json: {},
response_mapping_json: {}, output_schema_json: {}, version: 1, status: 'published', enabled: true,
}];
// 退役接近终态且使引用绑定同时失效:确认拒绝则不调 API
await c.changeInterfaceLifecycle(c.interfaces.value[0], 'retire');
expect(confirmSpy).toHaveBeenCalledTimes(1);
expect(api.changeIntegrationInterfaceLifecycle).not.toHaveBeenCalled();
confirmSpy.mockReturnValue(true);
await c.changeInterfaceLifecycle(c.interfaces.value[0], 'retire');
expect(api.changeIntegrationInterfaceLifecycle).toHaveBeenCalledWith('IF-R', 'retire');
vi.restoreAllMocks();
});
it('可逆转移(撤回)免确认直达;进行中重复触发被互斥忽略', async () => {
const c = makeHarness();
const confirmSpy = vi.spyOn(window, 'confirm');
let resolveApi!: (value: unknown) => void;
api.changeIntegrationInterfaceLifecycle.mockImplementation(
() => new Promise((resolve) => { resolveApi = resolve; }),
);
api.listIntegrationInterfaceDefinitions.mockResolvedValue([]);
c.interfaces.value = [{
id: 4, code: 'IF-U', name: 'iface', client_instance_code: 'CLI-A', connector_type: 'rest',
http_method: null, request_path: null, request_spec_json: {}, input_schema_json: {},
response_mapping_json: {}, output_schema_json: {}, version: 1, status: 'published', enabled: true,
}];
// 第一次触发占用互斥锁;第二次在其完成前触发应被忽略(防连点)
const first = c.changeInterfaceLifecycle(c.interfaces.value[0], 'unpublish');
const second = c.changeInterfaceLifecycle(c.interfaces.value[0], 'unpublish');
resolveApi({});
await Promise.all([first, second]);
expect(api.changeIntegrationInterfaceLifecycle).toHaveBeenCalledTimes(1);
// 可逆转移不弹确认
expect(confirmSpy).not.toHaveBeenCalled();
vi.restoreAllMocks();
});
}); });
@@ -3,14 +3,23 @@
* 集成连接器管理编排:客户端实例/接口定义/绑定/凭据引用四实体列表与增改表单, * 集成连接器管理编排:客户端实例/接口定义/绑定/凭据引用四实体列表与增改表单,
* 以及能力清单与手动调用测试。 * 以及能力清单与手动调用测试。
* 依赖:integration-connector.api、types、useMessage、useI18n。 * 依赖:integration-connector.api、types、useMessage、useI18n。
* 逻辑:各列表独立 loadAll;新增/编辑共用表单弹窗态(form.id 区分);能力测试 * 逻辑:各列表独立 loadAll;新增/编辑共用表单弹窗态(form.id 区分);客户端编码
* 独立于配置表单(CapabilityCall 弹窗)。保存/删除后刷新对应列表。 * 可手改、留空按名称自动生成,接口定义编码留空按「客户端编码-名称」自动建议;
* 接口与绑定状态只经 change*Lifecycle 按钮流转(表单内只读徽章);绑定表单的
* 客户端实例随所选接口定义联动带出并锁定(接口归属即客户端归属);
* 凭据状态只经列表行内开关流转(启用↔停用,表单不维护状态);
* 全部行内状态操作经 lifecycleBusy 互斥(进行中忽略新触发);接口/绑定退役
* 接近终态需 window.confirm 二次确认,可逆转移直达;
* 连接测试结果按行存放(列表徽章+展开详情);
* 启停支持行内开关(失败回滚);删除带确认。保存/删除后刷新对应列表。
*/ */
import { ref } from 'vue'; import { ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useMessage } from '@/shared/composables/useMessage'; import { useMessage } from '@/shared/composables/useMessage';
import { import {
callIntegrationCapability, callIntegrationCapability,
changeIntegrationBindingLifecycle,
changeIntegrationInterfaceLifecycle,
createIntegrationBinding, createIntegrationBinding,
createIntegrationClientInstance, createIntegrationClientInstance,
createIntegrationCredentialReference, createIntegrationCredentialReference,
@@ -20,6 +29,7 @@ import {
listIntegrationCapabilities, listIntegrationCapabilities,
listIntegrationClientInstances, listIntegrationClientInstances,
listIntegrationCredentialReferences, listIntegrationCredentialReferences,
listIntegrationCredentialTypes,
listIntegrationInterfaceDefinitions, listIntegrationInterfaceDefinitions,
testIntegrationClientConnection, testIntegrationClientConnection,
updateIntegrationBinding, updateIntegrationBinding,
@@ -30,13 +40,18 @@ import {
import { import {
bindingRowToForm, bindingRowToForm,
clientInstanceRowToForm, clientInstanceRowToForm,
CLIENT_CODE_PATTERN,
createEmptyBindingForm, createEmptyBindingForm,
createEmptyClientInstanceForm, createEmptyClientInstanceForm,
createEmptyCredentialReferenceForm, createEmptyCredentialReferenceForm,
createEmptyInterfaceDefinitionForm, createEmptyInterfaceDefinitionForm,
credentialReferenceRowToForm, credentialReferenceRowToForm,
interfaceDefinitionRowToForm, interfaceDefinitionRowToForm,
normalizeConnectionTestResponse,
suggestClientCode,
suggestInterfaceCode,
type BindingFormState, type BindingFormState,
type ClientConnectionTestResult,
type ClientInstanceFormState, type ClientInstanceFormState,
type CredentialReferenceFormState, type CredentialReferenceFormState,
type IntegrationBindingRow, type IntegrationBindingRow,
@@ -44,12 +59,17 @@ import {
type IntegrationCapabilityRow, type IntegrationCapabilityRow,
type IntegrationClientInstanceRow, type IntegrationClientInstanceRow,
type IntegrationCredentialReferenceRow, type IntegrationCredentialReferenceRow,
type IntegrationCredentialTypeSpec,
type IntegrationInterfaceDefinitionRow, type IntegrationInterfaceDefinitionRow,
type InterfaceDefinitionFormState, type InterfaceDefinitionFormState,
} from '../types/integration-connector.types'; } from '../types/integration-connector.types';
type EditableEntity = 'client' | 'interface' | 'binding' | 'credential'; type EditableEntity = 'client' | 'interface' | 'binding' | 'credential';
/** 接口定义/绑定生命周期动作(与后端 CONFIG_STATUS_TRANSITIONS 一一对应)。 */
export type InterfaceLifecycleAction = 'publish' | 'unpublish' | 'retire' | 'reopen';
export type BindingLifecycleAction = InterfaceLifecycleAction;
export function useIntegrationConnectorAdmin() { export function useIntegrationConnectorAdmin() {
const { t } = useI18n(); const { t } = useI18n();
const msg = useMessage(); const msg = useMessage();
@@ -60,6 +80,7 @@ export function useIntegrationConnectorAdmin() {
const bindings = ref<IntegrationBindingRow[]>([]); const bindings = ref<IntegrationBindingRow[]>([]);
const credentials = ref<IntegrationCredentialReferenceRow[]>([]); const credentials = ref<IntegrationCredentialReferenceRow[]>([]);
const capabilities = ref<IntegrationCapabilityRow[]>([]); const capabilities = ref<IntegrationCapabilityRow[]>([]);
const credentialTypes = ref<IntegrationCredentialTypeSpec[]>([]);
const isLoading = ref(true); const isLoading = ref(true);
// ---- 表单弹窗态 ---- // ---- 表单弹窗态 ----
@@ -79,14 +100,32 @@ export function useIntegrationConnectorAdmin() {
const callResult = ref<IntegrationCallResultRow | null>(null); const callResult = ref<IntegrationCallResultRow | null>(null);
const callBusy = ref(false); const callBusy = ref(false);
// ---- 连接测试 ---- // ---- 连接测试(结果按客户端编码存放,供列表行内徽章 + 可展开详情) ----
const testingClientCode = ref(''); const testingClientCode = ref('');
const testResultText = ref(''); const testResults = ref<Record<string, ClientConnectionTestResult>>({});
// ---- 状态转移互斥锁:任一启停/生命周期转移进行中即忽略新转移,防连点与并发转移 ----
const lifecycleBusy = ref(false);
/** 行内状态操作统一入口:busy 互斥包裹,进行中重复触发直接忽略。 */
const runStateToggle = async (fn: () => Promise<void>) => {
if (lifecycleBusy.value) return;
lifecycleBusy.value = true;
try {
await fn();
} finally {
lifecycleBusy.value = false;
}
};
const loadClients = async () => { clients.value = await listIntegrationClientInstances(); }; const loadClients = async () => { clients.value = await listIntegrationClientInstances(); };
const loadInterfaces = async () => { interfaces.value = await listIntegrationInterfaceDefinitions(); }; const loadInterfaces = async () => { interfaces.value = await listIntegrationInterfaceDefinitions(); };
const loadBindings = async () => { bindings.value = await listIntegrationBindings(); }; const loadBindings = async () => { bindings.value = await listIntegrationBindings(); };
const loadCredentials = async () => { credentials.value = await listIntegrationCredentialReferences(); }; const loadCredentials = async () => {
const [rows, typeSpecs] = await Promise.all([listIntegrationCredentialReferences(), listIntegrationCredentialTypes()]);
credentials.value = rows;
credentialTypes.value = typeSpecs;
};
const loadCapabilities = async () => { capabilities.value = await listIntegrationCapabilities(); }; const loadCapabilities = async () => { capabilities.value = await listIntegrationCapabilities(); };
const loadAll = async () => { const loadAll = async () => {
@@ -154,37 +193,45 @@ export function useIntegrationConnectorAdmin() {
try { try {
if (activeEntity.value === 'client') { if (activeEntity.value === 'client') {
const form = clientForm.value; const form = clientForm.value;
if (!form.code.trim() || !form.name.trim()) { if (!form.name.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillClient')); msg.warning(t('admin.integrationConnector.msg.fillClient'));
return; return;
} }
// 编码可由用户手改;留空时按名称兜底自动生成(唯一性由后端 409 兜底)。
const code = form.code.trim() || suggestClientCode(form.name);
if (!CLIENT_CODE_PATTERN.test(code)) {
msg.warning(t('admin.integrationConnector.msg.codeInvalid'));
return;
}
const configJson = parseJsonField(form.config_json, 'config_json'); const configJson = parseJsonField(form.config_json, 'config_json');
const payload = { const payload = {
code: form.code.trim(), name: form.name.trim(), connector_type: form.connector_type, code, name: form.name.trim(), connector_type: form.connector_type,
environment: form.environment, environment: form.environment,
endpoint: form.endpoint.trim() || null, endpoint: form.endpoint.trim() || null,
timeout_seconds: form.timeout_seconds.trim() ? Number(form.timeout_seconds) : null, timeout_seconds: form.timeout_seconds.trim() ? Number(form.timeout_seconds) : null,
config_json: configJson, config_json: configJson,
credential_ref_code: form.credential_ref_code.trim() || null, enabled: form.enabled, credential_ref_code: form.credential_ref_code.trim() || null, enabled: form.enabled,
}; };
if (form.id) await updateIntegrationClientInstance(form.code, payload); if (form.id) await updateIntegrationClientInstance(code, payload);
else await createIntegrationClientInstance(payload); else await createIntegrationClientInstance(payload);
} else if (activeEntity.value === 'interface') { } else if (activeEntity.value === 'interface') {
const form = interfaceForm.value; const form = interfaceForm.value;
if (!form.code.trim() || !form.client_instance_code.trim()) { if (!form.client_instance_code.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillInterface')); msg.warning(t('admin.integrationConnector.msg.fillInterface'));
return; return;
} }
// 编码留空时按「客户端实例编码-名称」自动建议(可手改;全局唯一由后端 409 兜底)。
// 连接器类型/状态/启用不随表单提交:类型由后端按客户端实例推导,状态走生命周期按钮。
const code = form.code.trim() || suggestInterfaceCode(form.client_instance_code, form.name);
const payload = { const payload = {
code: form.code.trim(), name: form.name.trim() || form.code.trim(), code, name: form.name.trim() || code,
client_instance_code: form.client_instance_code.trim(), connector_type: form.connector_type, client_instance_code: form.client_instance_code.trim(),
http_method: form.http_method.trim() || null, http_method: form.http_method.trim() || null,
request_path: form.request_path.trim() || null, request_path: form.request_path.trim() || null,
request_spec_json: parseJsonField(form.request_spec_json, 'request_spec_json'), request_spec_json: parseJsonField(form.request_spec_json, 'request_spec_json'),
input_schema_json: parseJsonField(form.input_schema_json, 'input_schema_json'), input_schema_json: parseJsonField(form.input_schema_json, 'input_schema_json'),
response_mapping_json: parseJsonField(form.response_mapping_json, 'response_mapping_json'), response_mapping_json: parseJsonField(form.response_mapping_json, 'response_mapping_json'),
output_schema_json: parseJsonField(form.output_schema_json, 'output_schema_json'), output_schema_json: parseJsonField(form.output_schema_json, 'output_schema_json'),
status: form.status, enabled: form.enabled,
}; };
if (form.id) await updateIntegrationInterfaceDefinition(form.code, payload); if (form.id) await updateIntegrationInterfaceDefinition(form.code, payload);
else await createIntegrationInterfaceDefinition(payload); else await createIntegrationInterfaceDefinition(payload);
@@ -194,26 +241,55 @@ export function useIntegrationConnectorAdmin() {
msg.warning(t('admin.integrationConnector.msg.fillBinding')); msg.warning(t('admin.integrationConnector.msg.fillBinding'));
return; return;
} }
// 客户端实例随所选接口定义联动带出(接口归属即客户端归属);
// 状态不随表单提交:新建固定 draft,发布/退役走列表生命周期按钮。
const payload = { const payload = {
capability: form.capability.trim(), context_selector_json: parseJsonField(form.context_selector_json, 'context_selector_json'), capability: form.capability.trim(), context_selector_json: parseJsonField(form.context_selector_json, 'context_selector_json'),
context_source_code: form.context_source_code.trim() || null, param_mapping_json: parseJsonField(form.param_mapping_json, 'param_mapping_json'),
client_instance_code: form.client_instance_code.trim(), interface_definition_code: form.interface_definition_code.trim(), client_instance_code: form.client_instance_code.trim(), interface_definition_code: form.interface_definition_code.trim(),
mapping_version: Number(form.mapping_version || 1), priority: Number(form.priority || 0), mapping_version: Number(form.mapping_version || 1), priority: Number(form.priority || 0),
environment: form.environment, effective_from: form.effective_from || null, effective_to: form.effective_to || null, environment: form.environment, effective_from: form.effective_from || null, effective_to: form.effective_to || null,
status: form.status,
}; };
if (form.id) await updateIntegrationBinding(form.id, payload); if (form.id) await updateIntegrationBinding(form.id, payload);
else await createIntegrationBinding(payload); else await createIntegrationBinding(payload);
} else { } else {
const form = credentialForm.value; const form = credentialForm.value;
if (!form.code.trim() || !form.secret_ref.trim()) { // db 模式:按凭据类型注册表动态字段,界面维护、服务端加密落库;
// 编辑时密文字段留空 = 沿用旧值。env 模式:只存环境配置键名。
if (!form.code.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillCredential')); msg.warning(t('admin.integrationConnector.msg.fillCredential'));
return; return;
} }
const payload = { const payload: Record<string, unknown> = {
code: form.code.trim(), secret_ref: form.secret_ref.trim(), secret_provider: form.secret_provider, code: form.code.trim(), secret_provider: form.secret_provider,
credential_type: form.credential_type, status: form.status, credential_type: form.credential_type, status: form.status,
}; };
if (form.secret_provider === 'db') {
const typeSpec = credentialTypes.value.find((item) => item.type === form.credential_type);
if (!typeSpec) {
msg.warning(t('admin.integrationConnector.msg.credentialTypeMissing'));
return;
}
if (!form.id) {
const missing = typeSpec.fields
.filter((field) => field.required && !(form.fields[field.key] || '').trim())
.map((field) => t(`admin.integrationConnector.credentialFields.${field.key}`, field.key));
if (missing.length) {
msg.warning(t('admin.integrationConnector.msg.fillCredentialDb', { fields: missing.join('、') }));
return;
}
}
for (const field of typeSpec.fields) {
const value = (form.fields[field.key] || '').trim();
if (value) payload[field.key] = value;
}
} else {
if (!form.secret_ref.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillCredential'));
return;
}
payload.secret_ref = form.secret_ref.trim();
}
if (form.id) await updateIntegrationCredentialReference(form.code, payload); if (form.id) await updateIntegrationCredentialReference(form.code, payload);
else await createIntegrationCredentialReference(payload); else await createIntegrationCredentialReference(payload);
} }
@@ -233,11 +309,11 @@ export function useIntegrationConnectorAdmin() {
// ---- 连接测试 ---- // ---- 连接测试 ----
const testConnection = async (code: string) => { const testConnection = async (code: string) => {
testingClientCode.value = code; testingClientCode.value = code;
testResultText.value = '';
try { try {
const result = await testIntegrationClientConnection(code); const normalized = normalizeConnectionTestResponse(await testIntegrationClientConnection(code));
testResultText.value = JSON.stringify(result, null, 2); testResults.value = { ...testResults.value, [code]: normalized };
msg.success(t('admin.integrationConnector.msg.testOk')); if (normalized.ok) msg.success(t('admin.integrationConnector.msg.testOk'));
else msg.error(t('admin.integrationConnector.msg.testFailed', { code: normalized.code }));
} catch (e) { } catch (e) {
msg.error((e as Error).message || t('admin.msg.requestFailed')); msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally { } finally {
@@ -245,6 +321,64 @@ export function useIntegrationConnectorAdmin() {
} }
}; };
// ---- 行内启停:直接切换 enabled;失败回滚并提示 ----
const toggleClient = async (row: IntegrationClientInstanceRow) => {
await runStateToggle(async () => {
const target = !row.enabled;
row.enabled = target;
try {
await updateIntegrationClientInstance(row.code, { enabled: target });
} catch (e) {
row.enabled = !target;
msg.error((e as Error).message || t('admin.integrationConnector.msg.toggleFailed'));
}
});
};
// ---- 凭据状态行内切换:启用↔停用(rotating 视为启用侧,点击即停用);解析层只认 active,停用即断流;失败回滚并提示 ----
const toggleCredential = async (row: IntegrationCredentialReferenceRow) => {
await runStateToggle(async () => {
const target = row.status === 'retired' ? 'active' : 'retired';
const prev = row.status;
row.status = target;
try {
await updateIntegrationCredentialReference(row.code, { status: target });
} catch (e) {
row.status = prev;
msg.error((e as Error).message || t('admin.integrationConnector.msg.toggleFailed'));
}
});
};
// ---- 接口定义生命周期:发布/撤回/退役/恢复(状态唯一入口,后端转移表校验) ----
// 退役接近终态且使引用该接口的绑定同时失效 → 二次确认;其余转移可逆,免确认直达。
const changeInterfaceLifecycle = async (row: IntegrationInterfaceDefinitionRow, action: InterfaceLifecycleAction) => {
await runStateToggle(async () => {
if (action === 'retire' && !window.confirm(t('admin.integrationConnector.msg.retireInterfaceConfirm'))) return;
try {
await changeIntegrationInterfaceLifecycle(row.code, action);
await loadInterfaces();
msg.success(t('admin.integrationConnector.msg.statusUpdated'));
} catch (e) {
msg.error((e as Error).message || t('admin.integrationConnector.msg.statusUpdateFailed'));
}
});
};
// ---- 绑定生命周期:发布/撤回/退役/恢复(状态唯一入口,后端转移表 + 发布就绪门禁校验) ----
const changeBindingLifecycle = async (row: IntegrationBindingRow, action: BindingLifecycleAction) => {
await runStateToggle(async () => {
if (action === 'retire' && !window.confirm(t('admin.integrationConnector.msg.retireBindingConfirm'))) return;
try {
await changeIntegrationBindingLifecycle(row.id, action);
await loadBindings();
msg.success(t('admin.integrationConnector.msg.statusUpdated'));
} catch (e) {
msg.error((e as Error).message || t('admin.integrationConnector.msg.statusUpdateFailed'));
}
});
};
// ---- 能力调用测试 ---- // ---- 能力调用测试 ----
const openCallModal = (capability: string) => { const openCallModal = (capability: string) => {
callCapability.value = capability; callCapability.value = capability;
@@ -274,9 +408,14 @@ export function useIntegrationConnectorAdmin() {
} }
}; };
const deleteClient = async (code: string) => { /** 删除客户端实例:先确认(提示语带名称),确认后才调 API。 */
const deleteClient = async (row: IntegrationClientInstanceRow) => {
const summary = t('admin.integrationConnector.msg.deleteConfirm', { code: row.code, name: row.name });
if (!window.confirm(summary)) return;
try { try {
await deleteIntegrationClientInstance(code); await deleteIntegrationClientInstance(row.code);
const { [row.code]: _removed, ...rest } = testResults.value;
testResults.value = rest;
await loadClients(); await loadClients();
msg.success(t('admin.integrationConnector.msg.deleted')); msg.success(t('admin.integrationConnector.msg.deleted'));
} catch (e) { } catch (e) {
@@ -285,12 +424,14 @@ export function useIntegrationConnectorAdmin() {
}; };
return { return {
clients, interfaces, bindings, credentials, capabilities, clients, interfaces, bindings, credentials, capabilities, credentialTypes,
isLoading, activeEntity, showFormModal, isSaving, isLoading, activeEntity, showFormModal, isSaving,
clientForm, interfaceForm, bindingForm, credentialForm, clientForm, interfaceForm, bindingForm, credentialForm,
showCallModal, callCapability, callParamsText, callContextText, callResult, callBusy, showCallModal, callCapability, callParamsText, callContextText, callResult, callBusy,
testingClientCode, testResultText, testingClientCode, testResults,
lifecycleBusy,
loadAll, openCreateModal, openEditModal, closeFormModal, saveActive, loadAll, openCreateModal, openEditModal, closeFormModal, saveActive,
testConnection, openCallModal, closeCallModal, runCall, deleteClient, testConnection, toggleClient, toggleCredential, openCallModal, closeCallModal, runCall, deleteClient,
changeInterfaceLifecycle, changeBindingLifecycle,
}; };
} }
@@ -9,12 +9,104 @@
/** 连接器类型:与后端 CONNECTOR_TYPES 对齐。 */ /** 连接器类型:与后端 CONNECTOR_TYPES 对齐。 */
export type IntegrationConnectorType = 'rest' | 'soap'; export type IntegrationConnectorType = 'rest' | 'soap';
/** 连接器类型选项(labelKey 为 i18n 键;新增类型在此追加一行并补四语言文案)。 */
export const CONNECTOR_TYPE_OPTIONS: ReadonlyArray<{ value: IntegrationConnectorType; labelKey: string }> = [
{ value: 'rest', labelKey: 'admin.integrationConnector.connectorTypes.rest' },
{ value: 'soap', labelKey: 'admin.integrationConnector.connectorTypes.soap' },
];
/** 环境选项(与发布流程 dev→test→prod 对齐;新增环境在此追加并补四语言文案)。 */
export const ENVIRONMENT_OPTIONS = ['dev', 'test', 'prod'] as const;
/** 各连接器类型当前生效的 config_json 键(高级配置帮助文案依据,与 transports 消费代码对齐)。 */
export const CONNECTOR_CONFIG_KEYS: Readonly<Record<string, ReadonlyArray<string>>> = {
rest: ['headers'],
soap: [],
};
/** 客户端编码规则:小写字母/数字开头,仅小写字母、数字、连字符(保存后不可改)。 */
export const CLIENT_CODE_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
/** 编码最大长度(与后端 String(64) 列宽一致)。 */
const CODE_MAX_LENGTH = 64;
/** 由名称提取编码 slug:拉丁字符转 kebab-case;无拉丁字符(如纯中文)返回空串。 */
function slugifyName(name: string): string {
return String(name || '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}
/** 由名称建议客户端编码:slug 为空时回退 conn-xxxx(可手改,保存后不可改)。 */
export function suggestClientCode(name: string): string {
const slug = slugifyName(name);
if (slug) return slug.slice(0, CODE_MAX_LENGTH);
return `conn-${Math.random().toString(36).slice(2, 6)}`;
}
/**
* 建议接口定义编码:客户端编码前缀 + 名称 slug(如 1001-topgp-getitemstocklist)。
* 前缀降低跨客户端撞码概率,slug 保证同一客户端下多个接口可区分;
* 仅是建议值(可手改),全局唯一仍由后端 409 兜底。
*/
export function suggestInterfaceCode(clientCode: string, name: string): string {
const prefix = String(clientCode || '').trim();
if (!prefix) return '';
const slug = slugifyName(name);
const suffix = slug || Math.random().toString(36).slice(2, 6);
return `${prefix}-${suffix}`.slice(0, CODE_MAX_LENGTH);
}
/** 行内连接测试结果(列表徽章 + 可展开详情的数据模型)。 */
export interface ClientConnectionTestResult {
ok: boolean;
code: string;
message: string;
}
/** 连接测试接口响应(后端返回 { ok, status, result },result 为传输层 raw dict)。 */
export interface ClientConnectionTestResponse {
ok?: boolean;
status?: string;
result?: Record<string, unknown>;
}
const CALL_FAILURE_STATUSES = ['business_failed', 'technical_failed', 'timeout', 'result_unknown'];
/** 把连接测试响应归一为行内展示模型:优先 probe 结果;回退兼容只实现 call 的传输 raw dict。 */
export function normalizeConnectionTestResponse(response: ClientConnectionTestResponse): ClientConnectionTestResult {
const raw = response.result ?? {};
if (typeof raw.ok === 'boolean') {
return { ok: raw.ok, code: String(raw.code ?? ''), message: String(raw.message ?? '') };
}
const status = String(raw.status ?? response.status ?? '');
return {
ok: !CALL_FAILURE_STATUSES.includes(status),
code: String(raw.code ?? status),
message: String(raw.message ?? ''),
};
}
/** 配置状态:draft 草稿 / published 已发布 / retired 已退役。 */ /** 配置状态:draft 草稿 / published 已发布 / retired 已退役。 */
export type IntegrationConfigStatus = 'draft' | 'published' | 'retired'; export type IntegrationConfigStatus = 'draft' | 'published' | 'retired';
/** 凭据状态。 */ /** 凭据状态。 */
export type IntegrationCredentialStatus = 'active' | 'rotating' | 'retired'; export type IntegrationCredentialStatus = 'active' | 'rotating' | 'retired';
/** 凭据类型字段定义(secret=加密落库且永不回显;required 合并旧值后仍必填)。 */
export interface IntegrationCredentialTypeField {
key: string;
secret: boolean;
required: boolean;
}
/** 凭据类型规格(后端代码注册表下发,UI 按其动态渲染字段)。 */
export interface IntegrationCredentialTypeSpec {
type: string;
fields: IntegrationCredentialTypeField[];
}
/** 能力清单项(后端 capability 注册表)。 */ /** 能力清单项(后端 capability 注册表)。 */
export interface IntegrationCapabilityRow { export interface IntegrationCapabilityRow {
name: string; name: string;
@@ -71,7 +163,7 @@ export interface IntegrationBindingRow {
id: number; id: number;
capability: string; capability: string;
context_selector_json: Record<string, unknown>; context_selector_json: Record<string, unknown>;
context_source_code: string | null; param_mapping_json: Record<string, unknown>;
client_instance_code: string; client_instance_code: string;
interface_definition_code: string; interface_definition_code: string;
mapping_version: number; mapping_version: number;
@@ -82,15 +174,18 @@ export interface IntegrationBindingRow {
status: IntegrationConfigStatus; status: IntegrationConfigStatus;
} }
/** 凭据引用(只存 secret_ref,不落明文)。 */ /** 凭据引用(db 模式按类型加密落库不落明文;env 模式存环境配置键名)。 */
export interface IntegrationCredentialReferenceRow { export interface IntegrationCredentialReferenceRow {
id: number; id: number;
code: string; code: string;
secret_ref: string; secret_ref: string;
secret_provider: string; secret_provider: string;
credential_type: string; credential_type: string;
secret_fields: Record<string, string>;
has_secret: boolean;
version: number; version: number;
status: IntegrationCredentialStatus; status: IntegrationCredentialStatus;
updated_at: string | null;
last_verified_at: string | null; last_verified_at: string | null;
} }
@@ -108,7 +203,11 @@ export interface ClientInstanceFormState {
enabled: boolean; enabled: boolean;
} }
/** 接口定义表单(JSON 字段以文本承载,提交时解析)。 */ /**
* 接口定义表单(JSON 字段以文本承载,提交时解析)。
* connector_type 仅作展示:随所选客户端实例联动回填,提交时后端以客户端实例为单一事实源推导;
* status 仅作徽章展示:新建固定 draft,发布/退役经列表生命周期按钮流转,均不随表单提交。
*/
export interface InterfaceDefinitionFormState { export interface InterfaceDefinitionFormState {
id: number | null; id: number | null;
code: string; code: string;
@@ -122,15 +221,18 @@ export interface InterfaceDefinitionFormState {
response_mapping_json: string; response_mapping_json: string;
output_schema_json: string; output_schema_json: string;
status: IntegrationConfigStatus; status: IntegrationConfigStatus;
enabled: boolean;
} }
/** 绑定表单。 */ /**
* 绑定表单(JSON 字段以文本承载,提交时解析)。
* client_instance_code 随所选接口定义联动带出并锁定(接口归属即客户端归属),仍随表单提交;
* status 仅作徽章展示:新建固定 draft,发布/退役经列表生命周期按钮流转,均不随表单提交。
*/
export interface BindingFormState { export interface BindingFormState {
id: number | null; id: number | null;
capability: string; capability: string;
context_selector_json: string; context_selector_json: string;
context_source_code: string; param_mapping_json: string;
client_instance_code: string; client_instance_code: string;
interface_definition_code: string; interface_definition_code: string;
mapping_version: number; mapping_version: number;
@@ -141,13 +243,14 @@ export interface BindingFormState {
status: IntegrationConfigStatus; status: IntegrationConfigStatus;
} }
/** 凭据引用表单。 */ /** 凭据引用表单(按凭据类型动态字段;fields 值留空 = 编辑时保持旧值)。 */
export interface CredentialReferenceFormState { export interface CredentialReferenceFormState {
id: number | null; id: number | null;
code: string; code: string;
secret_ref: string; secret_ref: string;
secret_provider: string; secret_provider: string;
credential_type: string; credential_type: string;
fields: Record<string, string>;
status: IntegrationCredentialStatus; status: IntegrationCredentialStatus;
} }
@@ -188,7 +291,7 @@ export function clientInstanceRowToForm(row: IntegrationClientInstanceRow): Clie
}; };
} }
/** 创建空的接口定义表单。 */ /** 创建空的接口定义表单(新建固定落 draft,上线走列表「发布」按钮)。 */
export function createEmptyInterfaceDefinitionForm(): InterfaceDefinitionFormState { export function createEmptyInterfaceDefinitionForm(): InterfaceDefinitionFormState {
return { return {
id: null, id: null,
@@ -203,11 +306,10 @@ export function createEmptyInterfaceDefinitionForm(): InterfaceDefinitionFormSta
response_mapping_json: '', response_mapping_json: '',
output_schema_json: '', output_schema_json: '',
status: 'draft', status: 'draft',
enabled: true,
}; };
} }
/** 列表行回填为接口定义编辑表单。 */ /** 列表行回填为接口定义编辑表单(connector_type/status 仅回显,不随保存提交)。 */
export function interfaceDefinitionRowToForm(row: IntegrationInterfaceDefinitionRow): InterfaceDefinitionFormState { export function interfaceDefinitionRowToForm(row: IntegrationInterfaceDefinitionRow): InterfaceDefinitionFormState {
return { return {
id: row.id, id: row.id,
@@ -222,7 +324,6 @@ export function interfaceDefinitionRowToForm(row: IntegrationInterfaceDefinition
response_mapping_json: toJsonText(row.response_mapping_json), response_mapping_json: toJsonText(row.response_mapping_json),
output_schema_json: toJsonText(row.output_schema_json), output_schema_json: toJsonText(row.output_schema_json),
status: row.status, status: row.status,
enabled: Boolean(row.enabled),
}; };
} }
@@ -232,7 +333,7 @@ export function createEmptyBindingForm(): BindingFormState {
id: null, id: null,
capability: '', capability: '',
context_selector_json: '', context_selector_json: '',
context_source_code: '', param_mapping_json: '',
client_instance_code: '', client_instance_code: '',
interface_definition_code: '', interface_definition_code: '',
mapping_version: 1, mapping_version: 1,
@@ -244,13 +345,13 @@ export function createEmptyBindingForm(): BindingFormState {
}; };
} }
/** 列表行回填为绑定编辑表单。 */ /** 列表行回填为绑定编辑表单(status 仅回显,不随保存提交)。 */
export function bindingRowToForm(row: IntegrationBindingRow): BindingFormState { export function bindingRowToForm(row: IntegrationBindingRow): BindingFormState {
return { return {
id: row.id, id: row.id,
capability: row.capability, capability: row.capability,
context_selector_json: toJsonText(row.context_selector_json), context_selector_json: toJsonText(row.context_selector_json),
context_source_code: row.context_source_code ?? '', param_mapping_json: toJsonText(row.param_mapping_json),
client_instance_code: row.client_instance_code, client_instance_code: row.client_instance_code,
interface_definition_code: row.interface_definition_code, interface_definition_code: row.interface_definition_code,
mapping_version: Number(row.mapping_version || 1), mapping_version: Number(row.mapping_version || 1),
@@ -262,19 +363,20 @@ export function bindingRowToForm(row: IntegrationBindingRow): BindingFormState {
}; };
} }
/** 创建空的凭据引用表单。 */ /** 创建空的凭据引用表单(管理端默认 db 模式 + password 类型:界面维护、加密落库、免重启)。 */
export function createEmptyCredentialReferenceForm(): CredentialReferenceFormState { export function createEmptyCredentialReferenceForm(): CredentialReferenceFormState {
return { return {
id: null, id: null,
code: '', code: '',
secret_ref: '', secret_ref: '',
secret_provider: 'env', secret_provider: 'db',
credential_type: 'password', credential_type: 'password',
fields: {},
status: 'active', status: 'active',
}; };
} }
/** 列表行回填为凭据引用编辑表单。 */ /** 列表行回填为凭据引用编辑表单(密文字段不回填,留空 = 保持旧值)。 */
export function credentialReferenceRowToForm(row: IntegrationCredentialReferenceRow): CredentialReferenceFormState { export function credentialReferenceRowToForm(row: IntegrationCredentialReferenceRow): CredentialReferenceFormState {
return { return {
id: row.id, id: row.id,
@@ -282,6 +384,7 @@ export function credentialReferenceRowToForm(row: IntegrationCredentialReference
secret_ref: row.secret_ref, secret_ref: row.secret_ref,
secret_provider: row.secret_provider, secret_provider: row.secret_provider,
credential_type: row.credential_type, credential_type: row.credential_type,
fields: { ...(row.secret_fields ?? {}) },
status: row.status, status: row.status,
}; };
} }