Files
syops/backend/app/services/in_transit_transfer/deps.py
T
hugo 9f2b023a10 feat(in-transit-transfer): 打通ERP 写路径按票执行与已执行调拨单卡片入口
- 新增 TransferDocument 按票执行模型与单据号序列生成(document_id 独立模块,迁移 tt0d/tt8b)
- 发票行新增单位字段、matching_id 放宽可空,支持行与票两级执行口径(迁移 tt9c/tt1a)
- capability_client 新增 create_transfer 写契约与六态结果裁决,执行链补写前复查门禁
- 抽取/匹配/执行 Job 按 run/item/match 拆分并入 jobs store 队列,transfer 队列单实例 worker 配套本地启动脚本
- 首页新增「已执行调拨单」四统计卡入口与明细列表子视图,重查/重试/关闭/重新触发与筛选分页齐全
- 行评估新鲜度 TTL 从 10 分钟放宽为当日有效(86400s),跨日由文件版本对账门禁兜底
- 同步 chat/errors 文案四语言、测试全家与两份实施计划文档
2026-09-27 18:13:25 +08:00

177 lines
8.7 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
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 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 ShippingReceiptFileRepository
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_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 _strategy_from_config():
"""从 Flask 配置装配策略快照(TTL 环境变量的真实生效点)。
Why: IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS 只进 Flask config(settings.Config),
而 TransferDeps.strategy 缺省落数据类硬编码 600s——环境变量曾是死配置,调大无效。
无应用上下文(纯脚本/裸调用)时回落代码默认值,行为与历史一致。
Returns:
TransferStrategyPolicy(confirm_ttl_seconds=max(1, 配置值),禁令项沿用默认)。
"""
try:
raw = current_app.config.get(
"IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS", DEFAULT_CONFIRM_TTL_SECONDS,
)
except RuntimeError: # 无 app context:回落代码默认(等同旧行为)
raw = DEFAULT_CONFIRM_TTL_SECONDS
try:
ttl = int(raw)
except (TypeError, ValueError):
ttl = DEFAULT_CONFIRM_TTL_SECONDS
return replace(default_strategy(), confirm_ttl_seconds=max(1, ttl))
def get_transfer_dependencies() -> TransferDeps:
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/外部系统 网关)。"""
if _override is not None:
return _override
return TransferDeps(
file_repository=ShippingReceiptFileRepository(),
rpa_trigger=_DefaultRpaTrigger(),
route_resolver=DefaultRouteResolver(),
capabilities=_build_capability_client(),
strategy=_strategy_from_config(),
)
class _DefaultRpaTrigger:
"""默认收料 RPA 触发器:委托真实触发服务(trigger_receipt_rpa)。
真实链路 = 落单元行 + 原子写 trigger 文件;来源/收料配置缺失或 trigger
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
另在本类前置守卫:收料配置存在但未绑定已发布 movement 解析规则时
直接返回 RPA_RECEIPT_MOVEMENT_PROFILE_MISSING,不触发徒劳抓取。
"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
# [守卫] 收料配置存在但未绑定已发布 movement 解析规则时,触发 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 != 'movement':
return {'ok': False, 'error_code': 'RPA_RECEIPT_MOVEMENT_PROFILE_MISSING'}
outcome = trigger_receipt_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"),
}