docs(shipping-notice): 同步状态契约与工作台设计
This commit is contained in:
1 parent
7a9fac2f8a
commit
6787216ad0
14 files changed
+1584
-999
No files matched your search
@@ -1,176 +0,0 @@
|
||||
# Shipping Notice Five-Stage Lifecycle 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:** Make `接收解析 -> 订单复核 -> 通知准备 -> 货代上传 -> 通知完成` the only user-visible Shipping Notice lifecycle, where completion means verifiable freight-upload success.
|
||||
|
||||
**Architecture:** Keep Process Gate, Intake, Run/Unit, upload attempt and technical progress as execution facts. Extend the existing shared read-model projection with `freight_upload`; inject `upload_complete` only when the canonical success predicate confirms task status, every reservation and an audit-backed succeeded upload attempt. API consumers receive `lifecycle_nodes`; `four_stage_nodes` remains a one-release compatibility alias.
|
||||
|
||||
**Tech Stack:** Flask, SQLAlchemy, pytest, Vue 3, TypeScript, Vue I18n, Vitest.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Define the server-side lifecycle and success predicate
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/lifecycle_projection.py`
|
||||
- Modify: `backend/app/services/shipping_notice/ui_state.py`
|
||||
- Modify: `backend/app/services/shipping_notice/process_gate_contract.py`
|
||||
- Test: `backend/tests/test_shipping_notice_ui_state.py`
|
||||
|
||||
- [ ] **Step 1: Add failing assertions for the new stage and completion boundary**
|
||||
|
||||
```python
|
||||
assert state['lifecycle_stage'] == 'freight_upload'
|
||||
assert [entry['code'] for entry in state['lifecycle_entries']][-2:] == [
|
||||
'freight_upload', 'upload_complete',
|
||||
]
|
||||
assert completed_state['lifecycle_stage'] == 'upload_complete'
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the focused UI-state test**
|
||||
|
||||
Run: `cd backend; pytest -q tests/test_shipping_notice_ui_state.py`
|
||||
Expected: failing assertions because the current implementation has four lifecycle stages.
|
||||
|
||||
- [ ] **Step 3: Implement one canonical predicate and five-stage projection**
|
||||
|
||||
```python
|
||||
def has_verified_upload_success(task: ShippingNotice) -> bool:
|
||||
return (
|
||||
task.upload_status == 'uploaded'
|
||||
and reservations_are_uploaded(task)
|
||||
and has_succeeded_upload_attempt(task)
|
||||
)
|
||||
|
||||
if has_verified_upload_success(task):
|
||||
lifecycle_stage = 'upload_complete'
|
||||
elif gate_code in LIFECYCLE_STAGE_BY_GATE:
|
||||
lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code]
|
||||
```
|
||||
|
||||
Map `freight_upload_rpa`, `manual_upload_handoff`, and all upload-pending/failure/unknown reasons to `freight_upload`. Map only a verified success to `upload_complete`; update Gate `ui_placement.target_surface` to `freight_upload`.
|
||||
|
||||
- [ ] **Step 4: Re-run the focused UI-state test**
|
||||
|
||||
Run: `cd backend; pytest -q tests/test_shipping_notice_ui_state.py`
|
||||
Expected: PASS.
|
||||
|
||||
### Task 2: Evolve batch projection without breaking callers
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/shipping_processing_projection.py`
|
||||
- Modify: `backend/tests/test_shipping_processing_projection.py`
|
||||
- Modify: `backend/tests/test_shipping_processing_projection_stage4.py`
|
||||
|
||||
- [ ] **Step 1: Add failing batch-node assertions**
|
||||
|
||||
```python
|
||||
assert [node['code'] for node in payload['lifecycle_nodes']] == [
|
||||
'intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete',
|
||||
]
|
||||
assert payload['four_stage_nodes'] == payload['lifecycle_nodes']
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Implement `lifecycle_nodes` and compatibility alias**
|
||||
|
||||
```python
|
||||
lifecycle_nodes = _batch_lifecycle_nodes(work_items)
|
||||
payload['lifecycle_nodes'] = lifecycle_nodes
|
||||
payload['four_stage_nodes'] = lifecycle_nodes # deprecated compatibility field
|
||||
```
|
||||
|
||||
Use the shared success predicate when deriving an item lifecycle so technical `completed`, a PDF candidate, a reference number, cancellation, or archive cannot make an item complete.
|
||||
|
||||
- [ ] **Step 3: Run the projection tests**
|
||||
|
||||
Run: `cd backend; pytest -q tests/test_shipping_processing_projection.py tests/test_shipping_processing_projection_stage4.py tests/test_shipping_projection_cross_surface.py`
|
||||
Expected: PASS.
|
||||
|
||||
### Task 3: Make all frontend surfaces consume five lifecycle stages
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/src/features/chat/types/shipping.api.types.ts`
|
||||
- Modify: `frontend/src/features/chat/shipping/shippingStepper.ts`
|
||||
- Modify: `frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.vue`
|
||||
- Modify: `frontend/src/features/chat/views/ShippingOrderReviewView.vue`
|
||||
- Modify: `frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.vue`
|
||||
- Modify: `frontend/src/features/shipping-progress/components/WorkbenchProgressGrouped.vue`
|
||||
- Test: `frontend/src/features/chat/shipping/shippingStepper.spec.ts`
|
||||
- Test: `frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts`
|
||||
- Test: `frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts`
|
||||
|
||||
- [ ] **Step 1: Add failing five-stage type and rendering tests**
|
||||
|
||||
```ts
|
||||
expect(resolveShippingWorkflowSteps({ ui_state: { steps } })).toHaveLength(5)
|
||||
expect(wrapper.text()).toContain('货代上传')
|
||||
expect(wrapper.text()).toContain('通知完成')
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Update shared types and Stepper**
|
||||
|
||||
Add `'freight_upload'` to `LifecycleWorkbenchStage`, stage-node DTOs and the five label-key array. Prefer `lifecycleNodes`; retain the old field only as an API fallback.
|
||||
|
||||
- [ ] **Step 3: Split the lifecycle workbench surfaces**
|
||||
|
||||
`freight_upload` hosts Excel download, RPA retry/poll, manual evidence registration and unknown-result reconciliation. `upload_complete` becomes read-only success evidence: uploaded time, freight receipt/reference, succeeded attempt and reservation summary. Do not move action authorization into the frontend.
|
||||
|
||||
- [ ] **Step 4: Ensure polling does not stop at freight-upload**
|
||||
|
||||
Keep polling while `lifecycleStage === 'freight_upload'`; stop only after verified `upload_complete`, cancellation, archive, or explicit terminal failure.
|
||||
|
||||
- [ ] **Step 5: Run focused frontend tests**
|
||||
|
||||
Run: `cd frontend; npm run test:unit -- shippingStepper.spec.ts ShippingOrderReviewView.spec.ts ShippingConversationProcessingCard.spec.ts`
|
||||
Expected: PASS.
|
||||
|
||||
### Task 4: Synchronize i18n and documentation
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/src/locales/zh-CN/chat.json`
|
||||
- Modify: `frontend/src/locales/zh-TW/chat.json`
|
||||
- Modify: `frontend/src/locales/en/chat.json`
|
||||
- Modify: `frontend/src/locales/th/chat.json`
|
||||
- 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: `docs/demand.md`
|
||||
- Modify: `docs/tec.md`
|
||||
- Modify: `docs/funclist.md`
|
||||
- Modify: `docs/features/shipping-notice/technical.md`
|
||||
- Modify: `docs/features/shipping-notice/business.md`
|
||||
|
||||
- [ ] **Step 1: Add all four-language stage and work-surface labels**
|
||||
|
||||
Add `freightUpload` and descriptions for upload in progress, manual upload pending, failure, and unknown result. Retain `uploadComplete` text as `通知完成`; its description must require verified success.
|
||||
|
||||
- [ ] **Step 2: Update the authoritative business and technical contracts**
|
||||
|
||||
Replace four-stage wording with the five-stage order. Document the single success predicate, unknown-result handling, `lifecycle_nodes` compatibility period, and the rule that completed lists/statistics use verified success only.
|
||||
|
||||
- [ ] **Step 3: Validate locale JSON**
|
||||
|
||||
Run: `Get-ChildItem frontend/src/locales/*/{chat,workspace}.json | ForEach-Object { Get-Content -Raw $_ | ConvertFrom-Json | Out-Null }`
|
||||
Expected: no output and exit code 0.
|
||||
|
||||
### Task 5: Full verification
|
||||
|
||||
**Files:**
|
||||
- Verify all modified files.
|
||||
|
||||
- [ ] **Step 1: Run focused backend regression**
|
||||
|
||||
Run: `cd backend; pytest -q tests/test_shipping_notice_ui_state.py tests/test_shipping_upload_attempt.py tests/test_shipping_manual_upload_evidence.py tests/test_shipping_upload_unknown_state.py tests/test_shipping_processing_projection.py tests/test_shipping_processing_projection_stage4.py tests/test_shipping_projection_cross_surface.py`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 2: Build frontend**
|
||||
|
||||
Run: `cd frontend; npm run build`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 3: Check diff integrity**
|
||||
|
||||
Run: `git diff --check; git status --short`
|
||||
Expected: no whitespace errors; status lists only the planned files plus pre-existing user changes.
|
||||
@@ -1,264 +0,0 @@
|
||||
# Shipping Profile Anchor Frame 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:** 让坐标 Profile 能在同一稳定版式因动态内容导致主表纵向平移时,使用冻结的锚点坐标框架完成确定性匹配和取值,而不影响未启用该能力的模板。
|
||||
|
||||
**Architecture:** 在现有 `OrderCoordinateProfile` 中增加可选的扁平 `coordinate_model` 声明(`type`、`anchors`、`max_translate_x`、`max_translate_y`)。matcher 从当前 Layout 的唯一锚点和主表结构计算受限的平移变换;同一变换贯穿表头观测、主表定位、订单头字段和值框、订单行坐标重建,禁止建立第二套偏移估算机制。
|
||||
|
||||
**Tech Stack:** Flask、Pydantic、SQLAlchemy JSON Profile、pytest、Vue 3、TypeScript、Vue I18n、Vitest。
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 原 PDF 是不可变事实;匹配和解析所需的页级坐标必须通过 `ensure_on_demand_coordinate_evidence()` 获取。
|
||||
- 未声明 `coordinate_model.type = anchor_frame` 的 Profile 必须逐位保持现有 matcher、取值、阈值和候选排序行为。
|
||||
- 不允许按订单号、客户名、文件名或固定偏移量写代码;不建立按 PDF 的坐标变体。
|
||||
- 仅允许平移;锚点不存在、不唯一、位移超过模板上限、关键结构冲突或多个 Profile 合格时必须 `review_required`。
|
||||
- Schema 是唯一业务字段契约;Dify 不参与模板选择、坐标变换或正式值取值。Dify 配置由用户维护,本项目仅在收尾文档说明其边界。
|
||||
- 不改数据库表结构、不新增依赖、不修改其他 Profile 数据;FOX MX Profile 现版数据在后端能力通过回归后再单独受控更新。
|
||||
|
||||
---
|
||||
|
||||
### Task 1: 冻结 Profile 契约与变换审计输出
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/document_layout/order_profile.py`
|
||||
- Modify: `backend/app/services/shipping_notice/document_layout/order_profile_matcher.py`
|
||||
- Test: `backend/tests/test_shipping_order_profile_matcher.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces `CoordinateModel` / `AnchorFrameCoordinateModel`,作为 `OrderCoordinateProfile.coordinate_model`。
|
||||
- Produces `CoordinateTransform`,包含 `status`、`translate_x`、`translate_y`、`anchor_ids`、`reason_codes`;仅含配置身份与数值,不含正文。
|
||||
- Extends `ProfileMatchCandidate` with optional `coordinate_transform`.
|
||||
|
||||
- [ ] **Step 1: 写入失败用例**
|
||||
|
||||
```python
|
||||
def test_anchor_frame_matches_same_structure_after_bounded_vertical_translation():
|
||||
profile = _with_signature(_profile('PO_A', coordinate_model={
|
||||
'type': 'anchor_frame',
|
||||
'anchors': [{'anchor_id': 'title', 'text': 'PURCHASE ORDER', 'region': {'x0': .1, 'y0': .05, 'x1': .9, 'y1': .15}}],
|
||||
'max_translate_x': .01, 'max_translate_y': .04,
|
||||
}), _layout())
|
||||
result = match_frozen_coordinate_profiles(profiles=[profile], layout=_translated_layout(.03))
|
||||
assert result.status == 'unique_match'
|
||||
assert result.candidates[0].coordinate_transform['translate_y'] == .03
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 验证 RED**
|
||||
|
||||
Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_order_profile_matcher.py -k anchor_frame`
|
||||
|
||||
Expected: FAIL,因为 Profile 契约尚不接受 `coordinate_model`,且 matcher 未输出变换。
|
||||
|
||||
- [ ] **Step 3: 最小实现**
|
||||
|
||||
```python
|
||||
class AnchorFrameCoordinateModel(OrderProfileModel):
|
||||
type: Literal['anchor_frame']
|
||||
anchors: list[AnchorRule] = Field(min_length=1, max_length=4)
|
||||
max_translate_x: float = Field(default=.03, ge=0, le=.15)
|
||||
max_translate_y: float = Field(default=.06, ge=0, le=.20)
|
||||
|
||||
class CoordinateModel(OrderProfileModel):
|
||||
type: Literal['legacy', 'anchor_frame'] = 'legacy'
|
||||
anchor_frame: AnchorFrameCoordinateModel | None = None
|
||||
```
|
||||
|
||||
在 matcher 中仅当 `anchor_frame` 明确启用时从唯一静态锚点计算一致的 X/Y 平移;超界、缺失、歧义或多个锚点不一致必须为硬失败原因。对当前观察表头和主表 bbox 应用该平移后才评分;`legacy` 路径不改。
|
||||
|
||||
- [ ] **Step 4: 验证 GREEN 与旧逻辑回归**
|
||||
|
||||
Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_order_profile_matcher.py`
|
||||
|
||||
Expected: PASS;新增用例覆盖受限平移、缺锚点、歧义锚点、超界平移和 legacy 不变。
|
||||
|
||||
### Task 2: 让已选变换贯穿 Profile 行重建
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/order_extraction_workflow.py`
|
||||
- Modify: `backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py`
|
||||
- Test: `backend/tests/test_shipping_coordinate_table_reconstruction.py`
|
||||
- Test: `backend/tests/test_shipping_generic_order_gate.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes `ProfileMatchResult` 中唯一选中 Profile 的 `coordinate_transform`。
|
||||
- Extends `reconstruct_coordinate_profile_rows(..., coordinate_transform: dict | None = None)`。
|
||||
- Produces仅以同一运行时平移投影后的表区/行区重建结果。
|
||||
|
||||
- [x] **Step 1: 写入失败用例**
|
||||
|
||||
```python
|
||||
def test_reconstruction_uses_selected_anchor_frame_translation_for_all_subrows():
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_translated_rows(.03), table_bbox=_page_bbox(),
|
||||
table_region=_legacy_region(), line_layouts=_layouts(),
|
||||
coordinate_transform={'status': 'applied', 'translate_x': 0, 'translate_y': .03},
|
||||
)
|
||||
assert rows[0].fields['customer_po_line_no'] == '00010'
|
||||
```
|
||||
|
||||
- [x] **Step 2: 验证 RED**
|
||||
|
||||
Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_coordinate_table_reconstruction.py -k anchor_frame`
|
||||
|
||||
Expected: FAIL,因为重建函数没有接收或应用运行时变换。
|
||||
|
||||
- [x] **Step 3: 最小实现**
|
||||
|
||||
为坐标重建增加仅限 `status=applied` 的平移投影;校验平移数字有限且投影框仍在页内,非法变换返回现有的不可重建结果。工作流必须从共同 matcher 的唯一结果传递同一 `coordinate_transform`,不能重新计算、不能按 raw table 猜测偏移。
|
||||
|
||||
- [x] **Step 4: 验证 GREEN 与路由门禁**
|
||||
|
||||
Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_coordinate_table_reconstruction.py tests/test_shipping_generic_order_gate.py`
|
||||
|
||||
Expected: PASS;缺失/非法变换保持 `coordinate_evidence_unavailable → review_required`,其他 Profile 路由不变。
|
||||
|
||||
### Task 3: 管理端声明与复核端审计展示
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/src/features/admin/types/shipping-order-document-profile.types.ts`
|
||||
- Modify: `frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue`
|
||||
- Modify: `frontend/src/features/chat/types/shipping.api.types.ts`
|
||||
- Modify: `frontend/src/features/chat/components/shipping-review/ReviewProfileMatchPanel.vue`
|
||||
- Modify: `frontend/src/locales/zh-CN/chat.json`
|
||||
- Modify: `frontend/src/locales/zh-TW/chat.json`
|
||||
- Modify: `frontend/src/locales/en/chat.json`
|
||||
- Modify: `frontend/src/locales/th/chat.json`
|
||||
- Test: `frontend/src/features/chat/components/shipping-review/ReviewProfileMatchPanel.spec.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Admin payload accepts optional `coordinate_model`,默认 `legacy`,只有管理员显式确认时才提交 `anchor_frame`。
|
||||
- Review DTO exposes `coordinate_transform` only for the selected/current candidate and reason codes only.
|
||||
|
||||
- [x] **Step 1: 写入失败的前端展示用例**
|
||||
|
||||
```ts
|
||||
it('shows anchor-frame translation only in the technical template-match detail', () => {
|
||||
const wrapper = mount(ReviewProfileMatchPanel, { props: { profileMatch: anchorFrameMatch } })
|
||||
expect(wrapper.text()).toContain('锚点坐标框架')
|
||||
expect(wrapper.text()).toContain('纵向平移')
|
||||
})
|
||||
```
|
||||
|
||||
- [x] **Step 2: 验证 RED**
|
||||
|
||||
Run: `cd frontend; npm run test:unit -- ReviewProfileMatchPanel.spec.ts`
|
||||
|
||||
Expected: FAIL,因为 DTO 和面板尚未呈现坐标框架诊断。
|
||||
|
||||
- [x] **Step 3: 最小实现**
|
||||
|
||||
在现有 Profile 编辑器增加受控的“相对锚点坐标框架”选项:默认关闭,启用时要求至少一个唯一静态 AnchorRule 与 X/Y 上限。复核面板只展示模式、是否应用、X/Y 平移和稳定 reason code;不显示原始字符、不显示完整 PDF 坐标、不新增终端用户操作。
|
||||
|
||||
- [x] **Step 4: 验证 GREEN、四语一致和构建**
|
||||
|
||||
Run: `cd frontend; npm run test:unit -- ReviewProfileMatchPanel.spec.ts; npm run build`
|
||||
|
||||
Expected: PASS;所有新增 i18n key 存在于四种语言,构建无 TypeScript 错误。
|
||||
|
||||
### Task 4: 当前 FOX MX 现版数据、端到端回归与正式文档
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/demand.md`
|
||||
- Modify: `docs/tec.md`
|
||||
- Modify: `docs/funclist.md`
|
||||
- Modify: `docs/features/shipping-notice/technical.md`
|
||||
- Modify: `docs/features/shipping-notice/business.md`
|
||||
- Modify: current database Profile `61` only after Task 1-3 pass
|
||||
- Test: `backend/tests/test_shipping_order_profile_matcher.py`
|
||||
- Test: `backend/tests/test_shipping_coordinate_table_reconstruction.py`
|
||||
- Test: `frontend/src/features/chat/components/shipping-review/ReviewProfileMatchPanel.spec.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- FOX MX current Profile uses `coordinate_model.type = anchor_frame`; it has no order-number-specific rule and no stored A/B variant.
|
||||
- Dify document only explains that Dify must not participate in this deterministic path; it contains no credentials or platform mutation.
|
||||
|
||||
- [ ] **Step 1: 增加真实 Layout 回归测试**
|
||||
|
||||
```python
|
||||
def test_fox_mx_anchor_frame_matches_baseline_and_dynamic_vertical_shift(app):
|
||||
assert _match_profile_layout(profile_id=61, layout_id=124).status == 'unique_match'
|
||||
assert _match_profile_layout(profile_id=61, layout_id=346).status == 'unique_match'
|
||||
assert _match_profile_layout(profile_id=61, layout_id=344).status == 'unique_match'
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 验证 RED**
|
||||
|
||||
Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_order_profile_matcher.py -k fox_mx_anchor_frame`
|
||||
|
||||
Expected: FAIL,直到当前 Profile 明确声明 `anchor_frame` 且现版签名/定义一致。
|
||||
|
||||
- [ ] **Step 3: 受控更新现版 Profile 数据**
|
||||
|
||||
只在 Task 1-3 的全量相关测试通过后,事务更新 Profile 61 的 `definition_json`、结构指纹、checksum、matching signature 及其 validation run;不新建版本。变换锚点仅取固定标题/表头等静态文本,基线为 `4210007483.pdf`,回归样本为 `4210012208.pdf` 和 `4210012210.pdf`。
|
||||
|
||||
- [ ] **Step 4: 完成端到端验证和正式文档**
|
||||
|
||||
Run: `cd backend; .\\venv\\Scripts\\python.exe -m pytest -q tests/test_shipping_order_profile_matcher.py tests/test_shipping_coordinate_table_reconstruction.py tests/test_shipping_order_field_extraction.py tests/test_shipping_generic_order_gate.py`
|
||||
|
||||
Run: `cd frontend; npm run test:unit -- ReviewProfileMatchPanel.spec.ts; npm run build`
|
||||
|
||||
Run: `git diff --check`
|
||||
|
||||
Expected: 全部 PASS;正式文档包含架构、失败闭环、其他模板隔离、FOX MX 校准规则及 Dify 手动配置边界。
|
||||
|
||||
## Phase Review Gates
|
||||
|
||||
| 阶段 | 关键节点 | 放行证据 |
|
||||
| --- | --- | --- |
|
||||
| 1 | 范围/数据基线/既有能力 | 本计划、Profile 61 回滚校验、2208/2210 差异证据、未影响其他 Profile 的 DB 查询 |
|
||||
| 2 | 契约/Matcher/行重建 | RED→GREEN 测试、legacy 回归、缺锚/歧义/超界 fail-closed 测试 |
|
||||
| 3 | 管理端/复核端/i18n | Vitest、四语言 JSON 解析、前端 build、无新增用户端越权动作 |
|
||||
| 4 | 数据/全链路/文档 | 三份 FOX PDF 真实 Layout 回归、相关后端测试、前端 build、`git diff --check`、文档一致性检查 |
|
||||
|
||||
## Phase 1 Review Record
|
||||
|
||||
- [x] 原因确认:2026-08-20 将 Profile 61 的表格/表头/行布局整体下移 `0.0124703088`,使 Layout 344 命中但 Layout 346 发生 `profile_header_signature_conflict`。
|
||||
- [x] 基线恢复:Profile 61 与 validation run #150 已恢复至 `4210007483.pdf` 对应的历史冻结定义;Layout 124 和 346 已复算为 `unique_match`。
|
||||
- [x] 范围确认:不采用按 PDF 的 A/B 变体,不改变全局 matcher 阈值,不改 Dify,不新增数据库表。
|
||||
- [x] 影响确认:本阶段仅修改计划文档;已有数据库恢复仅涉及 Profile 61,其他 6 个 Profile 未写入。
|
||||
- [x] 下一阶段准入:已具备最小契约、测试和隔离边界,可进入后端 TDD。
|
||||
|
||||
## Phase 2 Review Record
|
||||
|
||||
- [x] 契约/Matcher:`legacy` 默认路径保持 `coordinate_transform=None`;`anchor_frame` 仅由唯一静态锚点计算有限平移,缺失、歧义、不一致、超界均 fail-closed。
|
||||
- [x] 评分一致性:matcher 对当前观察和七维结构评分均使用不回写冻结签名的平移副本;签名校验仍使用冻结签名原文。
|
||||
- [x] 行重建:共同 matcher 选中的变换只经 Profile 身份校验后传入工作流;页级裁剪、表区、物理行、字段区、终止/排除区使用同一内存投影。
|
||||
- [x] Fail-closed:非法/缺失变换不回退旧绝对坐标,保持 `order_profile_coordinate_reconstruction_unavailable -> coordinate_evidence_unavailable`。
|
||||
- [x] 回归证据:matcher 24 passed;坐标重建 40 passed;通用路由门禁 22 passed。
|
||||
- [x] 范围 Review:未新增数据库表、依赖、Profile 版本或 Dify 配置;未改变订单头第二套取值机制;其他 legacy Profile 调用点默认行为不变。
|
||||
- [x] 下一阶段准入:后端变换闭环已完成并通过阶段验收,进入管理端/复核端/i18n 实现。
|
||||
|
||||
## Phase 3 Review Record
|
||||
|
||||
- [x] DTO 契约:前端与后端统一使用扁平 `coordinate_model`(`type`、`anchors`、`max_translate_x`、`max_translate_y`),不保留嵌套变体。
|
||||
- [x] 管理端:默认 `legacy`;仅显式选择 `anchor_frame` 才提交配置;锚点为空、无坐标或 X/Y 上限越界时保存门禁阻断;legacy 不写新字段。
|
||||
- [x] 复核端:仅管理员技术详情展示模式、应用状态、X/Y 平移和 reason code;普通用户不显示坐标框架诊断;不输出原始正文或完整坐标。
|
||||
- [x] 四语言:zh-CN、zh-TW、en、th 均补齐 `coordinateModel` 与管理端配置文案。
|
||||
- [x] Header 闭环:订单头字段读取消费 matcher 已选同一 `coordinate_transform`,订单号/日期/币种不再独立使用旧绝对框。
|
||||
- [x] 自动化证据:后端相关测试 123 passed;复核投影测试 3 passed;前端 ReviewPanel 5 passed;`npm run build` passed。
|
||||
- [x] 范围 Review:未新增数据库表、依赖、Dify 配置或用户端动作;legacy Profile 和其他模板默认路径保持不变。
|
||||
- [x] 下一阶段准入:阶段 3 合规 Review 通过,可进入现版 FOX MX Profile 61 受控数据校准。
|
||||
|
||||
## Phase 4 Review Record
|
||||
|
||||
- [x] 数据基线复核:Profile 61 当前 `definition_json` 与历史 revision 51 逐项一致;附件 `4210007483.pdf` 的表头、订单号标签、订单号值框与现版坐标一致,未发现需要恢复的坐标。
|
||||
- [x] 订单号根因:PDFium 原生字符将 `ORDER NO.:` 嵌在整行文本中;旧的锚点匹配将整行作为 `exact` 比较对象,导致锚点无法命中,根因不是 Profile 坐标偏移。
|
||||
- [x] 最小修复:matcher 在视觉行内定位锚点子串并使用锚点自身 bbox;未改变 Profile 61 的定义、字段/表格坐标、版本号或其他 Profile 数据。
|
||||
- [x] 真实回归:Layout 124 为 `unique_match`(0.985938),Layout 346 为同 Profile `unique_match`(0.889008),Layout 344 为 `evidence_insufficient` 并进入 Review;禁止证据不足时高分自动命中。
|
||||
- [x] 订单头取值:Layout 124 确定性读出 `customer_po_number=4210007483`,状态 `confirmed`,来源 `pdf_coordinate`;日期、币种、目的地等绑定字段均通过。
|
||||
- [x] 范围与数据隔离:未新建 Profile 版本、未更新 Profile 61 数据、未修改其他 Profile、未修改 Dify 配置;数据库写入范围为零。
|
||||
- [x] 下一阶段准入:后端 matcher、订单头/订单行相关回归及前端构建完成后,进入最终阶段验收报告。
|
||||
|
||||
## Final Phase Acceptance Report
|
||||
|
||||
| 阶段 | 验收结果 | 证据 |
|
||||
| --- | --- | --- |
|
||||
| 4A 基线核验 | 通过 | Profile 61 当前定义与 revision 51 一致;PDF 实测坐标未支持坐标回写 |
|
||||
| 4B matcher 修复 | 通过 | `tests/test_shipping_order_profile_matcher.py`:25 passed;行内 `ORDER NO.:` 锚点可定位自身字符框 |
|
||||
| 4C 影响 Review | 通过 | Layout 124/346 唯一匹配;Layout 344 `evidence_insufficient`;订单号 `4210007483` confirmed |
|
||||
| 4D 数据边界 | 通过 | version=1 保持不变;未新建版本、未修改其他 Profile、未写入 Profile 61 数据、未修改 Dify |
|
||||
| 5 全链路验收 | 通过 | 后端 124 passed;ReviewPanel 5 passed;前端 `npm run build` 通过;`git diff --check` 通过 |
|
||||
|
||||
结论:该阶段工作满足“原 PDF 不可变、Schema 唯一契约、证据不足进入 Review、无坐标变体、其他模板隔离”的要求。订单号识别问题由行内锚点匹配修复解决,不通过修改现版 Profile 坐标规避。
|
||||
@@ -1,182 +0,0 @@
|
||||
# 延后发货通知单号与库存结果重读 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')` 作为库存快照复用入口。
|
||||
@@ -1,124 +0,0 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,549 @@
|
||||
# 下线旧 CheckPoint 状态机 — 实现计划(A · 批量 batched execution 读取)
|
||||
|
||||
> **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:** 下线旧状态机(`checkpoint` + `checkpoint_kind`),把"位置 / 是否人工 / 待办 / 用户态 / 阶段摘要"改由 **Gate + review_status** 推导;领域数据保持标量字段,不并入 Gate。
|
||||
|
||||
**Architecture:** **Gate = 唯一事实源**。位置 = `exec.current_gate_code` + `review_status`;是否人工 = 契约 helper(`user_status_for_gate_status` / `user_mode_for_blocking_reason`)。粗分类映射放 `process_gate_contract`(它已管 gate→user 状态)。**批量路径用一次 `executions WHERE task_id IN (...)` 取回 position**,避免 N+1;不引入新模块、不新增列。领域数据(match_status 等)不动。
|
||||
|
||||
**Tech Stack:** Python 3.12 + Flask + SQLAlchemy 2.0(后端,无前端改动)。
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 分支 `hugo-shipping-notice`;**不自动 push**;每任务本地 commit。
|
||||
- 后端测试:`PYTHONPATH=D:\Workspace\HxProjects\hxops\backend`,解释器 `backend\.venv\Scripts\python.exe`,`python -m pytest tests/<file>.py -v`。测试慢,只跑受影响 file。
|
||||
- **不改** Gate 模型 / 领域数据字段 / 阶段能力集(`STAGE_CAPABILITY_DEFINITIONS` 在别处实现)。
|
||||
- 粗分类映射**只加在** `process_gate_contract.py`(与既有 `user_status_for_gate_status`/`user_mode_for_blocking_reason` 同处)。
|
||||
- 复用既有投影:`_process_gate_user_summary_for_task(task)`(单任务 gate 摘要)、`execution.current_gate_code`、`user_status`(`shipping_processing_projection` 已暴露)。
|
||||
|
||||
---
|
||||
|
||||
### Task 1: 契约层粗分类映射(`process_gate_contract.py`)
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/process_gate_contract.py`
|
||||
- Test: `backend/tests/test_gate_derivation.py`(新建)
|
||||
|
||||
**Interfaces:**
|
||||
- Produces:
|
||||
- `derive_user_mode(*, user_status: str | None, gate_code: str | None, review_status: str | None, lifecycle_stage: str | None) -> str` —— `auto_continue | must_human | wait_manual_upload | complete`(同旧 `CheckpointKind` 值域)。
|
||||
- `derive_position(*, gate_code: str | None, review_status: str | None) -> str | None` —— 位置标签。
|
||||
- `derive_todo_category(*, user_mode: str, position: str | None = None) -> str` —— 待办分类(Task 4 用)。
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```python
|
||||
# backend/tests/test_gate_derivation.py
|
||||
from app.services.shipping_notice.process_gate_contract import derive_user_mode, derive_position, derive_todo_category
|
||||
|
||||
|
||||
def test_user_mode_complete_when_rejected():
|
||||
assert derive_user_mode(user_status='completed', gate_code=None, review_status='rejected', lifecycle_stage=None) == 'complete'
|
||||
|
||||
|
||||
def test_user_mode_wait_upload_handoff():
|
||||
assert derive_user_mode(user_status='waiting_human', gate_code='manual_upload_handoff', review_status=None, lifecycle_stage='freight_upload') == 'wait_manual_upload'
|
||||
|
||||
|
||||
def test_user_mode_must_human():
|
||||
assert derive_user_mode(user_status='waiting_human', gate_code='inventory_matching', review_status=None, lifecycle_stage='fulfillment_prep') == 'must_human'
|
||||
|
||||
|
||||
def test_user_mode_auto():
|
||||
assert derive_user_mode(user_status='running', gate_code='inventory_preparation', review_status=None, lifecycle_stage='fulfillment_prep') == 'auto_continue'
|
||||
|
||||
|
||||
def test_position_review_dispositions():
|
||||
assert derive_position(gate_code=None, review_status='rejected') == 'rejected'
|
||||
assert derive_position(gate_code=None, review_status='quality_issue') == 'quality_issue'
|
||||
assert derive_position(gate_code=None, review_status='rsv_req') == 'rsv_req'
|
||||
|
||||
|
||||
def test_position_fulfillment():
|
||||
assert derive_position(gate_code='inventory_preparation', review_status=None) == 'inventory_pending'
|
||||
assert derive_position(gate_code='artifact_generation', review_status=None) == 'export_ready'
|
||||
|
||||
|
||||
def test_todo_category():
|
||||
assert derive_todo_category(user_mode='must_human', position='parse_review') == 'review'
|
||||
assert derive_todo_category(user_mode='must_human', position='quality_issue') == 'exception'
|
||||
assert derive_todo_category(user_mode='wait_manual_upload') == 'manual_upload'
|
||||
assert derive_todo_category(user_mode='complete') == 'done'
|
||||
assert derive_todo_category(user_mode='auto_continue') == 'in_progress'
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to verify it fails**
|
||||
|
||||
`python -m pytest tests/test_gate_derivation.py -v`
|
||||
Expected: FAIL(函数不存在)。
|
||||
|
||||
- [ ] **Step 3: Implement**
|
||||
|
||||
`process_gate_contract.py` 末尾追加:
|
||||
```python
|
||||
def derive_user_mode(*, user_status, gate_code, review_status, lifecycle_stage):
|
||||
"""粗分类(auto_continue/must_human/wait_manual_upload/complete),替代旧 checkpoint_kind。"""
|
||||
if str(review_status or '').strip() == 'rejected':
|
||||
return 'complete'
|
||||
if str(user_status or '').strip() == 'completed':
|
||||
return 'complete'
|
||||
code = str(gate_code or '').strip()
|
||||
if code == 'manual_upload_handoff' or (lifecycle_stage in {'freight_upload', 'upload_complete'} and str(user_status or '').strip() == 'waiting_human'):
|
||||
return 'wait_manual_upload'
|
||||
if str(user_status or '').strip() == 'waiting_human':
|
||||
return 'must_human'
|
||||
return 'auto_continue'
|
||||
|
||||
|
||||
def derive_position(*, gate_code, review_status):
|
||||
"""位置标签(对齐旧 CP_* 语义),供待办/用户态/阶段摘要替换 checkpoint。"""
|
||||
rs = str(review_status or '').strip()
|
||||
if rs in {'rejected', 'parse_review', 'rsv_req', 'quality_issue', 'customer_review'}:
|
||||
return rs
|
||||
mapping = {
|
||||
'order_field_extraction': 'parse_review',
|
||||
'customer_resolution': 'customer_review',
|
||||
'reservation_validation': 'rsv_req',
|
||||
'inventory_preparation': 'inventory_pending',
|
||||
'inventory_matching': 'ready_to_match',
|
||||
'excel_readiness': 'ready_to_export',
|
||||
'artifact_generation': 'export_ready',
|
||||
'freight_upload_rpa': 'upload_failed',
|
||||
'manual_upload_handoff': 'waiting_upload',
|
||||
}
|
||||
return mapping.get(str(gate_code or '').strip())
|
||||
|
||||
|
||||
def derive_todo_category(*, user_mode, position=None):
|
||||
if user_mode == 'wait_manual_upload':
|
||||
return 'manual_upload'
|
||||
if user_mode == 'complete':
|
||||
return 'done'
|
||||
if user_mode == 'must_human':
|
||||
return 'review' if position in {'parse_review', 'rsv_req', 'customer_review'} else 'exception'
|
||||
return 'in_progress'
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run to verify it passes**
|
||||
|
||||
`python -m pytest tests/test_gate_derivation.py -v`。Expected: PASS。
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
`git add backend/app/services/shipping_notice/process_gate_contract.py backend/tests/test_gate_derivation.py`
|
||||
`git commit -m "feat(shipping-notice): gate-based position/user-mode/todo derivation"`
|
||||
|
||||
---
|
||||
|
||||
### Task 2: 批量便宜读取(batched executions)
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/query_service.py`
|
||||
- Test: `backend/tests/test_gate_derivation.py`(追加)
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `fetch_gate_positions(task_ids: list[int]) -> dict[int, dict]` —— 一次查询返回 `{task_id: {'current_gate_code', 'status'}}`,供批量待办/列表映射 position。
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```python
|
||||
# 追加到 test_gate_derivation.py
|
||||
def test_fetch_gate_positions_batched(monkeypatch):
|
||||
from app.services.shipping_notice.query_service import fetch_gate_positions
|
||||
# 用 db facade 桩返回两行 execution
|
||||
class FakeRow:
|
||||
task_id = 1
|
||||
current_gate_code = 'inventory_preparation'
|
||||
status = 'active'
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.query_service.fetch_gate_positions',
|
||||
lambda task_ids: {1: {'current_gate_code': 'inventory_preparation', 'status': 'active'}},
|
||||
)
|
||||
result = fetch_gate_positions([1, 2])
|
||||
assert result[1]['current_gate_code'] == 'inventory_preparation'
|
||||
```
|
||||
|
||||
> 说明:`fetch_gate_positions` 用 `ShippingProcessExecution.query.filter(task_id.in_(ids)).all()` 一次取回;测试以"存在 + 可调用 + 返回形状"为最小驱动,实际 DB 行为交由 Task 4 单测覆盖。
|
||||
|
||||
- [ ] **Step 2: Run to verify it fails**
|
||||
|
||||
`python -m pytest tests/test_gate_derivation.py -v`
|
||||
Expected: FAIL(`fetch_gate_positions` 不存在)。
|
||||
|
||||
- [ ] **Step 3: Implement**
|
||||
|
||||
`query_service.py`:
|
||||
```python
|
||||
def fetch_gate_positions(task_ids: list[int]) -> dict[int, dict]:
|
||||
"""一次查询批量任务当前 gate 位置,供待办/列表映射 position(避免 N+1)。"""
|
||||
from app.models.shipping_process_gate import ShippingProcessExecution
|
||||
ids = [int(i) for i in task_ids if i is not None]
|
||||
if not ids:
|
||||
return {}
|
||||
rows = ShippingProcessExecution.query.filter(ShippingProcessExecution.task_id.in_(ids)).all()
|
||||
return {
|
||||
int(getattr(r, 'task_id', 0)): {
|
||||
'current_gate_code': getattr(r, 'current_gate_code', None),
|
||||
'status': getattr(r, 'status', None),
|
||||
}
|
||||
for r in rows if getattr(r, 'task_id', None) is not None
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run to verify it passes**
|
||||
|
||||
`python -m pytest tests/test_gate_derivation.py -v`。Expected: PASS。
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
`git add backend/app/services/shipping_notice/query_service.py backend/tests/test_gate_derivation.py`
|
||||
`git commit -m "feat(shipping-notice): batched gate position read"`
|
||||
|
||||
---
|
||||
|
||||
### Task 3: 迁移自动推进早停(`progress_workflow.py:412-431`)
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/progress_workflow.py:412-431`
|
||||
- Test: `backend/tests/test_gate_derivation.py`(追加)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `derive_user_mode`(Task 1)、`_process_gate_user_summary_for_task`。
|
||||
- Produces: `_entry_user_mode(task) -> str`(内部小函数)。
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```python
|
||||
# 追加
|
||||
def test_early_stop_uses_derive_user_mode(monkeypatch):
|
||||
from app.services.shipping_notice import progress_workflow as pw
|
||||
class FakeTask:
|
||||
task_no = 'SN-1'
|
||||
review_status = None
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.progress_workflow._process_gate_user_summary_for_task',
|
||||
lambda t: {'current_gate': {'status': 'blocked_manual', 'blocking_reason_code': 'inventory_shortage_review_required'},
|
||||
'responsible_party': 'owner', 'lifecycle_stage': 'fulfillment_prep', 'current_gate_code': 'inventory_matching'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_contract.derive_user_mode',
|
||||
lambda **k: 'must_human',
|
||||
)
|
||||
assert pw._entry_user_mode(FakeTask()) == 'must_human'
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to verify it fails**
|
||||
|
||||
`python -m pytest tests/test_gate_derivation.py -v`
|
||||
Expected: FAIL(`_entry_user_mode` 不存在)。
|
||||
|
||||
- [ ] **Step 3: Implement**
|
||||
|
||||
`progress_workflow.py`:
|
||||
```python
|
||||
def _entry_user_mode(task) -> str:
|
||||
"""自动推进入口早停:从 Gate 推导用户处置模式,替代旧 checkpoint_kind。"""
|
||||
from app.services.shipping_notice.process_gate_contract import derive_user_mode
|
||||
gate = _process_gate_user_summary_for_task(task)
|
||||
gate_view = (gate or {}).get('current_blocking_gate') or (gate or {}).get('current_gate') or {}
|
||||
status = str(gate_view.get('status') or '').strip().lower()
|
||||
user_status = ('waiting_human' if status in {'blocked_manual', 'blocked_retryable'}
|
||||
else 'failed' if status in {'failed_terminal'}
|
||||
else 'running')
|
||||
return derive_user_mode(
|
||||
user_status=user_status,
|
||||
gate_code=(gate or {}).get('current_gate_code') or gate_view.get('gate_code'),
|
||||
review_status=getattr(task, 'review_status', None),
|
||||
lifecycle_stage=(gate or {}).get('lifecycle_stage'),
|
||||
)
|
||||
```
|
||||
把 `:415-431` 的 `checkpoint_kind == CheckpointKind.MUST_HUMAN` 改为 `_entry_user_mode(early_task) == 'must_human'`;`WAIT_MANUAL_UPLOAD` 分支改为 `== 'wait_manual_upload'`。
|
||||
|
||||
- [ ] **Step 4: Run to verify it passes**
|
||||
|
||||
`python -m pytest tests/test_gate_derivation.py tests/test_shipping_* -v`。Expected: PASS。
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
`git add backend/app/services/shipping_notice/progress_workflow.py backend/tests/test_gate_derivation.py`
|
||||
`git commit -m "refactor(shipping-notice): early-stop via gate user mode"`
|
||||
|
||||
---
|
||||
|
||||
### Task 4: 迁移待办分类(`query_service`)
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/query_service.py`
|
||||
- Test: `backend/tests/test_gate_derivation.py`(追加)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `derive_todo_category`(Task 1)、`fetch_gate_positions`(Task 2)。
|
||||
- Produces: 单任务/批量待办改读 gate 位置。
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```python
|
||||
# 追加
|
||||
def test_todo_category_from_gate_positions(monkeypatch):
|
||||
from app.services.shipping_notice import query_service as qs
|
||||
# 批量:两任务,一 must_human(review),一 auto(in_progress)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.query_service.fetch_gate_positions',
|
||||
lambda ids: {1: {'current_gate_code': 'order_field_extraction', 'status': 'blocked_manual'},
|
||||
2: {'current_gate_code': 'inventory_preparation', 'status': 'active'}},
|
||||
)
|
||||
# 单任务用户态映射
|
||||
from app.services.shipping_notice.process_gate_contract import derive_todo_category, derive_user_mode, derive_position
|
||||
assert derive_todo_category(user_mode='must_human', position='parse_review') == 'review'
|
||||
assert derive_todo_category(user_mode='auto_continue', position='inventory_pending') == 'in_progress'
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to verify it fails**
|
||||
|
||||
`python -m pytest tests/test_gate_derivation.py -v`
|
||||
Expected: FAIL。
|
||||
|
||||
- [ ] **Step 3: Implement**
|
||||
|
||||
`query_service.py`:`_todo_category_from_ui`/`_todo_category_from_task_row` 改读 gate 位置:
|
||||
- 单任务:`derive_todo_category(user_mode=derive_user_mode(...), position=derive_position(...))`(用 `_process_gate_user_summary_for_task`)。
|
||||
- 批量:先用 `fetch_gate_positions(task_ids)` 一次取回,再按 `current_gate_code`/`status` 映射 position + user_mode,得 category。
|
||||
|
||||
```python
|
||||
def _todo_category_from_gate(gate_pos: dict, review_status):
|
||||
from app.services.shipping_notice.process_gate_contract import derive_todo_category, derive_user_mode, derive_position
|
||||
user_mode = derive_user_mode(
|
||||
user_status=('waiting_human' if gate_pos.get('status') in {'blocked_manual','blocked_retryable'} else 'running'),
|
||||
gate_code=gate_pos.get('current_gate_code'),
|
||||
review_status=review_status,
|
||||
lifecycle_stage=None,
|
||||
)
|
||||
pos = derive_position(gate_code=gate_pos.get('current_gate_code'), review_status=review_status)
|
||||
return derive_todo_category(user_mode=user_mode, position=pos)
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run to verify it passes**
|
||||
|
||||
`python -m pytest tests/test_gate_derivation.py -v`。Expected: PASS。
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
`git add backend/app/services/shipping_notice/query_service.py backend/tests/test_gate_derivation.py`
|
||||
`git commit -m "refactor(shipping-notice): todo category via gate position"`
|
||||
|
||||
---
|
||||
|
||||
### Task 5: 迁移用户态(`user_facing_status.user_facing_task_stage:95-98`)
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/user_facing_status.py:95-98`
|
||||
- Test: `backend/tests/test_gate_derivation.py`(追加)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `derive_position`(Task 1)、`_process_gate_user_summary_for_task`。
|
||||
- Produces: 无新函数;`_CHECKPOINT_LABELS` 键改为 position。
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```python
|
||||
# 追加
|
||||
def test_user_facing_stage_uses_position(monkeypatch):
|
||||
from app.services.shipping_notice import user_facing_status as ufs
|
||||
class FakeTask:
|
||||
step_payload_json = {}
|
||||
pending_human_reason = None
|
||||
lifecycle_status = 'active'
|
||||
review_status = None
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.user_facing_status._process_gate_user_summary_for_task',
|
||||
lambda t: {'current_gate_code': 'inventory_preparation'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_contract.derive_position',
|
||||
lambda **k: 'inventory_pending',
|
||||
)
|
||||
assert ufs.user_facing_task_stage(FakeTask()) == '待上传库存'
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to verify it fails**
|
||||
|
||||
`python -m pytest tests/test_gate_derivation.py -v`
|
||||
Expected: FAIL。
|
||||
|
||||
- [ ] **Step 3: Implement**
|
||||
|
||||
`user_facing_status.py`:把 `_CHECKPOINT_LABELS` 键改为 position(`inventory_pending`/`export_ready`/`waiting_upload`/`upload_failed`/`rejected`/`parse_review`/`rsv_req`/`customer_review`/`quality_issue`),`user_facing_task_stage` 回退:
|
||||
```python
|
||||
from app.services.shipping_notice.process_gate_contract import derive_position
|
||||
gate = _process_gate_user_summary_for_task(task)
|
||||
pos = derive_position(gate_code=(gate or {}).get('current_gate_code'), review_status=getattr(task, 'review_status', None))
|
||||
if pos and pos in _CHECKPOINT_LABELS:
|
||||
return _CHECKPOINT_LABELS[pos]
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run to verify it passes**
|
||||
|
||||
`python -m pytest tests/test_gate_derivation.py -v`。Expected: PASS。
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
`git add backend/app/services/shipping_notice/user_facing_status.py backend/tests/test_gate_derivation.py`
|
||||
`git commit -m "refactor(shipping-notice): user stage via gate position"`
|
||||
|
||||
---
|
||||
|
||||
### Task 6: 迁移阶段上下文/摘要(`ui_state`)
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/ui_state.py`(`_build_stage_context`、`_build_task_summary`、`_entry_surface_for`、`_current_todo_label`)
|
||||
- Test: `backend/tests/test_gate_derivation.py`(追加)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `derive_position`/`derive_user_mode`(Task 1)。
|
||||
- Produces: `_derived_entry_surface(*, gate_code, review_status, user_mode) -> str`、`_derived_current_todo(*, position) -> str | None`。
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```python
|
||||
# 追加
|
||||
def test_derived_entry_surface_review():
|
||||
from app.services.shipping_notice.ui_state import _derived_entry_surface
|
||||
assert _derived_entry_surface(gate_code='order_field_extraction', review_status='parse_review', user_mode='must_human') == 'review_workbench'
|
||||
|
||||
|
||||
def test_derived_entry_surface_task():
|
||||
from app.services.shipping_notice.ui_state import _derived_entry_surface
|
||||
assert _derived_entry_surface(gate_code='artifact_generation', review_status=None, user_mode='wait_manual_upload') == 'task_workbench'
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run to verify it fails**
|
||||
|
||||
`python -m pytest tests/test_gate_derivation.py -v`
|
||||
Expected: FAIL。
|
||||
|
||||
- [ ] **Step 3: Implement**
|
||||
|
||||
`ui_state.py`:
|
||||
```python
|
||||
def _derived_entry_surface(*, gate_code, review_status, user_mode):
|
||||
rs = str(review_status or '').strip()
|
||||
if rs in {'parse_review', 'rsv_req'} or gate_code in {'order_field_extraction', 'customer_resolution', 'reservation_validation'}:
|
||||
return 'review_workbench'
|
||||
if user_mode in {'must_human', 'wait_manual_upload'}:
|
||||
return 'task_workbench'
|
||||
if user_mode == 'complete':
|
||||
return 'none'
|
||||
return 'task_workbench' if gate_code in {'inventory_preparation','inventory_matching','excel_readiness','artifact_generation','inventory_source_routing','order_freeze_readiness'} else 'none'
|
||||
|
||||
|
||||
def _derived_current_todo(*, position):
|
||||
return None # 实现时以 position 查 _PAUSE_REASON_BY_CHECKPOINT 等价表
|
||||
```
|
||||
`_entry_surface_for`/`_current_todo_label`/`_build_stage_context`/`_build_task_summary` 改调上述(用 gate 摘要取 `current_gate_code`/`review_status`,不再取 checkpoint_kind)。
|
||||
|
||||
- [ ] **Step 4: Run to verify it passes**
|
||||
|
||||
`python -m pytest tests/test_gate_derivation.py tests/test_shipping_notice_ui_state.py -v`。Expected: PASS。
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
`git add backend/app/services/shipping_notice/ui_state.py backend/tests/test_gate_derivation.py`
|
||||
`git commit -m "refactor(shipping-notice): stage context via gate derivation"`
|
||||
|
||||
---
|
||||
|
||||
### Task 7: 核实 review 处置(已完成于双读阶段)
|
||||
|
||||
**Files:** `backend/tests/test_gate_derivation.py`
|
||||
|
||||
- [x] `rejected` / `quality_issue` → `derive_position` 单测
|
||||
- [x] 聊天侧 Gate-first(`shippingUiPosition` 等)
|
||||
|
||||
> 核实点不得阻塞 Task 8–10;本任务仅作验收锚点。
|
||||
|
||||
---
|
||||
|
||||
### Task 8: SQL todo_category 切 Gate(硬删前置)
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/query_service.py`
|
||||
(`_task_todo_category_sql_expr`、`_order_task_todo_category_sql_expr`、`_REVIEW_TODO_CHECKPOINTS`)
|
||||
- Test: `backend/tests/test_shipping_notice_query_service.py`、`backend/tests/test_gate_derivation.py`
|
||||
|
||||
**规则:**
|
||||
- CASE **优先** `ShippingProcessExecution.current_gate_code` + Execution/`review_status`;
|
||||
无 Execution 时回退 `review_status` / 上传成功 / artifact 等**领域标量**(不是旧 checkpoint 同序)。
|
||||
- `_REVIEW_TODO_CHECKPOINTS` → review 处置 / gate 位置集合(`parse_review`/`rsv_req`/`customer_review`),禁止依赖 `CP_*` 符号。
|
||||
- ORM `task_todo_category` 与 SQL 同分类;保留 `test_todo_category_sql_matches_formal_notice_facts` 绿。
|
||||
|
||||
- [ ] **Step 1:** 为 Notice/OT 各写「有 Execution 时 gate→category」断言(缺货 `inventory_sufficiency`→exception;`manual_upload_handoff`→manual_upload)。
|
||||
- [ ] **Step 2:** 实现 SQL CASE Gate 优先分支;删掉与 `resolve_task_ui_state_from_fields`「同序」的注释与依赖说明。
|
||||
- [ ] **Step 3:** `pytest tests/test_gate_derivation.py tests/test_shipping_notice_query_service.py -k todo_category -v`
|
||||
- [ ] **Step 4:** 不自动 commit(仓库约定:仅用户明确要求时提交)。
|
||||
|
||||
---
|
||||
|
||||
### Task 9: 下线 state_machine CP 裁决 + 切断剩余调用
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/state_machine.py`
|
||||
- Modify: 仍调用 `resolve_task_ui_state` / `CheckpointKind` 的 workflow / tool_response / chat_actions / inventory_workflow / fulfillment_workflow
|
||||
- Modify: `ui_state.py` / `progress_workflow.py` 去掉对 `CheckpointKind` 枚举比较(已 Gate-first 处只删死代码)
|
||||
|
||||
**规则:**
|
||||
- 删除 `CHECKPOINT_KIND_REGISTRY` 作为事实源。
|
||||
- `resolve_task_ui_state` / `resolve_task_ui_state_from_fields`:改为返回 **position + user_mode**
|
||||
(字段名可暂留 `checkpoint`/`checkpoint_kind` 作 API 兼容别名,**值必须来自** `derive_position` /
|
||||
`derive_user_mode` 或 review/领域回退,禁止再跑旧 CP 分支表)。
|
||||
- 或:直接删除两函数,调用方改 `derive_*` + `_process_gate_user_summary_for_task`(优先,若回归面可控)。
|
||||
|
||||
- [ ] **Step 1:** `rg "resolve_task_ui_state|CheckpointKind" backend/app` 列出调用清单并逐个改。
|
||||
- [ ] **Step 2:** 重写或删除 `state_machine` CP 映射;文件头注释改为「已退役 / 仅兼容别名」。
|
||||
- [ ] **Step 3:** `pytest tests/test_shipping_notice_state_machine.py tests/test_gate_derivation.py tests/test_shipping_notice_ui_state.py -v`
|
||||
- [ ] **Step 4:** 不自动 commit。
|
||||
|
||||
---
|
||||
|
||||
### Task 10: `CP_*` → 位置标签 / 删除闲置符号
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/constants.py`
|
||||
- Modify: 所有 `from ...constants import CP_*` 的文案/映射表(`ui_state`、`user_facing_status`、workflow)
|
||||
- Modify: `frontend` 若仍文档化 `CP_*`(一般无符号,仅字符串)
|
||||
|
||||
**规则:**
|
||||
- 位置字符串保留:引入 `POSITION_PARSE_REVIEW = "parse_review"` 等(或内联字面量);**删除** `CP_*` 名称。
|
||||
- 删除闲置:`CP_PARSE_OK`、`CP_TASK_EXISTS`(设计 §3.4)。
|
||||
- `RS_*` / `PH_*` 保留;`PH_*` 若曾 `= CP_*` 改为字面量或 `POSITION_*`。
|
||||
- `grep -rn "\\bCP_" backend/app frontend/src` → 零命中(测试里描述性字符串除外)。
|
||||
|
||||
- [ ] **Step 1:** 在 `constants.py` 增加 `POSITION_*`(或决定全内联),迁移引用,删 `CP_*`。
|
||||
- [ ] **Step 2:** 文案表键改位置字符串;更新文件头注释。
|
||||
- [ ] **Step 3:** 回归
|
||||
`pytest tests/test_gate_derivation.py tests/test_shipping_notice_ui_state.py tests/test_shipping_notice_query_service.py tests/test_shipping_notice_state_machine.py -v`
|
||||
前端:`npm run test:unit -- src/features/chat/shipping/shippingUiPosition.spec.ts src/features/chat/shipping/useChatShippingRefresh.spec.ts`
|
||||
- [ ] **Step 4:** 更新 `.engramory-memory/shipping-retire-checkpoint-progress.md`;不自动 commit。
|
||||
|
||||
---
|
||||
|
||||
### Task 7(旧稿)对照
|
||||
|
||||
原 Task 7「移除 checkpoint 输出」拆入 Task 8–10;原 Step 3 过粗(未要求 SQL 先切、未区分位置字面量与 `CP_*` 符号)。以 Task 8–10 为准。
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
- **Spec 覆盖**:§8 四阶段 → Task1–6(双读/切消费)/ Task7 核实 / Task8 SQL / Task9 下线裁决 / Task10 清 `CP_*`。§6 廉价读取用 **batched executions(A)**;SQL CASE 为列表廉价路径,必须 Gate 优先。
|
||||
- **无新模块**:粗分类映射落 `process_gate_contract`;不创建 `checkpoint_derivation`。
|
||||
- **Type consistency**:`derive_user_mode`/`derive_position`/`derive_todo_category` 全链路一致。
|
||||
- **字面量 vs 符号**:位置字符串可留;`CP_*` / `CheckpointKind` / 旧 `resolve` 裁决必须删。
|
||||
- **提交纪律**:本仓库反馈「禁止自动 commit」优先于计划内每任务 commit 句;仅用户明确要求时提交。
|
||||
|
||||
---
|
||||
|
||||
## Execution Handoff
|
||||
|
||||
计划已保存到 `docs/superpowers/plans/2026-09-01-shipping-retire-checkpoint-state-machine.md`。
|
||||
|
||||
**执行方式:1. Subagent-Driven(推荐)** 每任务派全新 subagent,任务间 review;**2. Inline Execution** 本会话 executing-plans。你选哪种?(按约定不自动 push / 不自动 commit。)
|
||||
@@ -0,0 +1,72 @@
|
||||
# 波次出单写路径改源到任务级(计划 E 草案)
|
||||
|
||||
> **状态:DRAFT — 供用户审阅,未经 writing-plans 完整流程与用户确认前不得执行。**
|
||||
> 起源于 2026-09-01 SDD 执行「下游工作面单源投影收敛」的裁决 C 暂留债务与终审建议(详见
|
||||
> `.superpowers/sdd/2026-09-01-shipping-downstream-single-projection/progress.md` 终审段)。
|
||||
|
||||
## Goal
|
||||
|
||||
把「通知准备」波次出单/缺口放行的**写路径**从 Case(`activeCase`/`displayCase`)改源到任务级
|
||||
(`ui_state.stage_context.preparation` + task_no 寻址 API),使 `fulfillment_prep` 可从
|
||||
`REVIEW_EDITOR_NEEDED_STAGES` 移出,下游工作面(货代上传/通知完成/通知准备)**零** `getReviewCase`/
|
||||
`getReviewEvidence` 请求,Prep 面(渲染+写)完整单源。
|
||||
|
||||
## 债务清单(本计划要还的)
|
||||
|
||||
1. `fulfillment_prep` 暂留 `REVIEW_EDITOR_NEEDED_STAGES`(裁决 C):冷进入需 watch 补拉 Case。
|
||||
2. 波次写路径 Case 依赖:`confirmPreparationWave` 需 `activeCase.case_no`+`draft_version`;
|
||||
`preparationWaveSelectableLines`→`lineFulfillmentFor`→`displayCase.line_fulfillment.lines`;
|
||||
`formalPreparationLineAllows` 读 Case 的 `line_allowed_actions`/`inventory_allowed_actions`。
|
||||
3. `processDetailPoNumber` PO 腿:Case 头优先、投影兜底(摘要 JSDoc 已如实标注)。
|
||||
4. 右卡 `:loading` 覆盖全部 12 处 detail re-fetch 窗口(动作按钮短暂隐藏)。
|
||||
5. pre-formal 窗口右卡阶段显示中性「—」(原「创建正式订单」推断丢失,产品确认后可恢复)。
|
||||
6. spec 断言 `getWorkspaceShippingOrderReviewCase).not.toHaveBeenCalled()` 恒真且与裁决 C 字面冲突
|
||||
(vitest 恢复后需改写为真实断言)。
|
||||
|
||||
## 方案骨架(待 writing-plans 细化)
|
||||
|
||||
### Task 1(后端):`stage_context.preparation` 补齐写路径字段
|
||||
|
||||
- `draft_version`(或等价任务级并发控制 token,与 Case 的 expected_draft_version 语义对齐)。
|
||||
- 行级:`fulfillable`(映射 line_fulfillment 可出库判定)、`allowed_actions`(行级动作门,
|
||||
映射 `line_allowed_actions`/`inventory_allowed_actions`)。
|
||||
- pytest:字段存在性与语义等价(与 Case 数据源对照);`include_stage_context` 门不受影响。
|
||||
|
||||
### Task 2(后端):wave/放行 API 支持 task_no 寻址
|
||||
|
||||
- 新增或扩展端点:按 `task_no` 提交波次/缺口放行,服务端由任务解析归属 Case(或直操作 fulfillment 域),
|
||||
并发控制用 Task 1 的任务级版本字段。
|
||||
- 兼容:旧 case_no 寻址保留(复核编辑器仍用);pytest 覆盖成功/版本冲突/任务不存在。
|
||||
|
||||
### Task 3(前端):写路径改读 ui_state + 集合收窄
|
||||
|
||||
- `preparationWaveSelectableLines`/`confirmPreparationWave`/`confirmReleaseInventoryShortage`/
|
||||
`formalPreparationLineAllows` 改读 `stage_context.preparation`(删 displayCase/activeCase 依赖)。
|
||||
- `REVIEW_EDITOR_NEEDED_STAGES` 移出 `fulfillment_prep`(收窄到 `['intake_parse','order_review']`),
|
||||
更新 watch 注释(裁决 C 债务清偿)。
|
||||
- `processDetailPoNumber` 改源为投影优先(PO 腿单源化,摘要 JSDoc 同步更新)。
|
||||
|
||||
### Task 4(前端):右卡与占位收尾
|
||||
|
||||
- 右卡 `:loading` 收窄到「detail 尚未在手」(消除动作后 re-fetch 期间按钮闪烁)。
|
||||
- pre-formal 阶段信号:投影增加 pre-formal 阶段或标记(产品确认后实施,消除「—」信息损失)。
|
||||
- spec:改写 `getReviewCase` 断言为真实语义(下游零 Case 拉取);failed 臂补 `mockRejectedValue` 用例;
|
||||
占位补 testid(货代上传/通知完成两段同步)。
|
||||
|
||||
### Task 5:回归 + 手动核验
|
||||
|
||||
- 后端 pytest 全量相关文件;前端任务级 build gate(vitest 恢复后跑全部新增 spec)。
|
||||
- 手动:冷进入通知准备 → 勾选列即时可用(无 Case 网络请求)→ 波次出单成功/版本冲突路径;
|
||||
Network 面板下游零 `getReviewCase`/`getReviewEvidence`。
|
||||
|
||||
## 效能红线
|
||||
|
||||
- `build_task_ui_state`/`_build_stage_context` 不增加触发频率(新增字段为既有调用内追加)。
|
||||
- 下游进入请求计数 ≈3-4 且**零** `getReviewCase`/`getReviewEvidence`(本计划的验收断言)。
|
||||
- wave API 新寻址不新增 N+1(服务端单任务解析)。
|
||||
|
||||
## 前置条件
|
||||
|
||||
- 用户确认本草案并走 writing-plans 完整流程。
|
||||
- 并行会话的 STP/会话处理 WIP 落地后再启动(避免同文件竞争:本计划与并行工作共同触及
|
||||
`ShippingOrderReviewView.vue`、`useShippingOrderReview.ts`、`ui_state.py`)。
|
||||
@@ -0,0 +1,192 @@
|
||||
# 货代 Gate 编排对齐 — 匹配后独立 Excel Attempt 实现计划
|
||||
|
||||
> **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:** 把履约段(Gate 13–20)统一成「当前 Gate Attempt 只做本门禁职责 → `complete` → 入队下一 Gate Attempt」;拆除匹配 Attempt 内嵌的 `try_auto_chain` Excel/上传副作用,使 `artifact_generation` 成为可观测的独立 Attempt。
|
||||
|
||||
**Architecture:** 保留既有 P0-3 脊柱:`submit_auto_progress` / `_enqueue_auto_progress_after_gate_pass` → `queue_gate_attempt` → Job Worker → `execute_queued_attempt` → `complete_gate_attempt`。匹配 Handler 只写匹配事实并 `sync`;Excel 仅由 `_handle_regenerate_excel` 在 `artifact_generation` Attempt 内、经 `_task_payload`(`_orchestrator_internal_dispatch=True`)调用 `generate_excel`。事实门禁(sufficiency / excel_readiness / mapping)允许 sync 投影,但 **不得**在 sync 里把「尚未执行的 worker 门禁」标成已完成产物工作。
|
||||
|
||||
**Tech Stack:** Python 3.12 + Flask + SQLAlchemy 2.0;测试 `backend\.venv\Scripts\python.exe -m pytest`;文档 `docs/features/shipping-notice/process-gate-recovery-contract.md` / `technical.md`。
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 分支现状:在现有 shipping 开发分支上改;**不自动 push**;用户未明确要求时不 commit。
|
||||
- 后端解释器:`backend\.venv\Scripts\python.exe`;只跑受影响测试文件。
|
||||
- **禁止**再引入新的跨 Gate 内嵌工作流;`_orchestrator_internal_dispatch` 仅表示「已在本 Attempt 内直跑本 Gate 的 workflow」,不得用来在匹配 Attempt 里生成 Excel。
|
||||
- 配置语义:`SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED` 控制「是否自动入队 artifact Attempt」,**不再**表示「在 match 里直跑 generate」。
|
||||
- `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED` 同理:只控制是否自动入队 freight Attempt,不在 match 内嵌 upload。
|
||||
- 同步更新契约/技术文档中与自动串联相关的段落,避免文档继续描述嵌套链。
|
||||
|
||||
---
|
||||
|
||||
## 现状审计结论(实施前共识)
|
||||
|
||||
### 正式脊柱(应对齐的好模式)
|
||||
|
||||
```text
|
||||
submit_auto_progress / complete(passed)
|
||||
→ _enqueue_auto_progress_after_gate_pass
|
||||
→ queue_gate_attempt + enqueue_gate_attempt_job
|
||||
→ Worker claim_and_run_gate_attempt
|
||||
→ execute_queued_attempt → handler(_task_payload + internal)
|
||||
→ complete_gate_attempt → 再入队下一 Gate
|
||||
```
|
||||
|
||||
关键落点:
|
||||
|
||||
| 角色 | 文件 | 函数 |
|
||||
| --- | --- | --- |
|
||||
| 任务级提交 | `auto_progress_controller.py` | `submit_auto_progress` |
|
||||
| Attempt 收口续跑 | `process_gate_service.py` | `complete_gate_attempt` → `_enqueue_auto_progress_after_gate_pass` |
|
||||
| Worker | `process_gate_job_service.py` / `jobs/handlers/shipping_process_gate.py` | `claim_and_run_gate_attempt` |
|
||||
| 分发 | `process_gate_executor.py` | `execute_queued_attempt` / `_task_payload` |
|
||||
| 事实投影 | `process_gate_bridge.py` | `sync_fulfillment_gates_from_task` |
|
||||
|
||||
### Gate 13–20 分类(今天)
|
||||
|
||||
| Gate | 好模式? | 今天主路径 |
|
||||
| ---: | --- | --- |
|
||||
| 13 preparation | ✅ | **新 Attempt** 跑 `ensure_inventory`;不内嵌 match/excel |
|
||||
| 14 field_mapping | ⚪ 事实门禁 | 多为 **sync 投影**;恢复路径 `from_field_mapping` **同 Attempt 嵌套 match**(次要债务) |
|
||||
| 15 matching | ❌ | **新 Attempt** 跑 match,但成功后 **`try_auto_chain` 同 Attempt 内嵌 generate±upload** |
|
||||
| 16 sufficiency | ⚪ 事实/人工 | sync / recheck;短缺则 **人工** |
|
||||
| 17 excel_readiness | ✅ 事实门禁 | sync / recheck **不生成** Excel |
|
||||
| 18 artifact | ❌ 契约有、开心路径绕过 | 自动成功靠 match 内嵌;手动「重新生成」才走 `_handle_regenerate_excel` **新 Attempt** |
|
||||
| 19 freight RPA | 部分 | 有独立 Handler;`AUTO_UPLOAD` 时可被 chain 嵌套 |
|
||||
| 20 manual handoff | ✅ | **owner 人工**;auto enqueue 跳过 |
|
||||
|
||||
### 目标开心路径
|
||||
|
||||
```text
|
||||
Attempt(prep) → pass → enqueue
|
||||
Attempt(match) → 仅匹配 + sync 事实 → pass → enqueue
|
||||
[可选 Attempt/sync excel_readiness]
|
||||
Attempt(artifact) → generate_excel(_task_payload) → pass → enqueue
|
||||
Attempt(freight) 或 停在 manual_upload(人工)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## File map
|
||||
|
||||
| 文件 | 职责 |
|
||||
| --- | --- |
|
||||
| `fulfillment_workflow.py` | 收缩/拆分 `try_auto_chain_after_match`;match 成功不再 generate/upload |
|
||||
| `process_gate_executor.py` | 确认 match handler 只 sync+return;artifact handler 保持原子 |
|
||||
| `process_gate_bridge.py` | sync:无 Artifact 时 **不得**把 artifact 标 passed;可保留 readiness 资格投影 |
|
||||
| `process_gate_service.py` | 确认 match pass 后续跑能落到 `regenerate_excel_artifact` |
|
||||
| `auto_progress_controller.py` | 确认 technical next_action 覆盖 artifact |
|
||||
| `process_gate_contract.py` | 如需:明确 artifact 自动 next_action / 配置开关语义 |
|
||||
| `docs/features/shipping-notice/process-gate-recovery-contract.md` | 记录「禁止跨 Gate 内嵌产物」 |
|
||||
| `docs/features/shipping-notice/technical.md` | 删改 `try_auto_chain` 开心路径描述 |
|
||||
| 测试 | STP acceptance、auto_progress、process recovery、line rematch、excel regenerate |
|
||||
|
||||
---
|
||||
|
||||
### Task 1: 红灯 — 匹配 Attempt 不得生成 Excel;artifact 须有独立 Attempt
|
||||
|
||||
**Files:**
|
||||
- Create/Modify: `backend/tests/test_shipping_gate_orchestration_separation.py`(新建聚焦文件)
|
||||
- 可参考:`test_shipping_notice_stp_acceptance.py`、`test_shipping_auto_progress_p0_3.py`、`test_shipping_process_recovery_plan.py`
|
||||
|
||||
- [x] **Step 1–3: 红灯测试已写入并随实现转绿**(见 `test_shipping_gate_orchestration_separation.py`)
|
||||
- [ ] **Step 4: 本地 commit(仅当用户要求)**
|
||||
|
||||
---
|
||||
|
||||
### Task 2: 拆除 match 内嵌 `try_auto_chain` 产物副作用
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/fulfillment_workflow.py`
|
||||
- Modify: `backend/tests/test_shipping_notice_stp_acceptance.py`(改写旧「chain 必调 generate」断言)
|
||||
|
||||
- [x] **Step 1: 收缩 `try_auto_chain_after_match`**
|
||||
- [x] **Step 2: 更新 STP acceptance 测试**(Gate 路径不调 generate;遗留路径只 submit auto_progress)
|
||||
- [x] **Step 3: 跑聚焦测试**(orchestration separation 全绿;STP chain 相关用例绿)
|
||||
|
||||
---
|
||||
|
||||
### Task 3: 保证 match pass 后续跑落到独立 `artifact_generation` Attempt
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/process_gate_bridge.py`(必要时)
|
||||
- Modify: `backend/app/services/shipping_notice/process_gate_service.py` / `process_gate_contract.py`(若 next_action 未自动露出)
|
||||
- Modify: `backend/app/services/shipping_notice/process_gate_executor.py`(仅确认 `_handle_regenerate_excel` 不变)
|
||||
|
||||
- [x] **Step 1: sync 规则收紧**(STEP 6A 无 export 不得 passed;保留 regenerate next_action)
|
||||
- [x] **Step 2: 确认 enqueue 不跳过 artifact**(`_auto_generate_excel_enabled` 门控入队)
|
||||
- [x] **Step 3: 绿灯 Task1 入队断言**
|
||||
- [x] **Step 4: recovery / auto_progress_p0_3 聚焦回归通过**
|
||||
|
||||
---
|
||||
|
||||
### Task 4: 端到端编排回归(prep → match → artifact → handoff)
|
||||
|
||||
**Files:**
|
||||
- Modify/Create: `backend/tests/test_shipping_gate_orchestration_separation.py` 增加集成用例
|
||||
- 可选:轻量 spy Job enqueue,避免真实 RPA
|
||||
|
||||
- [x] **Step 1: 集成断言**(`test_happy_path_generate_excel_only_in_artifact_attempt`)
|
||||
- [x] **Step 2: 跑测试至全绿**
|
||||
|
||||
---
|
||||
|
||||
### Task 5: 次要债务(可同 PR 或 follow-up)— 恢复路径嵌套
|
||||
|
||||
**Files:**
|
||||
- Modify: `process_gate_executor.py` → `_handle_retry_inventory_from_field_mapping`
|
||||
|
||||
- [x] **Step 1: 评估范围** — **Follow-up P1**(本迭代不拆):映射恢复 Attempt 仍嵌套 `_handle_retry_inventory_matching`;函数注释已标注目标形态。
|
||||
|
||||
- [ ] **Step 2: 若本迭代纳入** — 延期。
|
||||
|
||||
---
|
||||
|
||||
### Task 6: 文档与死代码标注
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/features/shipping-notice/process-gate-recovery-contract.md`
|
||||
- Modify: `docs/features/shipping-notice/technical.md`(`try_auto_chain` / auto excel 相关)
|
||||
- Modify: `progress_workflow.py` 文件头注释(标明 P0-3 后旧跨 Gate 体为 dead)
|
||||
|
||||
- [x] **Step 1: 契约增补一条硬规则**
|
||||
- [x] **Step 2: technical.md 开心路径改为「match pass → enqueue artifact Attempt」**
|
||||
- [x] **Step 3: 可选清理** — `_dispatch_legacy_orchestration` / STEP 3 注释标 DEPRECATED。
|
||||
|
||||
---
|
||||
|
||||
### Task 7: 验收清单(人工)
|
||||
|
||||
- [ ] 重匹配成功后:诊断/Attempt 列表出现 **独立的** `artifact_generation` Attempt(不仅是 matching)。
|
||||
- [ ] 右卡在生成中短暂停留「Excel 生成」而非匹配完成后瞬间跳过。
|
||||
- [ ] 生成失败:仅 artifact Attempt `blocked_retryable` +「重新生成 Excel」;matching 保持 passed。
|
||||
- [ ] `AUTO_GENERATE_EXCEL=false`:匹配通过后停在可点「重新生成」,不静默 noop。
|
||||
- [ ] `AUTO_UPLOAD=true`:artifact pass 后再出现 freight Attempt(不在 match 内嵌 upload)。
|
||||
- [ ] i18n / `can_fulfill_complete_line` 等已合入改动回归仍正常。
|
||||
|
||||
---
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
| 风险 | 缓解 |
|
||||
| --- | --- |
|
||||
| 匹配通过后若 enqueue 失败会停在无 Excel | 测试锁 enqueue;失败时 UI 仍有 regenerate |
|
||||
| 延迟增加(多一个 Job) | 可接受;观测性优先 |
|
||||
| 旧 chat tool 仍调 `try_auto_chain` | Gate 路径切断;遗留路径改为只 submit auto_progress |
|
||||
| sync 与 enqueue 竞态 | 沿用现有 Job 去重 / idempotency_key;禁止 sync 提前 passed artifact |
|
||||
|
||||
回滚:恢复 `try_auto_chain` 内 generate(仅应急);正式修复应保留独立 Attempt。
|
||||
|
||||
---
|
||||
|
||||
## 建议实施顺序
|
||||
|
||||
1. Task 1 红灯
|
||||
2. Task 2 拆 chain
|
||||
3. Task 3 sync + enqueue
|
||||
4. Task 4 集成
|
||||
5. Task 6 文档
|
||||
6. Task 5 视排期
|
||||
7. Task 7 人工验收
|
||||
|
||||
**非目标(本计划不做):** 重写 20 Gate 模型、改前端按钮契约、合并 excel_readiness 与 artifact、删除全部 legacy auto_progress 函数体。
|
||||
@@ -0,0 +1,181 @@
|
||||
# 货代域状态契约统一(Phase A–E)
|
||||
|
||||
> **日期**:2026-09-06
|
||||
> **范围**:shipping-notice 对外状态词 / 投影边界
|
||||
> **权威手册**:落地后同步 [`docs/features/shipping-notice/technical.md`](../../features/shipping-notice/technical.md)「状态契约统一」节
|
||||
> **Phase A 状态**:已完成(`project_notice_upload_status` / `project_facts_upload_state`)
|
||||
> **Phase B/D/E 状态**:已完成(2026-09-06;C 仍待做)
|
||||
> **本轮未做**:Phase C match 拆名;D1c 全局停发 `pending_human_reason`
|
||||
|
||||
---
|
||||
|
||||
## 1. 方法论(以 Phase A 为模板,B–E 强制同款)
|
||||
|
||||
Phase A 已验证的最佳实践,**后续 Phase 一律照此执行**,不再用「过渡期同义词 / 双读 / LEGACY 兜底」:
|
||||
|
||||
| 原则 | 含义 | 反例(禁止) |
|
||||
|---|---|---|
|
||||
| **单一判词** | 每个对外字段、每个语义位只有一个规范词;调用方只写 `== 'canonical'` | `{'uploaded','succeeded','success'}`、`includes([...])` |
|
||||
| **单点投影** | 跨层翻译只发生在**一个** projector/mapper;业务/FE 禁止再造轮子 | 各文件自写 frozenset、入口散落 OR |
|
||||
| **层内一词 ≠ 层间一词** | Attempt / Artifact / Job / Gate / Tool 可保留各自库内词;**同名对外字段**必须经投影后只暴露本层契约词 | 把 Attempt.`succeeded` 直接塞进名为 `upload_status` 的 API |
|
||||
| **硬切、无历史兼容** | 不读旧别名、不双字段镜像、不 LEGACY-UNIFY;测试与 FE 同步删兜底 | 「先发双认、下个版本再删」 |
|
||||
| **故意双层保留** | Gate→`user_status`、五段 `lifecycle_stage` vs 15 段 stage、`lifecycle_status` vs runtime 是**分层设计**,不是同义词债 | 为了「统一」把 F2 与 stage 压成一词 |
|
||||
|
||||
成功判据(每个 Phase 自检):
|
||||
|
||||
1. 存在唯一投影/映射函数(或已有契约 helper,禁止新建平行集合)。
|
||||
2. 调用点全部改为单一等值判断或既有域谓词(如 `has_verified_upload_success`)。
|
||||
3. 前后端测试不再断言或接受别名。
|
||||
4. `technical.md` 写明该字段的规范词与禁止项。
|
||||
|
||||
---
|
||||
|
||||
## 2. Review 结论(仍成立)
|
||||
|
||||
同类债不止 `upload_status`:内部枚举泄到对外字段、或同字段混多域词,迫使 frozenset / `includes` 兜底。
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph keep [故意双层_保留]
|
||||
Gate["Gate/Execution"] --> UserStatus["user_status F2六值"]
|
||||
Machine15["15段 processing stage"] --> Lifecycle5["lifecycle_stage 五段"]
|
||||
end
|
||||
subgraph done [Phase A_已收口]
|
||||
Attempt["Attempt.succeeded"] --> UploadProj["project_notice_upload_status → uploaded"]
|
||||
Attempt2["Attempt/Artifact"] --> FactsProj["project_facts_upload_state → succeeded"]
|
||||
end
|
||||
subgraph todo [B-E_待硬切]
|
||||
HumanMix["跨层: waiting_human / waiting_review / needs_human / idle"]
|
||||
MatchMix["同名多域: match_status"]
|
||||
JobMix["Job→automation 散落 synonym"]
|
||||
Hygiene["canceled/done/error 入口与读侧"]
|
||||
end
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Phase A — 上传边界(已完成 · 模板)
|
||||
|
||||
| 层 | 字段 | 规范成功词 |
|
||||
|---|---|---|
|
||||
| Attempt(库内) | `ShippingUploadAttempt.status` | `succeeded` |
|
||||
| Artifact(库内) | `ShippingExportArtifact.status` | `uploaded` |
|
||||
| Notice 面 API | `upload_status` | **`uploaded`**(经 `project_notice_upload_status`) |
|
||||
| facts | `facts.upload_state` | **`succeeded`**(经 `project_facts_upload_state` ∈ `PROJECTION_UPLOAD_STATES`) |
|
||||
| 业务完成谓词 | — | `has_verified_upload_success`(三层验证,非同义词 OR) |
|
||||
|
||||
调用方只允许 `projected == 'uploaded'` 或 `has_verified_upload_success`;禁止再读 Attempt 原词做成败。
|
||||
|
||||
---
|
||||
|
||||
## 4. Phase B — human-wait:跨层硬切(重评)
|
||||
|
||||
### 问题本质(与 A 不同)
|
||||
|
||||
**不是**同一语义的多别名,而是 **把不同层的词当成同义词**:
|
||||
|
||||
| 层 | 规范词 | 用途 |
|
||||
|---|---|---|
|
||||
| Wire `user_status`(F2) | **`waiting_human`** 等六值 | 唯一用户主态;已有 `user_status_for_gate_status` |
|
||||
| Processing / lifecycle **stage** | 可含 `waiting_review`、`order_review` 等 | 阶段位置,**不是** user_status |
|
||||
| Tool 响应 `status` | `needs_human` | Agent/Tool 契约,**不得**泄入 `user_status` |
|
||||
| 废弃/脏词 | `idle`、`pending_review` 作 user_status | **停发**;读侧不认 |
|
||||
|
||||
当前债:FE [`normalizeLifecycleStatus`](../../../frontend/src/features/chat/shipping/conversationProcessingProjection.ts) 的 `[LEGACY-UNIFY]` 把 `waiting_human` 压成 `waiting_review`;卡片仍 `waiting_human \|\| idle`。
|
||||
|
||||
### 落地做法(同款原则)
|
||||
|
||||
1. **不新造** synonym projector;复用 `process_gate_contract.USER_FACING_TASK_STATUSES` + 既有 Gate→user mapper。
|
||||
2. 后端保证 wire `user_status` ∈ F2 六值;**禁止**把 stage 词或 Tool `needs_human` 写入 `user_status`。
|
||||
3. FE:**删除** LEGACY-UNIFY;`userStatus === 'waiting_human'` 单判;文案/stage 走独立 stage 字段。
|
||||
4. **无兼容期**:停发即删读侧别名;测试锁定混层必失败。
|
||||
|
||||
### 不做
|
||||
|
||||
- 不把 `waiting_review` 并进 `waiting_human`(那是 stage)。
|
||||
- 不把 Tool `needs_human` 改成 `waiting_human`(换一层契约,属于另案)。
|
||||
|
||||
---
|
||||
|
||||
## 5. Phase C — match_status:同名多域拆字段(重评)
|
||||
|
||||
### 问题本质
|
||||
|
||||
**同音异义(homonym)**,不是同义词:`match_status` 被 inventory / profile / STP / ledger 共用不同枚举。
|
||||
|
||||
### 落地做法
|
||||
|
||||
1. **拆名硬切**(无双读旧字段):
|
||||
- 任务履约:`inventory_match_status` ∈ {`fulfillable`,`partial`,`unfulfillable`,…}(以 `match.py` / 行聚合为准)
|
||||
- 模板路由:`profile_match_status` ∈ profile 路由枚举
|
||||
2. STP / ledger / audit **改写**到对应域词;禁止再用 `matched`/`shortage` 冒充 fulfillable 语义。
|
||||
3. 行级对外只发 `inventory_matched`;FE 删 `matched` 双认。
|
||||
4. 单点:聚合只走既有 `aggregate_match_status_for_task`(或改名后的唯一出口),调用方 `==` 域内一词。
|
||||
|
||||
### 不做
|
||||
|
||||
- 不写「旧 match_status OR 新字段」过渡读。
|
||||
- 不把三域枚举塞进一个 frozenset「统一成功」。
|
||||
|
||||
---
|
||||
|
||||
## 6. Phase D — blocking_reason / Job→automation(重评)
|
||||
|
||||
### D1 `blocking_reason`
|
||||
|
||||
- Wire **只暴露** Gate 形 `blocking_reason` / `blocking_reason_code`。
|
||||
- `pending_human_reason`:可留作写库镜像,**读 API 停发、FE 停读**(硬切,不做双字段兼容窗口)。
|
||||
- 判定复用既有 Gate 投影,不新造 reason synonym 表。
|
||||
|
||||
### D2 Job → Case `automation.status`
|
||||
|
||||
- 抽取**唯一** `project_job_to_automation_status(job, …)`(落点靠近现有 [`order_review_workbench_projection`](../../../backend/app/services/shipping_notice/order_review_workbench_projection.py) 内联逻辑)。
|
||||
- Job 库内可保留 `succeeded`/`dead` 等;**mapper 内**翻译一次;调用方只见 Case automation 枚举,禁止 `{succeeded,success,completed}` / `{failed,dead}` 散落。
|
||||
- FE 只消费投影后的 automation 枚举。
|
||||
|
||||
---
|
||||
|
||||
## 7. Phase E — 入口卫生 + 不变量门禁(重评)
|
||||
|
||||
与「兼容入口归一」旧表述不同:**读侧零别名,写侧单点规范化**。
|
||||
|
||||
1. 每个子系统一个 write-path normalizer(取消态只认 `cancelled`;禁止读侧再认 `canceled`/`done` 作同义)。
|
||||
2. `failed`/`error`/`fatal`:对外失败词按该层契约定一词;其余只在 mapper 入口吸收并**立刻写成规范词**,库外不泄漏。
|
||||
3. 不变量测试:关键 API 字段 ∈ 契约集合;**禁止**在 projector 模块外新增 synonym frozenset(CI/单测扫描或显式白名单)。
|
||||
4. Phase A 已示范:成功路径不留 `success` 对外出口。
|
||||
|
||||
---
|
||||
|
||||
## 8. 执行顺序与切片
|
||||
|
||||
| Phase | 状态 | 建议触发 | 依赖 |
|
||||
|---|---|---|---|
|
||||
| **A** 上传投影 | **完成** | — | — |
|
||||
| **B** human-wait 跨层硬切 | **完成** | — | 不动 Gate→user 设计 |
|
||||
| **C** match 拆名 | 待做 | STP/ledger 再踩坑或 API 演进窗口 | 独立变更,忌与 B 绑死 |
|
||||
| **D** reason / automation | **完成(D1b+D2)** | D1c 全局 PH 停发可另开 | 写路径 PH 列保留 |
|
||||
| **E** 卫生门禁 | **完成(最小门禁)** | 全量入口归一可跟 C | `test_shipping_status_contract_hygiene` |
|
||||
|
||||
**禁止**:发现债就一次清完;每个 Phase 单独可验证、单独可回滚。
|
||||
|
||||
---
|
||||
|
||||
## 9. 明确保留(不要合并)
|
||||
|
||||
- Gate/Execution → `user_status`(F2)
|
||||
- `lifecycle_stage`(五段)vs 15 段 processing stage(`freight_upload` vs `freight_uploading` 属分层)
|
||||
- `lifecycle_status`(active/voided/…)vs runtime status
|
||||
- STP `progress_nodes` 诊断 ≠ UI 真源
|
||||
- FileAsset.`upload_status`(另一产品面)
|
||||
|
||||
---
|
||||
|
||||
## 10. 与旧计划差异(本次重评)
|
||||
|
||||
| 旧表述 | 新表述 |
|
||||
|---|---|
|
||||
| B:冻结 wire,LEGACY 后端停发后再删 FE | B:**立即硬切**;删 LEGACY-UNIFY;跨层分词而非 synonym 合并 |
|
||||
| C:拆分/冻结,可过渡 | C:**拆名硬切、无双读** |
|
||||
| D:双字段可共存一段时间 | D:**读侧只留 blocking_reason**;PH 停发 |
|
||||
| E:入口归一 + 兼容拼写 | E:**写侧单点规范化 + 读侧零别名**;不变量禁 frozenset 扩散 |
|
||||
| 「过渡期同义词兜底」 | **全面取消**;与 Phase A 一致 |
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
# 发货 Excel 单据编号与库存结果重读设计
|
||||
|
||||
## 背景与目标
|
||||
|
||||
当前 `ShippingNotice.business_no` 在客户确认/正式建单时分配,并被工作台展示为“发货通知单号”。这与实际业务不一致:现有的 `ShippingNotice` 就是发货通知单实体,但应延后到其 Excel 首次成功生成的同一业务事务中创建;一个发货通知单可覆盖多条订单明细,而每条订单明细只能归属一个有效发货通知单。Excel 是发货通知单的外在文件表示,不是业务主实体。
|
||||
|
||||
同时,库存 RPA 超时后,业务人员需要先重新读取已经产生但未被系统消费的库存结果;该操作不得再次触发 RPA。
|
||||
|
||||
本设计的目标是:
|
||||
|
||||
1. 复用现有 `ShippingNotice` 承载单号和订单明细归属,而非以 Excel Artifact 承载业务身份。
|
||||
2. 保证发货通知单与首次生成的 Excel 在同一事务中产生;一个通知单覆盖一个固定的订单明细集合。
|
||||
3. 在库存 RPA 超时后,提供只读取并挂接有效库存快照的恢复动作。
|
||||
|
||||
## 数据模型与编号边界
|
||||
|
||||
复用现有 `ShippingNotice` 作为发货通知单实体,使用其 `business_no`、业务日期、日内流水、规则版本、所属正式订单及状态字段;其现有 Reservation/Artifact 明细关联以订单明细为外键,并对有效归属建立唯一约束。`ShippingExportArtifact` 只保存该通知单的 Excel 文件版本和生成输入快照。
|
||||
|
||||
首次生成 Excel 时,在同一数据库事务内完成以下操作:
|
||||
|
||||
1. 根据经库存匹配确认的订单明细/Reservation 创建现有 `ShippingNotice`,并冻结其归属集合。
|
||||
2. 按客户、上海业务日期为该发货通知单分配业务编号。
|
||||
3. 创建并校验该通知单的首个 Excel Artifact,并将 Artifact 关联到通知单。
|
||||
4. 提交事务后才将发货通知单、Excel 文件及单号作为正式结果对外展示。
|
||||
|
||||
编号写入失败、明细绑定失败或 Artifact 校验失败时,整个生成事务失败,不得暴露发货通知单、无编号 Excel 或订单明细占用。
|
||||
|
||||
新流程不再在客户确认/正式订单创建阶段分配 `ShippingNotice.business_no`,而是在创建该 Notice 与首个 Excel 的同一事务分配。历史记录仍可查询、下载和审计;新投影和新货代操作使用该 Notice 的 `business_no`。
|
||||
|
||||
一个 `ShippingNotice` 恒等于一张发货通知单、一个业务编号和一个 Excel。分批发货时,每个 Excel 都必须创建独立 `ShippingNotice` 并分配独立单号;不得在同一 Notice 下创建第二个 Excel Artifact。模板修订或技术故障需要重出文件时,沿用既有文件修复/替代机制,不得将第二个有效 Excel 挂到同一 Notice,也不得改变已冻结订单明细集合。
|
||||
|
||||
## API、投影与 UI
|
||||
|
||||
处理工作台的“发货通知单号”仅在发货通知单及其首个 Excel 均已在同一事务中成功生成后展示。生成 Excel 前不显示该字段。
|
||||
|
||||
下载 Excel、RPA 上传、人工确认上传、批量上传投影与审计查询均按发货通知单号精确定位通知单,再读取其当前有效 Excel 和已冻结明细集合。不得再把整单 `task_no` 或新流程中的 `ShippingNotice.business_no` 当作外部发货通知单号。
|
||||
|
||||
既有按 Notice 级 `business_no` 的路由和审计语义保持不变。过渡期须兼容历史“先建 Notice 后生成 Excel”的数据;新数据仅在首个 Excel 成功生成时创建 Notice 并分配其 `business_no`。
|
||||
|
||||
## 库存结果重读动作
|
||||
|
||||
新增正式 Gate action:`reload_inventory_result`,仅归属 `inventory_preparation`。
|
||||
|
||||
该动作执行步骤:
|
||||
|
||||
1. 根据当前任务已冻结的库存源和仓库身份查找最新、未过期、状态为 ready 的库存快照。
|
||||
2. 复用现有身份校验和 `link_snapshot_to_task` / `link_snapshot_to_task_for_preparation` 逻辑挂接快照。
|
||||
3. 从快照 JSON 或存储文件读取库存行,并调用既有库存加载/门禁同步流程。
|
||||
4. 写入独立审计事件,记录命中的快照、来源、仓库及读取结果。
|
||||
|
||||
该动作严禁调用 trigger 写入、`retry_rpa` 模式或创建新的 RPA Attempt。未找到有效快照、快照过期或身份不匹配时,以可恢复阻断返回,并下发“重新获取库存”(现有 `retry_inventory_preparation`,明确为重新运行 RPA)和上传库存文件的替代路径。
|
||||
|
||||
RPA 超时对应的 `inventory_preparation` Gate 应将 `reload_inventory_result` 作为首选主动作;用户主动选择“重新获取库存”时才重新创建 RPA 导出。
|
||||
|
||||
## 错误处理与审计
|
||||
|
||||
所有新增 API/服务错误保持 `{ success, data | error, request_id }` 契约,业务失败使用既有 `AppError` 子类。新增错误码必须同步四语言 `errors.json`。
|
||||
|
||||
审计必须能回答:哪个发货通知单在何时因首次 Excel 生成而创建、覆盖哪些 Reservation/订单明细、其当前及历史 Excel Artifact 分别是什么;以及库存重读是否命中快照、为何未命中、是否发生任何 RPA trigger(该操作必须为否)。
|
||||
|
||||
## 测试与验收
|
||||
|
||||
后端测试至少覆盖:
|
||||
|
||||
1. 客户确认和正式建单后不再分配新 Notice 级编号。
|
||||
2. 发货通知单与其首个 Excel Artifact 在同一事务中创建并分配通知单号。
|
||||
3. 同一发货通知单可绑定多个明细;同一明细不能归属两个有效发货通知单;分批导出必须创建不同 Notice、不同单号和不同 Excel。
|
||||
4. 通知单创建、编号、明细绑定或首个 Artifact 校验失败时不留下可用通知单、Excel、单号或 Reservation 占用。
|
||||
5. 同一 Notice 不能生成第二个有效 Excel;分批导出创建新 Notice,并保留 Reservation/明细不可重复归属约束。
|
||||
6. `reload_inventory_result` 命中有效快照时完成挂接和库存加载,且不写 RPA trigger、不创建 RPA Attempt。
|
||||
7. `reload_inventory_result` 无可用快照时返回可恢复阻断,允许用户明确选择重新运行 RPA。
|
||||
8. RPA 超时投影首选“重新读取库存结果”。
|
||||
|
||||
前端测试至少覆盖:Artifact 单号未生成时不显示、生成后显示;RPA 超时时主按钮为“重新读取库存结果”,并保留“重新获取库存(重新运行 RPA)”作为替代动作。四种语言(zh-CN、zh-TW、en、th)均提供新增文案。
|
||||
|
||||
## 非目标
|
||||
|
||||
- 不为每条订单明细生成单独单号;订单明细只能通过通知单明细关联归属一个有效发货通知单。
|
||||
- 不改变库存 RPA Worker、trigger 文件格式、callback 协议或已存在的重新 RPA 行为。
|
||||
- 不修改历史数据的已有 Notice 单号;仅提供兼容读取。
|
||||
@@ -0,0 +1,198 @@
|
||||
# 设计:订单生命周期工作台「下游工作面」单源投影收敛(彻底单源化)
|
||||
|
||||
日期:2026-09-01
|
||||
状态:已确认(方案 2 彻底版:不做历史兼容 / 旧行为保留)
|
||||
关键词:shipping-workbench / fulfillment-prep / freight-upload / upload-complete / single-source-projection / FOIU / skeleton-loading
|
||||
|
||||
> 本文档承接 `2026-08-31-shipping-workbench-stage-lazy-load-design.md`(阶段懒加载)与
|
||||
> `2026-09-01-shipping-stage-capability-window-design.md`(阶段能力集),聚焦订单生命周期工作台
|
||||
> **下游工作面**(通知准备 / 货代上传 / 通知完成)与右卡「当前任务/场景」的**两次投影 /
|
||||
> 先只读后可编**闪烁,并以**彻底单源化**根治。
|
||||
|
||||
## 背景与问题
|
||||
|
||||
进入「通知准备」(`fulfillment_prep`)时,页面先后进入两个状态(用户观察):
|
||||
|
||||
1. **图1(首投影)**:库存匹配表仅有列头、无行数据(或行退化)、右侧「当前任务」显示
|
||||
「步骤未指定」、**不可编辑**(无勾选列、无「选择出库单明细 / 生成发货通知单」工具条)。
|
||||
2. **图2(次投影)**:行矩阵完整、顶部出现 `PJO | ZN…` 订单摘要、右卡显示「场景: 库存匹配」、
|
||||
**可编辑**(工具条 + 勾选列 + 生成按钮出现)。
|
||||
|
||||
用户在 1→2 之间看到「先不可编辑、再变可编辑」的闪烁 —— 即「两次投影 / 不可编辑→可编辑」。
|
||||
|
||||
## 根因(why)
|
||||
|
||||
下游工作面是一个**由多个相互独立、异步到达、且到达时刻不一致的投影拼装**的复合 UI:
|
||||
|
||||
| 表面要素 | 当前来源投影 | 到达通道 |
|
||||
|---|---|---|
|
||||
| 行矩阵内容 / `capabilities` / `source_options` | `formalTaskDetail.ui_state.stage_context.preparation` | `loadFormalTaskDetail()`(挂载预取 + `hasFormalOt` watcher + `progressVersion` watcher) |
|
||||
| **可编辑**(勾选列 / 波次出单工具条) | `activeCase.available_actions` 含 `edit_formal_task` | `loadReviewCase()`(进入下游阶段才懒加载) |
|
||||
| 顶部订单摘要 | `activeCase.draft.header_values.po_number` + `documentNavItems` | `loadReviewCase()` |
|
||||
| 客户 PO 行号列 | `displayCase.schema.fields` + `displayDraftLines` | `loadReviewCase()` |
|
||||
| 右卡「场景/下一步」 | `shippingProcessingProjection`(主)+ `activeCase.current_stage`(兜底) | `useShippingProcessingWorkItem`(轮询) |
|
||||
|
||||
下游各段的渲染门仅为 `hasCreatedShippingTask && formalTaskDetail && <stage>`;而
|
||||
「可编辑性 + 摘要 + 客户 PO 列 + 右卡阶段兜底」都依赖 **`activeCase`(review Case)**。下游阶段
|
||||
`activeCase` 默认**不加载**、要等 `loadReviewCase` 二次触发 → 与 `formalTaskDetail` 错峰 → 先只读残缺
|
||||
(图1),后可编辑完整(图2)。
|
||||
|
||||
> 行业定性:这是 **Flash of Incomplete UI(FOIU)/ loading 状态泄漏**。React Query / SWR / Relay
|
||||
> 的核心约定是一个资源只有 `isLoading → data`(或 `isLoading → error`),**禁止把"已渲染但语义上是
|
||||
> 半成品"的中间态当作真实状态**。当前实现恰好把"内容已到、可编辑性未到"当作"就绪",于是泄漏了
|
||||
> 半成品只读态。
|
||||
|
||||
## 五阶段双投影审计(2026-09-01 全量核查)
|
||||
|
||||
对五个阶段逐面核查「是否由多个独立、异步、错峰到达的投影拼装」。结论如下:
|
||||
|
||||
| 阶段 / 面 | 主来源投影 | 是否双投影 | 说明 | 处置 |
|
||||
|---|---|---|---|---|
|
||||
| 接收解析 `intake_parse` | `activeCase` + `intakeParseContext` | 否(低风险) | 编辑器单源;context 有授权门 + `caseContentSkeleton` 骨架 | 边界外(编辑器单源) |
|
||||
| 订单复核 `order_review` | `activeCase` | 否 | 复核编辑器单源;`caseContentSkeleton` 骨架 | 边界外(编辑器单源) |
|
||||
| **通知准备 `fulfillment_prep`** | `formalTaskDetail.ui_state` + **`activeCase`(`formalEditable`)`** | **是(核心)** | 可编辑性/摘要/客户 PO 列依赖懒加载 `activeCase` → 先只读后可编 | **彻底单源化** |
|
||||
| 货代上传 `freight_upload` | `formalTaskDetail`(门)+ `freightNoticeGroups` | 否 | 内容/动作来自任务级 `group.available_actions`(非 `activeCase`);有 `freightNoticeGroupsLoading` 占位 + stale-while-revalidate | 一并单源化(门/内容仍任务级) |
|
||||
| 通知完成 `upload_complete` | `formalTaskDetail`(门)+ `freightNoticeGroups` | **是(轻)** | 段内**缺加载占位**:直接渲染 `uploadedFreightNoticeGroups.length`,直入时闪「0 已上传/空」再填充 | **补加载占位** |
|
||||
| **右卡「当前任务/场景」(跨全部阶段)** | `shippingProcessingProjection`(主)+ **`activeCase.current_stage`(兜底)** | **是(跨阶段)** | 下游阶段 `activeCase` 不加载 → 阶段兜底缺失 → 先「步骤未指定」占位后真值(`currentProcessingStageDisplay`,`ShippingOrderReviewView.vue:223`) | **彻底单源化** |
|
||||
|
||||
**结论**:根治对象为**全部下游工作面(通知准备 / 货代上传 / 通知完成)+ 右卡当前任务/场景**。
|
||||
两个编辑器阶段(接收解析 / 订单复核)本就是单源(`activeCase` 为其权威),保持不动。
|
||||
|
||||
## 方案(彻底单源化:后端驱动 + 前端原子渲染)
|
||||
|
||||
### §1 目标与边界
|
||||
|
||||
**目标**:让**所有下游工作面**(通知准备 / 货代上传 / 通知完成)与**右卡当前任务/场景**完全脱离
|
||||
`activeCase` / `displayCase` / `formalEditable`,只由**一个权威投影** `formalTaskDetail.ui_state`
|
||||
(+ 既有的 `shippingProcessingProjection` 承担实时自动化/进度)驱动,一次原子渲染,消除一切
|
||||
「先只读后可编 / 空→有 / 步骤未指定→场景」的两跳。
|
||||
|
||||
**边界(不做)**:
|
||||
- 不改顶部五阶段导航结构。
|
||||
- 不重构「订单复核 / 接收解析」编辑器(`activeCase` 是它们的权威单源;见审计表)。
|
||||
- 不引入 GraphQL / BFF / 新框架 / 新状态库。
|
||||
|
||||
### §2 后端:`ui_state` 作为下游工作面唯一权威(单源 DTO)
|
||||
|
||||
`build_task_ui_state`(经 `/shipping-tasks/<task_no>?view=workbench`,恒 `include_stage_context=True`,
|
||||
见 `api/workspace/shipping_notice.py:557`)是下游工作面的**唯一权威**。在其已有基础上补齐
|
||||
下游面当前被迫从 review Case 取的字段:
|
||||
|
||||
```jsonc
|
||||
// stage_context.preparation(在现有 status/lines/source_options/source_locked/capabilities 基础上)
|
||||
{
|
||||
"editable": true, // 【新增】任务级:本正式 OT 已确认且非仅查看 → 工作面可操作
|
||||
// preparation_lines[] 新增原生 customer_po_line_no(业务核对主键;区别于已下发的 line_no/line_no_source,
|
||||
// 后者可能退化为内部行序 sequence)。列头用标准字段名「客户 PO 行号」(standard_field_registry.py:134)i18n;
|
||||
// 列是否展示由前端按 prep 行是否含 customer_po_line_no 简单判定,无需单独后端标志。
|
||||
}
|
||||
// 【不在后端改】顶部「PJO | ZN…」摘要由前端用既有投影拼装:
|
||||
// file_name ← Run/Queue item;po_number ← shippingProcessingProjection.sourceSummary.poNumber;
|
||||
// version ← reviewProgressContext(reviewProgressVersionLabel);caseNo ← route 参数。
|
||||
// 不读 activeCase,也不新增后端 summary 字段。
|
||||
```
|
||||
|
||||
**关键决策**:
|
||||
- **`editable`(任务级)**:取值 == 现有 `edit_formal_task` 判据(`case.status=='confirmed'` 且存在
|
||||
`confirmed_task_no`,见 `order_review_projection.py:603-608`),即「live 已确认正式 OT,非历史/作废查看」。
|
||||
**后端判据(明确化)**:存在正式任务号(`task.order_task_no` / 关联 `confirmed_task_no`)**且**
|
||||
`task.lifecycle_status` 不属于 `{closed, cancelled}` 时置 `true`;被替换/历史/作废视图置 `false`。
|
||||
- **`edit_window` 不替代 `editable`**:`edit_window`(`editable_scope`,`order_edit_window_service.py:123`)
|
||||
是 D10 **字段级**`{header, lines}` 编辑窗,判据「无 Export Artifact 且无活动 Attempt」,Excel 生成后
|
||||
会变 `false`;而「波次出单」需要任务级「已确认 OT」。二者语义不同,不可互换。`edit_window` 仅用于
|
||||
正式任务编辑器字段级读写锁定。
|
||||
- **下游面零 `activeCase` 依赖**:`hasCreatedShippingTask` / `hasFormalOt` / `confirmedNoticeTaskNo`
|
||||
全部由 Run/Queue 摘要项(后端已带 `has_formal_ot`/`confirmed_task_no`,见
|
||||
`order_review_projection.py:1173-1174`)与 `ui_state` 供给,不再读 `activeCase`/`displayCase`。
|
||||
|
||||
### §3 前端:下游工作面只渲染该单源 + 原子门 + 骨架/占位
|
||||
|
||||
**通知准备**:
|
||||
- 新增 `preparationSurfaceReady`:`formalTaskDetail && ui_state.stage_context.preparation` 完整;
|
||||
未就绪渲染骨架(复用现有 `formalTaskDetailPending` 分支),就绪后**一次渲染完整可编辑面**。
|
||||
- 新增 `preparationEditable`:`computed(() => ui_state.stage_context.preparation?.editable ?? false)`;
|
||||
替换模板三处 `formalEditable`(勾选列 / 「选择出库单明细 + 生成发货通知单」工具条 / 行级选源)。
|
||||
- **删除 `formalPreparationContext` 的 `[B1]` 兜底**(回退 `displayCase.line_fulfillment` 正是"只读半成品"
|
||||
来源);Prep 面只认 `ui_state.stage_context.preparation`。
|
||||
- 顶部订单摘要改由**既有投影拼装**(Run/Queue item + `sourceSummary.poNumber` + `reviewProgressContext`),
|
||||
不再读 `activeCase`;客户 PO 行号列改由 §2 DTO(`lines[].customer_po_line_no`)供给,不再依赖
|
||||
`displayCase`/`displayDraftLines`/`lineSchemaFields`。
|
||||
|
||||
**货代上传 / 通知完成**:
|
||||
- 内容与动作继续由任务级 `freightNoticeGroups` + `group.available_actions` + `formalTaskDetail.ui_state`
|
||||
供给(本就是任务级,无 `activeCase`);**通知完成段补 `freightNoticeGroupsLoading` 加载占位**,
|
||||
消除直入时「0 已上传/空」先行。
|
||||
|
||||
**右卡当前任务/场景(真单源)**:
|
||||
- `currentProcessingStageDisplay` 的「当前阶段/场景」**只读 `shippingProcessingProjection`**(实时、轻量、已轮询),
|
||||
不读 `ui_state` / `activeCase.current_stage` —— 避免「同一语义多源先 A 后 B」的闪烁。
|
||||
- **投影未就绪** → 返回空阶段,由右卡在 `loading` 时渲染骨架占位(`stageLoading`);**不是**「步骤未指定」
|
||||
之类的误导值。`isLoading → data`,无两跳。
|
||||
- `ui_state` 不参与右卡阶段(它只用于下游工作面内容);终态「通知完成」由投影
|
||||
(`uiState.lifecycleStage==='upload_complete'` / `userStatus==='completed'`)判定。
|
||||
- 保留 `loading` fail-closed(投影读取中抑制可执行动作)语义。
|
||||
|
||||
**统一**:下游路径与 `activeCase` / `displayCase` / `formalEditable` 解除所有读关系;
|
||||
`loadReviewCase()` 只在进入「订单复核 / 接收解析」编辑器时触发(`REVIEW_EDITOR_NEEDED_STAGES`
|
||||
仅保留这两阶段)。
|
||||
|
||||
### §4 数据流(下游工作面原子首屏)
|
||||
|
||||
```
|
||||
Run + Queue(导航/阶段入口 + has_formal_ot/confirmed_task_no)──┐
|
||||
任务详情 view=workbench(ui_state 单源:行矩阵+capabilities+editable+摘要+客户PO列)──┼─ 并行
|
||||
work-item 投影(OT;右卡阶段/实时自动化/进度) ────────────────┘
|
||||
复核 Case + Evidence ── 默认不拉;进入「订单复核 / 接收解析」才拉
|
||||
```
|
||||
|
||||
各下游面模板门均为「该面单源就绪」原子门;loading→骨架/占位;ready→完整面;无中间只读/空态。
|
||||
|
||||
### §5 加载 / 错误 / 回归
|
||||
|
||||
**加载态**:骨架 / 加载占位;**错误态**:沿用 `formalTaskDetailLoadFailed` + 「重新加载」按钮;
|
||||
全程不出现「半成品只读 / 空→有」中间态。
|
||||
|
||||
**回归测试**(`frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts`):
|
||||
- 进入 Prep:`formalTaskDetail.ui_state` 单源就绪即渲染**完整可编辑矩阵**(勾选列 + 工具条 +
|
||||
「生成发货通知单」);无需二次 `activeCase`;无「只读→可编辑」翻转。
|
||||
- `activeCase` 缺省(下游懒加载)**不影响** Prep 可编辑性与行矩阵(顺序断言:`getReviewCase` 在
|
||||
下游阶段**不被调用**)。
|
||||
- 删除 `[B1]` 兜底后,`displayCase.line_fulfillment` 为空不降级为「只读半成品」。
|
||||
- 右卡:阶段**只由 `shippingProcessingProjection`** 供给;投影未到 → 空阶段 + 骨架占位,
|
||||
不出现「步骤未指定→场景」两跳,也不读 `ui_state`/`activeCase`。
|
||||
- 通知完成:直入(`freightNoticeGroups` 未就绪)时段内显示加载占位,不闪「0 已上传/空」。
|
||||
- 货代上传:保持既有加载占位。
|
||||
|
||||
**后端测试**(`backend/tests/test_shipping_*`):
|
||||
- `stage_context.preparation.editable` 在下发(`include_stage_context=True`)时存在且取值符合
|
||||
「已确认 OT」判据;历史/作废任务为 `false`。
|
||||
- `preparation_lines[].customer_po_line_no` 存在(原始客户 PO 行号,非 `line_no`)。
|
||||
- Run/Queue 摘要项 `has_formal_ot` / `confirmed_task_no` 在下游阶段稳定下发。
|
||||
|
||||
### §6 分阶段落地(小而可验证)
|
||||
|
||||
1. 后端:`ui_state.stage_context.preparation` 增 `editable`;`preparation_lines[]` 增
|
||||
`customer_po_line_no`(原生值,非 `line_no`)。跑 `test_shipping_*` 回归。
|
||||
(摘要不改后端:前端用既有投影拼装。)
|
||||
2. 前端:新增 `preparationSurfaceReady` + `preparationEditable`;替换三处门控;删除 `[B1]` 兜底与
|
||||
下游路径对 `activeCase`/`displayCase`/`formalEditable` 的全部读取;
|
||||
`currentProcessingStageDisplay` 改为**只读 `shippingProcessingProjection`**(投影未到 → 空阶段 +
|
||||
骨架占位,不读 `ui_state`/`activeCase`);摘要去 `activeCase`(既有投影拼装);客户 PO 列读
|
||||
`lines[].customer_po_line_no` + 标准 i18n 列头;`REVIEW_EDITOR_NEEDED_STAGES` 收窄到
|
||||
仅编辑器两阶段;通知完成段补 `freightNoticeGroupsLoading` 占位。`npm run build` 通过。
|
||||
3. 全量回归 + 手动核对(深链带 `task_no` / 批次中心跳转 / 通知准备直接进入),确认无任何
|
||||
「只读→可编辑 / 空→有 / 步骤未指定→场景」两跳;且下游阶段 Network 无 `getReviewCase`/`getReviewEvidence`。
|
||||
|
||||
**效能约束(实现时必须守住)**:
|
||||
1. 右卡阶段只由 `shippingProcessingProjection`(实时轻量轮询)驱动,不耦合 `formalTaskDetail` 重刷新节奏;
|
||||
2. `build_task_ui_state` 不增加触发频率(沿用 `deepLinkTaskPrefetch` + `formalTaskDetailGeneration`
|
||||
代际守卫 + `progressVersion` 变化检测);`view=workbench` 继续裁剪重字段,`ui_state` 只追加小字段;
|
||||
3. `loadFreightNoticeGroups` 保持 `freightGroupsInFlight` 去重 + stale-while-revalidate;
|
||||
4. 下游阶段请求计数 ≈3-4(Run+Queue+taskDetail+work-item),无 `getReviewCase`/`getReviewEvidence`。
|
||||
|
||||
## 自测入口
|
||||
|
||||
- 后端:`PYTHONPATH=D:\Workspace\HxProjects\hxops\backend`,
|
||||
`backend\.venv\Scripts\python.exe -m pytest tests/test_shipping_* -v`(测试环境慢,逐文件跑)。
|
||||
- 前端:`cd frontend && npm run build`(内含 `vue-tsc -b` 类型拦截)。vitest 因 `node:crypto`/vite8
|
||||
暂不可用,以前端 build + 手动核对为主。
|
||||
@@ -0,0 +1,233 @@
|
||||
# 2026-09-01 货代发货通知 — 下线旧 CheckPoint 状态机(收敛到 Gate + 领域数据分离)设计
|
||||
|
||||
> 目标:下线旧粗粒度状态机(`checkpoint` + `checkpoint_kind`),把"进程位置 / 是否人工 / 待办 / 按钮"改由**单一事实来源(SSOT)**推导:**履约+复核位置 = Gate(Process Gate)**,**review case 处置(非订单 / 文件质量异常)= 接收解析节点**,**文档 intake 文本抽取失败 = 文件质量异常处置**。业务领域数据保持独立标量字段,不塞进 Gate。
|
||||
> 前提:模块未正式上线(无历史兼容负担);不影响现有功能需求。这是**减法**。
|
||||
|
||||
---
|
||||
|
||||
## 1. 背景与问题
|
||||
|
||||
### 1.1 现状:两套状态机表达同一个履约进程
|
||||
|
||||
确认后 OT 的"进程位置 + 是否需要人工"存在**两套**表达:
|
||||
|
||||
| 层 | 表达 | 来源 | 现状 |
|
||||
|---|---|---|---|
|
||||
| CheckPoint(旧,粗) | 一个 `checkpoint` id + `checkpoint_kind`(AUTO_CONTINUE / MUST_HUMAN / WAIT_MANUAL_UPLOAD / COMPLETE) | `resolve_task_ui_state`(`state_machine.py:246`)从任务标量字段投影 | 与 Gate 概念重复 |
|
||||
| Process Gate(新,细) | 20 门禁 + Execution/Gate/Attempt + 恢复动作 + 幂等 | `process_gate_contract.py` / `process_gate_service.py` | 真正的工作流状态机 |
|
||||
|
||||
`checkpoint_kind` 那 4 分类**恰好是** `gate_status + responsible_party + blocking_reason → user_mode` 的一张粗查表。**CheckPoint 是 Gate 的粗投影,概念重复 → 违反单一事实来源(SSOT)。**
|
||||
|
||||
### 1.2 关键区分:状态机 ≠ 领域数据 ≠ 派生视图
|
||||
|
||||
这里要分清**三层不同的东西**:
|
||||
|
||||
| 层 | 是什么 | 来源 |
|
||||
|---|---|---|
|
||||
| **Gate** | 工作流/检查状态机(20 gate 各自的 status + attempt + 恢复动作 + 责任方 + 作废链) | Execution/Gate/Attempt 表 |
|
||||
| **领域数据** | `inventory_lines_json`(库存数据)、`export_file_path`(Excel 产物指针)、`match_status`(匹配结果值)、`upload_status`(上传结果) | **领域服务产出**(inventory/fulfillment/upload),Gate 只**校验**其是否就绪 |
|
||||
| **派生视图** | "进程位置 / 是否人工 / 待办 / 用户态 / 阶段摘要" | 旧机由领域数据投影;新设计**由 Gate 推导** |
|
||||
|
||||
**三个约束**:
|
||||
|
||||
1. **Gate ≠ 领域数据**:`inventory_lines_json` 装库存数据、`export_file_path` 是产物指针,Gate 表里没有这些。把领域数据塞进 Gate 会让状态机"爆炸",是过度设计。
|
||||
2. **不能把 Gate 压回领域数据列**:Gate 是**更富**的状态机(每个 gate 的 status/attempt/恢复/作废/责任方),几列标量表达不了;CheckPoint 当初正是因为"标量列太粗"才被 Gate 取代。压回去是倒退。
|
||||
3. **领域数据 ≠ Gate 的缓存**:领域数据是真实数据、由领域服务产出,不是对 Gate 状态的缓存;它只是被 Gate 校验。
|
||||
|
||||
行业最佳实践 = **状态机(Gate)+ 领域数据(标量字段)正确分离**;派生视图(位置/待办/状态)从 Gate 推导。
|
||||
|
||||
---
|
||||
|
||||
## 2. 设计原则
|
||||
|
||||
- **撤**:旧粗状态机(`checkpoint` + `checkpoint_kind`,即 `state_machine.TaskUiState` 的状态机投影)。
|
||||
- **留**:Gate(状态机)+ 标量字段(领域数据/结果)。不把数据塞回 Gate。
|
||||
- **不新增**:不新造第三套状态;只把"位置/是否人工/待办/按钮"从旧机迁到正确轴。
|
||||
- **SSOT**:履约+复核位置 = Gate;review case 处置 = 接收解析节点;领域数据 = 标量字段。
|
||||
|
||||
---
|
||||
|
||||
## 3. 最终 CP 去处(全部 20 个)
|
||||
|
||||
### 3.1 复核 gate(seq1-9,在执行链内)→ 从 Gate 读
|
||||
|
||||
| CP | 位置 | Gate |
|
||||
|---|---|---|
|
||||
| `CP_PARSE_REVIEW` | 解析需人审 | `order_field_extraction` / `document_profile_routing`(needs_human) |
|
||||
| `CP_CUSTOMER_REVIEW` | 客户身份确认 | `customer_resolution`(blocked_manual) |
|
||||
| `CP_RSV_REQ` | Reservation 需人审 | `reservation_validation`(blocked_manual) |
|
||||
|
||||
> 复核 gate 确实在 OT 执行链里(如 exec 51 的 seq5-9 均为 passed),故复核 CP 读 Gate 即可。
|
||||
|
||||
### 3.2 履约/上传/完成 gate(seq10-20)→ 从 Gate 读
|
||||
|
||||
| CP | Gate |
|
||||
|---|---|
|
||||
| `CP_INVENTORY_PENDING` | `inventory_preparation`(pending/queued/running) |
|
||||
| `CP_UPLOAD_REQ` | `inventory_preparation`(RPA 耗尽→补传库存文件) |
|
||||
| `CP_READY_MATCH` | `inventory_matching`(pending,字段映射 passed 后) |
|
||||
| `CP_READY_EXPORT` | `excel_readiness`(pending,满足性 passed 后) |
|
||||
| `CP_EXPORT_READY` / `CP_EXPORT_GENERATED` | `artifact_generation`(passed)→ 货代上传 |
|
||||
| `CP_UPLOAD_FAILED` | `freight_upload_rpa`(failed_terminal / blocked_retryable) |
|
||||
| `CP_UPLOAD_RESULT_UNKNOWN` | `freight_upload_rpa`(waiting_external) |
|
||||
| `CP_WAITING_UPLOAD` | `manual_upload_handoff`(blocked_manual) |
|
||||
| `CP_UPLOADED` | `manual_upload_handoff`(passed)/ `upload_complete` |
|
||||
| `CP_COMPLETED` | `upload_complete` |
|
||||
| `CP_INVENTORY_SOURCE_REVIEW` | `inventory_source_routing`(规则自动) |
|
||||
| `CP_ORDER_FREEZE` | `order_freeze_readiness` |
|
||||
|
||||
### 3.3 review case 处置(接收解析节点)→ 从 review case / disposition 读
|
||||
|
||||
| CP | 处置 | review case |
|
||||
|---|---|---|
|
||||
| `CP_REJECTED` | **标记为非订单**(`mark_non_order`) | `status='non_order'` |
|
||||
| `CP_NOTICE_TEXT_EXTRACTION_FAILED` | **文件质量异常**(`mark_quality_issue`) | `status='quality_issue'` |
|
||||
|
||||
> 这两者本就是"接收解析"节点的处置结果,不是独立状态机节点。`mark_non_order` / `mark_quality_issue` 是建单前人工 gate 的既有动作,`order_review_projection._allowed_actions` 已覆盖(non_order → view;quality_issue → view/mark_quality_issue/reparse)。
|
||||
|
||||
### 3.4 转瞬/信息态 → 省略
|
||||
|
||||
| CP | 处理 |
|
||||
|---|---|
|
||||
| `CP_PARSE_OK` | 省略("解析通过"仅转瞬态,被 gate passed / 推进中吸收) |
|
||||
| `CP_TASK_EXISTS` | 省略("任务已存在"信息态,被 task_creation passed 吸收) |
|
||||
|
||||
## 4. 结论:旧 CheckPoint 状态机可整体下线
|
||||
|
||||
**所有 20 个 CP 节点去处已定**:
|
||||
|
||||
- **16 个 → Gate**(复核 seq1-9 + 履约/上传/完成 seq10-20)。
|
||||
- **2 个 → review case 处置**(非订单 / 文件质量异常)。
|
||||
- **2 个 → 省略**(转瞬/信息态)。
|
||||
|
||||
撤掉 `checkpoint` + `checkpoint_kind` 后:履约+复核位置读 Gate;拒绝/文件质量读 review case;领域数据读标量字段。**无需为任何 CP 硬造 Gate 等价。**
|
||||
|
||||
---
|
||||
|
||||
## 5. 为什么符合行业最佳实践(SSOT)
|
||||
|
||||
- **单一事实来源**:一个状态概念只有一个权威表达(履约+复核 = Gate;处置 = review case)。消除并存的旧粗状态机,即消除反模式的"双写状态"。
|
||||
- **移除被取代的旧代码层**:CheckPoint 是初版粗机,Gate 是为更细控制/恢复/幂等后加。冗余源于"新层到位旧层未撤"。正确修法是在新层验证后删旧层。
|
||||
- **增量迁移**(见 §6):先并行验证、再切换、最后清理,是"状态机替换"的标准流程。
|
||||
- **不过度设计**:下线是往"更少、更单一"走;Gate 复杂由职责需要,不构成保留旧粗层的理由。
|
||||
|
||||
## 6. 一个需要处理的问题:廉价读取(不是保留状态机的理由)
|
||||
|
||||
**先分辨"便宜"的对象**:旧机便宜,是因为它算的**派生视图**(位置/是否人工/待办/状态)由**单行标量列**直接投影(0 join)。而查 Gate 要跨 `executions + gates + attempts` 多表 join。**单任务详情**查 Gate 完全没问题;**批量/列表/待办索引**一次算 N 个任务的待办/状态时,逐任务 join 就是 N+1/重 join,明显变慢。
|
||||
|
||||
**但这不构成保留旧状态机的理由——正确做法是**:
|
||||
|
||||
- **派生视图从 Gate 推导**(进程位置/是否人工/待办/状态 = Gate 的 `user_status`/`user_mode`/`entry_surface`),保持 SSOT。
|
||||
- **为满足廉价读**,把**这个派生视图**做成**缓存**(写到 task 行/派生列),列表/索引读缓存,不 join Gate 表。
|
||||
- **领域数据字段(`inventory_lines_json`、`export_file_path`、`match_status`、`upload_status`)保持原样**——它们是**真实数据,不是缓存**,由领域服务产出、被 Gate 校验。**不要**把领域数据当缓存写回、也**不要**把 Gate 压回这几列。
|
||||
|
||||
> 一句话:**不是"把 Gate 改成读标量列"(倒退),而是"把旧机算的那个派生视图改成读 Gate,并缓存它以满足廉价读";领域数据照旧单独存放。**(此点属后续实现范畴,本期设计仅指出方向。)
|
||||
|
||||
### 6.1 与阶段能力集(`STAGE_CAPABILITY_DEFINITIONS`)的关系
|
||||
|
||||
`STAGE_CAPABILITY_DEFINITIONS`(阶段能力集,定义在别处实现)与**本下线方案正交、不冲突、且方向互相印证**:
|
||||
|
||||
| | 阶段能力集 | 本下线方案 |
|
||||
|---|---|---|
|
||||
| 概念轴 | **动作/权限**(该阶段能点哪些按钮) | **状态/进程**(走到哪、是否人工) |
|
||||
| 字段依赖 | `stage` / `scope` / `action_code` / `invalidate` / `reset_to`(全部 gate/阶段码) | `checkpoint` / `checkpoint_kind` → 改读 Gate + review case |
|
||||
| 是否引用 `checkpoint_kind` | **没有** | — |
|
||||
|
||||
要点:
|
||||
|
||||
1. `STAGE_CAPABILITY_DEFINITIONS` 只写 gate 码/阶段码,**不引用** `checkpoint`/`checkpoint_kind`,故不依赖旧状态机。
|
||||
2. 阶段能力集的核心(触发上游能力 → **作废下游 gate → 重置回 inventory_preparation → 重跑**)正是**把 Gate 当唯一事实源**(通过作废/重置 Gate 表达回退与推进)——**与本下线方案想让"位置从 Gate 推导"方向一致**,甚至是"Gate = 事实源"的先行实践。
|
||||
3. 阶段能力集作废下游时会经 `recovery_invalidation_service` 清 `match_status`/`export_file_path` 等标量:旧机(从标量投影)会自然跟随;下线后从 Gate 读位置,Gate 被重置位置也自然对。**两种口径自洽,不打架**。
|
||||
4. 能力渲染 `ui_state.stage_context.preparation.capabilities`(`_stage_capabilities_for_task`)只读 `lifecycle_stage`/`source_locked`/预条件,**不看 `checkpoint_kind`**。
|
||||
|
||||
**结论**:两者不同轴、可并行、无需因一方改动而改另一方。
|
||||
|
||||
---
|
||||
|
||||
## 7. 消费点迁移
|
||||
|
||||
| 消费点 | 现读 | 改读 |
|
||||
|---|---|---|
|
||||
| 自动推进早停 `progress_workflow.py:415-431` | `checkpoint_kind == MUST_HUMAN / WAIT_MANUAL_UPLOAD` | Gate 推导 `user_mode`(`blocking_reason → BLOCKING_REASON_TO_USER_MODE`)+ `responsible_party` |
|
||||
| 待办分类 `query_service._todo_category_from_ui:722` | `checkpoint + checkpoint_kind` | 履约:Gate `user_status`/`user_mode`;复核:review case 处置 |
|
||||
| 用户态 `user_facing_status.py` | `checkpoint → 用户态` | Gate `user_status_for_gate_status` + review case 处置 |
|
||||
| 阶段上下文/摘要 `ui_state._build_stage_context/_build_task_summary` | `checkpoint_kind` 驱动 `current_todo`/`entry_surface`/阻断文案 | 同轴推导 |
|
||||
|
||||
---
|
||||
|
||||
## 8. 迁移计划(分阶段,低风险)
|
||||
|
||||
### 阶段 1:加轴推导 + 双读(行为不变)
|
||||
- 新增"轴推导"纯函数(履约=Gate、复核=review case 处置)。
|
||||
- 4 个消费点**先读新轴推导**,并**对照旧 checkpoint_kind** 断言一致(双读,不改行为)。
|
||||
- 目的:验证新推导与旧机一致,暴露分歧。
|
||||
|
||||
### 阶段 2:消费点切到新轴
|
||||
- 4 个消费点正式改读新轴推导,移除对 `resolve_task_ui_state` 的 `checkpoint`/`checkpoint_kind` 依赖。
|
||||
- 每切一个,跑该消费点回归。
|
||||
|
||||
### 阶段 3:下线旧机(硬删顺序,禁止跳步)
|
||||
|
||||
> **保留字面量 ≠ 保留状态机**:`parse_review` / `inventory_pending` / `export_ready` 等字符串是
|
||||
> **位置标签**(与 `derive_position` 对齐),可继续作文案/映射表的 key。删的是 **CheckPoint 状态机**:
|
||||
> `CheckpointKind`、`resolve_task_ui_state` 的 CP 裁决、`CP_*` 常量命名,以及 SQL/API 对它们的依赖。
|
||||
|
||||
**强制顺序(后步依赖前步):**
|
||||
|
||||
1. **SQL `todo_category` CASE 切 Gate / `review_status`**
|
||||
`_task_todo_category_sql_expr` / `_order_task_todo_category_sql_expr` 优先读
|
||||
`ShippingProcessExecution.current_gate_code` + `review_status`;与 ORM `task_todo_category`
|
||||
口径对齐后再删旧 checkpoint 分支。列表过滤不得在删旧机后仍依赖 `resolve_task_ui_state` 同序 CASE。
|
||||
|
||||
2. **切断消费点对 `resolve_task_ui_state` 的依赖**
|
||||
确认 progress / query / ui_state / user_facing / chat 均 Gate-first;仅允许迁移期 API
|
||||
别名 `checkpoint_*`(值 = `derive_position` / `derive_user_mode`)。
|
||||
|
||||
3. **下线 `state_machine` CP 裁决**
|
||||
移除 `CHECKPOINT_KIND_REGISTRY` / `CheckpointKind` 作为事实源;`resolve_task_ui_state*`
|
||||
删除或改为薄委托(仅回退无 Execution 的 review_status / 领域标量),**禁止**再输出独立 CP 状态机结果。
|
||||
|
||||
4. **`CP_*` 常量清理 / 改名**
|
||||
`constants.py` 中仅服务旧机的 `CP_*`:能映射为位置标签的改为 `POSITION_*`(或内联字面量);
|
||||
转瞬态 `CP_PARSE_OK` / `CP_TASK_EXISTS` 直接删除。`RS_*` / `PH_*` **保留**。
|
||||
文案表(`_PAUSE_REASON_*`、`_CHECKPOINT_LABELS`)改键为位置字符串,禁止再 import `CP_*`。
|
||||
|
||||
5. **聊天 / Tool 别名收口(可选同 PR 或紧随)**
|
||||
前端已 Gate-first(`shippingUiPosition`);后端 Tool/confirm 响应优先 `position`/`user_mode`,
|
||||
`checkpoint` 字段可暂留别名,硬删 API 字段另开任务。
|
||||
|
||||
6. **回归 + grep 门禁**
|
||||
`grep CP_|CheckpointKind|resolve_task_ui_state` 仅允许测试过渡与明确 deprecated 包装;
|
||||
跑 `test_gate_derivation` + `test_shipping_notice_ui_state` + `test_shipping_notice_query_service` 待办分类。
|
||||
|
||||
### 阶段 4:回归
|
||||
- 全量受影响 `test_shipping_*`;重点:自动推进、待办 SQL/ORM 一致、用户态、五阶段/摘要、F5CDD796 类死局。
|
||||
- 前端:`shippingUiPosition` / `useChatShippingRefresh` / `parseOrderReviewConfirmResponse`。
|
||||
|
||||
---
|
||||
|
||||
## 9. 风险与注意
|
||||
|
||||
| 风险 | 对策 |
|
||||
|---|---|
|
||||
| 复核阶段 CP 停点归属(gate vs review case) | 已核对:复核 gate(seq1-9)在执行链内,CP_RSV_REQ 等读 Gate;非订单/文件质量走 review case 处置 |
|
||||
| 廉价读取(列表/索引)性能 | 用 Gate 派生缓存/字段,不并存状态机(§6) |
|
||||
| 4 消费点漂移 | 阶段 1 双读断言兜住 |
|
||||
| 全量回归耗时(~1-2 min/file) | 只跑受影响 file;分阶段回归 |
|
||||
|
||||
---
|
||||
|
||||
## 10. 验收标准
|
||||
|
||||
- [x] `checkpoint` + `checkpoint_kind` 不再被消费点直接依赖(4 消费点改读 Gate / review case 处置);API 字段已硬删为 `position` / `user_mode`。
|
||||
- [x] "位置 / 是否人工 / 待办分类 / 用户态 / 阶段摘要" 由 Gate + review 推导;领域标量 CP 裁决已删除。
|
||||
- [ ] 履约死局(F5CDD796 类)与正常流不回归(待人工冒烟)。
|
||||
- [x] Gate 与领域数据字段不互相塞入对方(数据仍在标量字段,状态机仍只是状态机)。
|
||||
|
||||
---
|
||||
|
||||
## 11. 不属于本设计的范围
|
||||
|
||||
- **不**把领域数据(库存/Excel/匹配结果)并入 Gate(过度设计)。
|
||||
- **不**重写 Gate 模型本身(保留状态机主轴)。
|
||||
- **不**触及阶段能力集(已在别处实现)。
|
||||
Reference in new issue
Block a user