feat(integration-connector): 新增集成连接器管理后台,支持关键字段拆列配置

This commit is contained in:
hugo committed 2026-09-04 02:16:41 +08:00
1 parent bf30cddc4a
commit 1269e04116
28 files changed
+2909 -155

No files matched your search

+145
View File
@@ -43,6 +43,7 @@ def _serialize_client(client) -> dict:
return {
'id': client.id, 'code': client.code, 'name': client.name,
'connector_type': client.connector_type, 'environment': client.environment,
'endpoint': client.endpoint, 'timeout_seconds': client.timeout_seconds,
'config_json': client.config_json or {}, 'credential_ref_code': client.credential_ref_code,
'enabled': client.enabled,
}
@@ -52,6 +53,7 @@ def _serialize_interface(iface) -> dict:
return {
'id': iface.id, 'code': iface.code, 'name': iface.name,
'client_instance_code': iface.client_instance_code, 'connector_type': iface.connector_type,
'http_method': iface.http_method, 'request_path': iface.request_path,
'request_spec_json': iface.request_spec_json or {}, 'input_schema_json': iface.input_schema_json or {},
'response_mapping_json': iface.response_mapping_json or {}, 'output_schema_json': iface.output_schema_json or {},
'version': iface.version, 'status': iface.status, 'enabled': iface.enabled,
@@ -62,6 +64,7 @@ def _serialize_binding(binding) -> dict:
return {
'id': binding.id, 'capability': binding.capability,
'context_selector_json': binding.context_selector_json or {},
'context_source_code': binding.context_source_code,
'client_instance_code': binding.client_instance_code,
'interface_definition_code': binding.interface_definition_code,
'mapping_version': binding.mapping_version, 'priority': binding.priority,
@@ -146,6 +149,8 @@ def create_client_instance():
client = IntegrationClientInstance(
code=str(body['code']).strip(), name=str(body['name']).strip(),
connector_type=connector_type, environment=str(body.get('environment') or 'prod').strip(),
endpoint=(str(body.get('endpoint') or '').strip() or None),
timeout_seconds=(int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None),
config_json=body.get('config_json') or {},
credential_ref_code=body.get('credential_ref_code'),
enabled=bool(body.get('enabled', True)),
@@ -177,6 +182,39 @@ def delete_client_instance(code):
return ok({'deleted': True})
@integration_connector_bp.route('/client-instances/<code>', methods=['PUT'])
@require_admin
def update_client_instance(code):
"""更新客户端实例(code 不变;可改名称/连接配置/凭据引用/启停)。"""
client = IntegrationClientInstance.query.filter_by(code=code).first()
if client is None:
raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND')
body = request.get_json(silent=True) or {}
connector_type = str(body.get('connector_type') or client.connector_type)
if connector_type not in VALID_CONNECTOR_TYPES:
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
if body.get('name') is not None:
_require(body.get('name'), 'name')
client.name = str(body['name']).strip()
if body.get('connector_type') is not None:
client.connector_type = connector_type
if body.get('environment') is not None:
client.environment = str(body['environment']).strip()
if 'endpoint' in body:
client.endpoint = str(body.get('endpoint') or '').strip() or None
if 'timeout_seconds' in body:
client.timeout_seconds = int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None
if 'config_json' in body:
client.config_json = body.get('config_json') or {}
if 'credential_ref_code' in body:
client.credential_ref_code = body.get('credential_ref_code')
if 'enabled' in body:
client.enabled = bool(body.get('enabled', True))
from app import db
db.session.commit()
return ok(_serialize_client(client))
# ---- 接口定义 ----
@integration_connector_bp.route('/interface-definitions', methods=['GET'])
@@ -202,6 +240,8 @@ def create_interface_definition():
iface = IntegrationInterfaceDefinition(
code=code, name=str(body.get('name') or code).strip(),
client_instance_code=body['client_instance_code'], connector_type=connector_type,
http_method=(str(body.get('http_method') or '').strip().upper() or None),
request_path=(str(body.get('request_path') or '').strip() or None),
request_spec_json=body.get('request_spec_json') or {},
input_schema_json=body.get('input_schema_json') or {},
response_mapping_json=body.get('response_mapping_json') or {},
@@ -215,6 +255,46 @@ def create_interface_definition():
return ok(_serialize_interface(iface), status=201)
@integration_connector_bp.route('/interface-definitions/<code>', methods=['PUT'])
@require_admin
def update_interface_definition(code):
"""更新接口定义(code 不变;可改模板/入参/回传/出参 Schema、状态、启停)。"""
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
if iface is None:
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
body = request.get_json(silent=True) or {}
if body.get('name') is not None:
_require(body.get('name'), 'name')
iface.name = str(body['name']).strip()
if body.get('client_instance_code') is not None:
_require(body.get('client_instance_code'), 'client_instance_code')
iface.client_instance_code = body['client_instance_code']
if body.get('connector_type') is not None:
connector_type = str(body['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:
iface.http_method = str(body.get('http_method') or '').strip().upper() or None
if 'request_path' in body:
iface.request_path = str(body.get('request_path') or '').strip() or None
for json_field in ('request_spec_json', 'input_schema_json', 'response_mapping_json', 'output_schema_json'):
if json_field in body:
setattr(iface, json_field, body.get(json_field) or {})
if body.get('version') is not None:
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
db.session.commit()
return ok(_serialize_interface(iface))
# ---- Binding ----
@integration_connector_bp.route('/bindings', methods=['GET'])
@@ -237,6 +317,7 @@ def create_binding():
binding = IntegrationBinding(
capability=body['capability'],
context_selector_json=body.get('context_selector_json') or {},
context_source_code=(str(body.get('context_source_code') or '').strip() or None),
client_instance_code=body['client_instance_code'],
interface_definition_code=body['interface_definition_code'],
mapping_version=int(body.get('mapping_version') or 1),
@@ -250,6 +331,48 @@ def create_binding():
return ok(_serialize_binding(binding), status=201)
@integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT'])
@require_admin
def update_binding(binding_id):
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间、状态)。"""
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')
body = request.get_json(silent=True) or {}
if body.get('capability') is not None:
_require(body.get('capability'), 'capability')
binding.capability = body['capability']
if 'context_selector_json' in body:
binding.context_selector_json = body.get('context_selector_json') or {}
if 'context_source_code' in body:
binding.context_source_code = str(body.get('context_source_code') or '').strip() or None
if body.get('client_instance_code') is not None:
_require(body.get('client_instance_code'), 'client_instance_code')
binding.client_instance_code = body['client_instance_code']
if body.get('interface_definition_code') is not None:
_require(body.get('interface_definition_code'), 'interface_definition_code')
binding.interface_definition_code = body['interface_definition_code']
if body.get('mapping_version') is not None:
binding.mapping_version = int(body.get('mapping_version') or 1)
if body.get('priority') is not None:
binding.priority = int(body.get('priority') or 0)
if body.get('environment') is not None:
binding.environment = str(body['environment']).strip()
if body.get('effective_from') is not None:
binding.effective_from = body['effective_from'] or None
if body.get('effective_to') is not 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
db.session.commit()
return ok(_serialize_binding(binding))
# ---- 凭据引用 ----
@integration_connector_bp.route('/credential-references', methods=['GET'])
@@ -280,6 +403,28 @@ def create_credential_reference():
return ok(_serialize_credential(cred), status=201)
@integration_connector_bp.route('/credential-references/<code>', methods=['PUT'])
@require_admin
def update_credential_reference(code):
"""更新凭据引用(code 不变;可改 secret_ref/provider/type/status)。只存引用,永不回显明文。"""
cred = IntegrationCredentialReference.query.filter_by(code=code).first()
if cred is None:
raise NotFoundError('credential reference not found', code='INTEGRATION.CREDENTIAL_NOT_FOUND')
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:
cred.secret_provider = str(body['secret_provider']).strip()
if body.get('credential_type') is not None:
cred.credential_type = str(body['credential_type']).strip()
if body.get('status') is not None:
cred.status = str(body['status']).strip()
from app import db
db.session.commit()
return ok(_serialize_credential(cred))
# ---- 连接测试 ----
@integration_connector_bp.route('/client-instances/<code>/test', methods=['POST'])
@@ -84,6 +84,10 @@ class IntegrationClientInstance(Base):
name: Mapped[str] = mapped_column(String(128), nullable=False)
connector_type: Mapped[str] = mapped_column(String(16), nullable=False)
environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod')
# 关键强类型字段独立列(JSON 保留作兜底;兼容层 binding.py 拼回 dict)。
# endpoint = 连接地址:REST 为接口基地址,SOAP 为 WSDL 地址(WSDL 内含服务端点)。
endpoint: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
timeout_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
config_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
credential_ref_code: Mapped[Optional[str]] = mapped_column(
ForeignKey('integration_credential_references.code'), nullable=True,
@@ -119,6 +123,9 @@ class IntegrationInterfaceDefinition(Base):
ForeignKey('integration_client_instances.code'), nullable=False,
)
connector_type: Mapped[str] = mapped_column(String(16), nullable=False)
# 关键强类型字段独立列(JSON 保留作兜底)。
http_method: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
request_path: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
request_spec_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
input_schema_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
response_mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
@@ -153,6 +160,8 @@ class IntegrationBinding(Base):
id: Mapped[int] = mapped_column(primary_key=True)
capability: Mapped[str] = mapped_column(String(128), nullable=False)
context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
# 最常用的 context 匹配键独立列(JSON 保留作兜底)。
context_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
client_instance_code: Mapped[str] = mapped_column(
ForeignKey('integration_client_instances.code'), nullable=False,
)
@@ -89,6 +89,25 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
iface = IntegrationInterfaceDefinition.query.filter_by(code=row.interface_definition_code).first()
if client is None or iface is None:
raise BindingNotFoundError(capability=capability)
# 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费。
# 优先列值,缺失回退 JSON(config_json / request_spec_json / context_selector_json)。
config = dict(client.config_json or {})
if client.endpoint is not None:
config['endpoint'] = client.endpoint
if client.timeout_seconds is not None:
config['timeout_seconds'] = client.timeout_seconds
request_spec = dict(iface.request_spec_json or {})
if iface.http_method is not None:
request_spec['method'] = iface.http_method
if iface.request_path is not None:
request_spec['path'] = iface.request_path
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(
capability=row.capability,
context_selector=selector,
@@ -98,8 +117,8 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
interface_version=iface.version,
mapping_version=row.mapping_version,
credential_ref_code=client.credential_ref_code,
config=client.config_json or {},
request_spec=iface.request_spec_json or {},
config=config,
request_spec=request_spec,
response_mapping=iface.response_mapping_json or {},
output_schema=iface.output_schema_json or {},
)
@@ -19,10 +19,11 @@ class SoapTransport:
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
config = client.get('config_json') or {}
endpoint = str(config.get('endpoint') or '').strip()
wsdl = str(config.get('wsdl') or '').strip()
if not endpoint or not wsdl:
raise TransportNotFrozenError('SOAP contract not frozen (missing endpoint/wsdl)')
# SOAP 只需一个连接地址(WSDL):WSDL 已含服务端点,不需单独的 REST 式 endpoint。
# 该地址存于 config['endpoint'](语义即连接地址);timeout 与 REST 同语义。
wsdl = str(config.get('endpoint') or '').strip()
if not wsdl:
raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)')
# 真实 SOAP 调用(zeep.Client(action=...,构造请求体、解析响应))待 WSDL 冻结后落地。
# 真实 SOAP 调用(zeep.Client(timeout=int(config.get('timeout_seconds') or 60), ...)) 待 WSDL 冻结后落地。
raise NotImplementedError('SOAP implementation pending frozen WSDL')
@@ -0,0 +1,385 @@
"""订单明细身份、项次及 OT 生命周期契约的一次性硬切换。"""
from __future__ import annotations
import copy
from alembic import op
import sqlalchemy as sa
revision = 'iw1a2b3c4d5e'
down_revision = 'if1b2c3d4e5i'
branch_labels = None
depends_on = None
def _i(): return sa.inspect(op.get_bind())
def _tables(): return set(_i().get_table_names())
def _cols(t): return {x['name'] for x in _i().get_columns(t)}
def _drop_uq(t, n):
if n in {x.get('name') for x in _i().get_unique_constraints(t)}: op.drop_constraint(n, t, type_='unique')
def _drop_idx(t, n):
if n in {x.get('name') for x in _i().get_indexes(t)}: op.drop_index(n, table_name=t)
def _drop_column_with_dependencies(t, column):
"""按实际库结构先解除列级外键/索引,再删除已退役的 OT 投影列。"""
if column not in _cols(t):
return
with op.batch_alter_table(t) as b:
for fk in _i().get_foreign_keys(t):
if column in (fk.get('constrained_columns') or []) and fk.get('name'):
b.drop_constraint(fk['name'], type_='foreignkey')
for index in _i().get_indexes(t):
if column in (index.get('column_names') or []) and index.get('name'):
b.drop_index(index['name'])
b.drop_column(column)
def _clean_task_step_payloads():
"""删除 OT JSON 中已迁移的业务事实,仅保留 UI/解析摘要。"""
if 'shipping_order_tasks' not in _tables() or 'step_payload_json' not in _cols('shipping_order_tasks'):
return
table = sa.table('shipping_order_tasks', sa.column('id', sa.Integer()), sa.column('step_payload_json', sa.JSON()))
removed = {
'field_conflicts', 'process_field_gate', 'inventory_rpa_skipped',
'last_inventory_rpa_runtime', 'line_inventory_candidates',
'candidate_inventory_prep', 'line_inventory_resolutions',
'forced_match_source_code', 'current_match_projection',
'resolved_ok_source_codes', 'multi_source_excel_block',
'inventory_source_resolution', 'rpa_inventory_source', 'export_meta',
'invalidated_from_stage', 'last_conflict_resolve_idempotency_key',
'last_notice_edit_idempotency',
}
bind = op.get_bind()
for row in bind.execute(sa.select(table.c.id, table.c.step_payload_json)).all():
payload = row.step_payload_json
if not isinstance(payload, dict):
continue
cleaned = {key: value for key, value in payload.items() if key not in removed}
if cleaned != payload:
bind.execute(table.update().where(table.c.id == row.id).values(step_payload_json=cleaned or None))
_OT_COLUMNS = {
'order_data_version': sa.Column('order_data_version', sa.Integer(), nullable=False, server_default='1'),
'current_order_extraction_id': sa.Column('current_order_extraction_id', sa.Integer(), nullable=True),
'order_snapshot_id': sa.Column('order_snapshot_id', sa.Integer(), nullable=True),
'active_inventory_candidate_set_id': sa.Column('active_inventory_candidate_set_id', sa.Integer(), nullable=True),
'step_payload_json': sa.Column('step_payload_json', sa.JSON(), nullable=True),
'active_process_execution_id': sa.Column('active_process_execution_id', sa.Integer(), nullable=True),
}
_TASK_FKS = {
'shipping_order_snapshots': ('task_id', 'shipping_order_tasks'), 'shipping_order_review_events': ('task_id', 'shipping_order_tasks'),
'shipping_order_review_confirmed_revisions': ('task_id', 'shipping_order_tasks'), 'shipping_order_review_wave_lines': ('task_id', 'shipping_order_tasks'),
'shipping_order_review_wave_idempotency': ('task_id', 'shipping_order_tasks'), 'shipping_order_review_line_decisions': ('task_id', 'shipping_order_tasks'),
'shipping_inventory_candidate_sets': ('task_id', 'shipping_order_tasks'), 'shipping_process_executions': ('task_id', 'shipping_order_tasks'),
'shipping_process_gates': ('task_id', 'shipping_order_tasks'), 'shipping_inventory_preparation_attempts': ('task_id', 'shipping_order_tasks'),
'shipping_notice_reservations': ('task_id', 'shipping_order_tasks'), 'shipping_notice_inventory_verifications': ('task_id', 'shipping_order_tasks'),
'shipping_task_inventory_links': ('task_id', 'shipping_order_tasks'), 'shipping_temporary_inventory_sessions': ('task_id', 'shipping_order_tasks'),
'shipping_task_events': ('task_id', 'shipping_order_tasks'),
'shipping_notice_line_inventory_matches': ('task_id', 'shipping_order_tasks'), 'shipping_task_field_conflicts': ('task_id', 'shipping_order_tasks'),
'shipping_order_extractions': ('task_id', 'shipping_order_tasks'), 'shipping_order_intakes': ('consumed_task_id', 'shipping_order_tasks'),
'shipping_order_candidates': ('consumed_task_id', 'shipping_order_tasks'),
}
def _repoint(t, c, target):
if t not in _tables(): return
fks = [x for x in _i().get_foreign_keys(t) if c in (x.get('constrained_columns') or [])]
with op.batch_alter_table(t) as b:
for fk in fks:
if fk.get('name'): b.drop_constraint(fk['name'], type_='foreignkey')
b.create_foreign_key(f'fk_{t}_{c}_order_task', target, [c], ['id'], ondelete='CASCADE')
def upgrade() -> None:
tables = _tables()
_clean_task_step_payloads()
# Notice 的库存确认人/时间是旧的单头运行投影;正式确认事实由
# PreparationAttempt/SourceAttempt 与 GateAttempt 承载。
if 'shipping_notices' in tables:
for n in (
'inventory_connector_type',
'active_inventory_candidate_set_id',
'active_process_execution_id',
'inventory_snapshot_id',
'inventory_source_confirmed_by',
'inventory_source_confirmed_at',
'inventory_lines_json',
'match_status',
'shortage_json',
'line_results_json',
'inventory_source_code',
'inventory_source_status',
'inventory_source_method',
'inventory_source_config_version',
'inventory_routing_fingerprint',
'inventory_rpa_consumed_run_no',
):
_drop_column_with_dependencies('shipping_notices', n)
if 'shipping_order_tasks' in tables:
existing = _cols('shipping_order_tasks')
with op.batch_alter_table('shipping_order_tasks') as b:
for n, c in _OT_COLUMNS.items():
if n not in existing: b.add_column(c)
for n in (
'inventory_source_code', 'inventory_connector_type', 'inventory_source_status',
'inventory_source_method', 'inventory_source_config_version',
'inventory_routing_fingerprint', 'inventory_snapshot_id',
):
if n in existing: b.drop_column(n)
for n in (
'customer_id', 'customer_resolution_status', 'customer_resolution_method',
'customer_identity_fingerprint', 'customer_confirmed_by', 'customer_confirmed_at',
'pending_human_reason',
):
_drop_column_with_dependencies('shipping_order_tasks', n)
# 已部署环境可能在本迁移到达 head 后仍残留历史 OT 投影列(例如旧分支
# 曾先执行过迁移、再补充模型字段)。这里再次按实际 schema 幂等清理,
# 确保“模型无字段、数据库也无字段”最终一致,而不依赖迁移执行时序。
for n in (
'customer_name_snapshot', 'customer_short_code_snapshot',
'destination_code', 'destination_city', 'destination_country', 'warehouse_hint',
'inventory_source_code', 'inventory_connector_type', 'inventory_source_status',
'inventory_source_method', 'inventory_source_config_version',
'inventory_routing_fingerprint', 'inventory_snapshot_id',
'inventory_lines_json', 'match_status', 'shortage_json', 'line_results_json',
):
_drop_column_with_dependencies('shipping_order_tasks', n)
cols = _cols('shipping_order_tasks')
if 'shipping_notice_id' in cols:
fks = [x for x in _i().get_foreign_keys('shipping_order_tasks') if 'shipping_notice_id' in (x.get('constrained_columns') or [])]
with op.batch_alter_table('shipping_order_tasks') as b:
for fk in fks:
if fk.get('name'): b.drop_constraint(fk['name'], type_='foreignkey')
b.drop_column('shipping_notice_id')
# 订单/通知项次及身份硬切换(旧身份数据不回填)。
if 'shipping_order_lines' in tables:
c = _cols('shipping_order_lines')
with op.batch_alter_table('shipping_order_lines') as b:
if 'line_key' in c: b.drop_column('line_key')
if 'draft_line_id' not in c: b.add_column(sa.Column('draft_line_id', sa.String(128), nullable=True))
if 'line_no' not in c: b.add_column(sa.Column('line_no', sa.Integer(), nullable=True))
op.execute(sa.text('''WITH n AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY extraction_id ORDER BY position,id) x FROM shipping_order_lines) UPDATE shipping_order_lines l SET line_no=n.x FROM n WHERE l.id=n.id'''))
with op.batch_alter_table('shipping_order_lines') as b:
b.alter_column('line_no', nullable=False, existing_type=sa.Integer())
if 'uq_shipping_order_lines_line_no' not in {x.get('name') for x in _i().get_unique_constraints('shipping_order_lines')}: b.create_unique_constraint('uq_shipping_order_lines_line_no', ['extraction_id','line_no'])
for t in ('shipping_order_review_suggestions','shipping_order_review_line_decisions'):
if t in tables:
c=_cols(t)
with op.batch_alter_table(t) as b:
if 'line_key' in c and 'draft_line_id' not in c: b.alter_column('line_key', new_column_name='draft_line_id')
elif 'line_key' in c: b.drop_column('line_key')
if 'shipping_order_snapshot_lines' in tables:
with op.batch_alter_table('shipping_order_snapshot_lines') as b:
if 'line_no' in _cols('shipping_order_snapshot_lines'): b.alter_column('line_no', existing_type=sa.String(64), type_=sa.Integer(), postgresql_using='line_no::integer')
op.execute(sa.text('''WITH n AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY snapshot_id ORDER BY position,id) x FROM shipping_order_snapshot_lines) UPDATE shipping_order_snapshot_lines l SET line_no=n.x FROM n WHERE l.id=n.id'''))
if 'shipping_notice_lines' in tables:
c=_cols('shipping_notice_lines')
with op.batch_alter_table('shipping_notice_lines') as b:
if 'line_key' in c: b.drop_column('line_key')
if 'line_no' not in c: b.add_column(sa.Column('line_no', sa.Integer(), nullable=True))
if 'inventory_source_code' not in c: b.add_column(sa.Column('inventory_source_code', sa.String(64), nullable=True))
if 'inventory_file_id' not in c: b.add_column(sa.Column('inventory_file_id', sa.Integer(), nullable=True))
if 'inventory_warehouse_id' not in c: b.add_column(sa.Column('inventory_warehouse_id', sa.String(64), nullable=True))
op.execute(sa.text('''WITH n AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY notice_id ORDER BY position,id) x FROM shipping_notice_lines) UPDATE shipping_notice_lines l SET line_no=n.x FROM n WHERE l.id=n.id'''))
with op.batch_alter_table('shipping_notice_lines') as b:
b.alter_column('line_no', nullable=False, existing_type=sa.Integer())
if 'uq_shipping_notice_lines_line_no' not in {x.get('name') for x in _i().get_unique_constraints('shipping_notice_lines')}: b.create_unique_constraint('uq_shipping_notice_lines_line_no', ['notice_id','line_no'])
if 'fk_shipping_notice_lines_inventory_file' not in {x.get('name') for x in _i().get_foreign_keys('shipping_notice_lines')}:
b.create_foreign_key('fk_shipping_notice_lines_inventory_file', 'shipping_inventory_files', ['inventory_file_id'], ['id'], ondelete='SET NULL')
existing_indexes = {x.get('name') for x in _i().get_indexes('shipping_notice_lines')}
if 'ix_shipping_notice_lines_inventory_source_code' not in existing_indexes:
b.create_index('ix_shipping_notice_lines_inventory_source_code', ['inventory_source_code'])
if 'ix_shipping_notice_lines_inventory_file_id' not in existing_indexes:
b.create_index('ix_shipping_notice_lines_inventory_file_id', ['inventory_file_id'])
if 'ix_shipping_notice_lines_inventory_warehouse_id' not in existing_indexes:
b.create_index('ix_shipping_notice_lines_inventory_warehouse_id', ['inventory_warehouse_id'])
if 'shipping_notices' in tables and 'inventory_warehouse_id' in _cols('shipping_notices'):
with op.batch_alter_table('shipping_notices') as b:
b.drop_column('inventory_warehouse_id')
if 'shipping_order_review_wave_lines' in tables:
c=_cols('shipping_order_review_wave_lines'); _drop_uq('shipping_order_review_wave_lines','uq_shipping_review_wave_lines_case_line'); op.execute(sa.text('DELETE FROM shipping_order_review_wave_lines'))
existing_fks = {x.get('name') for x in _i().get_foreign_keys('shipping_order_review_wave_lines')}
has_snapshot_line_fk = any('snapshot_line_id' in (x.get('constrained_columns') or []) for x in _i().get_foreign_keys('shipping_order_review_wave_lines'))
existing_uqs = {x.get('name') for x in _i().get_unique_constraints('shipping_order_review_wave_lines')}
with op.batch_alter_table('shipping_order_review_wave_lines') as b:
if 'line_key' in c: b.drop_column('line_key')
if 'snapshot_line_id' not in c: b.add_column(sa.Column('snapshot_line_id', sa.Integer(), nullable=False))
if not has_snapshot_line_fk and 'fk_shipping_review_wave_lines_snapshot_line' not in existing_fks:
b.create_foreign_key('fk_shipping_review_wave_lines_snapshot_line','shipping_order_snapshot_lines',['snapshot_line_id'],['id'],ondelete='CASCADE')
if 'uq_shipping_review_wave_lines_case_snapshot_line' not in existing_uqs:
b.create_unique_constraint('uq_shipping_review_wave_lines_case_snapshot_line',['review_case_id','snapshot_line_id'])
if 'shipping_order_review_wave_idempotency' in tables:
c=_cols('shipping_order_review_wave_idempotency')
with op.batch_alter_table('shipping_order_review_wave_idempotency') as b:
if 'line_keys_json' in c and 'snapshot_line_ids_json' not in c: b.alter_column('line_keys_json',new_column_name='snapshot_line_ids_json')
if 'line_keys_hash' in c and 'snapshot_line_ids_hash' not in c: b.alter_column('line_keys_hash',new_column_name='snapshot_line_ids_hash')
if 'shipping_notice_line_inventory_matches' in tables:
c=_cols('shipping_notice_line_inventory_matches'); op.execute(sa.text('DELETE FROM shipping_notice_line_inventory_matches')); _drop_idx('shipping_notice_line_inventory_matches','uq_shipping_notice_line_inv_match_current'); _drop_uq('shipping_notice_line_inventory_matches','uq_shipping_notice_line_inv_match_task_line_snap')
existing_fks = {x.get('name') for x in _i().get_foreign_keys('shipping_notice_line_inventory_matches')}
has_snapshot_line_fk = any('snapshot_line_id' in (x.get('constrained_columns') or []) for x in _i().get_foreign_keys('shipping_notice_line_inventory_matches'))
existing_uqs = {x.get('name') for x in _i().get_unique_constraints('shipping_notice_line_inventory_matches')}
with op.batch_alter_table('shipping_notice_line_inventory_matches') as b:
if 'line_key' in c: b.drop_column('line_key')
if 'line_no' not in c: b.add_column(sa.Column('line_no', sa.Integer(), nullable=True))
if 'snapshot_line_id' not in c: b.add_column(sa.Column('snapshot_line_id',sa.Integer(),nullable=False))
else: b.alter_column('snapshot_line_id',nullable=False,existing_type=sa.Integer())
if not has_snapshot_line_fk and 'fk_shipping_notice_line_inventory_matches_snapshot_line' not in existing_fks:
b.create_foreign_key('fk_shipping_notice_line_inventory_matches_snapshot_line','shipping_order_snapshot_lines',['snapshot_line_id'],['id'],ondelete='CASCADE')
if 'uq_shipping_notice_line_inv_match_task_snapshot_line_snap' not in existing_uqs:
b.create_unique_constraint('uq_shipping_notice_line_inv_match_task_snapshot_line_snap',['task_id','snapshot_line_id','inventory_snapshot_id'])
if 'uq_shipping_notice_line_inv_match_current' not in {x.get('name') for x in _i().get_indexes('shipping_notice_line_inventory_matches')}:
b.create_index('uq_shipping_notice_line_inv_match_current',['task_id','snapshot_line_id'],unique=True,postgresql_where=sa.text('is_current IS TRUE'))
op.execute(sa.text("""
UPDATE shipping_notice_line_inventory_matches m
SET line_no = COALESCE(sl.line_no, m.line_index + 1, 1)
FROM shipping_order_snapshot_lines sl
WHERE m.snapshot_line_id = sl.id
AND m.line_no IS NULL
"""))
with op.batch_alter_table('shipping_notice_line_inventory_matches') as b:
b.alter_column('line_no', nullable=False, existing_type=sa.Integer(), server_default='1')
# shipping_task_events.task_id 记录正式 ShippingOrderTask.id;部分旧环境
# 的外键错误指向 shipping_notices,导致确认建单写审计事件时触发 FK 违反。
if 'shipping_task_events' in tables and 'shipping_order_tasks' in tables:
event_fk = next(
(
fk for fk in _i().get_foreign_keys('shipping_task_events')
if tuple(fk.get('constrained_columns') or []) == ('task_id',)
),
None,
)
if not event_fk or event_fk.get('referred_table') != 'shipping_order_tasks':
old_fk_name = str(event_fk.get('name') or 'shipping_task_events_task_id_fkey') if event_fk else None
if old_fk_name:
with op.batch_alter_table('shipping_task_events') as b:
b.drop_constraint(old_fk_name, type_='foreignkey')
invalid_count = op.get_bind().execute(sa.text(
"""
SELECT COUNT(*)
FROM shipping_task_events e
WHERE NOT EXISTS (
SELECT 1 FROM shipping_order_tasks t WHERE t.id = e.task_id
)
"""
)).scalar_one()
if int(invalid_count or 0):
raise RuntimeError(
'shipping_task_events contains rows whose task_id is not a '
'shipping_order_tasks.id; repair those audit rows before migration'
)
with op.batch_alter_table('shipping_task_events') as b:
b.create_foreign_key(
'fk_shipping_task_events_task_id_order_task',
'shipping_order_tasks', ['task_id'], ['id'], ondelete='CASCADE',
)
bind=op.get_bind()
if 'shipping_excel_templates' in tables:
t=sa.table('shipping_excel_templates',sa.column('id',sa.Integer()),sa.column('definition_json',sa.JSON()))
def rw(v):
if isinstance(v,dict):
r={k:rw(x) for k,x in v.items()}
if r.get('source_kind') == 'system_fact' and r.get('source_key') == 'export_sequence':
r['source_key'] = 'notice_line_no'
return r
return [rw(x) for x in v] if isinstance(v,list) else v
for row in bind.execute(sa.select(t.c.id,t.c.definition_json)).all():
v=rw(row.definition_json)
if v!=row.definition_json: bind.execute(t.update().where(t.c.id==row.id).values(definition_json=v))
if 'shipping_order_schema_versions' in tables:
t=sa.table('shipping_order_schema_versions',sa.column('id',sa.Integer()),sa.column('definition_json',sa.JSON()))
for row in bind.execute(sa.select(t.c.id,t.c.definition_json)).all():
v=copy.deepcopy(row.definition_json)
if isinstance(v,dict):
# line_no 是系统项次标准字段,必须保留;这里只移除已废弃的派生规则配置。
v.pop('derivation_rules',None); v.pop('derivation_rules_checksum',None)
if v!=row.definition_json: bind.execute(t.update().where(t.c.id==row.id).values(definition_json=v))
if 'shipping_order_fields' in tables:
# line_no 已硬切换为系统生成整数项次;纠偏旧资产种子遗留的 string 类型。
op.execute(sa.text("""
UPDATE shipping_order_fields
SET value_type = 'integer', updated_at = CURRENT_TIMESTAMP
WHERE field_code = 'line_no'
AND scope = 'line'
AND asset_kind = 'system_standard'
"""))
if 'shipping_order_tasks' in tables:
with op.batch_alter_table('shipping_order_tasks') as b:
for n,c in _OT_COLUMNS.items():
pass
if 'lifecycle_status' not in _cols('shipping_order_tasks'): b.add_column(sa.Column('lifecycle_status',sa.String(16),nullable=False,server_default='active'))
for n, typ in (('current_step', sa.String(64)), ('review_status', sa.String(32)), ('pending_human_reason', sa.String(64))):
if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n, typ, nullable=True))
for n in ('deleted_at','voided_at','archived_at'):
if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n,sa.DateTime(),nullable=True))
for n in ('deletion_reason','void_reason'):
if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n,sa.Text(),nullable=True))
for n in ('deleted_by_id','voided_by_id','archived_by_id'):
if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n,sa.Integer(),nullable=True))
if 'lifecycle_status' not in _cols('shipping_order_tasks'):
b.create_check_constraint('ck_shipping_order_tasks_lifecycle_status', "lifecycle_status IN ('active', 'voided', 'archived')")
existing_fks = {x.get('name') for x in _i().get_foreign_keys('shipping_order_tasks')}
for name, column in (
('fk_shipping_order_tasks_deleted_by', 'deleted_by_id'),
('fk_shipping_order_tasks_voided_by', 'voided_by_id'),
('fk_shipping_order_tasks_archived_by', 'archived_by_id'),
):
if name not in existing_fks:
b.create_foreign_key(name, 'users', [column], ['id'])
obsolete_cols = {
'customer_name_snapshot', 'customer_short_code_snapshot',
'destination_code', 'destination_city', 'destination_country', 'warehouse_hint',
'inventory_lines_json', 'match_status', 'shortage_json', 'line_results_json',
} & _cols('shipping_order_tasks')
if obsolete_cols:
with op.batch_alter_table('shipping_order_tasks') as b:
for column in sorted(obsolete_cols):
b.drop_column(column)
if 'shipping_notices' in tables:
_drop_idx('shipping_notices', 'ix_shipping_notices_current_step')
_drop_idx('shipping_notices', 'ix_shipping_notices_upload_status')
_drop_idx('shipping_notices', 'ix_shipping_notices_order_snapshot_id')
_drop_idx('shipping_notices', 'ix_shipping_tasks_order_snapshot_id')
obsolete_notice_cols = {
'export_file_path', 'export_file_name', 'export_version', 'freight_ref_no',
'upload_status', 'upload_mode', 'upload_attempt', 'idempotency_key',
'upload_started_at', 'upload_finished_at', 'upload_error_code',
'upload_error_message', 'upload_receipt_json',
'current_step', 'review_status', 'step_payload_json', 'pending_human_reason', 'error_message',
'customer_id', 'customer_name_snapshot', 'customer_short_code_snapshot',
'customer_resolution_status', 'customer_resolution_method', 'customer_identity_fingerprint',
'customer_confirmed_by', 'customer_confirmed_at',
'destination_code', 'destination_city', 'destination_country', 'warehouse_hint',
'parse_confidence', 'order_data_version', 'current_order_extraction_id',
'order_snapshot_id', 'raw_content', 'source_file_name', 'source_file_type', 'source_content_hash',
'business_fingerprint', 'fingerprint_version', 'content_fingerprint', 'content_fingerprint_version',
'batch_index', 'batch_total',
} & _cols('shipping_notices')
for column in sorted(obsolete_notice_cols):
_drop_column_with_dependencies('shipping_notices', column)
if 'shipping_order_tasks' in tables:
_drop_idx('shipping_order_tasks', 'ix_shipping_tasks_order_snapshot_id')
_drop_idx('shipping_order_tasks', 'ix_shipping_order_tasks_order_snapshot_id')
_drop_uq('shipping_order_tasks', 'uq_shipping_order_tasks_order_snapshot_id')
# 统一所有履约事实的 task_id 外键目标;旧通知表中的孤儿数据不做猜测回填。
for table, (column, target) in _TASK_FKS.items():
if table not in _tables():
continue
# 不同历史表的任务关联列名并不统一;列不存在时跳过该映射,避免生成无效 SQL。
if column not in _cols(table):
continue
# 已被发货通知引用的快照不能作为孤儿删除,否则会触发外键冲突。
keep_referenced = (
" AND NOT EXISTS (SELECT 1 FROM shipping_notices sn WHERE sn.order_task_id = t.task_id)"
if table == 'shipping_order_snapshots' and 'shipping_notices' in _tables()
else ''
)
op.execute(sa.text(
f'DELETE FROM {table} t WHERE t.{column} IS NOT NULL AND NOT EXISTS '
f'(SELECT 1 FROM shipping_order_tasks ot WHERE ot.id = t.{column})'
f'{keep_referenced}'
))
_repoint(table, column, target)
if 'shipping_order_review_cases' in _tables():
_repoint('shipping_order_review_cases', 'confirmed_task_id', 'shipping_order_tasks')
def downgrade() -> None:
raise RuntimeError('order line identity contract is intentionally irreversible')
@@ -0,0 +1,43 @@
"""split integration connector columns
Revision ID: ix1a2b3c4d5e
Revises: iy1a2b3c4d5e
Create Date: 2026-09-01 09:00:00.000000
用途:把集成连接器"真正强类型的关键字段"从 JSON 拆成独立列,JSON 保留作兜底。
ClientInstance:endpoint(连接地址:REST=接口地址,SOAP=WSDL 地址)/ timeout_seconds;
InterfaceDefinition:http_method / request_path;
Binding:context_source_code。
依赖:ic1a2b3c4d5f 建表;不新建表,仅加列。
逻辑:SOAP 只需 WSDL(其内已含服务端点),故合一为 endpoint 字段;列可为空(存量数据
回填后由应用层拼回 JSON);不删 JSON,保证兼容层运行时零改动。
"""
from alembic import op
import sqlalchemy as sa
revision = 'ix1a2b3c4d5e'
down_revision = 'iy1a2b3c4d5e'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""在三张连接器表上新增关键字段列(nullable:存量数据回填后走兼容层)。"""
op.add_column('integration_client_instances', sa.Column('endpoint', sa.String(length=512), nullable=True))
op.add_column('integration_client_instances', sa.Column('timeout_seconds', sa.Integer(), nullable=True))
op.add_column('integration_interface_definitions', sa.Column('http_method', sa.String(length=16), nullable=True))
op.add_column('integration_interface_definitions', sa.Column('request_path', sa.String(length=512), nullable=True))
op.add_column('integration_bindings', sa.Column('context_source_code', sa.String(length=64), nullable=True))
def downgrade() -> None:
"""回滚:删除新增列(JSON 兜底仍在,数据不丢)。"""
op.drop_column('integration_bindings', 'context_source_code')
op.drop_column('integration_interface_definitions', 'request_path')
op.drop_column('integration_interface_definitions', 'http_method')
op.drop_column('integration_client_instances', 'timeout_seconds')
op.drop_column('integration_client_instances', 'endpoint')
@@ -0,0 +1,125 @@
"""收敛客户确认主链并删除已退役的订单角色匹配表。"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = 'iy1a2b3c4d5e'
down_revision = 'iw1a2b3c4d5e'
branch_labels = None
depends_on = None
def _columns(table_name: str) -> set[str]:
"""返回表当前列名,支持工作区迁移的幂等升级。"""
return {item['name'] for item in sa.inspect(op.get_bind()).get_columns(table_name)}
def upgrade() -> None:
"""补齐当前主链字段后删除已无生产读写方的旧角色匹配表。"""
# [STEP 1] 合并原 35d4 任务进度补列。
with op.batch_alter_table('shipping_order_tasks') as batch:
columns = _columns('shipping_order_tasks')
if 'current_step' not in columns:
batch.add_column(sa.Column('current_step', sa.String(length=64), nullable=True))
if 'review_status' not in columns:
batch.add_column(sa.Column('review_status', sa.String(length=32), nullable=True))
# [STEP 2] 合并原 ix1 客户 Resolution 确认字段升级。
if 'shipping_customer_shadow_resolutions' in set(sa.inspect(op.get_bind()).get_table_names()):
columns = _columns('shipping_customer_shadow_resolutions')
with op.batch_alter_table('shipping_customer_shadow_resolutions') as batch:
constraints = {
item.get('name')
for item in sa.inspect(op.get_bind()).get_check_constraints('shipping_customer_shadow_resolutions')
}
if 'ck_shipping_customer_shadow_status' in constraints:
batch.drop_constraint('ck_shipping_customer_shadow_status', type_='check')
batch.create_check_constraint(
'ck_shipping_customer_shadow_status',
"status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed', 'confirmed')",
)
if 'confirmed_customer_id' not in columns:
batch.add_column(sa.Column('confirmed_customer_id', sa.Integer(), nullable=True))
batch.create_foreign_key(
'fk_shipping_customer_resolution_confirmed_customer',
'shipping_customers', ['confirmed_customer_id'], ['id'],
)
if 'confirmation_method' not in columns:
batch.add_column(sa.Column('confirmation_method', sa.String(length=32), nullable=True))
if 'confirmation_reason' not in columns:
batch.add_column(sa.Column('confirmation_reason', sa.String(length=500), nullable=True))
if 'confirmed_by_id' not in columns:
batch.add_column(sa.Column('confirmed_by_id', sa.Integer(), nullable=True))
batch.create_foreign_key('fk_shipping_customer_resolution_confirmed_by', 'users', ['confirmed_by_id'], ['id'])
if 'confirmed_at' not in columns:
batch.add_column(sa.Column('confirmed_at', sa.DateTime(), nullable=True))
# [STEP 3] 旧表物理删除。
bind = op.get_bind()
if 'shipping_order_customer_matches' in set(sa.inspect(bind).get_table_names()):
op.drop_table('shipping_order_customer_matches')
def downgrade() -> None:
"""恢复旧表空结构并回退本迁移合并的新增字段;不恢复已删除数据。"""
op.create_table(
'shipping_order_customer_matches',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('extraction_id', sa.Integer(), nullable=False),
sa.Column('role', sa.String(length=16), nullable=False),
sa.Column('raw_name', sa.Text(), nullable=True),
sa.Column('normalized_name', sa.String(length=500), nullable=True),
sa.Column('source_system', sa.String(length=64), nullable=True),
sa.Column('external_code', sa.String(length=128), nullable=True),
sa.Column('identity_fingerprint', sa.String(length=64), nullable=True),
sa.Column('identity_rule_version', sa.String(length=32), nullable=True),
sa.Column('identity_components_json', sa.JSON(), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False),
sa.Column('customer_id', sa.Integer(), nullable=True),
sa.Column('site_id', sa.Integer(), nullable=True),
sa.Column('customer_name_snapshot', sa.String(length=200), nullable=True),
sa.Column('customer_short_code_snapshot', sa.String(length=6), nullable=True),
sa.Column('candidates_json', sa.JSON(), nullable=False),
sa.Column('resolution_method', sa.String(length=32), nullable=True),
sa.Column('confirmation_reason', sa.Text(), nullable=True),
sa.Column('confirmed_by_id', sa.Integer(), nullable=True),
sa.Column('confirmed_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.CheckConstraint("role IN ('bill_to', 'ship_to')", name='ck_shipping_order_customer_matches_role'),
sa.CheckConstraint(
"status IN ('unmatched', 'unique_candidate', 'ambiguous', 'confirmed')",
name='ck_shipping_order_customer_matches_status',
),
sa.ForeignKeyConstraint(['customer_id'], ['shipping_customers.id']),
sa.ForeignKeyConstraint(['confirmed_by_id'], ['users.id']),
sa.ForeignKeyConstraint(['extraction_id'], ['shipping_order_extractions.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['site_id'], ['shipping_customer_sites.id']),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('extraction_id', 'role', name='uq_shipping_order_customer_matches_extraction_role'),
)
op.create_index('ix_shipping_order_customer_matches_extraction_id', 'shipping_order_customer_matches', ['extraction_id'])
op.create_index('ix_shipping_order_customer_matches_customer_role', 'shipping_order_customer_matches', ['customer_id', 'role'])
op.create_index('ix_shipping_order_customer_matches_identity_fingerprint', 'shipping_order_customer_matches', ['identity_fingerprint'])
if 'shipping_customer_shadow_resolutions' in set(sa.inspect(op.get_bind()).get_table_names()):
with op.batch_alter_table('shipping_customer_shadow_resolutions') as batch:
for name in (
'fk_shipping_customer_resolution_confirmed_by',
'fk_shipping_customer_resolution_confirmed_customer',
):
try:
batch.drop_constraint(name, type_='foreignkey')
except Exception:
pass
columns = _columns('shipping_customer_shadow_resolutions')
for name in ('confirmed_at', 'confirmed_by_id', 'confirmation_reason', 'confirmation_method', 'confirmed_customer_id'):
if name in columns:
batch.drop_column(name)
with op.batch_alter_table('shipping_order_tasks') as batch:
columns = _columns('shipping_order_tasks')
for name in ('review_status', 'current_step'):
if name in columns:
batch.drop_column(name)
@@ -144,3 +144,147 @@ def test_client_instance_test_connection(app, client, admin_headers, fake_gatewa
response = client.post(f"{API_PREFIX}/client-instances/CLI-A/test", headers=admin_headers)
assert response.status_code == 200
assert response.get_json()["data"]["ok"] is True
def test_update_client_instance(app, client, admin_headers):
"""PUT /client-instances/<code> → 200,更新 name/config/enabled。"""
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-U", "name": "old", "connector_type": "rest", "environment": "prod",
"config_json": {"endpoint": "https://old.invalid"},
})
response = client.put(f"{API_PREFIX}/client-instances/CLI-U", headers=admin_headers, json={
"name": "new", "config_json": {"endpoint": "https://new.invalid"}, "enabled": False,
})
assert response.status_code == 200
assert response.get_json()["data"]["name"] == "new"
assert response.get_json()["data"]["enabled"] is False
assert response.get_json()["data"]["config_json"] == {"endpoint": "https://new.invalid"}
def test_update_interface_definition(app, client, admin_headers):
"""PUT /interface-definitions/<code> → 200,更新模板/回传映射/状态。"""
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-I", "name": "cli", "connector_type": "rest", "environment": "prod",
"config_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",
"request_spec_json": {"path": "/v1/old"}, "status": "draft",
})
response = client.put(f"{API_PREFIX}/interface-definitions/IF-U", headers=admin_headers, json={
"request_spec_json": {"path": "/v1/new"}, "response_mapping_json": {"qty": "data.quantity"},
"status": "published",
})
assert response.status_code == 200
data = response.get_json()["data"]
assert data["status"] == "published"
assert data["request_spec_json"] == {"path": "/v1/new"}
def test_update_binding(app, client, admin_headers):
"""PUT /bindings/<id> → 200,更新映射版本/优先级/状态。"""
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-B", "name": "cli", "connector_type": "rest", "environment": "prod",
"config_json": {},
})
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
"code": "IF-B", "name": "iface", "client_instance_code": "CLI-B", "connector_type": "rest",
})
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
"capability": "in_transit_transfer.query_inventory", "client_instance_code": "CLI-B",
"interface_definition_code": "IF-B", "status": "draft",
})
binding_id = created.get_json()["data"]["id"]
response = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={
"priority": 5, "mapping_version": 2, "status": "published",
})
assert response.status_code == 200
data = response.get_json()["data"]
assert data["priority"] == 5
assert data["mapping_version"] == 2
assert data["status"] == "published"
def test_update_credential_reference(app, client, admin_headers):
"""PUT /credential-references/<code> → 200,更新 secret_ref/status,且不回显明文。"""
client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
"code": "CRED-U", "secret_ref": "IN_TRANSIT_ERP_PASSWORD",
})
response = client.put(f"{API_PREFIX}/credential-references/CRED-U", headers=admin_headers, json={
"secret_ref": "IN_TRANSIT_ERP_PASSWORD_ROTATED", "status": "rotating",
})
assert response.status_code == 200
data = response.get_json()["data"]
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
def test_client_instance_split_columns(app, client, admin_headers):
"""POST /client-instances 写 endpoint/timeout_seconds 独立列,config_json 仅存扩展。"""
created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-COL", "name": "col client", "connector_type": "soap", "environment": "prod",
"endpoint": "https://erp.invalid/wsdl", "timeout_seconds": 90,
"config_json": {"headers": {"X-Tenant": "A"}},
})
assert created.status_code == 201
data = created.get_json()["data"]
assert data["endpoint"] == "https://erp.invalid/wsdl"
assert data["timeout_seconds"] == 90
assert data["config_json"] == {"headers": {"X-Tenant": "A"}}
updated = client.put(f"{API_PREFIX}/client-instances/CLI-COL", headers=admin_headers, json={
"endpoint": "https://erp2.invalid/wsdl", "timeout_seconds": 120,
})
assert updated.status_code == 200
assert updated.get_json()["data"]["endpoint"] == "https://erp2.invalid/wsdl"
assert updated.get_json()["data"]["timeout_seconds"] == 120
def test_interface_definition_split_columns(app, client, admin_headers):
"""POST/PUT /interface-definitions 写 http_method/request_path 独立列。"""
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
"code": "CLI-IF", "name": "cli", "connector_type": "rest", "environment": "prod",
"endpoint": "https://erp.invalid",
})
created = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
"code": "IF-COL", "name": "iface", "client_instance_code": "CLI-IF", "connector_type": "rest",
"http_method": "post", "request_path": "/transfer/{invoice_no}",
"request_spec_json": {"template": {"qty": "{quantity}"}},
})
assert created.status_code == 201
data = created.get_json()["data"]
assert data["http_method"] == "POST"
assert data["request_path"] == "/transfer/{invoice_no}"
updated = client.put(f"{API_PREFIX}/interface-definitions/IF-COL", headers=admin_headers, json={
"http_method": "get", "request_path": "/inventory/{invoice_no}",
})
assert updated.status_code == 200
assert updated.get_json()["data"]["http_method"] == "GET"
assert updated.get_json()["data"]["request_path"] == "/inventory/{invoice_no}"
def test_binding_split_columns(app, client, admin_headers):
"""POST/PUT /bindings 写 context_source_code 独立列并回显。"""
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}/interface-definitions", headers=admin_headers, json={
"code": "IF-BC", "name": "iface", "client_instance_code": "CLI-BC", "connector_type": "rest",
})
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",
"context_source_code": "DBS-AWSBI", "status": "published",
})
assert created.status_code == 201
data = created.get_json()["data"]
assert data["context_source_code"] == "DBS-AWSBI"
updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers, json={
"context_source_code": "CRANE-SZ",
})
assert updated.status_code == 200
assert updated.get_json()["data"]["context_source_code"] == "CRANE-SZ"
@@ -1,7 +1,7 @@
"""tests/services/integration_connector/test_migration.py
用途:验证 Integration Connector 迁移可独立升级与回滚,且正确链在当前 head 之后。
依赖:Alembic Operations、SQLAlchemy SQLite、ic1a2b3c4d5f 迁移。
依赖:Alembic Operations、SQLAlchemy SQLite、ic1a2b3c4d5f / ix1a2b3c4d5e 迁移。
逻辑:空库升级后 5 张表(含索引/约束)存在;回滚后全部删除;down_revision 指向既有 head。
"""
@@ -14,6 +14,8 @@ import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
import pytest
EXPECTED_TABLES = {
'integration_credential_references',
@@ -23,11 +25,13 @@ EXPECTED_TABLES = {
'integration_calls',
}
VERSIONS_DIR = Path(__file__).parents[3] / 'migrations' / 'versions'
def _load_migration():
"""加载连接器框架建表迁移。"""
path = Path(__file__).parents[3] / 'migrations' / 'versions' / 'ic1a2b3c4d5f_add_integration_connector.py'
spec = importlib.util.spec_from_file_location('integration_connector_migration', path)
def _load_migration(name: str, filename: str):
"""加载指定迁移模块。"""
path = VERSIONS_DIR / filename
spec = importlib.util.spec_from_file_location(name, path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
@@ -35,8 +39,8 @@ def _load_migration():
def test_migration_chains_after_head():
"""新迁移必须挂接在既有链 head it1a2b3c4d5e 之后。"""
migration = _load_migration()
"""建表迁移必须挂接在既有链 head it1a2b3c4d5e 之后。"""
migration = _load_migration('integration_connector_migration', 'ic1a2b3c4d5f_add_integration_connector.py')
assert migration.revision == 'ic1a2b3c4d5f'
assert migration.down_revision == 'it1a2b3c4d5e'
@@ -44,21 +48,39 @@ def test_migration_chains_after_head():
def test_integration_connector_migration_round_trip():
"""空库升级后 5 表存在;回滚后全部删除。"""
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')
with engine.begin() as connection:
context = MigrationContext.configure(connection)
operations = Operations(context)
migration = _load_migration()
migration.op = operations
base.op = operations
split.op = operations
migration.upgrade()
base.upgrade()
split.upgrade()
tables = set(sa.inspect(connection).get_table_names())
assert EXPECTED_TABLES.issubset(tables)
inspector = sa.inspect(connection)
client_cols = {item['name'] for item in inspector.get_columns('integration_client_instances')}
assert 'credential_ref_code' in client_cols
assert 'endpoint' in client_cols
assert 'timeout_seconds' in client_cols
iface_cols = {item['name'] for item in inspector.get_columns('integration_interface_definitions')}
assert 'http_method' in iface_cols
assert 'request_path' in iface_cols
binding_cols = {item['name'] for item in inspector.get_columns('integration_bindings')}
assert 'context_source_code' in binding_cols
binding_indexes = {item['name'] for item in inspector.get_indexes('integration_bindings')}
assert 'ix_integration_bindings_cap_env_status' in binding_indexes
migration.downgrade()
split.downgrade()
base.downgrade()
assert EXPECTED_TABLES.isdisjoint(set(sa.inspect(connection).get_table_names()))
def test_split_migration_chains_after_create():
"""拆列迁移必须挂接在 ic1a2b3c4d5e 之后(down_revision=iy1a2b3c4d5e)。"""
split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py')
assert split.revision == 'ix1a2b3c4d5e'
assert split.down_revision == 'iy1a2b3c4d5e'
@@ -84,7 +84,7 @@ def test_rest_fail_closed_without_endpoint():
def test_soap_fail_closed_without_wsdl():
"""SOAP 无 wsdl/endpoint 时 fail-closed 抛 TransportNotFrozenError。"""
"""SOAP 无 wsdl 时 fail-closed 抛 TransportNotFrozenError(SOAP 只需 wsdl,不需 endpoint)。"""
transport = SoapTransport()
with pytest.raises(TransportNotFrozenError):
transport.call(
@@ -0,0 +1,48 @@
"""
backend/tests/test_integration_connector_columns_migration.py
用途:验证集成连接器"关键字段拆列"迁移的版本链与新增/回滚列清单。
依赖:新增迁移模块、pytest monkeypatch。
逻辑:拦截 add_column/drop_column,确认三个表各加/删目标列;确认 down_revision 承接当前 head。
"""
from __future__ import annotations
from typing import Any
MIGRATION_REV = "ix1a2b3c4d5e_split_integration_connector_columns"
COLUMN_TARGETS: list[tuple[str, str]] = [
("integration_client_instances", "endpoint"),
("integration_client_instances", "timeout_seconds"),
("integration_interface_definitions", "http_method"),
("integration_interface_definitions", "request_path"),
("integration_bindings", "context_source_code"),
]
def test_integration_connector_column_migration_adds_columns(monkeypatch):
"""迁移应承接 head iy1a2b3c4d5e,并对三张表加关键字段列。"""
import importlib
module = importlib.import_module(f"migrations.versions.{MIGRATION_REV}")
add_calls: list[tuple[str, str]] = []
drop_calls: list[tuple[str, str]] = []
def capture_add(table_name: str, column: Any, **_: Any) -> None:
add_calls.append((table_name, getattr(column, "name", column)))
def capture_drop(table_name: str, column_name: Any, **_: Any) -> None:
drop_calls.append((table_name, getattr(column_name, "name", column_name)))
monkeypatch.setattr(module.op, "add_column", capture_add)
monkeypatch.setattr(module.op, "drop_column", capture_drop)
module.upgrade()
assert module.down_revision == "iy1a2b3c4d5e"
for target in COLUMN_TARGETS:
assert target in add_calls
module.downgrade()
for target in COLUMN_TARGETS:
assert target in drop_calls
@@ -85,6 +85,8 @@ const ProcurementContractPage = () =>
import("@/features/admin/modules/procurement-contract/ProcurementContractPage.vue");
const TrainingConfigPage = () =>
import("@/features/admin/modules/training-config/TrainingConfigPage.vue");
const IntegrationConnectorPage = () =>
import("@/features/admin/modules/integration-connector/IntegrationConnectorPage.vue");
export const adminRoutes: RouteRecordRaw[] = [
{
@@ -355,6 +357,16 @@ export const adminRoutes: RouteRecordRaw[] = [
title: "admin.nav.trainingConfig",
},
},
{
path: "integration-connector",
name: "AdminIntegrationConnector",
component: IntegrationConnectorPage,
meta: {
requiresAdmin: true,
adminModule: "integration_connector",
title: "admin.nav.integrationConnector",
},
},
{
path: "reports/:table?",
name: "AdminReports",
+1
View File
@@ -74,6 +74,7 @@ export const config = {
shipping_inventory: true, // 货代配置
procurement_contract: true, // 采购合同审查(模板库 + 历史)
training_config: true,
integration_connector: true, // 集成连接器配置
}
}
};
@@ -11,7 +11,7 @@ import { useRoute, useRouter } from 'vue-router';
import {
LayoutDashboard, UserPlus, UserCog, Building, Bot, FileText,
Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow,
ScrollText, ExternalLink, PackageSearch, GraduationCap,
ScrollText, ExternalLink, PackageSearch, GraduationCap, Cable,
} from 'lucide-vue-next';
import type { Component } from 'vue';
import { config } from '@/config';
@@ -44,6 +44,7 @@ const iconMap: Record<AdminModuleId, Component> = {
platform_apps: AppWindow,
procurement_contract: ScrollText,
training_config: GraduationCap,
integration_connector: Cable,
requests: ShieldCheck,
reports: BarChart2,
shipping_inventory: PackageSearch,
@@ -129,6 +130,8 @@ watch(
isShippingActive,
(active) => {
if (!active) return;
// 进入任一货代子路由时自动展开父菜单,保证当前子页可见。
navStore.shippingMenuExpanded = true;
let matched = false;
for (const groupKey of shippingGroups.value) {
const groupHasActiveSub = SHIPPING_CONFIG_SUB_MODULE_METAS.some(
@@ -210,14 +213,14 @@ watch(
type="button"
class="admin-nav-btn group justify-between"
:class="{ 'admin-nav-btn--active': isShippingActive }"
@click="navigateModule('AdminShippingInventory')"
@click="navStore.shippingMenuExpanded = !navStore.shippingMenuExpanded"
>
<div class="flex items-center gap-3">
<PackageSearch class="w-5 h-5 flex-shrink-0" :class="isShippingActive ? 'text-brand-600' : 'text-muted'" />
<span :class="navStore.sidebarCollapsed ? 'md:hidden' : ''">{{ t('admin.nav.shippingConfig') }}</span>
</div>
</button>
<div v-if="isShippingActive && !navStore.sidebarCollapsed" class="pl-4 space-y-1 mt-1 border-l-2 border-subtle ml-6">
<div v-if="navStore.shippingMenuExpanded && !navStore.sidebarCollapsed" class="pl-4 space-y-1 mt-1 border-l-2 border-subtle ml-6">
<div v-for="groupKey in shippingGroups" :key="groupKey" class="flex flex-col">
<button
type="button"
@@ -40,7 +40,7 @@ export interface ShippingConfigSubModuleMeta {
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
export const STANDALONE_ADMIN_MODULES = new Set<AdminModuleId>([
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'shipping_inventory', 'procurement_contract', 'reports','training_config'
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'shipping_inventory', 'procurement_contract', 'reports','training_config', 'integration_connector'
]);
export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
@@ -60,6 +60,7 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
{ id: 'platform_apps', routeName: 'AdminPlatformApps', path: 'platform-apps', labelKey: 'admin.nav.platformApps', configKey: 'platform_apps' },
{ id: 'procurement_contract', routeName: 'AdminProcurementContract', path: 'procurement-contract', labelKey: 'admin.nav.procurementContract', configKey: 'procurement_contract' },
{ id: 'training_config', routeName: 'AdminTrainingConfig', path: 'training-config', labelKey: 'admin.nav.trainingConfig', configKey: 'training_config' },
{ id: 'integration_connector', routeName: 'AdminIntegrationConnector', path: 'integration-connector', labelKey: 'admin.nav.integrationConnector', configKey: 'integration_connector' },
{ id: 'requests', routeName: 'AdminRequests', path: 'requests', labelKey: 'admin.nav.requests', configKey: 'requests' },
];
@@ -0,0 +1,275 @@
<!--
features/admin/modules/integration-connector/IntegrationConnectorPage.vue
用途:集成连接器管理页——四个配置实体(客户端实例/接口定义/绑定/凭据引用)tab 列表 +
能力清单与手动调用测试;创建/编辑弹窗 + 连接测试。
依赖:useIntegrationConnectorAdmin、两个弹窗组件、useI18n。
逻辑:按 tab 展示列表与「新增」;配置「绑定」是让自动调拨跑起来的最小闭环核心。
-->
<script setup lang="ts">
import { computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Plus, Edit, Trash2, Plug, PlayCircle } from 'lucide-vue-next';
import IntegrationConnectorFormModal from './components/IntegrationConnectorFormModal.vue';
import IntegrationCapabilityCallModal from './components/IntegrationCapabilityCallModal.vue';
import { useIntegrationConnectorAdmin } from './composables/useIntegrationConnectorAdmin';
const { t } = useI18n();
const {
clients, interfaces, bindings, credentials, capabilities,
isLoading, activeEntity, showFormModal, isSaving,
clientForm, interfaceForm, bindingForm, credentialForm,
showCallModal, callCapability, callParamsText, callContextText, callResult, callBusy,
testResultText,
loadAll, openCreateModal, openEditModal, closeFormModal, saveActive,
testConnection, openCallModal, closeCallModal, runCall, deleteClient,
} = useIntegrationConnectorAdmin();
onMounted(() => { void loadAll(); });
type TabKey = 'client' | 'interface' | 'binding' | 'credential' | 'capability';
const tabs: Array<{ key: TabKey; labelKey: string }> = [
{ key: 'client', labelKey: 'admin.integrationConnector.tabs.client' },
{ key: 'interface', labelKey: 'admin.integrationConnector.tabs.interface' },
{ key: 'binding', labelKey: 'admin.integrationConnector.tabs.binding' },
{ key: 'credential', labelKey: 'admin.integrationConnector.tabs.credential' },
{ key: 'capability', labelKey: 'admin.integrationConnector.tabs.capability' },
];
const activeTab = computed<TabKey>(() => (activeEntity.value === 'credential' ? 'credential' : activeEntity.value));
const clientOptions = computed(() => clients.value.map((c) => ({ code: c.code, name: c.name })));
const interfaceOptions = computed(() => interfaces.value.map((i) => ({ code: i.code, name: i.name })));
const capabilityOptions = computed(() => capabilities.value.map((c) => ({ name: c.name })));
function selectTab(key: TabKey) {
// capability tab 只读展示,不进入表单实体;其余映射到可编辑实体。
if (key === 'capability') return;
activeEntity.value = key;
}
</script>
<template>
<section class="admin-table-section animate-fade-in-up">
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.integrationConnector.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.integrationConnector.subtitle') }}</p>
</div>
<button
v-if="activeTab !== 'capability'"
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
@click="openCreateModal(activeEntity)"
>
<Plus class="w-4 h-4" />
<span>{{ t('admin.integrationConnector.add') }}</span>
</button>
</div>
<div class="flex gap-1 border-b border-default" role="tablist">
<button
v-for="tab in tabs"
:key="tab.key"
type="button"
role="tab"
class="px-4 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors"
:class="activeTab === tab.key ? 'border-brand-600 text-brand-600' : 'border-transparent text-muted hover:text-secondary'"
:aria-selected="activeTab === tab.key"
@click="selectTab(tab.key)"
>
{{ t(tab.labelKey) }}
</button>
</div>
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div>
<template v-else>
<!-- 客户端实例 -->
<div v-if="activeTab === 'client'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<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.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-right text-xs w-40">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="clients.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<tr v-for="row in clients" :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 text-secondary">{{ row.name }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.connector_type }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.environment }}</td>
<td class="px-6 py-4 text-right">
<div class="inline-flex items-center gap-1">
<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)">
<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.code)">
<Trash2 class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</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 v-else-if="activeTab === 'interface'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<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.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-right text-xs w-24">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="interfaces.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<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 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 text-sm text-secondary">{{ row.status }}</td>
<td class="px-6 py-4 text-right">
<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('interface', row)">
<Edit class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- 绑定 -->
<div v-else-if="activeTab === 'binding'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<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.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-right text-xs w-24">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<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">
<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 text-sm text-secondary">{{ row.interface_definition_code }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.status }}</td>
<td class="px-6 py-4 text-right">
<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('binding', row)">
<Edit class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- 凭据引用 -->
<div v-else-if="activeTab === 'credential'" class="admin-table-wrap">
<table class="admin-table">
<thead>
<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.secretRef') }}</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-right text-xs w-24">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="credentials.length === 0"><td colspan="5" class="px-6 admin-table-empty">{{ t('admin.integrationConnector.empty') }}</td></tr>
<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 text-secondary mono">{{ row.secret_ref }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.secret_provider }}</td>
<td class="px-6 py-4 text-sm text-secondary">{{ row.status }}</td>
<td class="px-6 py-4 text-right">
<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)">
<Edit class="w-4 h-4" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- 能力清单 -->
<div v-else class="admin-table-wrap">
<table class="admin-table">
<thead>
<tr>
<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.write') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.integrationConnector.headers.idempotency') }}</th>
<th class="px-6 py-4 text-right text-xs w-28">{{ t('admin.integrationConnector.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<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">
<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 text-sm text-secondary">{{ row.idempotency }}</td>
<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)">
<PlayCircle class="w-4 h-4" />
{{ t('admin.integrationConnector.call') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<IntegrationConnectorFormModal
:visible="showFormModal"
:active-entity="activeEntity"
:client-form="clientForm"
:interface-form="interfaceForm"
:binding-form="bindingForm"
:credential-form="credentialForm"
:is-saving="isSaving"
:client-options="clientOptions"
:interface-options="interfaceOptions"
:capability-options="capabilityOptions"
@close="closeFormModal"
@save="saveActive"
/>
<IntegrationCapabilityCallModal
:visible="showCallModal"
:capability="callCapability"
:params-text="callParamsText"
:context-text="callContextText"
:result="callResult"
:busy="callBusy"
@close="closeCallModal"
@run="runCall"
/>
</section>
</template>
@@ -0,0 +1,105 @@
/**
* features/admin/modules/integration-connector/api/integration-connector.api.ts
* 集成连接器管理 API 客户端:客户端实例/接口定义/绑定/凭据引用 CRUD + 能力清单 + 连接测试。
* 依赖:@/shared/api/client(requestJson / BusinessError)、@/shared/utils/auth。
* 逻辑:薄封装后端 /api/integration-connector/* 全部端点;JSON 写请求带 Content-Type。
* 错误码(INTEGRATION.*)由 requestJson 解析到四语言文案。
*/
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import type {
IntegrationBindingRow,
IntegrationCallResultRow,
IntegrationCapabilityRow,
IntegrationClientInstanceRow,
IntegrationCredentialReferenceRow,
IntegrationInterfaceDefinitionRow,
} from '../types/integration-connector.types';
const BASE = '/api/integration-connector';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
// ---- 能力清单与调用 ----
/** 能力清单(写/幂等/入出参 Schema)。 */
export const listIntegrationCapabilities = () =>
requestJson<IntegrationCapabilityRow[]>(`${BASE}/capabilities`, auth());
/** 手动调用一个已注册能力(入参 + 路由上下文)。 */
export const callIntegrationCapability = (capability: string, payload: { params?: Record<string, unknown>; context?: Record<string, unknown>; operation_id?: string; idempotency_key?: string }) =>
requestJson<IntegrationCallResultRow>(`${BASE}/capabilities/${encodeURIComponent(capability)}`, {
method: 'POST',
...jsonAuth(),
body: JSON.stringify(payload),
});
// ---- 客户端实例 ----
export const listIntegrationClientInstances = () =>
requestJson<IntegrationClientInstanceRow[]>(`${BASE}/client-instances`, auth());
export const createIntegrationClientInstance = (payload: Record<string, unknown>) =>
requestJson<IntegrationClientInstanceRow>(`${BASE}/client-instances`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
});
export const updateIntegrationClientInstance = (code: string, payload: Record<string, unknown>) =>
requestJson<IntegrationClientInstanceRow>(`${BASE}/client-instances/${encodeURIComponent(code)}`, {
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
});
export const deleteIntegrationClientInstance = (code: string) =>
requestJson(`${BASE}/client-instances/${encodeURIComponent(code)}`, { method: 'DELETE', ...auth() });
/** 连接测试(返回底层传输 raw 结果)。 */
export const testIntegrationClientConnection = (code: string) =>
requestJson<Record<string, unknown>>(`${BASE}/client-instances/${encodeURIComponent(code)}/test`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify({}),
});
// ---- 接口定义 ----
export const listIntegrationInterfaceDefinitions = () =>
requestJson<IntegrationInterfaceDefinitionRow[]>(`${BASE}/interface-definitions`, auth());
export const createIntegrationInterfaceDefinition = (payload: Record<string, unknown>) =>
requestJson<IntegrationInterfaceDefinitionRow>(`${BASE}/interface-definitions`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
});
export const updateIntegrationInterfaceDefinition = (code: string, payload: Record<string, unknown>) =>
requestJson<IntegrationInterfaceDefinitionRow>(`${BASE}/interface-definitions/${encodeURIComponent(code)}`, {
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
});
// ---- 绑定 ----
export const listIntegrationBindings = () =>
requestJson<IntegrationBindingRow[]>(`${BASE}/bindings`, auth());
export const createIntegrationBinding = (payload: Record<string, unknown>) =>
requestJson<IntegrationBindingRow>(`${BASE}/bindings`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
});
export const updateIntegrationBinding = (id: number, payload: Record<string, unknown>) =>
requestJson<IntegrationBindingRow>(`${BASE}/bindings/${id}`, {
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
});
// ---- 凭据引用 ----
export const listIntegrationCredentialReferences = () =>
requestJson<IntegrationCredentialReferenceRow[]>(`${BASE}/credential-references`, auth());
export const createIntegrationCredentialReference = (payload: Record<string, unknown>) =>
requestJson<IntegrationCredentialReferenceRow>(`${BASE}/credential-references`, {
method: 'POST', ...jsonAuth(), body: JSON.stringify(payload),
});
export const updateIntegrationCredentialReference = (code: string, payload: Record<string, unknown>) =>
requestJson<IntegrationCredentialReferenceRow>(`${BASE}/credential-references/${encodeURIComponent(code)}`, {
method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload),
});
@@ -0,0 +1,59 @@
<!--
features/admin/modules/integration-connector/components/IntegrationCapabilityCallModal.vue
用途:手动调用一个已注册能力(输入 params / context JSON),展示调用结果与 trace。
依赖:showCallModal、callParamsText、callContextText、callResult、callBusy。
逻辑:由 IntegrationConnectorPage 打开;emit close/run。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { IntegrationCallResultRow } from '../types/integration-connector.types';
const props = defineProps<{
visible: boolean;
capability: string;
paramsText: string;
contextText: string;
result: IntegrationCallResultRow | null;
busy: boolean;
}>();
const emit = defineEmits<{
close: [];
run: [];
}>();
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.callModal.title', { capability }) }}</h3>
<p class="section-desc mt-1">{{ t('admin.integrationConnector.callModal.hint') }}</p>
</div>
<div class="px-5 sm:px-8 py-5 space-y-4 overflow-y-auto">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.callModal.params') }}</label>
<textarea :value="props.paramsText" rows="6" class="input-field text-sm font-mono" spellcheck="false" readonly />
<p class="text-xs text-muted">{{ t('admin.integrationConnector.callModal.paramsHint') }}</p>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.callModal.context') }}</label>
<textarea :value="props.contextText" rows="4" class="input-field text-sm font-mono" spellcheck="false" readonly />
<p class="text-xs text-muted">{{ t('admin.integrationConnector.callModal.contextHint') }}</p>
</div>
<div v-if="result" class="space-y-1.5">
<label class="label-field">{{ t('admin.integrationConnector.callModal.result') }}</label>
<pre class="rounded-lg bg-surface-soft p-3 text-xs font-mono text-secondary whitespace-pre-wrap break-all">{{ JSON.stringify(result, null, 2) }}</pre>
</div>
</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="busy" @click="emit('run')">
{{ busy ? t('admin.integrationConnector.callModal.running') : t('admin.integrationConnector.callModal.run') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,96 @@
/**
* 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);
});
});
@@ -0,0 +1,277 @@
<!--
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,148 @@
/**
* features/admin/modules/integration-connector/composables/useIntegrationConnectorAdmin.spec.ts
* 用途:锁定集成连接器管理编排——四实体保存(create/update 分支)、JSON 字段解析校验、
* 必填校验拦截、能力调用与连接测试调用 API。
* 依赖:vi.mock(integration-connector.api)、@vue/test-utils、i18n。
* 逻辑:通过 setup 挂载 harness 组件访问 useIntegrationConnectorAdmin(useI18n 需在 setup 内);
* Mock API 断言 payload 构造与调用;非法 JSON 触发拦截且不调 API。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { defineComponent, h } from 'vue';
import { mount } from '@vue/test-utils';
import i18n from '@/i18n';
import { useIntegrationConnectorAdmin } from './useIntegrationConnectorAdmin';
const api = vi.hoisted(() => ({
listIntegrationClientInstances: vi.fn(),
createIntegrationClientInstance: vi.fn(),
updateIntegrationClientInstance: vi.fn(),
deleteIntegrationClientInstance: vi.fn(),
testIntegrationClientConnection: vi.fn(),
listIntegrationInterfaceDefinitions: vi.fn(),
createIntegrationInterfaceDefinition: vi.fn(),
updateIntegrationInterfaceDefinition: vi.fn(),
listIntegrationBindings: vi.fn(),
createIntegrationBinding: vi.fn(),
updateIntegrationBinding: vi.fn(),
listIntegrationCredentialReferences: vi.fn(),
createIntegrationCredentialReference: vi.fn(),
updateIntegrationCredentialReference: vi.fn(),
listIntegrationCapabilities: vi.fn(),
callIntegrationCapability: vi.fn(),
}));
vi.mock('@/features/admin/modules/integration-connector/api/integration-connector.api', () => api);
function makeHarness() {
let exposed: ReturnType<typeof useIntegrationConnectorAdmin> | null = null;
const Harness = defineComponent({
setup() {
exposed = useIntegrationConnectorAdmin();
return () => h('div');
},
});
mount(Harness, { global: { plugins: [i18n] } });
return exposed!;
}
describe('useIntegrationConnectorAdmin', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('loadAll 拉取五个列表', async () => {
api.listIntegrationClientInstances.mockResolvedValue([]);
api.listIntegrationInterfaceDefinitions.mockResolvedValue([]);
api.listIntegrationBindings.mockResolvedValue([]);
api.listIntegrationCredentialReferences.mockResolvedValue([]);
api.listIntegrationCapabilities.mockResolvedValue([]);
const c = makeHarness();
await c.loadAll();
expect(api.listIntegrationClientInstances).toHaveBeenCalled();
expect(api.listIntegrationCapabilities).toHaveBeenCalled();
});
it('新建客户端实例:关键字段独立列 + config_json 解析为对象并 POST', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.code = 'ERP-X';
c.clientForm.value.name = 'ERP X';
c.clientForm.value.endpoint = 'https://x.invalid';
c.clientForm.value.timeout_seconds = '90';
c.clientForm.value.config_json = '{"headers":{"X-Tenant":"A"}}';
await c.saveActive();
expect(api.createIntegrationClientInstance).toHaveBeenCalledWith({
code: 'ERP-X', name: 'ERP X', connector_type: 'rest', environment: 'prod',
endpoint: 'https://x.invalid', timeout_seconds: 90,
config_json: { headers: { 'X-Tenant': 'A' } }, credential_ref_code: null, enabled: true,
});
});
it('编辑客户端实例:有 id 走 PUT', async () => {
const c = makeHarness();
c.openEditModal('client', {
id: 1, code: 'ERP-X', name: 'old', connector_type: 'rest', environment: 'prod',
config_json: {}, credential_ref_code: null, enabled: true,
});
c.clientForm.value.name = 'new';
await c.saveActive();
expect(api.updateIntegrationClientInstance).toHaveBeenCalled();
});
it('非法 JSON 字段触发拦截且不调 API', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.code = 'ERP-X';
c.clientForm.value.name = 'ERP X';
c.clientForm.value.config_json = '{bad json';
await c.saveActive();
expect(api.createIntegrationClientInstance).not.toHaveBeenCalled();
});
it('客户端实例必填:缺 code 不调 API', async () => {
const c = makeHarness();
c.openCreateModal('client');
c.clientForm.value.name = 'ERP X';
await c.saveActive();
expect(api.createIntegrationClientInstance).not.toHaveBeenCalled();
});
it('绑定:必填校验与 POST payload', async () => {
const c = makeHarness();
c.openCreateModal('binding');
c.bindingForm.value.capability = 'in_transit_transfer.query_inventory';
c.bindingForm.value.client_instance_code = 'CLI-A';
c.bindingForm.value.interface_definition_code = 'IF-A';
await c.saveActive();
expect(api.createIntegrationBinding).toHaveBeenCalledWith({
capability: 'in_transit_transfer.query_inventory', context_selector_json: {},
context_source_code: null,
client_instance_code: 'CLI-A', interface_definition_code: 'IF-A',
mapping_version: 1, priority: 0, environment: 'prod',
effective_from: null, effective_to: null, status: 'draft',
});
});
it('凭据引用:创建 payload 不含明文 secret', async () => {
const c = makeHarness();
c.openCreateModal('credential');
c.credentialForm.value.code = 'CRED-A';
c.credentialForm.value.secret_ref = 'IN_TRANSIT_ERP_PASSWORD';
await c.saveActive();
expect(api.createIntegrationCredentialReference).toHaveBeenCalledWith({
code: 'CRED-A', secret_ref: 'IN_TRANSIT_ERP_PASSWORD', secret_provider: 'env',
credential_type: 'password', status: 'active',
});
});
it('连接测试与能力调用走对应 API', async () => {
const c = makeHarness();
api.testIntegrationClientConnection.mockResolvedValue({ ok: true });
api.callIntegrationCapability.mockResolvedValue({ status: 'success', data: { found: true }, error_code: null, error_message: null, document_no: null, trace_id: null });
await c.testConnection('CLI-A');
expect(api.testIntegrationClientConnection).toHaveBeenCalledWith('CLI-A');
c.openCallModal('in_transit_transfer.query_inventory');
await c.runCall();
expect(api.callIntegrationCapability).toHaveBeenCalled();
});
});
@@ -0,0 +1,296 @@
/**
* features/admin/modules/integration-connector/composables/useIntegrationConnectorAdmin.ts
* 集成连接器管理编排:客户端实例/接口定义/绑定/凭据引用四实体列表与增改表单,
* 以及能力清单与手动调用测试。
* 依赖:integration-connector.api、types、useMessage、useI18n。
* 逻辑:各列表独立 loadAll;新增/编辑共用表单弹窗态(form.id 区分);能力测试
* 独立于配置表单(CapabilityCall 弹窗)。保存/删除后刷新对应列表。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '@/shared/composables/useMessage';
import {
callIntegrationCapability,
createIntegrationBinding,
createIntegrationClientInstance,
createIntegrationCredentialReference,
createIntegrationInterfaceDefinition,
deleteIntegrationClientInstance,
listIntegrationBindings,
listIntegrationCapabilities,
listIntegrationClientInstances,
listIntegrationCredentialReferences,
listIntegrationInterfaceDefinitions,
testIntegrationClientConnection,
updateIntegrationBinding,
updateIntegrationClientInstance,
updateIntegrationCredentialReference,
updateIntegrationInterfaceDefinition,
} from '../api/integration-connector.api';
import {
bindingRowToForm,
clientInstanceRowToForm,
createEmptyBindingForm,
createEmptyClientInstanceForm,
createEmptyCredentialReferenceForm,
createEmptyInterfaceDefinitionForm,
credentialReferenceRowToForm,
interfaceDefinitionRowToForm,
type BindingFormState,
type ClientInstanceFormState,
type CredentialReferenceFormState,
type IntegrationBindingRow,
type IntegrationCallResultRow,
type IntegrationCapabilityRow,
type IntegrationClientInstanceRow,
type IntegrationCredentialReferenceRow,
type IntegrationInterfaceDefinitionRow,
type InterfaceDefinitionFormState,
} from '../types/integration-connector.types';
type EditableEntity = 'client' | 'interface' | 'binding' | 'credential';
export function useIntegrationConnectorAdmin() {
const { t } = useI18n();
const msg = useMessage();
// ---- 列表与加载态 ----
const clients = ref<IntegrationClientInstanceRow[]>([]);
const interfaces = ref<IntegrationInterfaceDefinitionRow[]>([]);
const bindings = ref<IntegrationBindingRow[]>([]);
const credentials = ref<IntegrationCredentialReferenceRow[]>([]);
const capabilities = ref<IntegrationCapabilityRow[]>([]);
const isLoading = ref(true);
// ---- 表单弹窗态 ----
const activeEntity = ref<EditableEntity>('client');
const showFormModal = ref(false);
const isSaving = ref(false);
const clientForm = ref<ClientInstanceFormState>(createEmptyClientInstanceForm());
const interfaceForm = ref<InterfaceDefinitionFormState>(createEmptyInterfaceDefinitionForm());
const bindingForm = ref<BindingFormState>(createEmptyBindingForm());
const credentialForm = ref<CredentialReferenceFormState>(createEmptyCredentialReferenceForm());
// ---- 能力调用测试弹窗态 ----
const showCallModal = ref(false);
const callCapability = ref('');
const callParamsText = ref('');
const callContextText = ref('');
const callResult = ref<IntegrationCallResultRow | null>(null);
const callBusy = ref(false);
// ---- 连接测试 ----
const testingClientCode = ref('');
const testResultText = ref('');
const loadClients = async () => { clients.value = await listIntegrationClientInstances(); };
const loadInterfaces = async () => { interfaces.value = await listIntegrationInterfaceDefinitions(); };
const loadBindings = async () => { bindings.value = await listIntegrationBindings(); };
const loadCredentials = async () => { credentials.value = await listIntegrationCredentialReferences(); };
const loadCapabilities = async () => { capabilities.value = await listIntegrationCapabilities(); };
const loadAll = async () => {
isLoading.value = true;
try {
await Promise.all([loadClients(), loadInterfaces(), loadBindings(), loadCredentials(), loadCapabilities()]);
} catch (e) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isLoading.value = false;
}
};
const reloadOne = async (entity: EditableEntity) => {
if (entity === 'client') await loadClients();
else if (entity === 'interface') await loadInterfaces();
else if (entity === 'binding') await loadBindings();
else await loadCredentials();
};
// ---- 弹窗打开/关闭 ----
const openCreateModal = (entity: EditableEntity) => {
activeEntity.value = entity;
if (entity === 'client') clientForm.value = createEmptyClientInstanceForm();
else if (entity === 'interface') interfaceForm.value = createEmptyInterfaceDefinitionForm();
else if (entity === 'binding') bindingForm.value = createEmptyBindingForm();
else credentialForm.value = createEmptyCredentialReferenceForm();
showFormModal.value = true;
};
const openEditModal = (entity: EditableEntity, row: IntegrationClientInstanceRow | IntegrationInterfaceDefinitionRow | IntegrationBindingRow | IntegrationCredentialReferenceRow) => {
activeEntity.value = entity;
if (entity === 'client') clientForm.value = clientInstanceRowToForm(row as IntegrationClientInstanceRow);
else if (entity === 'interface') interfaceForm.value = interfaceDefinitionRowToForm(row as IntegrationInterfaceDefinitionRow);
else if (entity === 'binding') bindingForm.value = bindingRowToForm(row as IntegrationBindingRow);
else credentialForm.value = credentialReferenceRowToForm(row as IntegrationCredentialReferenceRow);
showFormModal.value = true;
};
const closeFormModal = () => {
showFormModal.value = false;
clientForm.value = createEmptyClientInstanceForm();
interfaceForm.value = createEmptyInterfaceDefinitionForm();
bindingForm.value = createEmptyBindingForm();
credentialForm.value = createEmptyCredentialReferenceForm();
};
/** 解析 JSON 文本;空串返回 {},非法 JSON 抛错并提示。 */
const parseJsonField = (text: string, fieldLabel: string): Record<string, unknown> => {
const trimmed = String(text || '').trim();
if (!trimmed) return {};
try {
const parsed = JSON.parse(trimmed);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
throw new Error('must be an object');
} catch {
msg.warning(t('admin.integrationConnector.msg.invalidJson', { field: fieldLabel }));
throw new Error('invalid JSON');
}
};
// ---- 保存 ----
const saveActive = async () => {
isSaving.value = true;
try {
if (activeEntity.value === 'client') {
const form = clientForm.value;
if (!form.code.trim() || !form.name.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillClient'));
return;
}
const configJson = parseJsonField(form.config_json, 'config_json');
const payload = {
code: form.code.trim(), name: form.name.trim(), connector_type: form.connector_type,
environment: form.environment,
endpoint: form.endpoint.trim() || null,
timeout_seconds: form.timeout_seconds.trim() ? Number(form.timeout_seconds) : null,
config_json: configJson,
credential_ref_code: form.credential_ref_code.trim() || null, enabled: form.enabled,
};
if (form.id) await updateIntegrationClientInstance(form.code, payload);
else await createIntegrationClientInstance(payload);
} else if (activeEntity.value === 'interface') {
const form = interfaceForm.value;
if (!form.code.trim() || !form.client_instance_code.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillInterface'));
return;
}
const payload = {
code: form.code.trim(), name: form.name.trim() || form.code.trim(),
client_instance_code: form.client_instance_code.trim(), connector_type: form.connector_type,
http_method: form.http_method.trim() || null,
request_path: form.request_path.trim() || null,
request_spec_json: parseJsonField(form.request_spec_json, 'request_spec_json'),
input_schema_json: parseJsonField(form.input_schema_json, 'input_schema_json'),
response_mapping_json: parseJsonField(form.response_mapping_json, 'response_mapping_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);
else await createIntegrationInterfaceDefinition(payload);
} else if (activeEntity.value === 'binding') {
const form = bindingForm.value;
if (!form.capability.trim() || !form.client_instance_code.trim() || !form.interface_definition_code.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillBinding'));
return;
}
const payload = {
capability: form.capability.trim(), context_selector_json: parseJsonField(form.context_selector_json, 'context_selector_json'),
context_source_code: form.context_source_code.trim() || null,
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),
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);
else await createIntegrationBinding(payload);
} else {
const form = credentialForm.value;
if (!form.code.trim() || !form.secret_ref.trim()) {
msg.warning(t('admin.integrationConnector.msg.fillCredential'));
return;
}
const payload = {
code: form.code.trim(), secret_ref: form.secret_ref.trim(), secret_provider: form.secret_provider,
credential_type: form.credential_type, status: form.status,
};
if (form.id) await updateIntegrationCredentialReference(form.code, payload);
else await createIntegrationCredentialReference(payload);
}
closeFormModal();
await reloadOne(activeEntity.value);
msg.success(t('admin.integrationConnector.msg.saved'));
} catch (e) {
// parseJsonField 已在内部提示;这里兜底 API 错误。
if (!(e instanceof Error && e.message === 'invalid JSON')) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
} finally {
isSaving.value = false;
}
};
// ---- 连接测试 ----
const testConnection = async (code: string) => {
testingClientCode.value = code;
testResultText.value = '';
try {
const result = await testIntegrationClientConnection(code);
testResultText.value = JSON.stringify(result, null, 2);
msg.success(t('admin.integrationConnector.msg.testOk'));
} catch (e) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
testingClientCode.value = '';
}
};
// ---- 能力调用测试 ----
const openCallModal = (capability: string) => {
callCapability.value = capability;
callParamsText.value = JSON.stringify({ invoice_no: '', from_warehouse: '', to_warehouse: '', quantity: 0 }, null, 2);
callContextText.value = '{}';
callResult.value = null;
showCallModal.value = true;
};
const closeCallModal = () => {
showCallModal.value = false;
callResult.value = null;
};
const runCall = async () => {
callBusy.value = true;
try {
const params = parseJsonField(callParamsText.value, 'params');
const context = parseJsonField(callContextText.value, 'context');
callResult.value = await callIntegrationCapability(callCapability.value, { params, context });
} catch (e) {
if (!(e instanceof Error && e.message === 'invalid JSON')) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
} finally {
callBusy.value = false;
}
};
const deleteClient = async (code: string) => {
try {
await deleteIntegrationClientInstance(code);
await loadClients();
msg.success(t('admin.integrationConnector.msg.deleted'));
} catch (e) {
msg.error((e as Error).message || t('admin.msg.requestFailed'));
}
};
return {
clients, interfaces, bindings, credentials, capabilities,
isLoading, activeEntity, showFormModal, isSaving,
clientForm, interfaceForm, bindingForm, credentialForm,
showCallModal, callCapability, callParamsText, callContextText, callResult, callBusy,
testingClientCode, testResultText,
loadAll, openCreateModal, openEditModal, closeFormModal, saveActive,
testConnection, openCallModal, closeCallModal, runCall, deleteClient,
};
}
@@ -0,0 +1,287 @@
/**
* features/admin/modules/integration-connector/types/integration-connector.types.ts
* 集成连接器管理域类型:客户端实例、接口定义、绑定、凭据引用、能力清单、调用结果。
* 依赖:无(纯类型与表单构建函数)。
* 逻辑:与后端 /api/integration-connector/* 序列化契约对齐;JSON 配置字段以 Record 承载
* 具体结构由表单/JSON 编辑器负责,前端不硬编码外部系统差异。
*/
/** 连接器类型:与后端 CONNECTOR_TYPES 对齐。 */
export type IntegrationConnectorType = 'rest' | 'soap';
/** 配置状态:draft 草稿 / published 已发布 / retired 已退役。 */
export type IntegrationConfigStatus = 'draft' | 'published' | 'retired';
/** 凭据状态。 */
export type IntegrationCredentialStatus = 'active' | 'rotating' | 'retired';
/** 能力清单项(后端 capability 注册表)。 */
export interface IntegrationCapabilityRow {
name: string;
write: boolean;
idempotency: string;
input_schema: Record<string, unknown>;
output_schema: Record<string, unknown>;
}
/** 能力调用结果(后端 IntegrationCallResult 序列化)。 */
export interface IntegrationCallResultRow {
status: string;
data: Record<string, unknown> | null;
error_code: string | null;
error_message: string | null;
document_no: string | null;
trace_id: string | null;
}
/** 客户端实例(接口地址/凭据引用/连接配置)。 */
export interface IntegrationClientInstanceRow {
id: number;
code: string;
name: string;
connector_type: IntegrationConnectorType;
environment: string;
endpoint: string | null;
timeout_seconds: number | null;
config_json: Record<string, unknown>;
credential_ref_code: string | null;
enabled: boolean;
}
/** 接口定义(接口模板/入参字段/回传映射/出参 Schema)。 */
export interface IntegrationInterfaceDefinitionRow {
id: number;
code: string;
name: string;
client_instance_code: string;
connector_type: IntegrationConnectorType;
http_method: string | null;
request_path: string | null;
request_spec_json: Record<string, unknown>;
input_schema_json: Record<string, unknown>;
response_mapping_json: Record<string, unknown>;
output_schema_json: Record<string, unknown>;
version: number;
status: IntegrationConfigStatus;
enabled: boolean;
}
/** 绑定(能力 → 客户端 + 接口 + 映射版本)。 */
export interface IntegrationBindingRow {
id: number;
capability: string;
context_selector_json: Record<string, unknown>;
context_source_code: string | null;
client_instance_code: string;
interface_definition_code: string;
mapping_version: number;
priority: number;
environment: string;
effective_from: string | null;
effective_to: string | null;
status: IntegrationConfigStatus;
}
/** 凭据引用(只存 secret_ref,不落明文)。 */
export interface IntegrationCredentialReferenceRow {
id: number;
code: string;
secret_ref: string;
secret_provider: string;
credential_type: string;
version: number;
status: IntegrationCredentialStatus;
last_verified_at: string | null;
}
/** 客户端实例表单。 */
export interface ClientInstanceFormState {
id: number | null;
code: string;
name: string;
connector_type: IntegrationConnectorType;
environment: string;
endpoint: string;
timeout_seconds: string;
config_json: string;
credential_ref_code: string;
enabled: boolean;
}
/** 接口定义表单(JSON 字段以文本承载,提交时解析)。 */
export interface InterfaceDefinitionFormState {
id: number | null;
code: string;
name: string;
client_instance_code: string;
connector_type: IntegrationConnectorType;
http_method: string;
request_path: string;
request_spec_json: string;
input_schema_json: string;
response_mapping_json: string;
output_schema_json: string;
status: IntegrationConfigStatus;
enabled: boolean;
}
/** 绑定表单。 */
export interface BindingFormState {
id: number | null;
capability: string;
context_selector_json: string;
context_source_code: string;
client_instance_code: string;
interface_definition_code: string;
mapping_version: number;
priority: number;
environment: string;
effective_from: string;
effective_to: string;
status: IntegrationConfigStatus;
}
/** 凭据引用表单。 */
export interface CredentialReferenceFormState {
id: number | null;
code: string;
secret_ref: string;
secret_provider: string;
credential_type: string;
status: IntegrationCredentialStatus;
}
const toJsonText = (value: Record<string, unknown> | null | undefined): string => {
if (!value || Object.keys(value).length === 0) return '';
return JSON.stringify(value, null, 2);
};
/** 创建空的客户端实例表单。 */
export function createEmptyClientInstanceForm(): ClientInstanceFormState {
return {
id: null,
code: '',
name: '',
connector_type: 'rest',
environment: 'prod',
endpoint: '',
timeout_seconds: '60',
config_json: '',
credential_ref_code: '',
enabled: true,
};
}
/** 列表行回填为客户端实例编辑表单。 */
export function clientInstanceRowToForm(row: IntegrationClientInstanceRow): ClientInstanceFormState {
return {
id: row.id,
code: row.code,
name: row.name,
connector_type: row.connector_type,
environment: row.environment,
endpoint: row.endpoint ?? '',
timeout_seconds: String(row.timeout_seconds ?? ''),
config_json: toJsonText(row.config_json),
credential_ref_code: row.credential_ref_code ?? '',
enabled: Boolean(row.enabled),
};
}
/** 创建空的接口定义表单。 */
export function createEmptyInterfaceDefinitionForm(): InterfaceDefinitionFormState {
return {
id: null,
code: '',
name: '',
client_instance_code: '',
connector_type: 'rest',
http_method: '',
request_path: '',
request_spec_json: '',
input_schema_json: '',
response_mapping_json: '',
output_schema_json: '',
status: 'draft',
enabled: true,
};
}
/** 列表行回填为接口定义编辑表单。 */
export function interfaceDefinitionRowToForm(row: IntegrationInterfaceDefinitionRow): InterfaceDefinitionFormState {
return {
id: row.id,
code: row.code,
name: row.name,
client_instance_code: row.client_instance_code,
connector_type: row.connector_type,
http_method: row.http_method ?? '',
request_path: row.request_path ?? '',
request_spec_json: toJsonText(row.request_spec_json),
input_schema_json: toJsonText(row.input_schema_json),
response_mapping_json: toJsonText(row.response_mapping_json),
output_schema_json: toJsonText(row.output_schema_json),
status: row.status,
enabled: Boolean(row.enabled),
};
}
/** 创建空的绑定表单。 */
export function createEmptyBindingForm(): BindingFormState {
return {
id: null,
capability: '',
context_selector_json: '',
context_source_code: '',
client_instance_code: '',
interface_definition_code: '',
mapping_version: 1,
priority: 0,
environment: 'prod',
effective_from: '',
effective_to: '',
status: 'draft',
};
}
/** 列表行回填为绑定编辑表单。 */
export function bindingRowToForm(row: IntegrationBindingRow): BindingFormState {
return {
id: row.id,
capability: row.capability,
context_selector_json: toJsonText(row.context_selector_json),
context_source_code: row.context_source_code ?? '',
client_instance_code: row.client_instance_code,
interface_definition_code: row.interface_definition_code,
mapping_version: Number(row.mapping_version || 1),
priority: Number(row.priority || 0),
environment: row.environment,
effective_from: row.effective_from ?? '',
effective_to: row.effective_to ?? '',
status: row.status,
};
}
/** 创建空的凭据引用表单。 */
export function createEmptyCredentialReferenceForm(): CredentialReferenceFormState {
return {
id: null,
code: '',
secret_ref: '',
secret_provider: 'env',
credential_type: 'password',
status: 'active',
};
}
/** 列表行回填为凭据引用编辑表单。 */
export function credentialReferenceRowToForm(row: IntegrationCredentialReferenceRow): CredentialReferenceFormState {
return {
id: row.id,
code: row.code,
secret_ref: row.secret_ref,
secret_provider: row.secret_provider,
credential_type: row.credential_type,
status: row.status,
};
}
@@ -21,6 +21,7 @@ export type AdminModuleId =
| 'shipping_inventory'
| 'procurement_contract'
| 'training_config'
| 'integration_connector'
| 'reports';
/** 货代管理领域下可由侧栏展示和高亮的稳定业务页面。 */
+96 -33
View File
@@ -46,7 +46,8 @@
"overview": "Overview",
"linkedServices": "Linked Services",
"procurementContract": "Procurement Contract Review",
"trainingConfig": "Training Config"
"trainingConfig": "Training Config",
"integrationConnector": "Integration Connector"
},
"shippingOrderExtractionRuns": {
"eyebrow": "READ-ONLY RUN DIAGNOSTICS",
@@ -551,33 +552,6 @@
"schemaPolicyGroupHint": "Auto-creation and field derivation apply to the whole schema version; changes stay in draft until publish.",
"schemaPolicyDraftBadge": "Draft editable · save/publish pending",
"schemaPolicyPublishedBadge": "Published version (read-only)",
"derivationRulesTitle": "Field derivation rules (current schema draft)",
"derivationRulesHint": "Line-to-line derivation only; rules freeze with the published schema version.",
"derivationRulesNote": "Phase 1 supports copy_if_empty only: copy customer PO line into internal line_no when empty.",
"derivationEnabled": "Enabled",
"derivationSource": "Source field",
"derivationTarget": "Target field",
"derivationStrategy": "Strategy",
"derivationStrategyCopyIfEmpty": "Copy if empty",
"derivationSimulate": "Simulate",
"derivationSimulateTitle": "Derivation simulation",
"derivationSimulateSample": "Sample JSON (array of line objects)",
"derivationSimulateModeHistory": "Historical extraction sample",
"derivationSimulateModeInline": "Manual JSON",
"derivationSimulateHistorySample": "Select a traceable sample",
"derivationSimulateSamplesLoading": "Loading samples…",
"derivationSimulateSamplesEmpty": "No historical samples available",
"derivationSimulateSampleOption": "Extraction #{id} · {lines} lines · {status}",
"derivationSimulateSampleRequired": "Please select a historical sample",
"derivationSimulateRun": "Run simulation",
"derivationSimulateSampleInvalid": "Sample JSON must be an array of objects",
"derivationSimulateSummary": "Rule version V{version} · checksum {checksum}… · derived {derived} · skipped {skipped}",
"derivationSimulateNoMutate": "This operation does not create or modify orders.",
"derivationBefore": "Internal line_no before",
"derivationAfter": "Internal line_no after",
"derivationResult": "Result",
"derivationStatusDerived": "Derived",
"derivationStatusSkipped": "Skipped: {reason}",
"viewFieldImpact": "Impact analysis",
"assetIdentity": "Asset identity (read-only)",
"assetKindLabel": "Asset kind",
@@ -805,11 +779,11 @@
"noSourceOptions": "No fields available",
"systemFact": {
"task_no": "System task number",
"business_no": "Official business number",
"business_no": "Shipping notice number",
"warehouse_id": "Freight warehouse",
"inventory_source_code": "Inventory source code",
"export_date": "Export date",
"export_sequence": "Export row sequence"
"export_date": "Shipping notice date",
"notice_line_no": "Shipping notice line number"
},
"orderFieldOptionsEmpty": "There are no published order-template fields. Publish an Order Template Configuration version first; source fields will then appear here.",
"constantValueHint": "Writes the same value for every export, for example a fixed forwarder code.",
@@ -2783,8 +2757,7 @@
},
"events": {
"customer_auto_resolution_evaluated": "Auto-resolution evaluated",
"customer_auto_confirmed": "Customer auto-confirmed",
"customer_correction_applied": "Customer correction applied"
"customer_auto_confirmed": "Customer auto-confirmed"
},
"gate": {
"title": "Auto-confirmation quality gate",
@@ -5011,5 +4984,95 @@
"saved": "Training configuration saved",
"deleted": "Training configuration deleted"
}
},
"integrationConnector": {
"title": "Integration Connector",
"subtitle": "Configure external system clients, interface templates and response mapping, then bind them to capabilities; this is the integration config that makes auto-transfer run.",
"add": "Add",
"formHint": "Maintain JSON fields in the editor; the publish status decides whether a config is used by the Worker.",
"call": "Call",
"test": "Test Connection",
"empty": "No data",
"tabs": {
"client": "Client Instances",
"interface": "Interface Definitions",
"binding": "Bindings",
"credential": "Credential References",
"capability": "Capabilities"
},
"headers": {
"code": "Code",
"name": "Name",
"connectorType": "Type",
"environment": "Environment",
"status": "Status",
"clientInstance": "Client Instance",
"interfaceDef": "Interface Definition",
"secretRef": "Secret Ref",
"secretProvider": "Provider",
"capability": "Capability",
"write": "Write",
"idempotency": "Idempotency",
"actions": "Actions"
},
"fields": {
"code": "Code",
"name": "Name",
"connectorType": "Connector Type",
"environment": "Environment",
"credentialRef": "Credential Reference Code",
"configJson": "Connection config JSON (endpoint/timeout/default org, etc.)",
"clientInstance": "Client Instance",
"requestSpec": "Request template JSON",
"inputSchema": "Input schema JSON",
"responseMapping": "Response mapping JSON",
"outputSchema": "Output schema JSON",
"status": "Status",
"enabled": "Enabled",
"capability": "Capability",
"interfaceDef": "Interface Definition",
"mappingVersion": "Mapping Version",
"priority": "Priority",
"effectiveFrom": "Effective From",
"effectiveTo": "Effective To",
"contextSelector": "Context selector JSON (key-value, e.g. source_code=DBS-AWSBI)",
"secretRef": "Secret Ref Key",
"secretProvider": "Secret Provider",
"credentialType": "Credential Type",
"endpoint": "Endpoint",
"timeout": "Timeout (s)",
"wsdl": "WSDL URL",
"httpMethod": "HTTP Method",
"requestPath": "Request Path",
"contextSourceCode": "Source Instance Code"
},
"msg": {
"fillClient": "Please fill in code and name",
"fillInterface": "Please fill in code and select a client instance",
"fillBinding": "Please fill in capability, client instance and interface definition",
"fillCredential": "Please fill in code and secret ref",
"invalidJson": "{field} JSON is invalid",
"saved": "Saved",
"deleted": "Deleted",
"testOk": "Connection test passed"
},
"callModal": {
"title": "Call capability: {capability}",
"hint": "Debug only: manually call a registered capability; params and context are resolved by the current binding.",
"params": "Params JSON",
"paramsHint": "Fill per the capability input schema, e.g. invoice_no / from_warehouse / to_warehouse / quantity.",
"context": "Context JSON",
"contextHint": "Used for binding selector matching, e.g. source_code=DBS-AWSBI.",
"result": "Result",
"run": "Call",
"running": "Calling…"
},
"placeholders": {
"endpoint": "https://erp-api.example.com/ws",
"wsdl": "https://erp-api.example.com/wsdl",
"requestPath": "Path supports placeholders, e.g. /transfer/xxx",
"contextSourceCode": "e.g. DBS-AWSBI"
},
"advancedConfig": "Advanced config (JSON)"
}
}
+96 -33
View File
@@ -46,7 +46,8 @@
"linkedServices": "บริการที่เชื่อมโยง",
"platformApps": "แอปแพลตฟอร์ม",
"procurementContract": "ตรวจสอบสัญญาจัดซื้อ",
"trainingConfig": "การกำหนดค่าการฝึกอบรม"
"trainingConfig": "การกำหนดค่าการฝึกอบรม",
"integrationConnector": "ตัวเชื่อมต่อระบบ"
},
"shippingOrderExtractionRuns": {
"eyebrow": "การวินิจฉัยการทำงานแบบอ่านอย่างเดียว",
@@ -551,33 +552,6 @@
"schemaPolicyGroupHint": "การสร้างอัตโนมัติและการ derive ฟิลด์มีผลทั้งเวอร์ชัน Schema; แก้ในฉบับร่างและมีผลหลังเผยแพร่",
"schemaPolicyDraftBadge": "แก้ไขฉบับร่างได้ · รอบันทึก/เผยแพร่",
"schemaPolicyPublishedBadge": "ดูเวอร์ชันที่เผยแพร่เท่านั้น",
"derivationRulesTitle": "กฎการ derive ฟิลด์ (ฉบับร่าง Schema ปัจจุบัน)",
"derivationRulesHint": "อนุญาตเฉพาะ derive ภายในบรรทัดเดียวกัน และจะถูกแช่แข็งเมื่อเผยแพร่ Schema",
"derivationRulesNote": "ระยะแรกรองรับแค่ copy_if_empty: คัดลอก customer PO line ไปยัง line_no เมื่อว่าง",
"derivationEnabled": "เปิดใช้",
"derivationSource": "ฟิลด์ต้นทาง",
"derivationTarget": "ฟิลด์ปลายทาง",
"derivationStrategy": "กลยุทธ์",
"derivationStrategyCopyIfEmpty": "คัดลอกเมื่อว่าง",
"derivationSimulate": "จำลองด้วยตัวอย่าง",
"derivationSimulateTitle": "จำลองกฎ derive",
"derivationSimulateSample": "ตัวอย่าง JSON (อาร์เรย์ของบรรทัด)",
"derivationSimulateModeHistory": "ตัวอย่าง Extraction ในประวัติ",
"derivationSimulateModeInline": "JSON แบบมือ",
"derivationSimulateHistorySample": "เลือกตัวอย่างที่ตรวจสอบย้อนกลับได้",
"derivationSimulateSamplesLoading": "กำลังโหลดตัวอย่าง…",
"derivationSimulateSamplesEmpty": "ยังไม่มีตัวอย่างในประวัติ",
"derivationSimulateSampleOption": "Extraction #{id} · {lines} บรรทัด · {status}",
"derivationSimulateSampleRequired": "กรุณาเลือกตัวอย่างในประวัติ",
"derivationSimulateRun": "รันการจำลอง",
"derivationSimulateSampleInvalid": "ตัวอย่าง JSON ต้องเป็นอาร์เรย์ของอ็อบเจ็กต์",
"derivationSimulateSummary": "เวอร์ชันกฎ V{version} · checksum {checksum}… · derive {derived} · ข้าม {skipped}",
"derivationSimulateNoMutate": "การดำเนินการนี้จะไม่สร้างหรือแก้ไขคำสั่งซื้อ",
"derivationBefore": "line_no ก่อน derive",
"derivationAfter": "line_no หลัง derive",
"derivationResult": "ผลลัพธ์",
"derivationStatusDerived": "derive แล้ว",
"derivationStatusSkipped": "ข้าม: {reason}",
"viewFieldImpact": "วิเคราะห์ผลกระทบ",
"assetIdentity": "ตัวตนสินทรัพย์ (อ่านอย่างเดียว)",
"assetKindLabel": "ชนิดสินทรัพย์",
@@ -817,11 +791,11 @@
"templateLayoutReadFailed": "ไม่สามารถอ่านชีตและหัวตารางของเทมเพลต Excel ได้ โปรดตรวจสอบไฟล์แล้วลองใหม่",
"systemFact": {
"task_no": "หมายเลขงานระบบ",
"business_no": "เลขที่ธุรกิจอย่างเป็นทางการ",
"business_no": "เลขที่ใบแจ้งการจัดส่ง",
"warehouse_id": "คลังของผู้ให้บริการ",
"inventory_source_code": "รหัสแหล่งสต็อก",
"export_date": "วันที่ส่งออก",
"export_sequence": "ลำดับแถวส่งออก"
"export_date": "วันที่ใบแจ้งการจัดส่ง",
"notice_line_no": "ลำดับรายการใบแจ้งการจัดส่ง"
},
"excelTemplatesHelp": "อัปโหลดและเผยแพร่เทมเพลตการจัดส่งแบบมีเวอร์ชันที่ใช้ร่วมกันได้หลายแหล่งสินค้าคงคลังด้วย ID ฟิลด์คำสั่งซื้อที่คงที่",
"templateCode": "รหัสเทมเพลต",
@@ -2652,8 +2626,7 @@
},
"events": {
"customer_auto_resolution_evaluated": "ประเมินการระบุอัตโนมัติแล้ว",
"customer_auto_confirmed": "ยืนยันลูกค้าอัตโนมัติแล้ว",
"customer_correction_applied": "ใช้การแก้ไขลูกค้าแล้ว"
"customer_auto_confirmed": "ยืนยันลูกค้าอัตโนมัติแล้ว"
},
"gate": {
"title": "ประตูคุณภาพการยืนยันอัตโนมัติ",
@@ -4880,5 +4853,95 @@
"saved": "บันทึกการกำหนดค่าแล้ว",
"deleted": "ลบการกำหนดค่าแล้ว"
}
},
"integrationConnector": {
"title": "ตัวเชื่อมต่อระบบ",
"subtitle": "กำหนดค่าไคลเอนต์ระบบภายนอก เทมเพลตอินเทอร์เฟซ และการแมปผลตอบกลับ แล้วผูกกับความสามารถ นี่คือการกำหนดค่าแบบบูรณาการที่ทำให้การโอนย้ายอัตโนมัติทำงานได้",
"add": "เพิ่ม",
"formHint": "ดูแลฟิลด์ JSON ในตัวแก้ไข สถานะการเผยแพร่เป็นตัวกำหนดว่าการกำหนดค่านี้ถูกใช้โดย Worker หรือไม่",
"call": "เรียก",
"test": "ทดสอบการเชื่อมต่อ",
"empty": "ไม่มีข้อมูล",
"tabs": {
"client": "อินสแตนซ์ไคลเอนต์",
"interface": "นิยามอินเทอร์เฟซ",
"binding": "การผูก",
"credential": "การอ้างอิงข้อมูลรับรอง",
"capability": "รายการความสามารถ"
},
"headers": {
"code": "รหัส",
"name": "ชื่อ",
"connectorType": "ประเภท",
"environment": "สภาพแวดล้อม",
"status": "สถานะ",
"clientInstance": "อินสแตนซ์ไคลเอนต์",
"interfaceDef": "นิยามอินเทอร์เฟซ",
"secretRef": "การอ้างอิง Secret",
"secretProvider": "แหล่งที่มา",
"capability": "ความสามารถ",
"write": "เขียน",
"idempotency": "ไอดีมโพเทนซ์",
"actions": "การดำเนินการ"
},
"fields": {
"code": "รหัส",
"name": "ชื่อ",
"connectorType": "ประเภทตัวเชื่อมต่อ",
"environment": "สภาพแวดล้อม",
"credentialRef": "รหัสอ้างอิงข้อมูลรับรอง",
"configJson": "JSON การตั้งค่าการเชื่อมต่อ (endpoint/หมดเวลา/org เริ่มต้น ฯลฯ)",
"clientInstance": "อินสแตนซ์ไคลเอนต์",
"requestSpec": "JSON เทมเพลตคำขอ",
"inputSchema": "JSON Schema ขาเข้า",
"responseMapping": "JSON การแมปผลตอบกลับ",
"outputSchema": "JSON Schema ขาออก",
"status": "สถานะ",
"enabled": "เปิดใช้งาน",
"capability": "ความสามารถ",
"interfaceDef": "นิยามอินเทอร์เฟซ",
"mappingVersion": "เวอร์ชันการแมป",
"priority": "ลำดับความสำคัญ",
"effectiveFrom": "เริ่มมีผล",
"effectiveTo": "สิ้นสุดมีผล",
"contextSelector": "JSON ตัวเลือกบริบท (คู่คีย์-ค่า เช่น source_code=DBS-AWSBI)",
"secretRef": "คีย์อ้างอิง Secret",
"secretProvider": "แหล่งที่มาของ Secret",
"credentialType": "ประเภทข้อมูลรับรอง",
"endpoint": "ที่อยู่ปลายทาง",
"timeout": "หมดเวลา (วินาที)",
"wsdl": "URL WSDL",
"httpMethod": "วิธี HTTP",
"requestPath": "เส้นทางคำขอ",
"contextSourceCode": "รหัสแหล่งรับของ"
},
"msg": {
"fillClient": "กรุณากรอกรหัสและชื่อ",
"fillInterface": "กรุณากรอกรหัสและเลือกอินสแตนซ์ไคลเอนต์",
"fillBinding": "กรุณากรอกความสามารถ อินสแตนซ์ไคลเอนต์ และนิยามอินเทอร์เฟซ",
"fillCredential": "กรุณากรอกรหัสและการอ้างอิง Secret",
"invalidJson": "JSON ของ {field} ไม่ถูกต้อง",
"saved": "บันทึกแล้ว",
"deleted": "ลบแล้ว",
"testOk": "การทดสอบการเชื่อมต่อผ่าน"
},
"callModal": {
"title": "เรียกความสามารถ: {capability}",
"hint": "สำหรับการดีบักเท่านั้น: เรียกความสามารถที่ลงทะเบียนด้วยตนเอง พารามิเตอร์และบริบทจะถูกแก้ไขตามการผูกปัจจุบัน",
"params": "JSON พารามิเตอร์",
"paramsHint": "กรอกตาม Schema ขาเข้าของความสามารถ เช่น invoice_no / from_warehouse / to_warehouse / quantity",
"context": "JSON บริบท",
"contextHint": "ใช้สำหรับจับคู่ตัวเลือกการผูก เช่น source_code=DBS-AWSBI",
"result": "ผลการเรียก",
"run": "เรียก",
"running": "กำลังเรียก…"
},
"placeholders": {
"endpoint": "https://erp-api.example.com/ws",
"wsdl": "https://erp-api.example.com/wsdl",
"requestPath": "เส้นทางรองรับตัวแปร เช่น /transfer/xxx",
"contextSourceCode": "เช่น DBS-AWSBI"
},
"advancedConfig": "การตั้งค่าขั้นสูง (JSON)"
}
}
+96 -33
View File
@@ -46,7 +46,8 @@
"overview": "概览",
"linkedServices": "关联服务",
"procurementContract": "采购合同审查",
"trainingConfig": "培训配置"
"trainingConfig": "培训配置",
"integrationConnector": "集成连接器"
},
"shippingFieldAssets": {
"title": "字段资产库",
@@ -708,33 +709,6 @@
"schemaPolicyGroupHint": "自动建单与字段派生作用于整份 Schema 版本;改动仅写入草稿,发布后生效。",
"schemaPolicyDraftBadge": "草稿可编辑 · 待保存/发布",
"schemaPolicyPublishedBadge": "仅查看已发布版本",
"derivationRulesTitle": "字段派生规则(当前 Schema 草稿)",
"derivationRulesHint": "仅允许同行明细字段派生;发布后规则随 Schema 版本冻结。",
"derivationRulesNote": "首期仅支持 copy_if_empty:目标为空时从客户 PO 项次复制到内部项次。",
"derivationEnabled": "启用",
"derivationSource": "来源字段",
"derivationTarget": "目标字段",
"derivationStrategy": "策略",
"derivationStrategyCopyIfEmpty": "仅为空复制",
"derivationSimulate": "样本模拟",
"derivationSimulateTitle": "派生规则模拟",
"derivationSimulateSample": "样本 JSON(明细行数组)",
"derivationSimulateModeHistory": "历史 Extraction 样本",
"derivationSimulateModeInline": "手工 JSON",
"derivationSimulateHistorySample": "选择可追溯样本",
"derivationSimulateSamplesLoading": "正在加载样本…",
"derivationSimulateSamplesEmpty": "暂无可用历史样本",
"derivationSimulateSampleOption": "Extraction #{id} · {lines} 行 · {status}",
"derivationSimulateSampleRequired": "请选择历史样本",
"derivationSimulateRun": "运行模拟",
"derivationSimulateSampleInvalid": "样本 JSON 必须是对象数组",
"derivationSimulateSummary": "规则版本 V{version} · 校验和 {checksum}… · 已派生 {derived} · 跳过 {skipped}",
"derivationSimulateNoMutate": "本操作不会创建或修改订单。",
"derivationBefore": "派生前内部项次",
"derivationAfter": "派生后内部项次",
"derivationResult": "结果",
"derivationStatusDerived": "已派生",
"derivationStatusSkipped": "跳过:{reason}",
"viewFieldImpact": "影响分析",
"assetIdentity": "资产身份(只读)",
"assetKindLabel": "资产类型",
@@ -940,11 +914,11 @@
"noSourceOptions": "暂无可选字段",
"systemFact": {
"task_no": "系统任务号",
"business_no": "正式业务单号",
"business_no": "发货通知单号",
"warehouse_id": "货代仓库",
"inventory_source_code": "库存源编码",
"export_date": "导出日期",
"export_sequence": "导出行序号"
"export_date": "发货通知日期",
"notice_line_no": "发货通知项次"
},
"orderFieldOptionsEmpty": "当前没有已发布的订单模板字段;请先完成订单模板配置并发布版本,随后此处会显示可选择的来源字段。",
"constantValue": "常量值",
@@ -2894,8 +2868,7 @@
},
"events": {
"customer_auto_resolution_evaluated": "自动裁决已评估",
"customer_auto_confirmed": "客户已自动确认",
"customer_correction_applied": "客户纠错已应用"
"customer_auto_confirmed": "客户已自动确认"
},
"gate": {
"title": "自动确认质量门禁",
@@ -5005,5 +4978,95 @@
"saved": "培训配置已保存",
"deleted": "培训配置已删除"
}
},
"integrationConnector": {
"title": "集成连接器",
"subtitle": "配置外部系统客户端、接口模板与回传映射,并绑定到能力;它是自动调拨跑起来的集成配置。",
"add": "新增",
"formHint": "JSON 字段请在编辑框中维护;发布状态决定该配置是否被 Worker 使用。",
"call": "调用",
"test": "连接测试",
"empty": "暂无数据",
"tabs": {
"client": "客户端实例",
"interface": "接口定义",
"binding": "绑定",
"credential": "凭据引用",
"capability": "能力清单"
},
"headers": {
"code": "编码",
"name": "名称",
"connectorType": "类型",
"environment": "环境",
"status": "状态",
"clientInstance": "客户端实例",
"interfaceDef": "接口定义",
"secretRef": "Secret 引用",
"secretProvider": "来源",
"capability": "能力",
"write": "写入",
"idempotency": "幂等",
"actions": "操作"
},
"fields": {
"code": "编码",
"name": "名称",
"connectorType": "连接器类型",
"environment": "环境",
"credentialRef": "凭据引用编码",
"configJson": "连接配置 JSON(接口地址/超时/默认 org 等)",
"clientInstance": "客户端实例",
"requestSpec": "请求模板 JSON",
"inputSchema": "入参 Schema JSON",
"responseMapping": "回传映射 JSON",
"outputSchema": "出参 Schema JSON",
"status": "状态",
"enabled": "启用",
"capability": "能力",
"interfaceDef": "接口定义",
"mappingVersion": "映射版本",
"priority": "优先级",
"effectiveFrom": "生效开始",
"effectiveTo": "生效结束",
"contextSelector": "上下文选择器 JSON(键值对,如 source_code=DBS-AWSBI)",
"secretRef": "Secret 引用键",
"secretProvider": "Secret 来源",
"credentialType": "凭据类型",
"endpoint": "接口地址",
"timeout": "超时(秒)",
"wsdl": "WSDL 地址",
"httpMethod": "HTTP 方法",
"requestPath": "请求路径",
"contextSourceCode": "来源实例编码"
},
"msg": {
"fillClient": "请填写编码与名称",
"fillInterface": "请填写编码并选择客户端实例",
"fillBinding": "请填写能力、客户端实例与接口定义",
"fillCredential": "请填写编码与 Secret 引用",
"invalidJson": "{field} JSON 格式无效",
"saved": "已保存",
"deleted": "已删除",
"testOk": "连接测试通过"
},
"callModal": {
"title": "调用能力:{capability}",
"hint": "仅供调试:手动调用一个已注册能力,入参与上下文将按当前绑定解析。",
"params": "入参 JSON",
"paramsHint": "按能力入参 Schema 填写,例如 invoice_no / from_warehouse / to_warehouse / quantity。",
"context": "上下文 JSON",
"contextHint": "用于绑定选择器匹配,如 source_code=DBS-AWSBI。",
"result": "调用结果",
"run": "调用",
"running": "调用中…"
},
"placeholders": {
"endpoint": "https://erp-api.example.com/ws",
"wsdl": "https://erp-api.example.com/wsdl",
"requestPath": "路径支持占位符,如 /transfer/xxx",
"contextSourceCode": "例如 DBS-AWSBI"
},
"advancedConfig": "高级配置(JSON)"
}
}
+96 -33
View File
@@ -46,7 +46,8 @@
"linkedServices": "關聯服務",
"platformApps": "平台應用說明",
"procurementContract": "採購合同審查",
"trainingConfig": "培訓配置"
"trainingConfig": "培訓配置",
"integrationConnector": "整合連接器"
},
"shippingOrderExtractionRuns": {
"eyebrow": "唯讀執行診斷",
@@ -551,33 +552,6 @@
"schemaPolicyGroupHint": "自動建單與欄位派生作用於整份 Schema 版本;改動僅寫入草稿,發布後生效。",
"schemaPolicyDraftBadge": "草稿可編輯 · 待儲存/發布",
"schemaPolicyPublishedBadge": "僅檢視已發布版本",
"derivationRulesTitle": "欄位派生規則(目前 Schema 草稿)",
"derivationRulesHint": "僅允許同行明細欄位派生;發布後規則隨 Schema 版本凍結。",
"derivationRulesNote": "首期僅支援 copy_if_empty:目標為空時從客戶 PO 項次複製到內部項次。",
"derivationEnabled": "啟用",
"derivationSource": "來源欄位",
"derivationTarget": "目標欄位",
"derivationStrategy": "策略",
"derivationStrategyCopyIfEmpty": "僅為空複製",
"derivationSimulate": "樣本模擬",
"derivationSimulateTitle": "派生規則模擬",
"derivationSimulateSample": "樣本 JSON(明細行陣列)",
"derivationSimulateModeHistory": "歷史 Extraction 樣本",
"derivationSimulateModeInline": "手工 JSON",
"derivationSimulateHistorySample": "選擇可追溯樣本",
"derivationSimulateSamplesLoading": "正在載入樣本…",
"derivationSimulateSamplesEmpty": "暫無可用歷史樣本",
"derivationSimulateSampleOption": "Extraction #{id} · {lines} 行 · {status}",
"derivationSimulateSampleRequired": "請選擇歷史樣本",
"derivationSimulateRun": "執行模擬",
"derivationSimulateSampleInvalid": "樣本 JSON 必須是物件陣列",
"derivationSimulateSummary": "規則版本 V{version} · 校驗和 {checksum}… · 已派生 {derived} · 跳過 {skipped}",
"derivationSimulateNoMutate": "本操作不會建立或修改訂單。",
"derivationBefore": "派生前內部項次",
"derivationAfter": "派生後內部項次",
"derivationResult": "結果",
"derivationStatusDerived": "已派生",
"derivationStatusSkipped": "跳過:{reason}",
"viewFieldImpact": "影響分析",
"assetIdentity": "資產身份(唯讀)",
"assetKindLabel": "資產類型",
@@ -805,11 +779,11 @@
"noSourceOptions": "暫無可選欄位",
"systemFact": {
"task_no": "系統任務號",
"business_no": "正式業務單號",
"business_no": "發貨通知單號",
"warehouse_id": "貨代倉庫",
"inventory_source_code": "庫存來源編碼",
"export_date": "匯出日期",
"export_sequence": "匯出行序號"
"export_date": "發貨通知日期",
"notice_line_no": "發貨通知項次"
},
"orderFieldOptionsEmpty": "目前沒有已發布的訂單範本欄位;請先完成訂單範本設定並發布版本,之後此處會顯示可選來源欄位。",
"constantValueHint": "每次匯出都寫入相同內容,例如固定貨代代碼。",
@@ -2657,8 +2631,7 @@
},
"events": {
"customer_auto_resolution_evaluated": "自動裁決已評估",
"customer_auto_confirmed": "客戶已自動確認",
"customer_correction_applied": "客戶糾錯已套用"
"customer_auto_confirmed": "客戶已自動確認"
},
"gate": {
"title": "自動確認品質門禁",
@@ -4885,5 +4858,95 @@
"saved": "培訓配置已儲存",
"deleted": "培訓配置已刪除"
}
},
"integrationConnector": {
"title": "整合連接器",
"subtitle": "設定外部系統客戶端、介面範本與回傳映射,並繫結到能力;這是自動調撥能運行的整合設定。",
"add": "新增",
"formHint": "JSON 欄位請在編輯框中維護;發布狀態決定該設定是否被 Worker 使用。",
"call": "呼叫",
"test": "連線測試",
"empty": "暫無資料",
"tabs": {
"client": "客戶端實例",
"interface": "介面定義",
"binding": "繫結",
"credential": "憑證引用",
"capability": "能力清單"
},
"headers": {
"code": "編碼",
"name": "名稱",
"connectorType": "類型",
"environment": "環境",
"status": "狀態",
"clientInstance": "客戶端實例",
"interfaceDef": "介面定義",
"secretRef": "Secret 引用",
"secretProvider": "來源",
"capability": "能力",
"write": "寫入",
"idempotency": "冪等",
"actions": "操作"
},
"fields": {
"code": "編碼",
"name": "名稱",
"connectorType": "連接器類型",
"environment": "環境",
"credentialRef": "憑證引用編碼",
"configJson": "連線設定 JSON(介面位址/逾時/預設 org 等)",
"clientInstance": "客戶端實例",
"requestSpec": "請求範本 JSON",
"inputSchema": "入參 Schema JSON",
"responseMapping": "回傳映射 JSON",
"outputSchema": "出參 Schema JSON",
"status": "狀態",
"enabled": "啟用",
"capability": "能力",
"interfaceDef": "介面定義",
"mappingVersion": "映射版本",
"priority": "優先順序",
"effectiveFrom": "生效開始",
"effectiveTo": "生效結束",
"contextSelector": "上下文選擇器 JSON(鍵值對,如 source_code=DBS-AWSBI)",
"secretRef": "Secret 引用鍵",
"secretProvider": "Secret 來源",
"credentialType": "憑證類型",
"endpoint": "介面位址",
"timeout": "逾時(秒)",
"wsdl": "WSDL 位址",
"httpMethod": "HTTP 方法",
"requestPath": "請求路徑",
"contextSourceCode": "來源實例編碼"
},
"msg": {
"fillClient": "請填寫編碼與名稱",
"fillInterface": "請填寫編碼並選擇客戶端實例",
"fillBinding": "請填寫能力、客戶端實例與介面定義",
"fillCredential": "請填寫編碼與 Secret 引用",
"invalidJson": "{field} JSON 格式無效",
"saved": "已儲存",
"deleted": "已刪除",
"testOk": "連線測試通過"
},
"callModal": {
"title": "呼叫能力:{capability}",
"hint": "僅供偵錯:手動呼叫一個已註冊能力,入參與上下文將依目前繫結解析。",
"params": "入參 JSON",
"paramsHint": "依能力入參 Schema 填寫,例如 invoice_no / from_warehouse / to_warehouse / quantity。",
"context": "上下文 JSON",
"contextHint": "用於繫結選擇器匹配,如 source_code=DBS-AWSBI。",
"result": "呼叫結果",
"run": "呼叫",
"running": "呼叫中…"
},
"placeholders": {
"endpoint": "https://erp-api.example.com/ws",
"wsdl": "https://erp-api.example.com/wsdl",
"requestPath": "路徑支援佔位符,如 /transfer/xxx",
"contextSourceCode": "例如 DBS-AWSBI"
},
"advancedConfig": "進階設定(JSON)"
}
}