Files
syops/docs/superpowers/plans/2026-09-17-shipping-notice-effective-view-and-line-closure.md
T
hugo 051f80e1e9 fix(shipping-notice): 有效订单值视图贯通履约链并补全行结案豁免
- 新增 effective_order_view:冻结快照+人工修正按(行position×field_id)对位叠加,整行替换后行级叠加保守跳过
- 库存匹配(order_field_purposes)、Excel值(export)、通知行物化(notice_line_service.line_overrides)统一消费有效值
- 行结案close_unfulfillable端到端豁免:聚合/match_completed/整单建通知/滚动导出四处剔除结案行(含有库存结案行)
- 结案决定落库后触发Gate重算(trigger=line_fulfillment_closed),对齐放行路径
- 兜底匹配分支切有效视图基线;全结案聚合口径与门禁一致(unfulfillable)
- 预约门禁断言更新为有效视图契约;文档同步technical.md/funclist(含结案时序规约)
2026-09-18 01:46:47 +08:00

65 KiB
Raw Blame History

货代发货通知:有效订单值视图(A)+ 行结案豁免补全(B)实施计划

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: 让订单冻结后的人工修正(料号等字段)真正进入库存匹配 / Excel / 通知行,并把已有的行结案(close_unfulfillable)补全为端到端豁免(聚合、满足性、建通知、导出、Gate 重算)。

Architecture: 不动快照不可变、不动 15 阶状态机、无数据库结构变更。新增「有效订单值视图」模块:以冻结快照为基线,把当前 accepted Extraction 的 FieldValue 按(行 position × field_id)对位叠加(整行替换后 position 不可比,行级叠加保守跳过,属后续行集维度);行结案复用 release_inventory_shortage 已有的豁免口径,在四处判定点补 closed 分支,并在结案决定落库后触发与放行相同的 Gate 重算。

Tech Stack: Flask + SQLAlchemy 2.0(后端既有栈维护,见 AGENTS.md §2);pytest(cd backend && python -m pytest)。

Spec: 设计来自 2026-09-17 头脑风暴对话(用户已批准范围 A+B;二期 D「冻结后重解析改道试算+应用」本计划不做,仅在文档留接口位)。领域权威文档:docs/features/shipping-notice/technical.md。

Global Constraints

  • 分支:从 dev 切 fix/shipping-notice-effective-view-line-closure,逐任务提交,完成后合回 dev(AGENTS.md §7)。
  • 提交信息 Conventional Commits:<type>(shipping-notice): 中文主题,主题 ≤100 字符(AGENTS.md §6,commitlint 自动校验)。
  • 注释三层结构强制(AGENTS.md §5):新文件写文件头块注释;每个函数 docstring 含用途/核心逻辑/Args/Returns;修改逻辑必须同步更新受影响注释。
  • 错误处理契约:只允许 AppError 子类;本计划不新增错误码(复用既有 ConflictError 语义),因此无 i18n 四语言改动。
  • 无模型变更 → 无 Alembic 迁移;无新第三方依赖;无前端改动 → 无需 npm run build。
  • 测试环境事实(已核实):app fixture(backend/tests/conftest.py:561)建 SQLite 并 db.create_all();FK 不强制(既有测试直接用 owner=88 这类不存在的用户 id,如 tests/test_shipping_done_line_report.py:141);测试默认关闭 auto 链(_shipping_notice_stable_auto_config),无需额外屏蔽。
  • 断言注释:每个测试函数 docstring 说明断言意图(AGENTS.md §5.4)。

背景事实(执行者必读,均已代码核实)

A 断层:编辑窗 replace_current_line_field_value(backend/app/services/shipping_notice/task_order_field_editor.py:192)只写 ShippingOrderFieldDecision/FieldValue(挂在 OT 的 current_order_extraction_id 指向的 Extraction 上);而库存匹配/Excel 的读取链 order_field_purposes.task_line_purpose_values → export.order_field_id_values(backend/app/services/shipping_notice/export.py:144-159)只读冻结快照 shipping_order_snapshot_lines.field_values_json;通知行物化 notice_line_service.replace_notice_lines_from_snapshot 读快照强类型列(part_number/reservation_id/qty)。三处互不相通 → 改料号后重匹配仍用旧值。

B 半成品:行级履约决定 close_unfulfillable(backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py:1063 decide_review_line_fulfillment)存在且波次/Excel 部分认它,但:

  1. 聚合 _recompute_task_match_aggregate(fulfillment_workflow.py:1341-1408)只有 matched/released/else 三分支,closed 短缺行仍 has_block=True 进缺口列表;
  2. match_completed(fulfillment_workflow.py:721-759)同样无 closed 豁免 → inventory_sufficiency gate 持续 blocked_manual;
  3. 整单建 Notice 门禁(shipping_notice_creation_service.py:87-108)要求每行 matched+ready 或 released,closed 两者皆非 → 拒绝;
  4. 结案决定落库后不触发 Gate 重算(decide_review_line_fulfillment 只在 RELEASE 分支调 _sync_confirmed_task_fulfillment_gates,order_review_fulfillment_decision_service.py:1242-1243);
  5. Excel 导出对有库存的结案行反而照常导出(reservation_service.current_available_snapshot_line_ids 无 closed 过滤,reservation_service.py:275-332)。

豁免同构先例:_released_snapshot_line_ids_for_task(fulfillment_workflow.py:687-718)按 ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage' + is_active 查询,经 line_index 映射快照行 id;closed 完全照抄该口径。

File Structure

修改:
  backend/app/services/shipping_notice/order_field_purposes.py      # 匹配用途投影改读有效视图
  backend/app/services/shipping_notice/export.py                    # Excel 值改读有效视图 + 导出资格排除结案行
  backend/app/services/shipping_notice/notice_line_service.py       # 通知行物化接受有效值覆盖
  backend/app/services/shipping_notice/shipping_notice_creation_service.py  # 建通知排除结案行 + 传有效行事实
  backend/app/services/shipping_notice/fulfillment_workflow.py      # 结案豁免:helper/聚合/match_completed/滚动导出
  backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py  # 结案触发 Gate 重算
  docs/features/shipping-notice/technical.md                        # 语义文档同步
新增:
  backend/app/services/shipping_notice/effective_order_view.py      # A 核心:有效订单值视图
  backend/tests/test_effective_order_view.py
  backend/tests/test_shipping_notice_creation_effective.py
  backend/tests/test_line_closure_fulfillment.py
  backend/tests/test_line_closure_export.py
  backend/tests/test_line_closure_gate_sync.py

Task 1: 有效订单值视图模块(A 核心)

Files:

  • Create: backend/app/services/shipping_notice/effective_order_view.py
  • Test: backend/tests/test_effective_order_view.py

Interfaces:

  • Consumes: export.order_field_id_values(task)(冻结基线投影)、编辑窗已写入的 ShippingOrderFieldValue(修正事实)。

  • Produces:

    • effective_order_field_values(task) -> tuple[dict[str, Any], list[dict[str, Any]]](形状与 order_field_id_values 完全一致:header 按 field_id 键、lines 为 field_id 键字典列表)
    • effective_line_facts_for_notice(owner: ShippingOrderTask) -> dict[int, dict[str, Any]](键 snapshot_line_id,值 {'part_number': str|None, 'reservation_id': str|None, 'qty': Decimal|None, 'field_values': dict})
  • Step 1: 写失败测试

创建 backend/tests/test_effective_order_view.py,内容如下(完整):

"""
tests/test_effective_order_view.py

用途:验证「冻结快照 + 冻结后人工修正」的有效订单值视图。
依赖:pytest、effective_order_view、task_order_field_editor、订单 Schema/快照模型。
逻辑:覆盖行级修正对位叠加、快照不可变、整行替换后的保守跳过与 Notice 行事实投影。
"""

from __future__ import annotations

from decimal import Decimal
from types import SimpleNamespace

from app import db
from app.models import (
    ShippingOrderExtraction,
    ShippingOrderFieldDecision,
    ShippingOrderFieldValue,
    ShippingOrderLine,
    ShippingOrderSchema,
    ShippingOrderSchemaVersion,
    ShippingOrderSnapshot,
    ShippingOrderSnapshotLine,
    ShippingOrderTask,
    User,
)
from app.services.shipping_notice.effective_order_view import (
    effective_line_facts_for_notice,
    effective_order_field_values,
)
from app.services.shipping_notice.task_order_field_editor import (
    replace_current_line_field_value,
    replace_current_line_fields,
)


def _seed_frozen_order():
    """最小冻结订单夹具:OT + accepted Extraction(两行三字段)+ 冻结快照。"""
    user = User(username='eff-view-user', email='eff-view@test.local', role='user', status='active')
    db.session.add(user)
    schema = ShippingOrderSchema(schema_code='EFFVIEW', display_name='EffView')
    db.session.add(schema)
    db.session.flush()
    version = ShippingOrderSchemaVersion(
        schema_id=schema.id, version=1, status='published',
        definition_json={'fields': [
            {'field_id': 'f-part', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'field_category': 'order_line', 'sequence': 1, 'enabled': True},
            {'field_id': 'f-rsv', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string', 'field_category': 'order_line', 'sequence': 2, 'enabled': True},
            {'field_id': 'f-qty', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'field_category': 'order_line', 'sequence': 3, 'enabled': True},
        ]},
    )
    db.session.add(version)
    db.session.flush()
    order = ShippingOrderTask(task_no='OT-EFFVIEW-1', source_type='direct_pdf', user_id=user.id)
    db.session.add(order)
    db.session.flush()
    extraction = ShippingOrderExtraction(
        task_id=order.id, schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted',
    )
    db.session.add(extraction)
    db.session.flush()
    snapshot = ShippingOrderSnapshot(
        task_id=order.id, extraction_id=extraction.id, schema_version_id=version.id,
        order_data_version=1,
        rule_versions_json={'fulfillment_rule': {'required_field_ids': {
            'part_number': 'f-part', 'reservation_id': 'f-rsv', 'qty': 'f-qty',
        }}},
        header_values_json={},
    )
    db.session.add(snapshot)
    db.session.flush()
    snap_lines = []
    for position, part in enumerate(('D4-A08AR12000002-', 'D4-B07BR07000001')):
        line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_no=position + 1)
        db.session.add(line)
        db.session.flush()
        for field_id, value in (('f-part', part), ('f-rsv', f'RSV-{position + 1}'), ('f-qty', '10')):
            decision = ShippingOrderFieldDecision(
                extraction_id=extraction.id, line_id=line.id, field_id=field_id,
                decision_status='accepted', resolved_value_json=value,
            )
            db.session.add(decision)
            db.session.flush()
            db.session.add(ShippingOrderFieldValue(
                extraction_id=extraction.id, line_id=line.id, field_id=field_id, decision_id=decision.id,
                value_text=str(value), value_json=value,
            ))
        snap_line = ShippingOrderSnapshotLine(
            snapshot_id=snapshot.id, position=position, line_no=position + 1,
            part_number=part, reservation_id=f'RSV-{position + 1}', qty=Decimal('10'),
            field_values_json={'f-part': part, 'f-rsv': f'RSV-{position + 1}', 'f-qty': '10'},
        )
        db.session.add(snap_line)
        db.session.flush()
        snap_lines.append(snap_line)
    order.current_order_extraction_id = extraction.id
    order.order_snapshot_id = snapshot.id
    db.session.flush()
    return SimpleNamespace(user=user, order=order, extraction=extraction, snapshot=snapshot, snap_lines=snap_lines)


def test_edited_part_number_flows_into_effective_values(app):
    """冻结后人工修正料号,有效视图必须返回修正值(匹配/Excel 的读取口径)。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        replace_current_line_field_value(
            task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
        )
        _header, lines = effective_order_field_values(fixture.order)
        # 断言:第 0 行为修正值、第 1 行保持冻结值,证明对位叠加只影响被改行。
        assert lines[0]['f-part'] == 'D4-A08AR12000002'
        assert lines[1]['f-part'] == 'D4-B07BR07000001'


def test_snapshot_stays_frozen_after_edit(app):
    """有效视图不得回写快照:冻结事实仍是审计锚点。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        replace_current_line_field_value(
            task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
        )
        # 断言:快照强类型列与 field_values_json 均保持冻结原值。
        assert fixture.snap_lines[0].part_number == 'D4-A08AR12000002-'
        assert fixture.snap_lines[0].field_values_json['f-part'] == 'D4-A08AR12000002-'


def test_line_set_replacement_skips_line_overlay(app):
    """整行替换后 position 不再可比:行级叠加保守跳过,返回冻结行值。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        replace_current_line_fields(task=fixture.order, lines=[
            {'part_number': 'D4-A08AR12000002', 'reservation_id': 'RSV-1', 'qty': '10'},
        ])
        _header, lines = effective_order_field_values(fixture.order)
        # 断言:行级叠加被守卫跳过(行集维度属后续特性),值仍来自冻结快照两行原样。
        assert [row['f-part'] for row in lines] == ['D4-A08AR12000002-', 'D4-B07BR07000001']


def test_effective_line_facts_for_notice(app):
    """Notice 行物化事实按冻结规则映射强类型键并携带修正值。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        replace_current_line_field_value(
            task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
        )
        facts = effective_line_facts_for_notice(fixture.order)
        first = facts[int(fixture.snap_lines[0].id)]
        # 断言:料号为修正值,数量被安全转为 Decimal,字段值字典完整。
        assert first['part_number'] == 'D4-A08AR12000002'
        assert first['reservation_id'] == 'RSV-1'
        assert first['qty'] == Decimal('10')
        assert first['field_values']['f-rsv'] == 'RSV-1'
  • Step 2: 运行测试确认失败

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/effview/backend" && python -m pytest tests/test_effective_order_view.py -v Expected: FAIL,收集错误 ModuleNotFoundError: No module named 'app.services.shipping_notice.effective_order_view'

  • Step 3: 实现模块

创建 backend/app/services/shipping_notice/effective_order_view.py:

"""
services/shipping_notice/effective_order_view.py

用途:向履约链提供「冻结快照 + 冻结后人工修正」的有效订单值视图。
依赖:export.order_field_id_values(冻结投影)、ShippingOrderFieldValue/ShippingOrderLine/
      ShippingOrderTask/ShippingOrderSnapshot(修正事实与行对位)。
逻辑:快照仍是审计锚点,本模块把当前 accepted Extraction 的 FieldValue 按(行 position × field_id)
      对位叠加到快照投影上,供库存匹配、Excel 导出与 Notice 行物化统一消费;整行替换(增删行)
      后 position 不再可比,行级叠加保守跳过(保持冻结值),由后续行集有效视图统一承接。
"""

from __future__ import annotations

from decimal import Decimal, InvalidOperation
from typing import Any

from app import db
from app.models import (
    ShippingOrderFieldValue,
    ShippingOrderLine,
    ShippingOrderSnapshot,
    ShippingOrderTask,
)
from app.services.shipping_notice.export import order_field_id_values


def _owner_task(task: Any) -> Any:
    """与 export.order_field_id_values 同源的任务归属解析(Notice → OT;OT 原样返回)。"""
    order_task_id = getattr(task, 'order_task_id', None)
    if order_task_id:
        return db.session.get(ShippingOrderTask, order_task_id)
    return task


def effective_order_field_values(task: Any) -> tuple[dict[str, Any], list[dict[str, Any]]]:
    """
    返回叠加了冻结后人工修正的订单 Header/Line 有效值(形状同 order_field_id_values)。

    核心逻辑:以冻结快照为基线;当前 accepted Extraction 的 FieldValue 按(行 position ×
    field_id)对位覆盖。当前 Extraction 与快照 Extraction 不同(发生过整行替换)时跳过
    行级叠加,避免错位污染匹配键;单头值不受行替换影响,始终叠加最新已接受值。

    Args:
        task: ShippingNotice 或 ShippingOrderTask。
    Returns:
        (header dict[field_id, value], lines list[dict[field_id, value]])。
    """
    header, lines = order_field_id_values(task)
    owner = _owner_task(task)
    current_id = getattr(owner, 'current_order_extraction_id', None)
    if current_id is None:
        return header, lines
    snapshot = (
        db.session.get(ShippingOrderSnapshot, int(owner.order_snapshot_id))
        if getattr(owner, 'order_snapshot_id', None) else None
    )
    header = dict(header)
    lines = [dict(row) for row in lines]
    values = ShippingOrderFieldValue.query.filter_by(extraction_id=int(current_id)).all()
    # [STEP 1] 单头修正:整行替换会把单头决定复制到新 Extraction(见 task_order_field_editor),
    # 因此单头值始终以当前 Extraction 的已接受值为准。
    for item in values:
        if item.line_id is None:
            header[str(item.field_id)] = item.value_json
    # [STEP 2] 行级修正:仅在当前 Extraction 即冻结来源 Extraction 时按 position 对位。
    if snapshot is not None and int(current_id) == int(snapshot.extraction_id):
        position_by_line_id = {
            int(row.id): int(row.position)
            for row in ShippingOrderLine.query.filter_by(extraction_id=int(current_id)).all()
        }
        overlay_by_index: dict[int, dict[str, Any]] = {}
        for item in values:
            if item.line_id is None:
                continue
            index = position_by_line_id.get(int(item.line_id))
            if index is None:
                continue
            overlay_by_index.setdefault(index, {})[str(item.field_id)] = item.value_json
        for index, row in enumerate(lines):
            row.update(overlay_by_index.get(index, {}))
    return header, lines


def _coerce_qty(value: Any) -> Decimal | None:
    """把字段值安全转为数量;空/非法值返回 None。"""
    if value in (None, ''):
        return None
    try:
        return Decimal(str(value).replace(',', '').strip())
    except (InvalidOperation, ValueError, TypeError):
        return None


def effective_line_facts_for_notice(owner: ShippingOrderTask) -> dict[int, dict[str, Any]]:
    """
    按 snapshot_line_id 返回 Notice 行物化所需的有效事实(强类型键 + 完整字段值)。

    核心逻辑:经 effective_order_field_values 取有效值后,按冻结履约规则的
    required_field_ids 把 part_number/reservation_id/qty 三个用途键解析为强类型事实;
    缺少规则映射时对应键为 None(由消费方回退冻结列)。

    Args:
        owner: 已冻结订单的 ShippingOrderTask。
    Returns:
        {snapshot_line_id: {'part_number', 'reservation_id', 'qty', 'field_values'}}。
    Raises:
        ValueError: 任务没有冻结快照。
    """
    snapshot = (
        db.session.get(ShippingOrderSnapshot, int(owner.order_snapshot_id))
        if getattr(owner, 'order_snapshot_id', None) else None
    )
    if snapshot is None:
        raise ValueError('任务没有可用于通知行物化的冻结订单快照')
    _header, lines = effective_order_field_values(owner)
    required_ids = (snapshot.rule_versions_json or {}).get('fulfillment_rule', {}).get('required_field_ids')
    required_ids = required_ids if isinstance(required_ids, dict) else {}
    part_fid = str(required_ids.get('part_number') or '')
    rsv_fid = str(required_ids.get('reservation_id') or '')
    qty_fid = str(required_ids.get('qty') or '')
    facts: dict[int, dict[str, Any]] = {}
    for line_orm, values in zip(snapshot.lines, lines, strict=True):
        facts[int(line_orm.id)] = {
            'part_number': values.get(part_fid) if part_fid else None,
            'reservation_id': values.get(rsv_fid) if rsv_fid else None,
            'qty': _coerce_qty(values.get(qty_fid)) if qty_fid else None,
            'field_values': dict(values),
        }
    return facts
  • Step 4: 运行测试确认通过

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/effview/backend" && python -m pytest tests/test_effective_order_view.py -v Expected: 4 PASS

  • Step 5: 提交
cd "D:/Workspace/HxProjects/hxops/.worktrees/effview"
git add backend/app/services/shipping_notice/effective_order_view.py backend/tests/test_effective_order_view.py
git commit -m "feat(shipping-notice): 新增冻结后修正的有效订单值视图模块"

Task 2: 库存匹配与 Excel 值切换到有效视图

Files:

  • Modify: backend/app/services/shipping_notice/order_field_purposes.py(:15 import 与 :52 调用)
  • Modify: backend/app/services/shipping_notice/export.py(:782 header_values, all_line_values = order_field_id_values(task))
  • Test: backend/tests/test_effective_order_view.py(追加)

Interfaces:

  • Consumes: Task 1 的 effective_order_field_values(task)。

  • Produces: task_line_purpose_values 与 Excel 行值集合返回修正后的值(对外签名不变)。

  • Step 1: 追加失败测试

在 backend/tests/test_effective_order_view.py 追加(含 import:文件头部 import 区追加 ShippingNotice 到 app.models 导入,并新增 from app.services.shipping_notice.order_field_purposes import task_line_purpose_values):

def test_matching_purpose_values_use_effective_view(app):
    """库存匹配用途投影必须读到修正后的料号(修复改值不进匹配的断层)。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        replace_current_line_field_value(
            task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
        )
        notice = ShippingNotice(
            task_no='SN-EFFVIEW-1', source_type='manual', user_id=fixture.user.id,
            order_task_id=fixture.order.id,
        )
        db.session.add(notice)
        db.session.flush()
        purpose_values = task_line_purpose_values(notice)
        # 断言:第 0 行用途值为修正料号,第 1 行保持冻结值。
        assert purpose_values[0]['part_number'] == 'D4-A08AR12000002'
        assert purpose_values[1]['part_number'] == 'D4-B07BR07000001'
  • Step 2: 运行确认失败

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/effview/backend" && python -m pytest tests/test_effective_order_view.py::test_matching_purpose_values_use_effective_view -v Expected: FAIL,purpose_values[0]['part_number'] == 'D4-A08AR12000002-'(仍读冻结值)

  • Step 3: 切换两个调用点

backend/app/services/shipping_notice/order_field_purposes.py:

  • :15 from app.services.shipping_notice.export import _source_notice_for_order_facts, order_field_id_values 改为:
from app.services.shipping_notice.effective_order_view import effective_order_field_values
from app.services.shipping_notice.export import _source_notice_for_order_facts
  • task_line_purpose_values(:49-56)内 _header, lines = order_field_id_values(task) 改为 _header, lines = effective_order_field_values(task),并把函数 docstring 中「值只来自冻结 Snapshot」改为「值来自冻结 Snapshot 叠加冻结后人工修正的有效视图(effective_order_view)」。

backend/app/services/shipping_notice/export.py :782 header_values, all_line_values = order_field_id_values(task) 改为:

    from app.services.shipping_notice.effective_order_view import effective_order_field_values
    header_values, all_line_values = effective_order_field_values(task)

(函数内局部 import,避免模块级循环依赖。)同时在文件头 export.py 的 order_field_id_values docstring 末尾补一行:库存匹配/Excel 消费方应改用 effective_order_view.effective_order_field_values 获取含冻结后修正的有效值。

  • Step 4: 运行本文件测试 + 匹配域回归

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/effview/backend" && python -m pytest tests/test_effective_order_view.py tests/test_shipping_stp_phase4_line_inventory_match.py tests/test_line_inventory_match_persistence.py tests/test_shipping_inventory_match_invalidation.py -v Expected: 全部 PASS(新增 5 个 + 既有回归)

  • Step 5: 提交
cd "D:/Workspace/HxProjects/hxops/.worktrees/effview"
git add backend/app/services/shipping_notice/order_field_purposes.py backend/app/services/shipping_notice/export.py backend/tests/test_effective_order_view.py
git commit -m "fix(shipping-notice): 库存匹配与Excel值改读有效订单视图"

Task 3: 通知行物化携带修正后的行事实

Files:

  • Modify: backend/app/services/shipping_notice/notice_line_service.py(replace_notice_lines_from_snapshot 增参)
  • Modify: backend/app/services/shipping_notice/shipping_notice_creation_service.py(:154 调用点传覆盖)
  • Test: backend/tests/test_shipping_notice_creation_effective.py(新建)

Interfaces:

  • Consumes: Task 1 的 effective_line_facts_for_notice(owner) -> dict[int, dict]。

  • Produces: replace_notice_lines_from_snapshot(..., line_overrides: dict[int, dict[str, Any]] | None = None)——键 snapshot_line_id,仅非 None 值覆盖快照列。

  • Step 1: 写失败测试

创建 backend/tests/test_shipping_notice_creation_effective.py:

"""
tests/test_shipping_notice_creation_effective.py

用途:验证正式通知行物化携带冻结后修正值,且整单建通知排除已结案行。
依赖:pytest、shipping_notice_creation_service、notice_line_service、行级履约决定模型。
逻辑:库存门禁通过(或行豁免)后建 Notice,断言 NoticeLine 的料号/数量来自有效视图,
      结案行既不进门禁目标集也不物化为通知行。
"""

from __future__ import annotations

from decimal import Decimal

from app import db
from app.models import (
    ShippingCustomer,
    ShippingNoticeLine,
    ShippingNoticeLineInventoryMatch,
    ShippingOrderReviewCase,
    ShippingOrderReviewLineDecision,
)
from app.services.shipping_notice.shipping_notice_creation_service import (
    create_shipping_notice_after_inventory_gate,
)
from app.services.shipping_notice.task_order_field_editor import replace_current_line_field_value
from tests.test_effective_order_view import _seed_frozen_order


def _seed_customer(snapshot):
    """给快照挂一个 active 客户(建 Notice 门禁必填)。"""
    customer = ShippingCustomer(standard_name='有效视图客户', short_code='EFFC', status='active')
    db.session.add(customer)
    db.session.flush()
    snapshot.customer_id = customer.id
    db.session.flush()


def _seed_match_row(order, snap_line, *, match_result='matched', shortage='0'):
    """给冻结行补一条当前匹配事实(matched+ready 表示门禁可过)。"""
    db.session.add(ShippingNoticeLineInventoryMatch(
        task_id=order.id, snapshot_line_id=snap_line.id, line_no=snap_line.line_no,
        line_index=snap_line.position, match_result=match_result, inventory_status='ready',
        required_qty='10', available_qty='10', shortage_qty=shortage,
        reservation_id=snap_line.reservation_id, part_number=snap_line.part_number,
        is_current=True,
    ))
    db.session.flush()


def test_notice_lines_carry_corrected_part_number(app):
    """修正后的料号必须进入正式通知行(通知行会被 Excel/货代消费)。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        _seed_customer(fixture.snapshot)
        replace_current_line_field_value(
            task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
        )
        _seed_match_row(fixture.order, fixture.snap_lines[0])
        notice = create_shipping_notice_after_inventory_gate(fixture.order)
        rows = ShippingNoticeLine.query.filter_by(notice_id=notice.id).all()
        # 断言:通知行料号是修正值,而不是快照冻结的带尾巴旧值。
        assert [row.part_number for row in rows] == ['D4-A08AR12000002']
  • Step 2: 运行确认失败

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/effview/backend" && python -m pytest tests/test_shipping_notice_creation_effective.py -v Expected: FAIL,['D4-A08AR12000002-'] != ['D4-A08AR12000002']

  • Step 3: 实现

backend/app/services/shipping_notice/notice_line_service.py——replace_notice_lines_from_snapshot 签名追加参数,docstring 的 Args 增加说明,行构建处改为(for line in list(snapshot.lines or []): 循环体内,取 override 后构建 ShippingNoticeLine):

def replace_notice_lines_from_snapshot(
    *,
    notice_id: int,
    snapshot: ShippingOrderSnapshot,
    snapshot_line_ids: set[int] | None = None,
    inventory_facts_by_snapshot_line_id: dict[int, dict[str, Any]] | None = None,
    line_overrides: dict[int, dict[str, Any]] | None = None,
) -> int:
    """
    用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。

    Args:
        notice_id: shipping_notices.id。
        snapshot: 已 flush 且带 lines 的 Snapshot。
        snapshot_line_ids: 仅写入本次发货通知选中的冻结行;为空时兼容整单冻结。
        inventory_facts_by_snapshot_line_id: 行级库存事实(来源/文件/仓库)。
        line_overrides: effective_order_view.effective_line_facts_for_notice 的输出,
            按 snapshot_line_id 携带冻结后人工修正;仅非 None 值覆盖快照列,
            缺失或 None 时回退冻结快照值。

    Returns:
        写入行数。
    """

循环体内:

    for line in list(snapshot.lines or []):
        if selected_ids and int(line.id) not in selected_ids:
            continue
        notice_position += 1
        inventory_facts = dict(inventory_facts_by_snapshot_line_id.get(int(line.id)) or {})
        override = (line_overrides or {}).get(int(line.id)) or {}
        rows.append(
            ShippingNoticeLine(
                notice_id=int(notice_id),
                snapshot_line_id=int(line.id) if getattr(line, 'id', None) else None,
                position=notice_position - 1,
                # 发货通知项次按当前通知单重新从 1 编排。
                line_no=notice_position,
                part_number=override.get('part_number')
                if override.get('part_number') is not None else getattr(line, 'part_number', None),
                reservation_id=override.get('reservation_id')
                if override.get('reservation_id') is not None else getattr(line, 'reservation_id', None),
                required_qty=override.get('qty')
                if override.get('qty') is not None else getattr(line, 'qty', None),
                inventory_source_code=inventory_facts.get('inventory_source_code'),
                inventory_file_id=inventory_facts.get('inventory_file_id'),
                inventory_warehouse_id=inventory_facts.get('inventory_warehouse_id'),
                field_values_json=dict(override['field_values'])
                if override.get('field_values') else dict(getattr(line, 'field_values_json', None) or {}),
                created_at=now,
            )
        )

(rows/now/selected_ids 等原有局部变量保持不变,仅按上面替换循环体。)

backend/app/services/shipping_notice/shipping_notice_creation_service.py——顶部 import 区新增:

from app.services.shipping_notice.effective_order_view import effective_line_facts_for_notice

:154 调用点改为:

    replace_notice_lines_from_snapshot(
        notice_id=int(notice.id),
        snapshot=snapshot,
        snapshot_line_ids=selected_ids,
        inventory_facts_by_snapshot_line_id=inventory_facts_by_snapshot_line_id,
        line_overrides=effective_line_facts_for_notice(order_task),
    )

并在 create_shipping_notice_after_inventory_gate docstring 的核心逻辑中补一句:通知行物化使用 effective_order_view 的有效行事实,携带冻结后人工修正值。

  • Step 4: 运行确认通过

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/effview/backend" && python -m pytest tests/test_shipping_notice_creation_effective.py tests/test_effective_order_view.py -v Expected: 全部 PASS

  • Step 5: 提交
cd "D:/Workspace/HxProjects/hxops/.worktrees/effview"
git add backend/app/services/shipping_notice/notice_line_service.py backend/app/services/shipping_notice/shipping_notice_creation_service.py backend/tests/test_shipping_notice_creation_effective.py
git commit -m "fix(shipping-notice): 通知行物化携带修正后的行事实"

Task 4: 行结案豁免——结案行集合 + 聚合 + 整单满足性

Files:

  • Modify: backend/app/services/shipping_notice/fulfillment_workflow.py(新增 helper、_recompute_task_match_aggregate、match_completed)
  • Test: backend/tests/test_line_closure_fulfillment.py(新建)

Interfaces:

  • Consumes: ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable' 决定事实(既有)。

  • Produces: fulfillment_workflow._closed_snapshot_line_ids_for_task(task) -> set[int](后续 Task 5/6/7 复用;与 _released_snapshot_line_ids_for_task 同源同口径)。

  • Step 1: 写失败测试

创建 backend/tests/test_line_closure_fulfillment.py:

"""
tests/test_line_closure_fulfillment.py

用途:验证行结案(close_unfulfillable)在满足性聚合与整单门禁中的豁免语义。
依赖:pytest、fulfillment_workflow、行级履约决定模型、冻结订单夹具。
逻辑:两行订单关闭短缺行后整单应判定满足;全部行结案时整单不通过(无剩余履约内容)。
"""

from __future__ import annotations

from app import db
from app.models import (
    ShippingNoticeLineInventoryMatch,
    ShippingOrderReviewCase,
    ShippingOrderReviewLineDecision,
)
from app.services.shipping_notice.fulfillment_workflow import (
    _closed_snapshot_line_ids_for_task,
    _recompute_task_match_aggregate,
    match_completed,
)
from tests.test_effective_order_view import _seed_frozen_order


def _seed_match_facts(fixture):
    """第 0 行 matched+ready,第 1 行 not_found 短缺(历史阻塞点)。"""
    for snap_line, result, shortage in (
        (fixture.snap_lines[0], 'matched', '0'),
        (fixture.snap_lines[1], 'not_found', '10'),
    ):
        db.session.add(ShippingNoticeLineInventoryMatch(
            task_id=fixture.order.id, snapshot_line_id=snap_line.id, line_no=snap_line.line_no,
            line_index=snap_line.position, match_result=result, inventory_status='ready',
            required_qty='10', available_qty='10' if result == 'matched' else '0',
            shortage_qty=shortage, reservation_id=snap_line.reservation_id,
            part_number=snap_line.part_number, is_current=True,
        ))
    db.session.flush()


def _seed_close_decision(fixture, line_index, *, case_no='SNRC-CLOSE-1', version=1):
    """给已确认 Case 补一条活动结案决定(FK 不强制,挂哨兵父 id 即可)。"""
    case = ShippingOrderReviewCase.query.filter_by(case_no=case_no).first()
    if case is None:
        case = ShippingOrderReviewCase(
            case_no=case_no, run_id=901, unit_id=902, document_id=903,
            owner_user_id=fixture.user.id, status='confirmed', confirmed_task_id=fixture.order.id,
        )
        db.session.add(case)
        db.session.flush()
    db.session.add(ShippingOrderReviewLineDecision(
        review_case_id=case.id, draft_line_id=f'line-{line_index}', line_index=line_index,
        decision_version=version, decision_code='close_unfulfillable', decision_source='user',
        line_status='closed_unfulfillable', is_active=True, reason='该行不再发货',
        actor_user_id=fixture.user.id, snapshot_json={},
    ))
    db.session.flush()


def test_closed_line_ids_helper_mirrors_release_query(app):
    """结案行集合必须与放行同款:活动决定 + line_index 映射快照行。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        _seed_close_decision(fixture, 1)
        # 断言:仅第 1 行(line_index=1)进入结案集合。
        assert _closed_snapshot_line_ids_for_task(fixture.order) == {int(fixture.snap_lines[1].id)}


def test_aggregate_exempts_closed_shortage_line(app):
    """关闭短缺行后聚合应判满足:closed 行不阻断、不进缺货列表。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        _seed_match_facts(fixture)
        _seed_close_decision(fixture, 1)
        status, shortages = _recompute_task_match_aggregate(fixture.order)
        payload = fixture.order.step_payload_json or {}
        line_results = payload['current_match_projection']['line_results']
        # 断言:整单满足、缺货列表为空、结案行状态为 closed 而非 shortage。
        assert status == 'fulfillable'
        assert shortages == []
        assert line_results[1]['line_status'] == 'closed'


def test_match_completed_passes_with_closed_line(app):
    """整单满足性门禁对结案行豁免:一行 matched + 一行 closed 即通过。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        _seed_match_facts(fixture)
        # 断言:结案前整单不通过(历史阻塞行为)。
        assert match_completed(fixture.order) is False
        _seed_close_decision(fixture, 1)
        # 断言:结案后整单通过(本任务修复目标)。
        assert match_completed(fixture.order) is True


def test_all_lines_closed_fails_match_completed(app):
    """全部行结案=无剩余履约内容:整单满足性不通过(此类单应走作废流程)。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        _seed_match_facts(fixture)
        _seed_close_decision(fixture, 1, version=1)
        _seed_close_decision(fixture, 0, version=1)
        # 断言:无任何待履约行时 match_completed 返回 False,避免自动建空通知。
        assert match_completed(fixture.order) is False
  • Step 2: 运行确认失败

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/effview/backend" && python -m pytest tests/test_line_closure_fulfillment.py -v Expected: FAIL,ImportError: cannot import name '_closed_snapshot_line_ids_for_task'

  • Step 3: 实现

backend/app/services/shipping_notice/fulfillment_workflow.py:

(a) 在 _released_snapshot_line_ids_for_task(:687-718)之后新增:

def _closed_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]:
    """读取当前任务已结案(close_unfulfillable)的冻结行 ID,供满足性与聚合豁免共用。

    核心逻辑:与 ``_released_snapshot_line_ids_for_task`` 同源同口径——只认活动决定,
    经 line_index 映射快照行;结案行不再是履约要求,在满足性/建单/导出各处按豁免处理。
    """
    from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision

    if task.id is None:
        return set()
    if not getattr(task, 'order_snapshot_id', None):
        return set()
    decisions = (
        ShippingOrderReviewLineDecision.query
        .join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
        .filter(
            ShippingOrderReviewCase.confirmed_task_id == int(task.id),
            ShippingOrderReviewLineDecision.is_active.is_(True),
            ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
        )
        .all()
    )
    from app.models import ShippingOrderSnapshot
    snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
    if snapshot is None:
        return set()
    return {
        int(snapshot.lines[int(row.line_index)].id)
        for row in decisions
        if row.line_index is not None
        and 0 <= int(row.line_index) < len(snapshot.lines)
    }

(b) match_completed(:721-759)整体替换为:

def match_completed(task: ShippingNotice) -> bool:
    """
    STP 整单满足性门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时通过。

    核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。
    已人工放行的短缺行视同满足;已结案(close_unfulfillable)行不再是履约要求,
    从覆盖校验与逐行判定中双重豁免;全部行结案时无剩余履约内容,按不通过处理。
    """
    from app.models import ShippingNoticeLineInventoryMatch

    if task.id is None:
        return False
    rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
    if not rows:
        return False
    from app.models import ShippingOrderSnapshot

    snapshot = (
        db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
        if getattr(task, 'order_snapshot_id', None) else None
    )
    closed_ids = _closed_snapshot_line_ids_for_task(task)
    expected_line_ids = {int(line.id) for line in getattr(snapshot, 'lines', []) or []} - closed_ids
    if not expected_line_ids:
        # 全部行已结案:订单无剩余履约内容,不得自动进入建通知/Excel(应走作废流程)。
        return False
    current_line_ids = {
        int(row.snapshot_line_id)
        for row in rows
        if getattr(row, 'snapshot_line_id', None) is not None
    } - closed_ids
    # 满足性必须覆盖剩余待履约的全部项次;仅有部分当前 Match 不能代表整单可履约。
    if current_line_ids != expected_line_ids:
        return False
    released_ids = _released_snapshot_line_ids_for_task(task)
    for row in rows:
        if getattr(row, 'snapshot_line_id', None) is not None and int(row.snapshot_line_id) in closed_ids:
            continue
        result = str(row.match_result or '').strip()
        shortage = _line_shortage_qty(getattr(row, 'shortage_qty', None))
        if result == 'matched' and shortage <= 0:
            continue
        if int(row.snapshot_line_id) in released_ids and shortage > 0:
            continue
        return False
    return True

(c) _recompute_task_match_aggregate(:1341-1408):docstring「核心逻辑」末尾追加一句 已结案(close_unfulfillable)行不再是履约要求,与放行同款不阻断、不进缺货列表(行状态记 closed)。;:1355 之后新增一行:

    closed_snapshot_line_ids = _closed_snapshot_line_ids_for_task(task)

行分类段(:1378-1391)替换为:

        # 已审计放行的短缺行视同满足:不阻断、不进入缺货列表。
        shortage = _line_shortage_qty(shortage_qty)
        released = entry['snapshot_line_id'] in released_snapshot_line_ids
        closed = entry['snapshot_line_id'] in closed_snapshot_line_ids
        if closed:
            # [BE-结案-豁免] 结案行不再是履约要求:与放行同款不阻断、不进缺货列表。
            entry['line_status'] = 'closed'
            has_ok = True
        elif match_result == 'matched' and shortage <= 0:
            entry['line_status'] = 'ok'
            has_ok = True
        elif released and shortage > 0:
            # 放行行状态仍暴露"放行",但聚合按满足计入,避免整单误判缺货。
            entry['line_status'] = 'released'
            has_ok = True
        else:
            entry['line_status'] = 'shortage'
            has_block = True
            shortages.append(entry)
  • Step 4: 运行确认通过 + 满足性域回归

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/effview/backend" && python -m pytest tests/test_line_closure_fulfillment.py tests/test_shipping_fulfillment_entry_gates.py tests/test_shipping_stp_phase4_line_inventory_match.py -v Expected: 全部 PASS

  • Step 5: 提交
cd "D:/Workspace/HxProjects/hxops/.worktrees/effview"
git add backend/app/services/shipping_notice/fulfillment_workflow.py backend/tests/test_line_closure_fulfillment.py
git commit -m "fix(shipping-notice): 行结案获得满足性聚合与整单门禁豁免"

Task 5: 整单建通知排除已结案行

Files:

  • Modify: backend/app/services/shipping_notice/shipping_notice_creation_service.py(:92-108 门禁段)
  • Test: backend/tests/test_shipping_notice_creation_effective.py(追加)

Interfaces:

  • Consumes: Task 4 的 _closed_snapshot_line_ids_for_task(task)。

  • Produces: 门禁目标行集自动剔除结案行;结案行不物化为通知行。

  • Step 1: 追加失败测试

在 backend/tests/test_shipping_notice_creation_effective.py 追加(import 区新增 from tests.test_line_closure_fulfillment import _seed_close_decision):

def test_notice_creation_skips_closed_line(app):
    """一行 matched + 一行结案:整单建通知成功且通知行不含结案行。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        _seed_customer(fixture.snapshot)
        _seed_match_row(fixture.order, fixture.snap_lines[0])
        _seed_match_row(
            fixture.order, fixture.snap_lines[1], match_result='not_found', shortage='10',
        )
        _seed_close_decision(fixture, 1)
        notice = create_shipping_notice_after_inventory_gate(fixture.order)
        rows = ShippingNoticeLine.query.filter_by(notice_id=notice.id).all()
        # 断言:只有第 0 行进入通知;结案行既过门禁又被物化排除。
        assert [row.snapshot_line_id for row in rows] == [int(fixture.snap_lines[0].id)]
  • Step 2: 运行确认失败

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/effview/backend" && python -m pytest tests/test_shipping_notice_creation_effective.py::test_notice_creation_skips_closed_line -v Expected: FAIL,抛 ConflictError: SHIPPING.INVENTORY_GATE_NOT_PASSED

  • Step 3: 实现

shipping_notice_creation_service.py 门禁段(:90-93 附近):

原:

    target_ids = selected_ids or {int(line.id) for line in snapshot.lines}
    by_line = {int(row.snapshot_line_id): row for row in fact_rows if row.snapshot_line_id is not None}
    from app.services.shipping_notice.fulfillment_workflow import _released_snapshot_line_ids_for_task
    released_ids = _released_snapshot_line_ids_for_task(order_task)

改为:

    by_line = {int(row.snapshot_line_id): row for row in fact_rows if row.snapshot_line_id is not None}
    from app.services.shipping_notice.fulfillment_workflow import (
        _closed_snapshot_line_ids_for_task,
        _released_snapshot_line_ids_for_task,
    )
    released_ids = _released_snapshot_line_ids_for_task(order_task)
    # [BE-结案-豁免] 结案行不再是履约要求:从目标行集剔除,不参与门禁、不物化为通知行。
    closed_ids = _closed_snapshot_line_ids_for_task(order_task)
    target_ids = (selected_ids or {int(line.id) for line in snapshot.lines}) - closed_ids

并在函数 docstring 的核心逻辑中补一句:已结案(close_unfulfillable)行从目标行集剔除,不参与门禁也不写入通知行;全部行结案时 target_ids 为空仍按门禁未通过拒绝。

  • Step 4: 运行确认通过

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/effview/backend" && python -m pytest tests/test_shipping_notice_creation_effective.py -v Expected: 2 PASS

  • Step 5: 提交
cd "D:/Workspace/HxProjects/hxops/.worktrees/effview"
git add backend/app/services/shipping_notice/shipping_notice_creation_service.py backend/tests/test_shipping_notice_creation_effective.py
git commit -m "fix(shipping-notice): 整单建通知排除已结案行"

Task 6: 滚动导出资格排除已结案行

Files:

  • Modify: backend/app/services/shipping_notice/reservation_service.py(current_available_snapshot_line_ids 增参)
  • Modify: backend/app/services/shipping_notice/export.py(STEP 1 段查结案决定并传参)
  • Modify: backend/app/services/shipping_notice/fulfillment_workflow.py(exportable_snapshot_line_ids :823 与 :2040 调用点)
  • Test: backend/tests/test_line_closure_export.py(新建)

Interfaces:

  • Consumes: Task 4 的 _closed_snapshot_line_ids_for_task(task)。

  • Produces: current_available_snapshot_line_ids(task, *, released_snapshot_line_ids=None, selected_snapshot_line_ids=None, closed_snapshot_line_ids: set[int] | None = None)——结案行无论库存是否可用一律剔除(修复「有库存的结案行照样导出」的边缘缺陷)。

  • Step 1: 写失败测试

创建 backend/tests/test_line_closure_export.py:

"""
tests/test_line_closure_export.py

用途:验证滚动导出资格对已结案行的剔除(含"有库存的结案行也不导出"边缘场景)。
依赖:pytest、reservation_service、fulfillment_workflow、核验/预约模型、行级履约决定。
逻辑:两行均有可用预约,结案其一后,导出资格集合只保留未结案行。
"""

from __future__ import annotations

from decimal import Decimal

from app import db
from app.models import (
    ShippingInventoryVerification,
    ShippingInventoryVerificationLine,
    ShippingReservation,
)
from app.services.shipping_notice.fulfillment_workflow import exportable_snapshot_line_ids
from app.services.shipping_notice.reservation_service import current_available_snapshot_line_ids
from tests.test_effective_order_view import _seed_frozen_order
from tests.test_line_closure_fulfillment import _seed_close_decision


def _seed_available_reservations(fixture):
    """两行各建一条 available 预约 + 一轮 completed 核验。"""
    verification = ShippingInventoryVerification(task_id=fixture.order.id, status='completed')
    db.session.add(verification)
    db.session.flush()
    for index, snap_line in enumerate(fixture.snap_lines):
        reservation = ShippingReservation(
            task_id=fixture.order.id, snapshot_line_id=snap_line.id,
            reservation_id=f'RSV-CLOSE-{index}', po_number_normalized='PO-CLOSE',
            part_number=snap_line.part_number, required_qty=Decimal('10'), status='available',
        )
        db.session.add(reservation)
        db.session.flush()
        db.session.add(ShippingInventoryVerificationLine(
            verification_id=verification.id, reservation_id=reservation.id,
            required_qty=Decimal('10'), available_qty=Decimal('10'), status='available',
        ))
    db.session.flush()


def test_closed_line_with_inventory_is_not_exportable(app):
    """结案行即使库存充足、核验 available 也不得进入导出资格集合。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        _seed_available_reservations(fixture)
        _seed_close_decision(fixture, 1)
        _verification, available = current_available_snapshot_line_ids(
            fixture.order, closed_snapshot_line_ids={int(fixture.snap_lines[1].id)},
        )
        # 断言:仅未结案的第 0 行可导出。
        assert available == {int(fixture.snap_lines[0].id)}


def test_exportable_snapshot_line_ids_excludes_closed(app):
    """滚动导出入口(exportable_snapshot_line_ids)自动剔除结案行。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        _seed_available_reservations(fixture)
        _seed_close_decision(fixture, 1)
        # 断言:导出集合不含结案行(该行预约仍 available,验证 closed 过滤优先)。
        assert exportable_snapshot_line_ids(fixture.order) == {int(fixture.snap_lines[0].id)}
  • Step 2: 运行确认失败

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/effview/backend" && python -m pytest tests/test_line_closure_export.py -v Expected: 第一个 FAIL TypeError: ... unexpected keyword argument 'closed_snapshot_line_ids';第二个 FAIL(返回两行集合)

  • Step 3: 实现

(a) backend/app/services/shipping_notice/reservation_service.py current_available_snapshot_line_ids(:275-332):签名追加 closed_snapshot_line_ids: set[int] | None = None;docstring Args 补 closed_snapshot_line_ids: 已结案冻结行 ID;无论库存状态一律从可导出集合剔除。;末段 line_ids = {...} 改为:

    closed_ids = {int(item) for item in (closed_snapshot_line_ids or set())}
    line_ids = {
        item.snapshot_line_id for item in reservations
        if not selected_ids or int(item.snapshot_line_id) in selected_ids
    } - closed_ids

(b) backend/app/services/shipping_notice/export.py STEP 1 段(:787-816 释放决定查询之后、selected_snapshot_line_ids 之前)追加结案决定查询:

    closed_rows = (
        ShippingOrderReviewLineDecision.query
        .join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
        .filter(
            ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
            ShippingOrderReviewLineDecision.is_active.is_(True),
            ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
        )
        .all()
    )
    closed_snapshot_line_ids = {
        int(snapshot.lines[int(decision.line_index)].id)
        for decision in closed_rows
        if decision.line_index is not None
        and 0 <= int(decision.line_index) < len(snapshot.lines)
    }

:823 调用改为:

        verification, available_line_ids = current_available_snapshot_line_ids(
            source_notice,
            released_snapshot_line_ids=released_snapshot_line_ids,
            selected_snapshot_line_ids=selected_snapshot_line_ids or None,
            closed_snapshot_line_ids=closed_snapshot_line_ids,
        )

(c) backend/app/services/shipping_notice/fulfillment_workflow.py:

  • exportable_snapshot_line_ids(:817-829)调用改为:
        _verification, line_ids = current_available_snapshot_line_ids(
            _source_notice_for_order_facts(task),
            released_snapshot_line_ids=_released_snapshot_line_ids_for_export(task),
            closed_snapshot_line_ids=_closed_snapshot_line_ids_for_task(task),
        )
  • :2040 滚动 Excel 复用检查调用改为:
            _verification, available_line_ids = current_available_snapshot_line_ids(
                _source_notice_for_order_facts(task),
                closed_snapshot_line_ids=_closed_snapshot_line_ids_for_task(task),
            )
  • Step 4: 运行确认通过 + 导出域回归

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/effview/backend" && python -m pytest tests/test_line_closure_export.py tests/test_shipping_rolling_fulfillment.py tests/test_line_inventory_match_persistence.py -v Expected: 全部 PASS

  • Step 5: 提交
cd "D:/Workspace/HxProjects/hxops/.worktrees/effview"
git add backend/app/services/shipping_notice/reservation_service.py backend/app/services/shipping_notice/export.py backend/app/services/shipping_notice/fulfillment_workflow.py backend/tests/test_line_closure_export.py
git commit -m "fix(shipping-notice): 滚动导出资格排除已结案行"

Task 7: 行结案决定落库后同步重算履约 Gate

Files:

  • Modify: backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py(_sync_confirmed_task_fulfillment_gates 增 trigger 参数;decide_review_line_fulfillment :1242-1243 分支扩展)
  • Test: backend/tests/test_line_closure_gate_sync.py(新建)

Interfaces:

  • Consumes: Task 4 的聚合豁免(recompute_task_fulfillment_state 内部委托 _recompute_task_match_aggregate)。

  • Produces: _sync_confirmed_task_fulfillment_gates(*, case, actor_id, trigger: str = 'inventory_shortage_released') -> None;结案决定使用 trigger='line_fulfillment_closed'。

  • Step 1: 写失败测试

创建 backend/tests/test_line_closure_gate_sync.py:

"""
tests/test_line_closure_gate_sync.py

用途:验证结案决定落库后的 Gate 重算联动(对齐放行路径),含 trigger 透传。
依赖:pytest、order_review_fulfillment_decision_service、fulfillment_workflow、匹配事实夹具。
逻辑:结案使聚合转为满足后,_sync 必须重算任务履约态并以 line_fulfillment_closed 触发编排。
"""

from __future__ import annotations

from types import SimpleNamespace

from app.services.shipping_notice.order_review_fulfillment_decision_service import (
    _sync_confirmed_task_fulfillment_gates,
)
from tests.test_effective_order_view import _seed_frozen_order
from tests.test_line_closure_fulfillment import _seed_close_decision, _seed_match_facts


def test_close_decision_syncs_gates_with_closed_trigger(app, monkeypatch):
    """结案行豁免使整单满足后,Gate 同步须重算并以 line_fulfillment_closed 触发编排。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        _seed_match_facts(fixture)
        _seed_close_decision(fixture, 1)
        calls = []

        def _capture_progress(*args, **kwargs):
            calls.append(('submit_auto_progress', kwargs.get('trigger')))

        def _capture_enqueue(*args, **kwargs):
            calls.append(('enqueue_post_ot_auto_fulfill_job', kwargs.get('trigger')))

        # 拦截编排出口:函数内为局部 import,直接 patch 源模块属性即可生效。
        monkeypatch.setattr(
            'app.services.shipping_notice.auto_progress_controller.submit_auto_progress',
            _capture_progress,
        )
        monkeypatch.setattr(
            'app.services.shipping_notice.line_auto_fulfill_coordinator.enqueue_post_ot_auto_fulfill_job',
            _capture_enqueue,
        )
        fake_case = SimpleNamespace(confirmed_task_id=fixture.order.id)
        _sync_confirmed_task_fulfillment_gates(
            case=fake_case, actor_id=fixture.user.id, trigger='line_fulfillment_closed',
        )
        payload = fixture.order.step_payload_json or {}
        # 断言:任务履约态被重算为满足,且两个编排出口都带结案 trigger。
        assert payload['current_match_projection']['match_status'] == 'fulfillable'
        assert ('submit_auto_progress', 'line_fulfillment_closed') in calls
        assert ('enqueue_post_ot_auto_fulfill_job', 'line_fulfillment_closed') in calls
  • Step 2: 运行确认失败

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/effview/backend" && python -m pytest tests/test_line_closure_gate_sync.py -v Expected: FAIL,TypeError: _sync_confirmed_task_fulfillment_gates() got an unexpected keyword argument 'trigger'

  • Step 3: 实现

(a) _sync_confirmed_task_fulfillment_gates(:429-485):签名改为:

def _sync_confirmed_task_fulfillment_gates(
    *,
    case: ShippingOrderReviewCase,
    actor_id: int,
    trigger: str = 'inventory_shortage_released',
) -> None:

docstring 首行改为 短缺放行/行结案后同步正式 OT Gate,并异步触发唯一明细的独立 Notice/Excel 创建。,Args 追加 trigger: 编排触发标签(放行 inventory_shortage_released / 结案 line_fulfillment_closed)。;函数内两处硬编码 trigger='inventory_shortage_released'(submit_auto_progress 与 enqueue_post_ot_auto_fulfill_job)都改为 trigger=trigger。

(b) decide_review_line_fulfillment :1242-1243 替换为:

    if code in {DECISION_RELEASE_SHORTAGE, DECISION_CLOSE}:
        # [BE-结案-豁免] 结案与放行同为库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
        _sync_confirmed_task_fulfillment_gates(
            case=case,
            actor_id=int(user_id),
            trigger='inventory_shortage_released' if code == DECISION_RELEASE_SHORTAGE else 'line_fulfillment_closed',
        )

(decide() 的分支接线由本测试 + Task 4 聚合测试共同覆盖;端到端走查列入 Task 8 验收清单。)

  • Step 4: 运行确认通过 + 决定域回归

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/effview/backend" && python -m pytest tests/test_line_closure_gate_sync.py tests/test_shipping_review_line_fulfillment_decision.py -v Expected: 全部 PASS

  • Step 5: 提交
cd "D:/Workspace/HxProjects/hxops/.worktrees/effview"
git add backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py backend/tests/test_line_closure_gate_sync.py
git commit -m "fix(shipping-notice): 行结案后同步重算履约门禁"

Task 8: 文档同步与全量回归

Files:

  • Modify: docs/features/shipping-notice/technical.md
  • Modify: docs/funclist.md(货代发货通知条目)

Interfaces:

  • Consumes: Task 1-7 全部成果。

  • Produces: 文档与代码一致的语义说明(AGENTS.md §9)。

  • Step 1: 更新 technical.md

在 docs/features/shipping-notice/technical.md 中定位「重试与重解析」章节(约 :699,grep -n "重试与重解析" docs/features/shipping-notice/technical.md)与编辑窗/缺口复核相关段落,追加以下小节(放在重试与重解析章节之后):

### 有效订单值视图与行结案豁免(2026-09-17)

**有效订单值视图(effective_order_view)**:订单冻结后的人工字段修正(编辑窗
`update-notice-fields`)写入当前 accepted Extraction 的 Decision/FieldValue;库存匹配
(order_field_purposes → effective_order_field_values)、Excel 行值(export)与通知行物化
(notice_line_service.line_overrides)统一消费「冻结快照 + 修正叠加」的有效值。快照保持
不可变审计锚点;整行替换(增删行)后行级叠加保守跳过(行集维度待后续特性)。

**行结案(close_unfulfillable)端到端豁免**:与 `release_inventory_shortage` 同源同口径——
满足性聚合与 `match_completed` 中结案行不阻断、不进缺货列表(行状态 `closed`);整单建
Notice 的目标行集剔除结案行(不物化为通知行);滚动导出资格(reservation_service /
export / exportable_snapshot_line_ids)无论库存状态一律剔除结案行;结案决定落库后触发
`_sync_confirmed_task_fulfillment_gates(trigger='line_fulfillment_closed')` 重算 Gate。
**边界**:全部行结案时 `match_completed` 按不通过处理(无剩余履约内容,应走作废流程);
「冻结后重解析改道试算+应用」(二期 D)尚未实现,重解析窗口仍维持确认前语义。
  • Step 2: 更新 funclist.md

在 docs/funclist.md 货代发货通知条目下追加一行行为说明(保留既有行,仅新增):

- 订单冻结后的人工字段修正(料号等)现可进入库存匹配、Excel 与通知行(有效订单值视图);缺口复核中的行结案(close_unfulfillable)现具备端到端豁免(不再阻塞整单,导出/建通知自动剔除结案行)。
  • Step 3: 后端全量回归

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/effview/backend" && python -m pytest tests -q Expected: 全部 PASS。若出现与本改动无关的既有失败,记录失败清单并与改动前基线对比(git stash 后复跑确认非本计划引入)。

  • Step 4: 手工走查清单(test 环境)
  1. 用测试环境任一 blocked(库存缺口)订单:编辑窗修正料号 → 「重新匹配库存」→ 匹配命中新料号。
  2. 同类订单:缺口复核中对短缺行执行「结案(无法履约)」→ 任务自动解除 blocked(Gate 重算)→ 剩余 matched 行进入通知准备/Excel。
  3. 有库存行执行结案 → 该行不出现在 Excel 与通知明细。
  4. 复核 blocked 面板确认「缺口复核」入口可见(前端 actionRegistry 已注册 open_shortage_review,无需前端改动,仅验证投影链路)。
  • Step 5: 提交
cd "D:/Workspace/HxProjects/hxops/.worktrees/effview"
git add docs/features/shipping-notice/technical.md docs/funclist.md
git commit -m "docs(shipping-notice): 补充有效视图与行结案语义文档"

Self-Review(已执行)

  1. Spec coverage:A(断层:匹配 Task 2 / Excel 值 Task 2 / 通知行 Task 3;快照不可变 Task 1 测试锁定);B(聚合+满足性 Task 4 / 建通知 Task 5 / 导出 Task 6 / Gate 重算 Task 7 / 入口验证 Task 8 Step 4-4)。二期 D 明确不做并在文档留接口位。✔
  2. Placeholder scan:无 TBD/TODO;所有代码块完整可粘贴;Task 8 文档插入点给出 grep 定位方式。✔
  3. Type consistency:_closed_snapshot_line_ids_for_task(task) -> set[int](Task 4 定义,Task 5/6/7 同名同签名消费);effective_order_field_values/effective_line_facts_for_notice(Task 1 定义,Task 2/3 同名消费);line_overrides 键为 snapshot_line_id(Task 1 产出与 Task 3 消费一致);current_available_snapshot_line_ids 新参名 closed_snapshot_line_ids(Task 6 内三处调用一致)。✔
  4. 已知风险:Task 7 的 recompute_task_fulfillment_state 内部 apply_task_transition 对夹具 OT 默认 status='processing' 的迁移守卫行为未逐一验证——若测试在转换处报错,把夹具 OT 置 status='blocked'(结案场景的真实状态)后重跑;Task 4 的 test_all_lines_closed_fails_match_completed 锁定的是计划约定的边界语义(全部结案不通过),如评审认为应改为"通过且空通知",需同步改 Task 5 门禁与文档。