Files
syops/backend/app/services/in_transit_transfer/deps.py
T
hugo abf3d48927 feat(in-transit-transfer): 自动调拨联动收料就绪并分层来源错误
- 调度整合:退役 in_transit_receipt_file_job,收料归档收敛 shipping_receipt_rpa_archive,排程注册表统一
- 自动调拨 Job:调拨前确保各来源当日收料文件就绪(缺失自动触发收料 RPA),严格等量匹配后生成 ERP 调拨单
- worker 手动唤醒:排程工作台支持手动唤醒与 runs 透视,heartbeat 协议同步
- 收料缺失幸存 T2:parse_failed 状态落库(迁移 q4c5)
- 来源错误分层与 stale 时钟换源:改挂 inventory_checked_at 库存查得时刻,展示阈值与执行门禁解耦(迁移 t5a6)
- 新增 wecom_sender 企微通知:每非空 Run 汇总一条,通知失败不影响 ERP 结果
- 同步排程工作台/调拨卡片前端、chat/admin 文案四语言、RPA 脚本与测试全家
2026-09-30 00:20:06 +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
(复用货代收料归档 + 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_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=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"),
}