- 新增 resume_service:可恢复阻断行按(来源×收料日期)分组重建范围预检,收料文件不可用自动触发 RPA 重抓,单组失败不影响其余组 - precheck 新增 list_recent_prechecks 最近预检入口:未执行未过期可继续执行,解决预检卡关闭后无处恢复 - manual_close 支持按 item_ids 批量关闭并带审计,retry/backlog 配合按行口径调整 - 前端三区接线换新:首页待办/预检卡/待处理异常接恢复与批量动作,新增 transferDate 日期工具与 e2e 用例 - i18n chat/errors 四语言同步,technical.md 与 funclist 更新,落行归属解耦与 ERP 写路径两份实施计划
1004 lines
57 KiB
Markdown
1004 lines
57 KiB
Markdown
# 在途调拨 ERP 写路径打通(中间表 + TIPTOP WS)实施计划
|
||
|
||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||
|
||
**Goal:** 打通在途调拨写路径:按(组织×来源×路由)分组建单,经集成连接器新增 `database` 类型直写 ERP Oracle 中间表 `htt.gls_cm_file`,SOAP 触发 TIPTOP WS 同步建单,按六态分类落位。
|
||
|
||
**Architecture:** 外部建单的域契约永久固定(`CapabilityClient.create_transfer(票级参数) → TransferWriteResult 六态`),编排差异收敛到 `write_strategies.py` 策略注册表——一期唯一策略 `tiptop_stage_submit`(写中间表 → SOAP 触发建单,WS 同步返回即终态裁决,无回读);未来直连类系统=新增一个策略类,域上层零改动。两步各经 CapabilityGateway 独立绑定/审计;幂等靠「同一 gls_cm27 批次号 + stage 前 DELETE 同批次未处理行 + 票级在飞守卫」;执行粒度从按行升级为按票(`TransferDocument` 新表)。
|
||
|
||
**Tech Stack:** Flask + SQLAlchemy 2.0 + Alembic;`oracledb`(thin,先例 `voucher_check/erp_repository`);既有集成连接器框架(engine/binding/mapping/transports)。
|
||
|
||
**Spec:** 契约与决策记录见 `.engramory-memory/in-transit-transfer.md` §写路径 ERP 契约样例(2026-09-23)与本文档 §全局约束;ERP 报文样例以用户提供为准(本文 Task 12 固化为配置)。
|
||
|
||
## 全局约束(每个任务隐含遵守)
|
||
|
||
- fail-closed:任何契约/绑定/凭据缺失一律拒绝,禁止猜测默认值(`BindingNotFoundError` / `TransportNotFrozenError` 语义不变)。
|
||
- SQL 一律绑定变量(`:name`),禁止字符串拼值进 SQL 文本;表名/常量来自接口定义配置(管理端受控),不来自调用参数。
|
||
- **中间表 SQL 全文属于接口定义配置(管理端维护、发布门禁管控),后端代码零 SQL**:`OracleSqlTransport` 仅是通用 SQL 执行器,不得出现任何 `gls_cm`/调拨业务词汇(Task 2 有回归锁);改列/改常量/换组织 = 管理端改接口定义或绑定,零代码发布。
|
||
- **通用性锚点**:`create_transfer(票) → 六态` 是域永久契约,execution/retry/结果投影不感知外部系统差异;每个外部系统的建单步骤序列 = 一个编排策略类(代码注册,含裁决语义,**禁配置 DSL 编排**);未来多系统并存=新策略类 + 绑定 context_selector 路由(框架既有能力),策略选择配置键等第二系统接入时再加(YAGNI)。
|
||
- 改表结构必须配套 Alembic 迁移;迁移链 `down_revision` 一律先 `cd backend && flask db heads` 取当前 head 再写。
|
||
- 新增 error.code 同步四语言 `frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json`;新增界面文案同步四语言。
|
||
- 后端注释遵循 AGENTS.md §5(模块 docstring 三要素 + 函数 docstring Args/Returns + `[STEP n]`);测试含断言意图注释。
|
||
- **禁止自动 commit**:每个任务以 `git add <具体文件>` 结束,提交由用户批准。
|
||
- 六态写分类语义不变:success / duplicate_success / business_failed / technical_failed / timeout / result_unknown;`result_unknown` 仍为终态禁自动重试。
|
||
- 幂等纪律(本次冻结):**同一票(文档)生命周期内 `doc_no` 与 `batch_id`(gls_cm27)一经生成永不更换**;重写幂等 = stage 前 `DELETE 同批次且状态='10'` + 票级在飞守卫,**不配置状态回读**(`result_unknown` 走人工核实 SOP:在 ERP 按来源单号查单)。
|
||
- 域内禁止 `erp_*` 命名外部系统字段(沿用 `external_org` 等既有口径)。
|
||
|
||
## 命名对照表(执行者必读)
|
||
|
||
| 名字 | 出现层 | 含义 |
|
||
| --- | --- | --- |
|
||
| `stage_transfer_order` | 能力(代码注册) | 「调拨单暂存」——把票写入 ERP 中间表待处理(stage = staging table,中间表的行业叫法;2026-09-23 用户确认不改名) |
|
||
| `submit_transfer_order` | 能力(代码注册) | 「提交建单」——SOAP 调 TIPTOP WS,同步生成 ERP 调拨单 |
|
||
| `create_transfer` | 能力(代码注册) | 域编排门面声明 = 暂存 + 提交 两步的组合(CapabilityClient 方法同名) |
|
||
| `tiptop_stage_submit` | 编排策略(代码注册) | TIPTOP 专属建单序列:先 stage 写中间表、再 submit 触发 WS;未来其他外部系统 = 新策略类(如单接口直连 `direct_api`),域契约不变 |
|
||
| `htt_gls_cm_stage` / `htt_tiptop_submit` | 接口定义(管理端配置) | **编码仅为本文示例,管理员自定**:接口定义整行(编码、SQL/报文全文、含 schema 前缀的表名)都由管理员在界面自行创建,后端代码零引用接口编码;能力↔接口的配对走绑定(同样是管理端配置) |
|
||
| `doc_no` / `batch_id` | 域参数 | 来源单号(HTT-OR-…,gls_cm04)/ 批次幂等锚(gls_cm27);一票一生成终身复用 |
|
||
|
||
## 文件结构总览
|
||
|
||
```text
|
||
backend/
|
||
app/models/integration_connector.py # 改:CONNECTOR_TYPES + 'database'
|
||
app/models/in_transit_transfer.py # 改:TransferDocument 新表 + Item.document_id/unit + Attempt.document_id
|
||
app/api/integration_connector.py # 改:VALID_CONNECTOR_TYPES
|
||
app/services/integration_connector/
|
||
transports/oracle_sql.py # 新:Oracle SQL 传输(execute/query + probe)
|
||
gateway.py # 改:注册 database 传输
|
||
engine.py # 改:write 能力先响应映射再分类,data 恒带映射结果
|
||
app/services/in_transit_transfer/
|
||
capabilities.py # 改:能力契约重造(3 能力 + 能力名常量)
|
||
capability_client.py # 改:create_transfer 委派编排策略(六态裁决移入策略)
|
||
write_strategies.py # 新:建单编排策略注册表(每外部系统一个策略类)
|
||
document_id.py # 新:HTT-OR 单号 + gls_cm27 批次号生成
|
||
execution_service.py # 改:分组建单 + 票级执行 + 结果落位
|
||
movement_contract.py / file_parser.py / precheck_service.py # 改:unit 第 11 字段
|
||
migrations/versions/ # 新迁移 ×4(连接器类型 CHECK、单号序列、调拨表、unit 列)
|
||
tests/services/in_transit_transfer/... # 改/新
|
||
frontend/src/features/admin/modules/integration-connector/ # 改:database 类型表单 + 四语言
|
||
docs/features/in-transit-transfer/technical.md · docs/funclist.md # 改
|
||
```
|
||
|
||
---
|
||
|
||
### Task 1: `database` 连接器类型注册(模型 + 迁移 + API)
|
||
|
||
**Files:**
|
||
- Modify: `backend/app/models/integration_connector.py:35`(CONNECTOR_TYPES)
|
||
- Modify: `backend/app/api/integration_connector.py:48`(VALID_CONNECTOR_TYPES)
|
||
- Create: `backend/migrations/versions/tt7a8b9c0d1e_add_database_connector_type.py`
|
||
- Test: `backend/tests/services/integration_connector/test_database_connector_type.py`
|
||
|
||
**Interfaces:**
|
||
- Produces: `CONNECTOR_TYPES = ('rest', 'soap', 'database')`;API 校验放行 `database`;迁移把 `integration_client_instances` / `integration_interface_definitions` 两表 CHECK 约束同步为三值。
|
||
|
||
- [ ] **Step 1: 写失败测试**
|
||
|
||
```python
|
||
"""database 连接器类型:模型常量 / API 校验 / CHECK 约束三处一致(回归锁)。"""
|
||
from app.models.integration_connector import CONNECTOR_TYPES
|
||
|
||
|
||
def test_database_is_registered_connector_type():
|
||
# 断言:'database' 进入合法类型集,且模型与 API 白名单同源不漂移
|
||
assert 'database' in CONNECTOR_TYPES
|
||
from app.api.integration_connector import VALID_CONNECTOR_TYPES
|
||
assert set(VALID_CONNECTOR_TYPES) == set(CONNECTOR_TYPES)
|
||
```
|
||
|
||
- [ ] **Step 2: 运行确认失败** —— `cd backend && pytest -q tests/services/integration_connector/test_database_connector_type.py`,预期 FAIL(`'database' not in`)。
|
||
|
||
- [ ] **Step 3: 最小实现** —— 两处常量加 `'database'`;建迁移(先 `flask db heads` 取 head 作为 down_revision):
|
||
|
||
```python
|
||
"""add database connector type
|
||
|
||
Revision ID: tt7a8b9c0d1e
|
||
"""
|
||
from alembic import op
|
||
|
||
old = "('rest', 'soap')"
|
||
new = "('rest', 'soap', 'database')"
|
||
|
||
|
||
def upgrade() -> None:
|
||
# 两个约束同名分属两表,逐一重建(先删后建,SQLite 批量模式不适用——生产为 PG)
|
||
op.drop_constraint('ck_integration_client_instances_connector_type', 'integration_client_instances', type_='check')
|
||
op.create_check_constraint('ck_integration_client_instances_connector_type', 'integration_client_instances',
|
||
f"connector_type IN {new}")
|
||
op.drop_constraint('ck_integration_interface_definitions_connector_type', 'integration_interface_definitions', type_='check')
|
||
op.create_check_constraint('ck_integration_interface_definitions_connector_type', 'integration_interface_definitions',
|
||
f"connector_type IN {new}")
|
||
|
||
|
||
def downgrade() -> None:
|
||
# 回滚前置:database 实例/接口必须先人工清空,否则 CHECK 违约
|
||
op.drop_constraint('ck_integration_client_instances_connector_type', 'integration_client_instances', type_='check')
|
||
op.create_check_constraint('ck_integration_client_instances_connector_type', 'integration_client_instances',
|
||
f"connector_type IN {old}")
|
||
op.drop_constraint('ck_integration_interface_definitions_connector_type', 'integration_interface_definitions', type_='check')
|
||
op.create_check_constraint('ck_integration_interface_definitions_connector_type', 'integration_interface_definitions',
|
||
f"connector_type IN {old}")
|
||
```
|
||
|
||
注意:模型文件内 CheckConstraint 是 `f"connector_type IN ({', '.join(repr(s) for s in CONNECTOR_TYPES)})"` 动态生成,常量改后自动跟随,勿手改表达式。
|
||
|
||
- [ ] **Step 4: 运行测试通过** + `pytest -q tests/services/integration_connector tests/api/test_integration_connector_api.py`(存量全绿)。
|
||
|
||
- [ ] **Step 5: 落盘** —— `git add backend/app/models/integration_connector.py backend/app/api/integration_connector.py backend/migrations/versions/tt7a8b9c0d1e_add_database_connector_type.py backend/tests/services/integration_connector/test_database_connector_type.py`
|
||
|
||
---
|
||
|
||
### Task 2: Oracle SQL 传输层 `transports/oracle_sql.py`
|
||
|
||
**Files:**
|
||
- Create: `backend/app/services/integration_connector/transports/oracle_sql.py`
|
||
- Modify: `backend/app/services/integration_connector/gateway.py`(注册)
|
||
- Test: `backend/tests/services/integration_connector/test_oracle_sql_transport.py`
|
||
|
||
**Interfaces:**
|
||
- Produces: `OracleSqlTransport(connector_type='database')`,实现 `call(client, interface, request) -> dict` 与 `probe(client) -> dict`。
|
||
- request_spec_json 契约(`sql` 节点):
|
||
- 执行型:`{"sql": {"mode": "execute", "pre": ["DELETE ..."], "bulk": {"sql": "INSERT ...", "rows_param": "lines"}, "post": []}}`;bulk 行先与 `request['params']` 合并(行内同名键覆盖基础参数),`executemany` 一次提交。
|
||
- 查询型:`{"sql": {"mode": "query", "sql": "SELECT ..."}}`;列别名即输出键,返回 `{"status": "success", "rows": [{...}]}`。
|
||
- 客户端 config:`endpoint` 列 = Oracle 连接串(`host:port/service_name`),`timeout_seconds`,可选 `oracle_lib_dir`(thick 模式);凭据复用 `password` 类型(`credential_username`/`credential_password` → 组装为 `username`/`password`)。
|
||
|
||
- [ ] **Step 1: 写失败测试**(连接工厂注入替身,不连真库)
|
||
|
||
```python
|
||
"""Oracle SQL 传输:绑定变量执行 / bulk 合并 / query 返回行 / 失败脱敏(全部用假连接)。"""
|
||
from app.services.integration_connector.transports.oracle_sql import OracleSqlTransport
|
||
|
||
|
||
class FakeCursor:
|
||
def __init__(self, rows=None):
|
||
self.rows = rows or []
|
||
self.executed = []
|
||
|
||
def execute(self, sql, params=None):
|
||
self.executed.append(("execute", sql, params))
|
||
|
||
def executemany(self, sql, rows):
|
||
self.executed.append(("executemany", sql, rows))
|
||
|
||
@property
|
||
def rowcount(self):
|
||
return len(self.executed)
|
||
|
||
def __iter__(self):
|
||
return iter(self.rows)
|
||
|
||
|
||
class FakeConnection:
|
||
def __init__(self, rows=None):
|
||
self.cursor_obj = FakeCursor(rows)
|
||
self.committed = False
|
||
self.rolled_back = False
|
||
|
||
def cursor(self):
|
||
return self.cursor_obj
|
||
|
||
def commit(self):
|
||
self.committed = True
|
||
|
||
def rollback(self):
|
||
self.rolled_back = True
|
||
|
||
def close(self):
|
||
pass
|
||
|
||
|
||
def _client(credential=None):
|
||
return {"config_json": {"endpoint": "dbhost:1521/HTTPDB", "timeout_seconds": 30},
|
||
"credential": credential or {"username": "u", "password": "p"}}
|
||
|
||
|
||
def test_execute_runs_pre_bulk_post_and_commits():
|
||
conn = FakeConnection()
|
||
transport = OracleSqlTransport(connection_factory=lambda config, cred: conn)
|
||
raw = transport.call(
|
||
client=_client(),
|
||
interface={"request_spec_json": {"sql": {
|
||
"mode": "execute",
|
||
"pre": ["DELETE FROM htt.gls_cm_file WHERE gls_cm27 = :batch_id AND gls_cm29 = '10'"],
|
||
"bulk": {"sql": "INSERT INTO htt.gls_cm_file (gls_cm04) VALUES (:doc_no)", "rows_param": "lines"},
|
||
"post": [],
|
||
}}},
|
||
request={"params": {"batch_id": "B1", "doc_no": "D1", "lines": [{"doc_no": "D1", "material_no": "M1"}]}},
|
||
)
|
||
# 断言:bulk 行与基础参数合并(行内含 doc_no),DELETE→INSERT→commit 顺序执行
|
||
assert raw["status"] == "success"
|
||
kinds = [item[0] for item in conn.cursor_obj.executed]
|
||
assert kinds == ["execute", "executemany"]
|
||
assert conn.committed and conn.rolled_back is False
|
||
bulk_rows = conn.cursor_obj.executed[1][2]
|
||
assert bulk_rows[0]["batch_id"] == "B1" and bulk_rows[0]["material_no"] == "M1"
|
||
|
||
|
||
def test_query_returns_rows_as_dicts():
|
||
conn = FakeConnection(rows=[{"status_code": "30", "document_no": "1401-1"}])
|
||
transport = OracleSqlTransport(connection_factory=lambda config, cred: conn)
|
||
raw = transport.call(
|
||
client=_client(),
|
||
interface={"request_spec_json": {"sql": {"mode": "query", "sql": "SELECT gls_cm29 AS status_code FROM htt.gls_cm_file WHERE gls_cm04 = :doc_no"}}},
|
||
request={"params": {"doc_no": "D1"}},
|
||
)
|
||
# 断言:query 模式返回 rows 列表且不 commit(只读)
|
||
assert raw["status"] == "success"
|
||
assert raw["rows"][0]["document_no"] == "1401-1"
|
||
assert conn.committed is False
|
||
|
||
|
||
def test_db_error_is_masked_technical_failure():
|
||
class Boom(FakeConnection):
|
||
def cursor(self):
|
||
raise RuntimeError("ORA-01017 invalid username/password: u/p@dbhost")
|
||
|
||
transport = OracleSqlTransport(connection_factory=lambda config, cred: Boom())
|
||
raw = transport.call(client=_client(), interface={"request_spec_json": {"sql": {"mode": "execute", "pre": [], "post": []}}}, request={"params": {}})
|
||
# 断言:异常归 technical_failed,且凭据值被 *** 脱敏
|
||
assert raw["status"] == "technical_failed"
|
||
assert "u/p@dbhost" not in raw["message"] and "***" in raw["message"] or "u" != raw["message"]
|
||
|
||
|
||
def test_probe_selects_dual():
|
||
conn = FakeConnection(rows=[{"one": 1}])
|
||
transport = OracleSqlTransport(connection_factory=lambda config, cred: conn)
|
||
result = transport.probe(client=_client())
|
||
# 断言:probe 只证明可达(SELECT 1 FROM DUAL),不要求业务契约
|
||
assert result["ok"] is True
|
||
|
||
|
||
def test_missing_endpoint_fails_closed():
|
||
transport = OracleSqlTransport(connection_factory=lambda config, cred: FakeConnection())
|
||
client = {"config_json": {}, "credential": {}}
|
||
# 断言:无 endpoint 直接抛 TransportNotFrozenError(fail-closed)
|
||
import pytest
|
||
from app.services.integration_connector.errors import TransportNotFrozenError
|
||
with pytest.raises(TransportNotFrozenError):
|
||
transport.call(client=client, interface={"request_spec_json": {"sql": {"mode": "query", "sql": "SELECT 1 FROM DUAL"}}}, request={"params": {}})
|
||
|
||
|
||
def test_transport_is_business_agnostic():
|
||
import inspect
|
||
from app.services.integration_connector.transports import oracle_sql
|
||
|
||
source = inspect.getsource(oracle_sql)
|
||
# 断言:传输层零业务知识——不出现中间表列名/调拨词汇;SQL 全文属于接口定义配置,
|
||
# 这是"插入逻辑不写死、能力可配置"的代码级回归锁。
|
||
assert "gls_cm" not in source
|
||
assert "调拨" not in source and "C0089" not in source
|
||
```
|
||
|
||
- [ ] **Step 2: 运行确认失败** —— `pytest -q tests/services/integration_connector/test_oracle_sql_transport.py`,预期 FAIL(模块不存在)。
|
||
|
||
- [ ] **Step 3: 实现**(完整模块)
|
||
|
||
```python
|
||
"""services/integration_connector/transports/oracle_sql.py
|
||
|
||
用途:database(Oracle 直连)传输——按接口 SQL 规格执行绑定变量语句,覆盖
|
||
中间表写入(execute)与状态回读(query)两类接口。
|
||
依赖:oracledb(惰性 import)、errors.py、transports.base.mask_secrets。
|
||
逻辑:endpoint(DSN)或 SQL 规格缺失 → fail-closed;所有值经 :named 绑定变量,
|
||
禁止拼接;execute 按 pre→bulk→post 单事务提交,异常回滚并脱敏归
|
||
technical_failed;query 返回列别名为键的 rows,不 commit;
|
||
probe = SELECT 1 FROM DUAL(只证明可达)。连接工厂可注入供测试。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from typing import Any, Callable
|
||
|
||
from app.services.integration_connector.errors import TransportNotFrozenError
|
||
from app.services.integration_connector.transports.base import mask_secrets
|
||
|
||
ConnectionFactory = Callable[[dict, dict], Any]
|
||
|
||
|
||
def _default_connect(config: dict, credential: dict) -> Any:
|
||
"""按客户端配置建 Oracle 连接;凭据键取 credential_types password 形态组装值。"""
|
||
import oracledb
|
||
|
||
dsn = str(config.get('endpoint') or '').strip()
|
||
if not dsn:
|
||
raise TransportNotFrozenError('database contract not frozen (missing endpoint/DSN)')
|
||
lib_dir = str(config.get('oracle_lib_dir') or '').strip()
|
||
if lib_dir:
|
||
oracledb.init_oracle_client(lib_dir=lib_dir)
|
||
return oracledb.connect(
|
||
user=str(credential.get('username') or ''),
|
||
password=str(credential.get('password') or ''),
|
||
dsn=dsn,
|
||
)
|
||
|
||
|
||
class OracleSqlTransport:
|
||
"""Oracle SQL 传输;connection_factory 可注入以便单元测试(默认真连)。"""
|
||
|
||
connector_type = 'database'
|
||
|
||
def __init__(self, connection_factory: ConnectionFactory | None = None):
|
||
self._connection_factory = connection_factory or _default_connect
|
||
|
||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||
config = client.get('config_json') or {}
|
||
if not str(config.get('endpoint') or '').strip():
|
||
raise TransportNotFrozenError('database contract not frozen (missing endpoint/DSN)')
|
||
spec = (interface.get('request_spec_json') or {}).get('sql') or {}
|
||
if not spec:
|
||
raise TransportNotFrozenError('database contract not frozen (missing sql spec)')
|
||
params = dict(request.get('params') or {})
|
||
credential = client.get('credential') or {}
|
||
try:
|
||
connection = self._connection_factory(config, credential)
|
||
except TransportNotFrozenError:
|
||
raise
|
||
except Exception as exc: # noqa: BLE001 —— 连接失败(含驱动缺失)统一脱敏归技术失败
|
||
return self._failure('DB_CONNECT_FAILED', exc, credential)
|
||
try:
|
||
mode = str(spec.get('mode') or 'execute')
|
||
cursor = connection.cursor()
|
||
if mode == 'query':
|
||
cursor.execute(str(spec['sql']), params)
|
||
columns = [str(desc[0]).lower() for desc in cursor.description]
|
||
rows = [dict(zip(columns, row)) for row in cursor.fetchall()]
|
||
return {'status': 'success', 'rows': rows}
|
||
# [STEP 1] pre:清理同批次未处理行(幂等 DELETE)
|
||
for statement in spec.get('pre') or []:
|
||
cursor.execute(str(statement), params)
|
||
# [STEP 2] bulk:行参数与基础参数合并(行内同名键覆盖)后 executemany
|
||
bulk = spec.get('bulk')
|
||
if bulk:
|
||
base = {k: v for k, v in params.items() if not isinstance(v, (list, dict))}
|
||
rows = [dict(base, **row) for row in (params.get(str(bulk.get('rows_param')) or 'lines') or [])]
|
||
cursor.executemany(str(bulk['sql']), rows)
|
||
# [STEP 3] post + 单事务提交
|
||
for statement in spec.get('post') or []:
|
||
cursor.execute(str(statement), params)
|
||
connection.commit()
|
||
return {'status': 'success', 'rows_affected': int(getattr(cursor, 'rowcount', 0) or 0)}
|
||
except Exception as exc: # noqa: BLE001 —— 执行失败回滚 + 脱敏(错误文本可能回显绑定值)
|
||
try:
|
||
connection.rollback()
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
return self._failure('DB_EXECUTE_FAILED', exc, credential)
|
||
finally:
|
||
try:
|
||
connection.close()
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
|
||
def probe(self, *, client: dict) -> dict[str, Any]:
|
||
"""连接测试探针:SELECT 1 FROM DUAL,只证明网络/账号/服务可达。"""
|
||
config = client.get('config_json') or {}
|
||
credential = client.get('credential') or {}
|
||
try:
|
||
connection = self._connection_factory(config, credential)
|
||
except Exception as exc: # noqa: BLE001
|
||
return {'ok': False, 'code': 'CONNECTION_FAILED', 'message': mask_secrets(str(exc)[:500], credential)}
|
||
try:
|
||
cursor = connection.cursor()
|
||
cursor.execute('SELECT 1 FROM DUAL')
|
||
cursor.fetchall()
|
||
return {'ok': True, 'code': 'DB_OK', 'message': 'select dual ok'}
|
||
except Exception as exc: # noqa: BLE001
|
||
return {'ok': False, 'code': 'DB_ERROR', 'message': mask_secrets(str(exc)[:500], credential)}
|
||
finally:
|
||
try:
|
||
connection.close()
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
|
||
@staticmethod
|
||
def _failure(code: str, exc: Exception, credential: dict) -> dict[str, Any]:
|
||
return {
|
||
'status': 'technical_failed',
|
||
'code': code,
|
||
'message': mask_secrets(str(exc)[:500], credential),
|
||
}
|
||
```
|
||
|
||
gateway.py 注册(`get_capability_gateway`):
|
||
|
||
```python
|
||
from app.services.integration_connector.transports.oracle_sql import OracleSqlTransport
|
||
# ...
|
||
return CapabilityGateway(transports={'rest': RestTransport(), 'soap': SoapTransport(), 'database': OracleSqlTransport()})
|
||
```
|
||
|
||
- [ ] **Step 4: 运行通过** + 存量 connector 测试全绿。
|
||
- [ ] **Step 5: 落盘** —— `git add` 上述三个文件。
|
||
|
||
---
|
||
|
||
### Task 3: 引擎写能力「先响应映射再分类」
|
||
|
||
**Files:**
|
||
- Modify: `backend/app/services/integration_connector/engine.py:135-141`(call 内写分支)
|
||
- Test: `backend/tests/services/integration_connector/test_engine_write_mapping.py`
|
||
|
||
**Interfaces:**
|
||
- Produces: 写能力调用行为——①传输层已判失败(`RESULT_FAILURE_STATUSES`)短路不变;②否则先过 `response_mapping` 归一为 `{status, document_no, ...}` 再 `classify_transport_response`;③`result.data` **恒携带**映射后 dict(原实现仅成功态带 data,业务侧需要从 data 读 `code`/`message` 二次解释)。
|
||
- 兼容性:读能力路径零改动;未配置 response_mapping 的写接口(如 SQL 写入返回自带 status)行为不变。
|
||
|
||
- [ ] **Step 1: 写失败测试**
|
||
|
||
```python
|
||
"""引擎写能力:Tiptop 无 status 键的原始响应经映射归一后再分类;data 恒携带映射结果。"""
|
||
from app.services.integration_connector.capability import CapabilitySpec, register_capability, reset_capabilities
|
||
from app.services.integration_connector.engine import CapabilityGateway
|
||
|
||
|
||
class _FakeTransport:
|
||
connector_type = 'soap'
|
||
|
||
def call(self, *, client, interface, request):
|
||
# 模拟 TIPTOP Response 归一化形状:无 status 键,ERP 单号藏在 @name/@value 列表
|
||
return {"Response": {"Execution": {"Status": {"@code": "0", "@description": ""}},
|
||
"ResponseContent": {"Parameter": {"Record": {"Field": [
|
||
{"@name": "doc_no", "@value": "1401-2609230003"}]}}}}}
|
||
|
||
def probe(self, *, client):
|
||
return {"ok": True}
|
||
|
||
|
||
def test_write_capability_maps_response_before_classify(reset_capability_registry, app_ctx):
|
||
reset_capabilities()
|
||
register_capability(CapabilitySpec(name="t.write", input_schema={}, output_schema={}, idempotency="none", write=True))
|
||
gateway = CapabilityGateway(transports={"soap": _FakeTransport()})
|
||
result = gateway.call(
|
||
capability="t.write", context={}, params={},
|
||
operation_id="op-test", environment="prod", transports={"soap": _FakeTransport()},
|
||
# 绑定解析依赖 DB(app_ctx 夹具内 seed client/interface/binding,response_mapping 如下)
|
||
# response_mapping = {
|
||
# "status": {"expr": "Response.Execution.Status.@code", "transform": "enum-map", "args": {"mapping": {"0": "success"}}},
|
||
# "document_no": {"expr": "Response.ResponseContent.Parameter.Record.Field", "transform": "pick",
|
||
# "args": {"key_field": "@name", "key_value": "doc_no", "value_field": "@value"}},
|
||
# }
|
||
)
|
||
# 断言:code=0 经 enum-map 归一 success;document_no 经 pick 取出;data 恒带映射 dict
|
||
assert result.status == "success"
|
||
assert result.document_no == "1401-2609230003"
|
||
assert result.data["document_no"] == "1401-2609230003"
|
||
```
|
||
|
||
(夹具按既有 `test_binding` / connector API 测试的 seed 方式落 ClientInstance+InterfaceDefinition+Binding 三行,response_mapping 用注释中 JSON。)
|
||
|
||
- [ ] **Step 2: 运行确认失败** —— 现实现 raw 无 status → `technical_failed`。
|
||
- [ ] **Step 3: 实现** —— `engine.call` 中:
|
||
|
||
```python
|
||
if isinstance(raw, dict) and raw.get('status') in RESULT_FAILURE_STATUSES:
|
||
# 传输层已判失败(HTTP 4xx/5xx、SOAP Fault、非 XML、DB 异常)→ 原样分类,不做输出映射。
|
||
result = classify_transport_response(raw)
|
||
elif spec.write:
|
||
# [写能力] 先按响应映射归一为 {status, document_no, code, message}(如 Tiptop
|
||
# 状态码→六态),再走通用分类;data 恒携带映射结果供域层二次解释(如非 0 码→业务失败)。
|
||
mapped = raw
|
||
if snapshot.response_mapping:
|
||
mapped = map_response(snapshot.response_mapping, raw, snapshot.output_schema or spec.output_schema)
|
||
result = classify_transport_response(mapped if isinstance(mapped, dict) else {})
|
||
result = replace(result, data=mapped if isinstance(mapped, dict) else raw)
|
||
elif isinstance(raw, dict) and raw.get('status') in RESULT_FAILURE_STATUSES:
|
||
result = classify_transport_response(raw)
|
||
else:
|
||
result = IntegrationCallResult(status='success')
|
||
```
|
||
|
||
(原有 `if spec.write:` 直接 classify 的分支删除;成功态末尾的 data 映射对写能力跳过——`result.status in (...)` 分支对写能力保持原样即可,重复映射无害但浪费,加 `and not spec.write` 守卫。)
|
||
|
||
- [ ] **Step 4: 全绿** —— `pytest -q tests/services/integration_connector`。
|
||
- [ ] **Step 5: 落盘。**
|
||
|
||
---
|
||
|
||
### Task 4: 能力契约重造(`capabilities.py`)
|
||
|
||
**Files:**
|
||
- Modify: `backend/app/services/in_transit_transfer/capabilities.py`
|
||
- Test: `backend/tests/services/in_transit_transfer/test_capabilities_contract.py`(新)
|
||
|
||
**Interfaces:**
|
||
- Produces 三个能力(`register_transfer_capabilities` 幂等注册,组合根零改动):
|
||
- `in_transit_transfer.stage_transfer_order`(write, idempotency=batch):入参 = 票级 Schema(下),出参 = `_WRITE_OUTPUT_SCHEMA`。
|
||
- `in_transit_transfer.submit_transfer_order`(write, idempotency=batch):入参 `{external_org, doc_no, batch_id}`,出参 = `_WRITE_OUTPUT_SCHEMA`。
|
||
- `in_transit_transfer.create_transfer`(write, idempotency=batch):入参 = 票级 Schema(域编排门面声明,不经网关直调,仅作能力清单展示与契约文档)。
|
||
- 删除:`verify_duplicate` 能力声明与 `_QUERY_INPUT_SCHEMA` 占位(`create_transfer` 旧 Schema);重复票裁决依赖 WS 同步响应,不设回读能力(2026-09-23 用户拍板)。
|
||
|
||
- [ ] **Step 1: 写失败测试**
|
||
|
||
```python
|
||
"""能力契约:票级 Schema 必填字段与三能力注册(幂等重注册不报错)。"""
|
||
from app.services.in_transit_transfer.capabilities import register_transfer_capabilities
|
||
from app.services.integration_connector.capability import get_capability
|
||
|
||
|
||
def test_stage_capability_requires_doc_and_lines():
|
||
register_transfer_capabilities()
|
||
spec = get_capability("in_transit_transfer.stage_transfer_order")
|
||
# 断言:票级入参必备 单号/批次/组织/行数组;行必备 料号/仓/批号/数量/单位/行号
|
||
for field in ("external_org", "doc_no", "batch_id", "lines"):
|
||
assert field in spec.input_schema["required"]
|
||
line_required = spec.input_schema["properties"]["lines"]["items"]["required"]
|
||
assert set(line_required) >= {"line_no", "material_no", "from_warehouse", "to_warehouse", "lot_no", "quantity", "unit"}
|
||
|
||
|
||
def test_submit_capability_is_doc_ref_input():
|
||
register_transfer_capabilities()
|
||
spec = get_capability("in_transit_transfer.submit_transfer_order")
|
||
# 断言:WS 触发只带 单据引用三元组,且是写能力
|
||
assert set(spec.input_schema["required"]) == {"external_org", "doc_no", "batch_id"}
|
||
assert spec.write is True
|
||
```
|
||
|
||
票级 Schema(实现内容):
|
||
|
||
```python
|
||
_TRANSFER_LINE_SCHEMA: dict = {
|
||
"type": "object",
|
||
"required": ["line_no", "material_no", "from_warehouse", "to_warehouse", "lot_no", "quantity", "unit"],
|
||
"properties": {
|
||
"line_no": {"type": "string"},
|
||
"material_no": {"type": "string"},
|
||
"from_warehouse": {"type": "string"},
|
||
"to_warehouse": {"type": "string"},
|
||
"lot_no": {"type": "string"},
|
||
"quantity": {"type": "string"},
|
||
"unit": {"type": "string"},
|
||
},
|
||
}
|
||
_TICKET_INPUT_SCHEMA: dict = {
|
||
"type": "object",
|
||
"required": ["external_org", "doc_no", "batch_id", "doc_date", "posting_date", "lines"],
|
||
"properties": {
|
||
"external_org": {"type": "string"},
|
||
"doc_no": {"type": "string"},
|
||
"batch_id": {"type": "string"},
|
||
"doc_date": {"type": "string"}, # YYYY-MM-DD 制单日期
|
||
"posting_date": {"type": "string"}, # YYYY-MM-DD 过账日期
|
||
"lines": {"type": "array", "items": _TRANSFER_LINE_SCHEMA},
|
||
},
|
||
}
|
||
_DOC_REF_INPUT_SCHEMA: dict = {
|
||
"type": "object",
|
||
"required": ["external_org", "doc_no", "batch_id"],
|
||
"properties": {"external_org": {"type": "string"}, "doc_no": {"type": "string"}, "batch_id": {"type": "string"}},
|
||
}
|
||
```
|
||
|
||
- [ ] **Step 2: 失败 → Step 3: 实现**(按上表替换 `register_transfer_capabilities` 的四能力与 Schema 常量;`_QUERY_INPUT_SCHEMA` 保留给 query_inventory)。
|
||
- [ ] **Step 4: 全绿**(in_transit_transfer 存量 + 新测试)。
|
||
- [ ] **Step 5: 落盘。**
|
||
|
||
---
|
||
|
||
### Task 5: 单号与批次号生成器 `document_id.py`
|
||
|
||
**Files:**
|
||
- Create: `backend/app/services/in_transit_transfer/document_id.py`
|
||
- Create: `backend/migrations/versions/tt8b9c0d1e2f_add_transfer_doc_no_seq.py`
|
||
- Test: `backend/tests/services/in_transit_transfer/test_document_id.py`
|
||
|
||
**Interfaces:**
|
||
- Produces:
|
||
- `new_batch_id(now: datetime | None = None) -> str` —— 32 位 uuid4 hex + `yyyyMMddHHmmssSSS`(与 ERP 样例 `gls_cm27` 同构)。
|
||
- `next_document_no(external_org: str, *, now=None, sequence_loader: Callable[[], int] | None = None) -> str` —— `{org}-OR-{yyMMdd}{seq:05d}`(全局 PG 序列,超 99999 自然扩位)。
|
||
|
||
- [ ] **Step 1: 失败测试**
|
||
|
||
```python
|
||
"""单号/批次生成:格式契约 + 序列注入;批次号是票生命周期幂等锚(长度/字符集锁定)。"""
|
||
from app.services.in_transit_transfer.document_id import new_batch_id, next_document_no
|
||
|
||
|
||
def test_batch_id_format_matches_erp_sample():
|
||
from datetime import datetime
|
||
value = new_batch_id(datetime(2026, 9, 23, 9, 52, 8, 25000))
|
||
# 断言:32hex + 17 位时间戳(样例 ecd459a6...20260923095208025 同构)
|
||
assert len(value) == 49 and value[32:] == "20260923095208025"
|
||
assert all(c in "0123456789abcdef" for c in value[:32])
|
||
|
||
|
||
def test_document_no_format():
|
||
value = next_document_no("HTT", now=__import__("datetime").datetime(2026, 9, 23), sequence_loader=lambda: 5)
|
||
# 断言:组织-OR-年月日+5位流水(样例 HTT-OR-260923000005 同构)
|
||
assert value == "HTT-OR-260923000005"
|
||
|
||
|
||
def test_document_no_sequence_over_99999_expands():
|
||
value = next_document_no("HTT", sequence_loader=lambda: 100000)
|
||
# 断言:超五位自然扩位不截断(唯一性优先于格式定长)
|
||
assert value == "HTT-OR-260923100000"
|
||
```
|
||
|
||
- [ ] **Step 2: 失败 → Step 3: 实现**
|
||
|
||
```python
|
||
"""services/in_transit_transfer/document_id.py
|
||
|
||
用途:ERP 建单的两个幂等锚生成——来源单号(gls_cm04,{org}-OR-yyMMdd+全局序列)
|
||
与批次号(gls_cm27,uuid+毫秒时间戳)。
|
||
依赖:app.db(PG 序列 nextval,可注入替身)。
|
||
逻辑:批次号与单号在票(TransferDocument)创建时生成一次、终身复用;重试/重执行
|
||
禁止重新生成(否则中间表残留未处理行会被 ERP 侧捡走造成双单)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import uuid
|
||
from datetime import datetime
|
||
from typing import Callable
|
||
|
||
DOC_NO_SEQUENCE = 'transfer_doc_no_seq'
|
||
|
||
|
||
def new_batch_id(now: datetime | None = None) -> str:
|
||
"""批次幂等锚:uuid4 hex(32) + yyyyMMddHHmmssSSS(与样例 gls_cm27 同构)。"""
|
||
moment = now or datetime.utcnow()
|
||
return f"{uuid.uuid4().hex}{moment.strftime('%Y%m%d%H%M%S%f')[:17]}"
|
||
|
||
|
||
def next_document_no(external_org: str, *, now: datetime | None = None,
|
||
sequence_loader: Callable[[], int] | None = None) -> str:
|
||
"""来源单号:{org}-OR-{yyMMdd}{seq:05d};序列全局递增免按日重置的并发计数表。"""
|
||
loader = sequence_loader or _next_sequence_value
|
||
date_part = (now or datetime.utcnow()).strftime('%y%m%d')
|
||
return f"{external_org}-OR-{date_part}{int(loader()):05d}"
|
||
|
||
|
||
def _next_sequence_value() -> int:
|
||
from sqlalchemy import text
|
||
from app import db
|
||
|
||
return int(db.session.execute(text(f'SELECT nextval(:seq)'), {'seq': DOC_NO_SEQUENCE}).scalar_one())
|
||
```
|
||
|
||
迁移(head 先查):
|
||
|
||
```python
|
||
"""add transfer_doc_no_seq
|
||
|
||
Revision ID: tt8b9c0d1e2f
|
||
"""
|
||
from alembic import op
|
||
|
||
SEQ = op.create_table # noqa: F841 —— 占位勿用;实际用原生 SQL(PG 方言)
|
||
|
||
|
||
def upgrade() -> None:
|
||
op.execute("CREATE SEQUENCE IF NOT EXISTS transfer_doc_no_seq START WITH 1 INCREMENT BY 1")
|
||
|
||
|
||
def downgrade() -> None:
|
||
op.execute("DROP SEQUENCE IF EXISTS transfer_doc_no_seq")
|
||
```
|
||
|
||
(删掉 `SEQ = ...` 占位行——写文件时不要它;`nextval` 用 `text('SELECT nextval(\'transfer_doc_no_seq\')')` 直拼常量即可,序列名是代码常量非用户输入。)
|
||
|
||
- [ ] **Step 4: 全绿 → Step 5: 落盘。**
|
||
|
||
---
|
||
|
||
### Task 6: 交易单位(movement 契约第 11 字段)
|
||
|
||
**Files:**
|
||
- Modify: `backend/app/services/in_transit_transfer/movement_contract.py`(MOVEMENT_FIELDS)
|
||
- Modify: `backend/app/services/in_transit_transfer/file_parser.py`(parse_movement_rows 透传 unit)
|
||
- Modify: `backend/app/services/in_transit_transfer/precheck_service.py`(建 Item 时落 unit;缺失 → 行级 blocked)
|
||
- Modify: `backend/app/models/in_transit_transfer.py`(TransferInvoiceItem 加 `unit` 列)
|
||
- Create: `backend/migrations/versions/tt9c0d1e2f3a_add_transfer_invoice_items_unit.py`
|
||
- Test: `backend/tests/services/in_transit_transfer/test_unit_field.py`(新)+ 存量 movement 测试
|
||
|
||
**Interfaces:**
|
||
- Produces: `MOVEMENT_FIELDS` 含 `unit`;`TransferInvoiceItem.unit: Mapped[str]`(String(16),NOT NULL,server_default '')。
|
||
- 语义:解析规则(movement profile)的 `field_mapping` 必须映射 unit 列;文件缺列/行值为空 → 该行预检落 `missing_unit` 行级 blocked(**不做**文件级 ReceiptFileSchemaError——单位缺失不该废掉整份收料文件,与 doc_no 缺失的文件级语义不同,此差异写入 movement_contract 注释)。
|
||
|
||
- [ ] **Step 1: 失败测试**(三断言:契约含 unit;解析行带 unit 原值;空 unit 行 → 预检 blocked 且 reason=missing_unit,同文件其余行不受影响)
|
||
- [ ] **Step 2: 失败 → Step 3: 实现**(按 Interfaces;迁移加列;`recompute_precheck_hash` 的 items 快照**不加** unit——Hash 口径不变,避免存量预检 409)。
|
||
- [ ] **Step 4: 全绿(含存量 test_movement_file_repository / test_precheck_service)→ Step 5: 落盘。**
|
||
|
||
---
|
||
|
||
### Task 7: `TransferDocument` 票模型 + 迁移
|
||
|
||
**Files:**
|
||
- Modify: `backend/app/models/in_transit_transfer.py`(新模型 + 常量 + Item/Attempt 外键)
|
||
- Create: `backend/migrations/versions/tt0d1e2f3a4b_add_transfer_documents.py`
|
||
- Test: `backend/tests/services/in_transit_transfer/test_document_model.py`(新,含迁移链测试更新 `test_migration_revision.py`)
|
||
|
||
**Interfaces:**
|
||
- Produces:
|
||
|
||
```python
|
||
TRANSFER_DOCUMENT_STATUSES = (
|
||
'executing', 'success', 'duplicate_success', 'business_failed',
|
||
'technical_failed', 'result_unknown', 'cancelled',
|
||
)
|
||
|
||
|
||
class TransferDocument(Base):
|
||
"""一张 ERP 调拨单(票)的真相源:组织×来源×在途仓→HUB路由 分组 = 一票。
|
||
|
||
doc_no / batch_id 创建时生成一次终身复用(重试幂等锚);lines_json 冻结
|
||
聚合行快照,保证重写与首写报文一致。
|
||
"""
|
||
|
||
__tablename__ = 'transfer_documents'
|
||
__table_args__ = (
|
||
UniqueConstraint('doc_no', name='uq_transfer_documents_doc_no'),
|
||
UniqueConstraint('batch_id', name='uq_transfer_documents_batch_id'),
|
||
CheckConstraint(
|
||
f"status IN ({', '.join(repr(s) for s in TRANSFER_DOCUMENT_STATUSES)})",
|
||
name='ck_transfer_documents_status',
|
||
),
|
||
Index('ix_transfer_documents_run_status', 'run_id', 'status'),
|
||
Index('ix_transfer_documents_erp_no', 'erp_document_no'),
|
||
)
|
||
|
||
id: Mapped[int] = mapped_column(primary_key=True)
|
||
run_id: Mapped[int] = mapped_column(ForeignKey('transfer_runs.id'), nullable=False, index=True)
|
||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
external_org: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
doc_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
batch_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='executing')
|
||
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||
erp_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||
lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
|
||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||
updated_at: Mapped[datetime] = mapped_column(
|
||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||
)
|
||
|
||
items: Mapped[list['TransferInvoiceItem']] = relationship(back_populates='document')
|
||
```
|
||
|
||
- `TransferInvoiceItem` 加 `document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_documents.id'), nullable=True)` + `document` relationship(不 delete-orphan)。
|
||
- `TransferAttempt` 加 `document_id: Mapped[Optional[int]]`(nullable,`item_id` 保持——重查 Attempt 仍挂 item,写 Attempt 挂 document)。
|
||
|
||
- [ ] **Step 1: 失败测试**(唯一约束 / 状态 CHECK / Item.document 关系 / 迁移链 head 推进)。
|
||
- [ ] **Step 2: 失败 → Step 3: 实现 + 迁移**(create_table transfer_documents + add columns;downgrade 反向 drop)。
|
||
- [ ] **Step 4: 全绿 → Step 5: 落盘。**
|
||
|
||
---
|
||
|
||
### Task 8: `CapabilityClient` 两步编排
|
||
|
||
**Files:**
|
||
- Modify: `backend/app/services/in_transit_transfer/capability_client.py`
|
||
- Test: `backend/tests/services/in_transit_transfer/test_capability_client_write.py`(新)
|
||
|
||
**Interfaces:**
|
||
- 新常量:`STAGE_CAPABILITY = "in_transit_transfer.stage_transfer_order"`、`SUBMIT_CAPABILITY = "in_transit_transfer.submit_transfer_order"`。
|
||
- 改造 `create_transfer`(签名换票级参数):
|
||
|
||
```python
|
||
def create_transfer(
|
||
self,
|
||
*,
|
||
operation_id: str,
|
||
external_org: str,
|
||
doc_no: str,
|
||
batch_id: str,
|
||
doc_date: str,
|
||
posting_date: str,
|
||
from_warehouse: str,
|
||
to_warehouse: str,
|
||
lines: list[dict],
|
||
) -> TransferWriteResult:
|
||
```
|
||
|
||
编排(`[STEP]` 注释齐全,网关替身注入测试):
|
||
|
||
```python
|
||
# [STEP 1] 写中间表:pre 的同批次 DELETE 保证重插幂等;失败(含超时)即技术失败——
|
||
# 本地 Oracle 落库超时后行可能已插入,但重执行会用同一批次 DELETE 清理后重写,无重复风险。
|
||
stage = self._gateway().call(capability=STAGE_CAPABILITY, context={}, params={
|
||
"external_org": external_org, "doc_no": doc_no, "batch_id": batch_id,
|
||
"doc_date": doc_date, "posting_date": posting_date, "lines": lines,
|
||
}, operation_id=operation_id)
|
||
if stage.status != 'success':
|
||
return TransferWriteResult(
|
||
status='technical_failed',
|
||
error_code=stage.error_code or 'EXTERNAL_STAGE_FAILED',
|
||
error_message=stage.error_message or '',
|
||
)
|
||
# [STEP 2] 触发 TIPTOP WS 同步建单;响应即终态裁决(用户拍板:不设状态回读)
|
||
submit = self._gateway().call(capability=SUBMIT_CAPABILITY, context={}, params={
|
||
"external_org": external_org, "doc_no": doc_no, "batch_id": batch_id,
|
||
}, operation_id=operation_id)
|
||
return self._classify_submit_result(submit)
|
||
```
|
||
|
||
`_classify_submit_result`(Tiptop 语义收口在域层):
|
||
|
||
```python
|
||
def _classify_submit_result(self, result) -> TransferWriteResult:
|
||
if result.status == 'success':
|
||
return TransferWriteResult(status='success', document_no=result.document_no)
|
||
if result.status == 'business_failed':
|
||
return TransferWriteResult(status='business_failed', error_code=result.error_code, error_message=result.error_message)
|
||
if result.status == 'timeout':
|
||
# 响应丢失且不回读:终态 result_unknown(禁自动重试);人工核实 SOP =
|
||
# 在 ERP 按来源单号查单:有单 → 人工关闭并备注单号;无单 → 恢复处理重建预检。
|
||
return TransferWriteResult(status='result_unknown', error_code='EXTERNAL_TIMEOUT_UNKNOWN')
|
||
# 技术失败可能携带 Tiptop 非 0 状态码:映射后的 data 里 code≠'0' → 业务失败(重试无效)
|
||
data = result.data if isinstance(result.data, dict) else {}
|
||
code = str(data.get('code') or '')
|
||
if data.get('status') not in (None, '', 'success') and code not in ('', '0'):
|
||
return TransferWriteResult(status='business_failed', error_code=code, error_message=str(data.get('message') or ''))
|
||
return TransferWriteResult(status='technical_failed', error_code=result.error_code or 'EXTERNAL_UNKNOWN_RESPONSE', error_message=result.error_message or '')
|
||
```
|
||
|
||
- 删除:`verify_duplicate` 方法(无调用方,重复票由人工核实 SOP 承担);`write_transport` 注入点与 `ExternalNotFrozenError` 的「未注入即抛」逻辑(绑定缺失由网关 `BindingNotFoundError` 承担,票级异常隔离承接);`ExternalWriteTimeoutError` 类删除(超时裁决内化)。
|
||
|
||
- [ ] **Step 1: 失败测试**(替身网关按 capability 名分发脚本化响应,逐分支断言:stage 失败→技术失败 / stage 超时→技术失败 / submit 成功→success+单号 / 业务失败→business_failed / 超时→result_unknown / 技术失败带 Tiptop 非 0 码→business_failed)。
|
||
- [ ] **Step 2: 失败 → Step 3: 实现 → Step 4: 全绿(存量 write 相关用例同步改写)→ Step 5: 落盘。**
|
||
|
||
---
|
||
|
||
### Task 9: 执行粒度重构(按票建单)
|
||
|
||
**Files:**
|
||
- Modify: `backend/app/services/in_transit_transfer/execution_service.py`(核心重构)
|
||
- Modify: `backend/app/services/in_transit_transfer/orchestrator.py`(finalize_run 口径不变,核对)
|
||
- Modify: `backend/app/services/in_transit_transfer/execution_service.execute_item`(worker 兼容入口:委托票执行)
|
||
- Test: `backend/tests/services/in_transit_transfer/test_execution_documents.py`(新)+ 存量 `test_execution_service` 改写
|
||
|
||
**Interfaces:**
|
||
- Produces:
|
||
|
||
```python
|
||
@dataclass(frozen=True)
|
||
class DocumentPlan:
|
||
"""一次执行内的一票分组:组织×来源×在途仓→HUB 路由。"""
|
||
source_code: str
|
||
external_org: str
|
||
from_warehouse: str
|
||
to_warehouse: str
|
||
items: list[TransferInvoiceItem]
|
||
lines: list[dict]
|
||
```
|
||
|
||
- `execute_precheck`:`selected` 确定后改走 `_plan_documents(selected, deps=deps)` → 逐票 `_execute_document(plan, ...)`;票间失败隔离(票异常 → 票内全部行 blocked_recoverable,其余票继续,与现行项级隔离同语义)。
|
||
- `_plan_documents`:复用 `_write_item` 既有写前路由复查(route 变化 → 行 blocked `precheck_expired`,路由一致才入组);组内 `_aggregate_lines`:
|
||
|
||
```python
|
||
def _aggregate_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
||
"""组内按(料号+批号)聚合数量,行号 1 起顺序编;数量 6 位小数字符串(样例口径)。"""
|
||
merged: dict[tuple[str, str], dict] = {}
|
||
for item in items:
|
||
key = (item.material_no, item.lot_no or '')
|
||
row = merged.setdefault(key, {
|
||
"material_no": item.material_no, "lot_no": item.lot_no or "",
|
||
"from_warehouse": item.from_warehouse, "to_warehouse": item.to_warehouse,
|
||
"unit": getattr(item, 'unit', '') or '',
|
||
"quantity": Decimal("0"),
|
||
})
|
||
row["quantity"] += Decimal(item.receipt_quantity)
|
||
return [
|
||
{"line_no": str(index + 1), **{k: v for k, v in row.items() if k != "quantity"},
|
||
"quantity": f"{row['quantity']:.6f}"}
|
||
for index, row in enumerate(merged.values())
|
||
]
|
||
```
|
||
|
||
- `_ensure_document(plan, run)`:同 run 同分组键已有 `executing` 文档则复用(**doc_no/batch_id 终身复用**);否则生成(Task 5)+ `lines_json` 冻结 + 行落 `document_id`。
|
||
- 票级在飞守卫(worker 重入队防双写):`UPDATE transfer_documents SET attempt_no = attempt_no + 1 WHERE id = :id AND status = 'executing'` 影响行数为 0 → 说明已有在飞执行,跳过。
|
||
- `_apply_document_result(doc, items, attempt, result)`:Attempt(kind='external_write',挂 document_id)+ 按 Task 8 六态落位——success/duplicate_success → doc 与票内全部行 success/external_document_no=erp 单号;business_failed/technical_failed → doc 同态 + 行 blocked_recoverable(result_message 透出);result_unknown → doc result_unknown + 行 result_unknown(终态)。
|
||
- `execute_item(item_id)` 改为:定位 item.document → 无 document(执行前异常行)保持旧行为报错 → 有则走 `_execute_document`(票级守卫防重复提交)。
|
||
|
||
- [ ] **Step 1: 失败测试**(核心场景全要):①两来源同路由 → 两票、各一单号;②同票跨 Invoice 同料号同批号 → 聚合一行数量相加;③一票成功 → 票内全部行 success + erp 单号一致;④票级异常 → 该票行 blocked、其他票继续;⑤worker 重入队同票 → 第二次跳过(守卫);⑥路由漂移行照旧 blocked 不入组。
|
||
- [ ] **Step 2: 失败 → Step 3: 实现 → Step 4: 全绿(存量 test_execution_service 的按行断言改写为按票)→ Step 5: 落盘。**
|
||
|
||
---
|
||
|
||
### Task 10: 结果投影与 API 冒烟
|
||
|
||
**Files:**
|
||
- Modify: `backend/app/services/in_transit_transfer/execution_service.py`(`_build_run_result`)
|
||
- Test: `backend/tests/api/test_in_transit_transfer_api.py`(追加冒烟)
|
||
|
||
**Interfaces:**
|
||
- `_build_run_result`:`external_documents` 改由 `run.documents`(票)投影——`document_no=erp_document_no`、`lines` 由 `lines_json` 展开(含 invoice_no 归属可由 items 反查填充);items 的 `external_document_no` 已随票落位,`aggregate_external_documents` 兜底逻辑保留(历史数据无票时仍可按行聚合)。`exceptions` 口径不变。
|
||
- API 冒烟:执行 → run 查询返回按票聚合的单据列表(新断言);`result_unknown` 票的行仍只读。
|
||
|
||
- [ ] **Step 1: 失败测试 → Step 2: 失败 → Step 3: 实现 → Step 4: API 全绿 → Step 5: 落盘。**
|
||
|
||
---
|
||
|
||
### Task 11: 管理端 `database` 类型适配(前端 + 四语言)
|
||
|
||
**Files:**
|
||
- Modify: `frontend/src/features/admin/modules/integration-connector/types/integration-connector.types.ts`
|
||
- Modify: `frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.vue`
|
||
- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/admin.json`(仅 connectorType/placeholder 相关键,**禁整文件重写**,块级/行级替换)
|
||
- Test: `frontend/src/features/admin/modules/integration-connector/components/IntegrationConnectorFormDrawer.spec.ts`(追加)
|
||
|
||
**Interfaces:**
|
||
- 连接器类型下拉加 `database`(label:简中「数据库(Oracle 直连)」/繁中/英/泰)。
|
||
- 客户端表单:database 类型 endpoint label=「数据库连接串(host:port/service_name)」;超时字段照显(通用字段不因类型隐藏);不显示 REST 的 HTTP 方法/请求路径。
|
||
- 高级配置 JSON 折叠区保留(`oracle_lib_dir` 走 config_json)。
|
||
|
||
- [ ] **Step 1: 失败 vitest 用例**(选 database → endpoint label 文案 + 无 method/path 输入框)。
|
||
- [ ] **Step 2: 失败 → Step 3: 实现(含四语言)→ Step 4: `npm run test:unit -- src/features/admin/modules/integration-connector && npm run build` 全绿 → Step 5: 落盘。**
|
||
|
||
---
|
||
|
||
### Task 12: 接口定义/绑定配置固化(写入 technical.md)
|
||
|
||
**Files:**
|
||
- Modify: `docs/features/in-transit-transfer/technical.md`(§10 新节「ERP 建单连接器配置」,内容如下全文)
|
||
|
||
**内容(配置产物全文,上线时经管理端录入;下述 `htt_*` 编码仅为本文行文示例——接口定义的编码、SQL/报文全文、含 schema 前缀的表名全部由管理员在界面自行创建和维护,后端代码不出现任何接口编码或表名):**
|
||
|
||
客户端实例(编码同样管理员自定):`connector_type=database`,`endpoint=<ERP Oracle 连接串>`,凭据引用(password 类型,db 模式录 ERP 账号)。
|
||
|
||
接口定义①(写中间表,编码示例 `htt_gls_cm_stage`):
|
||
```json
|
||
{
|
||
"input_schema_json": {"type": "object", "required": ["external_org", "doc_no", "batch_id", "doc_date", "posting_date", "lines"], "properties": {}},
|
||
"request_spec_json": {"sql": {"mode": "execute",
|
||
"pre": ["DELETE FROM htt.gls_cm_file WHERE gls_cm27 = :batch_id AND gls_cm29 = '10'"],
|
||
"bulk": {"rows_param": "lines", "sql": "INSERT INTO htt.gls_cm_file (gls_cm01, gls_cm02, gls_cm03, gls_cm04, gls_cm05, gls_cm06, gls_cm07, gls_cm08, gls_cm09, gls_cm10, gls_cm11, gls_cm12, gls_cm13, gls_cm14, gls_cm15, gls_cm16, gls_cm17, gls_cm18, gls_cm19, gls_cm20, gls_cm21, gls_cm22, gls_cm23, gls_cm24, gls_cm25, gls_cm26, gls_cm27, gls_cm28, gls_cm29, gls_cm30, gls_cm31, gls_cm32, gls_cm33, gls_cm34, gls_cm35, gls_cm36, gls_cm37, gls_cm38, gls_cm39, gls_cm40, gls_cm41, gls_cm42, gls_cm43, gls_cm44, gls_cm45, gls_cm46, gls_cm47, gls_cm48, gls_cm49, gls_cm50, gls_cm51, gls_cm52, gls_cm53, gls_cm54, gls_cm55, gls_cm56, gls_cm57, gls_cm58, gls_cm59, gls_cm60, gls_cm61, gls_cm62, gls_cm63, gls_cm64, gls_cm65, gls_cm66, gls_cm75, gls_cm76, gls_cm77, gls_cm78) VALUES (sys_guid(), :external_org, :external_org, :doc_no, :line_no, TO_DATE(:doc_date, 'YYYY-MM-DD'), :maker_account, :maker_account, 'C0089', '无源调拨出', :doc_no, :line_no, :material_no, :to_warehouse, :from_warehouse, ' ', ' ', :lot_no, :quantity, :unit, '', '', '', '', '', '', :batch_id, '23', '10', '', '', '', '', '0.000000', '', '', '0.000000', '', '', '0', '', '', '0', '0', '0', '0', '0', '', '', TO_DATE(:posting_date, 'YYYY-MM-DD'), '', '', '', '', '', '', '', '', '', '', '', '', '', 5, 0, '', '', '', '')"},
|
||
"post": []}}
|
||
}
|
||
```
|
||
(`maker_account`、来源类别 C0089 等常量由绑定 param_mapping 常量注入;入库/出库仓方向按样例:gls_cm14=拨入HUB=to_warehouse、gls_cm15=拨出在途仓=from_warehouse——联调首日与 ERP 核对一次方向。)
|
||
|
||
接口定义②(WS 触发,SOAP,编码示例 `htt_tiptop_submit`):
|
||
```json
|
||
{
|
||
"request_spec_json": {"method": "POST", "soap": {"action": "", "body_template": "<Request><Access><Authentication user=\"{credential_username}\" password=\"{credential_password}\" /><Connection application=\"APP\" source=\"{source_ip}\" /><Appdevice appid=\"\" appmodule=\"C0089\" timestamp=\"{batch_id}\"/><Organization name=\"{external_org}\" /><Locale language=\"zh_CN\" /></Access><RequestContent><Parameter></Parameter><Document><RecordSet id=\"1\"><Master name=\"Master\"><Record><Field name=\"doc_type_no\" value=\"1401\"/><Field name=\"doc_no\" value=\"{doc_no}\"/><Field name=\"docNo\" value=\"{doc_no}\"/></Record></Master><Detail name=\"Detail\"></Detail></RecordSet></Document></RequestContent></Request>"}},
|
||
"response_mapping_json": {
|
||
"status": {"expr": "Response.Execution.Status.@code", "transform": "enum-map", "args": {"mapping": {"0": "success"}}},
|
||
"code": {"expr": "Response.Execution.Status.@code"},
|
||
"message": {"expr": "Response.Execution.Status.@description"},
|
||
"document_no": {"expr": "Response.ResponseContent.Parameter.Record.Field", "transform": "pick", "args": {"key_field": "@name", "key_value": "doc_no", "value_field": "@value"}}
|
||
}
|
||
}
|
||
```
|
||
|
||
两个绑定(默认 context 空 selector,param_mapping 示例——写中间表绑定):
|
||
```json
|
||
{
|
||
"maker_account": {"expr": "external_org", "transform": "template", "args": {"template": "15070211"}},
|
||
"source_ip": {"expr": "external_org", "transform": "template", "args": {"template": "0.0.0.0"}}
|
||
}
|
||
```
|
||
(常量值上线前由业务确认;`template` 渲染无占位符文本即字面常量;映射引擎参数形态以 `mapping.py:224` `fill_param_template` 为准,录入前先直调验证端点冒烟。)
|
||
|
||
- [ ] **Step 1: 文档落盘(本任务只改文档)→ Step 2: `git add`。**
|
||
- 联调期运维顺序(写进文档):凭据 → 客户端实例 → 两接口定义 → 两绑定发布 → `POST /api/integration-connector/capabilities/...` 直调验证 stage(database)与 submit(SOAP,ERP 沙箱组织)。
|
||
|
||
---
|
||
|
||
### Task 13: 文档同步与全量回归
|
||
|
||
**Files:**
|
||
- Modify: `docs/features/in-transit-transfer/technical.md`(§1 唯一出口补 database 类型与三步能力;§3 无新增 env,删「写路径 fail-closed」过期表述;§9 验收清单补三步契约/双单防护场景)
|
||
- Modify: `docs/funclist.md`(调拨段:ERP 建单(中间表+WS)能力行)
|
||
- Modify: `docs/demand.md`(如执行粒度描述涉及,则同步「按组织×来源×路由一票一单」)
|
||
|
||
- [ ] **Step 1: 全量回归**:
|
||
```bash
|
||
cd backend && pytest -q tests/services/in_transit_transfer tests/services/integration_connector tests/api/test_in_transit_transfer_api.py tests/api/test_integration_connector_api.py tests/workers/test_in_transit_transfer_worker.py
|
||
cd ../frontend && npm run test:unit -- src/features/chat src/features/admin/modules/integration-connector && npm run build
|
||
```
|
||
- [ ] **Step 2: 文档更新落盘 → `git add`。**
|
||
- [ ] **Step 3: 交付说明**(提交说明模板):列出迁移链 4 个新 revision、上线配置五步、方案前提与残余确认(均一句话问 ERP,不阻塞代码):①ERP 侧除 WS 外**没有**定时批处理自动消费 '10' 行(本方案幂等的前提;若存在,超时票恢复处理前必须先人工核实 ERP 无此单,防双单);②失败行 gls_cm29 终值(现仅认 '30' 为成功);③HTT-OR 单号是否强校验每日从 000001(现用全局 PG 序列)。另在 §9 补 result_unknown 人工核实 SOP:在 ERP 按来源单号查单——有单 → 人工关闭并备注单号;无单 → 恢复处理重建预检(超时票残留的 '10' 行在前提①下为无害垃圾)。
|
||
|
||
---
|
||
|
||
## Self-Review 记录
|
||
|
||
- 规格覆盖:两步契约(T2/T4/T8/T12)、分组建单(T7/T9)、幂等双单防护(T5/T8/T9 批次复用+stage DELETE+票级守卫)、unit 契约(T6)、管理端与配置(T11/T12)、文档(T13)——决策点 1–6 全部落任务。
|
||
- 类型一致性:`TransferWriteResult` 六态复用不变;`DocumentPlan.lines` 键集与能力 Schema `_TRANSFER_LINE_SCHEMA` 一致;`new_batch_id`/`next_document_no` 在 T5 定义、T9 消费。
|
||
- 已知风险前置:Task 3 的绑定 seed 夹具复用既有 connector 测试基建;Task 9 存量按行用例需成批改写(工作量最大项,先写新测试再动实现)。
|