Files
syops/backend/app/services/in_transit_transfer/deps.py
T
hugo 8102a1fe44 feat(in-transit-transfer): inbound/outbound 幂等重命名与解析用途分层
- receipt→inbound 三件套改名(回调桥/文件门禁/触发服务),回调链幂等去重,迁移 tt14 同步台账键与测试基建
- 库存解析用途分层 onhand/inbound/outbound(迁移 tt15):解析档案、文件存储与下载名按用途隔离,管理端表单同步
- 「成熟」概念退役(迁移 tt16):数据无成熟属性,日期边界由调用方入参严格判定
- backlog 新增重解析服务,在途重识别投影 processing,EML 父项不再停留处理中
- 收料 RPA 回调/归档/排程链路同步改名挂点,运维脚本复位假完成状态
- 文档随批:ADR 0003 模块边界决策、10-15/10-16 计划与设计、调拨文档族与 demand/tec/funclist
- 同步 chat/errors 文案四语言、调拨前端卡片与 e2e、测试全家
2026-10-16 19:43:49 +08:00

189 lines
9.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""在途调拨依赖装配(Dependencies)。
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
依赖:movement_file_repository / capability_client / matching_service / models / Flask config。
逻辑:默认实现直接接线真实链路 —— 入站文件行读取走 movement_file_repository
(复用 ShippingReceiptReport 归档 + inbound 解析规则,无文件/无规则时返回 None 由
匹配走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed);
策略经 _strategy_from_config 从 Flask 配置装配——IN_TRANSIT_TRANSFER_
CONFIRM_TTL_SECONDS 的真实生效点(2026-09-24 接线,此前环境变量为死配置:
TransferDeps 不传 strategy 时落数据类硬编码 600s)。
"""
from __future__ import annotations
from dataclasses import replace
from typing import Any
from flask import current_app
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.services.in_transit_transfer.capability_client import CapabilityClient
from app.services.in_transit_transfer.movement_file_repository import ShippingInboundFileRepository
from app.services.in_transit_transfer.matching_service import (
RouteMapping,
RouteNotResolvedError,
RouteResolver,
TransferDeps,
)
from app.services.in_transit_transfer.strategy import (
DEFAULT_CONFIRM_TTL_SECONDS,
DEFAULT_INVENTORY_STALE_TTL_SECONDS,
default_strategy,
)
class DefaultRouteResolver:
"""默认路由解析:仓库映射的在途仓编码 + 外部系统仓库。
拨出库位 = 映射行的在途仓编码(in_transit_warehouse_code);拨入仓库 = 映射的
目标仓库代码;组织 = 映射的外部组织编码。映射行按库存源识别方式选择:
inventory_match 源优先「入站文件仓库列 == 货代仓库」精确匹配,匹配不到回退
货代仓库为空的默认映射行(空库位兜底);fixed 源仅一条启用映射直接取用。
不借用站点固定仓库(那是货代发货/库存导出链路的字段)。
"""
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)
mappings = ShippingInventoryExternalMapping.query.filter_by(
inventory_source_id=source.id, enabled=True,
).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(selected.in_transit_warehouse_code or '').strip()
if not from_warehouse:
# 拨出库位无来源(映射未维护在途仓编码)——fail-closed,不猜测。
raise RouteNotResolvedError(source_code=source_code)
return RouteMapping(
external_org=selected.external_organization_code,
from_warehouse=from_warehouse,
to_warehouse=selected.external_warehouse_code,
)
def _build_capability_client() -> CapabilityClient:
"""装配调拨外部访问客户端:查询/建单统一走 CapabilityGateway(绑定缺失 fail-closed)。
P1 连接器框架:外部系统差异由配置(ClientInstance/InterfaceDefinition/Binding/映射)
承担;create_transfer 为单据级委派(T9)——顺序编排/分类在网关引擎,域侧只做
TransferOrder → 六键 params 展平与六态结果映射;原「WSDL 冻结前 fail-closed」
门(ExternalNotFrozenError)已移除,绑定缺失由网关 BindingNotFoundError 承担。
"""
return CapabilityClient()
_override: TransferDeps | None = None
def set_transfer_dependencies(deps: TransferDeps | None) -> None:
"""测试注入点:设置/清除 TransferDeps 覆盖。"""
global _override # noqa: PLW0603
_override = deps
def _ttl_from_config(key: str, default: int) -> int:
"""读取整型 TTL 配置(无应用上下文/非法值回落代码默认,下限 1 秒)。"""
try:
raw = current_app.config.get(key, default)
except RuntimeError: # 无 app context:回落代码默认(等同旧行为)
raw = default
try:
return max(1, int(raw))
except (TypeError, ValueError):
return default
def _strategy_from_config():
"""从 Flask 配置装配策略快照(TTL 环境变量的真实生效点)。
Why: IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS 只进 Flask config(settings.Config),
而 TransferDeps.strategy 缺省落数据类硬编码 600s——环境变量曾是死配置,调大无效。
无应用上下文(纯脚本/裸调用)时回落代码默认值,行为与历史一致。
Returns:
TransferStrategyPolicy(confirm_ttl_seconds / inventory_stale_ttl_seconds
=max(1, 配置值),禁令项沿用默认)。
"""
return replace(
default_strategy(),
confirm_ttl_seconds=_ttl_from_config(
"IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS", DEFAULT_CONFIRM_TTL_SECONDS,
),
inventory_stale_ttl_seconds=_ttl_from_config(
"IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS", DEFAULT_INVENTORY_STALE_TTL_SECONDS,
),
)
def get_transfer_dependencies() -> TransferDeps:
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/外部系统 网关)。"""
if _override is not None:
return _override
return TransferDeps(
file_repository=ShippingInboundFileRepository(),
rpa_trigger=_DefaultRpaTrigger(),
route_resolver=DefaultRouteResolver(),
capabilities=_build_capability_client(),
strategy=_strategy_from_config(),
)
class _DefaultRpaTrigger:
"""默认入站 RPA 触发器:委托真实触发服务(trigger_inbound_rpa)。
真实链路 = 落单元行 + 原子写 trigger 文件;来源/ShippingReceiptReportConfig 缺失或 trigger
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
另在本类前置守卫: ShippingReceiptReportConfig 存在但未绑定已发布 inbound 解析规则时
直接返回 RPA_INBOUND_PROFILE_MISSING,不触发徒劳抓取。
"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
from app.services.in_transit_transfer.inbound_trigger_service import trigger_inbound_rpa
# [守卫] ShippingReceiptReportConfig 存在但未绑定已发布 inbound 解析规则时,触发 RPA 必然徒劳:
# 抓回的文件无法被 latest_ready_file 复用,匹配会反复重抓。fail-closed 返回明确错误码。
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is not None:
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
if config is not None:
profile = config.parsing_profile
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
return {'ok': False, 'error_code': 'RPA_INBOUND_PROFILE_MISSING'}
outcome = trigger_inbound_rpa(source_code=source_code, business_date=business_date, reason=reason)
return {
"ok": bool(outcome.get("ok")),
"callback_id": outcome.get("callback_id"),
"error_code": outcome.get("error_code"),
"error_message": outcome.get("error_message"),
}