Files
syops/docs/superpowers/plans/2026-09-18-shipping-notice-inline-edit-and-entry-repair.md
T
hugo eed1068ae3 feat(shipping-notice): 通知准备履约字段就地编辑并修复缺口复核入口
- 编辑闸门翻转为状态制:Excel 生成前+无活动 Attempt 即可编辑,原因不强制(审计自动记录操作人与变更)
- 修复 Decimal 字段人工编辑无法持久化(单字段+整行替换两路径)
- 预约注册与核验比对改读有效订单值视图,消除编辑后重匹配 RESERVATION_MISMATCH 阻断
- 通知准备值列改读有效视图:保存即显新值,匹配结果列保持最近一轮事实
- 行编辑入口为更多操作列编辑按钮;编辑态替换为保存/取消;库存源行内改选随保存统一提交
- 展示态动作收纳进更多菜单(Teleport 浮层,防表格 overflow 裁剪)
- 修复缺口复核投影键错位(has_shortage 恒 False 致入口隐藏)并补齐行级结案入口
- 缺口放行改行内补录条(菜单放行或缺 N 项徽标展开,确认放行/取消收起),放行原因可选
- i18n 四语言;technical.md/funclist.md 语义文档同步
2026-09-18 14:59:39 +08:00

43 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: 让订单确认后(Excel 生成前)的履约字段(料号/预约号/数量)在通知准备界面就地编辑并持久化,编辑后手点「重新匹配库存」全链路生效;同时修复缺口复核面板的两个入口 bug,让"不发货的行"有结案出路。

Architecture: 编辑权限从「字段字典逐字段配置」翻转为「状态制」(Excel 未生成 + 无活动 Attempt = 可编辑,字段配置退化为反向锁);写路径完全复用现有 update-notice-line(Decision/FieldValue + 版本号 + 自动 old→new 审计),零新增端点、零白名单、零新表。读路径把三处仍锚定冻结快照列的消费方(通知准备值列、预约/核验层)切到已有的有效订单值视图(effective_order_view)。前端在匹配表三个单元格加编辑框。另修缺口复核面板的键错位与结案入口。

Tech Stack: Flask + SQLAlchemy 2.0(后端既有栈);Vue 3 + TypeScript + i18n 四语言(前端);pytest + vitest。

Spec: 2026-09-17/18 头脑风暴对话结论(用户逐项确认的 6 项清单 + 三次设计简化裁决:无原因必填、无白名单、无候选值接口、编辑框样式、无自动触发)。前置分支成果:051f80e1e(有效视图 + 行结案豁免,已在 hugo-shipping-notice)。

Global Constraints

  • 分支:从 hugo-shipping-notice 切 worktree 分支 fix/shipping-notice-inline-edit-entry-repair 实施;完成后按用户惯例并入 hugo-shipping-notice。
  • Conventional Commits:<type>(shipping-notice): 中文主题,≤100 字符。
  • 注释三层结构(AGENTS.md §5):修改逻辑必须同步更新受影响注释。
  • 无数据库迁移(无模型变更);无新错误码 → 除前端新增文案外无新增 errors.json 键。
  • i18n 四语言强制:前端新增文案必须同时补 zh-CN / zh-TW / en / th(AGENTS.md §8)。
  • 前端改动必须保证 npm run build(含 vue-tsc)通过。
  • 测试命令(worktree 内,需先做 Task 0 的 junction):
    • 后端 cd backend && ./.venv/Scripts/python.exe -m pytest <目标> -v
    • 前端 cd frontend && npx vue-tsc -b --pretty false && npm run build
  • 禁止 git stash(共享 stash 栈有用户条目);验证用 git diff / 临时 commit。
  • 下游追踪结论(2026-09-18 探查报告)作为本计划的边界事实:Excel ready 后编辑被硬冻结(不可达窗口不做);「通知已存在后编辑不重物化通知行」为本期声明边界,不在本包修。

Task 0: 环境准备(worktree + junction)

Files: 无代码变更。

  • Step 1: 创建 worktree 并接好依赖 junction
cd "D:/Workspace/HxProjects/hxops"
git worktree add .worktrees/editfeat -b fix/shipping-notice-inline-edit-entry-repair hugo-shipping-notice
cd .worktrees/editfeat
powershell -Command "New-Item -ItemType Junction -Path node_modules -Target 'D:\Workspace\HxProjects\hxops\node_modules'"
powershell -Command "New-Item -ItemType Junction -Path backend\.venv -Target 'D:\Workspace\HxProjects\hxops\backend\.venv'"
mkdir backend/.pytest_tmp

(注意用 PowerShell 建 junction,Git Bash 的 cmd //c mklink 会篡改路径为 D:\D:\...。)

  • Step 2: 冒烟验证

Run: cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_effective_order_view.py -q Expected: 5 passed


Task 1: Decimal 写 JSON 列 bug 修复(数量编辑的前提)

Files:

  • Modify: backend/app/services/shipping_notice/task_order_field_editor.py(_field_value_columns :180-189、replace_current_line_field_value :225、replace_current_header_field_value :267)
  • Test: backend/tests/test_effective_order_view.py(追加)

Interfaces:

  • Produces: 编辑 decimal 字段不再抛 TypeError: Object of type Decimal is not JSON serializable;value_json/resolved_value_json 对 decimal 存 format(value.normalize(), 'f') 字符串(与机器路径 order_schema/runtime.py:119-125 _json_value 对齐),value_decimal 列仍存真 Decimal。

  • Step 1: 写失败测试

在 backend/tests/test_effective_order_view.py 追加(文件已有 import 区,补 replace_current_line_field_value 已存在的无需重复;补 from app.models import ShippingOrderFieldValue 若缺失):

def test_decimal_edit_persists_without_json_error(app):
    """数量(decimal 字段)人工编辑必须可持久化:value_json 存字符串、value_decimal 存 Decimal。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        # 修复前此处抛 TypeError: Object of type Decimal is not JSON serializable。
        replace_current_line_field_value(
            task=fixture.order, position=0, field_code='qty', value='12.5',
        )
        row = ShippingOrderFieldValue.query.filter_by(
            extraction_id=fixture.extraction.id, line_id=fixture.snap_lines[0].__dict__['_sa_instance_state'].dict['id'] if False else None,
        )

上面的查询写法不对,直接用关系取(替换为以下最终版本):

def test_decimal_edit_persists_without_json_error(app):
    """数量(decimal 字段)人工编辑必须可持久化:value_json 存字符串、value_decimal 存 Decimal。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        replace_current_line_field_value(
            task=fixture.order, position=0, field_code='qty', value='12.5',
        )
        rows = [
            item for item in ShippingOrderFieldValue.query.filter_by(
                extraction_id=fixture.extraction.id,
            ).all()
            if item.value_json is not None
        ]
        qty_rows = [item for item in rows if item.field_id == 'f-qty' and item.line_id is not None]
        # 断言:JSON 列存规范字符串(与机器路径 _json_value 对齐),类型列保留 Decimal。
        assert qty_rows, 'qty FieldValue 必须存在'
        assert all(item.value_json == '12.5' for item in qty_rows)
        assert any(item.value_decimal == Decimal('12.5') for item in qty_rows)
  • Step 2: 运行确认失败

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_effective_order_view.py::test_decimal_edit_persists_without_json_error -v Expected: FAIL,TypeError: Object of type Decimal is not JSON serializable(flush 时)

  • Step 3: 实现

task_order_field_editor.py:

(a) 在 _field_value_columns(:180)之前新增:

def _json_value(value: Any) -> Any:
    """把人工输入转为 JSON 列可序列化形状;与 order_schema.runtime._json_value 对齐。

    核心逻辑:Decimal → format(normalize, 'f') 字符串(保留精度且 json.dumps 可序列化),
    date → isoformat;其余原样。类型化列(value_decimal 等)仍保存原生值。
    """
    if isinstance(value, Decimal):
        return format(value.normalize(), 'f')
    if isinstance(value, date):
        return value.isoformat()
    return value

(文件顶部 import 区补 from datetime import date。)

(b) _field_value_columns(:180-189)中 'value_json': value, 改为 'value_json': _json_value(value),。

(c) replace_current_line_field_value :225 decision.resolved_value_json = normalized 改为 decision.resolved_value_json = _json_value(normalized);replace_current_header_field_value :267 同样处理。

  • Step 4: 运行确认通过

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_effective_order_view.py tests/test_shipping_review_formal_task_edit.py -v Expected: 全部 PASS(新增 1 + 既有 5/10+)

  • Step 5: 提交
git add backend/app/services/shipping_notice/task_order_field_editor.py backend/tests/test_effective_order_view.py
git commit -m "fix(shipping-notice): 人工编辑decimal字段可持久化并保留原始JSON形状"

Task 2: 编辑闸门翻转为状态制 + 原因/证据改可选

Files:

  • Modify: backend/app/services/shipping_notice/schema_edit_policy.py(:22 常量、:49-51 初始化)
  • Modify: backend/app/services/shipping_notice/task_workflow.py(_prepare_review_context :1031-1061、_commit_notice_edit :923-924)
  • Test: backend/tests/test_shipping_schema_edit_policy.py(:21-23 改写)、backend/tests/test_shipping_review_formal_task_edit.py(:287-307 改写)、backend/tests/test_shipping_formal_task_edit_audit.py(:34-61 改写)

Interfaces:

  • Produces: 未配置 task_edit_policy 的字段默认可编辑(Excel ready 仍硬冻结;显式 editable:false 仍可反向锁);reason/evidence 缺省时自动落哨兵值(审计列 NOT NULL 不破坏)。

  • Step 1: 改写三个测试为新契约(先写失败)

backend/tests/test_shipping_schema_edit_policy.py :21-23 原断言 DEFAULT_EDITABLE_AFTER_TASK_CREATION is False 改为:

def test_default_formal_fields_are_editable_until_excel_ready():
    """新契约:未配置策略的字段默认可编辑(状态制),显式 editable=false 仍可反向锁。"""
    assert DEFAULT_EDITABLE_AFTER_TASK_CREATION is True
    assert field_task_edit_policy(None)['editable'] is True
    assert field_task_edit_policy({'task_edit_policy': {'editable': False}})['editable'] is False

(import 区按该文件现有导入补 DEFAULT_EDITABLE_AFTER_TASK_CREATION。)

backend/tests/test_shipping_review_formal_task_edit.py :287-307 test_formal_edit_rejects_default_readonly_field 改写为 accepts 语义(保留原夹具调用方式,仅翻转断言):

def test_formal_edit_accepts_unconfigured_field_by_default():
    """新契约:未配置 task_edit_policy 的字段在 Excel 未就绪时可直接编辑。"""
    # 沿用本文件既有夹具构造正式任务与请求体,字段用夹具中未配置策略的行字段;
    # 响应断言 success(不再抛 ORDER_FIELD_EDIT_FORBIDDEN),order_data_version 递增。

(实现者按该文件 :287-307 原用例的夹具与请求构造照抄,仅把「断言拒绝」换成「断言成功 + 版本递增」;原用例中若显式传了 task_edit_policy 夹具则去掉该配置。)

backend/tests/test_shipping_formal_task_edit_audit.py :34-61 同理:原断言拒绝+ORDER_FIELD_EDIT_FORBIDDEN 审计,改为断言编辑成功且审计事件为 formal_task_field_edited(old→new 存在)。

同时 grep 证据必填断言:grep -rn "ORDER_REVIEW_EVIDENCE_REQUIRED" backend/tests ——列出后逐个改写为「缺省时成功且审计 evidence_ref 为哨兵值」。

  • Step 2: 运行确认失败

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_schema_edit_policy.py tests/test_shipping_review_formal_task_edit.py tests/test_shipping_formal_task_edit_audit.py -v Expected: FAIL(新契约断言失败,旧实现返回 False / 拒绝)

  • Step 3: 实现

(a) schema_edit_policy.py :22 改为:

# 默认:建单后 Excel 生成前字段可编辑(状态制);个别字段需要锁定时在 Schema 配置 editable=false 反向关闭。
DEFAULT_EDITABLE_AFTER_TASK_CREATION: Final[bool] = True

(b) field_task_edit_policy :49-51 改为(注意:只改常量不够,初始化必须同步,否则无配置字段仍为 False):

    editable = bool(policy.get('editable')) if policy else DEFAULT_EDITABLE_AFTER_TASK_CREATION
    if not DEFAULT_EDITABLE_AFTER_TASK_CREATION and 'editable' not in policy:
        editable = False

(c) task_workflow.py _prepare_review_context(:1031-1061):reason 缺省改为哨兵、evidence 缺省跳过校验(先读全函数再落改):

    # 快捷就地编辑不强制填写原因/证据:审计链自动记录 old→new + 操作人 + 时间;
    # 提供了证据时仍走原校验。哨兵值满足 shipping_order_review_events 的 NOT NULL 列。
    reason = str(review_context.get('reason') or '').strip() or 'quick_field_edit'
    evidence = review_context.get('evidence') or None
    if evidence is not None:
        validate_review_evidence(evidence)  # 原 :1047-1061 的校验调用保持
        evidence_ref = ...  # 原有证据引用构建逻辑
    else:
        evidence_ref = 'inline:match-table'

(reviewed_by_id 与 event_source='workspace_api' 的要求保留不变——操作人身份是审计底线。)

(d) _commit_notice_edit :923-924 的 if not reviewed_by_id or not evidence_ref or not reason: raise 改为仅 if not reviewed_by_id: raise(evidence_ref/reason 已由上游哨兵兜底)。

  • Step 4: 运行确认通过 + 契约域回归

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_schema_edit_policy.py tests/test_shipping_review_formal_task_edit.py tests/test_shipping_formal_task_edit_audit.py tests/test_effective_order_view.py -v Expected: 全部 PASS。再跑 grep -rn "ORDER_FIELD_EDIT_FORBIDDEN" backend/tests | grep -v test_shipping_schema_edit_policy 核对无遗漏的旧契约断言(有则一并改写为新契约)。

  • Step 5: 提交
git add backend/app/services/shipping_notice/schema_edit_policy.py backend/app/services/shipping_notice/task_workflow.py backend/tests/test_shipping_schema_edit_policy.py backend/tests/test_shipping_review_formal_task_edit.py backend/tests/test_shipping_formal_task_edit_audit.py
git commit -m "feat(shipping-notice): 编辑闸门翻转为状态制并放宽原因证据必填"

Task 3: 预约/核验层切有效视图(修 RESERVATION_MISMATCH 阻断)

Files:

  • Modify: backend/app/services/shipping_notice/reservation_service.py(ensure_task_reservations :42-104、record_inventory_verification :178-184)
  • Test: backend/tests/test_reservation_effective_view.py(新建)

Interfaces:

  • Consumes: effective_order_view.effective_line_facts_for_notice(owner: ShippingOrderTask) -> {int: {'part_number','reservation_id','qty','field_values'}}(已存在)。

  • Produces: 预约注册/核验比对以有效值为准;编辑后重匹配不再抛 SHIPPING.RESERVATION_MISMATCH。

  • Step 1: 写失败测试

创建 backend/tests/test_reservation_effective_view.py:

"""
tests/test_reservation_effective_view.py

用途:验证预约注册与核验比对消费有效订单值视图(编辑后不再 RESERVATION_MISMATCH)。
依赖:pytest、reservation_service、task_order_field_editor、effective view 夹具。
逻辑:先按冻结值注册预约 → 就地编辑料号 → 再次 ensure 应自动修订(transfer)而非抛错。
"""

from __future__ import annotations

from app import db
from app.models import ShippingReservation
from app.services.shipping_notice.reservation_service import ensure_task_reservations
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 test_ensure_task_reservations_follows_effective_values(app):
    """预约注册必须消费有效值:编辑料号后再次 ensure 应更新预约(修订)而非校验失败。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        # 第一次注册:按冻结值(带尾巴的旧料号)建预约。
        ensure_task_reservations(fixture.order)
        reservation = ShippingReservation.query.filter_by(
            task_id=fixture.order.id,
        ).one()
        # 断言:初始注册值为冻结快照列原值。
        assert reservation.part_number == 'D4-A08AR12000002-'
        # 就地编辑第 0 行料号为正确值。
        replace_current_line_field_value(
            task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
        )
        # 第二次 ensure(重匹配核验前的真实调用时序):必须成功且预约更新为有效值。
        ensure_task_reservations(fixture.order)
        db.session.refresh(reservation)
        # 断言:预约料号已随有效值修订,状态回 pending(可重新核验)。
        assert reservation.part_number == 'D4-A08AR12000002'

(若 ensure_task_reservations 的实际入参/返回与上述调用不符,以 reservation_service.py:42-104 实际签名为准适配调用方式,断言语义不变。)

  • Step 2: 运行确认失败

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_reservation_effective_view.py -v Expected: FAIL——第二次调用抛 SHIPPING.RESERVATION_MISMATCH 或 RESERVATION_REVISION_REVIEW_REQUIRED(编辑后有效值 ≠ 注册值)

  • Step 3: 实现

先通读 ensure_task_reservations(:42-104)与 _transfer_confirmed_revision(:118-156)全函数再落改。语义目标:

(a) ensure_task_reservations :50-54 的快照列读取改为有效事实优先:

    # [BE-有效视图] 预约身份以有效订单值为准(冻结快照 + 已接受修正),
    # 否则就地编辑料号/数量后核验比对必抛 RESERVATION_MISMATCH。
    from app.services.shipping_notice.effective_order_view import effective_line_facts_for_notice
    effective_facts = effective_line_facts_for_notice(task)
    for line in snapshot.lines:
        eff = effective_facts.get(int(line.id)) or {}
        reservation_id_value = eff.get('reservation_id') if eff.get('reservation_id') is not None else line.reservation_id
        part_number_value = eff.get('part_number') if eff.get('part_number') is not None else line.part_number
        qty_value = eff.get('qty') if eff.get('qty') is not None else line.qty
        # ……后续 :55-101 的重复/冲突/注册/修订判定全部改用以上三个值

(b) part/qty 不一致分支:当该行无 Artifact 锁(:82-83 既有锁判断)且预约属于同一 OT 时,走 _transfer_confirmed_revision(:118-156,其内部已有 bump 版本 + reservation_revision_confirmed 事件 + status 回 pending)完成自动修订;仅当行已锁定(已导出)时保留原 RESERVATION_REVISION_REVIEW_REQUIRED 拒绝。

(c) record_inventory_verification :178-184 的料号比对改为两侧归一化(消除大小写/空白造成的假阳性,数量比对逻辑不变):

        if reservation is None or str(reservation.part_number or '').strip().upper() != str(part_number or '').strip().upper():
  • Step 4: 运行确认通过 + 预约域回归

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_reservation_effective_view.py -v 后追加:grep -rln "ensure_task_reservations\|RESERVATION_MISMATCH" backend/tests | head 找到既有预约测试文件并全量跑(FAIL 的按新契约逐个核对:若断言"快照值注册"则更新为有效值语义)。 Expected: 全部 PASS

  • Step 5: 提交
git add backend/app/services/shipping_notice/reservation_service.py backend/tests/test_reservation_effective_view.py
git commit -m "fix(shipping-notice): 预约注册与核验比对改读有效订单值视图"

Task 4: 通知准备值列切有效视图

Files:

  • Modify: backend/app/services/shipping_notice/ui_state.py(frozen_order_lines :867-878、preparation_lines :880-882/:937-938)
  • Test: backend/tests/test_ui_state_effective_values.py(新建)

Interfaces:

  • Consumes: effective_line_facts_for_notice(order_task)(Task 3 同款)。

  • Produces: 前端 formalPreparationDisplayLines(ShippingOrderReviewView.vue:2562-2572 以 frozen_order_lines 为底、prep.lines 覆盖)在保存后立即显示新值;匹配结果列仍来自匹配事实(诚实反映最近一轮)。

  • Step 1: 写失败测试

创建 backend/tests/test_ui_state_effective_values.py:

"""
tests/test_ui_state_effective_values.py

用途:验证通知准备投影的值列(预约号/料号/需求数量)消费有效订单值视图。
依赖:pytest、ui_state 阶段上下文构建、有效视图夹具。
逻辑:编辑料号后(重匹配前),值列必须立即显示新值;匹配状态列不受影响。
"""

from __future__ import annotations

from app import db
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 test_preparation_value_columns_follow_effective_values(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',
        )
        from app.services.shipping_notice import ui_state
        context = ui_state._build_stage_context(fixture.order)
        lines = context['preparation']['frozen_order_lines'] if 'preparation' in context else context.get('frozen_order_lines', [])
        # 断言:值列为有效值(而非快照冻结的带尾巴旧值)。
        assert lines[0]['part_number'] == 'D4-A08AR12000002'

(_build_stage_context 的实际函数名/返回形状以 ui_state.py:793-794 与 :1067-1068 为准适配;断言语义不变:值列 = 有效值。若该构建函数需要更多入参,参照其既有测试或调用方 query_service 的传参方式构造。)

  • Step 2: 运行确认失败

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_ui_state_effective_values.py -v Expected: FAIL,part_number == 'D4-A08AR12000002-'(仍读冻结列)

  • Step 3: 实现

ui_state.py(先读 :837-960 全段):

(a) :848 之后(snapshot 解析完成处)计算一次有效事实:

    # [BE-有效视图] 值列消费有效订单值(快照 + 已接受修正):保存即显新值,
    # 匹配结果列仍读当前匹配事实,诚实反映最近一轮匹配结论。
    from app.services.shipping_notice.effective_order_view import effective_line_facts_for_notice
    effective_facts = (
        effective_line_facts_for_notice(order_task)
        if order_task is not None and getattr(order_task, 'order_snapshot_id', None) else {}
    )

(b) frozen_order_lines(:867-878):reservation_id/part_number/required_qty 改为有效值优先、快照列回退:

        eff = effective_facts.get(int(snapshot_line.id)) or {}
        frozen_order_lines.append({
            'snapshot_line_id': int(snapshot_line.id),
            'line_no': line_no,
            'reservation_id': eff.get('reservation_id') if eff.get('reservation_id') is not None else snapshot_line.reservation_id,
            'part_number': eff.get('part_number') if eff.get('part_number') is not None else snapshot_line.part_number,
            'required_qty': str(eff['qty']) if eff.get('qty') is not None else qty_text,
        })

(键名不动——前端类型 shipping.api.types.ts:1490-1497 契约稳定;注释同步改为「有效值优先」。)

(c) preparation_lines 的三处(:880-882 required_qty、:937 reservation_id、:938 part_number):把「fact → 快照」的回退链改为「有效事实 → fact → 快照」——保存后即使 fact 未刷新,覆盖合并(前端 :2570 prep 覆盖 frozen)也显示新值:

        eff = effective_facts.get(int(snapshot_line.id)) or {}
        # part_number:有效事实 → 匹配事实 → 快照列
        part_number_value = (
            eff.get('part_number')
            if eff.get('part_number') is not None
            else (fact or {}).get('part_number') or snapshot_line.part_number
        )
        # reservation_id / required_qty 同构(required_qty 记得 str() 化)
  • Step 4: 运行确认通过 + ui_state 域回归

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_ui_state_effective_values.py -v;再 grep -rln "ui_state" backend/tests | head -8 跑既有 ui_state 相关测试(FAIL 的核对:若断言值列为冻结值,更新为有效值语义)。 Expected: 全部 PASS

  • Step 5: 提交
git add backend/app/services/shipping_notice/ui_state.py backend/tests/test_ui_state_effective_values.py
git commit -m "fix(shipping-notice): 通知准备值列改读有效订单值视图"

Task 5: 前端匹配表三单元格编辑框(+ i18n 四语言)

Files:

  • Modify: frontend/src/features/chat/views/ShippingOrderReviewView.vue(表格 :4936-4952 区段;保存逻辑复用 :2859 loadFormalTaskDetail)
  • Modify: frontend/src/features/chat/api/shipping.api.ts(updateWorkspaceShippingNoticeLine :1205-1225 的 evidence/reason 参数改可选)
  • Modify: frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json(shippingOrderReview 子树新增 3 键)
  • Test: 手动走查(前端无既有组件测试基建覆盖该区段;npx vue-tsc -b + build 为门禁)

Interfaces:

  • Consumes: updateWorkspaceShippingNoticeLine(taskNo, lineIndex, patch, comment, options)(lineIndex = line.line_no - 1,与后端 ShippingOrderLine.position 0 基对齐);Task 2 后 evidence/reason 可选。

  • Produces: 料号/预约号/需求数量三单元格点击变编辑框,保存成功后刷新并提示「请点击重新匹配库存」。

  • Step 1: api 签名放宽

shipping.api.ts :1205-1225 updateWorkspaceShippingNoticeLine 的 options 中 evidence/reason 改为可选(evidence?/reason?),未传时不带这两个字段。同步改 :1177 updateWorkspaceShippingNoticeFields 同构参数。

  • Step 2: 表格单元格改造

在 ShippingOrderReviewView.vue 的 prep 表格(:4952 行)把三个 <td> 的纯文本改为「文本 + 点击进入编辑」模式(普通编辑框,不抄下拉):

<td>
  <input
    v-if="editingLine?.snapshot_line_id === line.snapshot_line_id"
    v-model="editingLine.part_number"
    class="..."
    :disabled="inlineEditSaving"
    @keyup.enter="saveInlineEdit(line)"
    @keyup.esc="cancelInlineEdit"
  />
  <span v-else class="cursor-pointer" @click="startInlineEdit(line)">{{ line.part_number || '—' }}</span>
</td>

(reservation_id、required_qty 两个 td 同构;required_qty 用 type="number" 输入。)

script 区新增状态与方法(放在 :2792 附近的行级操作函数区):

/** 就地编辑状态:仅一行处于编辑态;保存走既有 update-notice-line 通道。 */
const editingLine = ref<{ snapshot_line_id: number; line_no: number; part_number: string; reservation_id: string; required_qty: string } | null>(null);
const inlineEditSaving = ref(false);

function startInlineEdit(line: { snapshot_line_id: number; line_no: number; part_number?: string | null; reservation_id?: string | null; required_qty?: string | null }) {
  editingLine.value = {
    snapshot_line_id: line.snapshot_line_id,
    line_no: line.line_no,
    part_number: String(line.part_number ?? ''),
    reservation_id: String(line.reservation_id ?? ''),
    required_qty: String(line.required_qty ?? ''),
  };
}

function cancelInlineEdit() { editingLine.value = null; }

async function saveInlineEdit(line: { snapshot_line_id: number }) {
  const draft = editingLine.value;
  if (!draft || inlineEditSaving.value) return;
  const patch: Record<string, string> = {};
  if (draft.part_number !== String(line.part_number ?? '')) patch.part_number = draft.part_number;
  if (draft.reservation_id !== String(line.reservation_id ?? '')) patch.reservation_id = draft.reservation_id;
  if (draft.required_qty !== String(line.required_qty ?? '')) patch.qty = draft.required_qty;
  if (!Object.keys(patch).length) { cancelInlineEdit(); return; }
  inlineEditSaving.value = true;
  try {
    await updateWorkspaceShippingNoticeLine(
      /* taskNo */ formalTaskDetail.value?.task_no ?? '',
      /* lineIndex */ draft.line_no - 1,
      patch,
      /* comment */ '',
      { expectedOrderDataVersion: formalTaskDetail.value?.order_data_version },
    );
    cancelInlineEdit();
    useMessage().success(t('chat.shippingOrderReview.inlineEdit.saved'));
    await loadFormalTaskDetail();
  } finally {
    inlineEditSaving.value = false;
  }
}

(taskNo/order_data_version 的实际取值字段以 formalTaskDetail 类型为准适配;useMessage/t 按该文件既有用法。失败提示走既有 HTTP 客户端 BusinessError 通道,不重复实现。)

禁用态:inventory_rpa_is_running(formalTaskDetail.ui_state.preparation 内字段,见类型 :1490-1497)为 true 时,startInlineEdit 直接 return 并提示 inlineEdit.busy。

  • Step 3: i18n 四语言

在 frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json 的 shippingOrderReview 子树下新增:

"inlineEdit": {
  "saved": "已保存,请点击「重新匹配库存」生效",
  "busy": "系统处理中,请稍后再修改"
}

zh-TW:已儲存,請點擊「重新匹配庫存」生效 / 系統處理中,請稍後再修改;en:Saved. Click "Re-match inventory" to apply / System is busy. Please try again later;th:บันทึกแล้ว กด "จับคู่สินค้าคงเหลือใหม่" เพื่อใช้งาน / ระบบกำลังประมวลผล โปรดลองอีกครั้งภายหลัง。

  • Step 4: 构建门禁

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/frontend" && npx vue-tsc -b --pretty false && npm run build Expected: 0 error

  • Step 5: 提交
git add frontend/src/features/chat/views/ShippingOrderReviewView.vue frontend/src/features/chat/api/shipping.api.ts frontend/src/locales
git commit -m "feat(shipping-notice): 通知准备匹配表支持履约字段就地编辑"

Task 6: 缺口复核入口修复(键错位 + 结案按钮 + 滚动锚)

Files:

  • Modify: backend/app/services/shipping_notice/line_inventory_match_projection.py(:472-508 后新增按 line_index 的加载器)
  • Modify: backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py(:821/:846 键修复)
  • Modify: frontend/src/features/chat/views/ShippingOrderReviewView.vue(结案按钮 + 滚动锚 :3823-3832)
  • Modify: frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json(结案文案)
  • Test: backend/tests/test_review_line_fulfillment_shortage_projection.py(新建)

Interfaces:

  • Consumes: 匹配事实行内 line_index;decide_review_line_fulfillment(既有 API POST /shipping-notice/order-review-cases/<case_no>/line-fulfillment/decide)。

  • Produces: line_fulfillment.has_shortage 正确 → hasInventoryIssues=True → open_shortage_review 动作可见;prep 表「更多操作」新增结案入口。

  • Step 1: 写失败测试(键错位)

创建 backend/tests/test_review_line_fulfillment_shortage_projection.py:

"""
tests/test_review_line_fulfillment_shortage_projection.py

用途:锁定行级履约投影的匹配事实关联(修复草稿行ID vs 快照行ID 键错位)。
依赖:pytest、order_review_fulfillment_decision_service、有效视图夹具。
逻辑:确认 Case + 短缺匹配事实下,投影必须报 has_shortage=True 且行级 is_shortage=True。
"""

from __future__ import annotations

from app import db
from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderReviewCase, ShippingOrderReviewDraft
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
    project_review_case_line_decisions,
)
from tests.test_effective_order_view import _seed_frozen_order


def test_line_fulfillment_has_shortage_with_match_facts(app):
    """修复键错位:草稿行经 _line_index 关联匹配事实,has_shortage 必须为真。"""
    with app.app_context():
        fixture = _seed_frozen_order()
        # 短缺事实:第 0 行 not_found、缺 10。
        db.session.add(ShippingNoticeLineInventoryMatch(
            task_id=fixture.order.id, snapshot_line_id=fixture.snap_lines[0].id,
            line_no=1, line_index=0, match_result='not_found', inventory_status='ready',
            required_qty='10', available_qty='0', shortage_qty='10',
            reservation_id='RSV-1', part_number='D4-A08AR12000002-', is_current=True,
        ))
        case = ShippingOrderReviewCase(
            case_no='SNRC-SHORTAGE-PROJ', run_id=911, unit_id=912, document_id=913,
            owner_user_id=fixture.user.id, status='confirmed', confirmed_task_id=fixture.order.id,
        )
        db.session.add(case)
        db.session.flush()
        db.session.add(ShippingOrderReviewDraft(
            case_id=case.id, draft_version=1, schema_version_id=fixture.snapshot.schema_version_id,
            header_values_json={}, lines_json=[{'draft_line_id': 'line-1', 'part_number': 'D4-A08AR12000002-'}],
        ))
        db.session.flush()
        case.current_draft_id = case.drafts[0].id if case.drafts else None
        db.session.flush()
        result = project_review_case_line_decisions(case)
        # 断言:修复前 has_shortage 恒 False(键错位);修复后为 True。
        assert result['has_shortage'] is True
        assert result['lines'][0]['is_shortage'] is True

(ShippingOrderReviewDraft 必填列以模型为准适配;current_draft 关系按 :128-130 post_update 语义先 flush 再回填 current_draft_id。)

  • Step 2: 运行确认失败

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_review_line_fulfillment_shortage_projection.py -v Expected: FAIL,has_shortage 为 False

  • Step 3: 实现后端键修复

(a) line_inventory_match_projection.py :508 后新增:

def load_current_match_facts_by_line_index(task_id: int) -> dict[int, dict[str, Any]]:
    """按 line_index 索引当前匹配事实(Case 履约投影专用)。

    核心逻辑:与 load_current_match_facts_by_task 同一查询;Case 草稿行只有
    _line_index 没有 snapshot_line_id,必须按行号索引才能关联上事实。
    """
    rows = (
        ShippingNoticeLineInventoryMatch.query
        .filter_by(task_id=int(task_id), is_current=True)
        .all()
    )
    return {
        int(row.line_index): serialize_match_fact(row)
        for row in rows
        if row.line_index is not None
    }

(serialize_match_fact 与查询结构照抄 :496-508 既有实现;不共享 g memo 亦可,或复用同款 memo。)

(b) order_review_fulfillment_decision_service.py :821 加载改双通道、:846 查找改行号:

    match_facts = load_current_match_facts_by_task(formal_ot.get('task_id'))
    from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_line_index
    match_facts_by_line = load_current_match_facts_by_line_index(int(formal_ot.get('task_id')))
        # [BE-键修复] 草稿行只有 _line_index;旧实现误用 draft_line_id 查 snapshot_line_id 键,恒 miss。
        line_index = draft_line.get('_line_index')
        fact = (
            match_facts_by_line.get(int(line_index))
            if line_index is not None else None
        )
  • Step 4: 运行确认通过 + 决定域回归

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

  • Step 5: 前端结案按钮 + 滚动锚

(a) ShippingOrderReviewView.vue prep 表「更多操作」td(:4952 行尾)追加结案按钮(与既有放行缺口按钮 openReleaseInventoryShortage 同款交互:弹原因输入):

<button
  v-if="formalPreparationLineAllows(line, 'close')"
  class="..."
  :title="t('chat.shippingOrderReview.lineActions.closeLine')"
  @click="openCloseLineDialog(line)"
>⨂</button>

script 区(放行按钮函数旁)新增:通过 activeCase.value.line_fulfillment.lines 按 snapshot_line_id(或 line_index)找到 draft_line_id,调用既有 line-fulfillment decide API:

async function confirmCloseLine(lineIndex: number, reason: string) {
  const caseNo = activeCase.value?.case_no;
  const target = (activeCase.value?.line_fulfillment?.lines || []).find(
    (item) => item.line_index === lineIndex,
  );
  if (!caseNo || !target?.draft_line_id) return;
  await closeReviewLineFulfillment(caseNo, target.draft_line_id, reason); // 既有/新增 api 封装,decision_code='close_unfulfillable'
  await loadFormalTaskDetail();
}

(api 层若无 close 封装,按 :2149 decide API 的既有调用模式加 decideReviewLineFulfillment(caseNo, draftLineId, decisionCode, reason);原因输入复用放行缺口的弹层模式。)

(b) 滚动锚 :3823-3832:hasFormalOt 分支的 review-order-lines-table 改为 review-fulfillment-prep-workspace(缺口语境的真实宿主)。

(c) i18n 四语言 chat.json shippingOrderReview.lineActions:

"closeLine": "结案(不再发货)",
"closeLineReason": "请填写结案原因",
"closeLineConfirm": "确认结案"

zh-TW:結案(不再發貨)/請填寫結案原因/確認結案;en:Close line (no shipment)/Enter a reason to close/Confirm close;th:ปิดบรรทัด (ไม่จัดส่ง)/กรอกเหตุผลเพื่อปิด/ยืนยันการปิด。

  • Step 6: 构建门禁 + 提交

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/frontend" && npx vue-tsc -b --pretty false && npm run build

git add backend/app/services/shipping_notice/line_inventory_match_projection.py backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py backend/tests/test_review_line_fulfillment_shortage_projection.py frontend/src/features/chat/views/ShippingOrderReviewView.vue frontend/src/locales
git commit -m "fix(shipping-notice): 修复缺口投影键错位并补齐结案入口"

Task 7: 文档同步与回归

Files:

  • Modify: docs/features/shipping-notice/technical.md(在「有效订单值视图与行结案豁免(2026-09-17)」小节后追加)

  • Modify: docs/funclist.md

  • Step 1: technical.md 追加小节

### 通知准备就地编辑与入口修复(2026-09-18)

**编辑权限状态制**:正式订单字段(含履约三要素 料号/预约号/数量)默认在
「Excel 未生成 + 无活动 Attempt」时可编辑(DEFAULT_EDITABLE_AFTER_TASK_CREATION=True,
Schema task_edit_policy 退化为反向锁);原因/证据不强制,审计链自动记录 old→new
(shipping_order_review_events / formal_task_field_edited)。通知准备匹配表三单元格
就地编辑 → 保存(order_data_version+1)→ 手动「重新匹配库存」生效。

**有效值消费面补全**:通知准备值列、预约注册(ensure_task_reservations)与核验比对
(record_inventory_verification)均改读有效订单值视图——修复编辑后重匹配必抛
RESERVATION_MISMATCH 的阻断;匹配结果列仍反映最近一轮匹配事实。

**缺口复核入口修复**:行级履约投影的匹配事实关联由 draft_line_id 改为 line_index
(修复 has_shortage 恒 False 导致入口被隐藏);prep 表新增行级结案入口,滚动锚指向
prep 工作区。**边界**:Excel ready 后编辑硬冻结;通知已存在后编辑不重物化通知行
(可达窗口窄,声明边界);done_line_report/OT 通知列表投影仍显示冻结原值(历史定格语义)。
  • Step 2: funclist.md 追加一行
- 通知准备界面支持料号/预约号/数量就地编辑(保存后手动重新匹配库存生效);缺口复核入口与行结案按钮修复可见;编辑权限为状态制(Excel 生成前可改)。
  • Step 3: 后端定向回归 + 前端构建

Run: cd "D:/Workspace/HxProjects/hxops/.worktrees/editfeat/backend" && ./.venv/Scripts/python.exe -m pytest tests/test_effective_order_view.py tests/test_reservation_effective_view.py tests/test_ui_state_effective_values.py tests/test_review_line_fulfillment_shortage_projection.py tests/test_shipping_schema_edit_policy.py tests/test_shipping_review_formal_task_edit.py tests/test_shipping_formal_task_edit_audit.py tests/test_shipping_stp_phase4_line_inventory_match.py tests/test_shipping_review_line_fulfillment_decision.py tests/test_line_closure_gate_sync.py tests/test_reservation_effective_view.py -q Run: cd frontend && npx vue-tsc -b --pretty false && npm run build Expected: 全绿(前端 0 error)。域内回归为主口径(与用户确认的回归策略一致)。

  • Step 4: 手工走查清单(并入交付说明)
  1. 卡匹配订单:匹配表改料号(去尾部 -)→ 保存 → 值列立即显示新值 → 点「重新匹配库存」→ 匹配/核验通过(不再 RESERVATION_MISMATCH)。
  2. 改需求数量 → 保存 → 重匹配 → 缺口数量按新值计算。
  3. 系统处理中(RPA 运行)时编辑框不可进入。
  4. 缺口状态订单:订单复核工作台出现缺口复核入口(open_shortage_review 可见可点,滚动到 prep 工作区);prep 表行级「结案」可用 → 结案后整单不再被该行阻断。
  5. Excel 生成后:编辑框不可进入(冻结)。
  • Step 5: 提交
git add docs/features/shipping-notice/technical.md docs/funclist.md
git commit -m "docs(shipping-notice): 补充就地编辑与入口修复语义文档"

Self-Review(已执行)

  1. 覆盖度:清单 6 项 ↔ 任务:闸门翻转+原因可选=T2;值列=T4;预约/核验=T3;编辑框+样式=i18n=T5;Decimal=T1;面板两 bug=T6(键修复+结案按钮+滚动锚;死组件 ReviewInventoryIssueList 明确不挂载——其职能由 prep 表内嵌入口承接,清理列后续);文档回归=T7。✔
  2. 占位符:T2 Step1 的两个测试改写给出了断言语义+「照抄原夹具」指引(原夹具代码未在侦察中展开,属于对实现者的定向指令而非 TBD);T3/T4 的适配注记同性质。其余步骤均有完整代码。✔(有意为之的例外已标注。)
  3. 类型一致性:effective_line_facts_for_notice(owner)(既有,T3/T4 消费一致);load_current_match_facts_by_line_index(task_id)(T6 定义与使用一致);前端 updateWorkspaceShippingNoticeLine(taskNo, lineIndex, patch, comment, options)(既有签名,T5 传参对齐);i18n 键名 T5/T6 与 Step 中引用一致。✔
  4. 已知风险:T2 契约翻转的测试改动面依赖 grep 兜底(步骤内含);T3 的 ensure_task_reservations 分支结构需先通读再落改(语义表已给);T4 _build_stage_context 函数名/返回形状按实际适配;T6 结案按钮的 draft_line_id 解析依赖 T6 键修复后的投影行(有 snapshot_line_id/line_index 可依)。