Files
syops/docs/superpowers/plans/2026-09-22-warehouse-mapping-in-transit-code.md
T
hugo 9959b06acd 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 测试与域文档
2026-09-23 00:49:38 +08:00

42 KiB
Raw Blame History

仓库映射在途仓编码与调拨拨出库位改造 实施计划

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: 仓库映射新增「在途仓编码」字段并放开货代仓库必填;在途调拨拨出库位改为取映射行的在途仓编码,inventory_match 源按「收料文件仓库列 == 货代仓库」优先匹配、「空库位(货代仓库为空的默认映射行)」兜底。

Architecture: 配置侧为 shipping_inventory_external_mappings 加列 in_transit_warehouse_code(保存端必填)+ freight_warehouse_id 改可选(前后端同步)。调拨侧把收料文件「仓库」列(movement 契约 warehouse_code)从解析层贯通到 transfer_invoice_items.receipt_warehouse_code(新列),DefaultRouteResolver.resolve() 增加 warehouse_code 入参并按库存源 warehouse_resolution_mode 选择映射行;预检/执行/重试三处调用点同步传参。任何映射行缺失或在途仓编码为空维持 fail-closed(RouteNotResolvedError)。

Tech Stack: Flask + SQLAlchemy 2.0 + Alembic(后端);Vue 3 + TailwindCSS + Vue I18n 四语言(前端);pytest(测试)。

Spec: 本需求为会话确认稿(2026-09-22),共 4 点:① 目标仓库编码移至目标仓库名称前;② 原目标仓库编码位置新增「在途仓编码」;③ 货代仓库不再必填;④ 在途调拨拨出库位取在途仓编码,inventory_match 源优先「库存源+收料文件库位」匹配、失败按「库存源+空库位」兜底。已确认决策:库位 = 收料文件 movement 契约 warehouse_code(仓库)列;匹配比对映射行 freight_warehouse_id(大写归一);fixed(指定仓库)源仅一条启用映射直接取用;在途仓编码保存端必填。

Global Constraints

  • 改表结构必须配套 Alembic 迁移(AGENTS.md §8);迁移 head 当前为 re1f3a4b5c6d。
  • i18n 四语言 zh-CN / zh-TW / en / th 必须同步补齐,禁止硬编码中文。
  • 新建/调整代码须满足 AGENTS.md §5 注释两层标准:文件层 docstring + 函数层 docstring(含 Args/Returns);逻辑修改必须同步更新过期注释。
  • JSON API 错误统一 AppError 子类;本改造沿用 ValidationError / RouteNotResolvedError,不新造返回结构。
  • 禁止自动 commit:每个任务以 git add 暂存结束,提交由用户批准后进行;提交信息建议 feat(shipping-notice): 仓库映射新增在途仓编码并在途调拨拨出库位改取在途仓。
  • 后端测试命令在 backend/ 目录下执行(python -m pytest ...,先激活 venv);前端改动后必须 npm run build 通过。
  • 部分唯一索引 uq_shipping_inv_ext_map_src_default_enabled(freight_warehouse_id IS NULL AND enabled)与 uq_shipping_inv_ext_map_src_wh_enabled((inventory_source_id, freight_warehouse_id) AND enabled)已存在,无需改动——同源下「精确映射」与「默认映射」各最多一条启用,保证 resolver 选择确定性。

Task 1: Alembic 迁移与模型字段

Files:

  • Create: backend/migrations/versions/it2c3d4e5f6a7_add_in_transit_warehouse_code.py
  • Modify: backend/app/models/shipping_inventory_config.py:364-400(ShippingInventoryExternalMapping)
  • Modify: backend/app/models/in_transit_transfer.py:186-234(TransferInvoiceItem)

Interfaces:

  • Produces: ShippingInventoryExternalMapping.in_transit_warehouse_code: Mapped[str](NOT NULL,默认 '');TransferInvoiceItem.receipt_warehouse_code: Mapped[str](NOT NULL,默认 '')。后续任务按这两个属性名读写。

  • Step 1: 编写迁移文件

创建 backend/migrations/versions/it2c3d4e5f6a7_add_in_transit_warehouse_code.py:

"""仓库映射新增在途仓编码;调拨明细记录收料仓库匹配键。

用途:shipping_inventory_external_mappings 增加 in_transit_warehouse_code(在途调拨拨出库位
      来源,保存端必填);transfer_invoice_items 增加 receipt_warehouse_code(收料文件
      「仓库」列原值,inventory_match 源映射行匹配键的审计留痕)。
依赖:alembic op / sqlalchemy sa。
逻辑:两列均为带 '' 默认值的追加列,不改既有数据;downgrade 直接删列。
"""

from alembic import op
import sqlalchemy as sa

revision = 'it2c3d4e5f6a7'
down_revision = 're1f3a4b5c6d'
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.add_column(
        'shipping_inventory_external_mappings',
        sa.Column('in_transit_warehouse_code', sa.String(length=64), nullable=False,
                  server_default='', comment='在途仓编码(在途调拨拨出库位来源)'),
    )
    op.add_column(
        'transfer_invoice_items',
        sa.Column('receipt_warehouse_code', sa.String(length=64), nullable=False,
                  server_default='', comment='收料文件仓库列原值(映射行匹配键)'),
    )


def downgrade() -> None:
    op.drop_column('transfer_invoice_items', 'receipt_warehouse_code')
    op.drop_column('shipping_inventory_external_mappings', 'in_transit_warehouse_code')
  • Step 2: 迁移前重算 head 防漂移

Run: cd backend/migrations/versions && python -c "import re,glob;revs={};downs=set();[ (revs.update({m.group(1):f}),downs.update(re.findall(r'[\'\"]([^\'\"]+)[\'\"]',d.group(1)))) for f in glob.glob('*.py') for m,d in [(re.search(r'^revision(?::\s*str)?\s*=\s*[\'\"]([^\'\"]+)[\'\"]',open(f,encoding='utf-8').read(),re.M),re.search(r'^down_revision(?::[^=]*)?\s*=\s*(.+?)$',open(f,encoding='utf-8').read(),re.M))] if m]" 2>/dev/null || echo "用任务书上的脚本重算"(若 head 不是 re1f3a4b5c6d,改迁移文件的 down_revision;head 唯一且为本迁移名时继续)

  • Step 3: 模型加列(ShippingInventoryExternalMapping)

backend/app/models/shipping_inventory_config.py —— 类 docstring(365-369 行)整段替换 + 在 external_warehouse_name(398 行)之后加列:

class ShippingInventoryExternalMapping(Base):
    """库存源到外部系统仓库的映射。

    freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件
    「仓库」列(空值即「空库位」默认映射行,部分唯一索引保证同源最多一条启用);
    fixed 源仅一条启用映射直接取用。in_transit_warehouse_code(在途仓编码)是
    在途调拨拨出库位的来源(in_transit_transfer DefaultRouteResolver),保存端必填,
    库内空串仅为存量行兼容。
    """
    # 在途仓编码:在途调拨拨出库位来源(DefaultRouteResolver);保存端必填。
    in_transit_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, server_default='', default='')
  • Step 4: 模型加列(TransferInvoiceItem)

backend/app/models/in_transit_transfer.py —— 在 lot_no(213 行)之后加:

    # 收料文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
    receipt_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
  • Step 5: 跑既有套件确认无回归

Run: cd backend && python -m pytest tests/services/admin/test_shipping_inventory_service.py tests/services/in_transit_transfer -q Expected: 全部 PASS(加列不影响既有行为;此时尚未改服务逻辑)。若本地库可用,另跑 flask db upgrade 确认迁移可执行。

  • Step 6: 暂存
git add backend/migrations/versions/it2c3d4e5f6a7_add_in_transit_warehouse_code.py backend/app/models/shipping_inventory_config.py backend/app/models/in_transit_transfer.py

Task 2: 后端映射服务——货代仓库改可选、在途仓编码必填

Files:

  • Modify: backend/app/services/admin/shipping_inventory_service.py:1174-1229
  • Test: backend/tests/services/admin/test_shipping_inventory_service.py:536-577

Interfaces:

  • Consumes: Task 1 的 ShippingInventoryExternalMapping.in_transit_warehouse_code。

  • Produces: save_external_mapping(data, *, actor_id, mapping_id=None) -> dict——payload 新增键 in_transit_warehouse_code;freight_warehouse_id 缺省/空保存为 None;in_transit_warehouse_code 缺省抛 ValidationError。前端与 API 依赖该 payload 键。

  • Step 1: 改写测试(先失败)

backend/tests/services/admin/test_shipping_inventory_service.py —— 三个测试整体替换为:

def test_active_default_external_mapping_is_unique_per_source(app):
    """同一库存源同一货代仓库身份只能有一条启用的映射。"""
    app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
    with app.app_context():
        profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
        source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
        payload = {
            'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
            'external_organization_code': None, 'external_site_code': 'EU01',
            'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin',
            'in_transit_warehouse_code': 'TZR2', 'enabled': True,
        }
        shipping_inventory_service.save_external_mapping(payload, actor_id=None)
        with pytest.raises(ConflictError):
            shipping_inventory_service.save_external_mapping(payload, actor_id=None)


def test_external_mapping_allows_empty_freight_warehouse(app):
    """货代仓库改为可选:空值保存为 NULL(空库位默认映射行),供 inventory_match 源兜底匹配。"""
    app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
    with app.app_context():
        profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
        source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
        # [断言意图] 货代仓库为空不阻断保存;在途仓编码必填且大写归一后随 payload 返回。
        mapping = shipping_inventory_service.save_external_mapping({
            'inventory_source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP',
            'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin',
            'in_transit_warehouse_code': 'tzr2', 'enabled': True,
        }, actor_id=None)
        assert mapping['freight_warehouse_id'] is None
        assert mapping['in_transit_warehouse_code'] == 'TZR2'


def test_external_mapping_requires_in_transit_warehouse_code(app):
    """在途仓编码是在途调拨拨出库位来源——缺省必须在保存端拒绝(fail-closed 前置)。"""
    app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
    with app.app_context():
        profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
        source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
        # [断言意图] 缺在途仓编码的映射会让调拨拨出库位无来源,保存端必须 fail-closed。
        with pytest.raises(ValidationError):
            shipping_inventory_service.save_external_mapping({
                'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
                'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'enabled': True,
            }, actor_id=None)


def test_external_mapping_normalizes_freight_warehouse_identity(app):
    """配置端小写货代仓应与收料文件仓库值(大写归一后)使用同一精确映射身份。"""
    app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
    with app.app_context():
        profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
        source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
        mapping = shipping_inventory_service.save_external_mapping({
            'inventory_source_id': source['id'], 'freight_warehouse_id': 'dub',
            'external_system_code': 'TOPGP', 'external_warehouse_code': 'DUB01',
            'external_warehouse_name': 'Dublin', 'in_transit_warehouse_code': 'TZR2', 'enabled': True,
        }, actor_id=None)
        assert mapping['freight_warehouse_id'] == 'DUB'
  • Step 2: 运行测试确认失败

Run: cd backend && python -m pytest tests/services/admin/test_shipping_inventory_service.py -q -k external_mapping Expected: FAIL —— allows_empty_freight_warehouse 与 requires_in_transit_warehouse_code 失败(现逻辑货代仓库必填、在途仓编码未消费)。

  • Step 3: 实现服务层修改

backend/app/services/admin/shipping_inventory_service.py:

_external_payload(1174-1181 行)替换为:

def _external_payload(mapping: ShippingInventoryExternalMapping) -> dict[str, Any]:
    return {
        'id': mapping.id, 'inventory_source_id': mapping.inventory_source_id,
        '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,
    }

save_external_mapping(1211-1213 行的三行赋值)替换为:

    # 货代仓库改为可选维度: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()

(其余行不变;external_system_code 及之后的赋值保持原序。)

  • Step 4: 运行测试确认通过

Run: cd backend && python -m pytest tests/services/admin/test_shipping_inventory_service.py -q Expected: 全部 PASS。

  • Step 5: 暂存
git add backend/app/services/admin/shipping_inventory_service.py backend/tests/services/admin/test_shipping_inventory_service.py

Task 3: 收料文件仓库值贯通(解析层 + 汇总层)

Files:

  • Modify: backend/app/services/in_transit_transfer/file_parser.py:24-37,181-192
  • Modify: backend/app/services/in_transit_transfer/invoice_aggregator.py:21-33,73-83
  • Test: backend/tests/services/in_transit_transfer/test_movement_parser.py
  • Test: backend/tests/services/in_transit_transfer/test_invoice_aggregator.py

Interfaces:

  • Produces: ParsedReceiptRow.warehouse_code: str = ""、AggregatedInvoice.warehouse_code: str = ""(两处均带默认值,既有构造点不破坏);aggregate_invoices 取组内首行 warehouse_code(与 lot_no 同策略)。Task 4 的 resolve() 消费 AggregatedInvoice.warehouse_code。

  • Step 1: 写失败测试(parser)

backend/tests/services/in_transit_transfer/test_movement_parser.py 追加:

def test_movement_row_keeps_warehouse_code():
    """收料文件「仓库」列必须透传到解析行——inventory_match 源映射行匹配键的数据源头。"""
    parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows())
    assert parsed[0].warehouse_code == "DBS-TRANSIT"
  • Step 2: 写失败测试(aggregator)

backend/tests/services/in_transit_transfer/test_invoice_aggregator.py —— _row 助手(30-38 行)签名与返回 dict 增加 warehouse_code: str = "WMS-A" 参数与 "warehouse_code": warehouse_code 键,然后追加:

def test_aggregated_invoice_keeps_first_row_warehouse_code():
    """汇总发票取组内首行的仓库值(与 lot_no 同策略),供路由匹配使用。"""
    rows = [
        _row("INV-001", warehouse_code="WMS-A", row_no=10),
        _row("INV-001", warehouse_code="WMS-B", row_no=11),
    ]
    invoices = aggregate_invoices(_parsed(rows))
    # [断言意图] 同单多行仓库值不一致时取首行,保证路由匹配输入确定。
    assert invoices[0].warehouse_code == "WMS-A"
  • Step 3: 运行确认失败

Run: cd backend && python -m pytest tests/services/in_transit_transfer/test_movement_parser.py tests/services/in_transit_transfer/test_invoice_aggregator.py -q Expected: 新增 2 个用例 FAIL(AttributeError/断言失败:字段不存在)。

  • Step 4: 实现

file_parser.py —— ParsedReceiptRow(24-37 行)lot_no 之后加字段:

    lot_no: str = ""
    # 收料文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。
    warehouse_code: str = ""

_parse_rows 构造(181-192 行)lot_no=... 之后加:

            lot_no=str(row.get("lot_no") or "").strip(),
            warehouse_code=str(row.get("warehouse_code") or "").strip(),

同步更新模块 docstring 第 4 行「输出 ParsedReceiptRow」语义不变,但 parse_movement_rows docstring(72-77 行)中「warehouse_code、storage_code 透传/展示保留」改为「warehouse_code 透传至 ParsedReceiptRow.warehouse_code(路由匹配键);storage_code 仍仅展示保留」。

invoice_aggregator.py —— AggregatedInvoice(21-33 行)lot_no 之后加:

    lot_no: str = ""
    # 组内首行收料仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。
    warehouse_code: str = ""

aggregate_invoices(73-83 行)lot_no=first.lot_no, 之后加:

            lot_no=first.lot_no,
            warehouse_code=first.warehouse_code,
  • Step 5: 运行确认通过

Run: cd backend && python -m pytest tests/services/in_transit_transfer/test_movement_parser.py tests/services/in_transit_transfer/test_invoice_aggregator.py -q Expected: 全部 PASS。

  • Step 6: 暂存
git add backend/app/services/in_transit_transfer/file_parser.py backend/app/services/in_transit_transfer/invoice_aggregator.py backend/tests/services/in_transit_transfer/test_movement_parser.py backend/tests/services/in_transit_transfer/test_invoice_aggregator.py

Task 4: 路由解析改造与调用点贯通

Files:

  • Modify: backend/app/services/in_transit_transfer/deps.py:26-52(DefaultRouteResolver)
  • Modify: backend/app/services/in_transit_transfer/precheck_service.py:93-97(协议)、:325/336/367/383/399/411(DTO 构造)、:346(resolve 调用)、:535-549(持久化字段)、:628-640(恢复明细)
  • Modify: backend/app/services/in_transit_transfer/execution_service.py:190(resolve 调用)、:336-350(Run 结果 DTO)
  • Modify: backend/app/services/in_transit_transfer/retry_service.py:41(resolve 调用)
  • Modify: backend/app/services/in_transit_transfer/contracts.py:86-103(PrecheckInvoiceItemDTO)
  • Test: backend/tests/services/in_transit_transfer/test_route_resolver.py(整体重写)
  • Test: backend/tests/services/in_transit_transfer/repo_fakes.py:67-87(Fake 签名)

Interfaces:

  • Consumes: Task 2 的 in_transit_warehouse_code;Task 3 的 AggregatedInvoice.warehouse_code;Task 1 的 TransferInvoiceItem.receipt_warehouse_code。

  • Produces: RouteResolver.resolve(*, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping(协议级签名变更,三处生产调用点与测试 Fake 同步);from_warehouse 语义 = 映射行在途仓编码。PrecheckInvoiceItemDTO.receipt_warehouse_code: str = "" 新字段随既有 asdict 序列化进入 API 响应。

  • Step 1: 重写 resolver 测试(先失败)

backend/tests/services/in_transit_transfer/test_route_resolver.py 整文件替换为:

"""调拨路由解析器测试。

用途:验证 DefaultRouteResolver 的拨出库位与映射行选择契约——
      拨出库位 = 仓库映射的在途仓编码(必填),拨入仓库 = 映射的目标仓库代码;
      inventory_match 源优先按「收料文件仓库 == 货代仓库」精确匹配,
      匹配不到回退「货代仓库为空」的默认映射行(空库位兜底)。
依赖:app fixture 种子站点、ShippingInventoryExternalMapping、DefaultRouteResolver。
逻辑:fixed 源仅一条启用映射直接取用;任何映射行缺失或在途仓编码未维护 fail-closed。
"""

from __future__ import annotations

import pytest

from app.extensions import db
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.services.in_transit_transfer.deps import DefaultRouteResolver
from app.services.in_transit_transfer.precheck_service import RouteNotResolvedError


def _seed_mapping(
    source: ShippingInventorySource, *, freight_warehouse_id: str | None,
    in_transit_warehouse_code: str = 'TZT-01',
) -> ShippingInventoryExternalMapping:
    """在既有种子来源上挂一条启用映射。"""
    mapping = ShippingInventoryExternalMapping(
        inventory_source_id=source.id, freight_warehouse_id=freight_warehouse_id,
        external_system_code='TOPGP', external_organization_code='TGHX',
        external_warehouse_code='HUB-CN01', external_warehouse_name='HUB 仓',
        in_transit_warehouse_code=in_transit_warehouse_code, enabled=True,
    )
    db.session.add(mapping)
    db.session.commit()
    return mapping


def _seed_inventory_match_source() -> ShippingInventorySource:
    """以种子站点(fixed)的绑定配置为模板,新建 inventory_match 识别方式的来源。"""
    template = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
    source = ShippingInventorySource(
        source_code='DSV360_CRANE', display_name='Crane 测试源', connector_type='crane',
        rpa_profile_id=template.rpa_profile_id, parsing_profile_id=template.parsing_profile_id,
        excel_template_id=template.excel_template_id,
        warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None, enabled=True,
    )
    db.session.add(source)
    db.session.commit()
    return source


def test_fixed_source_uses_single_mapping_in_transit_code(app):
    """fixed 源仅一条启用映射:拨出库位取该行在途仓编码而非货代仓库/站点固定仓。"""
    with app.app_context():
        source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
        # 种子站点 fixed_warehouse_id='AWSDU';断言取映射在途仓 'TZT-01',证明拨出库位来自新字段。
        _seed_mapping(source, freight_warehouse_id='TZR2')

        route = DefaultRouteResolver().resolve(
            source_code='DSV360_AWSDU', invoice_no='INV-1', warehouse_code='')

        assert route.from_warehouse == 'TZT-01'
        assert route.to_warehouse == 'HUB-CN01'
        assert route.external_org == 'TGHX'


def test_inventory_match_prefers_receipt_warehouse_exact_mapping(app):
    """inventory_match 源:收料仓库与某行货代仓库精确匹配 → 取该行在途仓编码。"""
    with app.app_context():
        source = _seed_inventory_match_source()
        _seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='TZT-DEFAULT')
        _seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')

        route = DefaultRouteResolver().resolve(
            source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='wms-a')

        # [断言意图] 收料仓库小写传入也须命中大写归一的货代仓库身份。
        assert route.from_warehouse == 'TZT-A'
        assert route.to_warehouse == 'HUB-CN01'


def test_inventory_match_falls_back_to_empty_freight_mapping(app):
    """inventory_match 源:收料仓库无精确映射 → 回退货代仓库为空的默认映射行(空库位兜底)。"""
    with app.app_context():
        source = _seed_inventory_match_source()
        _seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='TZT-DEFAULT')
        _seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')

        route = DefaultRouteResolver().resolve(
            source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='WMS-UNKNOWN')

        assert route.from_warehouse == 'TZT-DEFAULT'


def test_inventory_match_blank_warehouse_goes_to_default_mapping(app):
    """inventory_match 源:收料文件仓库列缺失 → 直接走空库位默认映射行。"""
    with app.app_context():
        source = _seed_inventory_match_source()
        _seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='TZT-DEFAULT')
        _seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')

        route = DefaultRouteResolver().resolve(
            source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='')

        assert route.from_warehouse == 'TZT-DEFAULT'


def test_inventory_match_fails_closed_without_any_match(app):
    """inventory_match 源:无精确映射也无默认映射行 → fail-closed。"""
    with app.app_context():
        source = _seed_inventory_match_source()
        _seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')

        with pytest.raises(RouteNotResolvedError):
            DefaultRouteResolver().resolve(
                source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='WMS-UNKNOWN')


def test_route_resolver_fails_closed_without_in_transit_code(app):
    """映射未维护在途仓编码(存量空串)→ 拨出库位无来源,fail-closed。"""
    with app.app_context():
        source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
        _seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='')

        with pytest.raises(RouteNotResolvedError):
            DefaultRouteResolver().resolve(
                source_code='DSV360_AWSDU', invoice_no='INV-1', warehouse_code='')
  • Step 2: 更新测试 Fake 签名

backend/tests/services/in_transit_transfer/repo_fakes.py:78 —— FakeRouteResolver.resolve 签名改为(方法体不变):

    def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
  • Step 3: 运行确认失败

Run: cd backend && python -m pytest tests/services/in_transit_transfer/test_route_resolver.py -q Expected: FAIL —— 现实现取 freight_warehouse_id 且忽略 warehouse_code。

  • Step 4: 实现 DefaultRouteResolver

backend/app/services/in_transit_transfer/deps.py —— 类 docstring 与 resolve 整体替换:

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,
        )
  • Step 5: 运行 resolver 测试确认通过

Run: cd backend && python -m pytest tests/services/in_transit_transfer/test_route_resolver.py -q Expected: 6 个用例 PASS。

  • Step 6: 贯通协议、DTO、持久化与三处调用点

precheck_service.py:

  • 协议(93-97 行)签名改为:
    def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
        """返回 Invoice 的路由(warehouse_code 为收料文件仓库列,inventory_match 源匹配键);无法归属时抛 RouteNotResolvedError。"""
  • contracts.py PrecheckInvoiceItemDTO(86-103 行)lot_no 之后加字段:
    lot_no: str = ""
    # 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
    receipt_warehouse_code: str = ""
  • precheck_service.py 六处 PrecheckInvoiceItemDTO(...) 构造(325/336/367/383/399/411 行)各加一行 receipt_warehouse_code=invoice.warehouse_code or "",;
  • :346 resolve 调用改为:
        route = deps.route_resolver.resolve(
            source_code=source_code, invoice_no=invoice.invoice_no,
            warehouse_code=invoice.warehouse_code or "",
        )
  • create_precheck 持久化 fields dict(535-549 行)加:
            "receipt_warehouse_code": item.receipt_warehouse_code or "",
  • get_precheck_detail 明细 DTO(628-640 行)加 receipt_warehouse_code=item.receipt_warehouse_code or "",。

execution_service.py:

  • :190 改为:
    route = deps.route_resolver.resolve(
        source_code=item.source_code, invoice_no=item.invoice_no,
        warehouse_code=item.receipt_warehouse_code or "",
    )
  • _build_run_result(336-350 行)DTO 构造加 receipt_warehouse_code=item.receipt_warehouse_code or "",。

retry_service.py :41 改为:

    route = deps.route_resolver.resolve(
        source_code=item.source_code, invoice_no=item.invoice_no,
        warehouse_code=item.receipt_warehouse_code or "",
    )
  • Step 7: 跑整个在途调拨套件并修复夹具级联

Run: cd backend && python -m pytest tests/services/in_transit_transfer tests/api/test_in_transit_transfer_api.py tests/jobs/test_in_transit_transfer_jobs.py -q Expected: 全部 PASS。若有失败:优先检查断言 from_warehouse 的夹具(预检/执行/重试测试用 FakeRouteResolver,路由值由 Fake 提供,不受实现影响);test_precheck_service.py 若断言持久化字段集合,按新增 receipt_warehouse_code 补断言,不删除既有断言。

  • Step 8: 暂存
git add backend/app/services/in_transit_transfer/ backend/tests/services/in_transit_transfer/

Task 5: 前端表单与 i18n 四语言

Files:

  • Modify: frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue:348-355,666,982,1042
  • Modify: frontend/src/locales/zh-CN/admin.json:975,1188-1189、frontend/src/locales/en/admin.json:846,1059-1060、frontend/src/locales/zh-TW/admin.json:846,1059-1060、frontend/src/locales/th/admin.json:846,1059-1060

Interfaces:

  • Consumes: Task 2 payload 新增键 in_transit_warehouse_code(GET 列表回填 + POST/PUT 提交)。

  • Produces: 表单字段顺序 库存源 → 货代仓库(选填) → 目标系统 → 目标组织 → 目标地点 → 在途仓编码(必填) → 目标仓库编码 → 目标仓库名称 → 启用;两列网格下目标仓库编码与目标仓库名称同行且编码在前。

  • Step 1: 模板改造(348-355 行)

349 行去掉 required;352 行(目标地点)与 353 行(目标仓库编码)之间插入新字段。结果片段:

              <label><span>{{ t('admin.shippingInventory.freightWarehouse') }}</span><input v-model="mapping.freight_warehouse_id" class="input-field"></label>
              <label><span>{{ t('admin.shippingInventory.externalSystem') }}</span><input v-model="mapping.external_system_code" class="input-field" required></label>
              <label><span>{{ t('admin.shippingInventory.externalOrganization') }}</span><input v-model="mapping.external_organization_code" class="input-field"></label>
              <label><span>{{ t('admin.shippingInventory.externalSite') }}</span><input v-model="mapping.external_site_code" class="input-field"></label>
              <label><span>{{ t('admin.shippingInventory.inTransitWarehouseCode') }}</span><input v-model="mapping.in_transit_warehouse_code" class="input-field" required></label>
              <label><span>{{ t('admin.shippingInventory.externalWarehouseCode') }}</span><input v-model="mapping.external_warehouse_code" class="input-field" required></label>
              <label><span>{{ t('admin.shippingInventory.externalWarehouseName') }}</span><input v-model="mapping.external_warehouse_name" class="input-field" required></label>

(首行库存源 select 与末行启用 switch 不变。)

  • Step 2: 表单状态四处同步

  • :666 reactive 声明加 in_transit_warehouse_code: ''(置于 external_site_code 之后):

const mapping = reactive({ inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', in_transit_warehouse_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
  • :982 createNew 的 mappings 重置同步加 in_transit_warehouse_code: '';
  • :1042 selectItem 同步加 in_transit_warehouse_code: item.in_transit_warehouse_code || '':
  if (activeTab.value === 'mappings') Object.assign(mapping, { ...item, freight_warehouse_id: item.freight_warehouse_id || '', external_organization_code: item.external_organization_code || '', external_site_code: item.external_site_code || '', in_transit_warehouse_code: item.in_transit_warehouse_code || '' });
  • :1228 saveCurrent 无需改动(...mapping 展开已携带新键;freight_warehouse_id: mapping.freight_warehouse_id || null 恰好实现选填语义)。

  • Step 3: i18n 四语言补 key

各语言 admin.json 的 externalWarehouseName 行后新增 "inTransitWarehouseCode",并整体替换 mappingsHelp(语义已变:货代仓库选填、新增在途仓编码):

文件 新增 key 与值 mappingsHelp 替换值
zh-CN/admin.json "inTransitWarehouseCode": "在途仓编码", "将库存源映射到外部系统仓库编码与在途仓编码;货代仓库可空,作为按收料仓库匹配映射行的键。"
zh-TW/admin.json "inTransitWarehouseCode": "在途倉編碼", "將庫存來源對應至外部系統倉庫編碼與在途倉編碼;貨代倉庫可為空,作為按收料倉庫匹配映射列的鍵。"
en/admin.json "inTransitWarehouseCode": "In-transit warehouse code", "Map an inventory source to external system warehouse and in-transit warehouse codes; freight warehouse is optional and used as the receipt-warehouse matching key."
th/admin.json "inTransitWarehouseCode": "รหัสคลังระหว่างทาง", "แมปแหล่งสินค้าคงคลังไปยังรหัสคลังปลายทางและรหัสคลังระหว่างทางของระบบภายนอก คลังผู้ให้บริการเป็นทางเลือกและใช้เป็นคีย์จับคู่คลังรับสินค้า"
  • Step 4: 构建验证

Run: cd frontend && npm run build Expected: 构建成功,无 TS/模板错误。

  • Step 5: 暂存
git add frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue frontend/src/locales/

Task 6: 文档同步与全量验证

Files:

  • Modify: docs/features/in-transit-transfer/technical.md(路由解析章节)
  • Modify: docs/features/shipping-notice/technical.md:3429-3430(映射主数据描述)
  • Modify: docs/features/shipping-notice/inventory_source_plan.md:123-145(映射字段清单)
  • Modify: docs/funclist.md(若存在仓库映射/在途调拨条目)
  • Modify: backend/app/api/admin/shipping_inventory.py(仅文件层 docstring 如提及字段清单则同步;无则跳过)

Interfaces:

  • Consumes: Task 1-5 的最终行为。

  • Produces: 文档与代码一致(AGENTS.md §9 红线)。

  • Step 1: 在途调拨技术手册更新

docs/features/in-transit-transfer/technical.md 中检索「拨出库位 / from_warehouse / 货代仓库」的路由解析段落,把「拨出库位 = 映射行货代仓库」口径整体替换为:

拨出库位取仓库映射行的「在途仓编码」(in_transit_warehouse_code,保存端必填)。映射行按库存源 warehouse_resolution_mode 选择:inventory_match(按库存行匹配)源优先按「库存源 + 收料文件仓库列(warehouse_code)== 货代仓库」精确匹配,匹配不到回退「库存源 + 货代仓库为空」的默认映射行(空库位兜底);fixed(指定仓库)源仅一条启用映射直接取用。收料文件仓库列原值随明细落库于 transfer_invoice_items.receipt_warehouse_code,执行/重试期重解析以它为匹配键,路由变化仍 fail-closed 阻断。映射行缺失或在途仓编码未维护时维持 TRANSFER.ROUTE_NOT_RESOLVED。运维注意:来源的 movement 解析方案须把收料文件「仓库」表头映射到领域字段 warehouse_code,未映射时该值为空、inventory_match 源将直接走空库位兜底。

  • Step 2: shipping-notice 技术手册更新

docs/features/shipping-notice/technical.md:3430 「外部系统仓库映射保存在 …」段落,替换/追加为:

外部系统仓库映射保存在 shipping_inventory_external_mappings:货代仓库(freight_warehouse_id)为可选维度(inventory_match 源按收料仓库匹配的键,空值即默认映射行),在途仓编码(in_transit_warehouse_code)为在途调拨拨出库位来源(保存端必填);发货链路仍按 source + warehouse 精确优先、Source 默认映射兜底查询,调拨链路口径见 docs/features/in-transit-transfer/technical.md。

  • Step 3: inventory_source_plan 字段清单更新

docs/features/shipping-notice/inventory_source_plan.md:123-145 映射字段清单中:freight_warehouse_id 标注「可选」,并在其后追加一行 in_transit_warehouse_code(在途仓编码,必填):在途调拨拨出库位来源。

  • Step 4: 功能清单核对

Run: grep -n "在途调拨\|仓库映射\|external_mapping" docs/funclist.md 若有对应条目:在条目描述中补「映射支持在途仓编码(拨出库位来源),货代仓库选填(按收料仓库匹配映射行)」。若无条目:不改(本需求为既有功能的字段级调整,不新增功能项)。

  • Step 5: 全量回归

Run: cd backend && python -m pytest tests/services/in_transit_transfer tests/services/admin/test_shipping_inventory_service.py tests/api/test_in_transit_transfer_api.py tests/jobs/test_in_transit_transfer_jobs.py -q Run: cd frontend && npm run build Expected: 后端全部 PASS、前端构建成功。

  • Step 6: 暂存
git add docs/features/in-transit-transfer/technical.md docs/features/shipping-notice/technical.md docs/features/shipping-notice/inventory_source_plan.md docs/funclist.md

Self-Review 记录

  • 规格覆盖:需求①②→ Task 5(一次插入同时实现「在途仓编码占原位 + 目标仓库编码落到目标仓库名称前」);需求③→ Task 2 + Task 5;需求④→ Task 1(迁移)+ Task 3(仓库值贯通)+ Task 4(解析与调用点)+ Task 6(文档)。
  • 类型一致性:in_transit_warehouse_code(映射表)、receipt_warehouse_code(明细表/DTO)、warehouse_code(解析 DTO/resolve 入参)三层命名已统一并在 Interfaces 块声明;resolve() 协议签名在协议、实现、Fake、三处调用点保持一致。
  • 已知边界:站点启用就绪检查(_enabled_external_mapping_exists)不要求在途仓编码,本计划不改(需求未涉及);resolve 的 invoice_no 参数保留但当前不参与匹配(协议兼容,注释已说明)。