"""在途调拨依赖装配(Dependencies)。 用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。 依赖:movement_file_repository / capability_client / matching_service / models / Flask config。 逻辑:默认实现直接接线真实链路 —— 入站文件行读取走 movement_file_repository (复用 ShippingInboundReport 归档 + 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 FreightRpaOnhandExternalMapping from app.services.freight_rpa.reports.queries import ( get_inbound_config, get_inbound_parsing_profile, get_site, ) 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。 【阶段 B Task 4】站点行(主键/启停/识别方式)读取改经 freight_rpa.reports.queries.get_site 只读视图,不再引用站点模型; 外部仓库映射仍为调拨域自有表(freight_rpa_onhand_external_mappings 不改归属,见计划 Global Constraints),按站点主键直查。 Args: source_code: 来源实例编码(须启用)。 invoice_no: Invoice 单号(当前不参与匹配,保留协议兼容)。 warehouse_code: 入站文件「仓库」列原值(inventory_match 源的映射匹配键)。 Returns: RouteMapping(external_org / from_warehouse=在途仓编码 / to_warehouse)。 Raises: RouteNotResolvedError: 来源不存在、无可用映射行或在途仓编码未维护。 """ site = get_site(source_code) if site is None or not site.enabled: raise RouteNotResolvedError(source_code=source_code) mappings = FreightRpaOnhandExternalMapping.query.filter_by( source_id=site.source_id, enabled=True, ).all() selected = None if site.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 文件;站点/入站配置缺失或 trigger 目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。 另在本类前置守卫:入站配置存在但未绑定已发布 inbound 解析规则时 直接返回 RPA_INBOUND_PROFILE_MISSING,不触发徒劳抓取。 【阶段 B Task 4】守卫读取改经 freight_rpa.reports.queries 只读入口 (get_site / get_inbound_config / get_inbound_parsing_profile)。 """ 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 # [守卫] 入站配置存在但未绑定已发布 inbound 解析规则时,触发 RPA 必然徒劳: # 抓回的文件无法被 latest_ready_file 复用,匹配会反复重抓。fail-closed 返回明确错误码。 site = get_site(source_code) if site is not None and site.enabled: config = get_inbound_config(source_code) if config is not None: profile = get_inbound_parsing_profile(source_code) 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"), }