Merge branch 'hugo-shipping-notice' into test
This commit is contained in:
commit
e35f01bbe9
163 files changed
+21008
-2545
No files matched your search
@@ -58,7 +58,8 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
||||
deps=deps,
|
||||
)
|
||||
# 执行不再绑定匹配确认:按匹配 scope 圈 ready 行委托 execute_items
|
||||
# (三层门禁:可执行/行级新鲜度/文件版本对账);无可执行行时门禁抛错,
|
||||
# (两道门禁:可执行/文件版本对账;TTL 新鲜度门禁 2026-09-25 退役);
|
||||
# 无可执行行时门禁抛错,
|
||||
# 与旧流程一致记入 errors 不阻断通知阶段。
|
||||
executed = execute_matching_items(matching_id=summary.matching_id, deps=deps)
|
||||
outcome.run_no = executed.run_no
|
||||
|
||||
@@ -7,6 +7,12 @@
|
||||
版本化;应用组合根(app/__init__.py)在每次 create_app 时调用
|
||||
register_transfer_capabilities()(幂等),保证管理端「能力清单」冷启动即可见,
|
||||
测试 reset 注册表后也能重建。
|
||||
D13 能力收缩:清单只登记真实业务语义,恰两个能力——
|
||||
query_inventory(读,按组织批量查库存)与 create_transfer(写,单据级原子建单/
|
||||
审核/过账,幂等键语义 batch);原 stage/submit 合成能力取消,其接口定义保留为
|
||||
create_transfer 绑定的两个步骤(管理端绑定配置,不属本代码);verify_duplicate
|
||||
注册占位已随 T9 客户端重建一并移除(D6 无回读:不存在 verify 能力,客户端
|
||||
verify_duplicate 方法同步删除,绑定缺失由网关承担)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,57 +23,106 @@ from app.services.integration_connector.capability import (
|
||||
register_capability,
|
||||
)
|
||||
|
||||
# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。
|
||||
# 查询契约:按组织批量查库存,目标为 (料号, 拨出库位, 拨出批号) 元组列表;
|
||||
# 库存查询读契约(列锚点=TIPTOP img_file 库存资料明细档,2026-09-24 官方字典):
|
||||
# 按组织批量查库存,目标为 (料号, 仓库, 批号) 元组列表——键分别对应
|
||||
# img01 料件编号 / img02 仓库编号 / img04 批号;warehouse_code 用库存中性命名,
|
||||
# 调拨方向语义(拨出/拨入)属 movement 契约,翻译发生在仓库映射/绑定层。
|
||||
# external_org 取自仓库映射(external_organization_code),由绑定参数映射翻译为接口的 organization。
|
||||
_QUERY_INPUT_SCHEMA: dict = {
|
||||
# [口径] img03 库位刻意不进键:调拨按(仓库+批号)粒度汇总,同键多库位行由
|
||||
# StockQueryResult.lookup 累加;img11/img12 官方字典=No Use,永不取数。
|
||||
_INVENTORY_QUERY_INPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["external_org", "targets"],
|
||||
"properties": {
|
||||
"external_org": {"type": "string"},
|
||||
"targets": {"type": "array", "items": {
|
||||
"type": "object",
|
||||
"required": ["material_no", "from_warehouse", "lot_no"],
|
||||
"required": ["material_no", "warehouse_code", "lot_no"],
|
||||
"properties": {
|
||||
"material_no": {"type": "string"},
|
||||
"from_warehouse": {"type": "string"},
|
||||
"warehouse_code": {"type": "string"},
|
||||
"lot_no": {"type": "string"},
|
||||
},
|
||||
}},
|
||||
},
|
||||
}
|
||||
# 出参五键:三键回显目标元组(join 用)+ stock_quantity=img10 库存数量(官方字典
|
||||
# 确认 img11=No Use,账面在库只认 img10)+ stock_unit=img09 库存单位——ERP 侧
|
||||
# 确认不为空(2026-09-24),故为必填(响应缺失即校验失败 fail-closed);
|
||||
# 仅作参考展示锚点,不参与匹配键(交易单位语义归 movement 契约)。
|
||||
_QUERY_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["rows"],
|
||||
"properties": {
|
||||
"rows": {"type": "array", "items": {
|
||||
"type": "object",
|
||||
"required": ["material_no", "from_warehouse", "lot_no", "quantity"],
|
||||
"required": ["material_no", "warehouse_code", "lot_no", "stock_quantity", "stock_unit"],
|
||||
"properties": {
|
||||
"material_no": {"type": "string"},
|
||||
"from_warehouse": {"type": "string"},
|
||||
"warehouse_code": {"type": "string"},
|
||||
"lot_no": {"type": "string"},
|
||||
"quantity": {"type": "number"},
|
||||
"stock_quantity": {"type": "number"},
|
||||
"stock_unit": {"type": "string"},
|
||||
},
|
||||
}},
|
||||
},
|
||||
}
|
||||
# 写出参六态语义(T9 交接项落地):status 为规范终态之一——成功族
|
||||
# success/duplicate_success/duplicate_unverified + 失败族 business_failed/
|
||||
# technical_failed + 触发超时 timeout/result_unknown;补 duplicate_success/
|
||||
# duplicate_unverified 两态使引擎 classify+映射后的成功族能过本 Schema 校验。
|
||||
# document_no/verified_posted 仅在可证明时携带(无法证明为 null)。
|
||||
_WRITE_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["status"],
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"],
|
||||
"enum": [
|
||||
"success", "duplicate_success", "duplicate_unverified",
|
||||
"business_failed", "technical_failed", "timeout", "result_unknown",
|
||||
],
|
||||
},
|
||||
"document_no": {"type": ["string", "null"]},
|
||||
"verified_posted": {"type": ["boolean", "null"]},
|
||||
},
|
||||
}
|
||||
# 调拨单行级 Schema:一张单的 lines 元素,七字段必填——行号、料号、拨出/拨入库位、
|
||||
# 批号、数量与交易单位(Task 7:unit 为 movement 契约第 11 字段)。
|
||||
_TRANSFER_LINE_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["line_no", "material_no", "from_warehouse", "to_warehouse", "lot_no", "quantity", "unit"],
|
||||
"properties": {
|
||||
"line_no": {"type": "integer"},
|
||||
"material_no": {"type": "string"},
|
||||
"from_warehouse": {"type": "string"},
|
||||
"to_warehouse": {"type": "string"},
|
||||
"lot_no": {"type": "string"},
|
||||
"quantity": {"type": "number"},
|
||||
"unit": {"type": "string"},
|
||||
},
|
||||
}
|
||||
# 建单写契约(单据级入参):五元组一组一单,doc_no/submit_timestamp 由域生成器
|
||||
# (Task 6 document_id)终身复用,作为 batch 幂等键语义的载体。
|
||||
_TICKET_INPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
# R9:maker_account=触发执行的操作人账号(执行服务从 run.created_by 解析),
|
||||
# 经绑定直通给中间表 :maker_account(gls_cm07/08 制单人)。
|
||||
"required": ["external_org", "doc_no", "submit_timestamp", "doc_date", "posting_date", "lines", "maker_account"],
|
||||
"properties": {
|
||||
"external_org": {"type": "string"},
|
||||
"doc_no": {"type": "string"},
|
||||
"submit_timestamp": {"type": "string"},
|
||||
"doc_date": {"type": "string"},
|
||||
"posting_date": {"type": "string"},
|
||||
"maker_account": {"type": "string"},
|
||||
"lines": {"type": "array", "items": _TRANSFER_LINE_SCHEMA},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def register_transfer_capabilities() -> None:
|
||||
"""注册在途调拨域的三个能力(幂等:已注册的同名跳过)。
|
||||
"""注册在途调拨域的两个能力(幂等:已注册的同名跳过)。
|
||||
|
||||
幂等是硬要求:组合根每次 create_app 都会调用;测试 reset 注册表后(模块缓存导致
|
||||
import 副作用不再执行)也依赖本函数重建,故不能依赖「只注册一次」。
|
||||
@@ -76,25 +131,18 @@ def register_transfer_capabilities() -> None:
|
||||
for spec in (
|
||||
CapabilitySpec(
|
||||
name="in_transit_transfer.query_inventory",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
input_schema=_INVENTORY_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_QUERY_OUTPUT_SCHEMA,
|
||||
idempotency="none",
|
||||
write=False,
|
||||
),
|
||||
CapabilitySpec(
|
||||
name="in_transit_transfer.create_transfer",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
input_schema=_TICKET_INPUT_SCHEMA,
|
||||
output_schema=_WRITE_OUTPUT_SCHEMA,
|
||||
idempotency="invoice",
|
||||
idempotency="batch",
|
||||
write=True,
|
||||
),
|
||||
CapabilitySpec(
|
||||
name="in_transit_transfer.verify_duplicate",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_WRITE_OUTPUT_SCHEMA,
|
||||
idempotency="invoice",
|
||||
write=False,
|
||||
),
|
||||
):
|
||||
if spec.name not in registered:
|
||||
register_capability(spec)
|
||||
|
||||
@@ -1,36 +1,39 @@
|
||||
"""services/in_transit_transfer/capability_client.py
|
||||
|
||||
用途:在途调拨域的外部访问统一客户端——查询经 CapabilityGateway 按能力批量调用;
|
||||
写路径在外部契约冻结前 fail-closed(Phase 2 接线点);域异常与写结果分类集中于此。
|
||||
依赖:integration_connector.gateway / errors、app.core.errors。
|
||||
逻辑:查询按 (料号, 拨出库位, 拨出批号) 元组批量进行,组织键 external_org 取自
|
||||
用途:在途调拨域的外部访问统一客户端——查询与建单均经 CapabilityGateway 按能力
|
||||
调用(D13 恰两能力:query_inventory 读 / create_transfer 写);域单据级契约
|
||||
(TransferOrder)、写结果分类(TransferWriteResult)与六态映射集中于此。
|
||||
依赖:integration_connector.gateway / transports.base / errors、app.core.errors。
|
||||
逻辑:查询按 (料号, 仓库, 批号) 元组批量进行(列锚点=img_file img01/img02/img04,
|
||||
库存中性命名,拨出语义归 movement 契约),组织键 external_org 取自
|
||||
仓库映射(external_organization_code);查询超时→ExternalQueryTimeoutError,
|
||||
网关失败→AppError;写 transport 未注入时 create_transfer/verify_duplicate
|
||||
抛 ExternalNotFrozenError,注入后超时分类为 technical_failed / result_unknown。
|
||||
网关失败→AppError。写路径为纯委派(D13/D6):create_transfer 把单据级
|
||||
TransferOrder 展平为六键 params → 网关顺序引擎按绑定多步快照执行
|
||||
(resume=final_only 纯透传,business_ref 业务锚点纯透传落调用日志,
|
||||
D7② 策略由执行服务按单状态决定,本层零判断)→
|
||||
_to_write_result 六态显式映射。D6 无回读:不实现任何 ERP 状态回读/verify,
|
||||
result_unknown 仅产生于触发超时(timeout)与 duplicate_unverified(保守收敛),
|
||||
两者均禁止自动重试;绑定缺失由网关 BindingNotFoundError 原样上抛承担
|
||||
(单据级异常隔离在执行服务),契约冻结门(ExternalNotFrozenError)已随
|
||||
WSDL 冻结移除。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
|
||||
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
|
||||
CREATE_TRANSFER_CAPABILITY = "in_transit_transfer.create_transfer"
|
||||
|
||||
EXTERNAL_NOT_FROZEN_CODE = "TRANSFER.EXTERNAL_NOT_FROZEN"
|
||||
EXTERNAL_QUERY_TIMEOUT_CODE = "TRANSFER.EXTERNAL_QUERY_TIMEOUT"
|
||||
EXTERNAL_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN"
|
||||
|
||||
|
||||
class ExternalNotFrozenError(AppError):
|
||||
"""外部系统契约(WSDL/endpoint)尚未冻结,禁止调用(fail-closed)。"""
|
||||
|
||||
def __init__(self, message: str = "external system contract not frozen"):
|
||||
super().__init__(code=EXTERNAL_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
|
||||
|
||||
|
||||
class ExternalQueryTimeoutError(AppError):
|
||||
"""外部系统查询超时(只读路径,允许上层重试)。"""
|
||||
|
||||
@@ -39,33 +42,20 @@ class ExternalQueryTimeoutError(AppError):
|
||||
|
||||
|
||||
class ExternalResultUnknownError(AppError):
|
||||
"""外部系统写结果无法确认(Phase 2 使用);禁止自动重试。"""
|
||||
"""外部系统写结果无法确认(执行服务人工 retrigger 链路使用);禁止自动重试。"""
|
||||
|
||||
def __init__(self, message: str = "external result unknown", *, operation_id: str | None = None):
|
||||
details = {"operation_id": operation_id} if operation_id else {}
|
||||
super().__init__(code=EXTERNAL_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details)
|
||||
|
||||
|
||||
class ExternalWriteTimeoutError(TimeoutError):
|
||||
"""外部系统写超时;committed 表达是否可证明已落单。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
*,
|
||||
committed: bool | None,
|
||||
document_no: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.committed = committed
|
||||
self.document_no = document_no
|
||||
self.operation_id = operation_id
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferWriteResult:
|
||||
"""外部系统原子建单/审核/过账结果分类。"""
|
||||
"""外部系统原子建单/审核/过账结果分类(域侧六态枚举)。
|
||||
|
||||
经 _to_write_result 映射后 client 实际只产出五态:duplicate_unverified 保守
|
||||
收敛为 result_unknown(D6),枚举保留该态供执行服务/审计语义完整。
|
||||
"""
|
||||
|
||||
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
|
||||
document_no: str | None = None
|
||||
@@ -74,23 +64,59 @@ class TransferWriteResult:
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferOrder:
|
||||
"""域单据级契约(外部系统无关):一张 ERP 调拨单的全部域事实。
|
||||
|
||||
五元组一组一单(D3):doc_no/submit_timestamp 由域生成器终身复用,作为 ERP
|
||||
batch 幂等键语义的载体;本结构不感知 ERP 字段名——单头六字段 → 接口参数的
|
||||
翻译由网关绑定的 param_mapping 承担(T15 配置)。lines 行 dict 结构由能力
|
||||
Schema 把关(capabilities._TRANSFER_LINE_SCHEMA):line_no / material_no /
|
||||
from_warehouse / to_warehouse / lot_no / quantity / unit 七字段必填;
|
||||
行级 from/to 允许与单头不同(行集由行聚合层产出,client 禁止改写)。
|
||||
"""
|
||||
|
||||
external_org: str
|
||||
doc_no: str
|
||||
submit_timestamp: str
|
||||
doc_date: str
|
||||
posting_date: str
|
||||
from_warehouse: str
|
||||
to_warehouse: str
|
||||
lines: list[dict]
|
||||
# R9:制单人=触发本次执行的运维账号(run.created_by → users.username),
|
||||
# 由执行服务解析后随单下传;空串=系统触发无操作人(ERP 侧按其规则处理)。
|
||||
maker_account: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StockTarget:
|
||||
"""库存查询目标元组:料号 + 拨出库位 + 拨出批号。"""
|
||||
"""库存查询目标元组:料号 + 仓库 + 批号(ERP img01/img02/img04)。
|
||||
|
||||
warehouse_code 为库存中性命名(img02 仓库编号);调拨方向语义(拨出库位)
|
||||
属 movement 契约,由调用方从路由解析值换键名传入。
|
||||
"""
|
||||
|
||||
material_no: str
|
||||
from_warehouse: str
|
||||
warehouse_code: str
|
||||
lot_no: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StockRow:
|
||||
"""外部系统返回的一行账面库存。"""
|
||||
"""外部系统返回的一行账面库存。
|
||||
|
||||
stock_quantity=img10 库存数量(img11 官方字典 No Use,不取数);
|
||||
stock_unit=img09 库存单位(ERP 侧确认恒非空,能力出参必填)——
|
||||
调拨行交易单位(unit)的唯一数据来源(单据字段只取 ERP,禁用货代文件
|
||||
单位列),空值由域层落 blocked_missing_unit。
|
||||
"""
|
||||
|
||||
material_no: str
|
||||
from_warehouse: str
|
||||
warehouse_code: str
|
||||
lot_no: str
|
||||
quantity: Decimal
|
||||
stock_unit: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -99,28 +125,35 @@ class StockQueryResult:
|
||||
|
||||
rows: tuple[StockRow, ...]
|
||||
|
||||
def lookup(self, *, material_no: str, from_warehouse: str, lot_no: str) -> Decimal | None:
|
||||
def lookup(self, *, material_no: str, warehouse_code: str, lot_no: str) -> Decimal | None:
|
||||
"""按三元组取库存数量;同键多行累加;未命中返回 None。"""
|
||||
total: Decimal | None = None
|
||||
for row in self.rows:
|
||||
if (row.material_no, row.from_warehouse, row.lot_no) == (material_no, from_warehouse, lot_no):
|
||||
if (row.material_no, row.warehouse_code, row.lot_no) == (material_no, warehouse_code, lot_no):
|
||||
total = row.quantity if total is None else total + row.quantity
|
||||
return total
|
||||
|
||||
def lookup_row(self, *, material_no: str, warehouse_code: str, lot_no: str) -> StockRow | None:
|
||||
"""按三元组取首个命中库存行(数量+单位一并取用);未命中返回 None。
|
||||
|
||||
同键多行时数量口径见 lookup(累加),单位取首行(ERP 同料号+批号
|
||||
账面单位唯一,img09 恒非空)。
|
||||
"""
|
||||
for row in self.rows:
|
||||
if (row.material_no, row.warehouse_code, row.lot_no) == (material_no, warehouse_code, lot_no):
|
||||
return row
|
||||
return None
|
||||
|
||||
|
||||
class CapabilityClient:
|
||||
"""域内外部访问统一客户端:查询经 CapabilityGateway,写路径 fail-closed。
|
||||
"""域内外部访问统一客户端:查询与建单均经 CapabilityGateway 委派。
|
||||
|
||||
Args:
|
||||
gateway: 可注入替身(测试);缺省 get_capability_gateway()。
|
||||
write_transport: 写路径传输替身(Phase 2 前恒 None → 写调用抛
|
||||
ExternalNotFrozenError;测试注入后走经典写分类:可证明未落单→
|
||||
technical_failed,否则 result_unknown)。
|
||||
"""
|
||||
|
||||
def __init__(self, gateway: Any | None = None, write_transport: Any | None = None) -> None:
|
||||
def __init__(self, gateway: Any | None = None) -> None:
|
||||
self._gateway_override = gateway
|
||||
self._write_transport = write_transport
|
||||
|
||||
def _gateway(self) -> Any:
|
||||
if self._gateway_override is not None:
|
||||
@@ -152,7 +185,7 @@ class CapabilityClient:
|
||||
"targets": [
|
||||
{
|
||||
"material_no": target.material_no,
|
||||
"from_warehouse": target.from_warehouse,
|
||||
"warehouse_code": target.warehouse_code,
|
||||
"lot_no": target.lot_no,
|
||||
}
|
||||
for target in targets
|
||||
@@ -172,9 +205,10 @@ class CapabilityClient:
|
||||
rows = [
|
||||
StockRow(
|
||||
material_no=str(row.get("material_no") or ""),
|
||||
from_warehouse=str(row.get("from_warehouse") or ""),
|
||||
warehouse_code=str(row.get("warehouse_code") or ""),
|
||||
lot_no=str(row.get("lot_no") or ""),
|
||||
quantity=Decimal(str(row.get("quantity") or "0")),
|
||||
quantity=Decimal(str(row.get("stock_quantity") or "0")),
|
||||
stock_unit=str(row.get("stock_unit") or ""),
|
||||
)
|
||||
for row in ((result.data or {}).get("rows") or [])
|
||||
]
|
||||
@@ -184,100 +218,136 @@ class CapabilityClient:
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
external_org: str,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
order: TransferOrder,
|
||||
final_only: bool = False,
|
||||
on_nonfinal_success: Callable[[Any, int], None] | None = None,
|
||||
business_ref: str | None = None,
|
||||
) -> TransferWriteResult:
|
||||
"""外部系统原子建单/审核/过账并按结果分类。
|
||||
"""域建单唯一入口:解析 create_transfer 绑定(多步快照)→ 委派顺序引擎。
|
||||
|
||||
【AI 触发时机】执行服务对一张未完结单发起 ERP 建单/审核/过账时调用;
|
||||
防双单策略(全量 or 只跑末步)完全由调用方按单状态决定,本方法零策略判断。
|
||||
|
||||
核心逻辑:[STEP 1] 单 → params 六键展平(external_org/doc_no/submit_timestamp/
|
||||
doc_date/posting_date/lines);[STEP 2] 网关 call(capability=
|
||||
in_transit_transfer.create_transfer,resume=final_only)——多步顺序(先落
|
||||
中间表后触发过账)、参数翻译、逐步审计(同 operation_id 串联)与末步分类
|
||||
全部在网关顺序引擎,本方法不感知步骤数;[STEP 3] _to_write_result 六态映射。
|
||||
|
||||
Args:
|
||||
operation_id: 审计串联键(一次建单 N 步共享,IntegrationCall 按 step_index 定位)。
|
||||
order: 域单(doc_no/submit_timestamp 终身复用;lines 原样下传,禁止改写行集)。
|
||||
final_only: 纯透传网关 resume(D7②,由执行服务按单状态决定)——
|
||||
True = result_unknown / 重领取的 executing 单续跑:可能已建成单,
|
||||
禁止重插,网关跳过全部非末步(不建连、不审计、不回调)只执行末步;
|
||||
False = pending 首跑 / business_failed / technical_failed 重提交:
|
||||
全量重跑(DELETE 清同时间戳旧行 + 插入当前可执行行集,可并入新行,
|
||||
使用最新绑定配置)。
|
||||
on_nonfinal_success: 纯透传网关通用步进回调(R7,引擎在「非末步成功放行
|
||||
且审计落库后、进入下一步前」同步回调一次 (该步 BindingStep, 步号))——
|
||||
语义:中间表(stage)写成功断点标记(如 stage_confirmed_at 先落库
|
||||
再触发,D7③),关闭「submit 途中被杀→恢复重插→双单」窗口;回调体
|
||||
必须短小(仅库内毫秒级操作),异常将由引擎按该步失败中止
|
||||
(STEP_CALLBACK_FAILED)。本方法不调用、不包装、不吞异常。
|
||||
business_ref: 通用业务锚点(可空):纯透传网关落 IntegrationCall.business_ref
|
||||
(每步审计行携带,通常传 order.doc_no),供调用日志按业务单号检索/关联
|
||||
(Task 5 API 直接读列);不传为 NULL,现有消费者零改动。
|
||||
|
||||
Returns:
|
||||
TransferWriteResult:success / duplicate_success / duplicate_unverified /
|
||||
business_failed / technical_failed / result_unknown。
|
||||
TransferWriteResult:success / duplicate_success / business_failed /
|
||||
technical_failed / result_unknown(见 _to_write_result 六态映射)。
|
||||
|
||||
Raises:
|
||||
ExternalNotFrozenError: 写契约未冻结(write_transport 未注入)。
|
||||
"""
|
||||
if self._write_transport is None:
|
||||
raise ExternalNotFrozenError("external create_transfer contract not frozen (endpoint missing)")
|
||||
try:
|
||||
response = self._write_transport.create_transfer(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
|
||||
invoice_no=invoice_no, external_org=external_org,
|
||||
from_warehouse=from_warehouse, to_warehouse=to_warehouse, quantity=quantity,
|
||||
)
|
||||
except ExternalWriteTimeoutError as exc:
|
||||
if exc.committed is False:
|
||||
# 可证明未落单 → 明确技术失败(不产生单据)。
|
||||
return TransferWriteResult(status="technical_failed", error_code="EXTERNAL_TIMEOUT_BEFORE_COMMIT")
|
||||
return TransferWriteResult(
|
||||
status="result_unknown", error_code="EXTERNAL_TIMEOUT_AFTER_COMMIT",
|
||||
document_no=exc.document_no,
|
||||
)
|
||||
except TimeoutError:
|
||||
# 无法区分是否落单 → result_unknown,禁止自动重试。
|
||||
return TransferWriteResult(status="result_unknown", error_code="EXTERNAL_TIMEOUT_UNKNOWN")
|
||||
return _classify_write_response(response)
|
||||
BindingNotFoundError: 无可用绑定(fail-closed,原样上抛;单据级异常隔离由执行服务承担)。
|
||||
AppError: 能力未注册 / 入参不合 Schema / 映射失败等引擎 fail-closed 异常。
|
||||
|
||||
def verify_duplicate(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
external_org: str,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> TransferWriteResult:
|
||||
"""核实重复 Invoice 原单是否已审核过账(幂等确认)。
|
||||
|
||||
Returns:
|
||||
duplicate_success(已过账,含原单号)或 duplicate_unverified。
|
||||
单号键约定(T15 的 response_mapping 配置按此产出):映射结果优先取
|
||||
document_no 键,缺失时兜底取 doc_no 键。
|
||||
"""
|
||||
if self._write_transport is None:
|
||||
raise ExternalNotFrozenError("external verify_duplicate contract not frozen (endpoint missing)")
|
||||
try:
|
||||
response = self._write_transport.verify_duplicate(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
|
||||
invoice_no=invoice_no, external_org=external_org,
|
||||
from_warehouse=from_warehouse, to_warehouse=to_warehouse, quantity=quantity,
|
||||
)
|
||||
except (TimeoutError, ExternalWriteTimeoutError):
|
||||
return TransferWriteResult(status="result_unknown", error_code="EXTERNAL_TIMEOUT_UNKNOWN")
|
||||
response = response if isinstance(response, dict) else {}
|
||||
status = str(response.get("status") or "")
|
||||
document_no = response.get("document_no")
|
||||
posted = bool(response.get("verified_posted"))
|
||||
if status == "duplicate_success" and posted:
|
||||
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
|
||||
return TransferWriteResult(
|
||||
status="duplicate_unverified", document_no=document_no, verified_posted=posted,
|
||||
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
params = {
|
||||
"external_org": order.external_org,
|
||||
"doc_no": order.doc_no,
|
||||
"submit_timestamp": order.submit_timestamp,
|
||||
"doc_date": order.doc_date,
|
||||
"posting_date": order.posting_date,
|
||||
"lines": order.lines,
|
||||
"maker_account": order.maker_account,
|
||||
}
|
||||
result = self._gateway().call(
|
||||
capability=CREATE_TRANSFER_CAPABILITY,
|
||||
context={},
|
||||
params=params,
|
||||
operation_id=operation_id,
|
||||
resume=final_only,
|
||||
on_nonfinal_success=on_nonfinal_success,
|
||||
business_ref=business_ref,
|
||||
)
|
||||
return _to_write_result(result)
|
||||
|
||||
|
||||
def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult:
|
||||
"""按外部系统写响应原文分类业务结果。"""
|
||||
status = str(response.get("status") or "")
|
||||
document_no = response.get("document_no")
|
||||
def _to_write_result(result: IntegrationCallResult) -> TransferWriteResult:
|
||||
"""把网关顺序引擎的分类结果显式映射为域写结果(纯函数,D6 无回读)。
|
||||
|
||||
六态映射(逐态注释):
|
||||
- success → success+document_no:末步映射确认建成并过账。
|
||||
- duplicate_success → duplicate_success+document_no:ERP 重触发返回原单号路径
|
||||
(引擎 classify 的 duplicate_success 已隐含 verified_posted=True),幂等收敛。
|
||||
- business_failed → 透传(枚举保留兼容;R8 后 WS 路径不再产生该态),
|
||||
error_code/error_message 原样保留;业务明细留在 result.data(已落审计)。
|
||||
- technical_failed → technical_failed:传输层/引擎技术失败与 ERP 拒单
|
||||
(code≠0)统一归此态透传。
|
||||
- timeout → result_unknown:D6 触发超时是 result_unknown 的唯一自然来源——
|
||||
无法确认是否落单,禁自动重试,等人工 retrigger(D7② 只执行末步)。
|
||||
- duplicate_unverified → result_unknown:保守收敛——声称重复但无法证明已过账,
|
||||
同样禁自动重试/重插(防双单);document_no 留作人工核实 SOP 证据。
|
||||
- result_unknown → 恒等透传。
|
||||
- 其余未映射态 → fail-closed 归 technical_failed(不猜测语义、不重试)。
|
||||
|
||||
失败原因透传(R8 用户口径:失败=失败+原因):classify 对未知响应形态只给
|
||||
通用 error_code,ERP 的 description 落在 data.message——失败族在
|
||||
error_message 为空时回填,行级 result_message 由此向用户展示原文。
|
||||
|
||||
单号键约定:document_no 优先、doc_no 兜底(T15 response_mapping 按此产出);
|
||||
映射未携带时回落网关 classify 的顶层 document_no(传输层直通路径)。
|
||||
"""
|
||||
mapped = result.data if isinstance(result.data, dict) else {}
|
||||
status = str(result.status or "")
|
||||
document_no = mapped.get("document_no") or mapped.get("doc_no") or result.document_no
|
||||
# 失败原因透传:classify 对未知响应形态只给通用 error_code,ERP 的
|
||||
# description 落在 mapped.message——error_message 为空时回填(R8 用户口径)。
|
||||
failure_message = result.error_message or (
|
||||
str(mapped["message"]) if mapped.get("message") not in (None, "") else None
|
||||
)
|
||||
if status == "success":
|
||||
return TransferWriteResult(status="success", document_no=document_no)
|
||||
if status == "duplicate_success":
|
||||
posted = bool(response.get("verified_posted"))
|
||||
if posted:
|
||||
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
|
||||
return TransferWriteResult(
|
||||
status="duplicate_unverified", document_no=document_no, verified_posted=False,
|
||||
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
|
||||
if status == "business_failed":
|
||||
return TransferWriteResult(
|
||||
status="business_failed",
|
||||
error_code=str(response.get("code") or "EXTERNAL_BUSINESS_REJECT"),
|
||||
error_message=str(response.get("message") or ""),
|
||||
error_code=result.error_code,
|
||||
error_message=failure_message,
|
||||
)
|
||||
return TransferWriteResult(status="technical_failed", error_code="EXTERNAL_UNKNOWN_RESPONSE")
|
||||
if status == "technical_failed":
|
||||
return TransferWriteResult(
|
||||
status="technical_failed",
|
||||
error_code=result.error_code,
|
||||
error_message=failure_message,
|
||||
)
|
||||
if status == "timeout":
|
||||
# D6:触发超时 → result_unknown(终态),禁自动重试;不臆造单号。
|
||||
return TransferWriteResult(status="result_unknown", error_code=result.error_code or "EXTERNAL_TIMEOUT_UNKNOWN")
|
||||
if status == "duplicate_unverified":
|
||||
return TransferWriteResult(
|
||||
status="result_unknown",
|
||||
document_no=document_no,
|
||||
error_code=result.error_code or "TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
if status == "result_unknown":
|
||||
return TransferWriteResult(status="result_unknown", document_no=document_no, error_code=result.error_code)
|
||||
# 其余未映射态 fail-closed:归技术失败(error_code 固定,便于运维检索)。
|
||||
return TransferWriteResult(
|
||||
status="technical_failed",
|
||||
error_code="EXTERNAL_UNKNOWN_RESPONSE",
|
||||
error_message=f"unmapped gateway status: {status}",
|
||||
)
|
||||
@@ -74,8 +74,8 @@ class TransferExecuteAction:
|
||||
|
||||
【AI 触发时机】:用户在匹配卡点击"直接生成调拨单"后触发;
|
||||
后台按匹配 scope 圈定 ready 行(invoice_nos 过滤)后按行执行,
|
||||
三层门禁(可执行/行级新鲜度/文件版本对账)与写前复查、
|
||||
外部系统 原子写入由确定性服务完成。
|
||||
两道门禁(可执行/文件版本对账;TTL 新鲜度门禁 2026-09-25 退役)与
|
||||
写前复查、外部系统 原子写入由确定性服务完成。
|
||||
"""
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
matching_id = str(payload.get("matching_id") or "").strip()
|
||||
|
||||
@@ -71,6 +71,11 @@ class MatchingCountsDTO:
|
||||
matched_count: int = 0
|
||||
executable_count: int = 0
|
||||
blocked_count: int = 0
|
||||
# 文件已落地、尚未查 ERP 库存的待查行(status='matching' +
|
||||
# result_code='pending_stock_check',evidence_sync 落地态)。
|
||||
pending_stock_check_count: int = 0
|
||||
# blocked_file_removed 行数(文件新版本中消失,已出清,不进默认视图/明细)。
|
||||
invalid_count: int = 0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -103,6 +108,9 @@ class MatchingItemDTO:
|
||||
lot_no: str = ""
|
||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
|
||||
receipt_warehouse_code: str = ""
|
||||
# 交易单位原值(movement 契约第 11 字段 unit,计划 D4):展示与 ERP 写入行输入,
|
||||
# 不参与匹配身份与 Hash 快照;空值行在匹配阶段落 blocked_missing_unit。
|
||||
unit: str = ""
|
||||
# 行装饰字段(restore 按 scope 实时视图时填齐;run_matching 快照路径保持缺省):
|
||||
# item_id=行主键(批量操作/待处理池回链);checked_at=行评估时间(updated_at);
|
||||
# stale=评估时间距今超过确认 TTL;file_current=行评估版本戳仍是该来源当前可用文件。
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
"""在途调拨依赖装配(Dependencies)。
|
||||
|
||||
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
|
||||
依赖:movement_file_repository / capability_client / matching_service / models。
|
||||
依赖:movement_file_repository / capability_client / matching_service / models / Flask config。
|
||||
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
|
||||
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
|
||||
匹配走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
|
||||
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed)。
|
||||
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed);
|
||||
策略经 _strategy_from_config 从 Flask 配置装配——IN_TRANSIT_TRANSFER_
|
||||
CONFIRM_TTL_SECONDS 的真实生效点(2026-09-24 接线,此前环境变量为死配置:
|
||||
TransferDeps 不传 strategy 时落数据类硬编码 600s)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
|
||||
from app.services.in_transit_transfer.capability_client import CapabilityClient
|
||||
from app.services.in_transit_transfer.movement_file_repository import ShippingReceiptFileRepository
|
||||
@@ -21,6 +27,10 @@ from app.services.in_transit_transfer.matching_service import (
|
||||
RouteResolver,
|
||||
TransferDeps,
|
||||
)
|
||||
from app.services.in_transit_transfer.strategy import (
|
||||
DEFAULT_CONFIRM_TTL_SECONDS,
|
||||
default_strategy,
|
||||
)
|
||||
|
||||
|
||||
class DefaultRouteResolver:
|
||||
@@ -78,10 +88,12 @@ class DefaultRouteResolver:
|
||||
|
||||
|
||||
def _build_capability_client() -> CapabilityClient:
|
||||
"""装配调拨外部访问客户端:查询走 CapabilityGateway(绑定缺失时 fail-closed)。
|
||||
"""装配调拨外部访问客户端:查询/建单统一走 CapabilityGateway(绑定缺失 fail-closed)。
|
||||
|
||||
P1 连接器框架:外部系统差异由配置(ClientInstance/InterfaceDefinition/Binding/映射)
|
||||
承担;create_transfer/verify_duplicate 在 WSDL 冻结前 fail-closed(Phase 2 接线)。
|
||||
承担;create_transfer 为单据级委派(T9)——顺序编排/分类在网关引擎,域侧只做
|
||||
TransferOrder → 六键 params 展平与六态结果映射;原「WSDL 冻结前 fail-closed」
|
||||
门(ExternalNotFrozenError)已移除,绑定缺失由网关 BindingNotFoundError 承担。
|
||||
"""
|
||||
return CapabilityClient()
|
||||
|
||||
@@ -95,6 +107,29 @@ def set_transfer_dependencies(deps: TransferDeps | None) -> None:
|
||||
_override = deps
|
||||
|
||||
|
||||
def _strategy_from_config():
|
||||
"""从 Flask 配置装配策略快照(TTL 环境变量的真实生效点)。
|
||||
|
||||
Why: IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS 只进 Flask config(settings.Config),
|
||||
而 TransferDeps.strategy 缺省落数据类硬编码 600s——环境变量曾是死配置,调大无效。
|
||||
无应用上下文(纯脚本/裸调用)时回落代码默认值,行为与历史一致。
|
||||
|
||||
Returns:
|
||||
TransferStrategyPolicy(confirm_ttl_seconds=max(1, 配置值),禁令项沿用默认)。
|
||||
"""
|
||||
try:
|
||||
raw = current_app.config.get(
|
||||
"IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS", DEFAULT_CONFIRM_TTL_SECONDS,
|
||||
)
|
||||
except RuntimeError: # 无 app context:回落代码默认(等同旧行为)
|
||||
raw = DEFAULT_CONFIRM_TTL_SECONDS
|
||||
try:
|
||||
ttl = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
ttl = DEFAULT_CONFIRM_TTL_SECONDS
|
||||
return replace(default_strategy(), confirm_ttl_seconds=max(1, ttl))
|
||||
|
||||
|
||||
def get_transfer_dependencies() -> TransferDeps:
|
||||
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/外部系统 网关)。"""
|
||||
if _override is not None:
|
||||
@@ -104,6 +139,7 @@ def get_transfer_dependencies() -> TransferDeps:
|
||||
rpa_trigger=_DefaultRpaTrigger(),
|
||||
route_resolver=DefaultRouteResolver(),
|
||||
capabilities=_build_capability_client(),
|
||||
strategy=_strategy_from_config(),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""在途调拨单号与提交时间戳生成器(D2/D3 幂等锚)。
|
||||
|
||||
用途:生成调拨单的两个终身幂等锚——来源单号 doc_no(D2:
|
||||
{external_org}-OR-{yyMMdd}{全局PG序列:05d},超 99999 自然扩位、
|
||||
不按日重置)与提交时间戳 submit_timestamp(D3:32 位 uuid4 hex +
|
||||
yyyyMMddHHmmssSSS,总长 49)。
|
||||
依赖:标准库 uuid/datetime/typing;app.db(SQLAlchemy 实例,仅默认 PG
|
||||
序列读取使用);app.core.errors.ValidationError(external_org
|
||||
非空 fail-closed)。
|
||||
逻辑:execution_service 组建新单时各调用一次并终身复用(禁止重试换新:
|
||||
我方清理 / ERP 处理 / ERP 回带单号三方全锚定此值)。两函数均为纯
|
||||
函数,时刻与序列经参数注入;默认序列读取仅支持 PostgreSQL(迁移
|
||||
tt8b9c0d1e2f 创建 transfer_doc_no_seq),SQLite 等无序列后端不做
|
||||
兼容,测试一律注入 sequence_loader 替身。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Callable
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
# 来源单号中间固定连接段(D2:{org}-OR-{yyMMdd}{seq})。
|
||||
_DOC_NO_MIDDLE = "-OR-"
|
||||
# 序列段最小位数(%05d;超 99999 自然扩位,禁止截断)。
|
||||
_SEQUENCE_MIN_DIGITS = 5
|
||||
# external_org 为空的错误码(与 frontend/src/locales/*/errors.json 四语言同步)。
|
||||
_ORG_REQUIRED_CODE = "TRANSFER.ORG_REQUIRED"
|
||||
# 默认 PG 全局序列(迁移 tt8b9c0d1e2f 创建;标识符为模块常量,非用户输入)。
|
||||
_PG_NEXTVAL_SQL = "SELECT nextval('transfer_doc_no_seq')"
|
||||
|
||||
|
||||
def new_submit_timestamp(now: datetime | None = None) -> str:
|
||||
"""生成 49 位提交时间戳(D3 幂等锚,一单生成一次终身复用)。
|
||||
|
||||
唯一性语义:前 32 位 uuid4 hex 承担唯一性(同一 now 两次调用必不同),
|
||||
后 17 位 yyyyMMddHHmmssSSS 仅承担可读时序;禁止依赖时间戳段做去重,
|
||||
禁止对同一单重复生成(重试/清理/ERP 回带均复用首次值)。
|
||||
|
||||
Args:
|
||||
now: 可选时刻(缺省 utcnow),仅用于生成可读时间戳段。
|
||||
|
||||
Returns:
|
||||
32 位小写 hex + 17 位 yyyyMMddHHmmssSSS 字符串,总长恒 49。
|
||||
"""
|
||||
moment = now if now is not None else datetime.utcnow()
|
||||
# [STEP 1] 可读段:秒级格式化 + 毫秒(取微秒前三位,恒 3 位)。
|
||||
readable = f"{moment.strftime('%Y%m%d%H%M%S')}{moment.microsecond // 1000:03d}"
|
||||
# [STEP 2] 唯一段:uuid4 hex(32 位小写,承担唯一性)。
|
||||
return f"{uuid.uuid4().hex}{readable}"
|
||||
|
||||
|
||||
def _pg_sequence_loader() -> int:
|
||||
"""从 PG 全局序列取下一单号序号(默认 sequence_loader 实现)。
|
||||
|
||||
注意:仅支持 PostgreSQL(transfer_doc_no_seq 由迁移 tt8b9c0d1e2f
|
||||
创建);SQLite 等无序列后端不做兼容——测试一律注入替身。
|
||||
|
||||
Returns:
|
||||
序列下一个值(int,全局单调递增,不按日重置)。
|
||||
"""
|
||||
result = db.session.execute(text(_PG_NEXTVAL_SQL))
|
||||
return int(result.scalar_one())
|
||||
|
||||
|
||||
def next_document_no(
|
||||
external_org: str,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
sequence_loader: Callable[[], int] | None = None,
|
||||
) -> str:
|
||||
"""生成来源单号(D2):{external_org}-OR-{yyMMdd}{seq:05d}。
|
||||
|
||||
业务约束:seq 来自全局 PG 序列(不按日重置,跨日不回绕);%05d 为
|
||||
最小五位数,超 99999 自然扩位(100000 → 6 位),禁止截断;yyMMdd
|
||||
日期段取自 now,仅用于可读性,唯一性由全局序列保证。
|
||||
|
||||
Args:
|
||||
external_org: 外部组织代码,禁止为空/全空白(fail-closed)。
|
||||
now: 可选时刻(缺省 utcnow),仅用于 yyMMdd 可读日期段。
|
||||
sequence_loader: 可选序列取值函数(缺省读 PG nextval;
|
||||
测试/非 PG 后端注入替身,禁止传入会重置序号的实现)。
|
||||
|
||||
Returns:
|
||||
形如 'DEMO-OR-26092400001' 的来源单号字符串。
|
||||
|
||||
Raises:
|
||||
ValidationError: external_org 为 None、空串或全空白
|
||||
(code=TRANSFER.ORG_REQUIRED)。
|
||||
"""
|
||||
# [STEP 1] fail-closed:组织代码缺失时拒绝生成(缺组织无法回带 ERP 对账)。
|
||||
if not isinstance(external_org, str) or not external_org.strip():
|
||||
raise ValidationError("external_org is required", code=_ORG_REQUIRED_CODE)
|
||||
|
||||
# [STEP 2] 取全局序列下一个值(缺省走 PG nextval)。
|
||||
loader = sequence_loader if sequence_loader is not None else _pg_sequence_loader
|
||||
seq = loader()
|
||||
|
||||
# [STEP 3] 拼装:日期段 yyMMdd(可读时序)+ 序列段 %05d(最小五位、自然扩位)。
|
||||
moment = now if now is not None else datetime.utcnow()
|
||||
return (
|
||||
f"{external_org}{_DOC_NO_MIDDLE}{moment.strftime('%y%m%d')}"
|
||||
f"{seq:0{_SEQUENCE_MIN_DIGITS}d}"
|
||||
)
|
||||
@@ -0,0 +1,339 @@
|
||||
"""services/in_transit_transfer/evidence_sync.py
|
||||
|
||||
用途:收料证据同步——把来源最新可用收料文件解析为调拨待办行(文件落地即写,
|
||||
主链路),并提供「行版本戳 vs 最新文件 sha」的对齐入口(匹配/重查兜底)。
|
||||
依赖:file_parser / invoice_aggregator / transfer_type / source_file_status /
|
||||
matching_service(_item_evaluated_sha 复用)/ models / audit。
|
||||
逻辑:一次解析三分类写入——文件里有、本地没有 → 插入待查行;有且 sha 未变 →
|
||||
整行跳过(幂等,不续新鲜度);sha 变了证据没变 → 刷新名称/规格展示值并只换
|
||||
版本戳;证据变了(数量/批号/仓库)→ 刷新证据并重置回待查(旧库存是对旧数量
|
||||
查的,作废);消失标记行复现 → 无论证据变化与否无条件恢复待查(防复现行卡死
|
||||
隐藏);文件里消失 → blocked_file_removed 且换戳到最新 sha(保证对齐入口
|
||||
row_shas 收敛直通)。全程零外部调用(不查 ERP、不触发 RPA);终态行绝不触碰,
|
||||
终态四元组入去重圈——同文件重落地不复活已执行行(防二次真实调拨);
|
||||
不 commit 只 flush(提交归调用方:落地桥自行 commit,匹配/重查随主事务)。
|
||||
13 状态冻结契约内表达待查态:status='matching' + result_code='pending_stock_check'。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.file_parser import parse_movement_rows
|
||||
from app.services.in_transit_transfer.invoice_aggregator import aggregate_invoices
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
RESULT_FILE_REMOVED,
|
||||
RouteNotResolvedError,
|
||||
_item_evaluated_sha,
|
||||
)
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
from app.services.in_transit_transfer.transfer_type import (
|
||||
TransferType,
|
||||
filter_invoices_for_type,
|
||||
)
|
||||
|
||||
# 待查态结果码:13 状态冻结契约内的表达(status='matching' + 本结果码),
|
||||
# 表示「收料文件已落地、库存侧尚未核对」;禁用新状态值。
|
||||
SYNC_RESULT_PENDING = "pending_stock_check"
|
||||
|
||||
# 终态集合与 matching_service 原地刷新口径一致:同步永不触碰既定事实。
|
||||
_TERMINAL_ITEM_STATUSES = frozenset({
|
||||
status_machine.TransferStatus.SUCCESS.value,
|
||||
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
|
||||
status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||
status_machine.TransferStatus.CANCELLED.value,
|
||||
status_machine.TransferStatus.EXECUTING.value,
|
||||
status_machine.TransferStatus.RESULT_UNKNOWN.value,
|
||||
})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SyncOutcome:
|
||||
"""一次来源同步的结果计数(审计与兜底日志的数据源)。"""
|
||||
|
||||
source_code: str
|
||||
file_sha256: str
|
||||
inserted: int = 0 # 文件有、本地无 → 插入待查行
|
||||
refreshed: int = 0 # sha 变了、业务值没变 → 只换版本戳,状态保留
|
||||
reset_pending: int = 0 # 业务值变了 → 刷新值 + 重置待查(旧库存作废)
|
||||
removed: int = 0 # 文件里消失 → blocked_file_removed
|
||||
skipped: int = 0 # sha 未变的幂等跳过;终态四元组重落地亦计入(不复活)
|
||||
|
||||
|
||||
def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetime) -> SyncOutcome | None:
|
||||
"""解析来源最新可用收料文件并三分类写入待办行(零外部调用,flush 不 commit)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
deps: TransferDeps(只用 file_repository 与 route_resolver)。
|
||||
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
|
||||
now: 新鲜度基准(显式续 updated_at,执行门禁展示依据)。
|
||||
Returns:
|
||||
SyncOutcome;来源无可用文件(未抓取/已过期/已清理)返回 None。
|
||||
"""
|
||||
ready = deps.file_repository.latest_ready_file(source_code=source_code, business_date=business_date)
|
||||
if ready is None:
|
||||
return None
|
||||
parsed = parse_movement_rows(source_code=source_code, rows=ready.rows)
|
||||
invoices = filter_invoices_for_type(
|
||||
aggregate_invoices(parsed, file_version=ready.file_version),
|
||||
TransferType.IN_TRANSIT_TO_HUB,
|
||||
)
|
||||
|
||||
# [STEP 1] 圈定本来源全部非终态既有行,按四元组建索引(matching_id 已放开
|
||||
# 非空,落地行不受 uq_transfer_invoice_items_matching_grain 保护,幂等去重
|
||||
# 由本应用层四元组负责)。
|
||||
existing = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.source_code == source_code,
|
||||
TransferInvoiceItem.status.not_in(_TERMINAL_ITEM_STATUSES),
|
||||
).all()
|
||||
by_key = {(r.source_code, r.invoice_no, r.material_no, r.receipt_date): r for r in existing}
|
||||
|
||||
# [终态去重圈] 终态行同样纳入四元组去重范围(只查四列,轻量):若只在非终态
|
||||
# 行内去重,来源全终态后同文件重落地(同日 RPA 重试再触发落地桥 / align 兜底
|
||||
# 重解析)时 quad 缺席索引会被当全新行重插 pending——已执行的调拨单「复活」
|
||||
# 回待办池,存在以新 doc_no 二次真实执行的风险。终态不复活是冻结约束:
|
||||
# 重落地对终态行既不重插也不触碰。
|
||||
terminal_keys = {
|
||||
tuple(r)
|
||||
for r in TransferInvoiceItem.query.with_entities(
|
||||
TransferInvoiceItem.source_code,
|
||||
TransferInvoiceItem.invoice_no,
|
||||
TransferInvoiceItem.material_no,
|
||||
TransferInvoiceItem.receipt_date,
|
||||
).filter(
|
||||
TransferInvoiceItem.source_code == source_code,
|
||||
TransferInvoiceItem.status.in_(_TERMINAL_ITEM_STATUSES),
|
||||
).all()
|
||||
}
|
||||
|
||||
counters = {"inserted": 0, "refreshed": 0, "reset_pending": 0, "removed": 0, "skipped": 0}
|
||||
incoming_keys: set[tuple] = set()
|
||||
|
||||
# [STEP 2] 文件内单逐张三分类:跳过 / 插入 / 刷新+重置。
|
||||
for invoice in invoices:
|
||||
receipt_date_iso = invoice.receipt_date.isoformat()
|
||||
key = (source_code, invoice.invoice_no, invoice.material_no, receipt_date_iso)
|
||||
incoming_keys.add(key)
|
||||
row = by_key.get(key)
|
||||
# [终态不复活] 该四元组已有终态行(已执行/已关闭等):同文件重落地跳过
|
||||
# 整行——不重插新 pending 行,也不触碰终态行本身(计数归 skipped 口径)。
|
||||
# 必须在插入判定之前拦截,否则全终态来源重落地会重开已执行的调拨单。
|
||||
if row is None and key in terminal_keys:
|
||||
counters["skipped"] += 1
|
||||
continue
|
||||
# [证据变化判定] 只比对收料事实(数量/批号/仓库);material_name 等展示
|
||||
# 字段不触发重置(重置会作废旧库存查询,代价是重查)。
|
||||
evidence_changed = row is None or (
|
||||
str(row.receipt_quantity) != str(invoice.receipt_quantity)
|
||||
or (row.lot_no or "") != (invoice.lot_no or "")
|
||||
or (row.receipt_warehouse_code or "") != (invoice.warehouse_code or "")
|
||||
)
|
||||
if row is not None and not evidence_changed and _item_evaluated_sha(row) == ready.checksum:
|
||||
counters["skipped"] += 1 # [幂等] 同文件重复落地:零写入(不续新鲜度)
|
||||
continue
|
||||
if row is None:
|
||||
from_wh, to_wh = _resolve_route_best_effort(deps, source_code, invoice)
|
||||
db.session.add(TransferInvoiceItem(
|
||||
matching_id=None, # 落地行尚无匹配归属(列已放开非空)
|
||||
source_code=source_code,
|
||||
invoice_no=invoice.invoice_no,
|
||||
material_no=invoice.material_no,
|
||||
material_name=invoice.material_name,
|
||||
specification=invoice.specification,
|
||||
receipt_date=receipt_date_iso,
|
||||
status=status_machine.TransferStatus.MATCHING.value,
|
||||
result_code=SYNC_RESULT_PENDING,
|
||||
result_message=None,
|
||||
from_warehouse=from_wh,
|
||||
to_warehouse=to_wh,
|
||||
receipt_quantity=str(invoice.receipt_quantity),
|
||||
external_quantity=None,
|
||||
lot_no=invoice.lot_no or "",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
unit="", # 单位只取 ERP stock_unit,匹配查询时落列
|
||||
raw_lines_json=[
|
||||
{"sheet": line.sheet, "row_no": line.row_no,
|
||||
"file_version": line.file_version, "file_sha256": ready.checksum}
|
||||
for line in invoice.raw_lines
|
||||
],
|
||||
updated_at=now,
|
||||
))
|
||||
counters["inserted"] += 1
|
||||
continue
|
||||
# [Important② 复现行] 消失标记行(blocked_file_removed)重新出现在最新
|
||||
# 文件:无论证据变化与否都必须恢复待查态——其历史解释(文件里消失)已
|
||||
# 失效;若只换戳不恢复,行卡在 blocked 且对齐入口直通,永久隐藏。
|
||||
# 非终态行恢复不违反终态冻结。
|
||||
restored_from_removed = row.result_code == RESULT_FILE_REMOVED
|
||||
# [版本戳] 行随最新文件版本刷新(复现行与普通行同路径换新戳,对齐入口
|
||||
# 据此收敛直通)。
|
||||
row.raw_lines_json = [
|
||||
{"sheet": line.sheet, "row_no": line.row_no,
|
||||
"file_version": line.file_version, "file_sha256": ready.checksum}
|
||||
for line in invoice.raw_lines
|
||||
]
|
||||
# [Important① 展示字段] 名称/规格属展示字段:进入非跳过分支即刷新
|
||||
# (放在证据分支判断之外)——是否重置待查只由三证据字段决定,避免纯
|
||||
# 名称变更落入 refreshed 后展示值随新戳固化(align 直通后永不更新)。
|
||||
row.material_name = invoice.material_name
|
||||
row.specification = invoice.specification
|
||||
if evidence_changed:
|
||||
# [STEP 3] 收料事实变化:刷新证据值(数量/批号/仓库)。
|
||||
row.receipt_quantity = str(invoice.receipt_quantity)
|
||||
row.lot_no = invoice.lot_no or ""
|
||||
row.receipt_warehouse_code = invoice.warehouse_code or ""
|
||||
if evidence_changed or restored_from_removed:
|
||||
# [重置/恢复] 值变 → 重置回待查(旧库存是对旧数量查的,作废);
|
||||
# 复现行 → 恢复待查(重新进入待办池,计数同归 reset_pending 口径)。
|
||||
row.status = status_machine.TransferStatus.MATCHING.value
|
||||
row.result_code = SYNC_RESULT_PENDING
|
||||
row.result_message = None
|
||||
row.external_quantity = None # 旧库存对旧数量,作废待重查
|
||||
counters["reset_pending"] += 1
|
||||
else:
|
||||
counters["refreshed"] += 1
|
||||
row.updated_at = now
|
||||
|
||||
# [STEP 4] 文件里消失的非终态行 → blocked_file_removed(终态行不在 by_key,绝不触碰)。
|
||||
for key, row in by_key.items():
|
||||
if key in incoming_keys:
|
||||
continue
|
||||
# [版本戳] 消失标记行同样换戳到最新文件 sha(保留原 sheet/row_no 行定位,
|
||||
# 只更新版本号与 sha):否则行版本戳停在旧文件,align 判据 row_shas 永不
|
||||
# 收敛为 {latest_sha},每次兜底都会空转重解析。
|
||||
row.raw_lines_json = [
|
||||
{**line, "file_version": ready.file_version, "file_sha256": ready.checksum}
|
||||
for line in (row.raw_lines_json or [])
|
||||
]
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_FILE_REMOVED
|
||||
row.result_message = "receipt row removed from latest file"
|
||||
row.updated_at = now
|
||||
counters["removed"] += 1
|
||||
|
||||
# [STEP 5] 只 flush 不 commit:落地桥自行 commit,匹配/重查随主事务。
|
||||
db.session.flush()
|
||||
outcome = SyncOutcome(source_code=source_code, file_sha256=ready.checksum or "", **counters)
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_EVIDENCE_SYNCED",
|
||||
aggregate_type="transfer_source",
|
||||
aggregate_id=source_code,
|
||||
actor_type="system",
|
||||
result="success",
|
||||
after={
|
||||
"file_sha256": outcome.file_sha256,
|
||||
"inserted": outcome.inserted, "refreshed": outcome.refreshed,
|
||||
"reset_pending": outcome.reset_pending, "removed": outcome.removed,
|
||||
"skipped": outcome.skipped,
|
||||
},
|
||||
))
|
||||
return outcome
|
||||
|
||||
|
||||
def align_scope_rows(*, source_codes: list[str], deps, business_date: str, now: datetime) -> dict:
|
||||
"""兜底对齐入口:行版本戳 ≠ 最新文件 sha 的来源才重新解析(一致直通零开销)。
|
||||
|
||||
【AI 触发时机】:匹配(run_matching STEP 0)与重查(requery_* STEP 0)调用;
|
||||
落地同步(主链路)失败的静默兜底——稳态下 sha 一致,本函数零解析直通。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例编码列表。
|
||||
deps: TransferDeps(透传 sync_source_rows)。
|
||||
business_date: 业务日期(文件新鲜度口径)。
|
||||
now: 新鲜度基准。
|
||||
Returns:
|
||||
{source_code: SyncOutcome|None};None=已对齐或无可用文件(未解析)。
|
||||
"""
|
||||
outcomes: dict = {}
|
||||
for code in source_codes:
|
||||
latest = resolve_source_file_status(source_code=code) or {}
|
||||
latest_sha = latest.get("file_sha256")
|
||||
if not latest_sha:
|
||||
outcomes[code] = None
|
||||
continue
|
||||
rows = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.source_code == code,
|
||||
TransferInvoiceItem.status.not_in(_TERMINAL_ITEM_STATUSES),
|
||||
).all()
|
||||
row_shas = {_item_evaluated_sha(r) for r in rows}
|
||||
if row_shas == {latest_sha}:
|
||||
outcomes[code] = None # 已对齐:直通
|
||||
continue
|
||||
outcomes[code] = sync_source_rows(source_code=code, deps=deps,
|
||||
business_date=business_date, now=now)
|
||||
return outcomes
|
||||
|
||||
|
||||
def _resolve_route_best_effort(deps, source_code: str, invoice) -> tuple[str, str]:
|
||||
"""同步期预解析路由落列(纯配置查表);解析失败留空不阻断(匹配时再解析)。
|
||||
|
||||
Args:
|
||||
deps: TransferDeps(只用 route_resolver)。
|
||||
source_code: 来源实例编码。
|
||||
invoice: AggregatedInvoice(取 invoice_no / warehouse_code)。
|
||||
Returns:
|
||||
(from_warehouse, to_warehouse);未配置路由返回 ("", "")。
|
||||
"""
|
||||
try:
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=source_code, invoice_no=invoice.invoice_no,
|
||||
warehouse_code=invoice.warehouse_code or "",
|
||||
)
|
||||
return route.from_warehouse, route.to_warehouse
|
||||
except RouteNotResolvedError:
|
||||
return "", ""
|
||||
|
||||
|
||||
def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: datetime) -> bool:
|
||||
"""收料回调桥专用入口:同步 + 自行 commit + 异常全吞(仅 warning 日志)。
|
||||
|
||||
【AI 触发时机】:收料 RPA 回调 success 终态落文件后由
|
||||
shipping_notice.receipt_report_storage 的桥函数调用——桥是记账不是收料链路
|
||||
的正确性依赖,任何异常不得向收料归档主链路传播(B3:必须自行 commit)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(收料单元行上的 source_code)。
|
||||
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
|
||||
now: 新鲜度基准(显式续 updated_at)。
|
||||
Returns:
|
||||
True=同步成功或无事可做(无可用文件);False=同步失败(已记日志)。
|
||||
"""
|
||||
from flask import current_app
|
||||
|
||||
try:
|
||||
outcome = sync_source_rows(source_code=source_code, deps=_default_deps(),
|
||||
business_date=business_date, now=now)
|
||||
# [桥隔离] sync_source_rows 只 flush 不 commit;桥由回调主链路在归档
|
||||
# commit 之后独立调用,提交时机不归调用方管(B3 持久性教训),必须
|
||||
# 在此自行提交,否则请求结束 session 回滚会丢掉已解析的待办行。
|
||||
db.session.commit()
|
||||
if outcome is not None:
|
||||
current_app.logger.info(
|
||||
"TRANSFER_EVIDENCE_SYNC source=%s inserted=%s refreshed=%s reset=%s removed=%s skipped=%s",
|
||||
source_code, outcome.inserted, outcome.refreshed,
|
||||
outcome.reset_pending, outcome.removed, outcome.skipped)
|
||||
return True
|
||||
except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志(见模块 docstring「落地桥」)
|
||||
# [桥隔离] 为什么吞异常:桥是记账不是收料链路的正确性依赖,同步崩溃
|
||||
# 绝不允许波及收料归档终态;丢失的同步由对齐入口 align_scope_rows 兜底。
|
||||
current_app.logger.warning(
|
||||
"TRANSFER_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc)
|
||||
db.session.rollback()
|
||||
return False
|
||||
|
||||
|
||||
def _default_deps():
|
||||
"""装配默认 TransferDeps(桥入口专用:收料链路无 deps 可透传)。
|
||||
|
||||
Returns:
|
||||
TransferDeps(测试经 deps._override 注入 Fake 时返回注入值)。
|
||||
"""
|
||||
from app.services.in_transit_transfer.deps import get_transfer_dependencies
|
||||
|
||||
return get_transfer_dependencies()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -37,6 +37,9 @@ class ParsedReceiptRow:
|
||||
lot_no: str = ""
|
||||
# 收料文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。
|
||||
warehouse_code: str = ""
|
||||
# 交易单位列原值(movement 契约第 11 字段 unit,计划 D4):仅 trim 空白、
|
||||
# 不做单位换算/清洗;空值不产生解析失败,由匹配阶段行级 blocked_missing_unit 阻断。
|
||||
unit: str = ""
|
||||
|
||||
|
||||
class ReceiptFileSchemaError(AppError):
|
||||
@@ -77,6 +80,8 @@ def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]])
|
||||
movement_date → receipt_date(成熟过滤)
|
||||
其余字段(material_code→material_no、material_name、doc_no)透传/展示保留;
|
||||
warehouse_code 透传至 ParsedReceiptRow.warehouse_code(inventory_match 源路由匹配键);
|
||||
unit 原值透传至 ParsedReceiptRow.unit(movement 契约第 11 字段,仅 trim,
|
||||
空值不阻断解析——行级 missing_unit 阻断在匹配阶段);
|
||||
storage_code 仍仅展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
|
||||
|
||||
Args:
|
||||
@@ -193,6 +198,8 @@ def _parse_rows(
|
||||
receipt_quantity=quantity,
|
||||
lot_no=str(row.get("lot_no") or "").strip(),
|
||||
warehouse_code=str(row.get("warehouse_code") or "").strip(),
|
||||
# unit 原值透传(movement 契约第 11 字段):仅 trim,空值解析放行。
|
||||
unit=str(row.get("unit") or "").strip(),
|
||||
))
|
||||
if errors:
|
||||
raise ReceiptFileSchemaError(rows=errors)
|
||||
|
||||
@@ -33,6 +33,9 @@ class AggregatedInvoice:
|
||||
lot_no: str = ""
|
||||
# 组内首行收料仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。
|
||||
warehouse_code: str = ""
|
||||
# 组内首行交易单位原值(movement 契约第 11 字段 unit,计划 D4):与 lot_no 同为
|
||||
# 「组内首行」口径;空值在匹配阶段行级 blocked_missing_unit 阻断,不在此换算/清洗。
|
||||
unit: str = ""
|
||||
|
||||
|
||||
class InvoiceConflictError(AppError):
|
||||
@@ -83,5 +86,6 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str =
|
||||
raw_lines=raw_lines,
|
||||
lot_no=first.lot_no,
|
||||
warehouse_code=first.warehouse_code,
|
||||
unit=first.unit,
|
||||
))
|
||||
return invoices
|
||||
@@ -1,16 +1,26 @@
|
||||
"""在途调拨匹配服务。
|
||||
|
||||
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → 外部系统 库存查询 →
|
||||
严格数量匹配 → 匹配快照与 Hash",并支持匹配进度恢复(restore)。
|
||||
依赖:file_preparation / file_parser / invoice_aggregator / capability_client /
|
||||
date_policy / quantity / contracts / audit / models。
|
||||
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 外部系统;
|
||||
匹配 Hash 由冻结快照复算;create_matching 落库 Run + Matching + Items,
|
||||
重复匹配对既有行"原地刷新"(不迁移 matching_id),行携带文件版本戳
|
||||
file_sha256,文件新版本消失的可执行行标记 blocked_file_removed;
|
||||
用途:编排「证据兜底对齐 → 圈行 → D+1 成熟过滤 → 路由分组批量查 外部系统 库存 →
|
||||
严格数量比对落位 → 匹配快照与 Hash」,并支持匹配进度恢复(restore)。
|
||||
依赖:evidence_sync(STEP 0 兜底对齐)/ file_preparation(缺文件 RPA 分支)/
|
||||
source_file_status / capability_client / date_policy / quantity / contracts /
|
||||
audit / models。
|
||||
逻辑:【语义变更 2026-09-25】文件解析已上移 evidence_sync——行由文件落地同步
|
||||
(收料回调桥,主链路)或 run_matching STEP 0 兜底对齐(备)写入 DB;
|
||||
匹配只读 DB 行并写库存侧字段(status/result_code/result_message/
|
||||
external_quantity/from_warehouse/to_warehouse/unit/updated_at),
|
||||
raw_lines 版本戳归 evidence_sync 所有,匹配不碰。来源实例独立处理,
|
||||
任一来源失败不阻断其他来源;当天收料不查询 外部系统;匹配 Hash 由冻结
|
||||
快照复算;create_matching 只落 Run + SourceJob + Matching 留痕(行落位
|
||||
已由 run_matching 完成,行归属 matching_id 保持首次创建值不迁移);
|
||||
restore 与可调拨明细队列按匹配 scope(scope_item_query)实时圈行;
|
||||
restore 匹配卡是 scope 的实时视图:按 scope 圈行并逐行装饰新鲜度
|
||||
(checked_at/stale)与文件对账(file_current),counts 亦为实时聚合。
|
||||
(checked_at/stale)与文件对账(file_current),counts 亦为实时聚合,
|
||||
blocked_file_removed 行不进明细与常规 counts(只进 invalid_count);
|
||||
行交易单位(movement 契约第 11 字段 unit)只取 ERP 库存查询返回的
|
||||
stock_unit(img09,单据字段以 ERP 为唯一来源,禁用货代文件单位列):
|
||||
命中库存但 ERP 未给单位 → 行级 blocked_missing_unit(拨出/拨入仓库
|
||||
已解析落列,行可解释可重查);unit 不参与匹配 Hash 快照,口径冻结。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,7 +31,7 @@ from datetime import date, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from typing import Any, Protocol
|
||||
|
||||
from sqlalchemy import case, func, false, or_
|
||||
from sqlalchemy import func, false, or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
@@ -35,7 +45,6 @@ from app.services.in_transit_transfer.contracts import (
|
||||
RawLineRefDTO,
|
||||
)
|
||||
from app.services.in_transit_transfer.date_policy import (
|
||||
MATURITY_ELIGIBLE,
|
||||
eligible_receipt_date_to,
|
||||
MATURITY_FUTURE,
|
||||
MATURITY_NOT_MATURED,
|
||||
@@ -43,21 +52,13 @@ from app.services.in_transit_transfer.date_policy import (
|
||||
parse_date,
|
||||
)
|
||||
from app.services.in_transit_transfer.capability_client import ExternalQueryTimeoutError, StockTarget
|
||||
from app.services.in_transit_transfer.file_parser import (
|
||||
ParsedReceiptRow,
|
||||
ReceiptFileSchemaError,
|
||||
parse_movement_rows,
|
||||
parse_receipt_rows,
|
||||
)
|
||||
from app.services.in_transit_transfer.file_parser import ReceiptFileSchemaError
|
||||
from app.services.in_transit_transfer.file_preparation import (
|
||||
ReadyReceiptFile,
|
||||
ReceiptFileRepository,
|
||||
RpaTrigger,
|
||||
ensure_receipt_file_ready,
|
||||
)
|
||||
from app.services.in_transit_transfer.invoice_aggregator import (
|
||||
aggregate_invoices,
|
||||
)
|
||||
from app.services.in_transit_transfer.movement_contract import external_lot_no
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
from app.services.in_transit_transfer.strategy import (
|
||||
@@ -68,8 +69,6 @@ from app.services.in_transit_transfer.transfer_type import (
|
||||
IN_TRANSIT_TO_HUB_INVOICE_PREFIXES,
|
||||
TransferType,
|
||||
ensure_transfer_type_supported,
|
||||
filter_invoices_for_type,
|
||||
invoice_in_scope,
|
||||
normalize_transfer_type,
|
||||
transfer_type_scope_note,
|
||||
)
|
||||
@@ -86,6 +85,25 @@ RESULT_EXTERNAL_QUERY_FAILED = "blocked_external_query_failed"
|
||||
RESULT_EXTERNAL_QUERY_TIMEOUT = "external_query_timeout"
|
||||
# 文件新版本缺失该行(上一版本可执行、最新文件中消失)。
|
||||
RESULT_FILE_REMOVED = "blocked_file_removed"
|
||||
# 交易单位缺失:ERP 库存行未返回单位(stock_unit 空,img09 契约恒非空——出现即
|
||||
# ERP 侧数据异常):行级数据质量阻断。行在此前已完成路由解析,拨出/拨入仓库
|
||||
# 已落列(可解释、可重查);blocked_ 前缀计入 blocked_count(既有 blocked_* 契约)。
|
||||
RESULT_MISSING_UNIT = "blocked_missing_unit"
|
||||
# 路由不可解析(2026-09-25 行级化):行落 blocked 可解释、可重查(路由配置修复后
|
||||
# 重跑匹配/重查即恢复);同时来源级 stage 仍标 failed(fail-closed 语义保留)。
|
||||
RESULT_ROUTE_NOT_RESOLVED = "blocked_route_not_resolved"
|
||||
|
||||
# 匹配不触碰的行终态集合(与 evidence_sync._TERMINAL_ITEM_STATUSES 同口径):
|
||||
# 已执行/人工关闭等既定事实不复活;RESULT_UNKNOWN 行处于执行结果裁决中,同样不可
|
||||
# 被匹配改写(否则执行链路的结果回写会与匹配落位互相踩踏)。
|
||||
_SYNC_TERMINAL_STATUSES = frozenset({
|
||||
status_machine.TransferStatus.SUCCESS.value,
|
||||
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
|
||||
status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||
status_machine.TransferStatus.CANCELLED.value,
|
||||
status_machine.TransferStatus.EXECUTING.value,
|
||||
status_machine.TransferStatus.RESULT_UNKNOWN.value,
|
||||
})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -169,14 +187,20 @@ def run_matching(
|
||||
receipt_date_to: str | None = None,
|
||||
transfer_type: TransferType | str | None = None,
|
||||
) -> MatchingRunResult:
|
||||
"""执行一次只读匹配(不写 外部系统)。
|
||||
"""执行一次匹配(对齐→圈行→查库存→落位;文件解析已上移 evidence_sync)。
|
||||
|
||||
【语义变更 2026-09-25】本函数不再解析收料文件:行由文件落地同步(收料回调桥,
|
||||
主链路)或 STEP 0 兜底对齐(备)写入 DB;本函数只做「成熟过滤 → 路由分组
|
||||
批量查库存 → 数量比对落位」。来源无可用文件时保留既有 UX:触发 RPA 抓取
|
||||
并按准备结果标来源阶段。落库写入不在此 commit(随调用方事务:create_matching
|
||||
末尾统一提交 / 异步 Job handler 回写后提交)。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。
|
||||
business_date: 业务日期 T(YYYY-MM-DD)。
|
||||
deps: 注入的文件仓库 / RPA / 路由 / 外部系统 依赖。
|
||||
active_source_job_key: 活动 Source Job 键(缺文件时绑定已有任务)。
|
||||
run_no: Run 编号(创建 Run 前可为占位)。
|
||||
run_no: Run 编号(契约兼容保留;当前管道不消费,仅调用方留痕)。
|
||||
receipt_date_from / receipt_date_to: 可选收料日期查询范围。
|
||||
transfer_type: 调拨业务类型(缺省在途仓至HUB仓);类型决定收料数据范围。
|
||||
Returns:
|
||||
@@ -199,87 +223,121 @@ def run_matching(
|
||||
raise ValidationError(
|
||||
"receipt date range end exceeds D+1 maturity limit", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
|
||||
)
|
||||
validate_strategy = deps.strategy
|
||||
now = datetime.utcnow()
|
||||
|
||||
# [STEP 0] 证据兜底对齐:sha 不一致的来源先重解析(落地同步失败的静默兜底)。
|
||||
# 逐来源调用以保留来源级隔离:单个来源解析失败(如文件格式坏)只标该来源
|
||||
# failed,不炸整批(2026-09-25 前该隔离在「解析→匹配」内实现,现前移至此)。
|
||||
align_errors: dict[str, tuple[str, str]] = {}
|
||||
from app.services.in_transit_transfer.evidence_sync import align_scope_rows
|
||||
|
||||
sources: list[SourceProgressDTO] = []
|
||||
items: list[MatchingItemDTO] = []
|
||||
file_snapshot: dict[str, Any] = {}
|
||||
for source_code in source_codes:
|
||||
source_stage: SourceProgressDTO
|
||||
try:
|
||||
align_scope_rows(source_codes=[source_code], deps=deps,
|
||||
business_date=business_date, now=now)
|
||||
except ReceiptFileSchemaError as exc:
|
||||
align_errors[source_code] = (exc.code, exc.message)
|
||||
except Exception as exc: # noqa: BLE001 —— 来源级隔离,不阻断其他来源
|
||||
align_errors[source_code] = ("TRANSFER.SOURCE_MATCH_ERROR", str(exc))
|
||||
|
||||
# [文件状态快照] 逐来源判定可用文件:resolve 命中(含 sha)→ file_ready 留痕;
|
||||
# 未命中 → ensure_receipt_file_ready(缺文件触发 RPA,既有 UX 保留)。仓库
|
||||
# 复用直接给出 ready 文件(状态投影延迟或测试替身场景)时同样按 file_ready
|
||||
# 处理并留痕文件信息——只有拿到文件 checksum 的来源才进入本次圈行管道。
|
||||
sources: list[SourceProgressDTO] = []
|
||||
file_snapshot: dict[str, Any] = {}
|
||||
pipeline_codes: list[str] = []
|
||||
for source_code in source_codes:
|
||||
if source_code in align_errors:
|
||||
error_code, error_message = align_errors[source_code]
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="failed",
|
||||
error_code=error_code, error_message=error_message,
|
||||
))
|
||||
continue
|
||||
file_status = resolve_source_file_status(source_code=source_code) or {}
|
||||
checksum = file_status.get("file_sha256")
|
||||
if not checksum:
|
||||
prepared = ensure_receipt_file_ready(
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
repository=deps.file_repository,
|
||||
rpa_trigger=deps.rpa_trigger,
|
||||
source_code=source_code, business_date=business_date,
|
||||
repository=deps.file_repository, rpa_trigger=deps.rpa_trigger,
|
||||
active_source_job_key=active_source_job_key,
|
||||
)
|
||||
if prepared.stage != "file_ready" or prepared.file is None:
|
||||
if prepared.stage == "file_ready" and prepared.file is not None:
|
||||
ready_file = prepared.file
|
||||
checksum = ready_file.checksum
|
||||
file_snapshot[source_code] = {
|
||||
"file_no": ready_file.file_no,
|
||||
"file_version": ready_file.file_version,
|
||||
"checksum": ready_file.checksum,
|
||||
}
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code,
|
||||
stage=prepared.stage,
|
||||
source_code=source_code, stage="file_ready",
|
||||
file_no=ready_file.file_no,
|
||||
file_version=ready_file.file_version,
|
||||
checksum=ready_file.checksum,
|
||||
))
|
||||
else:
|
||||
# 等待 RPA 回调 / 触发失败:该来源本轮不圈行(行保持既有状态)。
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage=prepared.stage,
|
||||
error_code=prepared.error_code,
|
||||
error_message=prepared.error_message,
|
||||
))
|
||||
continue
|
||||
ready_file = prepared.file
|
||||
else:
|
||||
file_snapshot[source_code] = {
|
||||
"file_no": ready_file.file_no,
|
||||
"file_version": ready_file.file_version,
|
||||
"checksum": ready_file.checksum,
|
||||
"file_no": file_status.get("file_no"),
|
||||
"file_version": f"sha256:{checksum}"[:64],
|
||||
"checksum": checksum,
|
||||
}
|
||||
# 真实仓库(movement_file_repository)产出 movement 领域字段行
|
||||
# (doc_no/material_code/quantity/movement_date),按异动解析规则映射校验。
|
||||
parsed = parse_movement_rows(source_code=source_code, rows=ready_file.rows)
|
||||
invoices = aggregate_invoices(parsed, file_version=ready_file.file_version)
|
||||
if range_from is not None:
|
||||
invoices = [invoice for invoice in invoices if invoice.receipt_date >= range_from]
|
||||
if range_to is not None:
|
||||
invoices = [invoice for invoice in invoices if invoice.receipt_date <= range_to]
|
||||
# [调拨类型] 类型决定收料数据范围(如类型1仅保留 INVOICE 前缀 HOM/HOX/WTP),
|
||||
# 范围外票与日期范围过滤同语义:静默排除、不入明细、不阻断来源。
|
||||
invoices = filter_invoices_for_type(invoices, resolved_transfer_type)
|
||||
source_items = _matching_invoices(
|
||||
invoices=invoices,
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
ready_file=ready_file,
|
||||
deps=deps,
|
||||
run_no=run_no,
|
||||
)
|
||||
items.extend(source_items)
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code,
|
||||
stage="file_ready",
|
||||
file_no=ready_file.file_no,
|
||||
file_version=ready_file.file_version,
|
||||
checksum=ready_file.checksum,
|
||||
))
|
||||
except ReceiptFileSchemaError as exc:
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="failed",
|
||||
error_code=exc.code, error_message=exc.message,
|
||||
))
|
||||
except RouteNotResolvedError as exc:
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="failed",
|
||||
error_code=exc.code, error_message=exc.message,
|
||||
))
|
||||
except Exception as exc: # noqa: BLE001 —— 来源级隔离,不阻断其他来源
|
||||
sources.append(SourceProgressDTO(
|
||||
source_code=source_code, stage="failed",
|
||||
error_code="TRANSFER.SOURCE_MATCH_ERROR",
|
||||
error_message=str(exc),
|
||||
source_code=source_code, stage="file_ready",
|
||||
file_no=file_status.get("file_no"),
|
||||
file_version=f"sha256:{checksum}"[:64],
|
||||
checksum=checksum,
|
||||
))
|
||||
pipeline_codes.append(source_code)
|
||||
|
||||
items, pending_stock_check_count, route_failed_sources = _matching_rows(
|
||||
source_codes=pipeline_codes, business_date=business_date, deps=deps,
|
||||
receipt_date_from=receipt_date_from, receipt_date_to=receipt_date_to,
|
||||
file_snapshot=file_snapshot, now=now,
|
||||
)
|
||||
# [来源级 fail-closed] 路由不可解析的来源整源标 failed(行级已落
|
||||
# blocked_route_not_resolved,二者同源不同层:行可解释可重查,来源状态
|
||||
# 提示配置缺漏需人工处理)。
|
||||
for failed_code in route_failed_sources:
|
||||
sources = [
|
||||
SourceProgressDTO(
|
||||
source_code=stage.source_code, stage="failed",
|
||||
file_no=stage.file_no, file_version=stage.file_version,
|
||||
checksum=stage.checksum,
|
||||
error_code=ROUTE_NOT_RESOLVED_CODE,
|
||||
error_message=f"route not resolved for source {stage.source_code}",
|
||||
) if stage.source_code == failed_code else stage
|
||||
for stage in sources
|
||||
]
|
||||
|
||||
# [失效行计数] 同口径独立计数:blocked_file_removed 行不进明细与常规 counts,
|
||||
# 只以 invalid_count 透出(范围过滤与 _matching_rows 一致)。
|
||||
invalid_count = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.source_code.in_(list(source_codes)),
|
||||
TransferInvoiceItem.result_code == RESULT_FILE_REMOVED,
|
||||
*([] if not (receipt_date_from or receipt_date_to) else [
|
||||
*([TransferInvoiceItem.receipt_date >= str(receipt_date_from)] if receipt_date_from else []),
|
||||
*([TransferInvoiceItem.receipt_date <= str(receipt_date_to)] if receipt_date_to else []),
|
||||
]),
|
||||
).count()
|
||||
|
||||
counts = MatchingCountsDTO(
|
||||
file_invoice_count=sum(
|
||||
1 for item in items
|
||||
),
|
||||
file_invoice_count=sum(1 for item in items),
|
||||
not_matured_count=sum(1 for item in items if item.result == RESULT_NOT_MATURED),
|
||||
matched_count=sum(1 for item in items if item.result != RESULT_NOT_MATURED),
|
||||
executable_count=sum(1 for item in items if item.result == RESULT_EXECUTABLE),
|
||||
blocked_count=sum(1 for item in items if item.result.startswith("blocked_")),
|
||||
pending_stock_check_count=pending_stock_check_count,
|
||||
invalid_count=invalid_count,
|
||||
)
|
||||
estimated_quantity = sum(
|
||||
(item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0")
|
||||
@@ -290,6 +348,9 @@ def run_matching(
|
||||
"transfer_type": resolved_transfer_type.value,
|
||||
"file_snapshot": file_snapshot,
|
||||
"counts": {
|
||||
# [Hash 口径] 快照 counts 保持既有 5 键结构不变:pending/invalid 两桶
|
||||
# 是「落位前的瞬态口径」,纳入会使重复匹配的 Hash 漂移,破坏
|
||||
# 「相同输入可审计复算」性质(DTO/counts_json 留痕仍携带全桶)。
|
||||
"file_invoice_count": counts.file_invoice_count,
|
||||
"not_matured_count": counts.not_matured_count,
|
||||
"matched_count": counts.matched_count,
|
||||
@@ -298,6 +359,10 @@ def run_matching(
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
# [Hash 口径冻结] items 快照仅含匹配身份与结果字段;unit 不参与哈希
|
||||
# (口径冻结,历史预检哈希不因本次字段追加而变化——计划 D4,2026-09-24)。
|
||||
# 【2026-09-25】快照行集 = _matching_rows 落位后的 DB 行投影(键形状不变;
|
||||
# Hash 形状变化安全:hash 已是纯留痕不拦执行)。
|
||||
"source_code": item.source_code,
|
||||
"invoice_no": item.invoice_no,
|
||||
"from_warehouse": item.from_warehouse,
|
||||
@@ -327,68 +392,113 @@ def run_matching(
|
||||
return MatchingRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
|
||||
|
||||
|
||||
def _matching_invoices(
|
||||
def _matching_rows(
|
||||
*,
|
||||
invoices: list,
|
||||
source_code: str,
|
||||
source_codes: list[str],
|
||||
business_date: str,
|
||||
ready_file: ReadyReceiptFile,
|
||||
deps: TransferDeps,
|
||||
run_no: str,
|
||||
) -> list[MatchingItemDTO]:
|
||||
"""对单个来源的汇总 Invoice 匹配(成熟过滤 → 路由 → 按组织分组批量查 外部系统 → 匹配)。"""
|
||||
output: list[MatchingItemDTO] = []
|
||||
receipt_date_from: str | None,
|
||||
receipt_date_to: str | None,
|
||||
file_snapshot: dict[str, Any],
|
||||
now: datetime,
|
||||
) -> tuple[list[MatchingItemDTO], int, set[str]]:
|
||||
"""对 scope 内全部非终态非失效行执行「成熟过滤→路由分组批量查库存→落位」。
|
||||
|
||||
# [STEP 1] 成熟过滤与路由解析(不查询):未成熟/未来日期直接落位,
|
||||
# 成熟项按 external_org(仓库映射的外部组织)分组,每组合并为一次批量查询。
|
||||
matured: list[tuple[Any, RouteMapping, tuple[RawLineRefDTO, ...], str]] = []
|
||||
for invoice in invoices:
|
||||
maturity = maturity_status(invoice.receipt_date, business_date)
|
||||
raw = tuple(
|
||||
RawLineRefDTO(sheet=line.sheet, row_no=line.row_no, file_version=line.file_version)
|
||||
for line in invoice.raw_lines
|
||||
)
|
||||
receipt_date_iso = invoice.receipt_date.isoformat()
|
||||
【2026-09-25】替代旧 _matching_invoices(按文件 Invoice 内存匹配):行已在
|
||||
DB(evidence_sync 落地),本函数只写库存侧字段(status/result_code/
|
||||
result_message/external_quantity/from_warehouse/to_warehouse/unit/
|
||||
updated_at);raw_lines 版本戳归 evidence_sync 所有,匹配不碰。
|
||||
|
||||
Args:
|
||||
source_codes: 本轮有可用文件的来源(无文件来源不圈行,行保持既有状态)。
|
||||
business_date: 业务日期 T(成熟过滤基准)。
|
||||
deps: 注入依赖(路由解析 / 外部系统库存查询)。
|
||||
receipt_date_from / receipt_date_to: 可选收料日期范围(ISO 字符串列比较)。
|
||||
file_snapshot: {source_code: 文件留痕}(行 DTO 文件对账装饰输入)。
|
||||
now: 落位时间(updated_at 新鲜度基准)。
|
||||
Returns:
|
||||
(items DTO 列表, pending_count, route_failed_sources)——pending_count=
|
||||
落位前的待查行数(counts 桶);route_failed_sources=路由不可解析的来源
|
||||
集合(run_matching 据此整源标 failed)。
|
||||
"""
|
||||
# 延迟引用(evidence_sync 顶层反向导入本模块,模块级互相引用会循环导入)。
|
||||
from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING
|
||||
|
||||
query = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.source_code.in_(source_codes),
|
||||
TransferInvoiceItem.status.not_in(_SYNC_TERMINAL_STATUSES),
|
||||
# 失效行(文件新版本消失)不参与匹配,也不进明细(invalid_count 单独计数)。
|
||||
or_(TransferInvoiceItem.result_code.is_(None),
|
||||
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED),
|
||||
)
|
||||
if receipt_date_from:
|
||||
query = query.filter(TransferInvoiceItem.receipt_date >= str(receipt_date_from))
|
||||
if receipt_date_to:
|
||||
query = query.filter(TransferInvoiceItem.receipt_date <= str(receipt_date_to))
|
||||
scope_rows_all = query.order_by(
|
||||
TransferInvoiceItem.receipt_date.asc(), TransferInvoiceItem.id.asc(),
|
||||
).all()
|
||||
|
||||
# [STEP 1] 成熟过滤与路由解析(不查询):未成熟/未来日期直接落位;成熟行
|
||||
# 逐行重解析路由(配置可能已变:以本次解析值为准,执行期写前复查兜底漂移)。
|
||||
pending_count = 0
|
||||
route_failed_sources: set[str] = set()
|
||||
matured: list[tuple[TransferInvoiceItem, RouteMapping]] = []
|
||||
output: list[MatchingItemDTO] = []
|
||||
for row in scope_rows_all:
|
||||
# [口径] 待查行计数先于落位统计(落位会改写 result_code)。
|
||||
if (row.status == status_machine.TransferStatus.MATCHING.value
|
||||
and row.result_code == SYNC_RESULT_PENDING):
|
||||
pending_count += 1
|
||||
maturity = maturity_status(row.receipt_date, business_date)
|
||||
if maturity == MATURITY_NOT_MATURED:
|
||||
output.append(MatchingItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse="", from_quantity=None,
|
||||
to_warehouse="", to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_NOT_MATURED, reason="receipt not matured until next business day",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
row.status = status_machine.TransferStatus.NOT_MATURED.value
|
||||
row.result_code = RESULT_NOT_MATURED
|
||||
row.result_message = "receipt not matured until next business day"
|
||||
row.updated_at = now
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
continue
|
||||
if maturity == MATURITY_FUTURE:
|
||||
output.append(MatchingItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse="", from_quantity=None,
|
||||
to_warehouse="", to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_FUTURE_DATE, reason="future receipt date",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_FUTURE_DATE
|
||||
row.result_message = "future receipt date"
|
||||
row.updated_at = now
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
continue
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=source_code, invoice_no=invoice.invoice_no,
|
||||
warehouse_code=invoice.warehouse_code or "",
|
||||
)
|
||||
matured.append((invoice, route, raw, receipt_date_iso))
|
||||
try:
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=row.source_code, invoice_no=row.invoice_no,
|
||||
warehouse_code=row.receipt_warehouse_code or "",
|
||||
)
|
||||
except RouteNotResolvedError:
|
||||
# [2026-09-25 行级化] 路由不可解析:行落 blocked(可解释、可重查),
|
||||
# 来源级 stage 由调用方标 failed;不炸整批(原「来源级中断」语义)。
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_ROUTE_NOT_RESOLVED
|
||||
row.result_message = f"route not resolved for source {row.source_code}"
|
||||
row.updated_at = now
|
||||
route_failed_sources.add(row.source_code)
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
continue
|
||||
row.from_warehouse, row.to_warehouse = route.from_warehouse, route.to_warehouse
|
||||
matured.append((row, route))
|
||||
|
||||
groups: dict[str, list[tuple[Any, RouteMapping, tuple[RawLineRefDTO, ...], str]]] = {}
|
||||
for entry in matured:
|
||||
groups.setdefault(entry[1].external_org, []).append(entry)
|
||||
# [STEP 2] 按(来源, 外部组织)分组——来源实例为执行边界(故障域隔离:
|
||||
# 一个来源的网关绑定缺失不得波及同组织其他来源的查询结果)。
|
||||
groups: dict[tuple[str, str], list[tuple[TransferInvoiceItem, RouteMapping]]] = {}
|
||||
for row, route in matured:
|
||||
groups.setdefault((row.source_code, route.external_org), []).append((row, route))
|
||||
|
||||
# [STEP 2] 每个组织一次批量查询(targets = 料号+拨出库位+拨出批号 元组列表),
|
||||
# 组内逐票按三元组精确匹配库存数量;组级故障降级到组内全部票,不炸整来源。
|
||||
for external_org, entries in groups.items():
|
||||
for (_group_source, external_org), entries in groups.items():
|
||||
# [外部形态] 批号经 WTP→HOW 派生后查询与回查(movement_contract.external_lot_no):
|
||||
# 行上落库为 WMS 文件原形态,ERP 账面批号是 HOW 形态——原形态直查必查空(假阴性)。
|
||||
targets = [
|
||||
StockTarget(material_no=invoice.material_no, from_warehouse=route.from_warehouse, lot_no=invoice.lot_no)
|
||||
for invoice, route, _, _ in entries
|
||||
StockTarget(material_no=row.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(row.lot_no))
|
||||
for row, route in entries
|
||||
]
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
try:
|
||||
@@ -396,81 +506,66 @@ def _matching_invoices(
|
||||
operation_id=operation_id, external_org=external_org, targets=targets,
|
||||
)
|
||||
except ExternalQueryTimeoutError:
|
||||
for invoice, route, raw, receipt_date_iso in entries:
|
||||
output.append(MatchingItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=None, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_EXTERNAL_QUERY_TIMEOUT, reason="external query timeout",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
for row, _route in entries:
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_EXTERNAL_QUERY_TIMEOUT
|
||||
row.result_message = "external query timeout"
|
||||
row.updated_at = now
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
continue
|
||||
except Exception as exc: # noqa: BLE001 —— 网关/绑定层故障降级为整组阻断,不炸整来源
|
||||
# [语义] 绑定缺失、连接失败等基础设施故障是环境问题而非业务阻断:
|
||||
# 组内逐票给 blocked_external_query_failed + 原因,匹配列表保持可见可解释。
|
||||
# 组内逐行给 blocked_external_query_failed + 原因,行保持可见可解释。
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
for invoice, route, raw, receipt_date_iso in entries:
|
||||
output.append(MatchingItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=None, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_EXTERNAL_QUERY_FAILED, reason=f"external query failed: {detail}",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
for row, _route in entries:
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_EXTERNAL_QUERY_FAILED
|
||||
row.result_message = f"external query failed: {detail}"
|
||||
row.updated_at = now
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
continue
|
||||
for invoice, route, raw, receipt_date_iso in entries:
|
||||
stock_qty = stock.lookup(
|
||||
material_no=invoice.material_no, from_warehouse=route.from_warehouse, lot_no=invoice.lot_no,
|
||||
for row, route in entries:
|
||||
stock_row = stock.lookup_row(
|
||||
material_no=row.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(row.lot_no),
|
||||
)
|
||||
if stock_qty is None:
|
||||
output.append(MatchingItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
# 查无库存记录也是外部系统的真实答复:库存数按 0 展示(而非"-"),
|
||||
# 避免用户误以为查询失败;分类仍为 blocked_inventory_not_found。
|
||||
from_quantity=Decimal("0"), to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_INVENTORY_NOT_FOUND, reason="external inventory not found",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
match = classify_quantity_match(invoice.receipt_quantity, stock_qty)
|
||||
output.append(MatchingItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=stock_qty, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
return output
|
||||
|
||||
|
||||
def _item_status(result: str) -> str:
|
||||
"""明细结果 → Invoice 项状态。"""
|
||||
mapping = {
|
||||
RESULT_EXECUTABLE: status_machine.TransferStatus.READY_TO_EXECUTE.value,
|
||||
RESULT_NOT_MATURED: status_machine.TransferStatus.NOT_MATURED.value,
|
||||
RESULT_FUTURE_DATE: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
RESULT_EXTERNAL_QUERY_TIMEOUT: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
RESULT_QUANTITY_MISMATCH: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
RESULT_INVENTORY_NOT_FOUND: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
}
|
||||
return mapping.get(result, status_machine.TransferStatus.BLOCKED_RECOVERABLE.value)
|
||||
if stock_row is None:
|
||||
# 查无库存记录也是外部系统的真实答复:库存数按 0 落库展示(而非"-"),
|
||||
# 避免用户误以为查询失败;分类仍为 blocked_inventory_not_found。
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_INVENTORY_NOT_FOUND
|
||||
row.result_message = "external inventory not found"
|
||||
row.external_quantity = "0"
|
||||
row.unit = ""
|
||||
else:
|
||||
stock_unit = (stock_row.stock_unit or "").strip()
|
||||
# [STEP 3] 交易单位只取 ERP(stock_unit=img09,ERP 侧确认恒非空):
|
||||
# 命中库存但单位缺失=ERP 侧数据异常 → 本行 blocked_missing_unit;
|
||||
# 行已完成路由解析,拨出/拨入仓库照常落列(可解释、可重查)。
|
||||
if not stock_unit:
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = RESULT_MISSING_UNIT
|
||||
row.result_message = "external inventory unit is missing"
|
||||
row.external_quantity = str(stock_row.quantity)
|
||||
row.unit = ""
|
||||
else:
|
||||
match = classify_quantity_match(Decimal(row.receipt_quantity), stock_row.quantity)
|
||||
row.external_quantity = str(stock_row.quantity)
|
||||
row.unit = stock_unit
|
||||
if match == RESULT_EXECUTABLE:
|
||||
row.status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
row.result_code = None
|
||||
row.result_message = None
|
||||
else:
|
||||
row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
row.result_code = match
|
||||
row.result_message = "strict quantity mismatch"
|
||||
row.updated_at = now
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.confirm_ttl_seconds)))
|
||||
return output, pending_count, route_failed_sources
|
||||
|
||||
|
||||
def _generate_no(prefix: str, business_date: str) -> str:
|
||||
@@ -483,10 +578,10 @@ def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None:
|
||||
"""读取行的文件版本戳(评估该行时所用的收料文件 checksum)。
|
||||
|
||||
用途:消失行标记(create_matching)与文件对账(restore 展示 / execute_items
|
||||
执行门禁③)据此判断"行的评估版本是否仍是最新文件版本"。
|
||||
执行门禁②)据此判断"行的评估版本是否仍是最新文件版本"。
|
||||
两个消费方对 None(未知版本)口径不同:
|
||||
- restore 展示:None → file_current=False(仅展示不可执行原因,不阻断);
|
||||
- execute_items 门禁③:None 按"评估版本缺失"fail-closed 拒绝执行
|
||||
- execute_items 门禁②:None 按"评估版本缺失"fail-closed 拒绝执行
|
||||
(TRANSFER.FILE_CHANGED),宁可误拒也不按过期文件写 ERP。
|
||||
|
||||
Args:
|
||||
@@ -511,11 +606,13 @@ def create_matching(
|
||||
receipt_date_to: str | None = None,
|
||||
transfer_type: TransferType | str | None = None,
|
||||
) -> MatchingSummaryDTO:
|
||||
"""运行匹配并落库 TransferRun + TransferMatching + InvoiceItems。
|
||||
"""运行匹配并落库 TransferRun + SourceJob + TransferMatching(留痕;不写行)。
|
||||
|
||||
落库为行原地刷新语义:相同粒度的既有行只刷新业务值(不迁移 matching_id)、
|
||||
行携带本次评估所用文件的 file_sha256 版本戳;上一版本可执行而最新文件
|
||||
消失的 ready 行被标记 blocked_file_removed。
|
||||
【语义变更 2026-09-25】行落位已全部由 run_matching 完成(证据同步落地 +
|
||||
库存比对落位),本函数只负责留痕:Run / 来源级 SourceJob / Matching 记录
|
||||
(scope / file_snapshot / counts / Hash)。不再做「解析→upsert→消失行标记」
|
||||
——消失行标记(blocked_file_removed)归 evidence_sync;行归属 matching_id
|
||||
保持首次创建值(原地刷新语义),重复匹配不迁移、不累加行。
|
||||
|
||||
Args:
|
||||
source_codes / business_date / deps: 同 run_matching。
|
||||
@@ -598,106 +695,7 @@ def create_matching(
|
||||
)
|
||||
db.session.add(matching)
|
||||
db.session.flush()
|
||||
|
||||
# [幂等·原地刷新] 相同 (来源,单号,料号,收料日期) 的重复匹配不得累加异常行:
|
||||
# 非终态行在原地刷新业务值(不迁移 matching_id 归属),并显式续 updated_at
|
||||
# 新鲜度(同值写入不触发 onupdate);终态行(已执行/人工关闭等)保持既定事实
|
||||
# 不复活。行是否仍有效由文件版本戳 + 消失行标记判定(见循环后标记段)。
|
||||
_terminal_item_statuses = {
|
||||
status_machine.TransferStatus.SUCCESS.value,
|
||||
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
|
||||
status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||
status_machine.TransferStatus.CANCELLED.value,
|
||||
status_machine.TransferStatus.EXECUTING.value,
|
||||
}
|
||||
# 文件版本戳与 file_snapshot 同源:本次评估各行所用的收料文件 checksum。
|
||||
source_checksums = {
|
||||
stage.source_code: stage.checksum
|
||||
for stage in result.sources
|
||||
if stage.checksum
|
||||
}
|
||||
for item in result.items:
|
||||
fields = {
|
||||
"status": _item_status(item.result),
|
||||
"result_code": item.result if item.result != RESULT_EXECUTABLE else None,
|
||||
"result_message": item.reason or None,
|
||||
"from_warehouse": item.from_warehouse or "",
|
||||
"to_warehouse": item.to_warehouse or "",
|
||||
"receipt_quantity": str(item.to_quantity),
|
||||
"external_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"lot_no": item.lot_no or "",
|
||||
"receipt_warehouse_code": item.receipt_warehouse_code or "",
|
||||
"raw_lines_json": [
|
||||
{
|
||||
"sheet": line.sheet,
|
||||
"row_no": line.row_no,
|
||||
"file_version": line.file_version,
|
||||
# 文件版本戳:Task 2/3 文件对账与消失行标记的判定依据。
|
||||
"file_sha256": source_checksums.get(item.source_code),
|
||||
}
|
||||
for line in item.raw_lines
|
||||
],
|
||||
}
|
||||
# 禁 autoflush:避免本批 pending 插入在查询时提前落库(应随循环末统一 commit)。
|
||||
with db.session.no_autoflush:
|
||||
existing = (
|
||||
TransferInvoiceItem.query.filter_by(
|
||||
source_code=item.source_code,
|
||||
invoice_no=item.invoice_no,
|
||||
material_no=item.material_no,
|
||||
receipt_date=item.receipt_date,
|
||||
)
|
||||
.order_by(TransferInvoiceItem.id.desc())
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
if existing.status not in _terminal_item_statuses:
|
||||
for attr, value in fields.items():
|
||||
setattr(existing, attr, value)
|
||||
# 行不迁移归属(matching_id 保持首次创建值);显式续新鲜度,
|
||||
# 否则"同值刷新"不触发 onupdate、行看似陈旧。
|
||||
existing.updated_at = now
|
||||
continue
|
||||
# 匹配阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
|
||||
db.session.add(TransferInvoiceItem(
|
||||
matching_id=matching.id,
|
||||
source_code=item.source_code,
|
||||
invoice_no=item.invoice_no,
|
||||
material_no=item.material_no,
|
||||
material_name=item.material_name,
|
||||
specification=item.specification,
|
||||
receipt_date=item.receipt_date,
|
||||
**fields,
|
||||
))
|
||||
|
||||
# [消失行标记] 对每个有文件的 source:上一版本评估为可执行、本次文件版本
|
||||
# 已变化且行消失(或内容变化导致版本不同)的 ready 行,停用为
|
||||
# blocked_file_removed——防止按过期文件数据执行。只标 ready 行(blocked 行
|
||||
# 已有终局解释,覆盖会丢失真实原因);无版本戳的存量行跳过(fail-safe)。
|
||||
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
blocked_status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
for stage in result.sources:
|
||||
checksum = source_checksums.get(stage.source_code)
|
||||
if not checksum:
|
||||
continue
|
||||
query = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.source_code == stage.source_code,
|
||||
TransferInvoiceItem.status == ready_status,
|
||||
)
|
||||
# 仅标记本次匹配收料日期范围内的行(范围外行不属于本次评估口径)。
|
||||
if receipt_date_from:
|
||||
query = query.filter(TransferInvoiceItem.receipt_date >= receipt_date_from)
|
||||
if receipt_date_to:
|
||||
query = query.filter(TransferInvoiceItem.receipt_date <= receipt_date_to)
|
||||
with db.session.no_autoflush:
|
||||
candidates = query.all()
|
||||
for row in candidates:
|
||||
evaluated_sha = _item_evaluated_sha(row)
|
||||
if evaluated_sha is None or evaluated_sha == checksum:
|
||||
continue
|
||||
row.status = blocked_status
|
||||
row.result_code = RESULT_FILE_REMOVED
|
||||
row.result_message = "receipt row removed from latest file"
|
||||
# 留痕提交:行落位随本事务一并持久化(run_matching 只写不提交)。
|
||||
db.session.commit()
|
||||
|
||||
summary = MatchingSummaryDTO(
|
||||
@@ -724,7 +722,9 @@ def restore_matching(
|
||||
|
||||
匹配卡是 scope 的实时视图:明细不读 matching.items 行归属关系(行归属与
|
||||
匹配解耦后,"这份匹配覆盖哪些行"由 scope 重新圈定),counts 亦按 scope 行
|
||||
实时聚合;estimated_* 与 expires_at / matching_hash 沿用匹配记录留痕展示。
|
||||
实时聚合;blocked_file_removed 行不进明细与常规 counts(只计入
|
||||
counts.invalid_count,2026-09-25);estimated_* 与 expires_at /
|
||||
matching_hash 沿用匹配记录留痕展示。
|
||||
|
||||
Args:
|
||||
matching_id: 匹配编号(MTG-...)。
|
||||
@@ -752,11 +752,17 @@ def restore_matching(
|
||||
|
||||
# [STEP 1] 按 scope 实时圈行(来源 + 收料日期区间 + 调拨类型前缀),行归属
|
||||
# (matching_id)不参与——同一批行可被多份同 scope 匹配同时看到。
|
||||
rows = (
|
||||
rows_all = (
|
||||
scope_item_query(matching)
|
||||
.order_by(TransferInvoiceItem.invoice_no.asc(), TransferInvoiceItem.id.asc())
|
||||
.all()
|
||||
)
|
||||
# [失效行分层]【2026-09-25】blocked_file_removed 行已出清:不进明细与常规
|
||||
# counts(与 _matching_rows 圈行口径一致),只计入 invalid_count。
|
||||
from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING
|
||||
|
||||
invalid_rows = [row for row in rows_all if row.result_code == RESULT_FILE_REMOVED]
|
||||
rows = [row for row in rows_all if row.result_code != RESULT_FILE_REMOVED]
|
||||
|
||||
# [STEP 2] 文件对账映射:scope 内去重来源逐个投影当前可用文件版本,
|
||||
# 行评估版本戳与之比对得 file_current(来源无可用文件 → False)。
|
||||
@@ -766,7 +772,8 @@ def restore_matching(
|
||||
}
|
||||
|
||||
# [STEP 3] counts 按 scope 行实时聚合(行归属不参与)。
|
||||
# matched_count 为"未成熟以外"的可用总数(与 run_matching 语义一致)。
|
||||
# matched_count 为"未成熟以外"的可用总数(与 run_matching 语义一致);
|
||||
# pending/invalid 两桶为 2026-09-25 counts 契约扩展(同口径内存计算)。
|
||||
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
blocked_status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
not_matured_status = status_machine.TransferStatus.NOT_MATURED.value
|
||||
@@ -777,6 +784,12 @@ def restore_matching(
|
||||
matched_count=len(rows) - not_matured_count,
|
||||
executable_count=sum(1 for row in rows if row.status == ready_status),
|
||||
blocked_count=sum(1 for row in rows if row.status == blocked_status),
|
||||
pending_stock_check_count=sum(
|
||||
1 for row in rows
|
||||
if row.status == status_machine.TransferStatus.MATCHING.value
|
||||
and row.result_code == SYNC_RESULT_PENDING
|
||||
),
|
||||
invalid_count=len(invalid_rows),
|
||||
)
|
||||
summary = MatchingSummaryDTO(
|
||||
matching_id=matching.matching_no,
|
||||
@@ -852,7 +865,7 @@ def scope_item_query(matching: TransferMatching):
|
||||
*(func.upper(TransferInvoiceItem.invoice_no).like(f"{prefix}%") for prefix in prefixes),
|
||||
))
|
||||
else:
|
||||
# 占位类型范围外无任何票(与 invoice_in_scope 恒 False 同口径)。
|
||||
# 占位类型范围外无任何单(与 invoice_in_scope 恒 False 同口径)。
|
||||
query = query.filter(false())
|
||||
return query
|
||||
|
||||
@@ -869,7 +882,8 @@ def _item_dto(
|
||||
item: 明细行。
|
||||
latest: 该行来源当前可用文件状态投影(resolve_source_file_status 结果)。
|
||||
moment: 新鲜度判定基准时间。
|
||||
ttl_seconds: 行级新鲜度 TTL(strategy.confirm_ttl_seconds)。
|
||||
ttl_seconds: 行级 stale 展示阈值(strategy.confirm_ttl_seconds;仅驱动
|
||||
stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。
|
||||
Returns:
|
||||
MatchingItemDTO(含 item_id / checked_at / stale / file_current)。
|
||||
"""
|
||||
@@ -884,6 +898,9 @@ def _item_dto(
|
||||
receipt_date=item.receipt_date,
|
||||
lot_no=item.lot_no or "",
|
||||
receipt_warehouse_code=item.receipt_warehouse_code or "",
|
||||
# 交易单位原值(movement 契约第 11 字段):restore/明细队列视图与
|
||||
# 序列化(serializers)均已透传(T11 接线完成)。
|
||||
unit=item.unit or "",
|
||||
from_warehouse=item.from_warehouse,
|
||||
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
||||
to_warehouse=item.to_warehouse,
|
||||
@@ -902,9 +919,12 @@ def _item_dto(
|
||||
)
|
||||
for line in (item.raw_lines_json or [])
|
||||
),
|
||||
# [行装饰] 行级新鲜度与文件对账(实时视图判定依据):
|
||||
# stale=距上次评估超过确认 TTL;file_current=行评估版本戳仍是该来源
|
||||
# 当前可用文件 sha(无版本戳或无可用文件均视为不一致 → False)。
|
||||
# [行装饰] 行级新鲜度与文件对账(均纯展示,不阻断执行):
|
||||
# [2026-09-25 TTL 退役] stale 仅是「库存数据已过期,请重查」展示徽标
|
||||
# (原 TTL 执行门禁已删除,防错由文件版本对账 + worker 写前库存复查
|
||||
# 承担):stale=距上次评估超过展示阈值(confirm_ttl_seconds);
|
||||
# file_current=行评估版本戳仍是该来源当前可用文件 sha
|
||||
# (无版本戳或无可用文件均视为不一致 → False)。
|
||||
item_id=item.id,
|
||||
checked_at=updated_at.isoformat() if updated_at else None,
|
||||
stale=bool(updated_at) and (moment - updated_at).total_seconds() > ttl_seconds,
|
||||
|
||||
@@ -40,9 +40,14 @@ class MovementField:
|
||||
required: bool = False
|
||||
|
||||
|
||||
# 定死的 10 个通用异动字段(领域契约,不配置化)。
|
||||
# 定死的 11 个通用异动字段(领域契约,不配置化)。
|
||||
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 收料单号);
|
||||
# 批号(lot_no)为展示维度——匹配列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
|
||||
# [PROMPT_UPDATE] 2026-09-25:WTP→HOW 派生收敛为 external_lot_no() 唯一实现——
|
||||
# 库存查询 / 建单下传 / 单行聚合 / 展示统一按外部形态;落库保持文件原形态(证据原则)。
|
||||
# [PROMPT_UPDATE] 2026-09-24:追加第 11 字段 unit(交易单位,计划 D4)——ERP 写入
|
||||
# 行必填(gls_cm19),但解析层放行空值(不产生解析失败),空值由匹配阶段行级
|
||||
# blocked_missing_unit 阻断;unit 不参与幂等/匹配,也不进匹配 Hash 快照(口径冻结)。
|
||||
MOVEMENT_FIELDS: tuple[MovementField, ...] = (
|
||||
MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True),
|
||||
MovementField("line_no", "项次", MovementFieldValueType.TEXT),
|
||||
@@ -54,6 +59,7 @@ MOVEMENT_FIELDS: tuple[MovementField, ...] = (
|
||||
MovementField("lot_no", "批号", MovementFieldValueType.TEXT),
|
||||
MovementField("quantity", "数量", MovementFieldValueType.DECIMAL, required=True),
|
||||
MovementField("movement_date", "异动日期", MovementFieldValueType.DATE, is_identity=True, required=True),
|
||||
MovementField("unit", "单位", MovementFieldValueType.TEXT),
|
||||
)
|
||||
|
||||
|
||||
@@ -75,3 +81,25 @@ def movement_identity_fields() -> set[str]:
|
||||
def movement_field_codes() -> set[str]:
|
||||
"""全部定死字段名集合。"""
|
||||
return {field.code for field in MOVEMENT_FIELDS}
|
||||
|
||||
|
||||
def external_lot_no(lot_no: str | None) -> str:
|
||||
"""批号外部形态派生:WMS 批号 WTP 前缀 → 外部系统真实批号 HOW 前缀。
|
||||
|
||||
【AI 触发时机】任何把行上 lot_no 发往外部系统的场景——库存查询 targets、
|
||||
写前库存复查、建单单行——组装参数前必须经本函数转换;单行聚合键与展示列
|
||||
「拨出/拨入批号」同规则(前端 features/chat/components/messages/transferBatch.ts
|
||||
deriveBatchNo 为本函数的展示侧镜像,改动须双侧同步)。行上落库值保持文件
|
||||
原形态(证据原则:raw_lines 对账/审计复算以文件为准),转换只发生在外部
|
||||
系统边界。
|
||||
|
||||
Args:
|
||||
lot_no: 行上批号原值(文件证据形态;None/空白按空串处理)。
|
||||
Returns:
|
||||
外部系统批号形态:WTP 前缀识别大小写不敏感,余串逐字保留;
|
||||
非 WTP 前缀原样返回;空输入返回空串。
|
||||
"""
|
||||
value = str(lot_no or "").strip()
|
||||
if value.upper().startswith("WTP"):
|
||||
return f"HOW{value[3:]}"
|
||||
return value
|
||||
@@ -1,10 +1,11 @@
|
||||
"""在途调拨执行编排(Run 生命周期辅助)。
|
||||
|
||||
用途:按选中明细行创建执行 Run(置 executing、记录业务日/来源范围/行计数)、
|
||||
用途:按选中明细行创建执行 Run(初始态 queued、记录业务日/来源范围/行计数)、
|
||||
按明细终态收尾 Run(success / partial_failed)。
|
||||
依赖:models、status、date_policy、matching_service(编号生成/TransferDeps)。
|
||||
逻辑:执行 Run 与匹配解耦(不回写 matching.run_id / confirmed_at);行归属
|
||||
由调用方按 scope 圈定(见 matching_service.scope_item_query)后显式传入,
|
||||
逻辑:执行 Run 与匹配解耦(不回写 matching.run_id / confirmed_at);D8 异步拆分后
|
||||
Run 初始态为 queued(prepare 段只建 Run+关联行+建单,worker 段置 executing);
|
||||
行归属由调用方按 scope 圈定(见 matching_service.scope_item_query)后显式传入,
|
||||
本模块只负责"建 Run + 关联选中行",已关联(run_id 非空)的行跳过。
|
||||
"""
|
||||
|
||||
@@ -28,13 +29,16 @@ def create_execution_run_for_items(
|
||||
) -> TransferRun:
|
||||
"""为选中可执行明细行创建执行 Run 并关联(行级执行,不绑定匹配)。
|
||||
|
||||
D8 异步拆分:Run 初始态为 queued——API 同步段(prepare_execution)只建 Run、
|
||||
关联行并组建单,worker 段(execute_run)领取后置 executing。
|
||||
|
||||
Args:
|
||||
items: 候选明细行(调用方已完成可执行校验,见 execution_service.execute_items)。
|
||||
deps: 依赖集合(预留)。
|
||||
actor_id: 触发执行的用户(写入 run.created_by 留痕)。
|
||||
selected_item_ids: 关联范围(行 id 集;缺省关联 items 中全部可执行未关联行)。
|
||||
Returns:
|
||||
状态为 executing 的 TransferRun(run_no/business_date 取当前业务日)。
|
||||
状态为 queued 的 TransferRun(run_no/business_date 取当前业务日)。
|
||||
"""
|
||||
selected = selected_item_ids if selected_item_ids is not None else None
|
||||
business_date = str(business_date_now())
|
||||
@@ -49,7 +53,8 @@ def create_execution_run_for_items(
|
||||
run_no=_generate_no("RUN", business_date),
|
||||
trigger_type="manual",
|
||||
business_date=business_date,
|
||||
status=status_machine.TransferRunStatus.EXECUTING.value,
|
||||
# D8 异步拆分:初始态 queued(API 同步段毫秒级返回,worker 领取后置 executing)。
|
||||
status=status_machine.TransferRunStatus.QUEUED.value,
|
||||
source_codes_json=sorted({item.source_code for item in candidates}),
|
||||
counts_json={
|
||||
"file_invoice_count": len(candidates),
|
||||
|
||||
@@ -4,7 +4,14 @@
|
||||
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
|
||||
依赖:models、capability_client、quantity、status、audit、matching_service.TransferDeps。
|
||||
逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断;
|
||||
重查即续新鲜度——每次重检显式刷新行 updated_at(执行门禁行级 TTL 的续期机制)。
|
||||
重查即续新鲜度——每次重检显式刷新行 updated_at(执行门禁行级 TTL 的续期机制);
|
||||
重查前置兜底对齐(STEP 0,同 run_matching):两个批量重查入口先 align_scope_rows
|
||||
补救落地同步失败/迟到的证据,再圈行重查(待处理池后门不得基于过期证据作答);
|
||||
file_removed 失效行不可重查:匹配号圈行路径由 scope 谓词排除,按 id 直取与
|
||||
单行入口由 retry_item 的 result_code 兜底拒绝(拒绝逻辑单点闭环,消失证据
|
||||
不可用旧库存翻回可执行);
|
||||
交易单位唯一来源=ERP 库存行 stock_unit(img09):重查命中且数量一致但 ERP
|
||||
未给单位 → blocked_missing_unit(不落 ready,单位不得以文件值顶替)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,18 +21,27 @@ import uuid
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import TransferAttempt, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.capability_client import StockTarget
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.evidence_sync import align_scope_rows
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
RESULT_EXTERNAL_QUERY_FAILED,
|
||||
RESULT_EXECUTABLE,
|
||||
RESULT_FILE_REMOVED,
|
||||
RESULT_MISSING_UNIT,
|
||||
TransferDeps,
|
||||
scope_item_query,
|
||||
)
|
||||
from app.services.in_transit_transfer.movement_contract import external_lot_no
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.serializers import DOCUMENT_STATUS_GROUPS
|
||||
|
||||
RETRY_KIND_EXTERNAL_RECHECK = "external_recheck"
|
||||
RETRY_KIND_RPA_REFETCH = "rpa_refetch"
|
||||
@@ -50,6 +66,12 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
# [口径] 重查按当前路由配置发查询,行上仓库字段同步刷新为本次解析值——
|
||||
# 查询与后续执行写路径必须用同一仓库值:行上旧值可能来自更早配置(路由
|
||||
# 已漂移),也可能为空(如 blocked_missing_unit 行在路由解析前被阻断)。
|
||||
if (item.from_warehouse or "") != route.from_warehouse or (item.to_warehouse or "") != route.to_warehouse:
|
||||
item.from_warehouse = route.from_warehouse
|
||||
item.to_warehouse = route.to_warehouse
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
receipt_qty = Decimal(item.receipt_quantity)
|
||||
item.attempt_no += 1
|
||||
@@ -65,19 +87,23 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.flush()
|
||||
# [降级] 与 matching 逐票语义一致:外部系统网关/绑定故障(如集成连接器缺绑定
|
||||
# [降级] 与 matching 逐单语义一致:外部系统网关/绑定故障(如集成连接器缺绑定
|
||||
# BindingNotFoundError)记为该行 blocked_external_query_failed + 原因,
|
||||
# 不中断批量重查、不向调用方抛基础设施异常(避免全局错误弹窗)。
|
||||
try:
|
||||
# [外部形态] 查询目标与回查同用 WTP→HOW 派生批号(movement_contract.external_lot_no)。
|
||||
stock = deps.capabilities.query_stock(
|
||||
operation_id=operation_id, external_org=route.external_org,
|
||||
targets=[StockTarget(
|
||||
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
|
||||
material_no=item.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(item.lot_no),
|
||||
)],
|
||||
)
|
||||
stock_qty = stock.lookup(
|
||||
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
|
||||
stock_row = stock.lookup_row(
|
||||
material_no=item.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(item.lot_no),
|
||||
)
|
||||
stock_qty = stock_row.quantity if stock_row is not None else None
|
||||
except Exception as exc: # noqa: BLE001
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
# 降级只落 DB(result_message/审计),若再无应用日志,控制台侧完全无痕可查。
|
||||
@@ -118,11 +144,22 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
|
||||
# 不得显示"-"让用户误以为查询失败。
|
||||
item.external_quantity = str(stock_qty) if stock_qty is not None else "0"
|
||||
attempt.status = "failed"
|
||||
elif not (stock_row.stock_unit or "").strip():
|
||||
# [单位只取 ERP] 数量一致但 ERP 未返回单位(img09 契约恒非空,出现即 ERP
|
||||
# 侧数据异常)→ blocked_missing_unit,禁止落 ready、禁止以文件单位顶替;
|
||||
# 行仓库已刷新为本次路由解析值(可解释、可再重查)。
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = RESULT_MISSING_UNIT
|
||||
item.result_message = "external inventory unit is missing"
|
||||
item.external_quantity = str(stock_qty)
|
||||
item.unit = ""
|
||||
attempt.status = "failed"
|
||||
else:
|
||||
item.status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
item.result_code = None
|
||||
item.result_message = None
|
||||
item.external_quantity = str(stock_qty)
|
||||
item.unit = (stock_row.stock_unit or "").strip()
|
||||
attempt.status = "success"
|
||||
attempt.completed_at = datetime.utcnow()
|
||||
# [行级 TTL 续期] 重查即续新鲜度:状态落定后显式刷新 updated_at(执行门禁
|
||||
@@ -159,7 +196,10 @@ def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTER
|
||||
Returns:
|
||||
{"item_id": ..., "status": ..., "attempt_no": ...}。
|
||||
Raises:
|
||||
ValidationError: 状态不可重试 / 重试类型不允许 / result_unknown 只读。
|
||||
ValidationError: 状态不可重试 / 重试类型不允许 / result_unknown 只读 /
|
||||
file_removed 行不可重查(消失证据不可恢复:证据行的源单已从最新
|
||||
收料文件中消失,重查只会用外部系统旧库存把行翻回可执行,唯一出口
|
||||
= 人工关闭 / 等重新同步恢复)。
|
||||
NotFoundError: item 不存在。
|
||||
"""
|
||||
kind_value = str(kind or "").strip()
|
||||
@@ -174,6 +214,16 @@ def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTER
|
||||
raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN")
|
||||
if item.status not in _RETRYABLE_STATUSES:
|
||||
raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED")
|
||||
# [兜底] file_removed 行拒绝重查:匹配号圈行路径(requery_items)已在 scope
|
||||
# 谓词排除失效行,但按 id 直取(requery_items_by_ids 循环)与单行入口都绕过
|
||||
# 该谓词——拒绝逻辑只落在此单点,三条入口同时闭环。为什么拒绝:消失证据
|
||||
# 不可恢复,重查会用外部系统旧库存把行翻回可执行(虚假放行),唯一出口
|
||||
# = 人工关闭 / 等重新同步恢复该行。
|
||||
if item.result_code == RESULT_FILE_REMOVED:
|
||||
raise ValidationError(
|
||||
"removed rows cannot be requeried; close manually or wait for re-sync",
|
||||
code="TRANSFER.RETRY_NOT_ALLOWED",
|
||||
)
|
||||
|
||||
status = _recheck_item(item, deps=deps, request_id=request_id)
|
||||
db.session.commit()
|
||||
@@ -201,6 +251,18 @@ def requery_items_by_ids(
|
||||
ids = [int(x) for x in (item_ids or []) if x is not None]
|
||||
if not ids:
|
||||
raise ValidationError("item_ids is required", code="TRANSFER.BATCH_ITEMS_REQUIRED")
|
||||
# [口径] 受影响来源=按 id 查回行的 source_code 去重(先查行→对齐→再重查)。
|
||||
source_rows = (
|
||||
db.session.query(TransferInvoiceItem.source_code)
|
||||
.filter(TransferInvoiceItem.id.in_(ids))
|
||||
.all()
|
||||
)
|
||||
affected_sources = sorted({(code or "").strip() for (code,) in source_rows})
|
||||
# [兜底对齐] 落地同步失败/迟到的静默补救:重查前先保证行对齐最新文件。
|
||||
# 对齐可能重写行集(证据变化重置回待查、消失行复现恢复),必须先于任何
|
||||
# 重查读取执行,否则待处理池后门会基于过期证据放行旧库存。
|
||||
align_scope_rows(source_codes=affected_sources, deps=deps,
|
||||
business_date=str(business_date_now()), now=datetime.utcnow())
|
||||
results: list[dict] = []
|
||||
for item_id in ids:
|
||||
try:
|
||||
@@ -223,12 +285,17 @@ def requery_items_by_ids(
|
||||
|
||||
def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""批量重查 外部系统 库存:对同一匹配下全部/指定的可重查行(可恢复阻断 + 可执行)逐票重查并刷新。
|
||||
"""批量重查 外部系统 库存:按匹配 scope 圈定全部/指定的可重查行逐单重查并刷新。
|
||||
|
||||
圈行口径与匹配卡实时视图同源(scope_item_query:来源+收料日期区间+调拨类型),
|
||||
行归属 matching_id 不参与——行归属解耦后行不随匹配迁移,视图能看到的历史行
|
||||
(matching_id 指向旧匹配)必须同样可被本次匹配的重查触达,否则出现「卡片提示
|
||||
重查、重查却查不到行」的死锁(2026-09-24 修复)。
|
||||
|
||||
Args:
|
||||
matching_no: 匹配编号(定位明细集合)。
|
||||
matching_no: 匹配编号(经 scope_json 圈定行集)。
|
||||
deps: 注入依赖(capabilities = 外部系统网关客户端)。
|
||||
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该匹配全部可重查行。
|
||||
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该 scope 全部可重查行。
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
{"matching_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
|
||||
@@ -239,9 +306,27 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str
|
||||
matching = TransferMatching.query.filter_by(matching_no=matching_no).first()
|
||||
if matching is None:
|
||||
raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND")
|
||||
query = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.matching_id == matching.id,
|
||||
TransferInvoiceItem.status.in_(_RETRYABLE_STATUSES),
|
||||
# [口径一致] 受影响来源=scope_json 的 source_codes(与 scope_item_query 圈行同源,
|
||||
# 提取口径同 matching_service.scope_item_query:非 dict 视为空 scope)。
|
||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||
affected_sources = sorted({str(code) for code in (scope.get("source_codes") or [])})
|
||||
# [兜底对齐] 落地同步失败/迟到的静默补救:重查前先保证行对齐最新文件。
|
||||
# 对齐可能重写行集(证据变化重置回待查、消失行复现恢复),必须先于 scope
|
||||
# 圈行执行,否则重查会圈到过期行、基于过期证据放行旧库存。
|
||||
align_scope_rows(source_codes=affected_sources, deps=deps,
|
||||
business_date=str(business_date_now()), now=datetime.utcnow())
|
||||
# [口径统一] 圈行必须与匹配卡视图同谓词(scope:来源+日期区间+类型前缀)——
|
||||
# 行归属解耦后 matching_id 停留在首次创建值,按它圈行会漏掉全部存量行。
|
||||
# file_removed 行排除:消失证据不可重查恢复(唯一出口=人工关闭/出清)。
|
||||
query = (
|
||||
scope_item_query(matching)
|
||||
.filter(
|
||||
TransferInvoiceItem.status.in_(_RETRYABLE_STATUSES),
|
||||
or_(
|
||||
TransferInvoiceItem.result_code.is_(None),
|
||||
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED,
|
||||
),
|
||||
)
|
||||
)
|
||||
wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()]
|
||||
if wanted:
|
||||
@@ -268,3 +353,106 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str
|
||||
"ok": False,
|
||||
"error": str(exc).strip() or exc.__class__.__name__})
|
||||
return {"matching_no": matching_no, "total": len(items), "results": results}
|
||||
|
||||
|
||||
def retry_document(
|
||||
*, doc_no: str, deps: TransferDeps,
|
||||
actor_id: int | None = None, request_id: str | None = None,
|
||||
) -> dict:
|
||||
"""调拨单级重试(失败单一键恢复,主路径):圈单内行 → 逐行重查 → 全 ready 自动重跑。
|
||||
|
||||
【AI 触发时机】:用户在失败调拨单上点「重试」——替代旧的单据级重查(其按
|
||||
可执行池关联行,对 blocked 行必报"未能关联");本函数按单圈行(单是行权威
|
||||
归属),不依赖前端跨池拼 item_id。
|
||||
|
||||
核心逻辑:[STEP 1] 状态门禁——仅 failed 族(business/technical_failed)可重试;
|
||||
result_unknown 唯一出口=重新触发(D11),pending/executing 在飞拒绝,终态拒绝。
|
||||
[STEP 2] 单内 blocked 行逐行重查(复用 retry_item:单行隔离、file_removed 拒绝、
|
||||
每行落 Attempt);ready 行原样保留。 [STEP 3] 全部行 ready → 自动建新 Run 重跑
|
||||
(prepare_execution:门禁②文件对账 + D7①分支②复用原单号,写前复查兜底);
|
||||
任一行仍阻断 → 不重跑(单是原子单位,缺行不跑),阻断明细原样返回由池子兜底。
|
||||
|
||||
Args:
|
||||
doc_no: TransferDocument.doc_no。
|
||||
deps / actor_id / request_id: 同 retry_item。
|
||||
Returns:
|
||||
{"doc_no", "rerun": bool, "run_no": str|None,
|
||||
"ready": int, "blocked": [{invoice_no, item_id, reason}], "total": int}。
|
||||
Raises:
|
||||
NotFoundError: 单不存在。
|
||||
ValidationError: 状态不允许重试。
|
||||
"""
|
||||
from app.models import TransferDocument
|
||||
|
||||
doc = TransferDocument.query.filter_by(doc_no=str(doc_no).strip()).first()
|
||||
if doc is None:
|
||||
raise NotFoundError("transfer document not found", code="TRANSFER.DOCUMENT_NOT_FOUND")
|
||||
if doc.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
|
||||
raise ValidationError(
|
||||
"result_unknown is read-only; use retrigger (D11)",
|
||||
code="TRANSFER.DOCUMENT_RETRY_NOT_ALLOWED",
|
||||
)
|
||||
if doc.status not in DOCUMENT_STATUS_GROUPS["failed"]:
|
||||
raise ValidationError(
|
||||
f"document status {doc.status} is not retryable",
|
||||
code="TRANSFER.DOCUMENT_RETRY_NOT_ALLOWED",
|
||||
)
|
||||
|
||||
items = list(doc.items)
|
||||
if not items:
|
||||
raise ValidationError(
|
||||
"document has no attached items", code="TRANSFER.DOCUMENT_RETRY_NOT_ALLOWED",
|
||||
)
|
||||
|
||||
# [STEP 2] 单内 blocked 行逐行重查(行级隔离,单行失败不炸整单)。
|
||||
for item in items:
|
||||
if item.status != status_machine.TransferStatus.BLOCKED_RECOVERABLE.value:
|
||||
continue
|
||||
try:
|
||||
retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK,
|
||||
actor_id=actor_id, request_id=request_id)
|
||||
except (ValidationError, NotFoundError):
|
||||
# file_removed 等拒绝语义:行保持阻断,原因随结果返回。
|
||||
continue
|
||||
|
||||
for item in items:
|
||||
db.session.expire(item)
|
||||
ready_ids = [item.id for item in items
|
||||
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value]
|
||||
blocked = [
|
||||
{"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"reason": item.result_message or item.result_code or ""}
|
||||
for item in items
|
||||
if item.status != status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
]
|
||||
|
||||
# [STEP 3] 全 ready → 自动重跑;缺行不跑(单是原子单位)。
|
||||
rerun = bool(ready_ids) and not blocked
|
||||
run_no = None
|
||||
if rerun:
|
||||
from app.services.in_transit_transfer.execution_service import prepare_execution
|
||||
|
||||
outcome = prepare_execution(
|
||||
item_ids=ready_ids, deps=deps, actor_id=actor_id, request_id=request_id,
|
||||
# 链内新鲜事实豁免:重查(恢复判定)刚完成,重跑豁免写前复查。
|
||||
skip_write_recheck=True,
|
||||
)
|
||||
run_no = outcome.run_no
|
||||
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_DOCUMENT_RETRIED",
|
||||
aggregate_type="transfer_document",
|
||||
aggregate_id=doc.doc_no,
|
||||
run_no=run_no,
|
||||
actor_type="user",
|
||||
actor_id=str(actor_id) if actor_id else None,
|
||||
request_id=request_id,
|
||||
result="success" if rerun else "failure",
|
||||
before={"status": doc.status},
|
||||
after={"ready": len(ready_ids), "blocked": len(blocked), "rerun": rerun},
|
||||
))
|
||||
db.session.commit()
|
||||
return {
|
||||
"doc_no": doc.doc_no, "rerun": rerun, "run_no": run_no,
|
||||
"ready": len(ready_ids), "blocked": blocked, "total": len(items),
|
||||
}
|
||||
@@ -1,15 +1,38 @@
|
||||
"""在途调拨 DTO 序列化(API 与 Chat Action 共用)。
|
||||
|
||||
用途:将领域 DTO 转为前端稳定 JSON(匹配摘要/明细/来源进度/执行结果)。
|
||||
依赖:contracts、execution_service。
|
||||
逻辑:单一序列化来源,避免 API 与 Chat Action 各自实现导致契约漂移。
|
||||
用途:将领域 DTO 转为前端稳定 JSON(匹配摘要/明细/来源进度/执行结果/单投影)。
|
||||
依赖:contracts、execution_service(serialize_order 内按需延迟引用其行聚合,
|
||||
避免模块级循环导入:execution_service 顶层引用本模块的 serialize_order)。
|
||||
逻辑:单一序列化来源,避免 API 与 Chat Action 各自实现导致契约漂移;
|
||||
单(TransferDocument)投影经 serialize_order 统一(Task 11 融合卡调拨单清单
|
||||
与 Task 17 已执行单查询共用同一契约源)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.in_transit_transfer.execution_service import serialize_run_result
|
||||
from app.services.in_transit_transfer.movement_contract import external_lot_no
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 单状态 → 展示分组映射(Task 17:首页「已执行」区块统计口径)
|
||||
# ---------------------------------------------------------------------------
|
||||
# success=累计产出(含重复提交成功);failed/executing/result_unknown=未完结即待办;
|
||||
# cancelled 不展示(无产生路径,且不在任何分组计数中)。
|
||||
DOCUMENT_STATUS_GROUPS: dict[str, tuple[str, ...]] = {
|
||||
"success": ("success", "duplicate_success"),
|
||||
"failed": ("business_failed", "technical_failed"),
|
||||
"executing": ("pending", "executing"),
|
||||
"result_unknown": ("result_unknown",),
|
||||
}
|
||||
|
||||
|
||||
def order_status_group(status: str) -> str | None:
|
||||
"""单状态 → 展示分组键;组外状态(cancelled)返回 None(不展示)。"""
|
||||
for group, statuses in DOCUMENT_STATUS_GROUPS.items():
|
||||
if status in statuses:
|
||||
return group
|
||||
return None
|
||||
|
||||
|
||||
def serialize_summary(summary) -> dict[str, Any]:
|
||||
@@ -26,6 +49,10 @@ def serialize_summary(summary) -> dict[str, Any]:
|
||||
"matched_count": summary.counts.matched_count,
|
||||
"executable_count": summary.counts.executable_count,
|
||||
"blocked_count": summary.counts.blocked_count,
|
||||
# 待查行(文件已落地未查库存)与失效行(blocked_file_removed)透传
|
||||
# (2026-09-25 counts 契约扩展,键名与 DTO 字段同名)。
|
||||
"pending_stock_check_count": summary.counts.pending_stock_check_count,
|
||||
"invalid_count": summary.counts.invalid_count,
|
||||
},
|
||||
"estimated_transfer_quantity": summary.estimated_transfer_quantity,
|
||||
"estimated_external_write_count": summary.estimated_external_write_count,
|
||||
@@ -52,6 +79,8 @@ def serialize_item(item) -> dict[str, Any]:
|
||||
"from_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"to_warehouse": item.to_warehouse,
|
||||
"to_quantity": str(item.to_quantity),
|
||||
# 交易单位原值透传(movement 契约第 11 字段 unit,T7 交接:序列化缺口补齐)。
|
||||
"unit": item.unit,
|
||||
"result": item.result,
|
||||
"reason": item.reason,
|
||||
"raw_lines": [
|
||||
@@ -85,3 +114,113 @@ def serialize_matching_detail(detail: dict[str, Any]) -> dict[str, Any]:
|
||||
"items": [serialize_item(item) for item in detail["items"]],
|
||||
"sources": [serialize_source(source) for source in detail["sources"]],
|
||||
}
|
||||
|
||||
|
||||
def serialize_order(doc, items: list) -> dict[str, Any]:
|
||||
"""单投影公共序列化(Task 11 融合卡调拨单清单与 Task 17 已执行单查询共用契约源)。
|
||||
|
||||
【AI 触发时机】:任何需要把一张 TransferDocument(单)转成前端 JSON 的场景
|
||||
(GET /runs/{run_no} 的 orders 数组、GET /documents 的单行),禁止再各自拼装。
|
||||
|
||||
核心逻辑:[STEP 1] 行集按 ERP 行粒度(物料+批号+拨出/拨入库位)聚合,数量
|
||||
Decimal 相加取 6 位小数字符串(D14 快照口径),unit/material_name 取组内首个
|
||||
非空原值;[STEP 2] 行级 reason 契约(T13-3):键恒出现——失败/未知行=组内
|
||||
首个非空行级 result_message,成功行/无原因为 None(前端按
|
||||
「reason ?? 单 error_message」展示)。
|
||||
|
||||
Args:
|
||||
doc: TransferDocument ORM 实例。
|
||||
items: 单挂接行集(TransferInvoiceItem 列表,调用方保证顺序)。
|
||||
|
||||
Returns:
|
||||
单投影 dict(8 键):{doc_no, receipt_date, from_warehouse, to_warehouse,
|
||||
status, erp_document_no, error_message, lines}。
|
||||
"""
|
||||
# 延迟引用 execution_service 的行聚合(模块级互相引用会循环导入;
|
||||
# 运行期 sys.modules 已就绪)。聚合键/序与 ERP 写入行一致。
|
||||
from app.services.in_transit_transfer.execution_service import _build_order_lines
|
||||
|
||||
ordered = sorted(items, key=lambda row: row.id)
|
||||
aggregated = _build_order_lines(ordered)
|
||||
name_by_key: dict[tuple[str, str, str, str], str] = {}
|
||||
reason_by_key: dict[tuple[str, str, str, str], str] = {}
|
||||
for item in ordered:
|
||||
# [外部形态] join 键与 _build_order_lines 聚合键同形(批号 WTP→HOW 派生),
|
||||
# 否则 WTP 前缀行的品名/原因投影 lookup 会 miss。
|
||||
key = (
|
||||
str(item.material_no or "").strip(),
|
||||
external_lot_no(item.lot_no),
|
||||
str(item.from_warehouse or "").strip(),
|
||||
str(item.to_warehouse or "").strip(),
|
||||
)
|
||||
name = str(item.material_name or "").strip()
|
||||
if name and key not in name_by_key:
|
||||
name_by_key[key] = name
|
||||
# [T13-3] 行级失败/未知原因(result_message)随行组投影;成功行为 None。
|
||||
message = str(item.result_message or "").strip()
|
||||
if message and key not in reason_by_key:
|
||||
reason_by_key[key] = message
|
||||
return {
|
||||
"doc_no": doc.doc_no,
|
||||
"receipt_date": doc.receipt_date,
|
||||
"from_warehouse": doc.from_warehouse,
|
||||
"to_warehouse": doc.to_warehouse,
|
||||
"status": doc.status,
|
||||
"erp_document_no": doc.erp_document_no,
|
||||
"error_message": doc.error_message,
|
||||
"lines": [
|
||||
{
|
||||
"material_no": line["material_no"],
|
||||
"material_name": name_by_key.get(
|
||||
(line["material_no"], line["lot_no"],
|
||||
line["from_warehouse"], line["to_warehouse"]),
|
||||
"",
|
||||
),
|
||||
"lot_no": line["lot_no"],
|
||||
"quantity": line["quantity_text"],
|
||||
"unit": line["unit"],
|
||||
# [T13-3 契约] reason=行级 result_message(失败/未知行),成功行 None。
|
||||
"reason": reason_by_key.get(
|
||||
(line["material_no"], line["lot_no"],
|
||||
line["from_warehouse"], line["to_warehouse"]),
|
||||
),
|
||||
}
|
||||
for line in aggregated
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def serialize_executed_order(doc, items: list) -> dict[str, Any]:
|
||||
"""已执行单查询投影(Task 17 GET /documents orders 逐键,首页区块数据源)。
|
||||
|
||||
在公共单投影(serialize_order)之上补齐查询视图字段:submit_timestamp/
|
||||
status_group/created_at/run_no/items(invoice 粒度行集——与融合卡的聚合
|
||||
lines 不同,本视图逐 Invoice 行展示,供展开明细与影响面核对)。
|
||||
run_no 为 Task 17 契约的必要补充键(契约未列但 result_unknown 行
|
||||
[重新触发] 必须持 run_no 调 POST /runs/{run_no}/documents/{doc_no}/retrigger)。
|
||||
"""
|
||||
base = serialize_order(doc, items)
|
||||
return {
|
||||
"doc_no": base["doc_no"],
|
||||
"submit_timestamp": doc.submit_timestamp,
|
||||
"status": base["status"],
|
||||
"status_group": order_status_group(doc.status),
|
||||
"receipt_date": base["receipt_date"],
|
||||
"from_warehouse": base["from_warehouse"],
|
||||
"to_warehouse": base["to_warehouse"],
|
||||
"erp_document_no": base["erp_document_no"],
|
||||
"error_message": base["error_message"],
|
||||
"created_at": doc.created_at.isoformat() if doc.created_at else None,
|
||||
"run_no": doc.run.run_no if doc.run_id and doc.run else None,
|
||||
"items": [
|
||||
{
|
||||
"invoice_no": item.invoice_no,
|
||||
"material_no": item.material_no,
|
||||
"material_name": item.material_name,
|
||||
"lot_no": item.lot_no or "",
|
||||
"quantity": item.receipt_quantity,
|
||||
"unit": item.unit or "",
|
||||
}
|
||||
for item in sorted(items, key=lambda row: row.id)
|
||||
],
|
||||
}
|
||||
@@ -6,7 +6,9 @@
|
||||
依赖:app.core.errors.AppError。
|
||||
逻辑:转换表声明即白名单,未声明的迁移一律抛 TransferStateError;
|
||||
result_unknown / manually_closed / success / duplicate_success /
|
||||
not_matured / cancelled 为无出边终态;
|
||||
not_matured / cancelled 为无出边终态(唯二例外均为显式人工/生命周期语义:
|
||||
DOCUMENT_RETRIGGER_TRANSITIONS 允许 result_unknown 单经人工 retrigger
|
||||
→ executing,D11 唯一出口;QUEUED Run 经 worker 领取 → executing);
|
||||
通知失败(notification_failed)是通知投递状态,绝不改写 外部系统 业务结果。
|
||||
"""
|
||||
|
||||
@@ -61,6 +63,9 @@ class TransferNotificationStatus(StrEnum):
|
||||
|
||||
|
||||
# 无出边终态:这些状态不得再触发任何自动或手工迁移。
|
||||
# [T10/R7 例外,均已显式声明于 ITEM_TRANSITIONS]:result_unknown 行唯一人工出边 =
|
||||
# retrigger 驱动 → executing(D11 唯一出口,随单重跑);success/duplicate_success
|
||||
# 仍为严格终态(单成功行不可再执行)。
|
||||
TERMINAL_TRANSFER_STATUSES: frozenset[str] = frozenset({
|
||||
TransferStatus.SUCCESS.value,
|
||||
TransferStatus.DUPLICATE_SUCCESS.value,
|
||||
@@ -99,16 +104,24 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
TransferStatus.RESULT_UNKNOWN.value,
|
||||
TransferStatus.CANCELLED.value,
|
||||
# [T10 执行链路出边] worker 重领取/同单复用重跑:executing 行随单再次进入执行。
|
||||
TransferStatus.EXECUTING.value,
|
||||
}),
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value: frozenset({
|
||||
TransferStatus.MATCHING.value, # 仅 外部系统 重查/重新匹配,创建新 Attempt
|
||||
# [T10 执行链路出边] D7①② 复用重跑:blocked 行随失败单重新勾选,随单再执行。
|
||||
TransferStatus.EXECUTING.value,
|
||||
TransferStatus.MANUALLY_CLOSED.value,
|
||||
TransferStatus.CANCELLED.value,
|
||||
}),
|
||||
TransferStatus.NOT_MATURED.value: frozenset(),
|
||||
TransferStatus.SUCCESS.value: frozenset(),
|
||||
TransferStatus.DUPLICATE_SUCCESS.value: frozenset(),
|
||||
TransferStatus.RESULT_UNKNOWN.value: frozenset(),
|
||||
# [T10/R7 出边] result_unknown 行唯一出边 = 人工 retrigger 驱动 → executing
|
||||
# (D11 唯一出口;行随 result_unknown 单重跑,仅 retrigger_document 链路可达)。
|
||||
TransferStatus.RESULT_UNKNOWN.value: frozenset({
|
||||
TransferStatus.EXECUTING.value,
|
||||
}),
|
||||
TransferStatus.MANUALLY_CLOSED.value: frozenset(),
|
||||
TransferStatus.CANCELLED.value: frozenset(),
|
||||
TransferStatus.NOTIFICATION_FAILED.value: frozenset(),
|
||||
@@ -116,8 +129,10 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
|
||||
# Run 级转换白名单。
|
||||
RUN_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
# QUEUED → EXECUTING:D8 异步拆分(prepare 建 queued Run,worker 领取后置 executing)。
|
||||
TransferRunStatus.QUEUED.value: frozenset({
|
||||
TransferRunStatus.PREPARING_FILES.value,
|
||||
TransferRunStatus.EXECUTING.value,
|
||||
TransferRunStatus.CANCELLED.value,
|
||||
}),
|
||||
TransferRunStatus.PREPARING_FILES.value: frozenset({
|
||||
@@ -140,9 +155,16 @@ RUN_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
TransferRunStatus.FAILED.value,
|
||||
TransferRunStatus.CANCELLED.value,
|
||||
}),
|
||||
# [T10/R7 复用边] 终态/部分失败 Run 承载 retrigger 重触发执行(execute_run
|
||||
# doc_id 路径回置 executing,逐单完成后由 finalize_run 重新收尾)。
|
||||
# success/cancelled 仍为严格终态(cancelled=人工停止;success=全单已成,无出边)。
|
||||
TransferRunStatus.SUCCESS.value: frozenset(),
|
||||
TransferRunStatus.PARTIAL_FAILED.value: frozenset(),
|
||||
TransferRunStatus.FAILED.value: frozenset(),
|
||||
TransferRunStatus.PARTIAL_FAILED.value: frozenset({
|
||||
TransferRunStatus.EXECUTING.value,
|
||||
}),
|
||||
TransferRunStatus.FAILED.value: frozenset({
|
||||
TransferRunStatus.EXECUTING.value,
|
||||
}),
|
||||
TransferRunStatus.CANCELLED.value: frozenset(),
|
||||
}
|
||||
|
||||
@@ -198,6 +220,38 @@ def assert_transition_allowed(
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 单(TransferDocument)级人工转移白名单(D11 红线,仅 retrigger 驱动)
|
||||
# ---------------------------------------------------------------------------
|
||||
# result_unknown 单禁止关闭后重建(唯一双单路径),唯一合法出边 =
|
||||
# 人工重新触发(retrigger)→ executing(复用单号/时间戳只触发末步,幂等)。
|
||||
DOCUMENT_RETRIGGER_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
TransferStatus.RESULT_UNKNOWN.value: frozenset({TransferStatus.EXECUTING.value}),
|
||||
}
|
||||
|
||||
|
||||
def assert_document_retrigger_allowed(current: str) -> None:
|
||||
"""单据级人工转移门禁:仅 result_unknown → executing(D11,retrigger 唯一出口)。
|
||||
|
||||
用途:retrigger_document 在改写单状态前调用本门禁,保证「人工转移」只能由
|
||||
retrigger 链路驱动;其余任何路径对 result_unknown 单的状态改写均视为
|
||||
违反 SOP 红线。
|
||||
|
||||
Args:
|
||||
current: 单当前状态。
|
||||
Raises:
|
||||
TransferStateError: 当前状态不是 result_unknown(或目标非 executing)。
|
||||
"""
|
||||
current_value = str(current or "").strip()
|
||||
allowed = DOCUMENT_RETRIGGER_TRANSITIONS.get(current_value)
|
||||
if allowed is None or TransferStatus.EXECUTING.value not in allowed:
|
||||
raise TransferStateError(
|
||||
"document retrigger only allowed from result_unknown",
|
||||
current=current_value,
|
||||
target=TransferStatus.EXECUTING.value,
|
||||
)
|
||||
|
||||
|
||||
def apply_notification_failure(run_status: str) -> str:
|
||||
"""通知失败不改变 外部系统 结果。
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""在途调拨策略硬门禁。
|
||||
|
||||
用途:一期策略禁止部分数量调拨、数量容差与 外部系统 自动重试,
|
||||
强制默认 10 分钟确认有效期。
|
||||
用途:一期策略禁止部分数量调拨、数量容差与 外部系统 自动重试;
|
||||
confirm_ttl_seconds 为纯展示阈值(默认 10 分钟 stale 徽标判定窗口,
|
||||
不再作为执行门禁——2026-09-25 退役)。
|
||||
依赖:app.core.errors.AppError、standard decimal。
|
||||
逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError,
|
||||
阻止发布/执行(fail-closed)。
|
||||
@@ -25,6 +26,9 @@ class TransferStrategyPolicy:
|
||||
allow_partial: bool = False
|
||||
quantity_tolerance: Decimal = Decimal("0")
|
||||
allow_external_auto_retry: bool = False
|
||||
# 纯展示阈值:行 stale 徽标(「库存数据已过期,请重查」提示)的判定窗口;
|
||||
# 不再作为执行门禁(2026-09-25 退役)——防错由文件版本对账 + worker 写前
|
||||
# 库存复查承担(见 execution_service)。
|
||||
confirm_ttl_seconds: int = DEFAULT_CONFIRM_TTL_SECONDS
|
||||
|
||||
|
||||
@@ -57,5 +61,5 @@ def validate_strategy(strategy: TransferStrategyPolicy) -> None:
|
||||
|
||||
|
||||
def default_strategy() -> TransferStrategyPolicy:
|
||||
"""返回一期默认策略(全部禁令关闭,确认有效期 600 秒)。"""
|
||||
"""返回一期默认策略(全部禁令关闭,stale 展示阈值 600 秒)。"""
|
||||
return TransferStrategyPolicy()
|
||||
@@ -3,8 +3,8 @@
|
||||
用途:定义调拨业务类型(在途仓至HUB仓 / HUB仓维修出 / HUB仓间调拨)及各类型
|
||||
的收料数据范围规则;类型 2/3 一期占位(fail-closed 拒绝匹配,规则先冻结)。
|
||||
依赖:app.core.errors.ValidationError、invoice_aggregator.AggregatedInvoice。
|
||||
逻辑:类型决定匹配纳入哪些收料票——类型 1 只保留 INVOICE 以 HOM/HOX/WTP 开头
|
||||
的票(大小写不敏感,范围外票与收料日期范围过滤同语义,静默排除不入明细);
|
||||
逻辑:类型决定匹配纳入哪些收料单——类型 1 只保留 INVOICE 以 HOM/HOX/WTP 开头
|
||||
的单(大小写不敏感,范围外单与收料日期范围过滤同语义,静默排除不入明细);
|
||||
类型 2 规则已定(ODM ID=HoxinRMA)待收料文件解析层支持 odm_id 字段后启用;
|
||||
类型 3 规则待业务定义。范围判断统一走 invoice_in_scope 谓词(匹配过滤与
|
||||
scope 行圈定共用);调用方必须先 ensure_transfer_type_supported 再过滤。
|
||||
@@ -83,13 +83,13 @@ def invoice_in_scope(invoice_no: str, transfer_type: TransferType | str | None)
|
||||
"""判断 Invoice 单号是否落在调拨类型的收料数据范围内(单一判断口径)。
|
||||
|
||||
用途:匹配过滤(filter_invoices_for_type)与 scope 行圈定(matching_service
|
||||
的 scope_item_query)共用本谓词,避免"票过滤"与"行圈定"口径漂移。
|
||||
的 scope_item_query)共用本谓词,避免"单过滤"与"行圈定"口径漂移。
|
||||
|
||||
Args:
|
||||
invoice_no: 收料票单号(大小写不敏感,前后空白忽略;空值恒 False)。
|
||||
invoice_no: 收料单单号(大小写不敏感,前后空白忽略;空值恒 False)。
|
||||
transfer_type: 调拨类型(未规范化值允许,缺省/空回落类型 1)。
|
||||
Returns:
|
||||
True 表示该票在类型范围内(应纳入匹配/scope 查询);
|
||||
True 表示该单在类型范围内(应纳入匹配/scope 查询);
|
||||
占位类型(规则未启用)恒 False。
|
||||
"""
|
||||
resolved = normalize_transfer_type(transfer_type)
|
||||
@@ -104,13 +104,13 @@ def filter_invoices_for_type(
|
||||
invoices: Iterable[AggregatedInvoice],
|
||||
transfer_type: TransferType,
|
||||
) -> list[AggregatedInvoice]:
|
||||
"""按类型的收料数据范围过滤汇总票(返回保留项,保持原顺序)。
|
||||
"""按类型的收料数据范围过滤汇总单(返回保留项,保持原顺序)。
|
||||
|
||||
Args:
|
||||
invoices: 已汇总的收料票。
|
||||
invoices: 已汇总的收料单。
|
||||
transfer_type: 已规范化且已确认支持的调拨类型。
|
||||
Returns:
|
||||
类型范围内的票列表(判断口径统一走 invoice_in_scope)。
|
||||
类型范围内的单列表(判断口径统一走 invoice_in_scope)。
|
||||
"""
|
||||
return [
|
||||
invoice for invoice in invoices
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
"""services/integration_connector/binding.py
|
||||
|
||||
用途:Binding 解析与版本冻结——按 (capability, context, environment) 解析到
|
||||
(客户端 + 接口 + 映射版本),并冻结调用期配置快照。
|
||||
依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、errors.py。
|
||||
有序 BindingStep 快照(一对多配方),并冻结调用期配置。
|
||||
依赖:IntegrationBinding/IntegrationClientInstance/IntegrationInterfaceDefinition、
|
||||
errors.py、transports.base.merge_client_config。
|
||||
逻辑:只命中 published + environment 匹配 + 生效区间 + context_selector 是 context 子集;
|
||||
且接口定义须为 published、客户端实例须 enabled(管理端「发布/退役」「启停」的总开关);
|
||||
同 context 下 priority 高者优先;无命中抛 BindingNotFoundError(fail-closed)。
|
||||
每步接口须 published、每步客户端须 enabled(fail-closed);同 context 下 priority
|
||||
高者优先;无命中或任一步门禁失败抛 BindingNotFoundError。
|
||||
存量空 steps_json 时由旧列合成单步(迁移兜底);读能力=单步,形状与多步统一。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,24 +24,35 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BindingSnapshot:
|
||||
"""一次调用冻结的绑定快照:调用期配置 + 版本号(非活表引用)。"""
|
||||
class BindingStep:
|
||||
"""绑定中的单步冻结快照:接口 + 归属客户端配置 + 该步参数映射。"""
|
||||
|
||||
capability: str
|
||||
context_selector: dict
|
||||
client_code: str
|
||||
interface_code: str
|
||||
connector_type: str
|
||||
interface_version: int
|
||||
mapping_version: int
|
||||
credential_ref_code: str | None
|
||||
client_code: str
|
||||
config: dict
|
||||
request_spec: dict
|
||||
response_mapping: dict
|
||||
output_schema: dict
|
||||
# 域参数→接口参数映射(空 = 同名直通)与接口入参 Schema(映射结果校验)。
|
||||
param_mapping: dict
|
||||
input_schema: dict
|
||||
param_mapping: dict
|
||||
output_schema: dict
|
||||
interface_version: int
|
||||
credential_ref_code: str | None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BindingSnapshot:
|
||||
"""一次调用冻结的绑定快照:有序步骤 + 映射版本(非活表引用)。
|
||||
|
||||
读能力为单元素 steps;写能力可为多步。credential_ref_code 兼容字段取自首步
|
||||
(真实凭据在逐步 client 上,顺序引擎按步解析)。
|
||||
"""
|
||||
|
||||
capability: str
|
||||
context_selector: dict
|
||||
steps: tuple[BindingStep, ...]
|
||||
mapping_version: int
|
||||
credential_ref_code: str | None
|
||||
|
||||
|
||||
def _to_naive(dt: datetime | None) -> datetime | None:
|
||||
@@ -65,19 +78,140 @@ def _is_subset(selector: dict, context: dict) -> bool:
|
||||
return all(context.get(k) == v for k, v in selector.items())
|
||||
|
||||
|
||||
def _raw_steps_from_binding(row: IntegrationBinding) -> list[dict]:
|
||||
"""取出绑定步骤原料:优先 steps_json;空则由旧单步列合成(存量迁移兜底)。"""
|
||||
raw = list(row.steps_json or [])
|
||||
if raw:
|
||||
return raw
|
||||
# 兼容窗:迁移前/未回填行 → 单元素数组
|
||||
if row.interface_definition_code:
|
||||
return [{
|
||||
'interface_code': row.interface_definition_code,
|
||||
'param_mapping_json': row.param_mapping_json or {},
|
||||
}]
|
||||
return []
|
||||
|
||||
|
||||
def _freeze_step(
|
||||
*,
|
||||
capability: str,
|
||||
binding_id: int,
|
||||
step_index: int,
|
||||
step_raw: dict,
|
||||
) -> BindingStep:
|
||||
"""将一步配置冻结为 BindingStep;门禁失败抛 BindingNotFoundError。
|
||||
|
||||
Args:
|
||||
capability: 能力名(日志/异常)。
|
||||
binding_id: 绑定主键。
|
||||
step_index: 步骤下标(0-based,日志区分哪一步)。
|
||||
step_raw: {interface_code, param_mapping_json|param_mapping}。
|
||||
|
||||
Returns:
|
||||
BindingStep。
|
||||
|
||||
Raises:
|
||||
BindingNotFoundError: 接口/客户端缺失、未发布或停用。
|
||||
"""
|
||||
if not isinstance(step_raw, dict):
|
||||
logger.warning(
|
||||
"connector binding step invalid: capability=%s binding_id=%s step=%s reason=not_dict",
|
||||
capability, binding_id, step_index,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
iface_code = str(
|
||||
step_raw.get('interface_code') or step_raw.get('interface_definition_code') or ''
|
||||
).strip()
|
||||
if not iface_code:
|
||||
logger.warning(
|
||||
"connector binding step invalid: capability=%s binding_id=%s step=%s reason=missing_interface_code",
|
||||
capability, binding_id, step_index,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
mapping = step_raw.get('param_mapping_json', step_raw.get('param_mapping', {}))
|
||||
if mapping is None:
|
||||
mapping = {}
|
||||
if not isinstance(mapping, dict):
|
||||
logger.warning(
|
||||
"connector binding step invalid: capability=%s binding_id=%s step=%s reason=param_mapping_not_dict",
|
||||
capability, binding_id, step_index,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=iface_code).first()
|
||||
if iface is None:
|
||||
logger.warning(
|
||||
"connector binding step target missing: capability=%s binding_id=%s step=%s iface=%s",
|
||||
capability, binding_id, step_index, iface_code,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
client = IntegrationClientInstance.query.filter_by(code=iface.client_instance_code).first()
|
||||
if client is None:
|
||||
logger.warning(
|
||||
"connector binding step client missing: capability=%s binding_id=%s step=%s client=%s iface=%s",
|
||||
capability, binding_id, step_index, iface.client_instance_code, iface_code,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
# fail-closed:该步接口未发布或客户端停用 → 视同无可用绑定(日志标明步号与原因)。
|
||||
if iface.status != 'published':
|
||||
logger.warning(
|
||||
"connector binding gated: capability=%s binding_id=%s step=%s iface=%s reason=iface_status=%s",
|
||||
capability, binding_id, step_index, iface_code, iface.status,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
if not client.enabled:
|
||||
logger.warning(
|
||||
"connector binding gated: capability=%s binding_id=%s step=%s client=%s reason=client_disabled",
|
||||
capability, binding_id, step_index, client.code,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
config = merge_client_config({
|
||||
'config_json': client.config_json,
|
||||
'endpoint': client.endpoint,
|
||||
'timeout_seconds': client.timeout_seconds,
|
||||
'db_kind': client.db_kind,
|
||||
})
|
||||
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
|
||||
|
||||
return BindingStep(
|
||||
interface_code=iface.code,
|
||||
connector_type=client.connector_type,
|
||||
client_code=client.code,
|
||||
config=config,
|
||||
request_spec=request_spec,
|
||||
response_mapping=iface.response_mapping_json or {},
|
||||
input_schema=iface.input_schema_json or {},
|
||||
param_mapping=dict(mapping),
|
||||
output_schema=iface.output_schema_json or {},
|
||||
interface_version=int(iface.version or 1),
|
||||
credential_ref_code=client.credential_ref_code,
|
||||
)
|
||||
|
||||
|
||||
def resolve_binding(capability: str, context: dict, environment: str, *, now: datetime | None = None) -> BindingSnapshot:
|
||||
"""解析最佳绑定并冻结调用期快照。
|
||||
"""解析最佳绑定并冻结有序步骤快照。
|
||||
|
||||
Args:
|
||||
capability: 能力名(如 in_transit_transfer.query_inventory)。
|
||||
context: 路由上下文(来源/组织/租户等),如 {"source_code": "DBS-AWSBI"}。
|
||||
environment: 环境(prod/test/dev)。
|
||||
now: 可选时钟(测试注入);缺省用 utcnow。
|
||||
|
||||
Returns:
|
||||
BindingSnapshot。
|
||||
BindingSnapshot(steps 至少一元素;读能力通常单步)。
|
||||
|
||||
Raises:
|
||||
BindingNotFoundError: 无可用绑定(fail-closed);接口未发布或客户端已停用同样按
|
||||
无可用绑定处理(与列表「发布/退役」「启停」按钮语义闭环,且不向调用方泄露配置细节)。
|
||||
BindingNotFoundError: 无可用绑定,或任一步接口未发布/客户端停用/目标缺失
|
||||
(与列表「发布/退役」「启停」语义闭环;不向调用方泄露配置细节)。
|
||||
"""
|
||||
base_now = now or datetime.utcnow()
|
||||
rows = IntegrationBinding.query.filter_by(capability=capability, environment=environment, status='published').all()
|
||||
@@ -90,63 +224,37 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
|
||||
continue
|
||||
candidates.append((row, selector))
|
||||
if not candidates:
|
||||
# fail-closed 必须可排障:区分「一条 published 都没有」与「有但路由选择器/生效窗口不命中」,
|
||||
# 否则调用方只看到 no binding for capability(2026-09 排障实测痛点)。
|
||||
# fail-closed 必须可排障:区分「一条 published 都没有」与「有但路由选择器/生效窗口不命中」。
|
||||
logger.warning(
|
||||
"connector binding miss: capability=%s env=%s published_rows=%s context_keys=%s",
|
||||
capability, environment, len(rows), sorted((context or {}).keys()),
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
candidates.sort(key=lambda item: (item[0].priority, len(item[1])), reverse=True)
|
||||
row, selector = candidates[0]
|
||||
|
||||
client = IntegrationClientInstance.query.filter_by(code=row.client_instance_code).first()
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=row.interface_definition_code).first()
|
||||
if client is None or iface is None:
|
||||
raw_steps = _raw_steps_from_binding(row)
|
||||
if not raw_steps:
|
||||
logger.warning(
|
||||
"connector binding target missing: capability=%s binding_id=%s client=%s iface=%s",
|
||||
capability, row.id, row.client_instance_code, row.interface_definition_code,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
# fail-closed 门禁:接口未发布(draft/retired)或客户端已停用视同无可用绑定——
|
||||
# 管理端「发布/退役」「启停」按钮因此具备真实的调用期语义;错误类型与无命中一致。
|
||||
if iface.status != 'published' or not client.enabled:
|
||||
logger.warning(
|
||||
"connector binding gated: capability=%s binding_id=%s iface_status=%s client_enabled=%s",
|
||||
capability, row.id, iface.status, client.enabled,
|
||||
"connector binding empty steps: capability=%s binding_id=%s",
|
||||
capability, row.id,
|
||||
)
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
# 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费
|
||||
# (与 transports.base.merge_client_config 同一实现)。
|
||||
# 优先列值,缺失回退 JSON(config_json / request_spec_json / context_selector_json)。
|
||||
config = merge_client_config({
|
||||
'config_json': client.config_json,
|
||||
'endpoint': client.endpoint,
|
||||
'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 {})
|
||||
steps: list[BindingStep] = []
|
||||
for idx, step_raw in enumerate(raw_steps):
|
||||
steps.append(_freeze_step(
|
||||
capability=capability,
|
||||
binding_id=row.id,
|
||||
step_index=idx,
|
||||
step_raw=step_raw,
|
||||
))
|
||||
|
||||
return BindingSnapshot(
|
||||
capability=row.capability,
|
||||
context_selector=selector,
|
||||
client_code=client.code,
|
||||
interface_code=iface.code,
|
||||
connector_type=client.connector_type,
|
||||
interface_version=iface.version,
|
||||
context_selector=dict(row.context_selector_json or {}),
|
||||
steps=tuple(steps),
|
||||
mapping_version=row.mapping_version,
|
||||
credential_ref_code=client.credential_ref_code,
|
||||
config=config,
|
||||
request_spec=request_spec,
|
||||
response_mapping=iface.response_mapping_json or {},
|
||||
output_schema=iface.output_schema_json or {},
|
||||
param_mapping=row.param_mapping_json or {},
|
||||
input_schema=iface.input_schema_json or {},
|
||||
credential_ref_code=steps[0].credential_ref_code,
|
||||
)
|
||||
@@ -1,11 +1,30 @@
|
||||
"""services/integration_connector/engine.py
|
||||
|
||||
用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→map-params→call→classify→audit。
|
||||
用途:CapabilityGateway 调用引擎——统一执行 resolve→validate→按步 map-params→call→classify→audit。
|
||||
依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。
|
||||
逻辑:域入参先经能力 Schema 校验,再按绑定 param_mapping 翻译为接口参数(对照接口
|
||||
入参 Schema 校验);凭据按引用解析后以 credential_* 注入传输层;读能力返回
|
||||
带 status 的失败 dict 时原样分类,其余映射校验通过即 success;
|
||||
入参非法/无绑定/映射失败/契约未冻结均 fail-closed;result_unknown 不自动重试。
|
||||
逻辑:域入参先经能力 Schema 校验,再按绑定步骤 param_mapping 翻译为接口参数(对照该步
|
||||
接口入参 Schema 校验);凭据按引用逐步解析后以 credential_* 注入传输层。
|
||||
读能力(write=False)保持单步语义:首步执行 + 成功态做输出映射(行为与历史一致)。
|
||||
写能力(write=True)按 BindingSnapshot.steps 顺序执行四条统一规则(唯一编排语义,
|
||||
禁止扩展成 DSL):①resume=True 跳过全部非末步(不建连、不审计);
|
||||
②非末步失败/超时 → 中止=技术失败(后续步零调用):普通失败原样返回该步分类结果;
|
||||
超时的审计行保留 status='timeout' 技术真相,引擎对外返回 technical_failed
|
||||
(error_code=EXTERNAL_TIMEOUT_ABORTED,与末步超时区分)——stage 超时=WS 未触发、
|
||||
ERP 不可能建单,恢复路径是全量重跑(stage SQL 自带 DELETE 同时间戳幂等),
|
||||
不得落入 result_unknown 红线态;
|
||||
③末步响应经该步 response_mapping 映射 → 六态分类,result.data 恒带映射结果
|
||||
(含失败态);④末步超时 → status=timeout(上层落 result_unknown)。
|
||||
非末步成功放行后支持可选同步回调 on_nonfinal_success(通用步进机制,非业务 DSL):
|
||||
供域调用方在「中间表写成功」与「触发末步」之间落库断点标记(如 stage_confirmed_at
|
||||
先落库再触发);回调异常按该步失败处理(中止=technical_failed,追加异常审计行);
|
||||
读能力单步路径不回调。
|
||||
每步落一条 IntegrationCall:同 operation_id(一票一次执行 = N 条,按 operation_id 串联,
|
||||
步骤定位靠 binding_snapshot_json 的 step_index;模型已解除该列唯一约束并补普通索引,
|
||||
迁移 tt5b6c7d8e9f);传输层返回的保留键 `_wire`(线级事实,database/soap/rest)在落库前
|
||||
剥离为 wire_json 独立成列(经 _clamp_wire 统一尺寸收口,防超大响应撑爆审计行),
|
||||
禁止混入 response_summary_json;调用方可透传 business_ref(业务单号锚点)落库供检索;
|
||||
禁止跨步传参;入参非法/无绑定/映射失败/无 transport
|
||||
均 fail-closed;result_unknown 不自动重试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,9 +33,10 @@ import logging
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import replace
|
||||
from typing import Callable
|
||||
|
||||
from app import db
|
||||
from app.services.integration_connector.binding import BindingSnapshot, resolve_binding
|
||||
from app.services.integration_connector.binding import BindingSnapshot, BindingStep, resolve_binding
|
||||
from app.services.integration_connector.capability import CapabilitySpec, get_capability
|
||||
from app.services.integration_connector.errors import CallFailedError, InputInvalidError
|
||||
from app.services.integration_connector.mapping import map_response, schema_errors
|
||||
@@ -31,6 +51,38 @@ from app.models import IntegrationCall
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 非末步"允许继续"的终态:仅成功族。其余(失败态/timeout/result_unknown)一律中止——
|
||||
# 非末步未确认成功时继续执行后续步会破坏"先落表后触发"的顺序不变量。
|
||||
_NON_FINAL_PROCEED_STATUSES = ('success', 'duplicate_success', 'duplicate_unverified')
|
||||
|
||||
# wire_json 内单字符串尺寸收口上限(控制器裁定:引擎侧统一截断,不在三传输层散补)。
|
||||
_WIRE_MAX_STRING_LEN = 20000
|
||||
# 超长截断尾缀:排障时可辨识"此处曾被收口",非原文。
|
||||
_WIRE_TRUNCATED_SUFFIX = '...[truncated]'
|
||||
|
||||
|
||||
def _clamp_wire(wire):
|
||||
"""递归收口 wire_json 内所有字符串字段到 _WIRE_MAX_STRING_LEN(纯函数,不改入参)。
|
||||
|
||||
用途:传输层 `_wire` 可能携带超大线级事实(SQL 全文/statements[].sql、请求体/
|
||||
响应体等),落 IntegrationCall.wire_json 前统一截断,防审计行与 JSON 列被撑爆。
|
||||
|
||||
Args:
|
||||
wire: `_wire` 原始结构(dict/嵌套 dict/list/标量任意组合)。
|
||||
Returns:
|
||||
收口后的新结构:超长字符串截为前 _WIRE_MAX_STRING_LEN 字符并追加
|
||||
_WIRE_TRUNCATED_SUFFIX 尾缀;未超长字符串与其余类型原样保留。
|
||||
"""
|
||||
if isinstance(wire, str):
|
||||
if len(wire) > _WIRE_MAX_STRING_LEN:
|
||||
return wire[:_WIRE_MAX_STRING_LEN] + _WIRE_TRUNCATED_SUFFIX
|
||||
return wire
|
||||
if isinstance(wire, dict):
|
||||
return {key: _clamp_wire(value) for key, value in wire.items()}
|
||||
if isinstance(wire, (list, tuple)):
|
||||
return [_clamp_wire(item) for item in wire]
|
||||
return wire
|
||||
|
||||
|
||||
def build_request(request_spec: dict, config: dict, params: dict) -> dict:
|
||||
"""按接口请求规格构造请求:填充 path 占位符,组装 params/body/headers。"""
|
||||
@@ -94,7 +146,43 @@ class CapabilityGateway:
|
||||
idempotency_key: str | None = None,
|
||||
environment: str | None = None,
|
||||
transports: dict[str, Transport] | None = None,
|
||||
resume: bool = False,
|
||||
on_nonfinal_success: Callable[[BindingStep, int], None] | None = None,
|
||||
business_ref: str | None = None,
|
||||
) -> IntegrationCallResult:
|
||||
"""执行一次能力调用:读能力单步(既有行为);写能力按绑定步骤顺序执行。
|
||||
|
||||
Args:
|
||||
capability: 已注册能力名。
|
||||
context: 绑定路由上下文(来源/组织等键值对)。
|
||||
params: 域入参(先经能力 input_schema 校验,再逐步经 param_mapping 翻译)。
|
||||
operation_id: 审计串联键(一次调用 N 步共享,按 step_index 定位)。
|
||||
idempotency_key: 预留幂等键(引擎当前不消费)。
|
||||
environment: 显式环境;缺省从 Flask 配置推导。
|
||||
transports: 临时覆盖的 {connector_type: Transport}。
|
||||
resume: True 时跳过全部非末步(断点续跑:该票可能已建成单,禁止重插,
|
||||
只重新触发末步);被跳过的步骤不建连、不落审计、不回调。
|
||||
on_nonfinal_success: 通用步进回调(仅写能力多步路径):每个非末步成功放行
|
||||
(该步审计落库后、进入下一步前)同步调用一次,入参 (该步 BindingStep, 步号)。
|
||||
用途:域调用方在「中间表写成功」与「触发末步」之间落库断点标记
|
||||
(如 stage_confirmed_at 先落库再触发,D7③)。约束:回调同步执行并阻塞
|
||||
后续步,须保持短小——长事务/外部 IO 的副作用与耗时由调用方自律;
|
||||
回调异常按该步失败处理(中止=technical_failed,追加异常审计行,
|
||||
原成功审计行保留不篡改)。读能力单步路径不回调。
|
||||
business_ref: 通用业务锚点(可空):调用方透传的业务单号/任务号,落
|
||||
IntegrationCall.business_ref 供调用日志按业务单号检索/关联(能力无关,
|
||||
不传为 NULL,现有消费者零改动)。
|
||||
|
||||
Returns:
|
||||
IntegrationCallResult(六态之一;写能力末步 data 恒带映射结果)。
|
||||
|
||||
Raises:
|
||||
CapabilityNotFoundError: 能力未注册。
|
||||
InputInvalidError: 域入参不合能力输入 Schema。
|
||||
BindingNotFoundError: 无可用绑定或任一步接口/客户端门禁失败。
|
||||
CallFailedError: 某步无可用 transport。
|
||||
MappingInvalidError: 参数翻译或末步输出映射不合 Schema。
|
||||
"""
|
||||
spec = get_capability(capability)
|
||||
input_errors = schema_errors(params, spec.input_schema)
|
||||
if input_errors:
|
||||
@@ -108,70 +196,297 @@ class CapabilityGateway:
|
||||
|
||||
env = environment or _environment()
|
||||
snapshot = resolve_binding(capability, context, env)
|
||||
if not spec.write:
|
||||
return self._call_read(spec, snapshot, params, operation_id, transports, business_ref)
|
||||
return self._call_write(
|
||||
spec, snapshot, params, operation_id, transports, resume, on_nonfinal_success,
|
||||
business_ref,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 读能力:单步(既有行为,勿改语义)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _call_read(
|
||||
self,
|
||||
spec: CapabilitySpec,
|
||||
snapshot: BindingSnapshot,
|
||||
params: dict,
|
||||
operation_id: str,
|
||||
transports: dict[str, Transport] | None,
|
||||
business_ref: str | None = None,
|
||||
) -> IntegrationCallResult:
|
||||
"""读能力单步执行:首步翻译参数 → 调用 → 失败态直通分类 / 成功态输出映射。"""
|
||||
step = snapshot.steps[0]
|
||||
# 域参数 → 接口参数翻译:绑定配置了 param_mapping 时按映射引擎执行,
|
||||
# 结果对照接口入参 Schema 校验;未配置时同名直通(能力入参原样下传)。
|
||||
params = map_response(snapshot.param_mapping, params, snapshot.input_schema) \
|
||||
if snapshot.param_mapping else params
|
||||
transport = (transports or self.transports).get(snapshot.connector_type)
|
||||
params = map_response(step.param_mapping, params, step.input_schema) \
|
||||
if step.param_mapping else params
|
||||
transport = (transports or self.transports).get(step.connector_type)
|
||||
if transport is None:
|
||||
raise CallFailedError(details={'reason': f'no transport for connector_type={snapshot.connector_type}'})
|
||||
raise CallFailedError(details={'reason': f'no transport for connector_type={step.connector_type}'})
|
||||
|
||||
# 凭据按引用解析(db 密文解密 / env 配置键读取),缺失即 fail-closed。
|
||||
credential = resolve_credential(snapshot.credential_ref_code) if snapshot.credential_ref_code else {}
|
||||
request = build_request(snapshot.request_spec, snapshot.config, params)
|
||||
credential = resolve_credential(step.credential_ref_code) if step.credential_ref_code else {}
|
||||
request = build_request(step.request_spec, step.config, params)
|
||||
trace_id = f'ic-{uuid.uuid4().hex}'
|
||||
start_ms = int(time.time() * 1000)
|
||||
try:
|
||||
raw = transport.call(
|
||||
client={'config_json': snapshot.config, 'credential': credential},
|
||||
interface={'request_spec_json': snapshot.request_spec},
|
||||
client={'config_json': step.config, 'credential': credential},
|
||||
interface={'request_spec_json': step.request_spec},
|
||||
request=request,
|
||||
)
|
||||
except TimeoutError:
|
||||
result = IntegrationCallResult(status='timeout', error_code='EXTERNAL_TIMEOUT_UNKNOWN', trace_id=trace_id)
|
||||
_record_call(operation_id, capability, snapshot, params, None, result, start_ms, trace_id)
|
||||
_record_call(operation_id, spec.name, snapshot, 0, params, None, result, start_ms, trace_id, business_ref)
|
||||
return result
|
||||
|
||||
if spec.write:
|
||||
result = classify_transport_response(raw)
|
||||
elif isinstance(raw, dict) and raw.get('status') in RESULT_FAILURE_STATUSES:
|
||||
if isinstance(raw, dict) and raw.get('status') in RESULT_FAILURE_STATUSES:
|
||||
# 传输层已判失败(HTTP 4xx/5xx、SOAP Fault、非 XML)→ 原样分类,不做输出映射。
|
||||
result = classify_transport_response(raw)
|
||||
else:
|
||||
result = IntegrationCallResult(status='success')
|
||||
if result.status in ('success', 'duplicate_success', 'duplicate_unverified'):
|
||||
data = map_response(snapshot.response_mapping, raw, snapshot.output_schema or spec.output_schema)
|
||||
data = map_response(step.response_mapping, raw, step.output_schema or spec.output_schema)
|
||||
result = replace(result, data=data)
|
||||
result = replace(result, trace_id=trace_id)
|
||||
_record_call(operation_id, capability, snapshot, params, raw, result, start_ms, trace_id)
|
||||
_record_call(operation_id, spec.name, snapshot, 0, params, raw, result, start_ms, trace_id, business_ref)
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 写能力:多步顺序执行(四条统一规则)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _call_write(
|
||||
self,
|
||||
spec: CapabilitySpec,
|
||||
snapshot: BindingSnapshot,
|
||||
params: dict,
|
||||
operation_id: str,
|
||||
transports: dict[str, Transport] | None,
|
||||
resume: bool,
|
||||
on_nonfinal_success: Callable[[BindingStep, int], None] | None,
|
||||
business_ref: str | None = None,
|
||||
) -> IntegrationCallResult:
|
||||
"""写能力按绑定步骤顺序执行;规则②非末步失败/超时中止、规则④末步超时返回 timeout。
|
||||
|
||||
Args:
|
||||
spec: 能力契约(write=True)。
|
||||
snapshot: 冻结的有序步骤快照(≥1 步)。
|
||||
params: 域入参(已过能力 Schema 校验)。
|
||||
operation_id: 审计串联键。
|
||||
transports: 临时覆盖的传输层字典。
|
||||
resume: 规则①——True 跳过全部非末步(不建连、不审计、不回调)。
|
||||
on_nonfinal_success: 非末步成功放行后的同步回调((该步 BindingStep, 步号));
|
||||
None 表示不回调。
|
||||
business_ref: 业务锚点(可空):透传各步审计行 business_ref 列落库。
|
||||
|
||||
Returns:
|
||||
末步分类结果;或中止步(非末步)结果——普通失败原样返回该步分类结果,
|
||||
超时中止对外返回 technical_failed(EXTERNAL_TIMEOUT_ABORTED,与末步超时区分),
|
||||
回调异常中止返回 technical_failed(STEP_CALLBACK_FAILED)。
|
||||
"""
|
||||
steps = snapshot.steps
|
||||
last_index = len(steps) - 1
|
||||
result: IntegrationCallResult | None = None
|
||||
for index, step in enumerate(steps):
|
||||
is_final = index == last_index
|
||||
if resume and not is_final:
|
||||
# 规则①:续跑只执行末步——非末步可能已落表,禁止重插;不建连、不审计、不回调。
|
||||
continue
|
||||
result, step_params, trace_id, start_ms = self._execute_step(
|
||||
spec, snapshot, index, step, params, operation_id, transports, business_ref,
|
||||
)
|
||||
if not is_final and result.status not in _NON_FINAL_PROCEED_STATUSES:
|
||||
if result.status == 'timeout':
|
||||
# 规则②:非末步超时 → 中止=技术失败。审计行已按 'timeout' 落库(技术
|
||||
# 真相),对外改判 technical_failed:stage 超时=WS 未触发、ERP 不可能
|
||||
# 建单,正确恢复路径是全量重跑(stage SQL 自带 DELETE 同时间戳幂等),
|
||||
# 不得落入 result_unknown 红线态(组锁+人工 retrigger)。
|
||||
result = replace(result, status='technical_failed', error_code='EXTERNAL_TIMEOUT_ABORTED')
|
||||
return result
|
||||
if not is_final and on_nonfinal_success is not None:
|
||||
# 通用步进机制(非业务 DSL):非末步成功放行且审计已落库后、进入下一步前
|
||||
# 同步回调一次——域调用方借此在「中间表写成功」与「触发末步」之间落库
|
||||
# 断点标记(如 stage_confirmed_at 先落库再触发,D7③)。
|
||||
callback_started_ms = int(time.time() * 1000)
|
||||
try:
|
||||
on_nonfinal_success(step, index)
|
||||
except Exception as exc:
|
||||
# 回调异常按该步失败处理:中止=technical_failed,并追加一条异常审计行
|
||||
# (原成功审计行保留不篡改,append-only,同 operation_id 同 step_index)。
|
||||
logger.warning(
|
||||
"connector nonfinal callback failed: capability=%s operation_id=%s step=%s",
|
||||
spec.name, operation_id, index, exc_info=True,
|
||||
)
|
||||
cb_result = IntegrationCallResult(
|
||||
status='technical_failed',
|
||||
error_code='STEP_CALLBACK_FAILED',
|
||||
error_message=str(exc)[:500],
|
||||
trace_id=trace_id,
|
||||
)
|
||||
_record_call(
|
||||
operation_id, spec.name, snapshot, index, step_params,
|
||||
None, cb_result, callback_started_ms, trace_id, business_ref,
|
||||
)
|
||||
return cb_result
|
||||
assert result is not None # steps ≥ 1(resolve_binding 保证),末步必产出结果
|
||||
return result
|
||||
|
||||
def _execute_step(
|
||||
self,
|
||||
spec: CapabilitySpec,
|
||||
snapshot: BindingSnapshot,
|
||||
index: int,
|
||||
step: BindingStep,
|
||||
params: dict,
|
||||
operation_id: str,
|
||||
transports: dict[str, Transport] | None,
|
||||
business_ref: str | None = None,
|
||||
) -> tuple[IntegrationCallResult, dict, str, int]:
|
||||
"""执行单步:参数翻译 → transport → 分类;末步追加映射 + 六态分类(规则③)。
|
||||
|
||||
Args:
|
||||
spec: 能力契约(write=True)。
|
||||
snapshot: 冻结的有序步骤快照。
|
||||
index: 当前步下标(0-based)。
|
||||
step: 当前步快照。
|
||||
params: 域入参(已过能力 Schema 校验)。
|
||||
operation_id: 审计串联键(所有步骤共用同一裸值)。
|
||||
transports: 临时覆盖的传输层字典。
|
||||
business_ref: 业务锚点(可空):本步审计行 business_ref 列落库值。
|
||||
|
||||
Returns:
|
||||
(该步结果, 该步翻译后的接口参数, trace_id, 起始毫秒)——后三项供调用方在
|
||||
回调异常等场景补落审计行时复用。
|
||||
"""
|
||||
# 域参数 → 该步接口参数翻译(沿用既有 map_response 路径,结果对照该步入参 Schema)。
|
||||
step_params = map_response(step.param_mapping, params, step.input_schema) \
|
||||
if step.param_mapping else params
|
||||
transport = (transports or self.transports).get(step.connector_type)
|
||||
if transport is None:
|
||||
raise CallFailedError(details={'reason': f'no transport for connector_type={step.connector_type}'})
|
||||
credential = resolve_credential(step.credential_ref_code) if step.credential_ref_code else {}
|
||||
request = build_request(step.request_spec, step.config, step_params)
|
||||
trace_id = f'ic-{uuid.uuid4().hex}' # 每步独立链路 ID(与单步时代一致;串联由 operation_id 承担)
|
||||
start_ms = int(time.time() * 1000)
|
||||
try:
|
||||
raw = transport.call(
|
||||
client={'config_json': step.config, 'credential': credential},
|
||||
interface={'request_spec_json': step.request_spec},
|
||||
request=request,
|
||||
)
|
||||
except TimeoutError:
|
||||
result = IntegrationCallResult(status='timeout', error_code='EXTERNAL_TIMEOUT_UNKNOWN', trace_id=trace_id)
|
||||
_record_call(operation_id, spec.name, snapshot, index, step_params, None, result, start_ms, trace_id, business_ref)
|
||||
return result, step_params, trace_id, start_ms
|
||||
|
||||
if index == len(snapshot.steps) - 1:
|
||||
result = _finalize_step(spec, step, raw, trace_id)
|
||||
else:
|
||||
# 非末步不产出末步判定:仅按传输层分类,供"是否继续"判定。
|
||||
classified = classify_transport_response(raw if isinstance(raw, dict) else {})
|
||||
result = replace(classified, trace_id=trace_id)
|
||||
_record_call(operation_id, spec.name, snapshot, index, step_params, raw, result, start_ms, trace_id, business_ref)
|
||||
return result, step_params, trace_id, start_ms
|
||||
|
||||
|
||||
def _finalize_step(
|
||||
spec: CapabilitySpec,
|
||||
step: BindingStep,
|
||||
raw: dict | None,
|
||||
trace_id: str,
|
||||
) -> IntegrationCallResult:
|
||||
"""末步判定链(规则③):response_mapping 映射 → 六态分类。
|
||||
|
||||
分类输入 = 原始响应 ∪ 映射结果(映射优先):映射未覆盖 status 时保留传输层
|
||||
规范六态(存量单步写绑定兼容),覆盖后以映射为准(如 TIPTOP code→status)。
|
||||
result.data 恒带 mapped(含失败态),供上层消费业务字段;ERP 业务拒单
|
||||
(code≠0)即 classify 归 technical_failed、code/message 透传(用户口径:
|
||||
失败+原因,恢复动作与关票口径对失败态本就一致)。
|
||||
|
||||
Args:
|
||||
spec: 能力契约(output_schema 兜底来源)。
|
||||
step: 末步快照(response_mapping/output_schema)。
|
||||
raw: 末步原始响应。
|
||||
trace_id: 链路追踪 ID。
|
||||
|
||||
Returns:
|
||||
分类后的 IntegrationCallResult。
|
||||
|
||||
Raises:
|
||||
MappingInvalidError: 映射结果不合该步/能力输出 Schema(fail-closed)。
|
||||
"""
|
||||
mapped = map_response(step.response_mapping, raw, step.output_schema or spec.output_schema)
|
||||
base = dict(raw) if isinstance(raw, dict) else {}
|
||||
result = classify_transport_response({**base, **mapped})
|
||||
return replace(result, data=mapped, trace_id=trace_id)
|
||||
|
||||
|
||||
def _record_call(
|
||||
operation_id: str,
|
||||
capability: str,
|
||||
snapshot: BindingSnapshot,
|
||||
step_index: int,
|
||||
params: dict,
|
||||
raw: dict | None,
|
||||
result: IntegrationCallResult,
|
||||
start_ms: int,
|
||||
trace_id: str,
|
||||
business_ref: str | None = None,
|
||||
) -> None:
|
||||
"""落 IntegrationCall(冻结绑定版本 + 脱敏请求/响应摘要)。"""
|
||||
"""落 IntegrationCall(每步一条;同 operation_id 串联 + step_index 定位 + 脱敏请求/响应摘要)。
|
||||
|
||||
多步顺序引擎一次调用落 N 条、共享同一裸 operation_id(模型唯一约束已由迁移
|
||||
tt5b6c7d8e9f 解除并补普通索引);步骤定位靠 binding_snapshot_json.step_index/step_count。
|
||||
传输层保留键 `_wire`(线级事实)在本函数剥离:经 _clamp_wire 尺寸收口后落
|
||||
wire_json 独立成列,不混入 response_summary_json。
|
||||
|
||||
Args:
|
||||
operation_id: 审计串联键(所有步骤共用同一裸值)。
|
||||
capability: 能力名。
|
||||
snapshot: 冻结的有序步骤快照。
|
||||
step_index: 当前步下标(0-based)。
|
||||
params: 该步翻译后的接口参数(sanitize 脱敏后入审计)。
|
||||
raw: 该步原始响应(超时为 None;可含保留键 `_wire`)。
|
||||
result: 该步结果。
|
||||
start_ms: 该步起始毫秒时间戳。
|
||||
trace_id: 该步链路 ID(每步独立生成)。
|
||||
business_ref: 业务锚点(可空):调用方透传的业务单号/任务号,不传为 NULL。
|
||||
"""
|
||||
elapsed_ms = int(time.time() * 1000) - start_ms
|
||||
step = snapshot.steps[step_index]
|
||||
# 剥离保留键 `_wire`:副本上 pop(不污染传输层原返回对象);非 dict(可缺/异形)
|
||||
# 视为无 wire;dict 则尺寸收口后落 wire_json 独立列。余下内容才是响应摘要。
|
||||
raw_dict = dict(raw) if isinstance(raw, dict) else {}
|
||||
wire = raw_dict.pop('_wire', None)
|
||||
call = IntegrationCall(
|
||||
operation_id=operation_id,
|
||||
capability=capability,
|
||||
binding_snapshot_json={
|
||||
'client_code': snapshot.client_code,
|
||||
'interface_code': snapshot.interface_code,
|
||||
'connector_type': snapshot.connector_type,
|
||||
'interface_version': snapshot.interface_version,
|
||||
'client_code': step.client_code,
|
||||
'interface_code': step.interface_code,
|
||||
'connector_type': step.connector_type,
|
||||
'interface_version': step.interface_version,
|
||||
'mapping_version': snapshot.mapping_version,
|
||||
'credential_ref_code': snapshot.credential_ref_code,
|
||||
'credential_ref_code': step.credential_ref_code,
|
||||
# 步骤定位:本条审计对应的步号与总步数(一票一次执行 = N 条同 operation_id)。
|
||||
'step_index': step_index,
|
||||
'step_count': len(snapshot.steps),
|
||||
'steps': [
|
||||
{
|
||||
'interface_code': s.interface_code,
|
||||
'client_code': s.client_code,
|
||||
'connector_type': s.connector_type,
|
||||
}
|
||||
for s in snapshot.steps
|
||||
],
|
||||
},
|
||||
request_summary_json=sanitize(params),
|
||||
response_summary_json=sanitize(raw or {}),
|
||||
response_summary_json=sanitize(raw_dict or {}),
|
||||
wire_json=_clamp_wire(wire) if isinstance(wire, dict) else None,
|
||||
business_ref=business_ref,
|
||||
status=result.status,
|
||||
elapsed_ms=elapsed_ms,
|
||||
trace_id=trace_id,
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
"""services/integration_connector/gateway.py
|
||||
|
||||
用途:模块级 CapabilityGateway 装配与测试注入点。
|
||||
依赖:engine.CapabilityGateway、transports.rest/soap。
|
||||
逻辑:生产用 REST/SOAP 传输;测试通过 set_capability_gateway 注入替身。
|
||||
依赖:engine.CapabilityGateway、transports.rest/soap/database。
|
||||
逻辑:生产用 REST/SOAP/Database 传输;测试通过 set_capability_gateway 注入替身。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.integration_connector.engine import CapabilityGateway
|
||||
from app.services.integration_connector.transports.database import DatabaseTransport
|
||||
from app.services.integration_connector.transports.rest import RestTransport
|
||||
from app.services.integration_connector.transports.soap import SoapTransport
|
||||
|
||||
@@ -21,7 +22,11 @@ def set_capability_gateway(gateway: CapabilityGateway | None) -> None:
|
||||
|
||||
|
||||
def get_capability_gateway() -> CapabilityGateway:
|
||||
"""返回装配好的 CapabilityGateway(测试覆盖优先,默认 REST/SOAP)。"""
|
||||
"""返回装配好的 CapabilityGateway(测试覆盖优先,默认 REST/SOAP/Database)。"""
|
||||
if _override is not None:
|
||||
return _override
|
||||
return CapabilityGateway(transports={'rest': RestTransport(), 'soap': SoapTransport()})
|
||||
return CapabilityGateway(transports={
|
||||
'rest': RestTransport(),
|
||||
'soap': SoapTransport(),
|
||||
'database': DatabaseTransport(),
|
||||
})
|
||||
@@ -168,6 +168,11 @@ def _pick(value: Any, key_field: str | None = None, key_value: Any = None,
|
||||
return MISSING
|
||||
if key_field is None or key_value is None:
|
||||
raise MappingInvalidError(details={"reason": "pick_requires_key_field_and_key_value"})
|
||||
# [形态归一] XML 归一化后重复子节点"单条=dict、多条=list"二态并存(如单条
|
||||
# Field);单 dict 等价单元素列表,直接按列表语义 pick(回归:ERP 返回单条
|
||||
# doc_no Field 时 pick_target_not_list → 单号丢失,单被误判 technical_failed)。
|
||||
if isinstance(value, dict):
|
||||
value = [value]
|
||||
if not isinstance(value, list):
|
||||
raise MappingInvalidError(details={"reason": "pick_target_not_list"})
|
||||
for item in value:
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"""services/integration_connector/transports/__init__.py
|
||||
|
||||
集成连接器传输层:base(契约+分类)、rest、soap。后续扩展 rpa/sql/file。
|
||||
集成连接器传输层:base(契约+分类)、rest、soap、database。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult, Transport, classify_transport_response
|
||||
from app.services.integration_connector.transports.database import DatabaseTransport
|
||||
from app.services.integration_connector.transports.rest import RestTransport
|
||||
from app.services.integration_connector.transports.soap import SoapTransport
|
||||
|
||||
@@ -15,4 +16,5 @@ __all__ = [
|
||||
'classify_transport_response',
|
||||
'RestTransport',
|
||||
'SoapTransport',
|
||||
'DatabaseTransport',
|
||||
]
|
||||
@@ -5,6 +5,7 @@
|
||||
逻辑:Transport.call 返回原始 dict;classify_transport_response 把原始响应归一为
|
||||
IntegrationCallResult(复用调拨六态分类语义)。fail-closed 由各 Transport 抛异常。
|
||||
probe 为可选实现的连接测试探针(只证明网络可达,不做业务调用)。
|
||||
merge_client_config 将 endpoint/timeout_seconds/db_kind 专列拼回 config_json。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -52,16 +53,19 @@ class Transport(Protocol):
|
||||
|
||||
|
||||
def merge_client_config(client: dict) -> dict:
|
||||
"""把客户端实例独立列(endpoint/timeout_seconds)拼回 config_json 的兼容层。
|
||||
"""把客户端实例独立列(endpoint/timeout_seconds/db_kind)拼回 config_json 的兼容层。
|
||||
|
||||
与 binding.resolve_binding 的列拼回逻辑同源(单一实现),供连接测试等
|
||||
不经绑定解析、直接消费客户端实例的调用方复用;返回副本,不改入参。
|
||||
database 类型的 db_kind 专列在此拼入,供 DatabaseTransport 查驱动注册表。
|
||||
"""
|
||||
config = dict(client.get('config_json') or {})
|
||||
if client.get('endpoint') is not None:
|
||||
config['endpoint'] = client['endpoint']
|
||||
if client.get('timeout_seconds') is not None:
|
||||
config['timeout_seconds'] = client['timeout_seconds']
|
||||
if client.get('db_kind') is not None:
|
||||
config['db_kind'] = client['db_kind']
|
||||
return config
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,570 @@
|
||||
"""services/integration_connector/transports/database.py
|
||||
|
||||
用途:Database SQL 传输层——按 db_kind 四库驱动注册表连接并执行/查询 SQL。
|
||||
依赖:oracledb / pymysql / psycopg2 / pymssql;errors、transports.base.mask_secrets。
|
||||
逻辑:gateway 按 connector_type=database 分发至此;request_spec.sql 支持 execute
|
||||
(pre→bulk→post 单事务 commit)与 query(返回 rows 不 commit);D17 标识符
|
||||
白名单 `{key}` 替换(替换后残留任何 `{...}` 形状即 fail-closed,封堵畸形
|
||||
占位符静默直通缺口);四库 connect 工厂消费 config.timeout_seconds 接入驱动
|
||||
超时参数(缺失/非法用驱动默认);异常 rollback + 凭据脱敏;probe 按库种 probe_sql。
|
||||
标识符替换后须从 bind dict 剔除白名单键(oracledb 不容多余键);pre/bulk/post/query
|
||||
再按各语句实际引用的 :bind(跳过字符串字面量与注释)逐语句过滤(oracledb 对
|
||||
语句未引用的键同样报 ORA-01036)。
|
||||
本模块禁止出现具体业务表/单据字面量(D12)。
|
||||
调用日志:execute/query 成功返回 dict 附带保留键 `_wire`(语句、最终 SQL、
|
||||
实际绑定、行数/行快照等线级事实),由引擎(Task 4)剥离落库 wire_json,
|
||||
禁止上游业务消费该键。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.services.integration_connector.errors import InputInvalidError, TransportNotFrozenError
|
||||
from app.services.integration_connector.transports.base import mask_secrets
|
||||
|
||||
# D17:标识符(schema/表名)安全正则——字母开头,允许字母数字与 _ $ #
|
||||
_IDENTIFIER_RE = re.compile(r'^[A-Za-z][A-Za-z0-9_$#]{0,127}$')
|
||||
# 语句中出现的 {placeholder}
|
||||
_PLACEHOLDER_RE = re.compile(r'\{([A-Za-z_][A-Za-z0-9_]*)\}')
|
||||
# 语句中出现的 :bind(配合字面量/注释扫描使用)
|
||||
_PLACEHOLDER_BIND_RE = re.compile(r':([A-Za-z_][A-Za-z0-9_]*)')
|
||||
# 任意 `{...}` 残留形状(含畸形占位符如 {schema.} / {1abc} / {})——替换后不容残留
|
||||
_RESIDUAL_PLACEHOLDER_RE = re.compile(r'\{[^}]*\}')
|
||||
# endpoint 统一 host:port[/database](oracle 段为 service_name)
|
||||
_ENDPOINT_RE = re.compile(r'^([^:]+):(\d+)(?:/(.+))?$')
|
||||
# wire 单文本字段截断上限(防大报文撑爆审计列)。
|
||||
_WIRE_TEXT_LIMIT = 20000
|
||||
|
||||
ConnectFn = Callable[..., Any]
|
||||
|
||||
|
||||
def _timeout_seconds(config: dict) -> int | None:
|
||||
"""从 config.timeout_seconds 解析整数秒;缺失/非法/非正数 → None(用驱动默认,不报错)。
|
||||
|
||||
Args:
|
||||
config: 客户端 config(merge_client_config 已拼入 timeout_seconds 专列值)。
|
||||
|
||||
Returns:
|
||||
正整数秒;不可解析或 ≤0 返回 None(调用方据此省略驱动超时参数)。
|
||||
"""
|
||||
raw = config.get('timeout_seconds')
|
||||
if raw is None or isinstance(raw, bool):
|
||||
return None
|
||||
try:
|
||||
value = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return value if value > 0 else None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DriverSpec:
|
||||
"""单库驱动规格:connect 工厂 + probe SQL。"""
|
||||
|
||||
connect: ConnectFn
|
||||
probe_sql: str
|
||||
|
||||
|
||||
def _parse_endpoint(endpoint: str) -> tuple[str, int, str | None]:
|
||||
"""解析统一 endpoint 为 (host, port, database_or_service)。
|
||||
|
||||
Args:
|
||||
endpoint: `host:port` 或 `host:port/database`(oracle 为 service_name)。
|
||||
|
||||
Returns:
|
||||
(host, port, database_or_service);无路径段时第三项为 None。
|
||||
|
||||
Raises:
|
||||
TransportNotFrozenError: 格式不合法。
|
||||
"""
|
||||
text = str(endpoint or '').strip()
|
||||
match = _ENDPOINT_RE.match(text)
|
||||
if not match:
|
||||
raise TransportNotFrozenError(f'invalid database endpoint: {endpoint!r}')
|
||||
host, port_s, db = match.group(1), match.group(2), match.group(3)
|
||||
return host, int(port_s), db or None
|
||||
|
||||
|
||||
def _connect_oracle(*, config: dict, credential: dict) -> Any:
|
||||
"""Oracle:oracledb EZConnect dsn=host:port/service;可选 thick(11g 等老服务端必须)。
|
||||
|
||||
thick 目录取值优先级:按客户端 config_json.oracle_lib_dir → 全局环境变量
|
||||
ORACLE_CLIENT_LIB_DIR(.env.* 由 settings 载入 os.environ;容器/系统环境同样生效,
|
||||
与 text2sql 同源)。初始化失败(路径无效/版本过老/已初始化)静默回退 thin——
|
||||
真实连接失败在 connect 处暴露(thick-only 的老版本服务端会报 DPY-3010)。
|
||||
超时:tcp_connect_timeout(秒,建连超时)为安装版本(oracledb 4.0.2)connect()
|
||||
实际支持的参数;call_timeout(毫秒,单次 round-trip 超时)不是 connect 参数,
|
||||
建连后按连接属性设置(thin/thick 均支持,异常安装版本静默跳过用驱动默认)。
|
||||
"""
|
||||
import oracledb
|
||||
|
||||
# [STEP 1] 可选 thick 模式(config_json.oracle_lib_dir → 全局环境兜底)
|
||||
lib_dir = str(config.get('oracle_lib_dir') or '').strip() or (os.getenv('ORACLE_CLIENT_LIB_DIR') or '').strip()
|
||||
if lib_dir:
|
||||
try:
|
||||
oracledb.init_oracle_client(lib_dir=lib_dir)
|
||||
except Exception:
|
||||
# 已初始化或 thin 可用时忽略;真实连接失败再暴露
|
||||
pass
|
||||
|
||||
host, port, service = _parse_endpoint(str(config.get('endpoint') or ''))
|
||||
if not service:
|
||||
raise TransportNotFrozenError('oracle endpoint requires service_name: host:port/service')
|
||||
dsn = f'{host}:{port}/{service}'
|
||||
kwargs: dict[str, Any] = {}
|
||||
timeout = _timeout_seconds(config)
|
||||
if timeout is not None:
|
||||
kwargs['tcp_connect_timeout'] = timeout
|
||||
conn = oracledb.connect(
|
||||
user=str(credential.get('username') or ''),
|
||||
password=str(credential.get('password') or ''),
|
||||
dsn=dsn,
|
||||
**kwargs,
|
||||
)
|
||||
if timeout is not None:
|
||||
try:
|
||||
conn.call_timeout = timeout * 1000 # 毫秒
|
||||
except Exception:
|
||||
# 个别安装模式不支持 call_timeout 属性时跳过(建连超时已生效),不阻断调用
|
||||
pass
|
||||
return conn
|
||||
|
||||
|
||||
def _connect_mysql(*, config: dict, credential: dict) -> Any:
|
||||
"""MySQL:pymysql,charset=utf8mb4;超时=connect/read/write_timeout(秒)。"""
|
||||
import pymysql
|
||||
|
||||
host, port, database = _parse_endpoint(str(config.get('endpoint') or ''))
|
||||
kwargs: dict[str, Any] = {}
|
||||
timeout = _timeout_seconds(config)
|
||||
if timeout is not None:
|
||||
kwargs.update(connect_timeout=timeout, read_timeout=timeout, write_timeout=timeout)
|
||||
return pymysql.connect(
|
||||
host=host,
|
||||
port=port,
|
||||
user=str(credential.get('username') or ''),
|
||||
password=str(credential.get('password') or ''),
|
||||
database=database or '',
|
||||
charset='utf8mb4',
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
def _connect_postgresql(*, config: dict, credential: dict) -> Any:
|
||||
"""PostgreSQL:psycopg2,dbname 对应 endpoint 路径段;超时=connect_timeout(秒)。"""
|
||||
import psycopg2
|
||||
|
||||
host, port, database = _parse_endpoint(str(config.get('endpoint') or ''))
|
||||
kwargs: dict[str, Any] = {}
|
||||
timeout = _timeout_seconds(config)
|
||||
if timeout is not None:
|
||||
kwargs['connect_timeout'] = timeout
|
||||
return psycopg2.connect(
|
||||
host=host,
|
||||
port=port,
|
||||
user=str(credential.get('username') or ''),
|
||||
password=str(credential.get('password') or ''),
|
||||
dbname=database or '',
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
def _connect_sqlserver(*, config: dict, credential: dict) -> Any:
|
||||
"""SQL Server:pymssql(注册表键为 sqlserver,非 mssql);超时=login/timeout(秒)。"""
|
||||
import pymssql
|
||||
|
||||
host, port, database = _parse_endpoint(str(config.get('endpoint') or ''))
|
||||
kwargs: dict[str, Any] = {}
|
||||
timeout = _timeout_seconds(config)
|
||||
if timeout is not None:
|
||||
kwargs.update(login_timeout=timeout, timeout=timeout)
|
||||
return pymssql.connect(
|
||||
server=host,
|
||||
port=port,
|
||||
user=str(credential.get('username') or ''),
|
||||
password=str(credential.get('password') or ''),
|
||||
database=database or '',
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
# D16 四库驱动注册表;键必须与 models.DB_KINDS 一致(sqlserver 非 mssql)。
|
||||
_DRIVERS: dict[str, DriverSpec] = {
|
||||
'oracle': DriverSpec(connect=_connect_oracle, probe_sql='SELECT 1 FROM DUAL'),
|
||||
'mysql': DriverSpec(connect=_connect_mysql, probe_sql='SELECT 1'),
|
||||
'postgresql': DriverSpec(connect=_connect_postgresql, probe_sql='SELECT 1'),
|
||||
'sqlserver': DriverSpec(connect=_connect_sqlserver, probe_sql='SELECT 1'),
|
||||
}
|
||||
|
||||
|
||||
def _apply_identifiers(sql: str, *, identifiers: list[str], params: dict) -> str:
|
||||
"""对单条 SQL 做 D17 标识符 `{key}` 白名单替换。
|
||||
|
||||
标识符值字面量写入 SQL,不走 :bind。调用方在 execute/executemany 前须用
|
||||
`_strip_identifier_keys` 剔除白名单键,否则 oracledb 等对多余 bind 键报错。
|
||||
|
||||
Args:
|
||||
sql: 原始语句。
|
||||
identifiers: 允许替换的键名白名单。
|
||||
params: 绑定参数(标识符值取自此,不走 :bind)。
|
||||
|
||||
Returns:
|
||||
替换后的 SQL(保证无任何 `{...}` 残留形状)。
|
||||
|
||||
Raises:
|
||||
InputInvalidError: 未声明占位符、缺值、值未过安全正则,或替换后仍残留
|
||||
`{...}` 形状(畸形占位符如 `{schema.}`/`{1abc}` 不匹配替换正则,
|
||||
若不拦截会原样进入 SQL——fail-closed 封堵该静默直通缺口)。
|
||||
"""
|
||||
allowed = set(identifiers or [])
|
||||
|
||||
def _repl(match: re.Match[str]) -> str:
|
||||
key = match.group(1)
|
||||
if key not in allowed:
|
||||
raise InputInvalidError(
|
||||
f'undeclared SQL identifier placeholder: {{{key}}}',
|
||||
details={'placeholder': key},
|
||||
)
|
||||
if key not in params:
|
||||
raise InputInvalidError(
|
||||
f'missing identifier value: {key}',
|
||||
details={'placeholder': key},
|
||||
)
|
||||
value = str(params[key])
|
||||
if not _IDENTIFIER_RE.match(value):
|
||||
raise InputInvalidError(
|
||||
f'illegal SQL identifier value for {key}',
|
||||
details={'placeholder': key},
|
||||
)
|
||||
return value
|
||||
|
||||
result = _PLACEHOLDER_RE.sub(_repl, sql)
|
||||
# 替换完成后断言无残留:任何 `{...}` 形状(含畸形占位符)都视为未消化的模板,
|
||||
# 静默下传会让数据库收到字面 `{...}` 或被利用的畸形标识符。
|
||||
residual = _RESIDUAL_PLACEHOLDER_RE.search(result)
|
||||
if residual:
|
||||
raise InputInvalidError(
|
||||
f'unresolved SQL placeholder after substitution: {residual.group(0)}',
|
||||
details={'placeholder': residual.group(0)},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def _strip_identifier_keys(params: dict, identifiers: list[str]) -> dict:
|
||||
"""从 bind 参数字典中剔除 identifiers 白名单键。
|
||||
|
||||
用途:`{schema}` 等已做字面量替换后,不得再作为 :bind 传入驱动。
|
||||
核心逻辑:按白名单集合过滤,返回新 dict(不修改入参)。
|
||||
|
||||
Args:
|
||||
params: 待传给 execute/executemany 的绑定参数。
|
||||
identifiers: `sql.identifiers` 白名单键列表。
|
||||
|
||||
Returns:
|
||||
已剔除标识符键的新字典。
|
||||
"""
|
||||
if not identifiers:
|
||||
return dict(params)
|
||||
drop = set(identifiers)
|
||||
return {k: v for k, v in params.items() if k not in drop}
|
||||
|
||||
|
||||
def _referenced_bind_names(sql: str) -> set[str]:
|
||||
"""提取语句实际引用的 :bind 名(跳过字符串字面量与注释)。
|
||||
|
||||
【为什么】oracledb 不容许多余 bind 键(ORA-01036 unrecognized bind variable);
|
||||
pre/bulk/post/query 共享同一份参数字典,而各语句通常只引用其中一部分——
|
||||
必须按语句真实引用过滤,映射方可只写自己需要的绑定。
|
||||
|
||||
Args:
|
||||
sql: 标识符替换后的最终 SQL 文本。
|
||||
|
||||
Returns:
|
||||
语句中出现的 :name 集合(不含字符串字面量与 `--` / `/* */` 注释内的冒号)。
|
||||
"""
|
||||
names: set[str] = set()
|
||||
in_string = False
|
||||
i = 0
|
||||
n = len(sql)
|
||||
while i < n:
|
||||
ch = sql[i]
|
||||
if in_string:
|
||||
if ch == "'":
|
||||
in_string = False
|
||||
i += 1
|
||||
continue
|
||||
if ch == "'":
|
||||
in_string = True
|
||||
i += 1
|
||||
continue
|
||||
if ch == '-' and sql[i:i + 2] == '--':
|
||||
i = sql.find('\n', i)
|
||||
i = n if i == -1 else i + 1
|
||||
continue
|
||||
if ch == '/' and sql[i:i + 2] == '/*':
|
||||
end = sql.find('*/', i + 2)
|
||||
i = n if end == -1 else end + 2
|
||||
continue
|
||||
if ch == ':':
|
||||
match = _PLACEHOLDER_BIND_RE.match(sql, i)
|
||||
if match:
|
||||
names.add(match.group(1))
|
||||
i = match.end()
|
||||
continue
|
||||
i += 1
|
||||
return names
|
||||
|
||||
|
||||
def _filter_statement_binds(params: dict, sql: str) -> dict:
|
||||
"""按语句引用的 :bind 过滤参数字典(保持原键序,不改入参)。
|
||||
|
||||
Args:
|
||||
params: 待传给 execute/executemany 的绑定参数。
|
||||
sql: 该语句替换标识符后的最终文本。
|
||||
|
||||
Returns:
|
||||
仅含语句实际引用键的新字典。
|
||||
"""
|
||||
allowed = _referenced_bind_names(sql)
|
||||
return {k: v for k, v in params.items() if k in allowed}
|
||||
|
||||
|
||||
def _rows_as_dicts(cursor: Any) -> list[dict[str, Any]]:
|
||||
"""将游标结果按 description 列名(别名)转为 dict 列表。"""
|
||||
description = getattr(cursor, 'description', None) or ()
|
||||
columns = [col[0] for col in description]
|
||||
return [dict(zip(columns, row)) for row in (cursor.fetchall() or [])]
|
||||
|
||||
|
||||
class DatabaseTransport:
|
||||
"""数据库 SQL 传输;按 config.db_kind 查 `_DRIVERS`,未知值 fail-closed。"""
|
||||
|
||||
connector_type = 'database'
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
"""执行 request_spec.sql(execute 单事务 / query 返回 rows)。
|
||||
|
||||
Args:
|
||||
client: 含 config_json(须已拼入 endpoint/db_kind)与 credential。
|
||||
interface: 含 request_spec_json.sql 节点。
|
||||
request: 引擎构造的请求,参数取自 request['params']。
|
||||
|
||||
Returns:
|
||||
成功 dict(execute: status=success;query: 另含 rows),均附带保留键
|
||||
`_wire`(线级事实,由引擎剥离落库,业务侧不得消费);
|
||||
驱动异常时 technical_failed(message 已脱敏,无 `_wire`)。
|
||||
|
||||
Raises:
|
||||
TransportNotFrozenError: 缺 endpoint/db_kind 或未知库种。
|
||||
InputInvalidError: 标识符白名单/安全正则失败或 sql 规格非法。
|
||||
"""
|
||||
config = dict(client.get('config_json') or {})
|
||||
credential = dict(client.get('credential') or {})
|
||||
params = dict(request.get('params') or {})
|
||||
sql_spec = (interface.get('request_spec_json') or {}).get('sql') or {}
|
||||
if not isinstance(sql_spec, dict) or not sql_spec:
|
||||
raise InputInvalidError('request_spec.sql is required for database transport')
|
||||
|
||||
driver = self._resolve_driver(config)
|
||||
identifiers = list(sql_spec.get('identifiers') or [])
|
||||
mode = str(sql_spec.get('mode') or '').strip().lower()
|
||||
|
||||
conn = None
|
||||
try:
|
||||
# [STEP 1] 建连
|
||||
conn = driver.connect(config=config, credential=credential)
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
if mode == 'execute':
|
||||
return self._run_execute(conn, cursor, sql_spec, params, identifiers)
|
||||
if mode == 'query':
|
||||
return self._run_query(cursor, sql_spec, params, identifiers)
|
||||
raise InputInvalidError(
|
||||
f'unsupported sql.mode: {mode!r}',
|
||||
details={'mode': mode},
|
||||
)
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
except Exception:
|
||||
pass
|
||||
except (TransportNotFrozenError, InputInvalidError):
|
||||
if conn is not None:
|
||||
try:
|
||||
conn.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
except Exception as exc:
|
||||
if conn is not None:
|
||||
try:
|
||||
conn.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
'status': 'technical_failed',
|
||||
'code': 'DB_ERROR',
|
||||
'message': mask_secrets(str(exc)[:2000], credential)[:500],
|
||||
}
|
||||
finally:
|
||||
if conn is not None:
|
||||
try:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def probe(self, *, client: dict) -> dict[str, Any]:
|
||||
"""连接测试:执行各库 probe_sql,成功即 ok(不做业务调用)。
|
||||
|
||||
Args:
|
||||
client: 含 config_json(endpoint/db_kind)与 credential。
|
||||
|
||||
Returns:
|
||||
{'ok': True/False, 'code': ..., 'message': ...};异常 message 已脱敏。
|
||||
|
||||
Raises:
|
||||
TransportNotFrozenError: 缺 endpoint/db_kind 或未知库种。
|
||||
"""
|
||||
config = dict(client.get('config_json') or {})
|
||||
credential = dict(client.get('credential') or {})
|
||||
driver = self._resolve_driver(config)
|
||||
conn = None
|
||||
try:
|
||||
conn = driver.connect(config=config, credential=credential)
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
cursor.execute(driver.probe_sql)
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
except Exception:
|
||||
pass
|
||||
return {'ok': True, 'code': 'DB_PROBE_OK', 'message': 'ok'}
|
||||
except TransportNotFrozenError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
return {
|
||||
'ok': False,
|
||||
'code': 'CONNECTION_FAILED',
|
||||
'message': mask_secrets(str(exc)[:500], credential),
|
||||
}
|
||||
finally:
|
||||
if conn is not None:
|
||||
try:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _resolve_driver(self, config: dict) -> DriverSpec:
|
||||
"""校验 endpoint/db_kind 并返回驱动规格;未知库种 fail-closed。"""
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
raise TransportNotFrozenError('database endpoint not frozen (missing endpoint)')
|
||||
db_kind = str(config.get('db_kind') or '').strip().lower()
|
||||
if not db_kind:
|
||||
raise TransportNotFrozenError('database db_kind not frozen (missing db_kind)')
|
||||
driver = _DRIVERS.get(db_kind)
|
||||
if driver is None:
|
||||
raise TransportNotFrozenError(f'unknown database db_kind: {db_kind!r}')
|
||||
return driver
|
||||
|
||||
def _run_execute(
|
||||
self,
|
||||
conn: Any,
|
||||
cursor: Any,
|
||||
sql_spec: dict,
|
||||
params: dict,
|
||||
identifiers: list[str],
|
||||
) -> dict[str, Any]:
|
||||
"""execute:pre → bulk(executemany) → post,单事务 commit。
|
||||
|
||||
标识符 `{key}` 替换后,bind 参数(含 bulk 行合并)须剔除 identifiers 键。
|
||||
返回 dict 附带保留键 `_wire`:逐语句记录 phase/最终 SQL/实际绑定/行数
|
||||
(bulk 另记 row_count),顶层 rowcount 为各语句之和,供调用日志落库。
|
||||
"""
|
||||
bulk = sql_spec.get('bulk') or {}
|
||||
rows_param = str(bulk.get('rows_param') or '').strip() if bulk else ''
|
||||
# 基础参数不含行列表,避免 pre/post 绑定把整表塞进驱动参数。
|
||||
base_raw = (
|
||||
{k: v for k, v in params.items() if k != rows_param}
|
||||
if rows_param
|
||||
else dict(params)
|
||||
)
|
||||
# [STEP 1.5] 剔除已字面量替换的标识符键,避免 oracledb 多余 bind 键报错
|
||||
base = _strip_identifier_keys(base_raw, identifiers)
|
||||
|
||||
statements: list[dict] = []
|
||||
# [STEP 2] pre 语句(按语句引用过滤后的基础参数)
|
||||
for stmt in list(sql_spec.get('pre') or []):
|
||||
sql = _apply_identifiers(str(stmt), identifiers=identifiers, params=params)
|
||||
cursor.execute(sql, _filter_statement_binds(base, sql))
|
||||
statements.append({'phase': 'pre', 'sql': sql,
|
||||
'binds': _filter_statement_binds(base, sql),
|
||||
'rowcount': int(getattr(cursor, 'rowcount', 0) or 0)})
|
||||
|
||||
# [STEP 3] bulk:行与基础参数合并,行内键覆盖;合并后再剔标识符键
|
||||
if bulk:
|
||||
bulk_sql = _apply_identifiers(
|
||||
str(bulk.get('sql') or ''), identifiers=identifiers, params=params,
|
||||
)
|
||||
raw_rows = params.get(rows_param) if rows_param else None
|
||||
if not isinstance(raw_rows, list):
|
||||
raise InputInvalidError(
|
||||
f'bulk.rows_param must resolve to a list: {rows_param!r}',
|
||||
details={'rows_param': rows_param},
|
||||
)
|
||||
merged_rows = [
|
||||
_strip_identifier_keys({**base_raw, **dict(row or {})}, identifiers)
|
||||
for row in raw_rows
|
||||
]
|
||||
cursor.executemany(
|
||||
bulk_sql,
|
||||
[_filter_statement_binds(row, bulk_sql) for row in merged_rows],
|
||||
)
|
||||
statements.append({'phase': 'bulk', 'sql': bulk_sql,
|
||||
'binds': merged_rows[0] if merged_rows else {},
|
||||
'rowcount': int(getattr(cursor, 'rowcount', 0) or 0),
|
||||
'row_count': len(merged_rows)})
|
||||
|
||||
# [STEP 4] post 语句
|
||||
for stmt in list(sql_spec.get('post') or []):
|
||||
sql = _apply_identifiers(str(stmt), identifiers=identifiers, params=params)
|
||||
cursor.execute(sql, _filter_statement_binds(base, sql))
|
||||
statements.append({'phase': 'post', 'sql': sql,
|
||||
'binds': _filter_statement_binds(base, sql),
|
||||
'rowcount': int(getattr(cursor, 'rowcount', 0) or 0)})
|
||||
|
||||
conn.commit()
|
||||
return {'status': 'success',
|
||||
'_wire': {'kind': 'database', 'statements': statements,
|
||||
'rowcount': sum(s.get('rowcount', 0) for s in statements)}}
|
||||
|
||||
def _run_query(
|
||||
self,
|
||||
cursor: Any,
|
||||
sql_spec: dict,
|
||||
params: dict,
|
||||
identifiers: list[str],
|
||||
) -> dict[str, Any]:
|
||||
"""query:执行 SELECT,按列别名返回 rows,不 commit。
|
||||
|
||||
标识符替换后 bind 参数剔除 identifiers 键。
|
||||
返回 dict 附带保留键 `_wire`:单语句记录 phase=query 与最终 SQL/实际绑定,
|
||||
rows 截断至 _WIRE_TEXT_LIMIT 行作快照,供调用日志落库。
|
||||
"""
|
||||
raw_sql = str(sql_spec.get('sql') or '').strip()
|
||||
if not raw_sql:
|
||||
raise InputInvalidError('query mode requires sql.sql')
|
||||
sql = _apply_identifiers(raw_sql, identifiers=identifiers, params=params)
|
||||
binds = _filter_statement_binds(
|
||||
_strip_identifier_keys(params, identifiers), sql)
|
||||
cursor.execute(sql, binds)
|
||||
rows = _rows_as_dicts(cursor)
|
||||
return {'status': 'success', 'rows': rows,
|
||||
'_wire': {'kind': 'database',
|
||||
'statements': [{'phase': 'query', 'sql': sql, 'binds': binds}],
|
||||
'rows': rows[:_WIRE_TEXT_LIMIT]}}
|
||||
@@ -4,11 +4,15 @@
|
||||
依赖:requests(默认注入),可注入 http_request 供测试替身。
|
||||
逻辑:endpoint 未冻结 fail-closed(TransportNotFrozenError);4xx/5xx 映射为
|
||||
business_failed dict;非 JSON 响应映射为 technical_failed。
|
||||
调用日志:call 各返回分支(JSON 成功/HTTP≥400/NON_JSON)附带保留键 `_wire`
|
||||
(method/url/脱敏请求头/请求体/状态码/脱敏响应体等线级事实),由引擎
|
||||
(Task 4)剥离落库 wire_json,禁止上游业务消费该键。
|
||||
probe 连接测试探针:GET endpoint,任意 HTTP 响应即算可达(连接异常才算不通)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Callable
|
||||
|
||||
import requests
|
||||
@@ -18,6 +22,9 @@ from app.services.integration_connector.transports.base import mask_secrets
|
||||
|
||||
HttpRequest = Callable[..., Any]
|
||||
|
||||
# wire 单文本字段截断上限(防大报文撑爆审计列)。
|
||||
_WIRE_TEXT_LIMIT = 20000
|
||||
|
||||
|
||||
class RestTransport:
|
||||
"""REST 传输;http_request 可注入以便单元测试(默认 requests.request)。"""
|
||||
@@ -28,6 +35,24 @@ class RestTransport:
|
||||
self._http_request = http_request or requests.request
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
"""构造 HTTP 请求并返回原始响应 dict;各返回分支附带保留键 `_wire`。
|
||||
|
||||
用途与触发时机:引擎按 connector_type=rest 分发至此完成一次真实调用;
|
||||
`_wire` 记录线级事实(method/url/脱敏请求头/请求体/状态码/脱敏响应体),
|
||||
仅由调用日志引擎剥离落库,业务侧禁止消费。
|
||||
|
||||
Args:
|
||||
client: 含 config_json(endpoint/timeout_seconds/headers)与 credential。
|
||||
interface: 含 request_spec_json(method/path)。
|
||||
request: 引擎构造的请求(params/body/headers)。
|
||||
|
||||
Returns:
|
||||
JSON 成功 dict / business_failed(HTTP≥400)/ technical_failed(NON_JSON),
|
||||
各分支均附 `_wire`(JSON 解析结果非 dict 时无法附加键,按原样返回)。
|
||||
|
||||
Raises:
|
||||
TransportNotFrozenError: 缺 endpoint(fail-closed)。
|
||||
"""
|
||||
config = client.get('config_json') or {}
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
@@ -48,21 +73,37 @@ class RestTransport:
|
||||
headers=headers,
|
||||
timeout=timeout,
|
||||
)
|
||||
if int(getattr(response, 'status_code', 0)) >= 400:
|
||||
http_status = int(getattr(response, 'status_code', 0))
|
||||
response_text = str(getattr(response, 'text', '') or '')
|
||||
request_body = json.dumps(request.get('body'), ensure_ascii=False, default=str) \
|
||||
if request.get('body') is not None else ''
|
||||
wire = {'kind': 'rest', 'method': method, 'url': url,
|
||||
'headers': mask_secrets(json.dumps(headers, ensure_ascii=False, default=str),
|
||||
client.get('credential')),
|
||||
'request_body': request_body,
|
||||
'http_status': http_status,
|
||||
'response_body': mask_secrets(response_text, client.get('credential'))[:_WIRE_TEXT_LIMIT]}
|
||||
if http_status >= 400:
|
||||
return {
|
||||
'status': 'business_failed',
|
||||
'code': f"HTTP_{int(response.status_code)}",
|
||||
'code': f"HTTP_{http_status}",
|
||||
# 错误回显可能包含请求内容(含凭据),先脱敏再截断。
|
||||
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
|
||||
'_wire': wire,
|
||||
}
|
||||
try:
|
||||
return response.json()
|
||||
parsed = response.json()
|
||||
except Exception:
|
||||
return {
|
||||
'status': 'technical_failed',
|
||||
'code': 'NON_JSON',
|
||||
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
|
||||
'_wire': wire,
|
||||
}
|
||||
# JSON 解析结果为 dict 时附 `_wire`;list/标量无法携带键,按原样返回。
|
||||
if isinstance(parsed, dict):
|
||||
parsed['_wire'] = wire
|
||||
return parsed
|
||||
|
||||
def probe(self, *, client: dict) -> dict[str, Any]:
|
||||
"""连接测试探针:GET endpoint,任意 HTTP 响应(含 4xx/5xx)都证明网络可达。
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
非 XML → technical_failed。
|
||||
probe 连接测试探针:GET WSDL 地址并校验返回 XML(definitions/Envelope 任一即通);
|
||||
裸服务端点自动补 ?wsdl(SOAP 端点对裸 GET 常返回 404/405/501)。
|
||||
调用日志:call 各返回分支(成功/HTTP≥400/NON_XML)附带保留键 `_wire`
|
||||
(method/url/soap_action/脱敏请求体/状态码/脱敏响应体等线级事实),
|
||||
由引擎(Task 4)剥离落库 wire_json,禁止上游业务消费该键。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -31,6 +34,8 @@ HttpRequest = Callable[..., Any]
|
||||
|
||||
# 内嵌转义 XML 的最大递归展开深度(防深嵌套/构造报文拖垮解析)。
|
||||
MAX_EMBED_DEPTH = 3
|
||||
# wire 单文本字段截断上限(防大报文撑爆审计列)。
|
||||
_WIRE_TEXT_LIMIT = 20000
|
||||
|
||||
|
||||
def _localname(tag: Any) -> str:
|
||||
@@ -137,6 +142,25 @@ class SoapTransport:
|
||||
self._http_request = http_request or requests.request
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
"""按契约生成 SOAP 报文并解析响应;各返回分支附带保留键 `_wire`。
|
||||
|
||||
用途与触发时机:引擎按 connector_type=soap 分发至此完成一次真实调用;
|
||||
`_wire` 记录线级事实(method/url/soap_action/脱敏请求体/状态码/脱敏响应体),
|
||||
仅由调用日志引擎剥离落库,业务侧禁止消费。
|
||||
|
||||
Args:
|
||||
client: 含 config_json(endpoint/timeout_seconds)与 credential。
|
||||
interface: 含 request_spec_json(method + soap.action/body_template)。
|
||||
request: 引擎构造的请求,参数取自 request['params']。
|
||||
|
||||
Returns:
|
||||
解析后的业务 dict / business_failed(HTTP≥400、SOAP Fault)/
|
||||
technical_failed(NON_XML),各分支均附 `_wire`。
|
||||
|
||||
Raises:
|
||||
TransportNotFrozenError: 缺 endpoint 或 soap.body_template(fail-closed)。
|
||||
InputInvalidError: 模板占位符缺值/非法(fail-closed)。
|
||||
"""
|
||||
config = client.get('config_json') or {}
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
if not endpoint:
|
||||
@@ -165,22 +189,29 @@ class SoapTransport:
|
||||
headers=headers,
|
||||
timeout=int(config.get('timeout_seconds') or 60),
|
||||
)
|
||||
if int(getattr(response, 'status_code', 0)) >= 400:
|
||||
http_status = int(getattr(response, 'status_code', 0))
|
||||
# 响应文本与请求体在进入任何分支前先脱敏:错误回显/成功报文都可能含凭据。
|
||||
response_text = mask_secrets(str(getattr(response, 'text', '') or ''), client.get('credential'))
|
||||
wire = {'kind': 'soap', 'method': method, 'url': url,
|
||||
'soap_action': headers['SOAPAction'],
|
||||
'request_body': mask_secrets(body, client.get('credential')),
|
||||
'http_status': http_status,
|
||||
'response_body': response_text[:_WIRE_TEXT_LIMIT]}
|
||||
if http_status >= 400:
|
||||
return {
|
||||
'status': 'business_failed',
|
||||
'code': f"HTTP_{int(response.status_code)}",
|
||||
'code': f"HTTP_{http_status}",
|
||||
# 错误回显可能包含请求体(含凭据),先脱敏再截断。
|
||||
'message': mask_secrets(str(getattr(response, 'text', ''))[:2000], client.get('credential'))[:500],
|
||||
'_wire': wire,
|
||||
}
|
||||
response_text = mask_secrets(str(getattr(response, 'text', '') or ''), client.get('credential'))
|
||||
try:
|
||||
return _parse_soap_payload(response_text)
|
||||
parsed = _parse_soap_payload(response_text)
|
||||
except ET.ParseError:
|
||||
return {
|
||||
'status': 'technical_failed',
|
||||
'code': 'NON_XML',
|
||||
'message': response_text[:500],
|
||||
}
|
||||
return {'status': 'technical_failed', 'code': 'NON_XML',
|
||||
'message': response_text[:500], '_wire': wire}
|
||||
parsed['_wire'] = wire
|
||||
return parsed
|
||||
|
||||
def probe(self, *, client: dict) -> dict[str, Any]:
|
||||
"""连接测试探针:GET WSDL 地址并校验返回 XML,只证明网络与服务可达。
|
||||
|
||||
@@ -1275,28 +1275,28 @@ def submit_order_extraction_unit_result(
|
||||
run: Any,
|
||||
unit: Any,
|
||||
orders: list[dict[str, Any]],
|
||||
defer_stp_enqueue: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
单个 PDF/Unit 完成后立即落 Candidate 并按 STP 门禁建 Task,不等待同 Run 其它 Unit。
|
||||
单个 PDF/Unit 完成后立即落 Candidate 并幂等初始化 Review Case;不等待同 Run 其它 Unit。
|
||||
|
||||
核心逻辑:仅锁定本 Unit 的 Intake/Document;同 Run 续单元或未产生 Task/Batch 的重识别
|
||||
可安全复用已消费 Intake;复用 persist_order_extraction_result;
|
||||
通过门禁的 automatic Candidate 建批后由编排器触发 auto_progress;最后幂等初始化 Review Case。
|
||||
|
||||
[交接不变量] defer_stp_enqueue=True(Worker 开工快照仍有待排版附件、本 Job 必交接)时跳过
|
||||
本 Unit 的 STP 入队——Candidate/Review Case 仍即时物化,STP 统一由最后一个抽取 Job 的
|
||||
run 收口(submit_order_extraction_run_result)入队。否则本 Job 提交的 STP Job 会与续抽 Job
|
||||
并发执行,双方以相反顺序抢 run/intake 行锁形成结构性死锁(2026-09-22 生产事故)。
|
||||
[收口不变量] 本函数**不触发 STP 入队**——STP 统一由 run 收口
|
||||
(submit_order_extraction_run_result)与 run 状态同事务入队。若在此处逐单元入队,
|
||||
STP Job 会与仍在执行的抽取 Job 并发,双方以相反顺序争抢 run/intake 行锁与
|
||||
review_case/execution 行锁,形成结构性死锁(2026-09-22/24 生产与 test 事故)。
|
||||
用户显式确认/校验走 resume → ensure_stp_auto_create_for_case 的逐 Case 通道,不受影响。
|
||||
|
||||
Args:
|
||||
run: 所属 ShippingOrderProcessingRun。
|
||||
unit: 已进入 candidate_ready 的 ShippingOrderProcessingUnit。
|
||||
orders: 该 Unit 合并邮件补充后的订单数组。
|
||||
defer_stp_enqueue: True 时跳过 STP 入队(由 run 收口统一触发)。
|
||||
|
||||
Returns:
|
||||
与 submit_order_extraction_run_result 同形的业务摘要(作用域为本 Unit)。
|
||||
与 submit_order_extraction_run_result 同形的业务摘要(作用域为本 Unit);
|
||||
stp_auto_create 标记为 deferred_to_run_close_out。
|
||||
"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
snapshot_intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else []
|
||||
@@ -1441,12 +1441,10 @@ def submit_order_extraction_unit_result(
|
||||
result['unit_id'] = int(unit.id)
|
||||
from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit
|
||||
ensure_review_case_for_unit(run=run, unit=unit)
|
||||
# [交接不变量] defer_stp_enqueue=True 时跳过本 Unit 的 STP 入队,统一由 run 收口触发
|
||||
# (submit_order_extraction_run_result);否则 STP Job 会与本 Job 的续抽后继并发死锁。
|
||||
if not defer_stp_enqueue:
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import maybe_stp_auto_create_for_run
|
||||
|
||||
result['stp_auto_create'] = maybe_stp_auto_create_for_run(run=run)
|
||||
# [收口不变量] 单元提交不触发 STP 入队:STP 统一由 run 收口
|
||||
# (submit_order_extraction_run_result)与 run 状态同事务触发,保证 STP Job 可见时
|
||||
# 抽取 Job 已提交完毕,两者不再并发死锁(2026-09-22/24 事故族)。
|
||||
result['stp_auto_create'] = [{'status': 'deferred_to_run_close_out'}]
|
||||
_store_run_submission_result(
|
||||
intakes=current_intakes,
|
||||
snapshot_hash=str(run.input_snapshot_hash),
|
||||
|
||||
@@ -4789,23 +4789,22 @@ def progress_ready_extraction_unit(
|
||||
run: ShippingOrderProcessingRun,
|
||||
unit: Any,
|
||||
orders: list[dict[str, Any]],
|
||||
defer_stp_enqueue: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
单个 PDF/Unit 进入 candidate_ready 后立即物化 Candidate,并按 Review Case/STP 正式链触发下游。
|
||||
单个 PDF/Unit 进入 candidate_ready 后立即物化 Candidate 与 Review Case,并触发下游。
|
||||
|
||||
核心逻辑:不依赖同 Run 其它 Unit 完成;调用 unit 级 submit。自动建单与自动推进
|
||||
由 submit 内的 Review Case/STP 正式链异步协调,禁止此处再以已删除的 batch_no 或
|
||||
结果数组推断并直接调用旧 auto_progress,避免重复推进。
|
||||
|
||||
[交接不变量] defer_stp_enqueue=True(Worker 开工快照仍有待排版附件、本 Job 必交接)时
|
||||
推迟 STP 入队到 run 收口,防止 STP Job 与续抽 Job 并发死锁;Candidate/Review Case 仍即时物化。
|
||||
[收口不变量] STP 不在此处入队:unit 级 submit 只物化 Candidate/Review Case,
|
||||
STP 统一由 run 收口(submit_order_extraction_run_result)与 run 状态同事务触发,
|
||||
确保 STP Job 可见时抽取 Job 已提交完毕,两者不再并发死锁(2026-09-22/24 事故族)。
|
||||
|
||||
Args:
|
||||
run: 所属抽取 Run。
|
||||
unit: 已 candidate_ready 的 Unit。
|
||||
orders: 该 Unit 订单数组。
|
||||
defer_stp_enqueue: True 时跳过本 Unit 的 STP 入队(由 run 收口统一触发)。
|
||||
|
||||
Returns:
|
||||
Unit 级落库摘要(含 created / pending_orders)。
|
||||
@@ -4813,9 +4812,7 @@ def progress_ready_extraction_unit(
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_unit_result
|
||||
|
||||
mark_order_extraction_persistence_started(run)
|
||||
result = submit_order_extraction_unit_result(
|
||||
run=run, unit=unit, orders=orders, defer_stp_enqueue=defer_stp_enqueue,
|
||||
)
|
||||
result = submit_order_extraction_unit_result(run=run, unit=unit, orders=orders)
|
||||
return result
|
||||
|
||||
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
用途:接收收料 RPA 单元回调,原样归档文件三年且不写库存快照表;终态落库后
|
||||
通过收料回调桥推进在途调拨的 waiting_rpa_callback 来源任务(B3 接线)。
|
||||
依赖:models(ShippingReceiptReportFile/ShippingReceiptRpaUnitRun)、file_asset_storage、
|
||||
audit_service、in_transit_transfer.receipt_callback_bridge(惰性导入)。
|
||||
audit_service、in_transit_transfer.receipt_callback_bridge(惰性导入)、
|
||||
in_transit_transfer.evidence_sync(惰性导入,仅 success 终态)。
|
||||
逻辑:success/empty/failed 三个终态分支各自 commit 后调用 _advance_transfer_source_job;
|
||||
桥是记账不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。
|
||||
success 分支再触发调拨证据同步(sync_and_commit_for_callback);两座桥都是记账
|
||||
不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -132,6 +134,19 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
append_shipping_audit_event(event_type='shipping_receipt_report_archived', aggregate_type='shipping_receipt_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
|
||||
db.session.commit()
|
||||
_advance_transfer_source_job(unit, ok=True, file_no=str(record.id), file_sha256=sha256)
|
||||
# [调拨证据同步·主链路] success 终态文件落地即解析写调拨待办(本分支专属;
|
||||
# empty/failed 分支不触发同步)。桥模式失败仅日志,绝不影响收料归档主链路
|
||||
# (语义见 in_transit_transfer/evidence_sync.sync_and_commit_for_callback)。
|
||||
try:
|
||||
from datetime import datetime as _dt
|
||||
|
||||
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
|
||||
|
||||
sync_and_commit_for_callback(
|
||||
source_code=unit.source_code, business_date=str(_dt.utcnow().date()), now=_dt.utcnow(),
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 —— 双保险:桥内部已吞异常
|
||||
current_app.logger.warning('[receipt-callback] transfer evidence sync failed: %s', exc)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
# 文件通知不在此处逐文件发送:统一由排程终态归集后一次性推送(与库存 RPA 同构)。
|
||||
|
||||
Reference in new issue
Block a user