Merge branch 'dev' into runny827
feat(training): 新增精益培训视频与周任务管理 # Conflicts: # backend/app/models/__init__.py
This commit is contained in:
1 parent
85d27e9ffa
commit
91b7233872
812 files changed
+73763
-18908
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 一致 |
|
||||
Reference in new issue
Block a user