Files
syops/docs/superpowers/plans/2026-10-13-shipping-inventory-candidates-refresh.md
T
hugo ea94fb28db feat(shipping-notice): 人工重取库存前置候选刷新并放开行级库存源下拉
- 人工重试库存准备前置幂等重判:任务级整单重路由、行级定向重评目标行,复用裁决与冻结链路,零新动作码零契约变更
- 新版候选集 supersede 时内置失效旧库存事实,导出归档与查询服务同步适配
- 行级「库存源」下拉抽纯函数合并选项:歧义行候选置顶 + 全部已启用源去重兜底,任一已启用源可人工指定
- 库存源门禁归一 Notice→OT 身份解析;任务中心抽屉与表格接入行级重取入口
- 同步四语言文案、技术文档与实施计划
2026-10-13 15:04:40 +08:00

53 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: 让「重新获取库存(RPA)」的任务级与行级人工重取前,按当前主数据幂等重判候选库存源(任务级整单重路由;行级仅重评目标行),并放开前端歧义行库存源下拉到全部已启用源。

Architecture: 零新动作码、零契约变更、零 UI 按钮变更。后端在 _handle_retry_inventory_preparation 人工重试分支插入前置刷新:任务级走 refresh_candidates_from_current_routing(复用 adjudicate_and_apply_inventory_source + freeze 幂等);行级走 refresh_line_candidates_from_current_routing(行级规则重评 + 以活动集为骨架定向替换目标行后 freeze_candidates_for_task 冻结,created_new 判变化)。两者共用三条守卫红线;新版候选集 supersede 时由 _invalidate_task_candidate_outputs 内置失效旧库存事实。前端把行级下拉选项抽为纯函数 mergeInlineSourceOptions(候选置顶 + 全量源去重兜底)。

Tech Stack: Flask + SQLAlchemy(backend/app/services/shipping_notice)、Vue 3 + TS + Vitest(frontend/src/features/chat)。

Spec: 会话内已确认的「升级不换按钮 + 任务级/行级都刷新」方案(2026-10-13 诊断与设计,要点见 Global Constraints;诊断结论另存于 .engramory-memory/shipping-source-selection-impl.md)。

Global Constraints

  • 零新动作码:不改 process_gate_contract 动作清单、不下发新 capability、前端不新增按钮。
  • 刷新只是显式人工重取的伴随前置:仅 retry_inventory_preparation 触发——任务级(line_scope 为空)整单刷新;行级(line_scope 非空)仅刷新目标行。poll_inventory_preparation(只读轮询)、自动首投(trigger=='gate_attempt_passed')、retry_inventory_from_preparation(恢复流变体)一律不刷新。
  • 守卫红线(任务级与行级同源):① 已定源不自动改源——任务级冻结候选 ≤1 不刷新,行级该行候选 ≤1 不刷新;换源走 override_line_inventory_source 行级覆写;② 活动候选集含人工选源(frozen_by_id 非空或 candidate_origin=='manual_override')不刷新——人工指定即定论;③ Excel 已生成(latest_export_artifact 非空,D7 锁定边界)不刷新。
  • 幂等:输入指纹未变时 freeze_candidates_for_task 复用旧集(created_new=False),刷新返回 False、零副作用;主数据有变但路由结论未变时会产生新版集(配置版本进入指纹),此时用户本就在显式重取,失效重取符合预期,重复点击收敛。
  • 行级候选必须过滤可用性:InventoryRoutingResult.source_codes 为规则原始候选(未做启停过滤),入候选集前必须经 get_database_inventory_source 校验(对齐 _result_to_adjudication 语义)。
  • 不改 models.py,无数据库迁移(候选集天然支持 set_version 多版本)。
  • 不动既有边界:inventory_candidate_freeze_service.py 中已有的 #region debug-point A/C/E 调试代码块保持原样不要删除(边界外事项,另行处理)。
  • i18n 四语言(zh-CN / zh-TW / en / th)同步;禁止硬编码文案。
  • 注释遵循 AGENTS §5:文件层三要素 + 函数层 docstring/JSDoc;业务步骤用 [STEP n];禁止逐行翻译代码。
  • 禁止自动 commit:每个任务以 git add <具体文件> 收尾,提交由用户显式决定。
  • 后端测试命令:cd backend && .\.venv\Scripts\python.exe -m pytest tests/<file> -q;前端验证:cd frontend && npx vitest run <file> + 最终 npm run build 必须通过。

Task 1: 后端刷新 helper(freeze service 内新增,任务级+行级)

Files:

  • Modify: backend/app/services/shipping_notice/inventory_candidate_freeze_service.py(在 freeze_manual_line_source_selection 之后追加三个函数)
  • Test: backend/tests/test_shipping_refresh_inventory_candidates.py(新建)

Interfaces:

  • Consumes: adjudicate_and_apply_inventory_source(task, *, execution_id=None)(inventory_source_gate.py:121);get_active_candidate_set(task)(inventory_candidate_projection.py);task_frozen_inventory_source_codes(task)(stp_inventory_freeze.py:186);evaluate_inventory_source_rules(*, task, line=None) / _task_routing_lines(task) / extract_routing_context / compute_routing_fingerprint(inventory_source_rules.py,重导出自 routing_engine);get_database_inventory_source / inventory_sources_runtime_version(inventory_source_repository.py);log_task_event(tool_common.py);同模块 freeze_candidates_for_task。

  • Produces:

    • active_candidate_set_is_manually_pinned(task, *, session=None) -> bool
    • refresh_candidates_from_current_routing(task, *, execution_id=None, session=None) -> bool(任务级,True=产生新版候选集)
    • refresh_line_candidates_from_current_routing(task, *, line_no: int, execution_id=None, session=None) -> bool(行级,True=产生新版候选集)
    • 任务事件 inventory_candidates_refreshed(payload 含 scope: 'task'|'line')。
  • Step 1: 写失败测试(新建测试文件)

"""
tests/test_shipping_refresh_inventory_candidates.py

用途:人工重取前的候选集刷新守卫与幂等语义——任务级整单重路由、行级单行重评,
      未定源才刷新;人工钉源/已定源/无变化场景一律跳过或零副作用。
依赖:inventory_candidate_freeze_service(被测 helper)、inventory_source_gate 与
      inventory_source_rules(重裁决/重评入口,测试中 monkeypatch 隔离)、
      process_gate_executor(Task 2 的挂载点集成测试)。
逻辑:任务级守卫(多候选、非人工钉源)+ 幂等判定(活动 set_id 变化);行级守卫
      (目标行多候选、非人工钉源)+ 行级规则重评 + 定向行替换冻结;执行器仅在
      人工 retry(任务级/行级)且非 Excel 锁定时调用对应 helper。
"""

from __future__ import annotations

from types import SimpleNamespace

import pytest


def _task(set_id=10):
    """构造最小 OT 形状:仅 helper/执行器读取的字段。"""
    return SimpleNamespace(
        id=19, task_no='SN-REFRESH',
        order_snapshot_id=3,
        active_inventory_candidate_set_id=set_id,
        step_payload_json={},
    )


def _active_set(line_defs):
    """构造最小活动候选集:lines 为 (line_no, codes) 列表。"""
    return SimpleNamespace(
        id=10, frozen_by_id=None, sources=[],
        lines=[
            SimpleNamespace(
                line_no=line_no, source_codes_json=list(codes),
                source_line_no=str(line_no), part_number=f'PN{line_no}', reservation_id=f'R{line_no}',
            )
            for line_no, codes in line_defs
        ],
    )


def _patch_routing_common(monkeypatch, *, fingerprint='fp-test', config_version='cfg-test'):
    """隔离路由上下文与配置版本(避免测试依赖真实库表与指纹算法)。"""
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_rules.extract_routing_context',
        lambda _task: {'customer': 'X'},
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_rules.compute_routing_fingerprint',
        lambda _ctx: fingerprint,
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_repository.inventory_sources_runtime_version',
        lambda: config_version,
    )


# ---------- 任务级刷新 ----------

def test_refresh_skips_when_single_source_resolved(app, monkeypatch):
    """[断言] 守卫:源已定(冻结候选 ≤1)不重路由——换源只能走行级覆写,禁止自动改源。"""
    from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service

    task = _task()
    monkeypatch.setattr(
        'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
        lambda _task: ['DSV360_AWSDU'],
    )
    called = []
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
        lambda _task, **_k: called.append(1),
    )
    assert freeze_service.refresh_candidates_from_current_routing(task) is False
    assert not called


def test_refresh_skips_when_manual_selection_exists(app, monkeypatch):
    """[断言] 守卫:人工选源即定论,重取不得洗掉人工裁决。"""
    from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service

    task = _task()
    monkeypatch.setattr(
        'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
        lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'],
    )
    monkeypatch.setattr(
        freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: True,
    )
    called = []
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
        lambda _task, **_k: called.append(1),
    )
    assert freeze_service.refresh_candidates_from_current_routing(task) is False
    assert not called


def test_refresh_returns_true_and_logs_event_when_set_changes(app, monkeypatch):
    """[断言] 重裁决产生新版本:返回 True 并写 inventory_candidates_refreshed 任务事件(scope=task)。"""
    from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service

    task = _task(set_id=10)
    monkeypatch.setattr(
        'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
        lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'],
    )
    monkeypatch.setattr(
        freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: False,
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
        lambda _task: SimpleNamespace(id=task.active_inventory_candidate_set_id),
    )

    def _fake_readjudicate(_task, **_k):
        task.active_inventory_candidate_set_id = 11

    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
        _fake_readjudicate,
    )
    events = []
    monkeypatch.setattr(
        'app.services.shipping_notice.tool_common.log_task_event',
        lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
    )
    assert freeze_service.refresh_candidates_from_current_routing(task, execution_id=5) is True
    assert events and events[0][0] == 'inventory_candidates_refreshed'
    assert events[0][1]['scope'] == 'task'
    assert events[0][1]['previous_set_id'] == 10
    assert events[0][1]['new_set_id'] == 11


def test_refresh_is_noop_when_routing_result_identical(app, monkeypatch):
    """[断言] 幂等:重裁决输入指纹未变(复用旧集,set_id 不变)时返回 False,不写事件。"""
    from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service

    task = _task(set_id=10)
    monkeypatch.setattr(
        'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
        lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'],
    )
    monkeypatch.setattr(
        freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: False,
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
        lambda _task: SimpleNamespace(id=task.active_inventory_candidate_set_id),
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
        lambda _task, **_k: None,
    )
    events = []
    monkeypatch.setattr(
        'app.services.shipping_notice.tool_common.log_task_event',
        lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
    )
    assert freeze_service.refresh_candidates_from_current_routing(task) is False
    assert not events


# ---------- 行级刷新 ----------

def test_line_refresh_skips_when_target_line_single_source(app, monkeypatch):
    """[断言] 守卫:目标行候选 ≤1(已定源)不重评——改源走行级覆写。"""
    from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service

    task = _task()
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
        lambda _task: _active_set([(1, ['DSV360_AWSDU'])]),
    )
    called = []
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
        lambda **_k: called.append(1),
    )
    assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
    assert not called


def test_line_refresh_skips_when_manual_selection_exists(app, monkeypatch):
    """[断言] 守卫:候选集含人工选源即定论,行级重取不得洗掉人工裁决。"""
    from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service

    task = _task()
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
        lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
    )
    monkeypatch.setattr(
        freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: True,
    )
    called = []
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
        lambda **_k: called.append(1),
    )
    assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
    assert not called


def test_line_refresh_skips_when_routing_unresolved(app, monkeypatch):
    """[断言] 行级规则重评为 unresolved(或候选全部停用)时保持旧行为,不冻结不刷新。"""
    from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service

    task = _task()
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
        lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
        lambda _task, **_k: [{'part_number': 'PN1'}],
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
        lambda **_k: SimpleNamespace(status='unresolved', source_codes=()),
    )
    freeze_called = []
    monkeypatch.setattr(
        freeze_service, 'freeze_candidates_for_task',
        lambda *_a, **_k: freeze_called.append(1),
    )
    assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
    assert not freeze_called


def test_line_refresh_skips_when_routed_sources_all_disabled(app, monkeypatch):
    """[断言] 规则原始候选未过滤启停(InventoryRoutingResult 契约):候选全部停用时不得入集,保持旧行为。"""
    from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service

    task = _task()
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
        lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
        lambda _task, **_k: [{'part_number': 'PN1'}],
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
        lambda **_k: SimpleNamespace(status='resolved', source_codes=('DSV360_AWSDU',)),
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
        lambda code, **_k: None,
    )
    freeze_called = []
    monkeypatch.setattr(
        freeze_service, 'freeze_candidates_for_task',
        lambda *_a, **_k: freeze_called.append(1),
    )
    assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
    assert not freeze_called


def test_line_refresh_freezes_new_version_when_routing_changes(app, monkeypatch):
    """[断言] 行级重评产生新候选:目标行替换、其余行继承,新版本冻结返回 True 并写行级刷新事件。"""
    from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service

    task = _task()
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
        lambda _task: _active_set([
            (1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01']),
            (2, ['DSV360_AWSCV']),
        ]),
    )
    _patch_routing_common(monkeypatch)
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
        lambda _task, **_k: [{'part_number': 'PN1'}, {'part_number': 'PN2'}],
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
        lambda **_k: SimpleNamespace(status='ambiguous', source_codes=('DSV360_AWSDU', 'DSV360_AWSCV')),
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
        lambda code, **_k: {'source_code': code},
    )
    freeze_kwargs = []
    monkeypatch.setattr(
        freeze_service, 'freeze_candidates_for_task',
        lambda _task, **_k: freeze_kwargs.append(dict(_k)) or SimpleNamespace(created_new=True, candidate_set_id=12),
    )
    events = []
    monkeypatch.setattr(
        'app.services.shipping_notice.tool_common.log_task_event',
        lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
    )
    assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1, execution_id=5) is True
    projections = freeze_kwargs[0]['line_projections']
    assert projections[0]['line_no'] == 1
    assert projections[0]['candidate_inventory_source_codes'] == ['DSV360_AWSDU', 'DSV360_AWSCV']
    assert projections[1]['line_no'] == 2
    assert projections[1]['candidate_inventory_source_codes'] == ['DSV360_AWSCV']
    assert events and events[0][0] == 'inventory_candidates_refreshed'
    assert events[0][1]['scope'] == 'line'
    assert events[0][1]['line_no'] == 1
    assert events[0][1]['new_codes'] == ['DSV360_AWSDU', 'DSV360_AWSCV']


def test_line_refresh_is_noop_when_fingerprint_identical(app, monkeypatch):
    """[断言] 幂等:行级重评结论与现状一致(冻结复用旧集 created_new=False)时返回 False,不写事件。"""
    from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service

    task = _task()
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
        lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
    )
    _patch_routing_common(monkeypatch)
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
        lambda _task, **_k: [{'part_number': 'PN1'}],
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
        lambda **_k: SimpleNamespace(status='ambiguous', source_codes=('DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01')),
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
        lambda code, **_k: {'source_code': code},
    )
    monkeypatch.setattr(
        freeze_service, 'freeze_candidates_for_task',
        lambda _task, **_k: SimpleNamespace(created_new=False, candidate_set_id=10),
    )
    events = []
    monkeypatch.setattr(
        'app.services.shipping_notice.tool_common.log_task_event',
        lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
    )
    assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
    assert not events
  • Step 2: 运行测试确认失败

Run: cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_shipping_refresh_inventory_candidates.py -q Expected: FAIL(AttributeError: ... has no attribute 'refresh_candidates_from_current_routing' 等)

  • Step 3: 实现 helper(追加到 freeze_manual_line_source_selection 之后)
def active_candidate_set_is_manually_pinned(
    task: ShippingNotice,
    *,
    session: Session | None = None,
) -> bool:
    """
    判断活动候选集是否含人工选源(「人工指定即定论」的统一判定入口)。

    Args:
        task: 当前 ShippingOrderTask。
        session: 可选 Session。

    Returns:
        bool: True 表示人工已裁决候选源,自动重路由必须跳过。
    """
    sess = session or db.session
    active_set = (
        sess.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
        if getattr(task, 'active_inventory_candidate_set_id', None) is not None
        else None
    )
    if active_set is None:
        return False
    if getattr(active_set, 'frozen_by_id', None) is not None:
        return True
    return any(
        str(getattr(source, 'candidate_origin', '') or '').strip().lower() == 'manual_override'
        for source in (active_set.sources or [])
    )


def refresh_candidates_from_current_routing(
    task: ShippingNotice,
    *,
    execution_id: int | None = None,
    session: Session | None = None,
) -> bool:
    """
    任务级:按当前库存源主数据与路由规则重跑裁决并重冻结候选集;返回是否产生新版本候选集。
    【AI 触发时机】:仅「重新获取库存(RPA)」的任务级人工重取路径作为前置步骤调用;
    禁止在轮询(poll)、自动首投路径调用——刷新是显式人工动作的伴随效果,不是隐式自动行为。

    核心逻辑:
    [守卫 1] 仅多候选未定源可刷新(task_frozen_inventory_source_codes > 1);源已定单
      不得自动改源,换源走 override_line_inventory_source 行级覆写。
    [守卫 2] 活动候选集含人工选源(frozen_by_id / candidate_origin='manual_override')
      时跳过:人工指定即定论,禁止重路由洗掉人工裁决。
    [STEP 1] 记录当前活动 set_id。
    [STEP 2] adjudicate_and_apply_inventory_source(execution_id=...) 重裁决 + 幂等冻结
      (freeze 服务 input_fingerprint 未变则复用旧集,零副作用;重裁决为 unresolved 时
      apply 不落任何事实,活动集保持不变,同样视为无变化)。
    [STEP 3] 活动集变化时冻结服务已内置旧版本下游失效(_invalidate_task_candidate_outputs:
      匹配事实/准备 Attempt/RPA Attempt 等),此处仅补写任务事件供审计追溯。

    Args:
        task: 当前 ShippingOrderTask(须已冻结候选集)。
        execution_id: 当前 ProcessExecution id;透传冻结服务,避免重冻结撤销活动执行链。
        session: 可选 Session。

    Returns:
        bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。
    """
    from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
    from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source
    from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes

    sess = session or db.session
    if len(task_frozen_inventory_source_codes(task)) <= 1:
        return False
    if active_candidate_set_is_manually_pinned(task, session=sess):
        return False
    before = get_active_candidate_set(task)
    before_set_id = int(before.id) if before is not None else None
    adjudicate_and_apply_inventory_source(task, execution_id=execution_id)
    sess.flush()
    after = get_active_candidate_set(task)
    after_set_id = int(after.id) if after is not None else None
    if before_set_id == after_set_id:
        return False
    from app.services.shipping_notice.tool_common import log_task_event

    log_task_event(
        task,
        'inventory_candidates_refreshed',
        {
            'scope': 'task',
            'previous_set_id': before_set_id,
            'new_set_id': after_set_id,
            'source_codes': task_frozen_inventory_source_codes(task),
        },
        source='system',
    )
    return True


def refresh_line_candidates_from_current_routing(
    task: ShippingNotice,
    *,
    line_no: int,
    execution_id: int | None = None,
    session: Session | None = None,
) -> bool:
    """
    行级:按当前库存源主数据与路由规则重评单个订单行的候选源并重冻结候选集;返回是否产生新版本。
    【AI 触发时机】:仅「重新获取库存(RPA)」的行级重抓(retry_inventory_preparation 携带
    line_scope)作为前置步骤调用;禁止在轮询/自动首投路径调用。

    核心逻辑:
    [守卫 1] 目标行当前候选 >1(未定源)才重评;单源行已定,改源走行级覆写。
    [守卫 2] 活动候选集含人工选源时跳过(与任务级刷新同一条红线:人工指定即定论)。
    [STEP 1] 行级规则重评:_task_routing_lines(task) 按 line_no-1 取目标行(越界返回 False),
      evaluate_inventory_source_rules(task=task, line=...) 得到规则原始候选,经
      get_database_inventory_source 过滤停用源(对齐 _result_to_adjudication 语义);
      仅接受 resolved/ambiguous 结论,unresolved 保持旧行为不刷新。
    [STEP 2] 以活动集全量行为骨架构建 line_projections:目标行替换为新候选,其余行原样继承
      (保留既有行候选,不做整单重路由)。
    [STEP 3] freeze_candidates_for_task(candidates_frozen 裁决)幂等冻结;created_new 即新版
      候选集(supersede 旧集时内置下游失效),写行级刷新任务事件并返回 True。

    Args:
        task: 当前 ShippingOrderTask(须已冻结候选集)。
        line_no: 目标订单项次(1 基,对应冻结快照 line_no)。
        execution_id: 当前 ProcessExecution id;透传冻结服务,避免重冻结撤销活动执行链。
        session: 可选 Session。

    Returns:
        bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。
    """
    from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
    from app.services.shipping_notice.inventory_source_repository import (
        get_database_inventory_source,
        inventory_sources_runtime_version,
    )
    from app.services.shipping_notice.inventory_source_rules import (
        _task_routing_lines,
        compute_routing_fingerprint,
        evaluate_inventory_source_rules,
        extract_routing_context,
    )

    sess = session or db.session
    active_set = get_active_candidate_set(task)
    if active_set is None:
        return False
    if active_candidate_set_is_manually_pinned(task, session=sess):
        return False
    existing_lines = {
        int(row.line_no): row
        for row in (active_set.lines or [])
        if getattr(row, 'line_no', None) is not None
    }
    target = existing_lines.get(int(line_no))
    if target is None:
        return False
    current_codes = [
        str(code).strip().upper()
        for code in (target.source_codes_json or [])
        if str(code or '').strip()
    ]
    if len(current_codes) <= 1:
        return False

    routing_lines = _task_routing_lines(task)
    position = int(line_no) - 1
    if position < 0 or position >= len(routing_lines):
        return False
    line_result = evaluate_inventory_source_rules(task=task, line=routing_lines[position])
    line_status = str(getattr(line_result, 'status', '') or '').strip().lower()
    if line_status not in {'resolved', 'ambiguous'}:
        return False
    new_codes: list[str] = []
    for raw in (getattr(line_result, 'source_codes', None) or []):
        code = str(raw or '').strip().upper()
        if code and code not in new_codes and get_database_inventory_source(code) is not None:
            new_codes.append(code)
    if not new_codes:
        return False

    line_projections: list[dict[str, Any]] = []
    union_codes: list[str] = []
    for row_line_no in sorted(existing_lines):
        row = existing_lines[row_line_no]
        codes = (
            new_codes
            if row_line_no == int(line_no)
            else [
                str(code).strip().upper()
                for code in (row.source_codes_json or [])
                if str(code or '').strip()
            ]
        )
        for code in codes:
            if code not in union_codes:
                union_codes.append(code)
        line_projections.append({
            'line_no': row_line_no,
            'source_line_no': str(getattr(row, 'source_line_no', '') or '') or None,
            'part_number': getattr(row, 'part_number', None),
            'reservation_id': getattr(row, 'reservation_id', None),
            'candidate_inventory_source_codes': codes,
        })
    if not union_codes:
        return False

    context = extract_routing_context(task)
    adjudication = InventorySourceAdjudication(
        status='candidates_frozen',
        method='line_refresh_reroute',
        source_code=None,
        connector_type=None,
        warehouse_id=None,
        config_version=inventory_sources_runtime_version(),
        routing_fingerprint=compute_routing_fingerprint(context),
        candidates=[{'source_code': code} for code in union_codes],
        evidence=[{
            'line_candidates_refresh': {
                'line_no': int(line_no),
                'previous_codes': current_codes,
                'new_codes': new_codes,
            },
        }],
        reason='line_refresh_reroute',
    )
    freeze_result = freeze_candidates_for_task(
        task,
        adjudication=adjudication,
        line_projections=line_projections,
        execution_id=execution_id,
        session=sess,
    )
    if not freeze_result.created_new:
        return False
    from app.services.shipping_notice.tool_common import log_task_event

    log_task_event(
        task,
        'inventory_candidates_refreshed',
        {
            'scope': 'line',
            'line_no': int(line_no),
            'previous_codes': current_codes,
            'new_codes': new_codes,
            'new_set_id': int(freeze_result.candidate_set_id),
        },
        source='system',
    )
    return True
  • Step 4: 运行测试确认通过

Run: cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_shipping_refresh_inventory_candidates.py -q Expected: PASS(10 passed)

  • Step 5: 暂存
git add backend/app/services/shipping_notice/inventory_candidate_freeze_service.py backend/tests/test_shipping_refresh_inventory_candidates.py

Task 2: 执行器前置步骤(任务级+行级挂载)

Files:

  • Modify: backend/app/services/shipping_notice/process_gate_executor.py(_handle_retry_inventory_preparation 内,约 928-952 行的 if task is not None and payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch: 块内、invalidate_inventory_downstream(...) 调用之前插入)
  • Test: backend/tests/test_shipping_refresh_inventory_candidates.py(追加集成用例)

Interfaces:

  • Consumes: Task 1 的 refresh_candidates_from_current_routing(task, *, execution_id=None) 与 refresh_line_candidates_from_current_routing(task, *, line_no, execution_id=None);latest_export_artifact(task)(upload_attempt_service.py);line_scope['line_no'](executor 内 _resolve_line_inventory_scope 产物,含 snapshot_line_id/line_no/source_codes)。

  • Produces: 无新接口(行为变更:人工重取——任务级先整单刷新、行级先刷新目标行——再走既有失效 + ensure_inventory(mode='retry_rpa') 重取链)。

  • Step 1: 追加失败测试(同测试文件末尾)

def _retry_payload(**overrides):
    base = {'action_code': 'retry_inventory_preparation', 'actor_user_id': 7}
    base.update(overrides)
    return base


def _exercise_retry_handler(monkeypatch, task, payload, *, refresh_calls, line_scope=None, excel_artifact=None):
    """按既有 override 测试模式直调重取处理器:隔离重路由、失效、准备轮次与 ensure_inventory。

    refresh_calls 记录 ('task'|'line', kwargs),用于断言挂载路径与透传参数。
    """
    from app.services.shipping_notice import process_gate_executor as executor

    execution = SimpleNamespace(id=5, task_id=int(task.id), candidate_set_id=None)
    gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout')
    monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task)
    monkeypatch.setattr(executor, '_resolve_line_inventory_scope', lambda _task, **_k: line_scope)
    monkeypatch.setattr(executor, '_task_payload', lambda _execution, _payload: {'task_id': task.task_no})
    monkeypatch.setattr(
        'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
        lambda _task: excel_artifact,
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_candidate_freeze_service.refresh_candidates_from_current_routing',
        lambda _task, **_k: refresh_calls.append(('task', dict(_k))) or False,
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_candidate_freeze_service.refresh_line_candidates_from_current_routing',
        lambda _task, **_k: refresh_calls.append(('line', dict(_k))) or False,
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream',
        lambda **_k: {'outcome': 'passed'},
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round',
        lambda **_k: None,
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.inventory_workflow.ensure_inventory',
        lambda _payload: {'status': 'ok', 'data': {}},
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
        lambda **_k: None,
    )
    monkeypatch.setattr(
        'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
        lambda _task: 'inventory_preparation_failed',
    )
    return executor._handle_retry_inventory_preparation(
        execution=execution, gate=gate, payload=payload,
    )


def test_retry_refreshes_task_candidates_for_task_level_retry(app, monkeypatch):
    """[断言] 任务级人工重取触发整单刷新前置(透传 execution_id);随后仍走既有失效与重取链。"""
    refresh_calls = []
    outcome = _exercise_retry_handler(
        monkeypatch, _task(), _retry_payload(), refresh_calls=refresh_calls,
    )
    assert refresh_calls and refresh_calls[0][0] == 'task'
    assert refresh_calls[0][1].get('execution_id') == 5
    assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'}


def test_retry_refreshes_line_candidates_for_line_scope_retry(app, monkeypatch):
    """[断言] 行级重抓触发目标行刷新前置(透传 line_no 与 execution_id),不做整单重路由。"""
    refresh_calls = []
    outcome = _exercise_retry_handler(
        monkeypatch, _task(), _retry_payload(line_scope_key=3), refresh_calls=refresh_calls,
        line_scope={'source_codes': ['DSV360_AWSDU'], 'snapshot_line_id': 3, 'line_no': 1},
    )
    assert refresh_calls and refresh_calls[0][0] == 'line'
    assert refresh_calls[0][1].get('line_no') == 1
    assert refresh_calls[0][1].get('execution_id') == 5
    assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'}


def test_retry_skips_refresh_for_poll_and_excel_lock(app, monkeypatch):
    """[断言] 轮询路径与 Excel 已生成(源锁定,任务级+行级)均不刷新候选集。"""
    refresh_calls = []
    task = _task()
    _exercise_retry_handler(
        monkeypatch, task, _retry_payload(action_code='poll_inventory_preparation'),
        refresh_calls=refresh_calls,
    )
    _exercise_retry_handler(
        monkeypatch, task, _retry_payload(), refresh_calls=refresh_calls,
        excel_artifact=SimpleNamespace(id=77),
    )
    _exercise_retry_handler(
        monkeypatch, task, _retry_payload(line_scope_key=3), refresh_calls=refresh_calls,
        line_scope={'source_codes': ['DSV360_AWSDU'], 'snapshot_line_id': 3, 'line_no': 1},
        excel_artifact=SimpleNamespace(id=77),
    )
    assert not refresh_calls
  • Step 2: 运行测试确认失败

Run: cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_shipping_refresh_inventory_candidates.py -q Expected: 新增 3 例 FAIL(refresh_calls 为空,断言不成立);Task 1 的 10 例保持 PASS

  • Step 3: 实现前置步骤

在 _handle_retry_inventory_preparation 中定位该块(约 928 行):

    if task is not None and payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch:

在该块内、if payload.get('action_code') in { 'retry_inventory_preparation', ... }: 的 invalidate_inventory_downstream(...) 调用之前插入:

        # [STEP 0B] 人工重取前的候选源刷新(幂等):任务级 retry_inventory_preparation 先按当前
        # 主数据/路由规则整单重判候选集;行级重抓(line_scope 非空)仅重评目标行候选。
        # 两者均无变化零副作用;有变化则新版候选集随 supersede 自带旧事实失效,再走下方
        # 既有失效与重取链——补源场景由此闭环:管理端启用新源后点「重新获取库存(RPA)」
        # 即可让新源进入取数与匹配范围,无需重建订单。
        # 轮询/自动首投(外层条件已排除)与 Excel 已生成(源锁定,D7 边界)不刷新;
        # 已定源(任务级整单/行级目标行候选 ≤1)与人工钉源不刷新(helper 内守卫,改源走
        # override_line_inventory_source)。
        if str(payload.get('action_code') or '').strip() == 'retry_inventory_preparation':
            from app.services.shipping_notice.upload_attempt_service import latest_export_artifact

            if latest_export_artifact(task) is None:
                from app.services.shipping_notice.inventory_candidate_freeze_service import (
                    refresh_candidates_from_current_routing,
                    refresh_line_candidates_from_current_routing,
                )

                if line_scope is None:
                    refresh_candidates_from_current_routing(task, execution_id=int(execution.id))
                else:
                    refresh_line_candidates_from_current_routing(
                        task, line_no=int(line_scope['line_no']), execution_id=int(execution.id),
                    )
  • Step 4: 运行测试确认通过

Run: cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_shipping_refresh_inventory_candidates.py -q Expected: PASS(13 passed)

  • Step 5: 回归相邻测试面(轮询语义与覆写动作不受影响)

Run: cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_inventory_poll_failure_semantics.py tests/test_shipping_override_inventory_source.py tests/test_shipping_line_source_ambiguity.py -q Expected: PASS(如遇与本改动无关的既有 WIP 失败,记录并对照 git stash 验证,不得顺手修改)

  • Step 6: 暂存
git add backend/app/services/shipping_notice/process_gate_executor.py backend/tests/test_shipping_refresh_inventory_candidates.py

Task 3: 前端下拉合并(候选置顶 + 全量源兜底)

Files:

  • Create: frontend/src/features/chat/shipping/inlineSourceOptions.ts
  • Create: frontend/src/features/chat/shipping/inlineSourceOptions.test.ts
  • Modify: frontend/src/features/chat/views/ShippingOrderReviewView.vue(inlineSourceOptions 函数改约 3053-3068 行;删除仅被其使用的 lineSourceOptionLabel 约 2657-2661 行与 overrideSourceOptionLabel 约 2666-2668 行)

Interfaces:

  • Consumes: formSourceOptions(视图已有 computed,来自 ui_state.stage_context.preparation.source_options);行投影字段 source_ambiguous / source_candidates。

  • Produces: mergeInlineSourceOptions(line: InlineSourceLine, enabledSources: ReadonlyArray<EnabledSourceOption>): InlineSourceOption[](纯函数,供视图 inlineSourceOptions 委托)。

  • Step 1: 写失败测试(新建 spec,命名对齐同目录 shippingText.test.ts)

/**
 * features/chat/shipping/inlineSourceOptions.test.ts
 *
 * 用途:行级库存源下拉选项合并的纯函数单测——歧义行候选置顶、全量源兜底去重、空态回退。
 * 依赖:被测 mergeInlineSourceOptions(无副作用纯函数)。
 * 逻辑:断言合并顺序(候选在前、已启用源按后端下发序追加)、去重、大小写归一与空态。
 */
import { describe, expect, it } from 'vitest';
import { mergeInlineSourceOptions } from './inlineSourceOptions';

describe('mergeInlineSourceOptions', () => {
  it('歧义行候选置顶,后接全部已启用源去重兜底(补源场景:新源出现在末尾)', () => {
    const options = mergeInlineSourceOptions(
      { source_ambiguous: true, source_candidates: ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'] },
      [{ source_code: 'DSV360_AWSCV' }, { source_code: 'DSV360_AWSDU' }],
    );
    expect(options.map((option) => option.value)).toEqual([
      'DSV360_AWSCV',
      'DSV360_AWSBI_BYAWSCMH01',
      'DSV360_AWSDU',
    ]);
  });

  it('非歧义行仅给全部已启用源(保持既有行为,不前置候选)', () => {
    const options = mergeInlineSourceOptions(
      { source_ambiguous: false, source_candidates: ['DSV360_AWSCV'] },
      [{ source_code: 'DSV360_AWSDU' }],
    );
    expect(options.map((option) => option.value)).toEqual(['DSV360_AWSDU']);
  });

  it('歧义行候选缺省时退化为全部已启用源,编码统一大写', () => {
    const options = mergeInlineSourceOptions(
      { source_ambiguous: true },
      [{ source_code: 'dsv360_awssg' }],
    );
    expect(options.map((option) => option.value)).toEqual(['DSV360_AWSSG']);
  });

  it('两侧皆空返回空数组(调用方据此回退文本展示)', () => {
    expect(mergeInlineSourceOptions({ source_ambiguous: true }, [])).toEqual([]);
  });
});
  • Step 2: 运行测试确认失败

Run: cd frontend && npx vitest run src/features/chat/shipping/inlineSourceOptions.test.ts Expected: FAIL(Cannot find module './inlineSourceOptions')

  • Step 3: 实现纯函数(新建 inlineSourceOptions.ts)
/**
 * features/chat/shipping/inlineSourceOptions.ts
 *
 * 用途:通知准备行级「库存源」编辑下拉的选项合并(纯函数,无副作用)。
 * 依赖:无(仅入参结构约束,类型与 ui_state preparation 投影字段对齐)。
 * 逻辑:多候选歧义行(source_ambiguous)的路由冻结候选置顶,后接全部已启用库存源
 *      (preparation.source_options)去重兜底——后端 override_line_inventory_source 已放开
 *      「任一已启用源都允许」,管理端补源后新源即使不在候选内也可人工指定。
 */

/** 行级库存源下拉选项(value=源编码,label=展示编码,统一大写便于识别)。 */
export interface InlineSourceOption {
  value: string;
  label: string;
}

/** 准备行投影中与本合并相关的字段(ui_state preparation.lines[] 子集)。 */
export interface InlineSourceLine {
  source_ambiguous?: boolean;
  source_candidates?: Array<string>;
}

/** 后端下发的已启用库存源(ui_state preparation.source_options[] 子集)。 */
export interface EnabledSourceOption {
  source_code?: string | null;
}

/**
 * 合并行级库存源下拉选项:歧义行候选置顶 + 全部已启用源兜底,按源编码去重保序。
 * @param line - 准备行(读 source_ambiguous / source_candidates)
 * @param enabledSources - 后端下发的全部已启用库存源(保持后端排序)
 * @returns 下拉选项;两侧皆空时返回空数组(调用方据此回退文本展示)
 */
export function mergeInlineSourceOptions(
  line: InlineSourceLine,
  enabledSources: ReadonlyArray<EnabledSourceOption>,
): InlineSourceOption[] {
  const merged = new Map<string, InlineSourceOption>();
  if (line.source_ambiguous) {
    for (const raw of line.source_candidates || []) {
      const code = String(raw || '').trim().toUpperCase();
      if (code && !merged.has(code)) merged.set(code, { value: code, label: code });
    }
  }
  for (const source of enabledSources) {
    const code = String(source.source_code || '').trim().toUpperCase();
    if (code && !merged.has(code)) merged.set(code, { value: code, label: code });
  }
  return [...merged.values()];
}
  • Step 4: 运行测试确认通过

Run: cd frontend && npx vitest run src/features/chat/shipping/inlineSourceOptions.test.ts Expected: PASS(4 passed)

  • Step 5: 视图接入(ShippingOrderReviewView.vue)
  1. 在既有 ../shipping/ 相对导入区追加:
import { mergeInlineSourceOptions } from '../shipping/inlineSourceOptions';
  1. 将 inlineSourceOptions(约 3053-3068 行)整体替换为:
/**
 * 行级编辑态库存源下拉选项:歧义行候选置顶 + 全部已启用源兜底(合并去重,纯函数委托)。
 * 无可用项返回空——此时编辑态库存源保持文本展示(无可选即不可改)。
 */
function inlineSourceOptions(line: {
  source_ambiguous?: boolean;
  source_candidates?: Array<string>;
}): Array<{ value: string; label: string }> {
  return mergeInlineSourceOptions(line, formSourceOptions.value);
}
  1. 删除 lineSourceOptionLabel(约 2657-2661 行)与 overrideSourceOptionLabel(约 2666-2668 行)及其注释——二者仅被旧 inlineSourceOptions 使用,删除后全仓无引用(formSourceOptions computed 保留,仍在使用)。
  • Step 6: 全量验证(受影响 spec + 构建)

Run: cd frontend && npx vitest run src/features/chat/views/ShippingOrderReviewView.spec.ts && npm run build Expected: vitest PASS(既有 108+ 用例不回归);build 成功

  • Step 7: 暂存
git add frontend/src/features/chat/shipping/inlineSourceOptions.ts frontend/src/features/chat/shipping/inlineSourceOptions.test.ts frontend/src/features/chat/views/ShippingOrderReviewView.vue

Task 4: i18n 提示文案 + 文档同步

Files:

  • Modify: frontend/src/locales/zh-CN/chat.json、frontend/src/locales/zh-TW/chat.json、frontend/src/locales/en/chat.json、frontend/src/locales/th/chat.json(各 1 处 diagnosisInventoryRpaAdvice)
  • Modify: docs/features/shipping-notice/technical.md(末尾追加章节)、docs/funclist.md(shipping-notice 表追加 1 行)

Interfaces:

  • Consumes: Task 1/2 的后端行为语义(任务级+行级刷新前置)。

  • Produces: 四语言一致的提示文案;文档与代码一致(AGENTS §9)。

  • Step 1: 四语言更新 diagnosisInventoryRpaAdvice(键已在四语言存在,只改值)

  • zh-CN(约 689 行):

"diagnosisInventoryRpaAdvice": "建议先重新获取库存(将按最新主数据重新裁决候选源:任务级整单重判、行级仅重评该行);若外部系统不可用,可人工上传库存文件。"
  • zh-TW(约 655 行):
"diagnosisInventoryRpaAdvice": "建議先重新獲取庫存(將依最新主檔重新裁決候選來源:任務級整單重判、行級僅重評該行);若外部系統不可用,可人工上傳庫存檔。"
  • en(约 655 行):
"diagnosisInventoryRpaAdvice": "Retry inventory fetch first (candidate sources are re-adjudicated against the latest master data: task-level re-routes the whole order, line-level re-evaluates only that line); if the external system is unavailable, upload an inventory file manually."
  • th(约 655 行):
"diagnosisInventoryRpaAdvice": "ลองดึงสต็อกใหม่ก่อน (ระบบจะประเมินแหล่งสต็อกที่เป็นไปได้ใหม่ตามข้อมูลหลักล่าสุด: ระดับงานประเมินทั้งใบสั่ง ระดับบรรทัดประเมินเฉพาะบรรทัดนั้น) หากระบบภายนอกใช้ไม่ได้ ให้อัปโหลดไฟล์สต็อกด้วยตนเอง"
  • Step 2: 构建验证(JSON 合法性由 build 兜底)

Run: cd frontend && npm run build Expected: 成功

  • Step 3: docs/features/shipping-notice/technical.md 末尾追加(只追加,不改既有内容)
## 2026-10-13 候选库存源刷新(人工重取前置:任务级+行级,幂等)

**背景**:多候选订单建单时冻结候选库存源集合;之后管理端补配/新增库存源,存量单的
取数范围(RPA 逐源 / 行级按行候选收窄)与匹配池(候选域过滤)均不会自动纳入新源,
通知准备阶段出现"下拉只有 3 个候选源、重新匹配无法感知新源"的运营阻断
(prod 实例 SORC-E19FE1B9AB8F4FD2)。

**方案(升级不换按钮)**:「重新获取库存(RPA)」(`retry_inventory_preparation`)人工重取前
新增幂等前置刷新,任务级与行级共用守卫红线:
- 任务级(`refresh_candidates_from_current_routing`):重跑 `adjudicate_and_apply_inventory_source`
  整单重判候选集。
- 行级(`refresh_line_candidates_from_current_routing`):仅重评目标行——行级规则重评
  (`evaluate_inventory_source_rules(task, line)`,候选经理 `get_database_inventory_source`
  启停过滤,仅接受 resolved/ambiguous),以活动集全量行为骨架定向替换目标行候选后
  `freeze_candidates_for_task` 重冻结,其余行原样继承。
- 两者均幂等:输入指纹未变复用旧集零副作用;有变化生成新 `set_version`,supersede 旧集时
  由 `_invalidate_task_candidate_outputs` 内置失效旧匹配事实/准备与 RPA Attempt,随后既有
  `invalidate_inventory_downstream` + `ensure_inventory(mode='retry_rpa')` 按新候选重取并重算匹配。
- 守卫:已定源不刷新(任务级冻结候选 ≤1 / 行级目标行候选 ≤1),换源走
  `override_line_inventory_source`;候选集含人工选源(frozen_by_id /
  candidate_origin='manual_override')不刷新(人工指定即定论);Excel 已生成(D7)不刷新;
  轮询/自动首投/`retry_inventory_from_preparation` 不刷新。
- 前端歧义行(source_ambiguous)库存源下拉由"仅候选"改为"候选置顶 + 全部已启用源
  去重兜底"(`features/chat/shipping/inlineSourceOptions.ts` 纯函数),与后端覆写
  动作"任一已启用源都允许"的既有语义对齐;人工补选新源提交后自动重冻结该行并重匹配。

**审计**:产生新版本时写任务事件 `inventory_candidates_refreshed`
(scope=task:previous_set_id/new_set_id/source_codes;scope=line:line_no/previous_codes/new_codes/new_set_id)。
  • Step 4: docs/funclist.md shipping-notice 表追加 1 行

在货代发货通知功能清单表(### 货代发货通知(shipping-notice),3 列:功能项 | 状态 | 说明)末尾追加:

| 库存候选源刷新(人工重取前置,2026-10-13) | 已实现 | 「重新获取库存(RPA)」人工重取前按当前主数据幂等重判候选集(任务级整单重路由、行级仅重评目标行;仅未定源,人工钉源/已定源/Excel 已生成/轮询路径均不刷新),新版候选集 supersede 时内置失效旧库存事实,随后按新候选重取重算;前端歧义行库存源下拉改为候选置顶 + 全部已启用源兜底 |
  • Step 5: 暂存
git add frontend/src/locales/zh-CN/chat.json frontend/src/locales/zh-TW/chat.json frontend/src/locales/en/chat.json frontend/src/locales/th/chat.json docs/features/shipping-notice/technical.md docs/funclist.md

任务依赖与验证总览

  • Task 1 → Task 2(执行器消费两个 helper);Task 3、Task 4 相互独立,可并行。
  • 全部完成后整体回归:cd backend && .\.venv\Scripts\python.exe -m pytest tests/test_shipping_refresh_inventory_candidates.py tests/test_inventory_poll_failure_semantics.py tests/test_shipping_override_inventory_source.py -q + cd frontend && npm run build。
  • 人工冒烟(部署 dev 后):多候选缺口单——任务级「重新获取库存(RPA)」→ 整单候选按当前主数据重判;行级「重新获取库存(RPA)」→ 仅该行候选重评;两者在主数据无变化时行为与升级前一致;管理端启用新源后再点 → 新源进入对应范围。