feat(in-transit-transfer): 外部调用切换集成连接器并新增调拨类型与在途仓编码
- 退役 erp_adapter/gateway_adapter:外部查询/写经 capability_client 走集成连接器,端点凭据与并发超时由客户端实例管理 - 域能力代码注册 capabilities:入参出参 Schema、幂等语义与读写标志随域代码版本化,组合根 create_app 幂等注册 - 新增调拨业务类型 transfer_type(在途仓至HUB/HUB维修出/HUB间)冻结枚举,迁移落 CheckConstraint 数据库兜底 - 外部仓库映射新增 in_transit_warehouse_code 拨出库位来源,管理端库存映射页同步维护 - 单据命名外部化:erp_* 字段与索引改称 external_*,单据号格式交由连接器映射,测试数据同步换牌 - 收料归档文件可用性判定收敛 receipt_file_gate 单一事实来源(当天抓取/保留期/清理态) - 同步 chat 调拨卡片、useChatTransfer、e2e、全套服务/API/Job 测试与域文档
This commit is contained in:
1 parent
31591e663e
commit
9959b06acd
97 files changed
+3525
-1489
No files matched your search
@@ -1177,6 +1177,7 @@ def _external_payload(mapping: ShippingInventoryExternalMapping) -> dict[str, An
|
||||
'freight_warehouse_id': mapping.freight_warehouse_id, 'external_system_code': mapping.external_system_code,
|
||||
'external_organization_code': mapping.external_organization_code, 'external_site_code': mapping.external_site_code,
|
||||
'external_warehouse_code': mapping.external_warehouse_code, 'external_warehouse_name': mapping.external_warehouse_name,
|
||||
'in_transit_warehouse_code': mapping.in_transit_warehouse_code,
|
||||
'enabled': bool(mapping.enabled), 'version': mapping.version,
|
||||
}
|
||||
|
||||
@@ -1208,9 +1209,11 @@ def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping
|
||||
raise ValidationError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
record = record or ShippingInventoryExternalMapping(inventory_source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='')
|
||||
record.inventory_source_id = source_id
|
||||
# 货代仓库是映射必要维度(调拨拨出仓库来源),不再支持"库存源默认映射";
|
||||
# 归一化为大写以与库存行 Warehouse 身份精确匹配。
|
||||
record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id', required=True)).upper()
|
||||
# 货代仓库改为可选维度:inventory_match 源按「收料文件仓库 == 货代仓库」匹配映射行,
|
||||
# 空值即「空库位」默认映射行;归一化为大写以与收料仓库值精确比对。
|
||||
record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id') or '').upper() or None
|
||||
# 在途仓编码是在途调拨拨出库位来源(DefaultRouteResolver),保存端必填并大写归一。
|
||||
record.in_transit_warehouse_code = str(_text(data, 'in_transit_warehouse_code', required=True)).upper()
|
||||
record.external_system_code = str(_text(data, 'external_system_code', required=True)).upper()
|
||||
record.external_organization_code = _text(data, 'external_organization_code')
|
||||
record.external_site_code = _text(data, 'external_site_code')
|
||||
|
||||
@@ -4,5 +4,5 @@
|
||||
依赖:同包 date_policy / status / quantity / strategy / contracts / audit;
|
||||
Phase 1 起扩展 file_preparation / precheck_service 等。
|
||||
逻辑:本包只承载调拨领域规则与确定性门禁,不混入 shipping_notice 订单解析;
|
||||
对外部系统(RPA/ERP/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
|
||||
对外部系统(RPA/外部系统/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
|
||||
"""
|
||||
@@ -108,7 +108,7 @@ def archive_snapshot(
|
||||
"""归档一份对象并持久化索引 + 审计。
|
||||
|
||||
Args:
|
||||
object_type: 对象类型(erp_inventory_snapshot / exception_excel / receipt_file)。
|
||||
object_type: 对象类型(external_inventory_snapshot / exception_excel / receipt_file)。
|
||||
object_id: 业务对象编号(precheck_no / run_no)。
|
||||
data: 待归档字节。
|
||||
original_filename: 原始文件名。
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
用途:组合"每日恢复 → 自动预检 → 自动执行 → 企微汇总通知",
|
||||
供 in-transit-transfer platform job 调用。
|
||||
依赖:recovery_service、precheck_service、execution_service、notification。
|
||||
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 ERP 结果。
|
||||
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 外部系统 结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -45,7 +45,7 @@ def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request
|
||||
|
||||
cancelled = 0
|
||||
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all():
|
||||
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.erp_document_no:
|
||||
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.external_document_no:
|
||||
item.status = status_machine.TransferStatus.CANCELLED.value
|
||||
item.result_code = "cancelled"
|
||||
item.result_message = reason_value
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
"""services/in_transit_transfer/capabilities.py
|
||||
|
||||
用途:在途调拨域的能力声明——本域经集成连接器暴露的能力契约(入参/出参 Schema、
|
||||
幂等语义、读写标志),代码注册、禁止管理端动态定义。
|
||||
依赖:integration_connector.capability(机制层:CapabilitySpec/注册表)。
|
||||
逻辑:本模块属于领域包而非连接器框架——框架只提供注册/校验机制,域契约随域代码
|
||||
版本化;应用组合根(app/__init__.py)在每次 create_app 时调用
|
||||
register_transfer_capabilities()(幂等),保证管理端「能力清单」冷启动即可见,
|
||||
测试 reset 注册表后也能重建。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.integration_connector.capability import (
|
||||
CapabilitySpec,
|
||||
list_capabilities,
|
||||
register_capability,
|
||||
)
|
||||
|
||||
# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。
|
||||
# 查询契约:按组织批量查库存,目标为 (料号, 拨出库位, 拨出批号) 元组列表;
|
||||
# external_org 取自仓库映射(external_organization_code),由绑定参数映射翻译为接口的 organization。
|
||||
_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"],
|
||||
"properties": {
|
||||
"material_no": {"type": "string"},
|
||||
"from_warehouse": {"type": "string"},
|
||||
"lot_no": {"type": "string"},
|
||||
},
|
||||
}},
|
||||
},
|
||||
}
|
||||
_QUERY_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["rows"],
|
||||
"properties": {
|
||||
"rows": {"type": "array", "items": {
|
||||
"type": "object",
|
||||
"required": ["material_no", "from_warehouse", "lot_no", "quantity"],
|
||||
"properties": {
|
||||
"material_no": {"type": "string"},
|
||||
"from_warehouse": {"type": "string"},
|
||||
"lot_no": {"type": "string"},
|
||||
"quantity": {"type": "number"},
|
||||
},
|
||||
}},
|
||||
},
|
||||
}
|
||||
_WRITE_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["status"],
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"],
|
||||
},
|
||||
"document_no": {"type": ["string", "null"]},
|
||||
"verified_posted": {"type": ["boolean", "null"]},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def register_transfer_capabilities() -> None:
|
||||
"""注册在途调拨域的三个能力(幂等:已注册的同名跳过)。
|
||||
|
||||
幂等是硬要求:组合根每次 create_app 都会调用;测试 reset 注册表后(模块缓存导致
|
||||
import 副作用不再执行)也依赖本函数重建,故不能依赖「只注册一次」。
|
||||
"""
|
||||
registered = {spec.name for spec in list_capabilities()}
|
||||
for spec in (
|
||||
CapabilitySpec(
|
||||
name="in_transit_transfer.query_inventory",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_QUERY_OUTPUT_SCHEMA,
|
||||
idempotency="none",
|
||||
write=False,
|
||||
),
|
||||
CapabilitySpec(
|
||||
name="in_transit_transfer.create_transfer",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_WRITE_OUTPUT_SCHEMA,
|
||||
idempotency="invoice",
|
||||
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)
|
||||
|
||||
|
||||
register_transfer_capabilities()
|
||||
@@ -0,0 +1,283 @@
|
||||
"""services/in_transit_transfer/capability_client.py
|
||||
|
||||
用途:在途调拨域的外部访问统一客户端——查询经 CapabilityGateway 按能力批量调用;
|
||||
写路径在外部契约冻结前 fail-closed(Phase 2 接线点);域异常与写结果分类集中于此。
|
||||
依赖:integration_connector.gateway / errors、app.core.errors。
|
||||
逻辑:查询按 (料号, 拨出库位, 拨出批号) 元组批量进行,组织键 external_org 取自
|
||||
仓库映射(external_organization_code);查询超时→ExternalQueryTimeoutError,
|
||||
网关失败→AppError;写 transport 未注入时 create_transfer/verify_duplicate
|
||||
抛 ExternalNotFrozenError,注入后超时分类为 technical_failed / result_unknown。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
|
||||
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
|
||||
|
||||
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):
|
||||
"""外部系统查询超时(只读路径,允许上层重试)。"""
|
||||
|
||||
def __init__(self, message: str = "external query timeout"):
|
||||
super().__init__(code=EXTERNAL_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True)
|
||||
|
||||
|
||||
class ExternalResultUnknownError(AppError):
|
||||
"""外部系统写结果无法确认(Phase 2 使用);禁止自动重试。"""
|
||||
|
||||
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:
|
||||
"""外部系统原子建单/审核/过账结果分类。"""
|
||||
|
||||
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
|
||||
document_no: str | None = None
|
||||
verified_posted: bool | None = None
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StockTarget:
|
||||
"""库存查询目标元组:料号 + 拨出库位 + 拨出批号。"""
|
||||
|
||||
material_no: str
|
||||
from_warehouse: str
|
||||
lot_no: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StockRow:
|
||||
"""外部系统返回的一行账面库存。"""
|
||||
|
||||
material_no: str
|
||||
from_warehouse: str
|
||||
lot_no: str
|
||||
quantity: Decimal
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StockQueryResult:
|
||||
"""一次批量库存查询的结果;按元组精确匹配取数。"""
|
||||
|
||||
rows: tuple[StockRow, ...]
|
||||
|
||||
def lookup(self, *, material_no: str, from_warehouse: 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):
|
||||
total = row.quantity if total is None else total + row.quantity
|
||||
return total
|
||||
|
||||
|
||||
class CapabilityClient:
|
||||
"""域内外部访问统一客户端:查询经 CapabilityGateway,写路径 fail-closed。
|
||||
|
||||
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:
|
||||
self._gateway_override = gateway
|
||||
self._write_transport = write_transport
|
||||
|
||||
def _gateway(self) -> Any:
|
||||
if self._gateway_override is not None:
|
||||
return self._gateway_override
|
||||
from app.services.integration_connector.gateway import get_capability_gateway
|
||||
|
||||
return get_capability_gateway()
|
||||
|
||||
def query_stock(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
external_org: str,
|
||||
targets: list[StockTarget],
|
||||
) -> StockQueryResult:
|
||||
"""按组织批量查询库存(一次调用覆盖全部目标元组)。
|
||||
|
||||
Raises:
|
||||
ExternalQueryTimeoutError: 查询超时(可重试)。
|
||||
AppError: 网关失败(绑定缺失/调用失败,fail-closed)。
|
||||
"""
|
||||
if not targets:
|
||||
return StockQueryResult(rows=())
|
||||
result = self._gateway().call(
|
||||
capability=QUERY_INVENTORY_CAPABILITY,
|
||||
context={},
|
||||
params={
|
||||
"external_org": external_org,
|
||||
"targets": [
|
||||
{
|
||||
"material_no": target.material_no,
|
||||
"from_warehouse": target.from_warehouse,
|
||||
"lot_no": target.lot_no,
|
||||
}
|
||||
for target in targets
|
||||
],
|
||||
},
|
||||
operation_id=operation_id,
|
||||
)
|
||||
if result.status == "timeout":
|
||||
raise ExternalQueryTimeoutError()
|
||||
if result.status != "success":
|
||||
raise AppError(
|
||||
code=result.error_code or "INTEGRATION.CALL_FAILED",
|
||||
message=result.error_message or "query_inventory failed",
|
||||
http_status=503,
|
||||
retryable=False,
|
||||
)
|
||||
rows = [
|
||||
StockRow(
|
||||
material_no=str(row.get("material_no") or ""),
|
||||
from_warehouse=str(row.get("from_warehouse") or ""),
|
||||
lot_no=str(row.get("lot_no") or ""),
|
||||
quantity=Decimal(str(row.get("quantity") or "0")),
|
||||
)
|
||||
for row in ((result.data or {}).get("rows") or [])
|
||||
]
|
||||
return StockQueryResult(rows=tuple(rows))
|
||||
|
||||
def create_transfer(
|
||||
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:
|
||||
"""外部系统原子建单/审核/过账并按结果分类。
|
||||
|
||||
Returns:
|
||||
TransferWriteResult:success / duplicate_success / duplicate_unverified /
|
||||
business_failed / technical_failed / result_unknown。
|
||||
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)
|
||||
|
||||
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。
|
||||
"""
|
||||
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",
|
||||
)
|
||||
|
||||
|
||||
def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult:
|
||||
"""按外部系统写响应原文分类业务结果。"""
|
||||
status = str(response.get("status") or "")
|
||||
document_no = response.get("document_no")
|
||||
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",
|
||||
)
|
||||
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 ""),
|
||||
)
|
||||
return TransferWriteResult(status="technical_failed", error_code="EXTERNAL_UNKNOWN_RESPONSE")
|
||||
@@ -42,16 +42,18 @@ class TransferPrecheckAction:
|
||||
"""执行只读预检并输出 transfer-precheck 卡片。
|
||||
|
||||
【AI 触发时机】:用户表达"查询今天可调拨 / 预检"等意图后由候选 Action 触发;
|
||||
只读,不写 ERP。
|
||||
只读,不写 外部系统。
|
||||
"""
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
source_codes = [str(item).strip() for item in (payload.get("source_codes") or [])]
|
||||
business_date = str(payload.get("business_date") or business_date_now())
|
||||
transfer_type = str(payload.get("transfer_type")) if payload.get("transfer_type") else None
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
summary = create_precheck(
|
||||
source_codes=source_codes,
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
transfer_type=transfer_type,
|
||||
)
|
||||
detail = restore_precheck(summary.precheck_id)
|
||||
yield _message(
|
||||
@@ -71,7 +73,7 @@ class TransferExecuteAction:
|
||||
"""执行勾选范围并输出 transfer-result 卡片。
|
||||
|
||||
【AI 触发时机】:用户在预检卡点击"直接生成调拨单"后触发;
|
||||
后台确定性服务完成写前复查与 ERP 原子写入。
|
||||
后台确定性服务完成写前复查与 外部系统 原子写入。
|
||||
"""
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
precheck_id = str(payload.get("precheck_id") or "").strip()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨并发参数与单写者约束。
|
||||
|
||||
用途:冻结来源并发(2)、ERP 查询并发(2)与 ERP 写并发(1)默认值;
|
||||
ERP 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
|
||||
用途:冻结来源并发(2)、外部系统 查询并发(2)与 外部系统 写并发(1)默认值;
|
||||
外部系统 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
|
||||
依赖:无(纯常量)。
|
||||
逻辑:写并发 1 与"同 Invoice 执行数=1"为一期硬约束,禁止运行时提升。
|
||||
"""
|
||||
@@ -10,8 +10,8 @@ from __future__ import annotations
|
||||
|
||||
# 一期冻结并发参数(与规格 §10 一致)。
|
||||
SOURCE_CONCURRENCY = 3
|
||||
ERP_QUERY_CONCURRENCY = 3
|
||||
ERP_WRITE_CONCURRENCY = 3
|
||||
外部系统_QUERY_CONCURRENCY = 3
|
||||
外部系统_WRITE_CONCURRENCY = 3
|
||||
|
||||
|
||||
def assert_single_writer(run_count: int) -> None:
|
||||
@@ -22,4 +22,4 @@ def assert_single_writer(run_count: int) -> None:
|
||||
Raises:
|
||||
AssertionError: run_count > 1(一期硬约束)。
|
||||
"""
|
||||
assert run_count <= 1, "ERP write concurrency must stay 1 for the same precheck"
|
||||
assert run_count <= 1, "External write concurrency must stay 1 for the same precheck"
|
||||
@@ -1,10 +1,10 @@
|
||||
"""在途调拨 DTO 与稳定错误码契约。
|
||||
|
||||
用途:冻结前后端契约(预检摘要、明细项、ERP 单据聚合结果)与一期错误码,
|
||||
用途:冻结前后端契约(预检摘要、明细项、外部系统 单据聚合结果)与一期错误码,
|
||||
保证前端只依赖稳定 DTO、不感知 SOAP/WSDL/文件路径。
|
||||
依赖:标准库 dataclasses / decimal。
|
||||
逻辑:DTO 全部 frozen;aggregate_erp_documents 按 ERP 单号聚合最终结果页
|
||||
(决策 20:ERP 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。
|
||||
逻辑:DTO 全部 frozen;aggregate_external_documents 按 外部系统 单号聚合最终结果页
|
||||
(决策 20:外部系统 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,7 +20,7 @@ TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY"
|
||||
TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
|
||||
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
|
||||
TRANSFER_QUANTITY_MISMATCH = "TRANSFER_QUANTITY_MISMATCH"
|
||||
TRANSFER_ERP_INVENTORY_NOT_FOUND = "TRANSFER_ERP_INVENTORY_NOT_FOUND"
|
||||
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND = "TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND"
|
||||
TRANSFER_PRECHECK_EXPIRED = "TRANSFER_PRECHECK_EXPIRED"
|
||||
TRANSFER_CONFIRMATION_REQUIRED = "TRANSFER_CONFIRMATION_REQUIRED"
|
||||
TRANSFER_DUPLICATE_NOT_VERIFIED = "TRANSFER_DUPLICATE_NOT_VERIFIED"
|
||||
@@ -37,7 +37,7 @@ KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
|
||||
TRANSFER_FILE_SCHEMA_INVALID,
|
||||
TRANSFER_INVOICE_CONFLICT,
|
||||
TRANSFER_QUANTITY_MISMATCH,
|
||||
TRANSFER_ERP_INVENTORY_NOT_FOUND,
|
||||
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND,
|
||||
TRANSFER_PRECHECK_EXPIRED,
|
||||
TRANSFER_CONFIRMATION_REQUIRED,
|
||||
TRANSFER_DUPLICATE_NOT_VERIFIED,
|
||||
@@ -98,14 +98,16 @@ class PrecheckInvoiceItemDTO:
|
||||
result: str
|
||||
receipt_date: str | None = None
|
||||
reason: str = ""
|
||||
erp_document_no: str | None = None
|
||||
external_document_no: str | None = None
|
||||
raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple)
|
||||
lot_no: str = ""
|
||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
|
||||
receipt_warehouse_code: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PrecheckSummaryDTO:
|
||||
"""预检摘要(含预计调拨数量、预计 ERP 写入数与预检 Hash)。"""
|
||||
"""预检摘要(含预计调拨数量、预计 外部系统 写入数与预检 Hash)。"""
|
||||
|
||||
precheck_id: str
|
||||
status: str
|
||||
@@ -114,14 +116,14 @@ class PrecheckSummaryDTO:
|
||||
expires_at: str
|
||||
counts: PrecheckCountsDTO
|
||||
estimated_transfer_quantity: str
|
||||
estimated_erp_write_count: int
|
||||
estimated_external_write_count: int
|
||||
precheck_hash: str
|
||||
|
||||
|
||||
# ---- 结果页 DTO(决策 20)--------------------------------------------------
|
||||
@dataclass(frozen=True)
|
||||
class ErpDocumentLineDTO:
|
||||
"""ERP 单据内物料明细。"""
|
||||
class ExternalDocumentLineDTO:
|
||||
"""外部系统 单据内物料明细。"""
|
||||
|
||||
material_no: str
|
||||
material_name: str
|
||||
@@ -131,8 +133,8 @@ class ErpDocumentLineDTO:
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ErpDocumentDTO:
|
||||
"""按 ERP 单号聚合的结果项。"""
|
||||
class ExternalDocumentDTO:
|
||||
"""按 外部系统 单号聚合的结果项。"""
|
||||
|
||||
document_no: str
|
||||
from_warehouse: str
|
||||
@@ -140,12 +142,12 @@ class ErpDocumentDTO:
|
||||
material_count: int
|
||||
total_quantity: Decimal
|
||||
posting_status: str
|
||||
lines: tuple[ErpDocumentLineDTO, ...] = field(default_factory=tuple)
|
||||
lines: tuple[ExternalDocumentLineDTO, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferExceptionDTO:
|
||||
"""未生成 ERP 单据的异常项(单独展示)。"""
|
||||
"""未生成 外部系统 单据的异常项(单独展示)。"""
|
||||
|
||||
source_code: str
|
||||
invoice_no: str
|
||||
@@ -156,31 +158,31 @@ class TransferExceptionDTO:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RunResultDTO:
|
||||
"""Run 最终结果投影:ERP 单据聚合 + 未生成单据异常。"""
|
||||
"""Run 最终结果投影:外部系统 单据聚合 + 未生成单据异常。"""
|
||||
|
||||
run_no: str
|
||||
status: str
|
||||
erp_documents: tuple[ErpDocumentDTO, ...] = field(default_factory=tuple)
|
||||
external_documents: tuple[ExternalDocumentDTO, ...] = field(default_factory=tuple)
|
||||
exceptions: tuple[TransferExceptionDTO, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ErpDocumentDTO, ...]:
|
||||
"""按 ERP 单号聚合成功项,产出结果页文档视图。
|
||||
def aggregate_external_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ExternalDocumentDTO, ...]:
|
||||
"""按 外部系统 单号聚合成功项,产出结果页文档视图。
|
||||
|
||||
Args:
|
||||
items: 预检明细项(含 erp_document_no 与 result)。
|
||||
items: 预检明细项(含 external_document_no 与 result)。
|
||||
Returns:
|
||||
按单号聚合的 ErpDocumentDTO 元组(行按 Invoice 排序)。
|
||||
按单号聚合的 ExternalDocumentDTO 元组(行按 Invoice 排序)。
|
||||
"""
|
||||
grouped: dict[str, list[PrecheckInvoiceItemDTO]] = {}
|
||||
for item in items:
|
||||
if item.erp_document_no and item.result in {"success", "duplicate_success"}:
|
||||
grouped.setdefault(item.erp_document_no, []).append(item)
|
||||
documents: list[ErpDocumentDTO] = []
|
||||
if item.external_document_no and item.result in {"success", "duplicate_success"}:
|
||||
grouped.setdefault(item.external_document_no, []).append(item)
|
||||
documents: list[ExternalDocumentDTO] = []
|
||||
for document_no in sorted(grouped):
|
||||
rows = sorted(grouped[document_no], key=lambda row: row.invoice_no)
|
||||
lines = tuple(
|
||||
ErpDocumentLineDTO(
|
||||
ExternalDocumentLineDTO(
|
||||
material_no=row.material_no,
|
||||
material_name=row.material_name,
|
||||
specification=row.specification,
|
||||
@@ -189,7 +191,7 @@ def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[Er
|
||||
)
|
||||
for row in rows
|
||||
)
|
||||
documents.append(ErpDocumentDTO(
|
||||
documents.append(ExternalDocumentDTO(
|
||||
document_no=document_no,
|
||||
from_warehouse=rows[0].from_warehouse,
|
||||
to_warehouse=rows[0].to_warehouse,
|
||||
|
||||
@@ -62,6 +62,29 @@ def business_date_now(moment: datetime | None = None) -> date:
|
||||
return moment.astimezone(SHANGHAI_TZ).date()
|
||||
|
||||
|
||||
def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
|
||||
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
|
||||
|
||||
用途:判定"文件是否当天抓取"等新鲜度场景。数据库统一存 naive UTC 时间,
|
||||
直接取 .date() 与业务日期比较会漂移 8 小时,必须先换算窗口再比较。
|
||||
Args:
|
||||
now: 可选时刻;naive 按 UTC 兼容处理(与 business_date_now 口径一致)。
|
||||
Returns:
|
||||
(窗口起, 窗口止);两者均为 naive UTC datetime,止为开区间(时长 24h)。
|
||||
"""
|
||||
if now is None:
|
||||
now = datetime.now(SHANGHAI_TZ)
|
||||
if now.tzinfo is None:
|
||||
now = now.replace(tzinfo=ZoneInfo("UTC"))
|
||||
sh_now = now.astimezone(SHANGHAI_TZ)
|
||||
start_utc = (
|
||||
datetime(sh_now.year, sh_now.month, sh_now.day, tzinfo=SHANGHAI_TZ)
|
||||
.astimezone(ZoneInfo("UTC"))
|
||||
.replace(tzinfo=None)
|
||||
)
|
||||
return start_utc, start_utc + timedelta(hours=24)
|
||||
|
||||
|
||||
def maturity_status(receipt_date: date | str, business_date: date | str) -> str:
|
||||
"""按 D+1 规则判定收料日期成熟度。
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
"""在途调拨依赖装配(Dependencies)。
|
||||
|
||||
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
|
||||
依赖:movement_file_repository / gateway_adapter / precheck_service / models。
|
||||
依赖:movement_file_repository / capability_client / precheck_service / models。
|
||||
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
|
||||
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
|
||||
预检走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
|
||||
fail-closed 拒绝;ERP 访问走 CapabilityGateway(绑定缺失时 fail-closed)。
|
||||
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,7 +13,7 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
|
||||
from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter
|
||||
from app.services.in_transit_transfer.capability_client import CapabilityClient
|
||||
from app.services.in_transit_transfer.movement_file_repository import ShippingReceiptFileRepository
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
RouteMapping,
|
||||
@@ -24,40 +24,66 @@ from app.services.in_transit_transfer.precheck_service import (
|
||||
|
||||
|
||||
class DefaultRouteResolver:
|
||||
"""默认路由解析:仓库映射的货代仓库 + 外部系统仓库。
|
||||
"""默认路由解析:仓库映射的在途仓编码 + 外部系统仓库。
|
||||
|
||||
拨出仓库 = 映射行的货代仓库(货现在所在的 WMS 仓);拨入仓库 = 映射的
|
||||
目标仓库代码。不借用站点固定仓库(那是货代发货/库存导出链路的字段)。
|
||||
拨出库位 = 映射行的在途仓编码(in_transit_warehouse_code);拨入仓库 = 映射的
|
||||
目标仓库代码;组织 = 映射的外部组织编码。映射行按库存源识别方式选择:
|
||||
inventory_match 源优先「收料文件仓库列 == 货代仓库」精确匹配,匹配不到回退
|
||||
货代仓库为空的默认映射行(空库位兜底);fixed 源仅一条启用映射直接取用。
|
||||
不借用站点固定仓库(那是货代发货/库存导出链路的字段)。
|
||||
"""
|
||||
|
||||
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
|
||||
"""按来源配置与外部映射解析路由;无法归属时抛 RouteNotResolvedError。"""
|
||||
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
|
||||
"""按来源识别方式选择映射行并解析路由;无法归属时抛 RouteNotResolvedError。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(须启用)。
|
||||
invoice_no: Invoice 单号(当前不参与匹配,保留协议兼容)。
|
||||
warehouse_code: 收料文件「仓库」列原值(inventory_match 源的映射匹配键)。
|
||||
Returns:
|
||||
RouteMapping(external_org / from_warehouse=在途仓编码 / to_warehouse)。
|
||||
Raises:
|
||||
RouteNotResolvedError: 来源不存在、无可用映射行或在途仓编码未维护。
|
||||
"""
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
mapping = ShippingInventoryExternalMapping.query.filter_by(
|
||||
mappings = ShippingInventoryExternalMapping.query.filter_by(
|
||||
inventory_source_id=source.id, enabled=True,
|
||||
).first()
|
||||
if mapping is None or not mapping.external_organization_code:
|
||||
).all()
|
||||
selected = None
|
||||
if getattr(source, 'warehouse_resolution_mode', '') == 'inventory_match':
|
||||
# [匹配] 收料仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。
|
||||
# 部分唯一索引保证同源「精确/默认」各最多一条启用映射,选择结果确定。
|
||||
key = str(warehouse_code or '').strip().upper()
|
||||
if key:
|
||||
selected = next(
|
||||
(m for m in mappings if str(m.freight_warehouse_id or '').strip().upper() == key), None,
|
||||
)
|
||||
if selected is None:
|
||||
selected = next((m for m in mappings if not str(m.freight_warehouse_id or '').strip()), None)
|
||||
else:
|
||||
selected = mappings[0] if mappings else None
|
||||
if selected is None or not selected.external_organization_code:
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
from_warehouse = str(mapping.freight_warehouse_id or "").strip()
|
||||
from_warehouse = str(selected.in_transit_warehouse_code or '').strip()
|
||||
if not from_warehouse:
|
||||
# 拨出仓库无来源(映射未维护货代仓库)——fail-closed,不猜测。
|
||||
# 拨出库位无来源(映射未维护在途仓编码)——fail-closed,不猜测。
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
return RouteMapping(
|
||||
erp_org=mapping.external_organization_code,
|
||||
external_org=selected.external_organization_code,
|
||||
from_warehouse=from_warehouse,
|
||||
to_warehouse=mapping.external_warehouse_code,
|
||||
to_warehouse=selected.external_warehouse_code,
|
||||
)
|
||||
|
||||
|
||||
def _build_erp_adapter() -> CapabilityErpAdapter:
|
||||
"""装配调拨 ERP 访问:默认走 CapabilityGateway(query_inventory 首消费者)。
|
||||
def _build_capability_client() -> CapabilityClient:
|
||||
"""装配调拨外部访问客户端:查询走 CapabilityGateway(绑定缺失时 fail-closed)。
|
||||
|
||||
P1 连接器框架:外部系统差异由配置(ClientInstance/InterfaceDefinition/Binding/映射)
|
||||
承担;缺绑定/契约未冻结时 fail-closed。create_transfer/verify_duplicate 待执行阶段接线。
|
||||
承担;create_transfer/verify_duplicate 在 WSDL 冻结前 fail-closed(Phase 2 接线)。
|
||||
"""
|
||||
return CapabilityErpAdapter()
|
||||
return CapabilityClient()
|
||||
|
||||
|
||||
_override: TransferDeps | None = None
|
||||
@@ -70,14 +96,14 @@ def set_transfer_dependencies(deps: TransferDeps | None) -> None:
|
||||
|
||||
|
||||
def get_transfer_dependencies() -> TransferDeps:
|
||||
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/ERP 网关)。"""
|
||||
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/外部系统 网关)。"""
|
||||
if _override is not None:
|
||||
return _override
|
||||
return TransferDeps(
|
||||
file_repository=ShippingReceiptFileRepository(),
|
||||
rpa_trigger=_DefaultRpaTrigger(),
|
||||
route_resolver=DefaultRouteResolver(),
|
||||
erp=_build_erp_adapter(),
|
||||
capabilities=_build_capability_client(),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,295 +0,0 @@
|
||||
"""在途调拨 ERP 访问统一边界(Adapter)。
|
||||
|
||||
用途:隔离全部 ERP 请求;业务服务只允许经本模块访问 ERP。
|
||||
Phase 1 启用只读 query_inventory;Phase 2 增加 create_transfer /
|
||||
verify_duplicate / 结果分类。
|
||||
依赖:typing.Protocol 传输层(测试注入 FakeERP;生产为 SOAP 传输)。
|
||||
逻辑:请求统一携带 operation_id / run_no / attempt_no / invoice_no /
|
||||
erp_org / 拨出仓 / 拨入仓 / 数量;查询超时分类为可重试;
|
||||
SOAP 传输在 WSDL/endpoint 冻结前 fail-closed(ErpNotFrozenError)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from typing import Any, Protocol
|
||||
|
||||
from app.core.errors import AppError
|
||||
|
||||
ERP_NOT_FROZEN_CODE = "TRANSFER.ERP_NOT_FROZEN"
|
||||
ERP_QUERY_TIMEOUT_CODE = "TRANSFER.ERP_QUERY_TIMEOUT"
|
||||
ERP_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InventoryQuery:
|
||||
"""ERP 账面库存查询结果。"""
|
||||
|
||||
found: bool
|
||||
quantity: Decimal | None = None
|
||||
document_no: str | None = None
|
||||
|
||||
|
||||
class ErpNotFrozenError(AppError):
|
||||
"""ERP WSDL/endpoint 尚未冻结,禁止调用(fail-closed)。"""
|
||||
|
||||
def __init__(self, message: str = "ERP contract not frozen"):
|
||||
super().__init__(code=ERP_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
|
||||
|
||||
|
||||
class ErpQueryTimeoutError(AppError):
|
||||
"""ERP 查询超时(只读路径,允许上层重试)。"""
|
||||
|
||||
def __init__(self, message: str = "ERP query timeout"):
|
||||
super().__init__(code=ERP_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True)
|
||||
|
||||
|
||||
class ErpResultUnknownError(AppError):
|
||||
"""ERP 写结果无法确认(Phase 2 使用);禁止自动重试。"""
|
||||
|
||||
def __init__(self, message: str = "ERP result unknown", *, operation_id: str | None = None):
|
||||
details = {"operation_id": operation_id} if operation_id else {}
|
||||
super().__init__(code=ERP_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details)
|
||||
|
||||
|
||||
class ErpWriteTimeoutError(TimeoutError):
|
||||
"""ERP 写超时;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:
|
||||
"""ERP 原子建单/审核/过账结果分类。"""
|
||||
|
||||
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
|
||||
document_no: str | None = None
|
||||
verified_posted: bool | None = None
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
class ErpTransport(Protocol):
|
||||
"""ERP 传输层协议(SOAP 或测试替身)。"""
|
||||
|
||||
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""按 Invoice 查询账面库存。"""
|
||||
|
||||
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""原子建单/审核/过账(Phase 2)。"""
|
||||
|
||||
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""核实重复 Invoice 原单是否已审核过账。"""
|
||||
|
||||
|
||||
class SoapErpTransport:
|
||||
"""真实 SOAP 传输;凭据只来自配置/环境,不写入请求体回显。
|
||||
|
||||
Args:
|
||||
config: 来自 Flask config 或环境变量(endpoint/username/password 等)。
|
||||
"""
|
||||
|
||||
def __init__(self, config: dict[str, Any] | None = None) -> None:
|
||||
self._config = config or {}
|
||||
|
||||
def _require_frozen(self, operation: str) -> None:
|
||||
"""WSDL/endpoint 未冻结前任何调用直接拒绝。"""
|
||||
if not str(self._config.get("endpoint") or "").strip():
|
||||
raise ErpNotFrozenError(f"ERP {operation} contract not frozen (endpoint missing)")
|
||||
|
||||
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""SOAP 查询账面库存(实现待 WSDL 冻结后落地)。"""
|
||||
self._require_frozen("query_inventory")
|
||||
raise NotImplementedError("SOAP query_inventory implementation pending frozen WSDL")
|
||||
|
||||
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""SOAP 原子建单/审核/过账(实现待 WSDL 冻结后落地)。"""
|
||||
self._require_frozen("create_transfer")
|
||||
raise NotImplementedError("SOAP create_transfer implementation pending frozen WSDL")
|
||||
|
||||
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""SOAP 核实重复 Invoice 原单状态(实现待 WSDL 冻结后落地)。"""
|
||||
self._require_frozen("verify_duplicate")
|
||||
raise NotImplementedError("SOAP verify_duplicate implementation pending frozen WSDL")
|
||||
|
||||
|
||||
class ErpAdapter:
|
||||
"""ERP 唯一访问入口;组装统一请求并分类结果。"""
|
||||
|
||||
def __init__(self, transport: ErpTransport, *, default_org: str = "") -> None:
|
||||
self._transport = transport
|
||||
self._default_org = default_org
|
||||
|
||||
def query_inventory(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str | None = None,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> InventoryQuery:
|
||||
"""查询 ERP 账面库存并分类结果。
|
||||
|
||||
Args:
|
||||
operation_id / run_no / attempt_no / invoice_no / erp_org /
|
||||
from_warehouse / to_warehouse / quantity: 请求强制追踪字段。
|
||||
Returns:
|
||||
InventoryQuery。
|
||||
Raises:
|
||||
ErpQueryTimeoutError: 查询超时(可重试)。
|
||||
ErpNotFrozenError: ERP 契约未冻结。
|
||||
"""
|
||||
request = {
|
||||
"operation_id": operation_id,
|
||||
"run_no": run_no,
|
||||
"attempt_no": attempt_no,
|
||||
"invoice_no": invoice_no,
|
||||
"erp_org": erp_org or self._default_org,
|
||||
"from_warehouse": from_warehouse,
|
||||
"to_warehouse": to_warehouse,
|
||||
"quantity": quantity,
|
||||
}
|
||||
try:
|
||||
response = self._transport.query_inventory(**request)
|
||||
except ErpNotFrozenError:
|
||||
raise
|
||||
except TimeoutError as exc:
|
||||
raise ErpQueryTimeoutError() from exc
|
||||
response = response if isinstance(response, dict) else {}
|
||||
if response.get("found"):
|
||||
return InventoryQuery(found=True, quantity=Decimal(str(response.get("quantity") or "0")))
|
||||
return InventoryQuery(found=False)
|
||||
|
||||
def _build_request(self, *, operation_id, run_no, attempt_no, invoice_no, erp_org,
|
||||
from_warehouse, to_warehouse, quantity) -> dict[str, Any]:
|
||||
"""组装携带全部强制追踪字段的 ERP 请求。"""
|
||||
return {
|
||||
"operation_id": operation_id,
|
||||
"run_no": run_no,
|
||||
"attempt_no": attempt_no,
|
||||
"invoice_no": invoice_no,
|
||||
"erp_org": erp_org or self._default_org,
|
||||
"from_warehouse": from_warehouse,
|
||||
"to_warehouse": to_warehouse,
|
||||
"quantity": quantity,
|
||||
}
|
||||
|
||||
def create_transfer(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str | None = None,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> TransferWriteResult:
|
||||
"""ERP 原子建单/审核/过账并按结果分类。
|
||||
|
||||
Returns:
|
||||
TransferWriteResult:success / duplicate_success / duplicate_unverified /
|
||||
business_failed / technical_failed / result_unknown。
|
||||
Raises:
|
||||
ErpNotFrozenError: ERP 契约未冻结。
|
||||
"""
|
||||
request = self._build_request(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
|
||||
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
|
||||
to_warehouse=to_warehouse, quantity=quantity,
|
||||
)
|
||||
try:
|
||||
response = self._transport.create_transfer(**request)
|
||||
except ErpNotFrozenError:
|
||||
raise
|
||||
except ErpWriteTimeoutError as exc:
|
||||
if exc.committed is False:
|
||||
# 可证明未落单 → 明确技术失败(不产生单据)。
|
||||
return TransferWriteResult(status="technical_failed", error_code="ERP_TIMEOUT_BEFORE_COMMIT")
|
||||
return TransferWriteResult(
|
||||
status="result_unknown", error_code="ERP_TIMEOUT_AFTER_COMMIT",
|
||||
document_no=exc.document_no,
|
||||
)
|
||||
except TimeoutError:
|
||||
# 无法区分是否落单 → result_unknown,禁止自动重试。
|
||||
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
|
||||
return _classify_write_response(response)
|
||||
|
||||
def verify_duplicate(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str | None = None,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> TransferWriteResult:
|
||||
"""核实重复 Invoice 原单是否已审核过账(幂等确认)。
|
||||
|
||||
Returns:
|
||||
duplicate_success(已过账,含原单号)或 duplicate_unverified。
|
||||
"""
|
||||
request = self._build_request(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
|
||||
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
|
||||
to_warehouse=to_warehouse, quantity=quantity,
|
||||
)
|
||||
try:
|
||||
response = self._transport.verify_duplicate(**request)
|
||||
except ErpNotFrozenError:
|
||||
raise
|
||||
except (TimeoutError, ErpWriteTimeoutError):
|
||||
return TransferWriteResult(status="result_unknown", error_code="ERP_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",
|
||||
)
|
||||
|
||||
|
||||
def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult:
|
||||
"""按 ERP 写响应原文分类业务结果。"""
|
||||
status = str(response.get("status") or "")
|
||||
document_no = response.get("document_no")
|
||||
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",
|
||||
)
|
||||
if status == "business_failed":
|
||||
return TransferWriteResult(
|
||||
status="business_failed",
|
||||
error_code=str(response.get("code") or "ERP_BUSINESS_REJECT"),
|
||||
error_message=str(response.get("message") or ""),
|
||||
)
|
||||
return TransferWriteResult(status="technical_failed", error_code="ERP_UNKNOWN_RESPONSE")
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨七 Sheet 异常 Excel 导出。
|
||||
|
||||
用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/ERP无库存/
|
||||
ERP技术失败/ERP结果未知/通知失败/原始文件追溯),供企微附件与下载。
|
||||
用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/外部系统无库存/
|
||||
外部系统技术失败/外部系统结果未知/通知失败/原始文件追溯),供企微附件与下载。
|
||||
依赖:openpyxl、models、execution_service。
|
||||
逻辑:Sheet 内容按状态归类;原始文件追溯保留 Sheet/行号/文件版本;
|
||||
Secret 明文永不写入单元格(仅输出业务字段)。
|
||||
@@ -21,9 +21,9 @@ from app.core.errors import NotFoundError
|
||||
EXCEL_SHEET_NAMES = [
|
||||
"执行汇总",
|
||||
"数量不一致",
|
||||
"ERP无库存",
|
||||
"ERP技术失败",
|
||||
"ERP结果未知",
|
||||
"外部系统无库存",
|
||||
"外部系统技术失败",
|
||||
"外部系统结果未知",
|
||||
"通知失败",
|
||||
"原始文件追溯",
|
||||
]
|
||||
@@ -53,8 +53,8 @@ def build_exceptions_workbook(run_no: str) -> bytes:
|
||||
|
||||
_sheet_summary(workbook, run, items)
|
||||
_sheet_blocked(workbook, items, "数量不一致", {"blocked_quantity_mismatch", "precheck_expired"})
|
||||
_sheet_blocked(workbook, items, "ERP无库存", {"blocked_inventory_not_found"})
|
||||
_sheet_blocked(workbook, items, "ERP技术失败", {"business_failed", "technical_failed", "item_execution_error"})
|
||||
_sheet_blocked(workbook, items, "外部系统无库存", {"blocked_inventory_not_found"})
|
||||
_sheet_blocked(workbook, items, "外部系统技术失败", {"business_failed", "technical_failed", "item_execution_error"})
|
||||
_sheet_unknown(workbook, items)
|
||||
_sheet_notification(workbook, run)
|
||||
_sheet_raw_trace(workbook, items)
|
||||
@@ -71,30 +71,30 @@ def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInv
|
||||
sheet.append(["Run 状态", run.status])
|
||||
sheet.append(["通知状态", run.notification_status])
|
||||
sheet.append([])
|
||||
sheet.append(["Invoice", "来源", "料号", "预检结果", "ERP 单号"])
|
||||
sheet.append(["Invoice", "来源", "料号", "预检结果", "外部系统 单号"])
|
||||
for item in items:
|
||||
sheet.append([
|
||||
item.invoice_no, item.source_code, item.material_no,
|
||||
item.result_code or item.status, item.erp_document_no or "",
|
||||
item.result_code or item.status, item.external_document_no or "",
|
||||
])
|
||||
|
||||
|
||||
def _sheet_blocked(workbook: Workbook, items: list[TransferInvoiceItem], sheet_name: str, codes: set[str]) -> None:
|
||||
"""按阻断原因归类 Sheet。"""
|
||||
sheet = workbook.create_sheet(sheet_name)
|
||||
sheet.append(["Invoice", "来源", "料号", "收料数量", "ERP 数量", "原因"])
|
||||
sheet.append(["Invoice", "来源", "料号", "收料数量", "外部系统 数量", "原因"])
|
||||
for item in items:
|
||||
if (item.result_code or "") in codes or item.status in codes:
|
||||
sheet.append([
|
||||
item.invoice_no, item.source_code, item.material_no,
|
||||
item.receipt_quantity, item.erp_quantity or "",
|
||||
item.receipt_quantity, item.external_quantity or "",
|
||||
item.result_message or item.result_code or item.status,
|
||||
])
|
||||
|
||||
|
||||
def _sheet_unknown(workbook: Workbook, items: list[TransferInvoiceItem]) -> None:
|
||||
"""ERP 结果未知 Sheet(只读提示,含 Operation 关联)。"""
|
||||
sheet = workbook.create_sheet("ERP结果未知")
|
||||
"""外部系统 结果未知 Sheet(只读提示,含 Operation 关联)。"""
|
||||
sheet = workbook.create_sheet("外部系统结果未知")
|
||||
sheet.append(["Invoice", "来源", "料号", "说明"])
|
||||
sheet.append(["仅展示事实,禁止重试/关闭;请按人工核实 SOP 处理", "", "", ""])
|
||||
for item in items:
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨执行服务(确认门禁 + 写前复查 + ERP 原子写入 + 结果投影)。
|
||||
"""在途调拨执行服务(确认门禁 + 写前复查 + 外部系统 原子写入 + 结果投影)。
|
||||
|
||||
用途:执行一次预检:校验确认范围与预检快照(fail-closed)→ 创建执行 Run →
|
||||
逐项写前复查 ERP 库存 → 原子建单/审核/过账 → 按 ERP 单号投影最终结果。
|
||||
依赖:orchestrator、erp_adapter、quantity、contracts、audit、status、models。
|
||||
逻辑:未确认/过期/快照变化/选择含不可执行项 → ERP 写调用为 0;
|
||||
逐项写前复查 外部系统 库存 → 原子建单/审核/过账 → 按 外部系统 单号投影最终结果。
|
||||
依赖:orchestrator、capability_client、quantity、contracts、audit、status、models。
|
||||
逻辑:未确认/过期/快照变化/选择含不可执行项 → 外部系统 写调用为 0;
|
||||
每个 Invoice 独立写入,单项失败/结果未知不阻断其他项;
|
||||
result_unknown 为终态,禁止自动重试;每次写入创建新 Attempt。
|
||||
"""
|
||||
@@ -24,11 +24,11 @@ from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.contracts import (
|
||||
TRANSFER_CONFIRMATION_REQUIRED,
|
||||
TRANSFER_PRECHECK_EXPIRED,
|
||||
ErpDocumentDTO,
|
||||
ExternalDocumentDTO,
|
||||
PrecheckInvoiceItemDTO,
|
||||
RunResultDTO,
|
||||
TransferExceptionDTO,
|
||||
aggregate_erp_documents,
|
||||
aggregate_external_documents,
|
||||
)
|
||||
from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
@@ -36,6 +36,7 @@ from app.services.in_transit_transfer.precheck_service import (
|
||||
RouteNotResolvedError,
|
||||
TransferDeps,
|
||||
)
|
||||
from app.services.in_transit_transfer.capability_client import StockTarget
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
|
||||
PRECHECK_EXPIRED_RESULT = "precheck_expired"
|
||||
@@ -72,7 +73,7 @@ def recompute_precheck_hash(precheck: TransferPrecheck) -> str:
|
||||
"from_warehouse": item.from_warehouse,
|
||||
"to_warehouse": item.to_warehouse,
|
||||
"receipt_quantity": item.receipt_quantity,
|
||||
"erp_quantity": item.erp_quantity,
|
||||
"external_quantity": item.external_quantity,
|
||||
"result": _item_result_of(item),
|
||||
}
|
||||
for item in sorted(precheck.items, key=lambda row: row.id)
|
||||
@@ -88,6 +89,11 @@ def recompute_precheck_hash(precheck: TransferPrecheck) -> str:
|
||||
},
|
||||
"items": items,
|
||||
}
|
||||
# [调拨类型] 创建时快照含 transfer_type(2026-09-22 起 scope_json 恒写入);
|
||||
# 存量预检 scope_json 无该字段时保持旧快照形状,避免复算 Hash 不一致误判过期。
|
||||
scope_transfer_type = str(precheck.scope_json.get("transfer_type") or "").strip()
|
||||
if scope_transfer_type:
|
||||
snapshot["transfer_type"] = scope_transfer_type
|
||||
return f"sha256:{canonical_hash(snapshot)}"
|
||||
|
||||
|
||||
@@ -115,7 +121,7 @@ def execute_precheck(
|
||||
Returns:
|
||||
ExecuteOutcome(run_no / run 状态 / 单据聚合结果)。
|
||||
Raises:
|
||||
NotFoundError / ValidationError / AppError: 门禁失败(ERP 写入为 0)。
|
||||
NotFoundError / ValidationError / AppError: 门禁失败(外部系统 写入为 0)。
|
||||
ConflictError: 重复执行。
|
||||
"""
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(
|
||||
@@ -185,42 +191,48 @@ def execute_precheck(
|
||||
|
||||
|
||||
def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, request_id: str | None) -> None:
|
||||
"""写前复查 + ERP 原子写入单个 Invoice(创建新 Attempt)。"""
|
||||
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
|
||||
"""写前复查 + 外部系统 原子写入单个 Invoice(创建新 Attempt)。"""
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse:
|
||||
_mark_recheck_blocked(item, "precheck_expired", "route mapping changed since precheck")
|
||||
return
|
||||
receipt_qty = Decimal(item.receipt_quantity)
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
# [STEP 1] 写前复查:重新查询 ERP 库存并严格匹配冻结收料数量。
|
||||
# [STEP 1] 写前复查:重新查询外部系统库存并严格匹配冻结收料数量。
|
||||
try:
|
||||
query = deps.erp.query_inventory(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
|
||||
invoice_no=item.invoice_no, erp_org=route.erp_org,
|
||||
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
|
||||
quantity=receipt_qty,
|
||||
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 "",
|
||||
)],
|
||||
)
|
||||
stock_qty = stock.lookup(
|
||||
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
|
||||
)
|
||||
except RouteNotResolvedError:
|
||||
raise
|
||||
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
|
||||
_mark_recheck_blocked(item, "precheck_expired", "erp inventory changed since precheck")
|
||||
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
|
||||
_mark_recheck_blocked(item, "precheck_expired", "external inventory changed since precheck")
|
||||
return
|
||||
|
||||
# [STEP 2] 记录写 Attempt 并调用 ERP 原子建单/审核/过账。
|
||||
# [STEP 2] 记录写 Attempt 并调用外部系统原子建单/审核/过账。
|
||||
attempt = TransferAttempt(
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="erp_write",
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="external_write",
|
||||
status="running", operation_id=operation_id,
|
||||
request_snapshot_json={
|
||||
"run_no": run_no, "invoice_no": item.invoice_no, "erp_org": route.erp_org,
|
||||
"run_no": run_no, "invoice_no": item.invoice_no, "external_org": route.external_org,
|
||||
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
|
||||
"quantity": str(receipt_qty),
|
||||
},
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.flush()
|
||||
result = deps.erp.create_transfer(
|
||||
result = deps.capabilities.create_transfer(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
|
||||
invoice_no=item.invoice_no, erp_org=route.erp_org,
|
||||
invoice_no=item.invoice_no, external_org=route.external_org,
|
||||
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
|
||||
quantity=receipt_qty,
|
||||
)
|
||||
@@ -230,7 +242,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r
|
||||
|
||||
|
||||
def _mark_recheck_blocked(item: TransferInvoiceItem, result: str, message: str) -> None:
|
||||
"""写前复查失败:fail-closed,不写 ERP。"""
|
||||
"""写前复查失败:fail-closed,不写 外部系统。"""
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = result
|
||||
item.result_message = message
|
||||
@@ -238,7 +250,7 @@ def _mark_recheck_blocked(item: TransferInvoiceItem, result: str, message: str)
|
||||
|
||||
|
||||
def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, result) -> None:
|
||||
"""按 ERP 写结果分类落位 item 与 attempt(result_unknown 为终态)。"""
|
||||
"""按 外部系统 写结果分类落位 item 与 attempt(result_unknown 为终态)。"""
|
||||
attempt.response_summary_json = {
|
||||
"status": result.status,
|
||||
"document_no": result.document_no,
|
||||
@@ -247,12 +259,12 @@ def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, res
|
||||
}
|
||||
if result.status == "success":
|
||||
item.status = status_machine.TransferStatus.SUCCESS.value
|
||||
item.erp_document_no = result.document_no
|
||||
item.external_document_no = result.document_no
|
||||
item.result_code = None
|
||||
attempt.status = "success"
|
||||
elif result.status == "duplicate_success":
|
||||
item.status = status_machine.TransferStatus.DUPLICATE_SUCCESS.value
|
||||
item.erp_document_no = result.document_no
|
||||
item.external_document_no = result.document_no
|
||||
item.result_code = None
|
||||
attempt.status = "success"
|
||||
elif result.status == "result_unknown":
|
||||
@@ -270,7 +282,7 @@ def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, res
|
||||
|
||||
|
||||
def _audit_item_write(item, run_no, request_id, operation_id, before_status) -> None:
|
||||
"""为每次 ERP 写入追加审计事件(脱敏快照 + Hash)。"""
|
||||
"""为每次 外部系统 写入追加审计事件(脱敏快照 + Hash)。"""
|
||||
event = build_transfer_audit_event(
|
||||
event_type="TRANSFER_ITEM_EXECUTED",
|
||||
aggregate_type="transfer_item",
|
||||
@@ -284,7 +296,7 @@ def _audit_item_write(item, run_no, request_id, operation_id, before_status) ->
|
||||
operation_id=operation_id,
|
||||
result="success" if item.status in {"success", "duplicate_success"} else "failure",
|
||||
before={"status": before_status},
|
||||
after={"status": item.status, "erp_document_no": item.erp_document_no},
|
||||
after={"status": item.status, "external_document_no": item.external_document_no},
|
||||
)
|
||||
db.session.add(event)
|
||||
|
||||
@@ -312,7 +324,7 @@ def execute_item(*, item_id: int, deps: TransferDeps, request_id: str | None = N
|
||||
|
||||
|
||||
def get_run(run_no: str) -> dict[str, Any]:
|
||||
"""按 run_no 恢复 Run 最终结果(ERP 单号聚合 + 未生成单据异常)。"""
|
||||
"""按 run_no 恢复 Run 最终结果(外部系统 单号聚合 + 未生成单据异常)。"""
|
||||
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
|
||||
if run is None:
|
||||
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
|
||||
@@ -337,12 +349,13 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
|
||||
invoice_no=item.invoice_no,
|
||||
receipt_date=item.receipt_date,
|
||||
from_warehouse=item.from_warehouse,
|
||||
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
|
||||
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
||||
to_warehouse=item.to_warehouse,
|
||||
to_quantity=Decimal(item.receipt_quantity),
|
||||
result=result,
|
||||
reason=item.result_message or "",
|
||||
erp_document_no=item.erp_document_no,
|
||||
external_document_no=item.external_document_no,
|
||||
receipt_warehouse_code=item.receipt_warehouse_code or "",
|
||||
))
|
||||
if result not in {"success", "duplicate_success"}:
|
||||
exceptions.append(TransferExceptionDTO(
|
||||
@@ -350,12 +363,12 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
|
||||
invoice_no=item.invoice_no,
|
||||
material_no=item.material_no,
|
||||
reason=result,
|
||||
facts=f"收料 {item.receipt_quantity}" + (f" / ERP {item.erp_quantity}" if item.erp_quantity else ""),
|
||||
facts=f"收料 {item.receipt_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""),
|
||||
))
|
||||
return RunResultDTO(
|
||||
run_no=run.run_no,
|
||||
status=run.status,
|
||||
erp_documents=aggregate_erp_documents(item_dtos),
|
||||
external_documents=aggregate_external_documents(item_dtos),
|
||||
exceptions=tuple(exceptions),
|
||||
)
|
||||
|
||||
@@ -365,7 +378,7 @@ def serialize_run_result(result: RunResultDTO) -> dict[str, Any]:
|
||||
return {
|
||||
"run_no": result.run_no,
|
||||
"status": result.status,
|
||||
"erp_documents": [
|
||||
"external_documents": [
|
||||
{
|
||||
"document_no": document.document_no,
|
||||
"from_warehouse": document.from_warehouse,
|
||||
@@ -384,7 +397,7 @@ def serialize_run_result(result: RunResultDTO) -> dict[str, Any]:
|
||||
for line in document.lines
|
||||
],
|
||||
}
|
||||
for document in result.erp_documents
|
||||
for document in result.external_documents
|
||||
],
|
||||
"exceptions": [
|
||||
{
|
||||
|
||||
@@ -35,6 +35,8 @@ class ParsedReceiptRow:
|
||||
receipt_date: date
|
||||
receipt_quantity: Decimal
|
||||
lot_no: str = ""
|
||||
# 收料文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。
|
||||
warehouse_code: str = ""
|
||||
|
||||
|
||||
class ReceiptFileSchemaError(AppError):
|
||||
@@ -73,8 +75,9 @@ def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]])
|
||||
doc_no → invoice_no(幂等/汇总键)
|
||||
quantity → receipt_quantity(严格数量匹配)
|
||||
movement_date → receipt_date(成熟过滤)
|
||||
其余字段(material_code→material_no、material_name、warehouse_code、storage_code、
|
||||
doc_no)透传/展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
|
||||
其余字段(material_code→material_no、material_name、doc_no)透传/展示保留;
|
||||
warehouse_code 透传至 ParsedReceiptRow.warehouse_code(inventory_match 源路由匹配键);
|
||||
storage_code 仍仅展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
|
||||
|
||||
Args:
|
||||
source_code: 任务来源实例(行内来源身份一致性校验)。
|
||||
@@ -189,6 +192,7 @@ def _parse_rows(
|
||||
receipt_date=receipt_date,
|
||||
receipt_quantity=quantity,
|
||||
lot_no=str(row.get("lot_no") or "").strip(),
|
||||
warehouse_code=str(row.get("warehouse_code") or "").strip(),
|
||||
))
|
||||
if errors:
|
||||
raise ReceiptFileSchemaError(rows=errors)
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
"""services/in_transit_transfer/gateway_adapter.py
|
||||
|
||||
用途:把调拨的 ERP 访问收敛为通过 Integration Connector CapabilityGateway 调用
|
||||
(query_inventory 是首个配置绑定消费者)。
|
||||
依赖:integration_connector.gateway / capability、erp_adapter.InventoryQuery/ErpQueryTimeoutError。
|
||||
逻辑:领域只调 query_inventory 能力;外部系统差异全在连接器层。create_transfer /
|
||||
verify_duplicate 留待调拨执行阶段(Phase 2)接线。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError, InventoryQuery
|
||||
|
||||
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
|
||||
|
||||
|
||||
class CapabilityErpAdapter:
|
||||
"""把调拨 query_inventory 收敛为通过 CapabilityGateway 调用。
|
||||
|
||||
Args:
|
||||
gateway: 可选 Gateway;缺省用 get_capability_gateway()(可注入替身测试)。
|
||||
"""
|
||||
|
||||
def __init__(self, gateway: Any | None = None) -> None:
|
||||
self._gateway = gateway
|
||||
|
||||
def _gateway_or_default(self):
|
||||
if self._gateway is not None:
|
||||
return self._gateway
|
||||
from app.services.integration_connector.gateway import get_capability_gateway
|
||||
|
||||
return get_capability_gateway()
|
||||
|
||||
def query_inventory(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> InventoryQuery:
|
||||
"""查询外部系统库存(经连接器框架)。
|
||||
|
||||
Args/Raises:
|
||||
与 erp_adapter.ErpAdapter.query_inventory 一致;超时→ErpQueryTimeoutError;
|
||||
写失败→AppError(预检把它归为来源失败)。P1 用默认绑定(context={});
|
||||
来源专属绑定待 P2/P3。
|
||||
"""
|
||||
result = self._gateway_or_default().call(
|
||||
capability=QUERY_INVENTORY_CAPABILITY,
|
||||
context={},
|
||||
params={
|
||||
"invoice_no": invoice_no,
|
||||
"from_warehouse": from_warehouse,
|
||||
"to_warehouse": to_warehouse,
|
||||
"quantity": quantity,
|
||||
},
|
||||
operation_id=operation_id,
|
||||
)
|
||||
if result.status == "timeout":
|
||||
raise ErpQueryTimeoutError()
|
||||
if result.status != "success":
|
||||
raise AppError(
|
||||
code=result.error_code or "INTEGRATION.CALL_FAILED",
|
||||
message=result.error_message or "query_inventory failed",
|
||||
http_status=503,
|
||||
retryable=False,
|
||||
)
|
||||
data = result.data or {}
|
||||
found = bool(data.get("found"))
|
||||
qty = data.get("quantity")
|
||||
return InventoryQuery(found=found, quantity=Decimal(str(qty)) if qty is not None else None)
|
||||
@@ -31,6 +31,8 @@ class AggregatedInvoice:
|
||||
receipt_quantity: Decimal
|
||||
raw_lines: tuple[RawLineRefDTO, ...]
|
||||
lot_no: str = ""
|
||||
# 组内首行收料仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。
|
||||
warehouse_code: str = ""
|
||||
|
||||
|
||||
class InvoiceConflictError(AppError):
|
||||
@@ -80,5 +82,6 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str =
|
||||
receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")),
|
||||
raw_lines=raw_lines,
|
||||
lot_no=first.lot_no,
|
||||
warehouse_code=first.warehouse_code,
|
||||
))
|
||||
return invoices
|
||||
@@ -4,11 +4,11 @@
|
||||
用该来源收料配置绑定的 movement 解析规则(purpose='movement',端点=定死
|
||||
领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyReceiptFile。
|
||||
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
|
||||
movement_contract、openpyxl。
|
||||
逻辑:按来源取最新未过期(未清理)收料文件;无绑定 movement profile 或文件缺失时
|
||||
返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域字段 + 溯源字段
|
||||
(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整校验由下游
|
||||
file_parser 完成。
|
||||
movement_contract、receipt_file_gate(可用性门禁)、openpyxl。
|
||||
逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的收料文件;无绑定规则、
|
||||
文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
|
||||
字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整
|
||||
校验由下游 file_parser 完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,6 +18,7 @@ from typing import Any, Mapping
|
||||
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
|
||||
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
|
||||
|
||||
|
||||
class ShippingReceiptFileRepository:
|
||||
@@ -27,13 +28,14 @@ class ShippingReceiptFileRepository:
|
||||
self._storage = file_asset_storage
|
||||
|
||||
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
|
||||
"""返回该来源最新未过期收料文件;无绑定规则或文件缺失时返回 None。
|
||||
"""返回该来源最新且当天(业务日)抓取的未过期收料文件;否则返回 None。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
|
||||
Returns:
|
||||
ReadyReceiptFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
|
||||
新鲜度/保留期/缺失均 fail-closed 返回 None(fail 消息由上游触发重抓)。
|
||||
"""
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
|
||||
|
||||
@@ -52,7 +54,8 @@ class ShippingReceiptFileRepository:
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)单一事实来源见 receipt_file_gate。
|
||||
usable_receipt_file_condition(),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
||||
.first()
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨企业微信汇总通知。
|
||||
|
||||
用途:每个非空 Run 恰好一条汇总通知;空数据不通知;通知失败记录
|
||||
notification_failed 且不改变 ERP 业务结果(run.status 保持)。
|
||||
notification_failed 且不改变 外部系统 业务结果(run.status 保持)。
|
||||
依赖:models、audit、typing.Protocol。
|
||||
逻辑:通知状态独立于 ERP 状态;已成功投递幂等(每个 Run 一条)。
|
||||
逻辑:通知状态独立于 外部系统 状态;已成功投递幂等(每个 Run 一条)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -65,7 +65,7 @@ def notify_run_summary(*, run_no: str, sender: WeComSender, recipients: list[str
|
||||
if failed:
|
||||
run.notification_error_code = str(outcome.get("error_code") or "WECOM_SEND_FAILED")
|
||||
run.notification_error_message = str(outcome.get("error_message") or "")
|
||||
# 关键:通知失败绝不修改 run.status(ERP 业务结果保持)。
|
||||
# 关键:通知失败绝不修改 run.status(外部系统 业务结果保持)。
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_NOTIFICATION",
|
||||
aggregate_type="transfer_run",
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""在途调拨预检服务。
|
||||
|
||||
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → ERP 库存查询 →
|
||||
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → 外部系统 库存查询 →
|
||||
严格数量匹配 → 预检快照与 Hash",并支持预检进度恢复(restore)。
|
||||
依赖:file_preparation / file_parser / invoice_aggregator / erp_adapter /
|
||||
依赖:file_preparation / file_parser / invoice_aggregator / capability_client /
|
||||
date_policy / quantity / contracts / audit / models。
|
||||
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 ERP;
|
||||
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 外部系统;
|
||||
预检 Hash 由冻结快照复算;create_precheck 落库 Run + Precheck + Items。
|
||||
"""
|
||||
|
||||
@@ -35,7 +35,7 @@ from app.services.in_transit_transfer.date_policy import (
|
||||
maturity_status,
|
||||
parse_date,
|
||||
)
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError
|
||||
from app.services.in_transit_transfer.capability_client import ExternalQueryTimeoutError, StockTarget
|
||||
from app.services.in_transit_transfer.file_parser import (
|
||||
ParsedReceiptRow,
|
||||
ReceiptFileSchemaError,
|
||||
@@ -56,6 +56,13 @@ from app.services.in_transit_transfer.strategy import (
|
||||
TransferStrategyPolicy,
|
||||
default_strategy,
|
||||
)
|
||||
from app.services.in_transit_transfer.transfer_type import (
|
||||
TransferType,
|
||||
ensure_transfer_type_supported,
|
||||
filter_invoices_for_type,
|
||||
normalize_transfer_type,
|
||||
transfer_type_scope_note,
|
||||
)
|
||||
|
||||
ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED"
|
||||
|
||||
@@ -65,15 +72,15 @@ RESULT_NOT_MATURED = "not_matured"
|
||||
RESULT_QUANTITY_MISMATCH = "blocked_quantity_mismatch"
|
||||
RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
|
||||
RESULT_FUTURE_DATE = "blocked_future_date"
|
||||
RESULT_ERP_QUERY_FAILED = "blocked_erp_query_failed"
|
||||
RESULT_ERP_QUERY_TIMEOUT = "erp_query_timeout"
|
||||
RESULT_EXTERNAL_QUERY_FAILED = "blocked_external_query_failed"
|
||||
RESULT_EXTERNAL_QUERY_TIMEOUT = "external_query_timeout"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RouteMapping:
|
||||
"""来源路由:ERP 组织 / 拨出仓(ERP 在途仓)/ 拨入仓(ERP 映射仓)。"""
|
||||
"""来源路由:外部组织(external_org,取自仓库映射)/ 拨出仓(外部在途仓)/ 拨入仓(映射仓)。"""
|
||||
|
||||
erp_org: str
|
||||
external_org: str
|
||||
from_warehouse: str
|
||||
to_warehouse: str
|
||||
|
||||
@@ -93,8 +100,8 @@ class RouteNotResolvedError(AppError):
|
||||
class RouteResolver(Protocol):
|
||||
"""来源路由解析协议(路由归属规则冻结前由 Fake/门禁兜底)。"""
|
||||
|
||||
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
|
||||
"""返回 Invoice 的路由;无法归属时抛 RouteNotResolvedError。"""
|
||||
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
|
||||
"""返回 Invoice 的路由(warehouse_code 为收料文件仓库列,inventory_match 源匹配键);无法归属时抛 RouteNotResolvedError。"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -126,7 +133,7 @@ class TransferDeps:
|
||||
file_repository: ReceiptFileRepository
|
||||
rpa_trigger: RpaTrigger
|
||||
route_resolver: RouteResolver
|
||||
erp: Any
|
||||
capabilities: Any
|
||||
strategy: TransferStrategyPolicy = field(default_factory=default_strategy)
|
||||
|
||||
|
||||
@@ -148,22 +155,27 @@ def run_precheck(
|
||||
run_no: str = "RUN-PENDING",
|
||||
receipt_date_from: str | None = None,
|
||||
receipt_date_to: str | None = None,
|
||||
transfer_type: TransferType | str | None = None,
|
||||
) -> PrecheckRunResult:
|
||||
"""执行一次只读预检(不写 ERP)。
|
||||
"""执行一次只读预检(不写 外部系统)。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。
|
||||
business_date: 业务日期 T(YYYY-MM-DD)。
|
||||
deps: 注入的文件仓库 / RPA / 路由 / ERP 依赖。
|
||||
deps: 注入的文件仓库 / RPA / 路由 / 外部系统 依赖。
|
||||
active_source_job_key: 活动 Source Job 键(缺文件时绑定已有任务)。
|
||||
run_no: Run 编号(创建 Run 前可为占位)。
|
||||
receipt_date_from / receipt_date_to: 可选收料日期查询范围。
|
||||
transfer_type: 调拨业务类型(缺省在途仓至HUB仓);类型决定收料数据范围。
|
||||
Returns:
|
||||
PrecheckRunResult(摘要 + 明细 + 来源进度)。
|
||||
Raises:
|
||||
ValidationError: source_codes 为空。
|
||||
ValidationError: source_codes 为空、日期范围非法或调拨类型非法/未支持。
|
||||
"""
|
||||
if not source_codes:
|
||||
raise ValidationError("source_codes is required")
|
||||
resolved_transfer_type = normalize_transfer_type(transfer_type)
|
||||
ensure_transfer_type_supported(resolved_transfer_type)
|
||||
# [日期范围] 可选收料日期过滤;卡控:截止不得超出 D+1 规则(业务日期-1),起始不得晚于截止。
|
||||
range_from = parse_date(receipt_date_from) if receipt_date_from else None
|
||||
range_to = parse_date(receipt_date_to) if receipt_date_to else None
|
||||
@@ -212,6 +224,9 @@ def run_precheck(
|
||||
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 = _precheck_invoices(
|
||||
invoices=invoices,
|
||||
source_code=source_code,
|
||||
@@ -260,6 +275,7 @@ def run_precheck(
|
||||
snapshot = {
|
||||
"scope": sorted(set(source_codes)),
|
||||
"business_date": business_date,
|
||||
"transfer_type": resolved_transfer_type.value,
|
||||
"file_snapshot": file_snapshot,
|
||||
"counts": {
|
||||
"file_invoice_count": counts.file_invoice_count,
|
||||
@@ -275,7 +291,7 @@ def run_precheck(
|
||||
"from_warehouse": item.from_warehouse,
|
||||
"to_warehouse": item.to_warehouse,
|
||||
"receipt_quantity": str(item.to_quantity),
|
||||
"erp_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"external_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"result": item.result,
|
||||
}
|
||||
for item in items
|
||||
@@ -293,7 +309,7 @@ def run_precheck(
|
||||
expires_at="",
|
||||
counts=counts,
|
||||
estimated_transfer_quantity=str(estimated_quantity),
|
||||
estimated_erp_write_count=counts.executable_count,
|
||||
estimated_external_write_count=counts.executable_count,
|
||||
precheck_hash=precheck_hash,
|
||||
)
|
||||
return PrecheckRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
|
||||
@@ -308,8 +324,12 @@ def _precheck_invoices(
|
||||
deps: TransferDeps,
|
||||
run_no: str,
|
||||
) -> list[PrecheckInvoiceItemDTO]:
|
||||
"""对单个来源的汇总 Invoice 逐项预检(成熟过滤 → 路由 → ERP → 匹配)。"""
|
||||
"""对单个来源的汇总 Invoice 预检(成熟过滤 → 路由 → 按组织分组批量查 外部系统 → 匹配)。"""
|
||||
output: list[PrecheckInvoiceItemDTO] = []
|
||||
|
||||
# [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(
|
||||
@@ -325,6 +345,7 @@ def _precheck_invoices(
|
||||
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,
|
||||
))
|
||||
continue
|
||||
@@ -336,72 +357,94 @@ def _precheck_invoices(
|
||||
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,
|
||||
))
|
||||
continue
|
||||
route = deps.route_resolver.resolve(source_code=source_code, invoice_no=invoice.invoice_no)
|
||||
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))
|
||||
|
||||
groups: dict[str, list[tuple[Any, RouteMapping, tuple[RawLineRefDTO, ...], str]]] = {}
|
||||
for entry in matured:
|
||||
groups.setdefault(entry[1].external_org, []).append(entry)
|
||||
|
||||
# [STEP 2] 每个组织一次批量查询(targets = 料号+拨出库位+拨出批号 元组列表),
|
||||
# 组内逐票按三元组精确匹配库存数量;组级故障降级到组内全部票,不炸整来源。
|
||||
for external_org, entries in groups.items():
|
||||
targets = [
|
||||
StockTarget(material_no=invoice.material_no, from_warehouse=route.from_warehouse, lot_no=invoice.lot_no)
|
||||
for invoice, route, _, _ in entries
|
||||
]
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
try:
|
||||
query = deps.erp.query_inventory(
|
||||
operation_id=operation_id,
|
||||
run_no=run_no,
|
||||
attempt_no=1,
|
||||
invoice_no=invoice.invoice_no,
|
||||
erp_org=route.erp_org,
|
||||
from_warehouse=route.from_warehouse,
|
||||
to_warehouse=route.to_warehouse,
|
||||
quantity=invoice.receipt_quantity,
|
||||
stock = deps.capabilities.query_stock(
|
||||
operation_id=operation_id, external_org=external_org, targets=targets,
|
||||
)
|
||||
except ErpQueryTimeoutError:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
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_ERP_QUERY_TIMEOUT, reason="erp query timeout",
|
||||
raw_lines=raw,
|
||||
))
|
||||
except ExternalQueryTimeoutError:
|
||||
for invoice, route, raw, receipt_date_iso in entries:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
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,
|
||||
))
|
||||
continue
|
||||
except Exception as exc: # noqa: BLE001 —— ERP 网关/绑定层故障降级为单据阻断,不炸整来源
|
||||
except Exception as exc: # noqa: BLE001 —— 网关/绑定层故障降级为整组阻断,不炸整来源
|
||||
# [语义] 绑定缺失、连接失败等基础设施故障是环境问题而非业务阻断:
|
||||
# 逐票给 blocked_erp_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(PrecheckInvoiceItemDTO(
|
||||
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,
|
||||
))
|
||||
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,
|
||||
)
|
||||
if stock_qty is None:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
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(PrecheckInvoiceItemDTO(
|
||||
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,
|
||||
from_quantity=stock_qty, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_ERP_QUERY_FAILED, reason=f"erp query failed: {detail}",
|
||||
result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
if not query.found:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
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_INVENTORY_NOT_FOUND, reason="erp inventory not found",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
match = classify_quantity_match(invoice.receipt_quantity, query.quantity)
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
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=query.quantity, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch",
|
||||
raw_lines=raw,
|
||||
))
|
||||
return output
|
||||
|
||||
|
||||
@@ -411,7 +454,7 @@ def _item_status(result: str) -> str:
|
||||
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_ERP_QUERY_TIMEOUT: 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,
|
||||
}
|
||||
@@ -432,14 +475,18 @@ def create_precheck(
|
||||
active_source_job_key: str | None = None,
|
||||
receipt_date_from: str | None = None,
|
||||
receipt_date_to: str | None = None,
|
||||
transfer_type: TransferType | str | None = None,
|
||||
) -> PrecheckSummaryDTO:
|
||||
"""运行预检并落库 TransferRun + TransferPrecheck + InvoiceItems。
|
||||
|
||||
Args:
|
||||
source_codes / business_date / deps: 同 run_precheck。
|
||||
receipt_date_from / receipt_date_to / transfer_type: 同 run_precheck。
|
||||
Returns:
|
||||
预检摘要(precheck_id 已回填)。
|
||||
"""
|
||||
resolved_transfer_type = normalize_transfer_type(transfer_type)
|
||||
ensure_transfer_type_supported(resolved_transfer_type)
|
||||
run_no = _generate_no("RUN", business_date)
|
||||
result = run_precheck(
|
||||
source_codes=source_codes,
|
||||
@@ -448,6 +495,7 @@ def create_precheck(
|
||||
active_source_job_key=active_source_job_key,
|
||||
receipt_date_from=receipt_date_from,
|
||||
receipt_date_to=receipt_date_to,
|
||||
transfer_type=resolved_transfer_type,
|
||||
run_no=run_no,
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
@@ -458,6 +506,7 @@ def create_precheck(
|
||||
status="prechecking",
|
||||
source_codes_json=list(source_codes),
|
||||
counts_json=asdict(result.summary.counts),
|
||||
transfer_type=resolved_transfer_type.value,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
@@ -485,7 +534,13 @@ def create_precheck(
|
||||
run_id=run.id,
|
||||
business_date=business_date,
|
||||
status=result.summary.status,
|
||||
scope_json={"source_codes": list(source_codes), "receipt_date_from": receipt_date_from, "receipt_date_to": receipt_date_to},
|
||||
scope_json={
|
||||
"source_codes": list(source_codes),
|
||||
"receipt_date_from": receipt_date_from,
|
||||
"receipt_date_to": receipt_date_to,
|
||||
"transfer_type": resolved_transfer_type.value,
|
||||
"transfer_type_scope": transfer_type_scope_note(resolved_transfer_type),
|
||||
},
|
||||
file_snapshot_json={
|
||||
stage.source_code: {
|
||||
"file_no": stage.file_no,
|
||||
@@ -499,7 +554,7 @@ def create_precheck(
|
||||
strategy_version="v0",
|
||||
counts_json=asdict(result.summary.counts),
|
||||
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
|
||||
estimated_erp_write_count=result.summary.estimated_erp_write_count,
|
||||
estimated_external_write_count=result.summary.estimated_external_write_count,
|
||||
precheck_hash=result.summary.precheck_hash,
|
||||
expires_at=now + timedelta(seconds=deps.strategy.confirm_ttl_seconds),
|
||||
)
|
||||
@@ -524,8 +579,9 @@ def create_precheck(
|
||||
"from_warehouse": item.from_warehouse or "",
|
||||
"to_warehouse": item.to_warehouse or "",
|
||||
"receipt_quantity": str(item.to_quantity),
|
||||
"erp_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"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}
|
||||
for line in item.raw_lines
|
||||
@@ -568,7 +624,7 @@ def create_precheck(
|
||||
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
|
||||
counts=result.summary.counts,
|
||||
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
|
||||
estimated_erp_write_count=result.summary.estimated_erp_write_count,
|
||||
estimated_external_write_count=result.summary.estimated_external_write_count,
|
||||
precheck_hash=result.summary.precheck_hash,
|
||||
)
|
||||
return summary
|
||||
@@ -604,7 +660,7 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
|
||||
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
|
||||
counts=counts,
|
||||
estimated_transfer_quantity=precheck.estimated_transfer_quantity or "0",
|
||||
estimated_erp_write_count=int(precheck.estimated_erp_write_count or 0),
|
||||
estimated_external_write_count=int(precheck.estimated_external_write_count or 0),
|
||||
precheck_hash=precheck.precheck_hash,
|
||||
)
|
||||
items = []
|
||||
@@ -617,13 +673,17 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
|
||||
invoice_no=item.invoice_no,
|
||||
receipt_date=item.receipt_date,
|
||||
lot_no=item.lot_no or "",
|
||||
receipt_warehouse_code=item.receipt_warehouse_code or "",
|
||||
from_warehouse=item.from_warehouse,
|
||||
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
|
||||
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
||||
to_warehouse=item.to_warehouse,
|
||||
to_quantity=Decimal(item.receipt_quantity),
|
||||
result=item.result_code or (
|
||||
RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status
|
||||
),
|
||||
# 失败原因落库于 result_message(预检/重查降级均写);restore 不回读则
|
||||
# 前端刷新后原因恒为空,呈现「安静阻断」无法排查。
|
||||
reason=item.result_message or "",
|
||||
raw_lines=tuple(
|
||||
RawLineRefDTO(
|
||||
sheet=line.get("sheet", ""),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨严格数量门禁。
|
||||
|
||||
用途:实现"收料数量 == ERP 账面库存 才可执行"的精确匹配规则,
|
||||
用途:实现"收料数量 == 外部系统 账面库存 才可执行"的精确匹配规则,
|
||||
禁止部分调拨、数量容差与隐式截断。
|
||||
依赖:标准库 decimal。
|
||||
逻辑:所有比较基于 Decimal 精确语义;非法数量(0/负数/非数字)在解析层拒绝。
|
||||
@@ -45,17 +45,17 @@ def strict_quantities_equal(left: Any, right: Any) -> bool:
|
||||
return Decimal(str(left)) == Decimal(str(right))
|
||||
|
||||
|
||||
def classify_quantity_match(receipt_quantity: Any, erp_quantity: Any | None) -> str:
|
||||
def classify_quantity_match(receipt_quantity: Any, external_quantity: Any | None) -> str:
|
||||
"""按严格相等规则分类数量匹配结果。
|
||||
|
||||
Args:
|
||||
receipt_quantity: 收料数量。
|
||||
erp_quantity: ERP 账面库存;None 表示无库存。
|
||||
external_quantity: 外部系统 账面库存;None 表示无库存。
|
||||
Returns:
|
||||
'executable' | 'blocked_quantity_mismatch' | 'blocked_inventory_not_found'。
|
||||
"""
|
||||
if erp_quantity is None:
|
||||
if external_quantity is None:
|
||||
return MATCH_INVENTORY_NOT_FOUND
|
||||
if strict_quantities_equal(receipt_quantity, erp_quantity):
|
||||
if strict_quantities_equal(receipt_quantity, external_quantity):
|
||||
return MATCH_EXECUTABLE
|
||||
return MATCH_QUANTITY_MISMATCH
|
||||
@@ -0,0 +1,69 @@
|
||||
"""在途调拨收料归档文件的可用性门禁(单一事实来源)。
|
||||
|
||||
用途:把「一份 ShippingReceiptReportFile 是否可用于调拨链路」的判定收敛为本模块,
|
||||
供来源状态投影(source_file_status)、预检取文件(movement_file_repository)、
|
||||
收料文件下载(api/in_transit_transfer)三处统一引用,防止口径漂移。
|
||||
依赖:models(ShippingReceiptReportFile)、date_policy(业务日 UTC 窗口换算)。
|
||||
逻辑:可用 = 未清理 且 当天(Asia/Shanghai 业务日)抓取 且 未过保留期;
|
||||
已失效(expired)= 可用核心的反相(未清理 且 [保留期已到 或 非当天抓取])。
|
||||
两函数同核推导,规则文本只存在一处。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import ColumnElement, and_, not_, or_
|
||||
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.services.in_transit_transfer.date_policy import business_date_utc_window
|
||||
|
||||
|
||||
def _fresh_and_retention_valid(now: datetime) -> ColumnElement:
|
||||
"""新鲜度 + 保留期核心条件(不含清理态,供可用/失效两函数共用)。"""
|
||||
window_start, window_end = business_date_utc_window(now)
|
||||
return and_(
|
||||
ShippingReceiptReportFile.created_at >= window_start,
|
||||
ShippingReceiptReportFile.created_at < window_end,
|
||||
or_(
|
||||
ShippingReceiptReportFile.archive_expires_at.is_(None),
|
||||
ShippingReceiptReportFile.archive_expires_at > now,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def usable_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
|
||||
"""返回「当前可用的收料归档文件」SQL 条件。
|
||||
|
||||
判定:未清理(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
|
||||
+ 未过保留期(archive_expires_at 为空视为长期有效)。预检复用与下载
|
||||
只认可用文件;隔日/过期文件一律 fail-closed,交由上游触发重抓。
|
||||
|
||||
Args:
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
可直接并入 .filter() 的单个 SQLAlchemy 条件。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
return and_(
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
_fresh_and_retention_valid(now),
|
||||
)
|
||||
|
||||
|
||||
def expired_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
|
||||
"""返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。
|
||||
|
||||
判定:未清理 且 可用核心不成立(保留期已到 或 非当天业务日抓取)。
|
||||
命中即提示用户重试重抓,不报 ready,也不等待保留期清理任务落位。
|
||||
|
||||
Args:
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
可直接并入 .filter() 的单个 SQLAlchemy 条件。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
return and_(
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
not_(_fresh_and_retention_valid(now)),
|
||||
)
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨每日历史恢复(自动复核待处理池)。
|
||||
|
||||
用途:下一排程对可恢复异常项用最新文件与 ERP 重新预检并创建新 Attempt;
|
||||
用途:下一排程对可恢复异常项用最新文件与 外部系统 重新预检并创建新 Attempt;
|
||||
result_unknown / manually_closed / success 不自动写入。
|
||||
依赖:models、retry_service._recheck_item、TransferDeps。
|
||||
逻辑:恢复仅查询/匹配,不写 ERP;每次恢复新 Attempt,旧 Attempt 不变。
|
||||
逻辑:恢复仅查询/匹配,不写 外部系统;每次恢复新 Attempt,旧 Attempt 不变。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
"""在途调拨人工重试服务(基于冻结文件仅重新查询 ERP)。
|
||||
"""在途调拨人工重试服务(基于冻结文件仅重新查询 外部系统)。
|
||||
|
||||
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 ERP;
|
||||
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 外部系统;
|
||||
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
|
||||
依赖:models、erp_adapter、quantity、status、audit、precheck_service.TransferDeps。
|
||||
逻辑:重试不写 ERP、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。
|
||||
依赖:models、capability_client、quantity、status、audit、precheck_service.TransferDeps。
|
||||
逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
@@ -17,58 +18,75 @@ 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.precheck_service import (
|
||||
RESULT_ERP_QUERY_FAILED,
|
||||
RESULT_EXTERNAL_QUERY_FAILED,
|
||||
RESULT_EXECUTABLE,
|
||||
TransferDeps,
|
||||
)
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
|
||||
RETRY_KIND_ERP_RECHECK = "erp_recheck"
|
||||
RETRY_KIND_EXTERNAL_RECHECK = "external_recheck"
|
||||
RETRY_KIND_RPA_REFETCH = "rpa_refetch"
|
||||
|
||||
# 可重查状态:可恢复阻断 + 可执行(已可执行的行也允许重查核对最新库存,
|
||||
# 避免预检后库存变化无法发现);终态(已执行/人工关闭等)仍不可重查。
|
||||
_RETRYABLE_STATUSES = {
|
||||
status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
status_machine.TransferStatus.READY_TO_EXECUTE.value,
|
||||
}
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id: str | None) -> str:
|
||||
"""对单个异常项重新查询 ERP 并更新状态(创建新 Attempt)。
|
||||
"""对单个异常项重新查询 外部系统 并更新状态(创建新 Attempt)。
|
||||
|
||||
Returns:
|
||||
重检后的 item 状态。
|
||||
"""
|
||||
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
receipt_qty = Decimal(item.receipt_quantity)
|
||||
item.attempt_no += 1
|
||||
before_status = item.status
|
||||
attempt = TransferAttempt(
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="erp_query",
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="external_query",
|
||||
status="running", operation_id=operation_id,
|
||||
request_snapshot_json={
|
||||
"invoice_no": item.invoice_no, "erp_org": route.erp_org,
|
||||
"invoice_no": item.invoice_no, "external_org": route.external_org,
|
||||
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
|
||||
"quantity": str(receipt_qty),
|
||||
},
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.flush()
|
||||
# [降级] 与 precheck 逐票语义一致:ERP 网关/绑定故障(如集成连接器缺绑定
|
||||
# BindingNotFoundError)记为该行 blocked_erp_query_failed + 原因,
|
||||
# [降级] 与 precheck 逐票语义一致:外部系统网关/绑定故障(如集成连接器缺绑定
|
||||
# BindingNotFoundError)记为该行 blocked_external_query_failed + 原因,
|
||||
# 不中断批量重查、不向调用方抛基础设施异常(避免全局错误弹窗)。
|
||||
try:
|
||||
query = deps.erp.query_inventory(
|
||||
operation_id=operation_id,
|
||||
run_no=item.run.run_no if item.run else "RUN-PENDING",
|
||||
attempt_no=item.attempt_no,
|
||||
invoice_no=item.invoice_no,
|
||||
erp_org=route.erp_org,
|
||||
from_warehouse=route.from_warehouse,
|
||||
to_warehouse=route.to_warehouse,
|
||||
quantity=receipt_qty,
|
||||
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 "",
|
||||
)],
|
||||
)
|
||||
stock_qty = stock.lookup(
|
||||
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
# 降级只落 DB(result_message/审计),若再无应用日志,控制台侧完全无痕可查。
|
||||
logger.warning(
|
||||
"transfer external recheck failed (degrade to blocked): invoice=%s item=%s attempt=%s error=%s",
|
||||
item.invoice_no, item.id, item.attempt_no, detail,
|
||||
)
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = RESULT_ERP_QUERY_FAILED
|
||||
item.result_message = f"erp query failed: {detail}"
|
||||
item.result_code = RESULT_EXTERNAL_QUERY_FAILED
|
||||
item.result_message = f"external query failed: {detail}"
|
||||
attempt.status = "failed"
|
||||
attempt.completed_at = datetime.utcnow()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
@@ -88,16 +106,19 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
|
||||
))
|
||||
db.session.flush()
|
||||
return item.status
|
||||
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
|
||||
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = "blocked_inventory_not_found" if not query.found else "blocked_quantity_mismatch"
|
||||
item.result_message = "erp inventory not found" if not query.found else "strict quantity mismatch"
|
||||
item.result_code = "blocked_inventory_not_found" if stock_qty is None else "blocked_quantity_mismatch"
|
||||
item.result_message = "external inventory not found" if stock_qty is None else "strict quantity mismatch"
|
||||
# 查无记录与数量不足都是外部系统的真实答复:库存数必须落库展示(查无记录按 0),
|
||||
# 不得显示"-"让用户误以为查询失败。
|
||||
item.external_quantity = str(stock_qty) if stock_qty is not None else "0"
|
||||
attempt.status = "failed"
|
||||
else:
|
||||
item.status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
item.result_code = None
|
||||
item.result_message = None
|
||||
item.erp_quantity = str(query.quantity)
|
||||
item.external_quantity = str(stock_qty)
|
||||
attempt.status = "success"
|
||||
attempt.completed_at = datetime.utcnow()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
@@ -119,14 +140,14 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
|
||||
return item.status
|
||||
|
||||
|
||||
def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_RECHECK,
|
||||
def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTERNAL_RECHECK,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""人工重试异常项。
|
||||
|
||||
Args:
|
||||
item_id: TransferInvoiceItem.id。
|
||||
deps: 注入依赖。
|
||||
kind: erp_recheck(默认);rpa_refetch 在 Run 创建后禁止。
|
||||
kind: external_recheck(默认);rpa_refetch 在 Run 创建后禁止。
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
{"item_id": ..., "status": ..., "attempt_no": ...}。
|
||||
@@ -137,14 +158,14 @@ def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_R
|
||||
kind_value = str(kind or "").strip()
|
||||
if kind_value == RETRY_KIND_RPA_REFETCH:
|
||||
raise ValidationError("RPA refetch is not allowed after execution run is created", code="TRANSFER.RETRY_RPA_NOT_ALLOWED")
|
||||
if kind_value != RETRY_KIND_ERP_RECHECK:
|
||||
if kind_value != RETRY_KIND_EXTERNAL_RECHECK:
|
||||
raise ValidationError(f"unsupported retry kind: {kind_value}", code="TRANSFER.RETRY_KIND_INVALID")
|
||||
item = db.session.get(TransferInvoiceItem, item_id)
|
||||
if item is None:
|
||||
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
|
||||
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
|
||||
raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN")
|
||||
if item.status not in {status_machine.TransferStatus.BLOCKED_RECOVERABLE.value}:
|
||||
if item.status not in _RETRYABLE_STATUSES:
|
||||
raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED")
|
||||
|
||||
status = _recheck_item(item, deps=deps, request_id=request_id)
|
||||
@@ -154,12 +175,12 @@ def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_R
|
||||
|
||||
def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""批量重查 ERP 库存:对同一预检下全部/指定的可恢复阻断行逐票重查并刷新。
|
||||
"""批量重查 外部系统 库存:对同一预检下全部/指定的可重查行(可恢复阻断 + 可执行)逐票重查并刷新。
|
||||
|
||||
Args:
|
||||
precheck_no: 预检编号(定位明细集合)。
|
||||
deps: 注入依赖(erp = 网关适配器)。
|
||||
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该预检全部可恢复阻断行。
|
||||
deps: 注入依赖(capabilities = 外部系统网关客户端)。
|
||||
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该预检全部可重查行。
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
{"precheck_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
|
||||
@@ -170,8 +191,9 @@ def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=precheck_no).first()
|
||||
if precheck is None:
|
||||
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
|
||||
query = TransferInvoiceItem.query.filter_by(
|
||||
precheck_id=precheck.id, status=status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
query = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.precheck_id == precheck.id,
|
||||
TransferInvoiceItem.status.in_(_RETRYABLE_STATUSES),
|
||||
)
|
||||
wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()]
|
||||
if wanted:
|
||||
@@ -181,7 +203,7 @@ def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str
|
||||
results: list[dict] = []
|
||||
for item in items:
|
||||
try:
|
||||
retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_ERP_RECHECK,
|
||||
retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK,
|
||||
actor_id=actor_id, request_id=request_id)
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": True, "status": item.status})
|
||||
@@ -189,6 +211,11 @@ def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": False, "error": exc.message})
|
||||
except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:任何单行异常不炸整批
|
||||
# 与 _recheck_item 降级同理:DB 只留单行结果,控制台必须同步留痕。
|
||||
logger.warning(
|
||||
"transfer requery row crashed (skipped): invoice=%s item=%s error=%s",
|
||||
item.invoice_no, item.id, str(exc).strip() or exc.__class__.__name__,
|
||||
)
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": False,
|
||||
"error": str(exc).strip() or exc.__class__.__name__})
|
||||
|
||||
@@ -28,7 +28,7 @@ def serialize_summary(summary) -> dict[str, Any]:
|
||||
"blocked_count": summary.counts.blocked_count,
|
||||
},
|
||||
"estimated_transfer_quantity": summary.estimated_transfer_quantity,
|
||||
"estimated_erp_write_count": summary.estimated_erp_write_count,
|
||||
"estimated_external_write_count": summary.estimated_external_write_count,
|
||||
"precheck_hash": summary.precheck_hash,
|
||||
}
|
||||
|
||||
|
||||
@@ -3,14 +3,20 @@
|
||||
用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile),
|
||||
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 无文件待触发",
|
||||
供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
|
||||
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)。
|
||||
逻辑:按来源取该来源最新收料执行单元;有文件 → ready;有进行中单元 → fetching;
|
||||
最新单元为失败终态 → failed;否则 → none。
|
||||
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)、
|
||||
receipt_file_gate(可用/失效判定单一事实来源)。
|
||||
逻辑:按来源取该来源最新收料执行单元;命中可用门禁(当天业务日抓取且未过期,
|
||||
见 receipt_file_gate)→ ready;有进行中单元 → fetching;
|
||||
最新单元为失败终态 → failed;文件仍在但已失效 → expired;否则 → none。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
||||
from app.services.in_transit_transfer.receipt_file_gate import (
|
||||
expired_receipt_file_condition,
|
||||
usable_receipt_file_condition,
|
||||
)
|
||||
|
||||
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
|
||||
FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
|
||||
@@ -19,16 +25,19 @@ FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
|
||||
def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
"""返回某来源的收料文件状态投影。
|
||||
|
||||
失效判定(不依赖保留期清理任务落位,与预检取文件/下载同口径,见
|
||||
receipt_file_gate):保留期已到 或 非当前业务日(Asia/Shanghai)抓取。
|
||||
|
||||
Returns:
|
||||
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
|
||||
file_status ∈ {'ready', 'fetching', 'failed', 'none'}。
|
||||
file_status ∈ {'ready', 'fetching', 'failed', 'expired', 'none'}。
|
||||
"""
|
||||
report = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
usable_receipt_file_condition(),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
||||
.first()
|
||||
@@ -60,4 +69,17 @@ def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
|
||||
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
# 文件仍在但已失效(保留期已到或隔日旧文件):不报 ready,单独投影 expired 提示重抓。
|
||||
expired_report = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
expired_receipt_file_condition(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if expired_report is not None:
|
||||
return {'file_status': 'expired', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
@@ -4,7 +4,7 @@
|
||||
让 create_precheck / restore / 未来回调等调用方都经由本服务,不各自散落改表。
|
||||
依赖:models(TransferSourceJob)、status_machine。
|
||||
逻辑:本服务只操作 run 内来源状态;(run_id, source_code) 唯一由模型约束;
|
||||
不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 ERP/触发 RPA。
|
||||
不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 外部系统/触发 RPA。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
逻辑:转换表声明即白名单,未声明的迁移一律抛 TransferStateError;
|
||||
result_unknown / manually_closed / success / duplicate_success /
|
||||
not_matured / cancelled 为无出边终态;
|
||||
通知失败(notification_failed)是通知投递状态,绝不改写 ERP 业务结果。
|
||||
通知失败(notification_failed)是通知投递状态,绝不改写 外部系统 业务结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -39,7 +39,7 @@ class TransferStatus(StrEnum):
|
||||
|
||||
|
||||
class TransferRunStatus(StrEnum):
|
||||
"""Run 级生命周期;ERP 结果与通知结果分离。"""
|
||||
"""Run 级生命周期;外部系统 结果与通知结果分离。"""
|
||||
|
||||
QUEUED = "queued"
|
||||
PREPARING_FILES = "preparing_files"
|
||||
@@ -101,7 +101,7 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
TransferStatus.CANCELLED.value,
|
||||
}),
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value: frozenset({
|
||||
TransferStatus.PRECHECKING.value, # 仅 ERP 重查/重新预检,创建新 Attempt
|
||||
TransferStatus.PRECHECKING.value, # 仅 外部系统 重查/重新预检,创建新 Attempt
|
||||
TransferStatus.MANUALLY_CLOSED.value,
|
||||
TransferStatus.CANCELLED.value,
|
||||
}),
|
||||
@@ -199,19 +199,19 @@ def assert_transition_allowed(
|
||||
|
||||
|
||||
def apply_notification_failure(run_status: str) -> str:
|
||||
"""通知失败不改变 ERP 结果。
|
||||
"""通知失败不改变 外部系统 结果。
|
||||
|
||||
Args:
|
||||
run_status: Run 的 ERP 业务终态。
|
||||
run_status: Run 的 外部系统 业务终态。
|
||||
Returns:
|
||||
原 run_status(保持不变)。
|
||||
Raises:
|
||||
TransferStateError: Run 尚未进入 ERP 终态时不允许记录通知失败。
|
||||
TransferStateError: Run 尚未进入 外部系统 终态时不允许记录通知失败。
|
||||
"""
|
||||
status = str(run_status or "").strip()
|
||||
if status not in {TransferRunStatus.SUCCESS.value, TransferRunStatus.PARTIAL_FAILED.value}:
|
||||
raise TransferStateError(
|
||||
"notification failure only allowed after ERP terminal status",
|
||||
"notification failure only allowed after 外部系统 terminal status",
|
||||
current=status,
|
||||
)
|
||||
return status
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨策略硬门禁。
|
||||
|
||||
用途:一期策略禁止部分数量调拨、数量容差与 ERP 自动重试,
|
||||
用途:一期策略禁止部分数量调拨、数量容差与 外部系统 自动重试,
|
||||
强制默认 10 分钟确认有效期。
|
||||
依赖:app.core.errors.AppError、standard decimal。
|
||||
逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError,
|
||||
@@ -24,7 +24,7 @@ class TransferStrategyPolicy:
|
||||
|
||||
allow_partial: bool = False
|
||||
quantity_tolerance: Decimal = Decimal("0")
|
||||
allow_erp_auto_retry: bool = False
|
||||
allow_external_auto_retry: bool = False
|
||||
confirm_ttl_seconds: int = DEFAULT_CONFIRM_TTL_SECONDS
|
||||
|
||||
|
||||
@@ -46,14 +46,14 @@ def validate_strategy(strategy: TransferStrategyPolicy) -> None:
|
||||
Args:
|
||||
strategy: 待校验策略。
|
||||
Raises:
|
||||
StrategyViolationError: 开启部分调拨、非零容差或 ERP 自动重试。
|
||||
StrategyViolationError: 开启部分调拨、非零容差或 外部系统 自动重试。
|
||||
"""
|
||||
if strategy.allow_partial:
|
||||
raise StrategyViolationError("partial transfer is not supported in phase 1", reason="allow_partial")
|
||||
if strategy.quantity_tolerance != Decimal("0"):
|
||||
raise StrategyViolationError("quantity tolerance is not supported in phase 1", reason="quantity_tolerance")
|
||||
if strategy.allow_erp_auto_retry:
|
||||
raise StrategyViolationError("ERP auto retry is forbidden in phase 1", reason="allow_erp_auto_retry")
|
||||
if strategy.allow_external_auto_retry:
|
||||
raise StrategyViolationError("External auto retry is forbidden in phase 1", reason="allow_external_auto_retry")
|
||||
|
||||
|
||||
def default_strategy() -> TransferStrategyPolicy:
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""在途调拨类型契约。
|
||||
|
||||
用途:定义调拨业务类型(在途仓至HUB仓 / HUB仓维修出 / HUB仓间调拨)及各类型
|
||||
的收料数据范围规则;类型 2/3 一期占位(fail-closed 拒绝预检,规则先冻结)。
|
||||
依赖:app.core.errors.ValidationError、invoice_aggregator.AggregatedInvoice。
|
||||
逻辑:类型决定预检纳入哪些收料票——类型 1 只保留 INVOICE 以 HOM/HOX/WTP 开头
|
||||
的票(大小写不敏感,范围外票与收料日期范围过滤同语义,静默排除不入明细);
|
||||
类型 2 规则已定(ODM ID=HoxinRMA)待收料文件解析层支持 odm_id 字段后启用;
|
||||
类型 3 规则待业务定义。调用方必须先 ensure_transfer_type_supported 再过滤。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import StrEnum
|
||||
from typing import Iterable
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.in_transit_transfer.invoice_aggregator import AggregatedInvoice
|
||||
|
||||
# 类型不支持(占位类型被调用)时的稳定错误码。
|
||||
TRANSFER_TYPE_NOT_SUPPORTED = "TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED"
|
||||
|
||||
|
||||
class TransferType(StrEnum):
|
||||
"""调拨业务类型(值与前端/i18n、transfer_runs.transfer_type 列一致)。"""
|
||||
|
||||
IN_TRANSIT_TO_HUB = "in_transit_to_hub" # 在途仓至HUB仓
|
||||
HUB_REPAIR_OUT = "hub_repair_out" # HUB仓维修出(占位)
|
||||
HUB_TO_HUB = "hub_to_hub" # HUB仓间调拨(占位)
|
||||
|
||||
|
||||
# 一期已实现预检/执行链路的类型;其余类型 fail-closed(占位,防止误生成 外部系统 单)。
|
||||
SUPPORTED_TRANSFER_TYPES: frozenset[TransferType] = frozenset({TransferType.IN_TRANSIT_TO_HUB})
|
||||
|
||||
# 类型 1(在途仓至HUB仓)数据范围:INVOICE 开头前缀(大小写不敏感)。
|
||||
IN_TRANSIT_TO_HUB_INVOICE_PREFIXES: tuple[str, ...] = ("HOM", "HOX", "WTP")
|
||||
|
||||
# 类型 2(HUB仓维修出)数据范围:ODM ID 精确值;待 movement 文件暴露 odm_id 后启用。
|
||||
HUB_REPAIR_OUT_ODM_ID = "HoxinRMA"
|
||||
|
||||
|
||||
def normalize_transfer_type(value: str | TransferType | None) -> TransferType:
|
||||
"""规范化调拨类型入参;缺省/空值回落到类型 1(存量调用方语义不变)。
|
||||
|
||||
Args:
|
||||
value: 前端/API 传入的调拨类型值。
|
||||
Returns:
|
||||
TransferType 枚举。
|
||||
Raises:
|
||||
ValidationError: 非法类型值(不在枚举内)。
|
||||
"""
|
||||
raw = str(value.value if isinstance(value, TransferType) else (value or "")).strip()
|
||||
if not raw:
|
||||
return TransferType.IN_TRANSIT_TO_HUB
|
||||
try:
|
||||
return TransferType(raw)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(
|
||||
f"unknown transfer type: {raw}",
|
||||
code="TRANSFER.TRANSFER_TYPE_INVALID",
|
||||
details={"transfer_type": raw},
|
||||
) from exc
|
||||
|
||||
|
||||
def ensure_transfer_type_supported(transfer_type: TransferType) -> None:
|
||||
"""占位类型 fail-closed:类型 2/3 处理链路未实现前禁止进入预检。
|
||||
|
||||
Args:
|
||||
transfer_type: 已规范化的调拨类型。
|
||||
Raises:
|
||||
ValidationError: 类型未实现(TRANSFER_TYPE_NOT_SUPPORTED)。
|
||||
"""
|
||||
if transfer_type not in SUPPORTED_TRANSFER_TYPES:
|
||||
raise ValidationError(
|
||||
f"transfer type not supported yet: {transfer_type.value}",
|
||||
code=TRANSFER_TYPE_NOT_SUPPORTED,
|
||||
details={"transfer_type": transfer_type.value},
|
||||
)
|
||||
|
||||
|
||||
def filter_invoices_for_type(
|
||||
invoices: Iterable[AggregatedInvoice],
|
||||
transfer_type: TransferType,
|
||||
) -> list[AggregatedInvoice]:
|
||||
"""按类型的收料数据范围过滤汇总票(返回保留项,保持原顺序)。
|
||||
|
||||
Args:
|
||||
invoices: 已汇总的收料票。
|
||||
transfer_type: 已规范化且已确认支持的调拨类型。
|
||||
Returns:
|
||||
类型范围内的票列表。
|
||||
"""
|
||||
if transfer_type == TransferType.IN_TRANSIT_TO_HUB:
|
||||
prefixes = tuple(prefix.upper() for prefix in IN_TRANSIT_TO_HUB_INVOICE_PREFIXES)
|
||||
return [
|
||||
invoice for invoice in invoices
|
||||
if str(invoice.invoice_no or "").strip().upper().startswith(prefixes)
|
||||
]
|
||||
# 类型 2/3 的过滤规则在启用时补齐(此前 ensure_transfer_type_supported 已拦截)。
|
||||
return list(invoices)
|
||||
|
||||
|
||||
def transfer_type_scope_note(transfer_type: TransferType) -> str:
|
||||
"""类型的范围规则说明(写入 TransferPrecheck.scope_json 供审计追溯)。"""
|
||||
if transfer_type == TransferType.IN_TRANSIT_TO_HUB:
|
||||
return f"invoice_prefix:{'+'.join(IN_TRANSIT_TO_HUB_INVOICE_PREFIXES).lower()}"
|
||||
if transfer_type == TransferType.HUB_REPAIR_OUT:
|
||||
return f"odm_id:{HUB_REPAIR_OUT_ODM_ID}"
|
||||
return "pending_rule"
|
||||
Reference in new issue
Block a user