feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理

清理废弃的ShippingCase相关代码与依赖,统一使用ShippingNotice直接关联客户数据。调整库存网关依赖规则,支持仅对库存满足或已人工放行的订单行生成发货Excel,实现滚动履约逻辑。
This commit is contained in:
hugo committed 2026-08-26 02:47:07 +08:00
1 parent 7cfd5d167e
commit 1e5aedb9ed
235 files changed
+11394 -9613

No files matched your search

@@ -0,0 +1,182 @@
# 延后发货通知单号与库存结果重读 Implementation Plan
> **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 成功生成时为既有 `ShippingNotice` 分配业务单号,并提供不触发 RPA 的库存结果重读 Gate 动作。
**Architecture:** `ShippingNotice` 继续作为建单、库存和匹配阶段的内部流程载体;新 Notice 在 Excel 前保持 `business_no=None`。首次 Excel Artifact 生成时,同一事务内锁定明细归属、生成 Artifact 并为该 Notice 分配编号。库存重读复用既有快照查询、身份校验、挂接和库存加载函数,不写 RPA trigger。
**Tech Stack:** Flask、SQLAlchemy 2.0、Alembic、pytest、Vue 3、TypeScript、Vitest。
## Global Constraints
- 不新增发货通知单实体、平行表或第二套编号体系。
- 一个 Notice 可通过既有 Reservation/Artifact 明细关联覆盖多条订单明细;有效 Reservation 不得重复归属其他 Notice。
- 新 Notice 仅在首个 Excel 成功生成的事务中分配 `business_no`;历史数据兼容读取不变。
- `reload_inventory_result` 不得调用 `retry_rpa`、写 trigger 或新建 RPA Attempt。
- 新增前端文案同步 zh-CN、zh-TW、en、th 四语言;后端业务错误遵循 `AppError` envelope。
- 保留并避开工作区与本需求无关的未提交改动。
---
### Task 1: 延后 Notice 编号至首个 Excel 生成
**Files:**
- Modify: `backend/app/services/shipping_notice/customer_identity_gate.py`
- Modify: `backend/app/services/shipping_notice/export.py`
- Modify: `backend/app/services/shipping_notice/business_numbering_service.py`
- Modify: `backend/tests/test_shipping_customer_identity_gate.py`
- Modify: `backend/tests/test_shipping_excel_template.py`
**Interfaces:**
- Consumes: `confirm_task_customer(task, customer_id, actor_id)`、`generate_shipment_excel(task)`。
- Produces: 客户确认后 `task.business_no is None`;首个成功 Artifact 创建后 `task.business_no` 非空且可由既有货代接口使用。
- [ ] **Step 1: 写入失败测试**
```python
def test_confirm_customer_does_not_assign_business_number(app):
with app.app_context():
task, customer, user = _seed_task()
confirmed = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
assert confirmed.customer_id == customer.id
assert confirmed.business_no is None
def test_first_export_assigns_notice_business_number(app, tmp_path):
with app.app_context():
task = _seed_exportable_task_without_business_number(tmp_path)
artifact = generate_shipment_excel(task)
assert task.business_no is not None
assert artifact.task_id == task.id
```
- [ ] **Step 2: 验证失败原因正确**
Run: `cd backend; pytest tests/test_shipping_customer_identity_gate.py::test_confirm_customer_does_not_assign_business_number tests/test_shipping_excel_template.py::test_first_export_assigns_notice_business_number -q`
Expected: FAIL,因为客户确认路径仍分配编号,或导出路径未分配编号。
- [ ] **Step 3: 最小实现**
```python
# customer_identity_gate.py
# 仅写入客户确认事实;不得调用 assign_notice_business_number。
# export.py,在首个 Artifact 持久化的同一事务中:
if not task.business_no:
assign_notice_business_number(task)
```
保留已有 `assert_notice_has_no_export_artifact` 约束,确保同一 Notice 的首个 Artifact 是唯一编号触发点;分批导出必须由既有波次服务创建新 Notice,禁止在同一 Notice 重生成第二个有效 Artifact。
- [ ] **Step 4: 验证通过**
Run: `cd backend; pytest tests/test_shipping_customer_identity_gate.py tests/test_shipping_business_numbering.py tests/test_shipping_excel_template.py -q`
Expected: PASS。
### Task 2: 增加无 RPA 的库存结果重读 Gate 动作
**Files:**
- Modify: `backend/app/services/shipping_notice/process_gate_contract.py`
- Modify: `backend/app/services/shipping_notice/process_gate_executor.py`
- Modify: `backend/app/services/shipping_notice/process_gate_projection.py`
- Modify: `backend/app/services/shipping_notice/error_explainability_contract.py`
- Test: `backend/tests/test_shipping_process_gate_contract.py`
- Test: `backend/tests/test_shipping_process_gate_retry_cap.py`
**Interfaces:**
- Consumes: `reload_inventory_result`(`inventory_preparation` Gate 的用户动作)。
- Produces: 命中有效快照时挂接并加载库存;无快照时返回 `blocked_retryable`,不写 RPA trigger/Attempt。
- [ ] **Step 1: 写入失败测试**
```python
def test_inventory_preparation_allows_reload_without_rpa_trigger():
assert action_belongs_to_gate(
gate_code='inventory_preparation', action_code='reload_inventory_result',
) is True
def test_reload_inventory_result_reuses_snapshot_without_new_rpa_attempt(app, monkeypatch):
task, execution, snapshot = _seed_timeout_task_with_matching_snapshot()
result = _dispatch_gate_action(execution, 'reload_inventory_result')
assert result['outcome'] == 'passed'
assert task.inventory_snapshot_id == snapshot.id
assert _rpa_attempt_count(task) == 0
```
- [ ] **Step 2: 验证失败原因正确**
Run: `cd backend; pytest tests/test_shipping_process_gate_contract.py -q`
Expected: FAIL,因为 `reload_inventory_result` 未注册为 Gate 动作。
- [ ] **Step 3: 最小实现**
```python
def _handle_reload_inventory_result(*, execution, gate, payload):
# 使用 _try_reuse_inventory_snapshot 的查询、身份校验与库存加载行为;
# 不设置 mode='retry_rpa',不调用 ensure_inventory_via_rpa。
response = ensure_inventory({**_task_payload(execution, payload), 'mode': 'auto'})
return _tool_outcome(action_code='reload_inventory_result', response=response, ...)
```
当 `inventory_preparation` 的原因是 RPA 超时/耗尽时,投影将 `reload_inventory_result` 作为主动作;`retry_inventory_preparation` 作为明确的“重新获取库存(重新运行 RPA)”替代动作。
- [ ] **Step 4: 验证通过**
Run: `cd backend; pytest tests/test_shipping_process_gate_contract.py tests/test_shipping_process_gate_retry_cap.py tests/test_shipping_notice_inventory_rpa_workflow.py -q`
Expected: PASS。
### Task 3: 工作台文案、投影与回归验证
**Files:**
- Modify: `frontend/src/locales/zh-CN/workspace.json`
- Modify: `frontend/src/locales/zh-TW/workspace.json`
- Modify: `frontend/src/locales/en/workspace.json`
- Modify: `frontend/src/locales/th/workspace.json`
- Modify: `frontend/src/features/shipping-progress/actionPresentation.ts`
- Modify: `frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.spec.ts`
- Modify: `docs/features/shipping-notice/technical.md`
- Modify: `docs/funclist.md`
**Interfaces:**
- Consumes: 后端下发的 `reload_inventory_result` 和 Artifact 成功后才出现的 Notice `business_no`。
- Produces: 主按钮显示“重新读取库存结果”;备用按钮明确为“重新获取库存(重新运行 RPA)”;Excel 前不展示单号。
- [ ] **Step 1: 写入失败测试**
```ts
it('renders reload result as the timeout primary action', async () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: { primaryAction: { code: 'reload_inventory_result' } },
global: { plugins: [i18n] },
});
expect(wrapper.text()).toContain('重新读取库存结果');
});
```
- [ ] **Step 2: 验证失败原因正确**
Run: `cd frontend; npm run test -- ReviewCurrentProcessingCard.spec.ts`
Expected: FAIL,因为该动作尚无前端展示映射或翻译。
- [ ] **Step 3: 最小实现**
新增四语言 label,复用动作展示注册表;仅更改此动作及现有 RPA 重试动作的用户可见标签。更新技术文档与功能清单的单号时机、明细归属和库存重读说明。
- [ ] **Step 4: 验证通过**
Run: `cd frontend; npm run test -- ReviewCurrentProcessingCard.spec.ts; npm run build`
Expected: PASS。
## Plan Self-Review
- 覆盖规格:Task 1 覆盖延后编号;Task 2 覆盖无 RPA 快照读取与超时主动作;Task 3 覆盖 UI、四语言与文档。
- 未新增实体、编号表或新的 RPA 流程;复用现有 Notice、Artifact、Reservation、快照和 Gate 机制。
- 计划未采用未定义的跨域服务;实际代码以现有 `ensure_inventory(mode='auto')` 作为库存快照复用入口。
@@ -0,0 +1,124 @@
# Reservation Vendor Comments Anchor Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 已标注 Reservation ID 专区的订单模板,跨页在 `Vendor Comments` 与首次 `Terms and Condition(s)` 之间确定性读取 Reservation,而不依赖固定页码或坐标。
**Architecture:** `reservation_id_region` 继续作为该能力的显式启用开关,保留原几何数据以兼容历史草稿/画布,但运行时不再消费其 `page_no/region`。运行时为已启用模板补齐全部 PDF 页的坐标证据,以视觉阅读顺序定位起止锚点,截取边界内文本,再复用现有 Reservation 候选解析、行号归属和冲突 Review 契约。
**Tech Stack:** Flask、Python、PDF/OCR 坐标证据、pytest。
## Global Constraints
- 只对包含 `definition.reservation_id_region` 的已选中模板启用;未标注模板不得全文扫描或改变结果。
- 起点为首次 `Vendor Comments`;终点为其后首次 `Terms and Condition` 或 `Terms and Conditions`,匹配忽略大小写、冒号和复数差异。
- 区块允许跨页;不存在起点、终点或二者顺序异常时不猜值,稳定进入 Review。
- Reservation 仍仅接受带 `Reservation` 标签的 5 位或 10 位纯数字;行号、冲突和越界处理复用 `reservation_region.py`。
- 原 PDF 不可变;页坐标只通过 `ensure_on_demand_coordinate_evidence(..., page_nos=None)` 取得;不新增依赖、表结构或 Dify 改动。
---
### Task 1: Vendor Comments 区块提取契约
**Files:**
- Modify: `backend/app/services/shipping_notice/reservation_region.py`
- Test: `backend/tests/test_shipping_notice_reservation_id.py`
**Interfaces:**
- Produces `extract_reservation_from_vendor_comments_pages(pages: list[tuple[int, list[dict[str, Any]]]]) -> tuple[list[dict[str, object]], str | None]`。
- `str | None` 是 `None`、`vendor_comments_anchor_missing` 或 `terms_and_conditions_anchor_missing`;调用方据此决定 Review。
- [ ] **Step 1: Write failing tests**
```python
def test_vendor_comments_window_crosses_pages_and_stops_at_first_terms_heading():
candidates, reason = extract_reservation_from_vendor_comments_pages([
(1, _glyph_lines('Vendor Comments:', 'Reservation#33008')),
(2, _glyph_lines('Reservation#3000098851 for line#1', 'Terms and Conditions:', 'Reservation#99999')),
])
assert reason is None
assert [item['value'] for item in candidates] == ['33008', '3000098851']
```
- [ ] **Step 2: Verify RED**
Run: `cd backend; .\\.venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_notice_reservation_id.py -k vendor_comments`
Expected: FAIL because the extraction function is not defined.
- [ ] **Step 3: Implement minimal extractor**
Implement a pure helper in `reservation_region.py` that renders each page through existing `visual_text_lines`, scans all page lines in page-number order, begins after the first normalized `Vendor Comments` heading, ends before the first later normalized `Terms and Condition(s)` heading, and passes only joined window lines to `extract_reservation_from_region_text`. Do not read coordinates, assets, or database state in this helper.
- [ ] **Step 4: Verify GREEN**
Run: `cd backend; .\\.venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_notice_reservation_id.py`
Expected: PASS, including existing ID format, line mapping and conflict tests.
### Task 2: Production routing and fail-closed boundary result
**Files:**
- Modify: `backend/app/services/shipping_notice/order_extraction_workflow.py`
- Test: `backend/tests/test_order_extraction_pdf_po_split.py`
**Interfaces:**
- Replaces `_reservation_region_candidates(raw_profile, layout)` fixed-page geometry reading with a result containing `candidates` and optional `reason`.
- Existing `_build_approved_profile_order_result(..., reservation_region_candidates=...)` remains the single application point for values.
- [ ] **Step 1: Write failing integration tests**
```python
def test_enabled_reservation_region_reads_vendor_comments_across_pages():
result = _reservation_region_candidates(raw_profile=_profile_with_region(), layout=_two_page_layout())
assert result['reason'] is None
assert result['candidates'][0]['value'] == '33008'
def test_profile_without_reservation_region_does_not_scan_vendor_comments():
result = _reservation_region_candidates(raw_profile={'definition': {}}, layout=_two_page_layout())
assert result == {'candidates': [], 'reason': None}
```
- [ ] **Step 2: Verify RED**
Run: `cd backend; .\\.venv\\Scripts\\python.exe -m pytest -q tests/test_order_extraction_pdf_po_split.py -k reservation_region`
Expected: FAIL because the fixed-page reader returns a list and does not expose dynamic cross-page candidates.
- [ ] **Step 3: Implement minimal routing change**
For a Profile with `reservation_id_region`, call `ensure_on_demand_coordinate_evidence(document, layout, page_nos=None)` before matching/reading. In `_reservation_region_candidates`, order available `page_glyphs` numerically, call Task 1 helper, and return `{'candidates': ..., 'reason': ...}`. If a boundary reason exists, preserve it as `reservation_region_status='needs_review'` and `reservation_region_review_reasons=[reason]`; do not write Reservation fields and do not allow STP. No special behavior for profiles without the key.
- [ ] **Step 4: Verify GREEN**
Run: `cd backend; .\\.venv\\Scripts\\python.exe -m pytest -q tests/test_order_extraction_pdf_po_split.py tests/test_shipping_notice_reservation_id.py`
Expected: PASS; dynamic scan works across page breaks, first Terms heading terminates the window, missing boundaries become Review, and unmarked templates do not scan.
### Task 3: Documentation and final verification
**Files:**
- Modify: `docs/features/shipping-notice/technical.md`
- Modify: `docs/funclist.md`
- [ ] **Step 1: Document the enabled-template behavior**
Add one concise technical section: Reservation ID 专区 is an opt-in semantic parser; it scans from `Vendor Comments` to the first `Terms and Condition(s)` in reading order across pages; geometry remains annotation evidence only; missing/ambiguous boundaries and value conflicts require Review. State that unmarked templates are unchanged.
- [ ] **Step 2: Update feature list**
Add the Reservation 专区 dynamic-anchor behavior to the existing shipping order-template entry without creating a parallel feature.
- [ ] **Step 3: Run verification**
Run: `cd backend; .\\.venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_notice_reservation_id.py tests/test_order_extraction_pdf_po_split.py`
Run: `git diff --check`
Expected: all targeted tests PASS and no whitespace errors. If frontend files are unchanged, no frontend build is required.
## Self-Review
- The plan covers opt-in gating, cross-page reading, first-stop semantics, strict Reservation validation, Review failure paths, unmarked-template isolation, tests and documentation.
- It creates no database migration, dependency, Dify configuration or profile data rewrite.
- Helper and routing interfaces have explicit names and return types; all listed behavior is testable.