From 935bf26fa6c313fabdebd57bc0db996a052d530b Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Fri, 21 Aug 2026 09:20:47 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(shipping-notice):=20=E5=8D=87=E7=BA=A7?= =?UTF-8?q?=E8=B4=A7=E4=BB=A3=E5=8F=91=E8=B4=A7=E6=B5=81=E7=A8=8B=E4=B8=BA?= =?UTF-8?q?=E4=BA=94=E9=98=B6=E6=AE=B5=EF=BC=8C=E5=AE=8C=E5=96=84=E4=B8=9A?= =?UTF-8?q?=E5=8A=A1=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将货代发货流程从四阶段扩展为五阶段,拆分上传相关逻辑至独立的货代上传阶段; 统一多语言文案修正客户状态语义,将"客户尚未识别"调整为符合业务的"客户尚未确认"; 新增严格的上传成功验证谓词,需同时满足任务状态、全部预约单上传成功、存在有效成功上传尝试三个条件方可标记为完成; 新增坐标取值模型配置,支持Legacy冻结绝对坐标和锚点框架受限平移两种模式; 更新全链路相关文档、前端组件、后端服务与测试用例,确保业务逻辑对齐新业务规则。 --- backend/app/api/workspace/shipping_notice.py | 12 +- .../coordinate_table_reconstruction.py | 93 ++++ .../document_layout/lifecycle.py | 7 + .../on_demand_coordinate_evidence.py | 32 +- .../document_layout/order_field_extraction.py | 48 +- .../document_layout/order_profile.py | 41 ++ .../document_layout/order_profile_matcher.py | 432 +++++++++++++++++- .../error_explainability_contract.py | 2 +- .../shipping_notice/lifecycle_projection.py | 19 +- .../shipping_notice/order_extraction.py | 21 +- .../order_extraction_workflow.py | 78 +++- .../order_review_auto_progress_coordinator.py | 29 ++ .../order_review_disposition_service.py | 28 +- .../order_review_profile_match_service.py | 19 + .../order_review_projection.py | 73 ++- .../order_review_resume_service.py | 22 +- .../order_review_workbench_projection.py | 24 +- .../shipping_notice/process_gate_contract.py | 6 +- .../processing_projection_invariants.py | 51 ++- .../shipping_processing_projection.py | 137 ++++-- .../app/services/shipping_notice/ui_state.py | 53 ++- .../shipping_notice/upload_attempt_service.py | 33 ++ ...hipping_auto_progress_controller_phase1.py | 56 +++ ...hipping_coordinate_table_reconstruction.py | 47 ++ ...test_shipping_document_layout_lifecycle.py | 32 ++ .../tests/test_shipping_generic_order_gate.py | 36 ++ .../tests/test_shipping_notice_ui_state.py | 27 +- .../test_shipping_order_extraction_runs.py | 18 + .../test_shipping_order_field_extraction.py | 21 + .../test_shipping_order_profile_matcher.py | 149 ++++++ ...st_shipping_order_review_resume_service.py | 75 +++ .../test_shipping_order_review_service.py | 97 ++++ .../test_shipping_process_gate_contract.py | 8 +- ...ipping_processing_projection_invariants.py | 4 +- ...t_shipping_processing_projection_stage4.py | 93 +++- ...hipping_review_workbench_stage_layering.py | 8 +- backend/tests/test_shipping_upload_attempt.py | 29 +- docs/demand.md | 5 +- docs/features/shipping-notice/business.md | 5 +- docs/features/shipping-notice/technical.md | 19 +- docs/funclist.md | 5 +- docs/tec.md | 4 +- .../OrderProfileEditorPage.vue | 100 +++- .../shipping-order-document-profile.types.ts | 9 + .../src/features/chat/api/shipping.api.ts | 2 +- .../components/ShippingWorkflowStepper.vue | 4 +- .../ReviewBuildEligibilityDetailsDrawer.vue | 10 +- .../ReviewBuildEligibilitySummary.vue | 9 +- .../ReviewCustomerResolutionPanel.spec.ts | 63 +++ .../ReviewCustomerResolutionPanel.vue | 14 +- .../ReviewDocumentNavigation.vue | 4 +- .../ReviewLifecycleStageNavigation.spec.ts | 29 +- .../ReviewLifecycleStageNavigation.vue | 28 +- .../ReviewProfileMatchPanel.spec.ts | 51 +++ .../ReviewProfileMatchPanel.vue | 24 + ...ShippingConversationProcessingCard.spec.ts | 2 + .../ShippingConversationProcessingCard.vue | 9 +- .../shipping/ShippingWorkflowTimeline.spec.ts | 24 +- .../shipping/ShippingWorkflowTimeline.vue | 33 +- ...ping-order-review-workbench-layout.spec.ts | 6 +- .../useShippingOrderReview.spec.ts | 45 ++ .../shipping-review/useShippingOrderReview.ts | 32 +- .../conversationProcessingProjection.spec.ts | 9 +- .../conversationProcessingProjection.ts | 9 +- .../chat/shipping/shippingStepper.spec.ts | 14 +- .../features/chat/shipping/shippingStepper.ts | 7 +- .../features/chat/types/shipping.api.types.ts | 51 ++- .../views/ShippingOrderReviewView.spec.ts | 163 ++++++- .../chat/views/ShippingOrderReviewView.vue | 106 ++++- .../shipping-progress/actionPresentation.ts | 9 +- .../components/WorkbenchProgressGrouped.vue | 29 +- .../components/presenters.spec.ts | 34 +- .../ShippingTaskCenterPage.vue | 5 +- .../ShippingTaskWorkbench.vue | 2 +- frontend/src/locales/en/admin.json | 9 + frontend/src/locales/en/chat.json | 19 +- frontend/src/locales/en/workspace.json | 2 +- frontend/src/locales/th/admin.json | 9 + frontend/src/locales/th/chat.json | 19 +- frontend/src/locales/th/workspace.json | 2 +- frontend/src/locales/zh-CN/admin.json | 9 + frontend/src/locales/zh-CN/chat.json | 19 +- frontend/src/locales/zh-CN/workspace.json | 2 +- frontend/src/locales/zh-TW/admin.json | 9 + frontend/src/locales/zh-TW/chat.json | 19 +- frontend/src/locales/zh-TW/workspace.json | 2 +- 86 files changed, 2743 insertions(+), 311 deletions(-) create mode 100644 frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 1a7f7d83..dcb8f5b1 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -1808,26 +1808,24 @@ def workspace_delete_shipping_order_review_line(case_no: str, line_key: str): def workspace_validate_shipping_order_review_draft(case_no: str): """显式重跑当前草稿校验,并触发统一恢复协调器(可 auto_gate)。""" user = _require_user() - from app.services.shipping_notice.order_review_draft_service import validate_draft from app.services.shipping_notice.order_review_resume_service import ( attach_resume_outcome, resume_after_review_change, ) payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='draft_validated') - result = validate_draft( - user_id=user.id, case_no=case_no, expected_draft_version=payload.get('expected_draft_version'), - ) - db.session.commit() + # 保存校验必须由统一恢复协调器编排:唯一客户候选自动确认 → Draft 校验 → + # Gate/资格/STP。若先独立校验,会在同一次点击中把 unique_candidate 误判为未确认。 resume = resume_after_review_change( user_id=user.id, case_no=case_no, trigger='draft_validated', change_type=None, - skip_validate=True, + skip_validate=False, allow_auto_create=True, + expected_draft_version=payload.get('expected_draft_version'), ) - return _ok(attach_resume_outcome({'case': result}, resume)) + return _ok(attach_resume_outcome({'case': resume.get('case')}, resume)) @workspace_shipping_notice_bp.route( diff --git a/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py b/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py index 0f619601..a698ba90 100644 --- a/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py +++ b/backend/app/services/shipping_notice/document_layout/coordinate_table_reconstruction.py @@ -8,6 +8,8 @@ from __future__ import annotations +from copy import deepcopy +import math import re from statistics import median from typing import Any, Literal @@ -269,6 +271,7 @@ def reconstruct_coordinate_profile_rows( line_start_field_code: str | None = None, include_unanchored_rows: bool = False, row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows', + coordinate_transform: dict[str, Any] | None = None, ) -> list[CoordinateProfileLogicalRow]: """ 按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。 @@ -279,7 +282,22 @@ def reconstruct_coordinate_profile_rows( 才是已授权的删除证据;未授权删除文字会被忽略。``include_deleted`` 仅供标注预览 返回删除行证据;正式解析保持默认值,删除行不会进入业务结果。仅管理员预览可开启 ``include_unanchored_rows``,在没有任何有效起行值时返回待复核的主行字段,不能用于正式解析。 + ``coordinate_transform`` 只能接收共同 matcher 已确认的 ``status=applied`` 平移; + 它只在当前调用的内存副本投影表区、物理行和字段区域,绝不修改冻结 Profile。 """ + projected = _project_coordinate_profile_regions( + table_region=table_region, + line_layouts=line_layouts, + termination_rules=termination_rules, + exclusion_regions=exclusion_regions, + coordinate_transform=coordinate_transform, + ) + if projected is None: + return [] + table_region = projected['table_region'] + line_layouts = projected['line_layouts'] + termination_rules = projected['termination_rules'] + exclusion_regions = projected['exclusion_regions'] start_field_code = resolve_line_start_field_code(line_start_field_code) bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox) ordered_layouts = sorted((item for item in line_layouts if isinstance(item, dict)), key=lambda item: item.get('row_offset', -1)) @@ -451,6 +469,81 @@ def reconstruct_coordinate_profile_rows( return results if include_deleted else [row for row in results if row.role != 'deleted'] +def _project_coordinate_profile_regions( + *, + table_region: dict[str, Any] | None, + line_layouts: list[dict[str, Any]], + termination_rules: list[dict[str, Any]] | None, + exclusion_regions: list[dict[str, Any]] | None, + coordinate_transform: dict[str, Any] | None, +) -> dict[str, Any] | None: + """对当前重建调用复制并投影受 matcher 证明的相对坐标平移。 + + 未传变换时保留 legacy 行为。传入变换必须是有限、页面内的 ``applied`` + 变换;任何伪造、过界或未知状态都返回 ``None``,由调用方保持 Review, + 不能静默回退到旧绝对坐标。 + """ + if coordinate_transform is None: + return { + 'table_region': table_region, + 'line_layouts': line_layouts, + 'termination_rules': termination_rules, + 'exclusion_regions': exclusion_regions, + } + if not isinstance(coordinate_transform, dict) or coordinate_transform.get('status') != 'applied': + return None + try: + translate_x = float(coordinate_transform['translate_x']) + translate_y = float(coordinate_transform['translate_y']) + except (KeyError, TypeError, ValueError): + return None + if not math.isfinite(translate_x) or not math.isfinite(translate_y): + return None + + def translate_region(region: Any) -> bool: + if not isinstance(region, dict): + return False + try: + x0, y0 = float(region['x0']) + translate_x, float(region['y0']) + translate_y + x1, y1 = float(region['x1']) + translate_x, float(region['y1']) + translate_y + except (KeyError, TypeError, ValueError): + return False + if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1): + return False + region.update({'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1}) + return True + + projected_table = deepcopy(table_region) if table_region is not None else None + projected_layouts = deepcopy(line_layouts) + projected_terminations = deepcopy(termination_rules) if termination_rules is not None else None + projected_exclusions = deepcopy(exclusion_regions) if exclusion_regions is not None else None + if projected_table is not None and not translate_region(projected_table): + return None + for layout in projected_layouts: + if not isinstance(layout, dict): + return None + region = layout.get('region') + if region is not None and not translate_region(region): + return None + for field in layout.get('field_regions') or []: + if not isinstance(field, dict) or not translate_region(field.get('region')): + return None + for rule in projected_terminations or []: + anchor = rule.get('anchor') if isinstance(rule, dict) else None + region = anchor.get('region') if isinstance(anchor, dict) else None + if region is not None and not translate_region(region): + return None + for region in projected_exclusions or []: + if not translate_region(region): + return None + return { + 'table_region': projected_table, + 'line_layouts': projected_layouts, + 'termination_rules': projected_terminations, + 'exclusion_regions': projected_exclusions, + } + + def _reconstruct_adaptive_record_columns_profile_rows( *, glyphs: list[tuple[int, PositionedCharacter]], diff --git a/backend/app/services/shipping_notice/document_layout/lifecycle.py b/backend/app/services/shipping_notice/document_layout/lifecycle.py index 37925030..3755d50c 100644 --- a/backend/app/services/shipping_notice/document_layout/lifecycle.py +++ b/backend/app/services/shipping_notice/document_layout/lifecycle.py @@ -188,6 +188,13 @@ def _fit_layout_payload_to_budget( coordinate_evidence = candidate.get('coordinate_evidence') if isinstance(coordinate_evidence, dict): + # [STEP] 仅在即将删除逐字符坐标时固定模板身份特征,避免改变未压缩快照的 + # checksum;后续 matcher 只能读取此投影,不能退化为页面/表框高分猜测。 + if coordinate_evidence.get('page_glyphs') is not None or coordinate_evidence.get('tables') is not None: + from app.services.shipping_notice.document_layout.order_profile_matcher import ( + build_layout_matching_features, + ) + candidate['matching_features'] = build_layout_matching_features(layout=candidate) if coordinate_evidence.pop('page_glyphs', None) is not None: issues.append('shipping_document_layout_page_glyphs_compacted') if coordinate_evidence.pop('tables', None) is not None: diff --git a/backend/app/services/shipping_notice/document_layout/on_demand_coordinate_evidence.py b/backend/app/services/shipping_notice/document_layout/on_demand_coordinate_evidence.py index c0f993b4..63263976 100644 --- a/backend/app/services/shipping_notice/document_layout/on_demand_coordinate_evidence.py +++ b/backend/app/services/shipping_notice/document_layout/on_demand_coordinate_evidence.py @@ -44,8 +44,24 @@ def ensure_on_demand_coordinate_evidence( sources = _coordinate_mapping(evidence.get('sources')) source_pages = _coordinate_mapping(sources.get('pages')) tables = _coordinate_mapping(evidence.get('tables')) - if page_nos is not None and page_nos.issubset({int(p) for p in page_glyphs if str(p).isdigit()}): - return layout + available_page_nos = { + int(page_no) for page_no, glyphs in page_glyphs.items() + if str(page_no).isdigit() and isinstance(glyphs, list) and glyphs + } + if page_nos is not None and page_nos.issubset(available_page_nos): + # 当前 Layout 可能补齐了 Run 冻结快照中已被压缩的坐标证据。必须返回 + # 合并后的运行期 Layout;返回原 layout 会让调用方重新丢失这些字符坐标, + # 从而使同版式 PDF 因快照压缩路径不同进入不同的匹配分支。 + next_layout = dict(layout) + merged_evidence = {**evidence, 'pages': pages} + if page_glyphs: + merged_evidence['page_glyphs'] = page_glyphs + if tables: + merged_evidence['tables'] = tables + if sources or source_pages: + merged_evidence['sources'] = {**sources, 'pages': source_pages} + next_layout['coordinate_evidence'] = merged_evidence + return next_layout tables_by_page: dict[int, list[dict[str, Any]]] = {} for raw_table in layout.get('tables') or []: if not isinstance(raw_table, dict): @@ -108,8 +124,12 @@ def ensure_on_demand_coordinate_evidence( if table_id and chars: tables[table_id] = chars next_layout = dict(layout) - next_layout['coordinate_evidence'] = { - **evidence, 'pages': pages, 'page_glyphs': page_glyphs, - 'tables': tables, 'sources': {**sources, 'pages': source_pages}, - } + merged_evidence = {**evidence, 'pages': pages} + if page_glyphs: + merged_evidence['page_glyphs'] = page_glyphs + if tables: + merged_evidence['tables'] = tables + if sources or source_pages: + merged_evidence['sources'] = {**sources, 'pages': source_pages} + next_layout['coordinate_evidence'] = merged_evidence return next_layout diff --git a/backend/app/services/shipping_notice/document_layout/order_field_extraction.py b/backend/app/services/shipping_notice/document_layout/order_field_extraction.py index 4d08953d..91a4d7cd 100644 --- a/backend/app/services/shipping_notice/document_layout/order_field_extraction.py +++ b/backend/app/services/shipping_notice/document_layout/order_field_extraction.py @@ -49,6 +49,7 @@ class OrderFieldExtraction(BaseModel): def extract_order_fields( *, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any], allow_ocr_preview_fallback: bool = False, + coordinate_transform: dict[str, Any] | None = None, ) -> list[OrderFieldExtraction]: """ 用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。 @@ -63,6 +64,12 @@ def extract_order_fields( Returns: 每个已绑定布局对应一个候选,按模板声明顺序返回。 """ + effective_profile = _project_coordinate_transform(profile, coordinate_transform) + if effective_profile is None: + return [ + _unavailable(layout, 'order_field_coordinate_transform_invalid') + for layout in profile.order_field_layouts + ] return [ _extract_layout( layout=layout, @@ -70,10 +77,49 @@ def extract_order_fields( coordinate_evidence=coordinate_evidence, allow_ocr_preview_fallback=allow_ocr_preview_fallback, ) - for layout in profile.order_field_layouts + for layout in effective_profile.order_field_layouts ] +def _project_coordinate_transform( + profile: OrderCoordinateProfile, coordinate_transform: dict[str, Any] | None, +) -> OrderCoordinateProfile | None: + """把 matcher 唯一确认的平移一次性投影到订单头布局,禁止二次估算。""" + if coordinate_transform is None: + return profile + if not isinstance(coordinate_transform, dict) or coordinate_transform.get('status') != 'applied': + return None + try: + dx, dy = float(coordinate_transform['translate_x']), float(coordinate_transform['translate_y']) + except (KeyError, TypeError, ValueError): + return None + if not all(value == value and abs(value) != float('inf') for value in (dx, dy)): + return None + payload = profile.model_dump(mode='python') + for layout in payload.get('order_field_layouts') or []: + if not isinstance(layout, dict): + continue + for key in ('absolute_value_region', 'fallback_value_region'): + region = layout.get(key) + if isinstance(region, dict): + _translate_region_dict(region, dx=dx, dy=dy) + anchor = layout.get('anchor') + if isinstance(anchor, dict) and isinstance(anchor.get('region'), dict): + _translate_region_dict(anchor['region'], dx=dx, dy=dy) + try: + return OrderCoordinateProfile.model_validate(payload) + except Exception: + return None + + +def _translate_region_dict(region: dict[str, Any], *, dx: float, dy: float) -> None: + """原地平移归一化区域并拒绝越界;调用方随后重新校验 Profile。""" + region['x0'] = float(region['x0']) + dx + region['x1'] = float(region['x1']) + dx + region['y0'] = float(region['y0']) + dy + region['y1'] = float(region['y1']) + dy + + def _extract_layout( *, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any], allow_ocr_preview_fallback: bool = False, diff --git a/backend/app/services/shipping_notice/document_layout/order_profile.py b/backend/app/services/shipping_notice/document_layout/order_profile.py index 156a30cd..abb05394 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile.py @@ -427,6 +427,46 @@ class DocumentMatchProfile(OrderProfileModel): return self +class AnchorFrameCoordinateModel(OrderProfileModel): + """声明以稳定静态文字建立运行时平移坐标框架的 Profile 能力。""" + + 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) + + @model_validator(mode='after') + def validate_anchor_frame(self) -> 'AnchorFrameCoordinateModel': + """要求每个框架锚点都有基线区域且身份唯一,避免运行时从全文猜测基准。""" + if any(anchor.region is None for anchor in self.anchors): + raise ValueError('anchor frame anchors require baseline regions') + ids = [anchor.anchor_id for anchor in self.anchors] + if len(ids) != len(set(ids)): + raise ValueError('anchor frame anchor ids must be unique') + return self + + +class CoordinateModel(OrderProfileModel): + """定义坐标模板是否启用锚点框架;legacy 保持既有绝对坐标行为。""" + + type: Literal['legacy', 'anchor_frame'] = 'legacy' + anchors: list[AnchorRule] = Field(default_factory=list, 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) + + @model_validator(mode='after') + def validate_coordinate_model(self) -> 'CoordinateModel': + """仅 anchor_frame 允许锚点配置;legacy 必须是空声明以保证路径隔离。""" + if self.type == 'legacy' and self.anchors: + raise ValueError('legacy coordinate model must not define frame anchors') + if self.type == 'anchor_frame': + AnchorFrameCoordinateModel( + type='anchor_frame', anchors=self.anchors, + max_translate_x=self.max_translate_x, max_translate_y=self.max_translate_y, + ) + return self + + class OrderCoordinateProfile(OrderProfileModel): """唯一的订单坐标模板定义;运行时和管理端只消费这一种契约。""" profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$') @@ -435,6 +475,7 @@ class OrderCoordinateProfile(OrderProfileModel): table_regions: list[TableRegionProfile] = Field(min_length=1) order_field_layouts: list[OrderFieldLayout] = Field(default_factory=list) draft_unbound_order_field_layouts: list[DraftUnboundOrderFieldLayout] = Field(default_factory=list) + coordinate_model: CoordinateModel = Field(default_factory=CoordinateModel) @model_validator(mode='after') def validate_profile_rules(self) -> 'OrderCoordinateProfile': diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py b/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py index ffb840f5..e72034bb 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py @@ -9,6 +9,7 @@ services/shipping_notice/document_layout/order_profile_matcher.py from __future__ import annotations +from copy import deepcopy import re from typing import Any, Literal @@ -17,8 +18,10 @@ from pydantic import BaseModel, ConfigDict, Field from app.services.shipping_notice.document_layout.coordinate_region_text import ( positioned_token_spans, read_coordinate_region_text, + visual_glyph_rows, ) from app.services.shipping_notice.document_layout.order_profile import ( + AnchorRule, CRITICAL_STRUCTURE_DIMENSION_KEYS, MatchDimensionResult, MatchDimensionState, @@ -31,6 +34,9 @@ from app.services.shipping_notice.document_layout.order_profile_signature import ) +LAYOUT_MATCHING_FEATURES_VERSION = 'shipping-layout-matching-features.v2' + + def _anchor_comparable_text(value: Any) -> str: """规范化锚点比较文本,兼容 PDF 字符逐字拼接后丢失的版面空白。""" return ''.join(str(value or '').casefold().split()) @@ -66,6 +72,7 @@ class ProfileMatchCandidate(BaseModel): dimension_scores: ProfileMatchDimensionScores | None = None dimension_states: dict[str, MatchDimensionState] = Field(default_factory=dict) margin_to_next: float | None = Field(default=None, ge=0, le=1) + coordinate_transform: dict[str, Any] | None = None class ProfileMatchResult(BaseModel): @@ -136,15 +143,23 @@ def match_frozen_coordinate_profiles( document_match=definition.get('document_match'), table_regions=definition.get('table_regions'), order_field_layouts=definition.get('order_field_layouts') or [], + coordinate_model=definition.get('coordinate_model') or {}, ) except (TypeError, ValueError): continue reason_codes: list[str] = [] signature_body, signature_meta = _extract_matching_signature(raw) + coordinate_transform, transform_reasons = _resolve_coordinate_transform( + profile=profile, pages=pages, page_glyphs=page_glyphs, + ) + reason_codes.extend(transform_reasons) + observed_signature = _translate_signature( + signature=signature_body, coordinate_transform=coordinate_transform, + ) observed = _observe_layout_features( layout=layout, tables=tables, pages=pages, glyph_tables=glyph_tables, - page_glyphs=page_glyphs, signature=signature_body, + page_glyphs=page_glyphs, signature=observed_signature, ) if signature_body is None: reason_codes.append('profile_signature_missing') @@ -190,7 +205,7 @@ def match_frozen_coordinate_profiles( dimension_results, hard_conflict_codes = _compute_dimension_results( profile=profile, - signature=signature_body, + signature=observed_signature, observed=observed, tables=tables, pages=pages, @@ -200,6 +215,11 @@ def match_frozen_coordinate_profiles( customer_hint_id=customer_hint_id, ) reason_codes.extend(hard_conflict_codes) + if _profile_requires_unavailable_structure_evidence( + signature=observed_signature, + dimension_results=dimension_results, + ): + reason_codes.append('profile_coordinate_evidence_unavailable') weights = profile.document_match.scoring_weights score, evidence_coverage = _aggregate_dimension_score(weights=weights, dimension_results=dimension_results) @@ -223,6 +243,7 @@ def match_frozen_coordinate_profiles( matched_anchor_count=sum(required_hits) + sum(optional_hits), dimension_scores=dimension_scores, dimension_states=dimension_states, + coordinate_transform=coordinate_transform, ))) rendered = sorted( @@ -251,6 +272,11 @@ def match_frozen_coordinate_profiles( candidate.margin_to_next = round(max(0.0, candidate.score - next_score), 6) if not hard_valid: + if any('profile_coordinate_evidence_unavailable' in item.reason_codes for item in rendered): + return ProfileMatchResult( + status='evidence_insufficient', candidates=rendered, + top1_score=top1_score, top2_score=top2_score, margin=margin, + ) if not rendered: return ProfileMatchResult( status='no_match', candidates=rendered, @@ -305,6 +331,138 @@ def match_frozen_coordinate_profiles( ) +def build_layout_matching_features(*, layout: dict[str, Any]) -> dict[str, Any]: + """从完整坐标证据派生可持久化的候选表头特征,不保留逐字符正文。 + + 特征生成不依赖任何 Profile;保存所有候选视觉行,运行时再由冻结签名选择, + 避免“无 Profile 时猜一条表头”导致压缩后永久保存错误列拓扑。 + """ + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} + glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} + page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} + tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)] + first_page = pages.get('1') or pages.get(1) or next(iter(pages.values()), None) + aspect_ratio = 0.0 + if isinstance(first_page, dict): + try: + width, height = float(first_page.get('width') or 0), float(first_page.get('height') or 0) + aspect_ratio = round(width / height, 6) if width > 0 and height > 0 else 0.0 + except (TypeError, ValueError): + pass + rendered_tables: list[dict[str, Any]] = [] + for table in tables: + bbox = _normalized_table_bbox(table=table, pages=pages) + if bbox is None: + continue + candidates = _observe_header_candidates( + glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, + primary_bbox=bbox, + ) + first = candidates[0] if candidates else {} + rendered_tables.append({ + 'bbox': bbox, + 'header_candidates': candidates, + 'header_tokens': first.get('header_tokens', []), + 'column_centers': first.get('column_centers', []), + 'column_width_ratios': first.get('column_width_ratios', []), + }) + result = { + 'version': LAYOUT_MATCHING_FEATURES_VERSION, + 'page_structure': { + 'aspect_ratio': aspect_ratio, + 'page_count': len(pages), + 'table_count': len(tables), + }, + 'tables': rendered_tables, + 'static_text_centers': _observe_static_text_centers( + glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, + ), + } + if not result['static_text_centers']: + result.pop('static_text_centers') + return result + + +def _observe_header_candidates( + *, glyph_tables: dict[str, Any], page_glyphs: dict[str, Any], + pages: dict[str, Any], primary_bbox: list[float], +) -> list[dict[str, Any]]: + """提取主表顶部视觉行候选;不把数据行固化成唯一表头。""" + if not primary_bbox or len(primary_bbox) != 4: + return [] + page = pages.get('1') or pages.get(1) + glyphs = page_glyphs.get('1') or page_glyphs.get(1) + if not isinstance(glyphs, list): + glyphs = [g for values in glyph_tables.values() if isinstance(values, list) for g in values] + if not isinstance(page, dict) or not glyphs: + return [] + width, height = float(page.get('width') or 0), float(page.get('height') or 0) + if width <= 0 or height <= 0: + return [] + table_height = max(0.001, primary_bbox[3] - primary_bbox[1]) + rows = visual_glyph_rows(glyphs) + candidates: list[dict[str, Any]] = [] + for row in rows: + centers_y = [ + ((float(g['bbox']['y0']) + float(g['bbox']['y1'])) / 2) / height + for g in row if isinstance(g.get('bbox'), dict) + ] + if not centers_y: + continue + y = sum(centers_y) / len(centers_y) + if y < primary_bbox[1] or y > primary_bbox[1] + table_height * 0.30: + continue + spans = [ + item for item in positioned_token_spans(row, respect_explicit_spaces=False) + if _usable_observed_header_token(str(item.get('text') or '')) + ][:32] + if not spans: + continue + tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans] + centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans] + table_span = max(primary_bbox[2] - primary_bbox[0], 0.0001) + widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans] + bbox = [ + round(min(float(g['bbox']['x0']) for g in row if isinstance(g.get('bbox'), dict)) / width, 6), + round(min(float(g['bbox']['y0']) for g in row if isinstance(g.get('bbox'), dict)) / height, 6), + round(max(float(g['bbox']['x1']) for g in row if isinstance(g.get('bbox'), dict)) / width, 6), + round(max(float(g['bbox']['y1']) for g in row if isinstance(g.get('bbox'), dict)) / height, 6), + ] + candidates.append({'bbox': bbox, 'header_tokens': tokens, 'column_centers': centers, 'column_width_ratios': widths}) + candidates.sort(key=lambda item: (item['bbox'][1], -len(item['header_tokens']))) + return candidates[:8] + + +def _normalized_table_bbox(*, table: dict[str, Any], pages: dict[str, Any]) -> list[float] | None: + """将 Layout 表框转为页内归一化坐标;缺页尺寸时仅接受已经归一化的表框。""" + bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None + if bbox is None: + return None + try: + values = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')] + except (KeyError, TypeError, ValueError): + return None + if values[2] <= values[0] or values[3] <= values[1]: + return None + if max(values) <= 1: + return [round(value, 6) for value in values] + page_no = table.get('page_no') or 1 + page = pages.get(str(page_no)) or pages.get(page_no) + if not isinstance(page, dict): + return None + try: + width, height = float(page.get('width') or 0), float(page.get('height') or 0) + except (TypeError, ValueError): + return None + if width <= 0 or height <= 0: + return None + return [ + round(values[0] / width, 6), round(values[1] / height, 6), + round(values[2] / width, 6), round(values[3] / height, 6), + ] + + def _selected_result( *, raw: dict[str, Any], @@ -343,6 +501,212 @@ def _extract_matching_signature(raw: dict[str, Any]) -> tuple[dict[str, Any] | N return signature, matching if isinstance(matching, dict) else {} +def _resolve_coordinate_transform( + *, profile: OrderCoordinateProfile, pages: dict[str, Any], page_glyphs: dict[str, Any], +) -> tuple[dict[str, Any] | None, list[str]]: + """根据 Profile 声明的唯一静态锚点求受限平移,任何不确定性都返回硬失败原因。 + + Args: + profile: 当前冻结坐标 Profile;仅 ``anchor_frame`` 启用此能力。 + pages: 当前 Layout 的页尺寸证据。 + page_glyphs: 当前 Layout 的页级 PDF/OCR 字符坐标。 + + Returns: + ``(transform, reason_codes)``。legacy 返回 ``(None, [])``;anchor_frame 仅在 + 所有锚点唯一且变换位于声明上限内时返回 ``status=applied``。 + """ + model = profile.coordinate_model + if model.type != 'anchor_frame': + return None, [] + + deltas: list[tuple[float, float]] = [] + anchor_ids: list[str] = [] + for anchor in model.anchors: + found = _find_anchor_rule_matches( + anchor=anchor, pages=pages, page_glyphs=page_glyphs, + max_translate_x=min(.30, model.max_translate_x * 2), + max_translate_y=min(.30, model.max_translate_y * 2), + ) + if not found: + return None, ['profile_anchor_frame_anchor_missing'] + if len(found) != 1: + return None, ['profile_anchor_frame_anchor_ambiguous'] + page_no, bbox = found[0] + page = pages.get(str(page_no)) or pages.get(page_no) + if not isinstance(page, dict) or anchor.region is None: + return None, ['profile_anchor_frame_coordinate_evidence_unavailable'] + try: + width, height = float(page['width']), float(page['height']) + except (KeyError, TypeError, ValueError): + return None, ['profile_anchor_frame_coordinate_evidence_unavailable'] + if width <= 0 or height <= 0: + return None, ['profile_anchor_frame_coordinate_evidence_unavailable'] + observed_x = (bbox[0] + bbox[2]) / 2 / width + observed_y = (bbox[1] + bbox[3]) / 2 / height + expected_x = (anchor.region.x0 + anchor.region.x1) / 2 + expected_y = (anchor.region.y0 + anchor.region.y1) / 2 + deltas.append((observed_x - expected_x, observed_y - expected_y)) + anchor_ids.append(anchor.anchor_id) + + first_x, first_y = deltas[0] + if any(abs(x - first_x) > .01 or abs(y - first_y) > .01 for x, y in deltas[1:]): + return None, ['profile_anchor_frame_anchor_inconsistent'] + if abs(first_x) > model.max_translate_x or abs(first_y) > model.max_translate_y: + return None, ['profile_anchor_frame_transform_out_of_range'] + return { + 'status': 'applied', + 'translate_x': round(first_x, 6), + 'translate_y': round(first_y, 6), + 'anchor_ids': anchor_ids, + 'reason_codes': [], + }, [] + + +def _find_anchor_rule_matches( + *, anchor: AnchorRule, pages: dict[str, Any], page_glyphs: dict[str, Any], + max_translate_x: float, max_translate_y: float, +) -> list[tuple[int, list[float]]]: + """在基线区加声明平移窗口内寻找唯一锚点,绝不退化为全文弱匹配。""" + if anchor.region is None: + return [] + expected = [_anchor_comparable_text(value) for value in [anchor.text, *anchor.aliases]] + rendered: list[tuple[int, list[float]]] = [] + for raw_page_no, page in pages.items(): + try: + page_no, width, height = int(raw_page_no), float(page['width']), float(page['height']) + except (KeyError, TypeError, ValueError): + continue + glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no) + if width <= 0 or height <= 0 or not isinstance(glyphs, list): + continue + for line in _group_glyph_lines(glyphs): + ordered = sorted(line, key=lambda item: float((item.get('bbox') or {}).get('x0') or 0)) + comparable_parts: list[str] = [] + glyph_spans: list[tuple[int, int, dict[str, Any]]] = [] + for item in ordered: + part = _anchor_comparable_text(item.get('text') or '') + if not part: + continue + start = len(''.join(comparable_parts)) + comparable_parts.append(part) + glyph_spans.append((start, start + len(part), item)) + text = ''.join(comparable_parts) + if not text: + continue + matched_box_sets: list[list[dict[str, Any]]] = [] + for value in expected: + if not value: + continue + starts: list[int] = [] + offset = text.find(value) + while offset >= 0: + starts.append(offset) + offset = text.find(value, offset + 1) + if anchor.match_mode == 'exact' and not _anchor_rule_text_matches(value, text, mode='contains'): + starts = [] + for start in starts: + end = start + len(value) + matched_box_sets.append([ + item for span_start, span_end, item in glyph_spans + if span_start < end and span_end > start + ]) + if matched_box_sets: + break + if len(matched_box_sets) != 1 or not matched_box_sets[0]: + if len(matched_box_sets) > 1: + rendered.extend((page_no, [ + min(float(item['bbox']['x0']) for item in boxes if isinstance(item.get('bbox'), dict)), + min(float(item['bbox']['y0']) for item in boxes if isinstance(item.get('bbox'), dict)), + max(float(item['bbox']['x1']) for item in boxes if isinstance(item.get('bbox'), dict)), + max(float(item['bbox']['y1']) for item in boxes if isinstance(item.get('bbox'), dict)), + ]) for boxes in matched_box_sets if boxes) + continue + matched_boxes = matched_box_sets[0] + if not matched_boxes: + continue + boxes = [item.get('bbox') for item in matched_boxes if isinstance(item.get('bbox'), dict)] + if not boxes: + continue + bbox = [ + min(float(item['x0']) for item in boxes), min(float(item['y0']) for item in boxes), + max(float(item['x1']) for item in boxes), max(float(item['y1']) for item in boxes), + ] + center_x, center_y = (bbox[0] + bbox[2]) / 2 / width, (bbox[1] + bbox[3]) / 2 / height + if ( + max(0, anchor.region.x0 - max_translate_x) <= center_x <= min(1, anchor.region.x1 + max_translate_x) + and max(0, anchor.region.y0 - max_translate_y) <= center_y <= min(1, anchor.region.y1 + max_translate_y) + ): + rendered.append((page_no, bbox)) + return rendered + + +def _group_glyph_lines(glyphs: list[dict[str, Any]]) -> list[list[dict[str, Any]]]: + """按字符中心 Y 聚合视觉行,供框架锚点精确匹配,不改变既有字段提取逻辑。""" + lines: list[list[dict[str, Any]]] = [] + for glyph in sorted((item for item in glyphs if isinstance(item, dict) and isinstance(item.get('bbox'), dict)), key=lambda item: (float(item['bbox'].get('y0') or 0), float(item['bbox'].get('x0') or 0))): + bbox = glyph['bbox'] + try: + center_y = (float(bbox['y0']) + float(bbox['y1'])) / 2 + glyph_height = max(.01, float(bbox['y1']) - float(bbox['y0'])) + except (KeyError, TypeError, ValueError): + continue + if lines: + previous = lines[-1][0]['bbox'] + previous_y = (float(previous['y0']) + float(previous['y1'])) / 2 + previous_height = max(.01, float(previous['y1']) - float(previous['y0'])) + if abs(center_y - previous_y) <= max(glyph_height, previous_height) * .65: + lines[-1].append(glyph) + continue + lines.append([glyph]) + return lines + + +def _anchor_rule_text_matches(expected: str, observed: str, *, mode: str) -> bool: + """按 AnchorRule 的 exact/contains 合约比较已规范化文本。""" + return expected == observed if mode == 'exact' else expected in observed + + +def _translate_signature( + *, signature: dict[str, Any] | None, coordinate_transform: dict[str, Any] | None, +) -> dict[str, Any] | None: + """将当前 Profile 的签名副本映射到同一运行时框架,绝不回写冻结签名。""" + if not signature or not coordinate_transform or coordinate_transform.get('status') != 'applied': + return signature + try: + dx, dy = float(coordinate_transform['translate_x']), float(coordinate_transform['translate_y']) + except (KeyError, TypeError, ValueError): + return signature + translated = deepcopy(signature) + for pattern in translated.get('table_patterns') or []: + if not isinstance(pattern, dict): + continue + bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else {} + median = bbox.get('median') if isinstance(bbox.get('median'), list) else None + if median and len(median) == 4: + bbox['median'] = [median[0] + dx, median[1] + dy, median[2] + dx, median[3] + dy] + header = pattern.get('header_bbox') + if isinstance(header, list) and len(header) == 4: + pattern['header_bbox'] = [header[0] + dx, header[1] + dy, header[2] + dx, header[3] + dy] + for relation in translated.get('field_relation_graph') or []: + if isinstance(relation, dict): + # 同一平移不会改变两锚点的相对关系,特意不修改 dx/dy。 + continue + return translated + + +def _profile_requires_unavailable_structure_evidence( + *, signature: dict[str, Any] | None, + dimension_results: dict[str, MatchDimensionResult], +) -> bool: + """关键模板结构维度缺证据即禁止自动选中,不能靠缩小评分分母获得 hard match。""" + if not signature: + return False + return any( + dimension_results[key].state == 'unavailable' + for key in CRITICAL_STRUCTURE_DIMENSION_KEYS + ) + + def _aggregate_dimension_score( *, weights: Any, @@ -664,6 +1028,17 @@ def _observe_layout_features( signature: dict[str, Any] | None, ) -> dict[str, Any]: """从冻结 layout 聚合非敏感结构特征供维度比对。""" + persisted = layout.get('matching_features') + # 完整坐标存在时必须以当前证据重算;压缩快照才允许使用 v2 投影。 + if isinstance(page_glyphs, dict) and any(isinstance(value, list) and value for value in page_glyphs.values()): + persisted = None + if isinstance(persisted, dict) and persisted.get('version') == LAYOUT_MATCHING_FEATURES_VERSION: + observed = _observed_features_from_persisted_projection( + features=persisted, signature=signature, + ) + if observed is not None: + return observed + first_page = pages.get('1') or pages.get(1) or next(iter(pages.values()), None) aspect_ratio = 0.0 if isinstance(first_page, dict): @@ -699,6 +1074,53 @@ def _observe_layout_features( } +def _observed_features_from_persisted_projection( + *, features: dict[str, Any], signature: dict[str, Any] | None, +) -> dict[str, Any] | None: + """将压缩前持久化的轻量特征恢复为 matcher 输入,绝不读取逐字符正文。""" + page_structure = features.get('page_structure') + tables = features.get('tables') + if not isinstance(page_structure, dict) or not isinstance(tables, list): + return None + candidates = [item for item in tables if isinstance(item, dict) and isinstance(item.get('bbox'), list)] + if not candidates: + return None + expected = _signature_column_values(signature or {}, 'column_centers') + primary = candidates[0] + if expected: + def distance(item: dict[str, Any]) -> tuple[float, int]: + options = item.get('header_candidates') if isinstance(item.get('header_candidates'), list) else [item] + best = min((abs(len(option.get('column_centers') or []) - len(expected)) for option in options if isinstance(option, dict)), default=999) + return best, abs(len(item.get('column_centers') or []) - len(expected)) + primary = min(candidates, key=distance) + options = primary.get('header_candidates') if isinstance(primary.get('header_candidates'), list) else [] + if options: + primary = min(options, key=lambda item: abs(len(item.get('column_centers') or []) - len(expected))) | {'bbox': candidates[0].get('bbox')} + bbox = primary.get('bbox') + centers = primary.get('column_centers') + widths = primary.get('column_width_ratios') + tokens = primary.get('header_tokens') + if not ( + isinstance(bbox, list) and len(bbox) == 4 + and isinstance(centers, list) and isinstance(widths, list) and isinstance(tokens, list) + ): + return None + return { + 'aspect_ratio': float(page_structure.get('aspect_ratio') or 0), + 'table_count': int(page_structure.get('table_count') or len(candidates)), + 'page_count': int(page_structure.get('page_count') or 0), + 'primary_table_bbox': bbox, + 'header_tokens': tokens, + 'column_count': len(centers), + 'column_centers': centers, + 'column_width_ratios': widths, + 'static_text_centers': ( + features.get('static_text_centers') + if isinstance(features.get('static_text_centers'), dict) else {} + ), + } + + def _select_signature_primary_table_bbox( *, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None, ) -> list[float] | None: @@ -881,11 +1303,13 @@ def _observe_static_text_centers( result: dict[str, list[float]] = {} for row in rows: ordered = sorted(row, key=lambda item: item['bbox'].get('x0', 0)) - text = _anchor_comparable_text(''.join(str(item.get('text') or '') for item in ordered)) - if not text: + text = _anchor_comparable_text(''.join(str(item.get('text') or '') for item in ordered))[:80] + if not text or len(text) >= 80: continue xs = [(float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 / width for item in ordered] ys = [(float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 / height for item in ordered] + if len(result) >= 32: + break result[text] = [round(sum(xs) / len(xs), 4), round(sum(ys) / len(ys), 4)] return result diff --git a/backend/app/services/shipping_notice/error_explainability_contract.py b/backend/app/services/shipping_notice/error_explainability_contract.py index 2c9c860d..d57ea5eb 100644 --- a/backend/app/services/shipping_notice/error_explainability_contract.py +++ b/backend/app/services/shipping_notice/error_explainability_contract.py @@ -531,7 +531,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { '字段已按 PDF 优先裁决,请核对辅助证据差异', ), 'evidence_missing': _meta('owner', 'open_order_review', '关键识别结果缺少有效证据'), - 'customer_unresolved': _meta('owner', 'confirm_customer', '未能识别客户'), + 'customer_unresolved': _meta('owner', 'confirm_customer', '客户尚未确认'), 'customer_ambiguous': _meta('owner', 'confirm_customer', '匹配到多个客户'), 'customer_out_of_scope': _meta('owner', 'confirm_customer', '客户不在当前业务范围内'), 'reservation_missing': _meta('owner', 'edit_reservation', '缺少有效 Reservation'), diff --git a/backend/app/services/shipping_notice/lifecycle_projection.py b/backend/app/services/shipping_notice/lifecycle_projection.py index 6ba2cc8c..5cc5d6f9 100644 --- a/backend/app/services/shipping_notice/lifecycle_projection.py +++ b/backend/app/services/shipping_notice/lifecycle_projection.py @@ -1,7 +1,7 @@ """ services/shipping_notice/lifecycle_projection.py -用途:为批次进度、任务详情与订单生命周期工作台裁决同一份四阶段业务生命周期。 +用途:为批次进度、任务详情与订单生命周期工作台裁决同一份五阶段业务生命周期。 依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或历史兜底事实。 逻辑:正式 Process Gate 优先,其次是可解释阻断原因;仅无正式事实时才使用旧阶段兜底。 本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。 @@ -18,6 +18,7 @@ LIFECYCLE_STAGES: tuple[dict[str, str], ...] = ( {'code': 'intake_parse', 'label': '接收解析'}, {'code': 'order_review', 'label': '订单复核'}, {'code': 'fulfillment_prep', 'label': '通知准备'}, + {'code': 'freight_upload', 'label': '货代上传'}, {'code': 'upload_complete', 'label': '通知完成'}, ) @@ -43,8 +44,8 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = { 'inventory_sufficiency': 'fulfillment_prep', 'excel_readiness': 'fulfillment_prep', 'artifact_generation': 'fulfillment_prep', - 'freight_upload_rpa': 'upload_complete', - 'manual_upload_handoff': 'upload_complete', + 'freight_upload_rpa': 'freight_upload', + 'manual_upload_handoff': 'freight_upload', } # 没有正式 Gate 的历史项才能使用此映射。它必须保持在共享裁决器内,避免各入口漂移。 @@ -60,7 +61,9 @@ LIFECYCLE_STAGE_RANGES: tuple[tuple[str, set[str]], ...] = ( 'inventory_matching', 'inventory_match', 'inventory_matched', 'excel_generating', 'excel_generate', 'excel_generated', }), - ('upload_complete', {'freight_uploading', 'freight_upload', 'upload_receipt_recorded', 'completed'}), + ('freight_upload', { + 'freight_uploading', 'freight_upload', 'upload_receipt_recorded', 'upload_complete', 'completed', + }), ) @@ -104,6 +107,7 @@ def project_lifecycle( legacy_stage: str | None, has_candidate_context: bool, has_intake_parse_context: bool = False, + verified_upload_success: bool = False, ) -> dict[str, Any]: """按 Gate → 阻断归属 → 历史阶段的固定优先级裁决生命周期和入口。 @@ -111,7 +115,12 @@ def project_lifecycle( """ gate = current_gate if isinstance(current_gate, dict) else {} gate_code = str(gate.get('gate_code') or gate.get('code') or '').strip().lower() - if gate_code in LIFECYCLE_STAGE_BY_GATE: + # 成功事实高于当前 Gate/历史阶段:异步回调成功后旧 Gate 尚未清理时,用户仍应 + # 看到已完成;反之任何技术完成、回执文本或旧 completed 都不能越过此条件。 + if verified_upload_success: + lifecycle_stage = 'upload_complete' + authority = 'verified_upload_success' + elif gate_code in LIFECYCLE_STAGE_BY_GATE: lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code] authority = 'process_gate' else: diff --git a/backend/app/services/shipping_notice/order_extraction.py b/backend/app/services/shipping_notice/order_extraction.py index 9306a936..45fc5d8a 100644 --- a/backend/app/services/shipping_notice/order_extraction.py +++ b/backend/app/services/shipping_notice/order_extraction.py @@ -13,6 +13,24 @@ backend/app/services/shipping_notice/order_extraction.py from __future__ import annotations +def reconcile_review_case_after_unit(*, run: Any, unit: Any) -> Any: + """ + Unit 结果已消费时,确保 Review Case 后仍执行统一校验/自动推进协调。 + + Args: + run: Unit 所属的订单抽取 Run。 + unit: 已消费、需要回放的 PDF Unit。 + + Returns: + 确保后的 Review Case;协调器副作用会刷新校验结果并按资格决定后续自动推进。 + """ + from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit + from app.services.shipping_notice.order_stp_auto_create_service import maybe_stp_auto_create_for_run + + case = ensure_review_case_for_unit(run=run, unit=unit) + maybe_stp_auto_create_for_run(run=run) + return case + import hashlib import json from datetime import datetime @@ -1271,8 +1289,7 @@ def submit_order_extraction_unit_result( 'idempotent_replay': True, 'unit_id': int(unit.id), } - from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit - ensure_review_case_for_unit(run=run, unit=unit) + reconcile_review_case_after_unit(run=run, unit=unit) return result session = _runtime_session_for_run(run) diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index a521fc61..fec158b1 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -312,6 +312,7 @@ def _coordinate_profile_rows( *, raw_profile: dict[str, Any], raw_table: dict[str, Any], layout: dict[str, Any], contract: Any, schema_fields: dict[str, dict[str, Any]], document_id: int | None = None, initial_carry: dict[str, Any] | None = None, + coordinate_transform: dict[str, Any] | None = None, ) -> list[dict[str, Any]] | None: """ 用模板表区和整页字符生成带字段坐标的紧凑行候选。 @@ -324,6 +325,7 @@ def _coordinate_profile_rows( schema_fields: field_id/code 对应的冻结 Schema 字段。 document_id: 当前 Unit 文档 ID;提供时生成稳定 token/evidence 引用。 initial_carry: 跨页固定子行的已解析字段。 + coordinate_transform: 共同 matcher 对当前唯一 Profile 已确认的平移;不在本函数重算。 Returns: 规范化字段行;坐标前置条件缺失时返回 None。 @@ -364,11 +366,16 @@ def _coordinate_profile_rows( relative_region = _coordinate_region_mapping(region.region) if relative_region is None: return None + evidence_relative_region = _translate_coordinate_region( + relative_region, coordinate_transform=coordinate_transform, + ) + if evidence_relative_region is None: + return None region_bbox = { - 'x0': relative_region['x0'] * page_bbox['x1'], - 'y0': relative_region['y0'] * page_bbox['y1'], - 'x1': relative_region['x1'] * page_bbox['x1'], - 'y1': relative_region['y1'] * page_bbox['y1'], + 'x0': evidence_relative_region['x0'] * page_bbox['x1'], + 'y0': evidence_relative_region['y0'] * page_bbox['y1'], + 'x1': evidence_relative_region['x1'] * page_bbox['x1'], + 'y1': evidence_relative_region['y1'] * page_bbox['y1'], } raw_bbox = raw_table.get('bbox') if isinstance(raw_table.get('bbox'), dict) else None if not is_virtual_page and raw_bbox is not None and not _coordinate_regions_overlap(raw_bbox, region_bbox): @@ -399,6 +406,7 @@ def _coordinate_profile_rows( initial_fields=carry.get('fields'), initial_next_offset=int(carry.get('next_offset') or 0), line_start_field_code=region.line_start_field_code, row_reconstruction_mode=region.row_reconstruction_mode, + coordinate_transform=coordinate_transform, ): values: list[dict[str, Any]] = [] issues = list(reconstructed.issues) @@ -442,6 +450,60 @@ def _coordinate_profile_rows( return rows +def _selected_coordinate_transform( + *, profile_match: dict[str, Any], raw_profile: dict[str, Any], +) -> dict[str, Any] | None: + """从共同 matcher 的唯一选中候选取得运行时变换,禁止为行解析二次匹配。""" + if str(profile_match.get('status') or '') not in {'unique_match', 'selected_by_score'}: + return None + identity = ( + str(raw_profile.get('profile_code') or ''), + int(raw_profile.get('version') or 0), + str(raw_profile.get('checksum') or ''), + ) + for candidate in profile_match.get('candidates') or []: + if not isinstance(candidate, dict): + continue + candidate_identity = ( + str(candidate.get('profile_code') or ''), + int(candidate.get('version') or 0), + str(candidate.get('checksum') or profile_match.get('checksum') or ''), + ) + if candidate_identity[:2] != identity[:2]: + continue + transform = candidate.get('coordinate_transform') + return transform if isinstance(transform, dict) else None + return None + + +def _translate_coordinate_region( + region: dict[str, float], *, coordinate_transform: dict[str, Any] | None, +) -> dict[str, float] | None: + """在裁剪页级 glyph 前使用 matcher 已确认的受限平移;非法声明 fail-closed。""" + if coordinate_transform is None: + return region + if not isinstance(coordinate_transform, dict) or coordinate_transform.get('status') != 'applied': + return None + try: + translate_x, translate_y = ( + float(coordinate_transform['translate_x']), + float(coordinate_transform['translate_y']), + ) + translated = { + 'x0': float(region['x0']) + translate_x, + 'y0': float(region['y0']) + translate_y, + 'x1': float(region['x1']) + translate_x, + 'y1': float(region['y1']) + translate_y, + } + except (KeyError, TypeError, ValueError): + return None + if not all(value == value and abs(value) != float('inf') for value in translated.values()): + return None + if not (0 <= translated['x0'] < translated['x1'] <= 1 and 0 <= translated['y0'] < translated['y1'] <= 1): + return None + return translated + + def _coordinate_region_mapping(value: Any) -> dict[str, float] | None: """将模板相对区域统一为坐标字典,供绝对裁剪与行重建共同使用。 @@ -734,6 +796,9 @@ def _profile_table_candidates( # MinerU HTML is intentionally neither required nor parsed on this path. try: profile = _frozen_coordinate_profile(raw_profile) + coordinate_transform = _selected_coordinate_transform( + profile_match=profile_match, raw_profile=raw_profile, + ) carry = None parent_table_id = str(raw_table.get('continuation_of') or '') if parent_table_id: @@ -749,6 +814,7 @@ def _profile_table_candidates( raw_profile=raw_profile, raw_table=raw_table, layout=layout, contract=contract, schema_fields=schema_fields, document_id=int(unit.document_id), initial_carry=carry, + coordinate_transform=coordinate_transform, ) except (TypeError, ValueError): issues.append('order_profile_snapshot_invalid') @@ -1806,6 +1872,10 @@ def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, An candidates = extract_order_fields( profile=_frozen_coordinate_profile(raw), schema_fields=schema_fields, coordinate_evidence=layout.get('coordinate_evidence') or {}, + coordinate_transform=_selected_coordinate_transform( + profile_match=match.model_dump(mode='json') if hasattr(match, 'model_dump') else match, + raw_profile=raw, + ), ) return [item.model_dump(mode='json') for item in candidates if item.status == 'confirmed'] diff --git a/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py b/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py index 767971cc..3e21cfdd 100644 --- a/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py +++ b/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py @@ -138,6 +138,8 @@ def _customer_step_for_case( site_id=None, actor_id=None, reason=confirm_reason, + # 保存校验入口需将客户确认、Draft 校验与后续 Gate/STP 写入作为同一事务提交。 + commit=False, ) except Exception as exc: # noqa: BLE001 _LOGGER.warning( @@ -179,6 +181,33 @@ def _customer_step_for_case( } +def auto_confirm_unique_customer_for_review_case( + *, + case: ShippingOrderReviewCase, + trigger: str, +) -> dict[str, Any]: + """ + 将当前 Case 的唯一 Shadow 客户候选落为 Bill-to 已确认事实。 + + 用途与触发时机:保存订单并校验、恢复协调等入口在读取建单资格前调用; + 仅 ``unique_candidate`` 能自动确认,其他匹配状态保持人工处置。 + + Args: + case: 当前文件 Stream 的可编辑订单复核 Case。 + trigger: 调用来源,写入客户确认审计。 + + Returns: + 客户步骤摘要;``auto_confirmed`` 时附带标准客户主键,其他状态不伪造确认事实。 + """ + status, metadata = _customer_step_for_case(case=case, trigger=trigger) + if status == 'auto_confirmed': + db.session.flush() + return { + 'status': status, + **(dict(metadata) if isinstance(metadata, dict) else {}), + } + + def reconcile_single_case_for_auto_progress( *, case_no: Any = None, diff --git a/backend/app/services/shipping_notice/order_review_disposition_service.py b/backend/app/services/shipping_notice/order_review_disposition_service.py index d7ee626b..af92d24e 100644 --- a/backend/app/services/shipping_notice/order_review_disposition_service.py +++ b/backend/app/services/shipping_notice/order_review_disposition_service.py @@ -6,7 +6,8 @@ backend/app/services/shipping_notice/order_review_disposition_service.py workflow_ledger_service、order_task_service.resolve_order_task_for_candidate。 逻辑:处置只改变当前 PDF 的 Case 生命周期;锁定时分别 FOR UPDATE Case 与 Draft, 禁止 joinedload+FOR UPDATE。单文件重识别通过新的 Run 保留原始 PDF 与机器结果, -成功后才由 Run 终态钩子替代旧 Case;创建后继 Run 时显式传入 Case 对应 OT(非 Run 根号)。 +成功后才由 Run 终态钩子替代旧 Case,并在 Stream 原子切换成功后补触发新版 Case 的统一自动推进; +创建后继 Run 时显式传入 Case 对应 OT(非 Run 根号)。 每次关键处置同时写 CaseEvent + 统一 ShippingAuditEvent; 质量异常原因码 `other` 时备注必填。被拒绝操作(无效原因、终态冲突、替代状态不满足、 WorkflowItem 已关闭等)在抛错前独立 commit 拒绝审计,避免 API 回滚吞掉留痕。由 workspace shipping_notice API 调用。 @@ -1015,7 +1016,17 @@ def reparse_case_document( def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: bool) -> None: - """在新版 Run 终态收口旧 Case:成功替代,失败恢复原草稿的原生命周期。""" + """ + 在新版 Run 终态收口旧 Case,并在成功切换当前版本后恢复自动推进。 + + 核心逻辑:重解析结果落库时新版 Case 尚不是 Stream 当前版本,协调器会安全跳过; + 因此只在 ``activate_review_case`` 已确认切换成功后调用单 Case 协调器。这样复用 + 客户确认、Draft 校验、Gate 与 STP 幂等链路,且不会让晚到分支覆盖已确认版本。 + + Args: + run: 已到终态的重解析后继 Run。 + succeeded: 新版 Run 是否成功到达可复核终态。 + """ marker = (run.input_snapshot_json or {}).get('review_reparse') if not isinstance(marker, dict) or not run.reparse_of_run_id: return @@ -1042,10 +1053,21 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo # Run 已到终态但没有可复核新版本时,不可废弃旧草稿。 return from app.services.shipping_notice.review_stream_service import activate_review_case - activate_review_case( + stream = activate_review_case( case=replacement_case, trigger='batch_reparse_succeeded' if marker.get('batch_reparse_id') else 'document_reparse_succeeded', ) + # [STEP] 只有 Stream 已原子指向新版 Case 才补偿自动推进。激活被并发确认或 + # 晚到分支拒绝时,保持该草稿只读,不得错误建单或进入库存准备。 + if int(stream.current_case_id or 0) == int(replacement_case.id): + from app.services.shipping_notice.order_review_auto_progress_coordinator import ( + reconcile_single_case_for_auto_progress, + ) + reconcile_single_case_for_auto_progress( + case=replacement_case, + trigger='document_reparse_succeeded', + refresh_validation=True, + ) _append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_succeeded', operation={ 'successor_run_no': run.run_no, 'replacement_case_no': replacement_case.case_no, diff --git a/backend/app/services/shipping_notice/order_review_profile_match_service.py b/backend/app/services/shipping_notice/order_review_profile_match_service.py index f4e85ed7..3e4a76eb 100644 --- a/backend/app/services/shipping_notice/order_review_profile_match_service.py +++ b/backend/app/services/shipping_notice/order_review_profile_match_service.py @@ -134,12 +134,31 @@ def _sanitize_candidates(raw: list[Any], *, display_map: dict[tuple[str, int], s 'missing_required_anchor_ids': [ str(c) for c in (item.get('missing_required_anchor_ids') or []) if c ][:12], + 'coordinate_transform': _sanitize_coordinate_transform(item.get('coordinate_transform')), }) if len(out) >= 5: break return out +def _sanitize_coordinate_transform(value: Any) -> dict[str, Any] | None: + """投影受限坐标变换审计摘要;禁止泄露原始正文和完整坐标。""" + if not isinstance(value, dict): + return None + status = str(value.get('status') or '').strip() + if not status: + return None + result: dict[str, Any] = {'status': status} + for key in ('translate_x', 'translate_y'): + raw = value.get(key) + try: + result[key] = round(float(raw), 6) if raw is not None else None + except (TypeError, ValueError): + result[key] = None + result['reason_codes'] = [str(code) for code in (value.get('reason_codes') or []) if str(code).strip()][:12] + return result + + def project_review_case_profile_match(case: ShippingOrderReviewCase) -> dict[str, Any]: """ 投影建单前文档模板匹配摘要。 diff --git a/backend/app/services/shipping_notice/order_review_projection.py b/backend/app/services/shipping_notice/order_review_projection.py index 0b33037f..cdd992ae 100644 --- a/backend/app/services/shipping_notice/order_review_projection.py +++ b/backend/app/services/shipping_notice/order_review_projection.py @@ -47,6 +47,7 @@ from app.models import ( ShippingOrderProcessingRun, ShippingOrderReviewCase, ShippingOrderReviewStream, + ShippingOrderIntake, ) @@ -535,6 +536,40 @@ def _document_filename(run: ShippingOrderProcessingRun, document_id: int) -> str return None +def _document_intake_for_retry( + run: ShippingOrderProcessingRun, + document_id: int, +) -> ShippingOrderIntake | None: + """按冻结文档归属定位当前 Intake,避免工作台按文件名或会话猜测 SNI。""" + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + for intake_snapshot in snapshot.get('intakes') or []: + if not isinstance(intake_snapshot, dict): + continue + for document in intake_snapshot.get('documents') or []: + if not isinstance(document, dict) or int(document.get('document_id') or 0) != int(document_id): + continue + intake_no = str(intake_snapshot.get('intake_no') or '').strip().upper() + if intake_no: + return ShippingOrderIntake.query.filter_by(intake_no=intake_no).one_or_none() + return None + + +def _intake_retry_projection( + case: ShippingOrderReviewCase, + run: ShippingOrderProcessingRun, + candidate: ShippingOrderCandidate | None, +) -> tuple[str | None, bool]: + """返回当前 Case 唯一的 Intake 重试目标与服务端授权结果。""" + intake = _document_intake_for_retry(run, int(case.document_id)) + retry_authorized = bool( + intake is not None + and str(intake.parse_status or '').strip().lower() == 'parse_failed' + and candidate is None + and not case.confirmed_task_id + ) + return (intake.intake_no if retry_authorized else None, retry_authorized) + + def _allowed_actions(case: ShippingOrderReviewCase) -> list[str]: """由后端 Case 状态与 WorkflowItem 生命周期决定可用动作,前端不可自行推导确认资格。""" from app.services.shipping_notice.tool_common import llm_review_enabled @@ -651,6 +686,7 @@ def serialize_review_case( run = case.run draft = case.current_draft candidate = db.session.get(ShippingOrderCandidate, case.candidate_id) if case.candidate_id else None + intake_no, intake_retry_authorized = _intake_retry_projection(case, run, candidate) schema_fields = _schema_fields(run) header_fields = [item for item in schema_fields if item.get('scope') == 'header'] line_fields = [item for item in schema_fields if item.get('scope') == 'line'] @@ -678,7 +714,13 @@ def serialize_review_case( 'issues': list(draft.issue_summary_json or []), 'validation': dict(draft.validation_result_json or {}), 'build_eligibility': { - 'can_build': bool((draft.validation_result_json or {}).get('can_build')), + # 未校验不是业务阻断;保留 None 让前端展示“尚未校验”,避免 + # 把缺失的布尔值投影成 can_build=false。 + 'can_build': ( + bool((draft.validation_result_json or {}).get('can_build')) + if str((draft.validation_result_json or {}).get('status') or '').strip() != 'not_validated' + else None + ), 'can_auto_create': bool((draft.validation_result_json or {}).get('can_auto_create')), 'status': str((draft.validation_result_json or {}).get('status') or 'needs_review'), 'gates': dict((draft.validation_result_json or {}).get('gates') or {}), @@ -912,6 +954,16 @@ def serialize_review_case( # task_missing:无恢复 API 时明确 view + contact_admin;防御性剥离残留 confirm。 available_actions = list(bundle['available_actions']) if bundle else [a for a in _allowed_actions(case) if a != 'confirm'] + if intake_retry_authorized: + available_actions = ['retry_parse'] + elif ( + candidate is None + and not case.confirmed_task_id + and (intake := _document_intake_for_retry(run, int(case.document_id))) is not None + and str(intake.parse_status or '').strip().lower() in {'parsing', 'queued', 'cancelled'} + ): + # parsing / cancelled 等状态只可等待或查看;不得把草稿动作误投影为解析恢复。 + available_actions = [] # 兼容兜底:task_missing 仍然优先固定视图动作。 if formal_ot.get('task_missing'): available_actions = ['view', 'contact_admin'] @@ -976,6 +1028,7 @@ def serialize_review_case( 'draft': projected_draft, 'llm_suggestions': llm_suggestions, 'available_actions': available_actions, + 'intake_no': intake_no, 'formal_editable_field_ids': ( list_editable_formal_field_ids( schema_fields, @@ -1002,6 +1055,8 @@ def _serialize_review_case_summary( ) -> dict[str, Any]: """为工作台文件队列投影单 Case 的只读识别与生命周期摘要。""" candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None + intake = _document_intake_for_retry(run, int(case.document_id)) + intake_no, intake_retry_authorized = _intake_retry_projection(case, run, candidate) # 空 Review Case 只是解析异常/人工处置容器,不能显示为已进入订单复核。 # 只有当前有效 Candidate 或正式任务事实存在时,才进入订单生命周期。 lifecycle_stage = 'intake_parse' @@ -1044,7 +1099,21 @@ def _serialize_review_case_summary( 'status': case.status, 'draft_version': int(case.current_draft.draft_version) if case.current_draft is not None else None, 'issue_count': len(case.current_draft.issue_summary_json or []) if case.current_draft is not None else 0, - 'available_actions': _allowed_actions(case), + # Intake 解析失败没有 Candidate,恢复必须从当前阶段卡调用原 SNI retry API。 + # 其它 Intake 状态(尤其 parsing/cancelled)不得由前端显示或猜测重试。 + 'available_actions': ( + ['retry_parse'] + if intake_retry_authorized + else ( + [] + if intake is not None + and str(intake.parse_status or '').strip().lower() in {'parsing', 'queued', 'cancelled'} + and candidate is None + and not case.confirmed_task_id + else _allowed_actions(case) + ) + ), + 'intake_no': intake_no, # 后端按 Case/正式任务裁决,禁止工作台仅为当前项从草稿拼接 PO 或阶段。 'po_number': str(candidate.po_number or '').strip() or None if candidate is not None else None, 'lifecycle_stage': lifecycle_stage, diff --git a/backend/app/services/shipping_notice/order_review_resume_service.py b/backend/app/services/shipping_notice/order_review_resume_service.py index 979b89fe..bcf9eb43 100644 --- a/backend/app/services/shipping_notice/order_review_resume_service.py +++ b/backend/app/services/shipping_notice/order_review_resume_service.py @@ -129,6 +129,7 @@ def resume_after_review_change( change_type: str | None = None, skip_validate: bool = False, allow_auto_create: bool = True, + expected_draft_version: int | None = None, ) -> dict[str, Any]: """ 建单前统一恢复:重校验 → Gate 同步 → 资格重算 → 可选 auto_gate 建单。 @@ -141,6 +142,7 @@ def resume_after_review_change( change_type: 可选失效规则键(process_gate_dependency)。 skip_validate: True 时跳过 validate_draft(调用方刚校验过)。 allow_auto_create: False 时只重算资格,不自动建单(例如仅预览)。 + expected_draft_version: 可选乐观锁版本;显式保存校验时必须传入。 Returns: resume_outcome 字典(含 gate_recalculated / auto_gate_allowed / task_created 等)。 @@ -177,12 +179,27 @@ def resume_after_review_change( 'case': serialize_review_case(case), } + # [STEP 1.5] 唯一 Shadow 候选必须先写成 Bill-to confirmed,再读取建单资格。 + # 否则保存校验会把“唯一候选待确认”误判为“客户未识别”。不在此处 commit, + # 保证客户确认、Draft 校验与后续 Gate/STP 决策属于同一事务。 + from app.services.shipping_notice.order_review_auto_progress_coordinator import ( + auto_confirm_unique_customer_for_review_case, + ) + customer_auto_confirmation = auto_confirm_unique_customer_for_review_case( + case=case, + trigger=trigger_code, + ) + # [STEP 2] 显式全量校验(同步建单前 Gate)。 if not skip_validate: validate_draft( user_id=int(user_id), case_no=str(case.case_no), - expected_draft_version=int(case.current_draft.draft_version), + expected_draft_version=( + int(expected_draft_version) + if expected_draft_version is not None + else int(case.current_draft.draft_version) + ), ) db.session.flush() case = _reload_case(user_id=user_id, case_no=case_no) @@ -216,6 +233,7 @@ def resume_after_review_change( 'auto_gate_allowed': snap['auto_gate_allowed'], 'qualification_status': snap['qualification_status'], 'failed_gates': snap['failed_gates'], + 'customer_auto_confirmation': customer_auto_confirmation, }, source='order_review_resume', strict=True, @@ -238,6 +256,7 @@ def resume_after_review_change( ), 'case': serialize_review_case(case), 'invalidated_gates': invalidated, + 'customer_auto_confirmation': customer_auto_confirmation, } # [STEP 5] 可建单但不允许 auto_gate:等待人工确认建单。 @@ -276,6 +295,7 @@ def resume_after_review_change( ), 'case': serialize_review_case(case), 'invalidated_gates': invalidated, + 'customer_auto_confirmation': customer_auto_confirmation, } # [STEP 6] auto_gate:入队 STP 幂等 Job(queued);Worker 再执行 confirm。 diff --git a/backend/app/services/shipping_notice/order_review_workbench_projection.py b/backend/app/services/shipping_notice/order_review_workbench_projection.py index 26d91736..11b16712 100644 --- a/backend/app/services/shipping_notice/order_review_workbench_projection.py +++ b/backend/app/services/shipping_notice/order_review_workbench_projection.py @@ -441,9 +441,12 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str } task_no = str(getattr(task, 'task_no', None) or '').strip().upper() or None + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + + verified_upload_success = has_verified_upload_success(task) upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower() progress_state = ( - 'uploaded' if upload_status in {'uploaded', 'succeeded', 'success'} + 'uploaded' if verified_upload_success else 'export_ready' if getattr(task, 'export_file_path', None) else 'matched' if getattr(task, 'match_status', None) else 'inventory_ready' if getattr(task, 'inventory_lines_json', None) @@ -633,9 +636,14 @@ def project_stage_for_task( map_notice_to_processing_status_stage, ) - upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower() + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + + # 业务完成不能仅信任 Notice 的历史聚合字段。复核工作台必须与批次投影 + # 复用同一成功谓词,否则同一任务会在不同入口出现“已完成/待上传”分叉。 + verified_upload_success = has_verified_upload_success(task) + raw_upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower() progress_state = ( - 'uploaded' if upload_status in {'uploaded', 'succeeded', 'success'} + 'uploaded' if verified_upload_success else 'export_ready' if getattr(task, 'export_file_path', None) else 'matched' if getattr(task, 'match_status', None) else 'inventory_ready' if getattr(task, 'inventory_lines_json', None) @@ -656,10 +664,12 @@ def project_stage_for_task( 'stage_node': None, } - # 上传登记/回调会先更新 ShippingNotice 聚合事实;旧 OT.stage 可能仍停在 - # freight_uploading,不能用过期阶段覆盖已经完成的履约状态。 - if progress_state in {'uploaded', 'closed', 'completed'}: + # 成功回调会先更新 Notice 聚合事实;旧 OT.stage 可能仍停在 + # freight_uploading,只有三层成功事实齐备时才能覆盖为 completed。 + if progress_state == 'uploaded': return _with_label('completed', source='notice_terminal') + if raw_upload_status in {'uploaded', 'succeeded', 'success'}: + return _with_label('freight_uploading', source='upload_success_unverified') # [STEP 1] OT 实体 stage 优先(与 shipping_processing_projection 同源)。 order_task = None @@ -678,6 +688,8 @@ def project_stage_for_task( order_task = None ot_stage = str(getattr(order_task, 'stage', None) or '').strip().lower() if order_task else '' if ot_stage and ot_stage in SHIPPING_PROCESSING_STAGES: + if ot_stage == 'completed' and not verified_upload_success: + return _with_label('freight_uploading', source='upload_success_unverified') # [STEP 1b] 正式 OT 已创建但 stage 仍停在 order_creating:业务上已进入获取库存。 # Notice 已到 waiting_inventory/parsed 时跟 notice 映射;仍为 created 时推进到 inventory_fetching。 if ot_stage == 'order_creating': diff --git a/backend/app/services/shipping_notice/process_gate_contract.py b/backend/app/services/shipping_notice/process_gate_contract.py index 67577492..5203af92 100644 --- a/backend/app/services/shipping_notice/process_gate_contract.py +++ b/backend/app/services/shipping_notice/process_gate_contract.py @@ -316,7 +316,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'gate_code': 'freight_upload_rpa', 'sequence_no': 19, 'label': '货代上传 RPA', - 'ui_placement': {'target_surface': 'upload_complete', 'target_anchor': 'freight_upload'}, + 'ui_placement': {'target_surface': 'freight_upload', 'target_anchor': 'freight_upload'}, 'responsible_party': 'worker', 'implementation_status': 'implemented', 'recoverable': True, @@ -330,7 +330,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'gate_code': 'manual_upload_handoff', 'sequence_no': 20, 'label': '人工上传交接', - 'ui_placement': {'target_surface': 'upload_complete', 'target_anchor': 'manual_upload'}, + 'ui_placement': {'target_surface': 'freight_upload', 'target_anchor': 'manual_upload'}, 'responsible_party': 'owner', 'implementation_status': 'implemented', 'recoverable': True, @@ -706,7 +706,7 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = { 'upload_rpa_failed': 'freight_upload_rpa', 'upload_rpa_login_failed': 'freight_upload_rpa', 'upload_platform_rejected': 'freight_upload_rpa', - 'upload_result_unknown': 'manual_upload_handoff', + 'upload_result_unknown': 'freight_upload_rpa', } # Candidate Qualification / 旧自动建单门禁键 → 唯一 owning_gate(禁止平行用户投影)。 diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index ca366a70..e1561315 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -167,7 +167,8 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: 【触发时机】写状态机回写 OT、投影组装 order_task 工作项。 - 核心逻辑:上传完成 → completed;上传中/待上传 → freight_uploading; + 核心逻辑:仅可审计的上传成功 → completed;上传中、待登记及历史无证据上传 + → freight_uploading; 导出/Excel → excel_generating;waiting_inventory/parsed → inventory_fetching; matching/inventory_ready/matched → inventory_matching;建单中 → order_creating。 领域映射唯一来源,禁止写状态机反向依赖投影私有函数。 @@ -185,8 +186,16 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: review = str(getattr(notice, 'review_status', None) or '').strip().lower() match = str(getattr(notice, 'match_status', None) or '').strip().lower() lifecycle = str(getattr(notice, 'lifecycle_status', None) or '').strip().lower() - if upload_st in {'uploaded', 'succeeded', 'success'} or lifecycle in {'archived', 'deleted'}: + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + + verified_upload_success = has_verified_upload_success(notice) + if lifecycle in {'voided', 'archived', 'deleted'}: + return ('cancelled', 'cancelled') + if verified_upload_success: ps = 'uploaded' + elif upload_st in {'uploaded', 'succeeded', 'success'}: + # 历史聚合字段或单一回执不构成业务完成。保留在上传工作面,等待核对。 + ps = 'waiting_upload' elif upload_st in {'uploading', 'pending', 'failed'} or pending in {'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown'}: ps = 'waiting_upload' if upload_st != 'failed' else 'upload_failed' elif export_path: @@ -444,6 +453,7 @@ def reconcile_processing_projection_facts( legacy_actions: list[str] | None = None, invalidated_from_stage: str | None = None, excel_ready: bool = False, + verified_upload_success: bool | None = None, ) -> dict[str, Any]: """ 在投影输出前强制 status/stage/gate/action 不变量,并写入 stage_nodes。 @@ -518,6 +528,17 @@ def reconcile_processing_projection_facts( status = 'automating' stage_idx = shipping_processing_stage_index(stage) + # 完成由上传成功谓词单独裁决。正式 OT 的历史 completed/uploaded 不能因为 + # 旧字段、归档或技术流程结束而越过人工核对;取消态不在此规则内改写。 + if verified_upload_success is True: + status = 'completed' + stage = 'completed' + gate = None + gate_action = None + elif verified_upload_success is False and status == 'completed': + status = 'waiting_human' + stage = 'freight_uploading' + # [BE-03] Extraction Run 完成误标为全流程 completed:早期 stage 时回退 status。 if status == 'completed' and stage and stage != 'completed': if stage_idx is not None and stage_idx <= waiting_idx: @@ -732,7 +753,21 @@ def apply_user_projection_fields( # ===== [STEP 4] 按冻结映射规则计算 user_status(F3 优先级) ===== notice_upload_status = str(getattr(notice, 'upload_status', None) or '').strip().lower() if notice is not None else '' - _rd_has_completed_process = notice_upload_status in {'uploaded', 'succeeded', 'success'} + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + + # 读取路径也必须遵守三层上传成功事实;否则 retry 决策或旧 status=completed + # 会在这一步将前序 reconcile 的货代上传态重新提升为完成。 + verified_upload_success = bool(notice is not None and has_verified_upload_success(notice)) + unverified_upload_terminal = bool( + notice is not None + and not verified_upload_success + and ( + old_status == 'completed' + or old_stage == 'completed' + or notice_upload_status in {'uploaded', 'succeeded', 'success'} + ) + ) + _rd_has_completed_process = verified_upload_success def _compute_user_status() -> str: # [BE-09] 当前 Gate 终态优先于旧 Notice retry decision。Retry decision @@ -742,6 +777,8 @@ def apply_user_projection_fields( return 'retryable' if gate_status == 'blocked_manual': return 'waiting_human' + if unverified_upload_terminal: + return 'waiting_human' # 1) 终态短路:old_status completed/cancelled/failed if old_status == 'completed': return 'completed' @@ -752,7 +789,7 @@ def apply_user_projection_fields( # Retry Decision 可得时:优先用决策器 if retry_decision is not None: # 4) rd_status=completed 或 action=noop 且 notice 完成态 → completed - if rd_status == _RD_STATUS_COMPLETED: + if rd_status == _RD_STATUS_COMPLETED and verified_upload_success: return 'completed' if rd_action == _RD_NOOP and _rd_has_completed_process: return 'completed' @@ -781,6 +818,12 @@ def apply_user_projection_fields( user_status = _compute_user_status() + if unverified_upload_terminal: + payload['status'] = 'waiting_human' + payload['stage'] = 'freight_uploading' + old_status = 'waiting_human' + old_stage = 'freight_uploading' + # ===== [不变] user_stage 计算(保持不动) ===== user_stage = _USER_STAGE_TO_CODE.get(old_stage) if user_stage is None: diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index 14ccc1c0..9b2d4b09 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -49,7 +49,7 @@ from app.services.shipping_notice.processing_ownership import ( record_projection_inconsistency_audit, ) from app.services.shipping_notice.lifecycle_projection import ( - LIFECYCLE_STAGE_RANGES, + LIFECYCLE_STAGE_CODES, project_lifecycle, ) from app.services.shipping_notice.query_service import resolve_task_export_download @@ -1280,19 +1280,34 @@ def _project_order_task_work_item( str(run.status or ''), stage=stage, ) - # 人工上传登记/RPA 回调先更新 ShippingNotice 聚合事实;旧 OT.status 可能仍为 - # automating。终态 Notice 必须覆盖旧 OT 状态,保证统一投影、右侧状态和进度节点同源。 + # 完成只接受三层可审计成功事实。旧 OT/process_status/upload_status 可能遗留 + # completed/uploaded;缺少成功 Attempt 时必须停在货代上传,不能进入完成统计。 + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + + verified_upload_success = bool( + notice_for_stage is not None and has_verified_upload_success(notice_for_stage) + ) notice_process_status = str(getattr(notice_for_stage, 'process_status', None) or '').strip().lower() if notice_for_stage is not None else '' notice_upload_status = str(getattr(notice_for_stage, 'upload_status', None) or '').strip().lower() if notice_for_stage is not None else '' notice_lifecycle = str(getattr(notice_for_stage, 'lifecycle_status', None) or '').strip().lower() if notice_for_stage is not None else '' - if ( - notice_process_status in {'uploaded', 'closed', 'completed'} - or notice_upload_status in {'uploaded', 'succeeded', 'success'} - or notice_lifecycle in {'voided', 'archived', 'deleted'} - ): + if verified_upload_success: status = 'completed' stage = 'completed' stage_label_key = 'completed' + elif notice_for_stage is not None and ( + status == 'completed' + or stage == 'completed' + or notice_process_status in {'uploaded', 'closed', 'completed'} + or notice_upload_status in {'uploaded', 'succeeded', 'success'} + ): + status = 'waiting_human' + stage = 'freight_uploading' + stage_label_key = 'freight_uploading' + elif notice_lifecycle in {'voided', 'archived', 'deleted'}: + status = 'cancelled' + # 取消/归档是终态而非完成态;保留最后业务工作面便于解释和审计回看。 + stage = 'freight_uploading' + stage_label_key = 'freight_uploading' # [BE-03] OT 上残留的 completed + 早期 stage 组合在输出前再折叠。 if status == 'completed' and stage != 'completed': status = derivation_status_for_extraction_run('completed', stage=stage) @@ -1382,6 +1397,7 @@ def _project_order_task_work_item( 'intake_no': _first_intake_no_for_run(run), 'status': status, 'stage': stage, + 'verified_upload_success': verified_upload_success if notice_for_stage is not None else None, # 与 Case.current_stage.label_key 同源;前端禁止用 stage 码直接当用户文案。 'stage_label_key': stage_label_key or ( 'waiting_system_start' if stage == 'order_creating' else stage @@ -1413,6 +1429,7 @@ def _project_order_task_work_item( legacy_actions=legacy_actions, invalidated_from_stage=invalidated_from_stage, excel_ready=excel_ready, + verified_upload_success=verified_upload_success if notice_for_stage is not None else None, ) # [STEP] 投影不一致:写审计后剥离内部诊断字段,避免泄漏给前端契约。 record_projection_inconsistency_audit(payload) @@ -1677,8 +1694,14 @@ def _conversation_processing_group_for_work_item(item: dict[str, Any]) -> str: item: order_task 工作项 dict。 Returns: - needs_action | processing | completed 之一。 + needs_action | processing | completed | history 之一。 """ + is_unverified_upload_terminal = ( + item.get('verified_upload_success') is False + and str(item.get('user_status') or item.get('status') or '').strip().lower() == 'completed' + ) + if is_unverified_upload_terminal: + return 'needs_action' user_group = str(item.get('user_group') or '').strip().lower() if user_group in {'failed', 'waiting_human'}: return 'needs_action' @@ -1693,12 +1716,18 @@ def _conversation_processing_group_for_work_item(item: dict[str, Any]) -> str: stage = str(item.get('stage') or '').strip().lower() if user_status in {'waiting_human', 'retryable', 'failed'}: return 'needs_action' - if user_status in {'completed', 'cancelled'}: + if user_status in {'cancelled', 'archived', 'voided', 'deleted'}: + return 'history' + if user_status == 'completed': return 'completed' if user_status == 'running': return 'processing' if status in {'failed', 'blocked'} or stage == 'waiting_review' or status == 'waiting_review': return 'needs_action' + if status in {'cancelled', 'archived', 'voided', 'deleted'} or stage in { + 'cancelled', 'archived', 'voided', 'deleted', + }: + return 'history' if status == 'completed' or stage == 'completed': return 'completed' return 'processing' @@ -1717,6 +1746,8 @@ def _conversation_processing_status_label_for_work_item(item: dict[str, Any]) -> user_status = str(item.get('user_status') or '').strip().lower() status = str(item.get('status') or '').strip().lower() stage = str(item.get('stage') or '').strip().lower() + if item.get('verified_upload_success') is False and user_status == 'completed': + return 'pending_review' if user_status == 'waiting_human': return 'pending_review' if user_status == 'retryable': @@ -2334,16 +2365,10 @@ def _conversation_task_row_from_work_item( 'document_id': source_document_id, 'filename': filename, }) - user_group = str(item.get('user_group') or '').strip().lower() - if not user_group: - user_status = str(item.get('user_status') or item.get('status') or '').strip().lower() - user_group = ( - 'failed' if user_status in {'failed', 'retryable'} - else 'waiting_human' if user_status in {'waiting_human', 'waiting_review'} - else 'completed' if user_status == 'completed' - else 'cancelled' if user_status == 'cancelled' - else 'processing' - ) + # status_groups 与文件统计必须消费同一用户态裁决。尤其是旧载荷的 + # completed + verified_upload_success=False,顶层已降级为待处理,不能在 + # status_groups 又显示为 completed。 + user_group = _batch_user_group(item) return { 'user_task_no': user_task_no, 'submission_ordinal': None, @@ -2415,6 +2440,7 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]: ), # 空 Candidate 的接收解析只认后端持久化 Case 显式授予的上下文。 has_intake_parse_context=bool(item.get('intake_parse_authorized')), + verified_upload_success=bool(item.get('verified_upload_success')), ) lifecycle_stage = lifecycle['lifecycle_stage'] if primary is not None: @@ -2491,7 +2517,7 @@ def _action_lifecycle_target(action_code: Any, *, lifecycle_stage: str | None) - 'download_excel', 'open_manual_upload', 'wait_manual_upload', 'mark_manual_uploaded', 'retry_freight_upload_rpa', 'retry_upload', }: - return 'upload_complete' + return 'freight_upload' # 历史 Review 投影的 view 与 view_result 同为只读查看入口;必须由后端附带 # 当前已裁决的工作台目标,前端不得因缺失目标误判为“前置阶段未完成”。 return lifecycle_stage if code in {'view', 'view_result', 'view_record'} else None @@ -2509,6 +2535,7 @@ def _lifecycle_stage_from_item(item: dict[str, Any]) -> str | None: legacy_stage=str(item.get('user_stage') or item.get('stage') or ''), has_candidate_context=bool(item.get('has_formal_ot') or item.get('shipping_notice_no')), has_intake_parse_context=bool(item.get('intake_parse_authorized')), + verified_upload_success=bool(item.get('verified_upload_success')), )['lifecycle_stage'] @@ -2516,7 +2543,7 @@ def _current_file_representatives(work_items: list[dict[str, Any]]) -> list[dict """为批次投影选择每个业务文件唯一的当前代表项。 核心逻辑:EML 聚合根不参与文件口径;同一文件的旧 Run、旧 OT 或历史失败 - 投影只保留最新活动项。四阶段、文件统计、未分类统计必须共用本函数,避免一个 + 投影只保留最新活动项。五阶段、文件统计、未分类统计必须共用本函数,避免一个 PDF 同时被计入多个阶段或多个状态组。 Args: @@ -2705,11 +2732,11 @@ def _display_work_items_from_current_files(work_items: list[dict[str, Any]]) -> return displayed -def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]: - """从最终用户态工作项构建批次四阶段主进度。 +def _batch_lifecycle_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]: + """从最终用户态工作项构建批次五阶段主进度。 业务阶段映射和状态优先级只在后端维护;15 个技术节点仍附着在单项诊断字段, - 绝不要求前端通过 stage 索引再计算四阶段。 + 绝不要求前端通过 stage 索引再计算业务阶段。 """ ranked_items = sorted( _current_file_representatives(work_items), @@ -2733,17 +2760,21 @@ def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, 'failed': 0, 'blocking_reason': None, } - for code, _ in LIFECYCLE_STAGE_RANGES + for code in LIFECYCLE_STAGE_CODES } for item in ranked_items: lifecycle_stage = _lifecycle_stage_from_item(item) if lifecycle_stage is None: continue + # 历史取消/归档只能保留在 history/status_groups,既不推动任一工作面, + # 也不得作为「通知完成」的分子或分母。 + item_group = _batch_user_group(item) + if item_group in {'cancelled', 'archived'}: + continue summary = stage_summaries[lifecycle_stage] summary['total'] += 1 - # 四阶段与文件概览必须消费同一正式用户分组。user_status 可能在旧 Run + # 生命周期与文件概览必须消费同一正式用户分组。user_status 可能在旧 Run # 兼容投影中残留为 running,不能把后端已裁决为“待处理”的文件再显示为处理中。 - item_group = _batch_user_group(item) if item_group == 'completed': summary['completed'] += 1 continue @@ -2763,7 +2794,7 @@ def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, } or None nodes: list[dict[str, Any]] = [] - for code, _ in LIFECYCLE_STAGE_RANGES: + for code in LIFECYCLE_STAGE_CODES: summary = stage_summaries[code] # 卡片状态只由本阶段聚合事实计算,禁止由其他阶段的优先文件反向影响。 status = ( @@ -2781,8 +2812,13 @@ def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, return nodes +def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]: + """兼容别名:已升级为五阶段输出,调用方应迁移至 ``_batch_lifecycle_nodes``。""" + return _batch_lifecycle_nodes(work_items) + + def _unclassified_summary(work_items: list[dict[str, Any]]) -> dict[str, int]: - """统计无法归入四阶段的业务文件,避免批次摘要与文件清单口径不一致。""" + """统计无法归入业务生命周期的文件,避免批次摘要与文件清单口径不一致。""" return { 'count': sum( 1 for item in _current_file_representatives(work_items) @@ -2823,7 +2859,7 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An 优先级与 EML 聚合保持一致:失败/可重试优先,其次待人工;系统处理中不伪造 人工入口。批次动作始终引用一个已授权叶子/EML action,写路径仍会二次校验。 """ - # 批次主状态与文件计数、四阶段必须消费同一份“每文件唯一当前代表项”。 + # 批次主状态与文件计数、五阶段必须消费同一份“每文件唯一当前代表项”。 # 否则历史 Run 的失败/待办虽然不再计数,仍可能抢走批次 CTA,形成 # “数字是当前、按钮却指向历史”的第二裁决源。 ranked = sorted( @@ -2862,26 +2898,37 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An def _batch_user_group(item: dict[str, Any]) -> str: """归一批次统计使用的互斥用户分组,优先消费领域投影已裁决的 user_group。""" + # 兼容载荷中可能残留 technical completed。只要正式 Notice/OT 已明确给出 + # 未验证成功,就绝不能把它带入批次 completed 分子。 + if item.get('verified_upload_success') is False and str( + item.get('user_status') or item.get('status') or '' + ).strip().lower() == 'completed': + return 'waiting_human' group = str(item.get('user_group') or '').strip().lower() - if group in {'failed', 'waiting_human', 'processing', 'completed'}: + if group in {'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived'}: return group status = str(item.get('user_status') or item.get('status') or '').strip().lower() if status in {'failed', 'retryable'}: return 'failed' if status in {'waiting_human', 'waiting_review', 'idle'}: return 'waiting_human' - if status in {'completed', 'cancelled'}: + if status == 'completed': return 'completed' + if status in {'cancelled', 'archived', 'voided', 'deleted'}: + return 'cancelled' return 'processing' def _batch_file_counts(work_items: list[dict[str, Any]]) -> dict[str, int]: """按唯一当前业务文件统计互斥状态组,EML 容器永不计数。""" + # 已取消/归档文件保留在历史列表,但不构成当前任务完成率的分母或分子。 groups = {'failed': 0, 'waiting_human': 0, 'processing': 0, 'completed': 0} for item in _current_file_representatives(work_items): group = _batch_user_group(item) summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {} filename = str(summary.get('filename') or '').strip().lower() + if group not in groups: + continue if not filename.endswith('.eml') and (filename or int(summary.get('document_id') or 0)): groups[group] += 1 return { @@ -2914,12 +2961,13 @@ def _conversation_processing_from_work_items( Returns: 与 project_conversation_processing 同形的 dict。 """ - # 文件清单必须与批次统计、四阶段和 CTA 使用相同的当前文件代表项,同时 + # 文件清单必须与批次统计、五阶段和 CTA 使用相同的当前文件代表项,同时 # 保留 EML 父卡,避免附件失去邮件归属或在多个状态组重复出现。 display_work_items = _display_work_items_from_current_files(work_items) needs_action: list[dict[str, Any]] = [] processing: list[dict[str, Any]] = [] completed: list[dict[str, Any]] = [] + history: list[dict[str, Any]] = [] all_rows: list[dict[str, Any]] = [] focused = str(focused_task_no or '').strip() or None recent = str(recent_task_no or '').strip() or None @@ -2938,6 +2986,8 @@ def _conversation_processing_from_work_items( needs_action.append(row) elif bucket == 'completed': completed.append(row) + elif bucket == 'history': + history.append(row) else: processing.append(row) @@ -2947,11 +2997,18 @@ def _conversation_processing_from_work_items( needs_action.sort(key=_sort_key, reverse=True) processing.sort(key=_sort_key, reverse=True) completed.sort(key=_sort_key, reverse=True) + history.sort(key=_sort_key, reverse=True) total = len(needs_action) + len(processing) + len(completed) # [STEP 2] 会话文件数是业务 PDF 去重数,不是各任务 Run 文档数的简单求和。 + # 仅以当前且仍活跃的业务文件兜底;取消/归档的历史文档不能因 + # source_summary 仍保留 document_id 而重新进入完成率分母。 + active_file_items = [ + item for item in _current_file_representatives(work_items) + if _batch_user_group(item) in {'failed', 'waiting_human', 'processing', 'completed'} + ] document_ids = { int(summary.get('document_id')) - for item in work_items + for item in active_file_items if isinstance(item, dict) and str(item.get('work_item_type') or '') == 'order_task' for child in (item.get('aggregate_children') or [item]) if isinstance(child, dict) @@ -2964,6 +3021,7 @@ def _conversation_processing_from_work_items( if document_ids else sum(int(row.get('file_count') or 0) for row in needs_action + processing + completed) ) + lifecycle_nodes = _batch_lifecycle_nodes(work_items) return { 'projection_version': 1, 'summary': { @@ -2972,7 +3030,7 @@ def _conversation_processing_from_work_items( 'processing': len(processing), 'needs_action': len(needs_action), 'completed': len(completed), - 'history': 0, + 'history': len(history), **file_counts, }, 'focused_task_no': focused, @@ -2980,7 +3038,7 @@ def _conversation_processing_from_work_items( 'needs_action': needs_action, 'processing': processing, 'completed': completed, - 'history': [], + 'history': history, 'status_groups': { 'failed': [row for row in all_rows if row.get('user_group') == 'failed'], 'waiting_human': [row for row in all_rows if row.get('user_group') == 'waiting_human'], @@ -2989,7 +3047,10 @@ def _conversation_processing_from_work_items( 'cancelled': [row for row in all_rows if row.get('user_group') == 'cancelled'], 'archived': [row for row in all_rows if row.get('user_group') == 'archived'], }, - 'four_stage_nodes': _batch_four_stage_nodes(work_items), + # 新客户端只消费 lifecycle_nodes;旧字段在一个发布周期内原样兼容,避免 + # 会话卡、批次中心和嵌入式消费者在灰度期间看到不同阶段数。 + 'lifecycle_nodes': lifecycle_nodes, + 'four_stage_nodes': lifecycle_nodes, 'unclassified_summary': _unclassified_summary(work_items), 'ui_state': _batch_ui_state_from_items(work_items), 'output_artifacts': _batch_output_artifacts(work_items), diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index 587f8a26..131c9254 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -6,7 +6,7 @@ services/shipping_notice/ui_state.py process_gate_projection(统一 Gate 用户摘要)、 order_review_workbench_projection.apply_post_ot_gate_rules。 逻辑:从 ShippingNotice DB 字段经状态机解析 checkpoint/checkpoint_kind,再统一投影 actions, - 再补充四阶段流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、 + 再补充五阶段流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、 stp_facts、progress_nodes); 若存在 ProcessExecution,所有用户动作统一由 process_gate/actions 投影; Task 即正式 OT,Gate 摘要必须套用 OT 后规则(系统等待不冒充人工待办); @@ -71,7 +71,8 @@ WORKFLOW_STEPS: tuple[dict[str, str], ...] = ( {"id": "shipping-stage-1", "code": "intake_parse", "label": "接收解析"}, {"id": "shipping-stage-2", "code": "order_review", "label": "订单复核"}, {"id": "shipping-stage-3", "code": "fulfillment_prep", "label": "通知准备"}, - {"id": "shipping-stage-4", "code": "upload_complete", "label": "通知完成"}, + {"id": "shipping-stage-4", "code": "freight_upload", "label": "货代上传"}, + {"id": "shipping-stage-5", "code": "upload_complete", "label": "通知完成"}, ) _CURRENT_STEP_INDEX_MAP: dict[str, int] = { @@ -135,7 +136,7 @@ _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = { CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"), } -# 业务人员可见的四阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。 +# 业务人员可见的五阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。 _STAGE_CHECKPOINT_CODES: dict[str, str] = { CP_PARSE_REVIEW: "order_review", CP_RSV_REQ: "order_review", @@ -148,12 +149,12 @@ _STAGE_CHECKPOINT_CODES: dict[str, str] = { CP_READY_EXPORT: "fulfillment_prep", CP_EXPORT_READY: "fulfillment_prep", CP_EXPORT_GENERATED: "fulfillment_prep", - CP_WAITING_UPLOAD: "upload_complete", + CP_WAITING_UPLOAD: "freight_upload", CP_UPLOAD_REQ: "fulfillment_prep", - CP_UPLOAD_FAILED: "upload_complete", - CP_UPLOAD_RESULT_UNKNOWN: "upload_complete", - CP_UPLOADED: "upload_complete", - CP_COMPLETED: "upload_complete", + CP_UPLOAD_FAILED: "freight_upload", + CP_UPLOAD_RESULT_UNKNOWN: "freight_upload", + CP_UPLOADED: "freight_upload", + CP_COMPLETED: "freight_upload", CP_REJECTED: "order_review", } @@ -165,11 +166,13 @@ def _task_lifecycle( gate = (process_gate or {}).get('current_blocking_gate') or (process_gate or {}).get('current_gate') legacy_stage = _STAGE_CHECKPOINT_CODES.get(str(checkpoint or '')) if legacy_stage is None: - legacy_stage = 'upload_complete' if str(checkpoint or '') in {CP_UPLOADED, CP_COMPLETED} else None + legacy_stage = 'freight_upload' if str(checkpoint or '') in {CP_UPLOADED, CP_COMPLETED} else None if legacy_stage is None: # 仅没有 Gate 时,沿用旧任务领域事实映射;不能覆盖正式 Gate。 legacy_index = _derive_current_step_index(task) - legacy_stage = ('intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete')[legacy_index] + legacy_stage = ('intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload')[legacy_index] + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + return project_lifecycle( current_gate=gate if isinstance(gate, dict) else None, blocking_reason=( @@ -180,6 +183,7 @@ def _task_lifecycle( legacy_stage=legacy_stage, # ShippingNotice 是已确认的正式 OT;生命周期入口可回看,写动作仍由 Gate 授权。 has_candidate_context=True, + verified_upload_success=has_verified_upload_success(task), ) @@ -249,7 +253,7 @@ def _unified_actions(*, process_gate: dict[str, Any] | None) -> dict[str, Any]: def _derive_current_step_index(task: ShippingNotice) -> int: """ - 根据任务领域事实推导四阶段流程当前索引。 + 根据任务领域事实推导五阶段流程当前索引。 核心逻辑:优先使用 current_step 精准定位;缺失时按复核、库存、导出、上传事实兜底。 """ @@ -295,7 +299,7 @@ def build_shipping_workflow_steps( lifecycle_stage: str | None = None, ) -> list[dict[str, str]]: """ - 构造四阶段流程状态。 + 构造五阶段流程状态。 Returns: list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。 @@ -304,13 +308,15 @@ def build_shipping_workflow_steps( (index for index, item in enumerate(LIFECYCLE_STAGES) if item['code'] == lifecycle_stage), None, ) - # 正式 Gate 已存在时,四阶段流程条必须使用同一裁决结果;旧字段只服务于历史兼容。 + # 正式 Gate 已存在时,五阶段流程条必须使用同一裁决结果;旧字段只服务于历史兼容。 current_index = lifecycle_index if lifecycle_index is not None else _derive_current_step_index(task) pending_reason = str(task.pending_human_reason or "").strip() checkpoint_value = str(checkpoint or "").strip() steps: list[dict[str, str]] = [] for index, step in enumerate(WORKFLOW_STEPS): - if str(getattr(task, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}: + # ``upload_complete`` 已由唯一成功谓词裁决。历史 Task.upload_status 不能让 + # 流程条伪装为完成,否则会与 lifecycle_entries 和批次完成率分叉。 + if lifecycle_stage == "upload_complete": status = "completed" elif index < current_index: status = "completed" @@ -664,7 +670,7 @@ def _build_stage_context( stp_facts: dict[str, Any] | None, process_gate: dict[str, Any] | None, ) -> dict[str, Any]: - """构造四阶段工作台的只读事实摘要,禁止把它作为新的业务状态机。 + """构造五阶段工作台的只读事实摘要,禁止把它作为新的业务状态机。 通知准备只消费已经冻结的订单行、库存匹配结果和 Excel Artifact;通知完成 只以真实上传 Attempt 判定成功,不能因进入 ``upload_complete`` 工作面而假装完成。 @@ -834,13 +840,17 @@ def _build_stage_context( ShippingExportArtifact.task_id == task.id, ).order_by(ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc()).all() latest_attempt = attempts[0] if attempts else None + succeeded_attempt = next( + (item for item in attempts if str(getattr(item, 'status', '') or '').lower() == 'succeeded'), + None, + ) latest_status = str(getattr(latest_attempt, 'status', '') or '').lower() upload_outcome = ( 'succeeded' if latest_status == 'succeeded' else 'failed' if latest_status in {'failed', 'timed_out'} else 'unknown' if latest_status == 'unknown' else 'running' if latest_status in {'pending', 'running'} else - 'awaiting_manual' if lifecycle_stage == 'upload_complete' else + 'awaiting_manual' if lifecycle_stage == 'freight_upload' else 'not_started' ) return { @@ -869,6 +879,15 @@ def _build_stage_context( }, 'upload': { 'outcome': upload_outcome, + # 成功工作面只能消费该不可变成功事实,而非“最近一条 Attempt”。后者可能 + # 是迟到失败或人工核对记录,不能反向定义完成证据。 + 'succeeded_attempt': ({ + 'id': succeeded_attempt.id, + 'status': succeeded_attempt.status, + 'mode': succeeded_attempt.mode, + 'freight_ref_no': succeeded_attempt.freight_ref_no, + 'finished_at': succeeded_attempt.finished_at.isoformat() if succeeded_attempt.finished_at else None, + } if succeeded_attempt is not None else None), 'latest_attempt': ({ 'id': latest_attempt.id, 'status': latest_attempt.status, @@ -930,7 +949,7 @@ def build_task_ui_state( 'enabled': True, # Artifact 已验证是下载授权的唯一来源;它直接声明展示位置, # 不依赖旧 checkpoint 或 action code 位置映射。 - 'target_surface': 'upload_complete', + 'target_surface': 'freight_upload', 'target_anchor': 'excel_artifact', }, default_kind='view') action_codes = { diff --git a/backend/app/services/shipping_notice/upload_attempt_service.py b/backend/app/services/shipping_notice/upload_attempt_service.py index fece748e..96ec4ff3 100644 --- a/backend/app/services/shipping_notice/upload_attempt_service.py +++ b/backend/app/services/shipping_notice/upload_attempt_service.py @@ -80,6 +80,39 @@ def _aggregate_task_upload_status(task: ShippingNotice) -> None: task.upload_status = 'pending' +def has_verified_upload_success(task: ShippingNotice) -> bool: + """判断任务是否具备可审计的货代上传成功事实。 + + 业务完成必须同时满足 Task 聚合、全部预约单和成功 Attempt 三层事实;历史字段、 + 单独回执号或技术流程 completed 都不能替代该判定。该函数是 UI 生命周期、批次 + 已完成分组与停止轮询共用的唯一成功谓词。 + """ + try: + from flask import has_app_context + if not has_app_context(): + return False + except Exception: # pragma: no cover - standalone/domain tests without Flask + return False + # 完成率只统计当前有效任务。已作废/归档的历史成功事实必须保留审计, + # 但不能再投影为「通知完成」或进入完成分母/分子。 + if str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in { + 'voided', 'archived', 'deleted', 'cancelled', + }: + return False + if getattr(task, 'id', None) is None or str(task.upload_status or '').strip().lower() != 'uploaded': + return False + reservations = ShippingReservation.query.filter_by(task_id=task.id).all() + if not reservations or any(row.status != 'uploaded' for row in reservations): + return False + return db.session.query(ShippingUploadAttempt.id).join( + ShippingExportArtifact, + ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id, + ).filter( + ShippingExportArtifact.task_id == task.id, + ShippingUploadAttempt.status == 'succeeded', + ).first() is not None + + def complete_attempt( attempt: ShippingUploadAttempt, *, success: bool, callback_id: str, freight_ref_no: str | None = None, error_message: str | None = None, diff --git a/backend/tests/test_shipping_auto_progress_controller_phase1.py b/backend/tests/test_shipping_auto_progress_controller_phase1.py index d65ce9de..caef0a9b 100644 --- a/backend/tests/test_shipping_auto_progress_controller_phase1.py +++ b/backend/tests/test_shipping_auto_progress_controller_phase1.py @@ -206,6 +206,62 @@ def test_contract_03_customer_auto_confirmed_runs_coordinator(app): ensure_mock.assert_called_once() +def test_unique_customer_candidate_can_be_confirmed_before_draft_validation(app): + """保存校验前,唯一 Shadow 候选必须先落为 Bill-to 已确认事实。""" + from app.services.shipping_notice import order_review_auto_progress_coordinator as coord + + case = SimpleNamespace(case_no='SORC-UNIQUE-CUSTOMER', candidate_id=31) + with patch.object( + coord, + '_customer_step_for_case', + return_value=('auto_confirmed', {'customer_id': 5555}), + ) as step_mock: + result = coord.auto_confirm_unique_customer_for_review_case( + case=case, + trigger='draft_validated', + ) + + step_mock.assert_called_once_with(case=case, trigger='draft_validated') + assert result == {'status': 'auto_confirmed', 'customer_id': 5555} + + +def test_unique_customer_auto_confirmation_defers_commit_to_resume_transaction(app): + """唯一客户自动确认只 flush,不能在 Draft 校验前单独提交事务。""" + from app.services.shipping_notice import order_review_auto_progress_coordinator as coord + + case = SimpleNamespace(case_no='SORC-UNIQUE-COMMIT', candidate_id=31) + candidate = SimpleNamespace(id=31) + shadow = SimpleNamespace(status='unique_candidate', top_customer_id=5555) + extraction = SimpleNamespace(id=101) + shadow_model = SimpleNamespace( + query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: shadow)), + ) + match_model = SimpleNamespace( + query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=1))), + ) + with patch.object(coord.db.session, 'get', return_value=candidate), patch.object( + coord, + 'ShippingCustomerShadowResolution', + shadow_model, + ), patch.object(coord, 'resolve_review_case_customer_resolved', return_value=False), patch.object( + coord, + '_resolve_extraction_for_case', + return_value=extraction, + ), patch.object( + coord, + 'ShippingOrderCustomerMatch', + match_model, + ), patch.object(coord, 'confirm_order_customer_match') as confirm_mock, patch.object( + coord, + 'record_fulfillment_audit', + ): + status, metadata = coord._customer_step_for_case(case=case, trigger='draft_validated') + + assert status == 'auto_confirmed' + assert metadata == {'customer_id': 5555, 'extraction_id': 101} + assert confirm_mock.call_args.kwargs['commit'] is False + + def test_contract_04_sweeper_does_not_enqueue_stp_after_failure(app): """合同 4:恢复扫描只收敛超时事实,不能在失败后自动补建 STP Job。""" from app.services.shipping_notice import shipping_recovery_sweeper_service as sw diff --git a/backend/tests/test_shipping_coordinate_table_reconstruction.py b/backend/tests/test_shipping_coordinate_table_reconstruction.py index 450b433a..dd10b910 100644 --- a/backend/tests/test_shipping_coordinate_table_reconstruction.py +++ b/backend/tests/test_shipping_coordinate_table_reconstruction.py @@ -277,6 +277,53 @@ def test_coordinate_profile_row_layout_repeats_across_the_table(): ] +def test_coordinate_profile_rows_apply_selected_anchor_frame_translation_to_all_regions(): + """锚点框架选中的平移必须同时投影主表、物理行和每个字段区。""" + baseline_layout = { + 'table_region': {'x0': 0, 'y0': .20, 'x1': 1, 'y1': .40}, + 'line_layouts': [{ + 'layout_id': 'main', 'row_offset': 0, + 'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': .35}, + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .25, 'x1': .25, 'y1': .35}}, + {'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .25, 'x1': .55, 'y1': .35}}, + {'field_code': 'qty', 'region': {'x0': .55, 'y0': .25, 'x1': .75, 'y1': .35}}, + {'field_code': 'unit_price', 'region': {'x0': .75, 'y0': .25, 'x1': 1, 'y1': .35}}, + ], + }], + } + shifted = reconstruct_coordinate_profile_rows( + characters=_glyphs([('00010', 10), ('PART-A', 65), ('2', 135), ('10.50', 175)]), + table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100}, + coordinate_transform={'status': 'applied', 'translate_x': 0, 'translate_y': .20}, + **baseline_layout, + ) + + # Without the selected transform these glyphs sit outside all baseline Y regions. + assert shifted[0].fields == { + 'customer_po_line_no': '00010', 'customer_part_number': 'PART-A', + 'qty': '2', 'unit_price': '10.50', + } + + +def test_coordinate_profile_rows_reject_invalid_selected_anchor_frame_transform(): + """非 matcher 认可的变换不得悄悄回退为绝对坐标取值。""" + kwargs = { + 'characters': _glyphs([('00010', 10), ('PART-A', 65)]), + 'table_bbox': {'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100}, + 'table_region': {'x0': 0, 'y0': .20, 'x1': 1, 'y1': .40}, + 'line_layouts': [{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .20, 'x1': 1, 'y1': .40}, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .20, 'x1': .25, 'y1': .40}}, + {'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .20, 'x1': 1, 'y1': .40}}, + ]}], + } + + assert reconstruct_coordinate_profile_rows(**kwargs, coordinate_transform={'status': 'pending'}) == [] + assert reconstruct_coordinate_profile_rows(**kwargs, coordinate_transform={ + 'status': 'applied', 'translate_x': 0, 'translate_y': .9, + }) == [] + + def test_coordinate_profile_preview_can_expose_unanchored_main_row_for_review(): """仅预览模式在缺少有效起行值时保留字段证据,正式重建仍严格过滤。""" kwargs = { diff --git a/backend/tests/test_shipping_document_layout_lifecycle.py b/backend/tests/test_shipping_document_layout_lifecycle.py index 0feb87eb..c6f9719a 100644 --- a/backend/tests/test_shipping_document_layout_lifecycle.py +++ b/backend/tests/test_shipping_document_layout_lifecycle.py @@ -504,6 +504,8 @@ def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverab assert pending.payload_json['layout_candidate'] == snapshot['layout_candidate'] assert 'tables' not in pending.payload_json['coordinate_evidence'] assert 'page_glyphs' not in pending.payload_json['coordinate_evidence'] + assert pending.payload_json['matching_features']['version'] == 'v1' + assert pending.payload_json['matching_features']['tables'][0]['bbox'] == [0.01, 0.01, 0.3, 0.2] assert 'shipping_document_layout_page_glyphs_compacted' in pending.issues_json assert 'shipping_document_layout_table_glyphs_compacted' in pending.issues_json assert 'shipping_document_layout_coordinate_evidence_on_demand' in pending.issues_json @@ -569,6 +571,36 @@ def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_map assert 'tables' not in restored['coordinate_evidence'] +def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app): + """冻结快照缺坐标而当前 Layout 已有坐标时,必须返回合并后的运行期证据。""" + with app.app_context(): + document = _document() + current = record_inline_layout_snapshot(document, { + **_snapshot(), + 'coordinate_evidence': { + 'pages': {'1': {'width': 100, 'height': 200}}, + 'page_glyphs': {'1': [{'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]}, + 'tables': {'table-1': [{'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]}, + 'sources': {'pages': {'1': 'pdf_coordinate'}}, + }, + }) + db.session.flush() + document.current_layout_version = current + frozen_layout = { + **_snapshot(), + 'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 200}}], + 'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}}, + } + + restored = ensure_on_demand_coordinate_evidence( + document=document, layout=frozen_layout, page_nos={1}, + ) + + # 关键断言:不得因当前版本坐标存在而错误返回旧冻结快照。 + assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'H' + assert restored['coordinate_evidence']['tables']['table-1'][0]['text'] == 'H' + + def test_on_demand_evidence_restores_every_table_on_the_same_page(app, monkeypatch): """同一页存在多张物理表时,每个 table_id 都必须获得独立坐标字符证据。""" with app.app_context(): diff --git a/backend/tests/test_shipping_generic_order_gate.py b/backend/tests/test_shipping_generic_order_gate.py index 254183d8..9c2b72ec 100644 --- a/backend/tests/test_shipping_generic_order_gate.py +++ b/backend/tests/test_shipping_generic_order_gate.py @@ -442,6 +442,42 @@ def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch): assert seen['characters'][0]['text'] == 'Terms' +def test_coordinate_profile_rows_forward_selected_match_transform_without_recomputing(monkeypatch): + """工作流只能转交共同 matcher 的已选变换,不能由表格或订单值重新推断。""" + region = SimpleNamespace( + page_scope='all_pages', page_no=None, line_layouts=[SimpleNamespace(model_dump=lambda: {})], + region=SimpleNamespace(model_dump=lambda: {'x0': 0.1, 'y0': 0.2, 'x1': 0.9, 'y1': 0.5}), + termination_rules=[], exclusion_regions=[], continuation_rule=SimpleNamespace(allow_cross_page=False), + line_start_field_code=None, row_reconstruction_mode='fixed_subrows', region_id='lines', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile', + lambda *_args, **_kwargs: SimpleNamespace(table_regions=[region]), + ) + seen = {} + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workflow.reconstruct_coordinate_profile_rows', + lambda **kwargs: (seen.update(coordinate_transform=kwargs.get('coordinate_transform')) or []), + ) + transform = { + 'status': 'applied', 'translate_x': 0.0, 'translate_y': .03, + 'anchor_ids': ['title'], 'reason_codes': [], + } + + rows = _coordinate_profile_rows( + raw_profile={}, raw_table={'table_id': 'order-table', 'page_no': 1}, + layout={'coordinate_evidence': { + 'pages': {'1': {'width': 200, 'height': 100}}, + 'page_glyphs': {'1': [{'text': 'x', 'bbox': {'x0': 30, 'y0': 30, 'x1': 31, 'y1': 31}}]}, + 'tables': {}, + }}, + contract=SimpleNamespace(fields_by_code={}), schema_fields={}, coordinate_transform=transform, + ) + + assert rows == [] + assert seen['coordinate_transform'] == transform + + def test_fixed_subrows_use_template_region_page_glyphs_beyond_mineru_bbox(monkeypatch): """固定子行以模板表区为权威,须读取 MinerU 框外续行并跳过同页无关表。""" region = SimpleNamespace( diff --git a/backend/tests/test_shipping_notice_ui_state.py b/backend/tests/test_shipping_notice_ui_state.py index 3559f5d5..7337d045 100644 --- a/backend/tests/test_shipping_notice_ui_state.py +++ b/backend/tests/test_shipping_notice_ui_state.py @@ -77,18 +77,18 @@ def test_unified_actions_preserve_backend_surface_without_action_code_fallback() "primary_action": { "code": "mark_manual_uploaded", "label": "登记人工上传", - "target_surface": "upload_complete", + "target_surface": "freight_upload", }, "action_presentation": [{ "code": "download_excel", "label": "下载发货 Excel", - "target_surface": "upload_complete", + "target_surface": "freight_upload", "target_anchor": "excel_artifact", }], }, ) - assert state["primary"]["target_surface"] == "upload_complete" - assert state["secondary"][0]["target_surface"] == "upload_complete" + assert state["primary"]["target_surface"] == "freight_upload" + assert state["secondary"][0]["target_surface"] == "freight_upload" assert state["secondary"][0]["target_anchor"] == "excel_artifact" @@ -121,7 +121,7 @@ def test_task_ui_state_stage_context_is_opt_in(app) -> None: assert "stage_context" in detailed_state -def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(app) -> None: +def test_build_task_ui_state_exposes_five_business_stages_and_unified_actions(app) -> None: """没有 Gate 的旧 checkpoint 仅表达状态,不能再直接产生可写 UI 动作。""" with app.app_context(): task = ShippingNotice( @@ -133,13 +133,13 @@ def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(ap state = build_task_ui_state(task) assert state["stage"]["code"] == "order_review" assert state["stage"]["index"] == 2 - assert state["stage"]["total"] == 4 + assert state["stage"]["total"] == 5 assert state["actions"]["primary"] is None assert state["actions"]["secondary"] == [] def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> None: - """正式工作台的四个入口必须由后端下发,页面不能按阶段顺序自行生成。""" + """正式工作台的五个入口必须由后端下发,页面不能按阶段顺序自行生成。""" with app.app_context(): task = ShippingNotice( task_no="SN-UI-LIFECYCLE-ENTRIES", @@ -153,6 +153,7 @@ def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> Non {"code": "intake_parse", "state": "available", "target_surface": "order_lifecycle_workbench"}, {"code": "order_review", "state": "current", "target_surface": "order_lifecycle_workbench"}, {"code": "fulfillment_prep", "state": "unavailable", "target_surface": "order_lifecycle_workbench"}, + {"code": "freight_upload", "state": "unavailable", "target_surface": "order_lifecycle_workbench"}, {"code": "upload_complete", "state": "unavailable", "target_surface": "order_lifecycle_workbench"}, ] @@ -213,7 +214,7 @@ def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None: def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> None: - """正式人工上传 Gate 必须裁决为通知完成,不受旧复核字段影响。""" + """正式人工上传 Gate 必须停留货代上传,不受旧复核字段影响。""" with app.app_context(): from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version @@ -235,16 +236,16 @@ def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> No state = build_task_ui_state(task) - assert state['lifecycle_stage'] == 'upload_complete' + assert state['lifecycle_stage'] == 'freight_upload' assert state['lifecycle_authority'] == 'process_gate' - assert state['stage']['code'] == 'upload_complete' + assert state['stage']['code'] == 'freight_upload' assert [entry['state'] for entry in state['lifecycle_entries']] == [ - 'available', 'available', 'available', 'current', + 'available', 'available', 'available', 'current', 'unavailable', ] def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(app) -> None: - """库存匹配/上传结果只映射四个业务阶段。""" + """库存匹配与无证据历史上传分别映射通知准备和货代上传。""" with app.app_context(): fulfillment = ShippingNotice( task_no="SN-UI-FULFILLMENT", @@ -259,7 +260,7 @@ def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages( ) assert build_task_ui_state(fulfillment)["stage"]["code"] == "fulfillment_prep" upload_state = build_task_ui_state(upload, include_stage_context=True) - assert upload_state["stage"]["code"] == "upload_complete" + assert upload_state["stage"]["code"] == "freight_upload" # 旧 Task 字段只能决定工作面;没有可追溯 UploadAttempt 时不得显示上传成功。 assert upload_state["stage_context"]["upload"]["outcome"] == "awaiting_manual" diff --git a/backend/tests/test_shipping_order_extraction_runs.py b/backend/tests/test_shipping_order_extraction_runs.py index a732e56b..a8c96b01 100644 --- a/backend/tests/test_shipping_order_extraction_runs.py +++ b/backend/tests/test_shipping_order_extraction_runs.py @@ -64,6 +64,7 @@ from app.jobs.queue import fail_job from app.services.shipping_notice.order_extraction import ( submit_order_extraction_run_result, submit_order_extraction_unit_result, + reconcile_review_case_after_unit, ) from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit from app.services.shipping_notice.order_extraction_plan import ( @@ -2925,6 +2926,23 @@ def test_reparse_unit_submission_accepts_orphaned_consumed_intake(app): assert ShippingOrderCandidate.query.filter_by(order_extraction_run_id=replacement.id).count() == 0 +def test_unit_replay_reconciles_review_case_after_ensure(monkeypatch): + """Unit 幂等回放创建/恢复 Case 后必须进入统一自动校验协调器。""" + calls = [] + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_service.ensure_review_case_for_unit', + lambda **kwargs: calls.append(('ensure', kwargs)) or object(), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_stp_auto_create_service.maybe_stp_auto_create_for_run', + lambda **kwargs: calls.append(('reconcile', kwargs)) or [{'validate_status': 'validated'}], + ) + + reconcile_review_case_after_unit(run='run', unit='unit') + + assert [item[0] for item in calls] == ['ensure', 'reconcile'] + + def test_unit_submission_survives_deleted_chat_session(app): """后台 Run 不得因 UI 会话历史已清理而回滚 Candidate/Review Case 持久化。""" with app.app_context(): diff --git a/backend/tests/test_shipping_order_field_extraction.py b/backend/tests/test_shipping_order_field_extraction.py index 83d10717..97393150 100644 --- a/backend/tests/test_shipping_order_field_extraction.py +++ b/backend/tests/test_shipping_order_field_extraction.py @@ -140,6 +140,27 @@ def test_anchor_relative_value_is_confirmed_with_native_page_coordinates(): assert result.source == 'pdf_coordinate' +def test_anchor_frame_transform_moves_order_number_anchor_and_value_together(): + """共同 matcher 的纵向平移必须同时投影订单号标签和值框。""" + profile = _profile(layout={ + 'anchor': { + 'anchor_id': 'po', 'text': 'PO NO', + 'region': {'x0': .05, 'y0': .1, 'x1': .25, 'y1': .14}, + 'position_locked': True, + }, + 'absolute_value_region': {'x0': .2, 'y0': .1, 'x1': .9, 'y1': .14}, + 'value_mode': 'right_of_anchor', + }) + result = extract_order_fields( + profile=profile, + schema_fields=_schema(), + coordinate_evidence=_evidence(pages={'1': _glyphs(('PO NO 45001', 20, 40))}), + coordinate_transform={'status': 'applied', 'translate_x': 0, 'translate_y': .1}, + )[0] + assert result.status == 'confirmed' + assert result.value == '45001' + + def test_right_of_anchor_keeps_saved_value_width_when_actual_anchor_text_is_narrower(): """值框只命中 USD 首字符时,应补齐同一连续词而非误报未读取到值。""" profile = _profile(layout={ diff --git a/backend/tests/test_shipping_order_profile_matcher.py b/backend/tests/test_shipping_order_profile_matcher.py index 21d654ac..6657fb5d 100644 --- a/backend/tests/test_shipping_order_profile_matcher.py +++ b/backend/tests/test_shipping_order_profile_matcher.py @@ -86,6 +86,124 @@ def _with_signature(profile: dict, layout: dict) -> dict: return enriched +def _anchor_frame_profile(code: str = 'PO_ANCHOR_FRAME') -> dict: + """构造声明锚点坐标框架的最小 Profile,供平移门禁回归使用。""" + profile = _profile(code) + profile['definition']['coordinate_model'] = { + 'type': 'anchor_frame', + 'anchors': [{ + 'anchor_id': 'title', 'text': 'PURCHASE ORDER', 'match_mode': 'exact', + 'minimum_evidence_level': 'coordinate', + 'region': {'x0': .185, 'y0': .05, 'x1': .26, 'y1': .0857142857}, + }], + 'max_translate_x': .02, + 'max_translate_y': .05, + } + return profile + + +def _layout_with_frame_anchor(*, anchor_y: float = .05, table_y: float = .25) -> dict: + """构造标题与主表同步平移的坐标 Layout,模拟正文高度改变而非结构变更。""" + layout = _layout(bbox={'x0': .05, 'y0': table_y, 'x1': .95, 'y1': .95}) + text = 'PURCHASE ORDER' + anchor_glyphs = [ + { + 'text': char, + 'bbox': {'x0': 10 + index * 5, 'y0': anchor_y * 280, 'x1': 14 + index * 5, 'y1': anchor_y * 280 + 10}, + 'boundary_before': 'space' if index and text[index - 1] == ' ' else 'none', + } + for index, char in enumerate(text) + if char != ' ' + ] + header = layout['coordinate_evidence']['tables']['table-1'] + for glyph in header: + glyph['bbox']['y0'] += (table_y - .25) * 280 + glyph['bbox']['y1'] += (table_y - .25) * 280 + plant_text = 'PLANT NAME: FACTORY A' + plant_glyphs = [ + {'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}} + for index, char in enumerate(plant_text) + ] + layout['coordinate_evidence']['page_glyphs']['1'] = [ + *plant_glyphs, + *anchor_glyphs, + *header, + ] + return layout + + +def test_anchor_frame_matches_bounded_vertical_translation_without_changing_legacy_profiles(): + """同一结构整体下移时仅启用锚点框架的 Profile 可命中,legacy 仍按原规则失败关闭。""" + baseline = _layout_with_frame_anchor() + shifted = _layout_with_frame_anchor(anchor_y=.095, table_y=.295) + framed = _with_signature(_anchor_frame_profile(), baseline) + legacy = _with_signature(_profile('PO_LEGACY'), baseline) + + framed_result = match_frozen_coordinate_profiles(profiles=[framed], layout=shifted) + legacy_result = match_frozen_coordinate_profiles(profiles=[legacy], layout=shifted) + + # 关键断言:变换来自唯一静态锚点,并且 legacy Profile 未因新能力改变行为。 + assert framed_result.status == 'unique_match' + assert framed_result.candidates[0].coordinate_transform == { + 'status': 'applied', 'translate_x': 0.0, 'translate_y': 0.045, + 'anchor_ids': ['title'], 'reason_codes': [], + } + assert legacy_result.candidates[0].coordinate_transform is None + + +def test_anchor_frame_fails_closed_when_anchor_is_missing_ambiguous_or_out_of_range(): + """锚点框架不得因缺锚、重锚或超界平移降级猜测,均须成为模板硬失败。""" + baseline = _layout_with_frame_anchor() + profile = _with_signature(_anchor_frame_profile(), baseline) + missing = _layout() + ambiguous = _layout_with_frame_anchor(anchor_y=.08, table_y=.28) + ambiguous['coordinate_evidence']['page_glyphs']['1'].extend( + _layout_with_frame_anchor(anchor_y=.115)['coordinate_evidence']['page_glyphs']['1'][21:34], + ) + out_of_range = _layout_with_frame_anchor(anchor_y=.14, table_y=.34) + + for layout, reason in ( + (missing, 'profile_anchor_frame_anchor_missing'), + (ambiguous, 'profile_anchor_frame_anchor_ambiguous'), + (out_of_range, 'profile_anchor_frame_transform_out_of_range'), + ): + result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout) + assert result.candidates[0].hard_match is False + assert reason in result.candidates[0].reason_codes + + +def test_anchor_frame_matches_static_anchor_embedded_in_a_pdf_line(): + """PDF 原生字符常把多个标签拼成一行;锚点应返回自身字符框而非整行框。""" + baseline = _layout_with_frame_anchor() + title = baseline['coordinate_evidence']['page_glyphs']['1'][21:34] + prefix = [{'text': 'X', 'bbox': {'x0': 0, 'y0': 14, 'x1': 5, 'y1': 24}}] + suffix = [{'text': 'X', 'bbox': {'x0': 80, 'y0': 14, 'x1': 85, 'y1': 24}}] + for glyph in title: + glyph['bbox']['y0'] += 10 + glyph['bbox']['y1'] += 10 + prefix[0]['bbox']['y0'] += 10 + prefix[0]['bbox']['y1'] += 10 + suffix[0]['bbox']['y0'] += 10 + suffix[0]['bbox']['y1'] += 10 + baseline['coordinate_evidence']['page_glyphs']['1'] = [ + *baseline['coordinate_evidence']['page_glyphs']['1'][:21], + *prefix, + *title, + *suffix, + *baseline['coordinate_evidence']['page_glyphs']['1'][34:], + ] + profile = _with_signature(_anchor_frame_profile(), baseline) + + result = match_frozen_coordinate_profiles(profiles=[profile], layout=baseline) + + # 关键断言:行内静态锚点仍唯一命中,且自身 bbox 不受前后文本扩大影响。 + assert result.status == 'unique_match' + assert result.candidates[0].coordinate_transform == { + 'status': 'applied', 'translate_x': 0.0, 'translate_y': 0.035714, + 'anchor_ids': ['title'], 'reason_codes': [], + } + + def test_profile_matcher_uniquely_matches_label_value_anchor_not_dynamic_order_values(): """工厂标签和值关系不受订单号、料号、数量变化影响。""" layout = _layout('PLANT NAME: FACTORY A TYPE: UM17 PO-999 QTY 999 PART-X') @@ -120,6 +238,37 @@ def test_profile_matcher_enforces_required_anchor_and_evidence_availability(): assert match_frozen_coordinate_profiles(profiles=[profile], layout={'tables': []}).status == 'evidence_insufficient' +def test_profile_matcher_uses_persisted_lightweight_features_when_glyphs_are_compacted(): + """字符坐标被压缩后,模板匹配仍须使用压缩前持久化的结构特征。""" + complete_layout = _layout() + profile = _profile('PO_A') + profile['definition']['document_match']['required_anchors'] = [] + profile = _with_signature(profile, complete_layout) + compacted_layout = { + 'tables': complete_layout['tables'], + 'coordinate_evidence': {'pages': complete_layout['coordinate_evidence']['pages']}, + 'matching_features': { + 'version': 'shipping-layout-matching-features.v1', + 'page_structure': {'aspect_ratio': 200 / 280, 'page_count': 1, 'table_count': 1}, + 'tables': [{ + 'table_id': 'table-1', 'page_no': 1, + 'bbox': [0.05, 0.25, 0.95, 0.95], + 'header_tokens': ['item', 'no', 'qty'], + 'column_centers': [0.1225, 0.2825, 0.4225], + 'column_width_ratios': [0.1611, 0.0722, 0.1167], + }], + 'static_text_centers': {}, + }, + } + + result = match_frozen_coordinate_profiles(profiles=[profile], layout=compacted_layout) + + assert result.status == 'unique_match' + candidate = result.candidates[0] + assert candidate.dimension_states['header_semantic_position'] == 'matched' + assert candidate.dimension_states['column_topology'] == 'matched' + + def test_profile_matcher_reports_only_missing_anchor_identifiers(): """缺失锚点诊断只能保存模板 anchor_id,绝不保存当前文档文本或坐标。""" profile = _profile('PO_A') diff --git a/backend/tests/test_shipping_order_review_resume_service.py b/backend/tests/test_shipping_order_review_resume_service.py index 5cf21b10..61dbe894 100644 --- a/backend/tests/test_shipping_order_review_resume_service.py +++ b/backend/tests/test_shipping_order_review_resume_service.py @@ -101,3 +101,78 @@ def test_resume_waiting_manual_confirm_when_auto_gate_false(monkeypatch): assert result['auto_gate_allowed'] is False assert result['task_created'] is False assert case.status == 'ready' + + +def test_resume_auto_confirms_unique_customer_before_validating(monkeypatch): + """保存校验时必须先确认唯一客户候选,再执行 Draft 校验。""" + case = _case(can_build=True, can_auto_create=False, validation_status='ready') + calls = [] + monkeypatch.setattr(svc, '_reload_case', lambda **_kw: case) + monkeypatch.setattr(svc, '_persist_candidate_qualification', lambda _c: None) + monkeypatch.setattr(svc, '_invalidate_downstream_if_needed', lambda **_kw: []) + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_auto_progress_coordinator.auto_confirm_unique_customer_for_review_case', + lambda **_kw: calls.append('customer') or {'status': 'auto_confirmed', 'customer_id': 5555}, + ) + monkeypatch.setattr( + svc, + 'validate_draft', + lambda **_kw: calls.append('validate') or {'status': 'ready'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit', + lambda **_kw: None, + ) + monkeypatch.setattr(svc.db.session, 'flush', lambda: None) + monkeypatch.setattr(svc.db.session, 'commit', lambda: None) + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_projection.serialize_review_case', + lambda _c: {'case_no': case.case_no}, + ) + + svc.resume_after_review_change( + user_id=7, + case_no=case.case_no, + trigger='draft_validated', + skip_validate=False, + ) + + assert calls == ['customer', 'validate'] + + +def test_validate_draft_api_delegates_versioned_validation_to_resume_coordinator(app, monkeypatch): + """保存校验 API 不可绕过协调器,必须传递乐观锁版本。""" + from app.api.workspace import shipping_notice as api + from app.services.shipping_notice import order_review_resume_service + + user = SimpleNamespace(id=7) + calls = [] + + def fake_resume(**kwargs): + calls.append(kwargs) + return { + 'case': {'case_no': kwargs['case_no']}, + 'outcome': 'blocked', + 'gate_recalculated': True, + } + + monkeypatch.setattr(api, '_require_user', lambda: user) + monkeypatch.setattr(order_review_resume_service, 'resume_after_review_change', fake_resume) + with app.test_request_context( + '/shipping-notice/order-review-cases/CASE-API/draft/validate', + method='POST', + json={'expected_draft_version': 12}, + ): + response, status = api.workspace_validate_shipping_order_review_draft('CASE-API') + + assert status == 200 + assert response.get_json()['data']['case'] == {'case_no': 'CASE-API'} + assert calls == [{ + 'user_id': 7, + 'case_no': 'CASE-API', + 'trigger': 'draft_validated', + 'change_type': None, + 'skip_validate': False, + 'allow_auto_create': True, + 'expected_draft_version': 12, + }] diff --git a/backend/tests/test_shipping_order_review_service.py b/backend/tests/test_shipping_order_review_service.py index bc475d68..7afba6b2 100644 --- a/backend/tests/test_shipping_order_review_service.py +++ b/backend/tests/test_shipping_order_review_service.py @@ -401,6 +401,32 @@ def _materialized_run(*, user, agent, session, intake): return run +def test_review_case_summary_exposes_only_failed_intake_retry_authorization(app): + """当前阶段卡只消费服务端 parse_failed 的 SNI 编号与 retry_parse 授权。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-INTAKE-RETRY') + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + case = ensure_run_review_cases(run=run)[0] + intake.parse_status = 'parse_failed' + db.session.commit() + + failed = serialize_review_run(run)['items'][0] + # 关键断言:失败节点提供原 SNI 和 retry_parse;不需要重新上传或前端猜测。 + assert failed['intake_no'] == intake.intake_no + assert failed['available_actions'] == ['retry_parse'] + + intake.parse_status = 'parsing' + db.session.commit() + parsing = serialize_review_run(run)['items'][0] + # 关键断言:运行中只能等待 Worker 超时回收,不能显示冲突重试动作。 + assert parsing['available_actions'] == [] + + intake.parse_status = 'cancelled' + db.session.commit() + cancelled = serialize_review_run(run)['items'][0] + assert cancelled['available_actions'] == [] + + def _seed_review_inventory_routing_catch_all(*, reservation_field_id: str = 'reservation-id') -> None: """ 为 Review 就绪路径测试注入行级 catch-all 库存源规则。 @@ -1768,6 +1794,63 @@ def test_document_reparse_supersedes_only_after_success_and_rejects_final_case(a raise AssertionError('superseded case must not be reparsed') +def test_successful_document_reparse_reconciles_only_activated_replacement_case(app, monkeypatch): + """PDF 重识别成功切换当前版本后,必须补触发新版 Case 的统一自动推进。""" + with app.app_context(): + from app.services.shipping_notice import order_review_disposition_service as disposition + + user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-AUTO-PROGRESS') + source = _materialized_run(user=user, agent=agent, session=session, intake=intake) + source_case = ensure_run_review_cases(run=source)[0] + transition_order_extraction_run(source, target_status='processing') + transition_order_extraction_run(source, target_status='review_required', result={}) + replacement, _ = reparse_case_document(user_id=user.id, case_no=source_case.case_no, reason='other') + ensure_order_extraction_plan(replacement) + for unit in replacement.extraction_plan.units: + unit.status = 'candidate_ready' + replacement_case = ensure_run_review_cases(run=replacement)[0] + reconciled = [] + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_auto_progress_coordinator.' + 'reconcile_single_case_for_auto_progress', + lambda **kwargs: reconciled.append(kwargs) or {'enqueue_status': 'queued'}, + ) + + finalize_document_reparse(run=replacement, succeeded=True) + + assert reconciled == [{ + 'case': replacement_case, + 'trigger': 'document_reparse_succeeded', + 'refresh_validation': True, + }] + + +def test_document_reparse_does_not_reconcile_when_stream_activation_is_rejected(app, monkeypatch): + """Stream 冲突或已确认旧版本拒绝切换时,不得推进晚到的新版草稿。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-AUTO-CONFLICT') + source = _materialized_run(user=user, agent=agent, session=session, intake=intake) + source_case = ensure_run_review_cases(run=source)[0] + mark_review_stream_confirmed(case=source_case) + transition_order_extraction_run(source, target_status='processing') + transition_order_extraction_run(source, target_status='review_required', result={}) + replacement, _ = reparse_case_document(user_id=user.id, case_no=source_case.case_no, reason='other') + ensure_order_extraction_plan(replacement) + for unit in replacement.extraction_plan.units: + unit.status = 'candidate_ready' + ensure_run_review_cases(run=replacement) + reconciled = [] + monkeypatch.setattr( + 'app.services.shipping_notice.order_review_auto_progress_coordinator.' + 'reconcile_single_case_for_auto_progress', + lambda **kwargs: reconciled.append(kwargs), + ) + + finalize_document_reparse(run=replacement, succeeded=True) + + assert reconciled == [] + + def test_run_auto_progress_ignores_legacy_open_case_that_is_not_stream_current(app): """Run 级协调只能处理文件 Stream 当前 Case,不能重启残留旧版本。""" with app.app_context(): @@ -2456,3 +2539,17 @@ def test_assert_exact_duplicate_excludes_same_case_wave_tasks(app): ) assert exc.value.code == 'SHIPPING.NOTICE_EXACT_DUPLICATE' del agent, session, intake +def test_unvalidated_draft_is_not_projected_as_build_blocked(app): + """未执行校验的 Draft 必须保持 not_validated,不能伪造成 can_build=false。""" + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='UNVALIDATED-PROJECTION') + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + unit = run.extraction_plan.units[0] + case = ensure_review_case_for_unit(run=run, unit=unit) + db.session.flush() + + detail = serialize_review_case(case) + eligibility = detail['draft']['build_eligibility'] + + assert eligibility['status'] == 'not_validated' + assert eligibility['can_build'] is None diff --git a/backend/tests/test_shipping_process_gate_contract.py b/backend/tests/test_shipping_process_gate_contract.py index c6f36258..0d7249e2 100644 --- a/backend/tests/test_shipping_process_gate_contract.py +++ b/backend/tests/test_shipping_process_gate_contract.py @@ -106,13 +106,13 @@ def test_fulfillment_action_presentation_declares_lifecycle_surface(): )['target_surface'] == 'fulfillment_prep' assert action_presentation( 'retry_freight_upload_rpa', gate_code='freight_upload_rpa', - )['target_surface'] == 'upload_complete' + )['target_surface'] == 'freight_upload' assert action_presentation( 'regenerate_manual_upload_todo', gate_code='manual_upload_handoff', - )['target_surface'] == 'upload_complete' + )['target_surface'] == 'freight_upload' assert action_presentation( 'mark_manual_uploaded', gate_code='manual_upload_handoff', - )['target_surface'] == 'upload_complete' + )['target_surface'] == 'freight_upload' def test_manual_upload_handoff_authorizes_excel_regeneration_at_artifact_anchor(): @@ -558,7 +558,7 @@ def test_manual_upload_handoff_projects_evidence_confirmation_as_primary_action( 'mark_manual_uploaded', 'retry_freight_upload_rpa', ] - assert summary['primary_action']['target_surface'] == 'upload_complete' + assert summary['primary_action']['target_surface'] == 'freight_upload' assert summary['primary_action']['target_anchor'] == 'manual_upload' diff --git a/backend/tests/test_shipping_processing_projection_invariants.py b/backend/tests/test_shipping_processing_projection_invariants.py index a081089d..0d50e070 100644 --- a/backend/tests/test_shipping_processing_projection_invariants.py +++ b/backend/tests/test_shipping_processing_projection_invariants.py @@ -223,9 +223,11 @@ def test_map_notice_to_processing_status_stage_domain_mapping(): ) uploaded = SimpleNamespace( + id=None, current_step='', upload_status='uploaded', export_file_path=None, ) - assert map_notice_to_processing_status_stage(uploaded) == ('completed', 'completed') + # 历史聚合字段没有预约单与成功 Attempt,不得直接进入完成。 + assert map_notice_to_processing_status_stage(uploaded) == ('automating', 'freight_uploading') waiting = SimpleNamespace( current_step='', upload_status='pending', export_file_path='/x.xlsx', diff --git a/backend/tests/test_shipping_processing_projection_stage4.py b/backend/tests/test_shipping_processing_projection_stage4.py index a098e04f..a8ff5fbe 100644 --- a/backend/tests/test_shipping_processing_projection_stage4.py +++ b/backend/tests/test_shipping_processing_projection_stage4.py @@ -103,14 +103,14 @@ def test_map_run_status_to_processing_status() -> None: ('inventory_snapshots_ready', 'fulfillment_prep'), ('inventory_matched', 'fulfillment_prep'), ('excel_generated', 'fulfillment_prep'), - ('upload_receipt_recorded', 'upload_complete'), + ('upload_receipt_recorded', 'freight_upload'), ], ) -def test_batch_four_stage_nodes_maps_auto_progress_gate_stages( +def test_batch_lifecycle_nodes_maps_auto_progress_gate_stages( stage: str, expected_lifecycle_stage: str, ) -> None: - """自动推进 Gate 的真实阶段码必须归入对应四阶段,不能回退到接收解析。""" + """自动推进 Gate 的真实阶段码必须归入对应五阶段,不能回退到接收解析。""" nodes = _batch_four_stage_nodes([{ 'stage': stage, 'user_stage': stage, @@ -127,7 +127,7 @@ def test_batch_four_stage_nodes_maps_auto_progress_gate_stages( ('item', 'expected_lifecycle_stage'), [ ({'user_stage': 'inventory_match'}, 'fulfillment_prep'), - ({'user_stage': 'freight_upload'}, 'upload_complete'), + ({'user_stage': 'freight_upload'}, 'freight_upload'), ({'user_stage': 'customer_resolving'}, 'order_review'), ({'user_stage': 'duplicate_checking'}, 'order_review'), ({'user_stage': 'waiting_human_review'}, 'order_review'), @@ -142,11 +142,11 @@ def test_batch_four_stage_nodes_maps_auto_progress_gate_stages( ({'blocking_reason': {'code': 'generic_extraction_disabled'}}, 'intake_parse'), ], ) -def test_batch_four_stage_nodes_prefers_formal_gate_and_maps_legacy_stage_aliases( +def test_batch_lifecycle_nodes_prefers_formal_gate_and_maps_legacy_stage_aliases( item: dict[str, object], expected_lifecycle_stage: str, ) -> None: - """批次四阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。""" + """批次五阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。""" nodes = _batch_four_stage_nodes([{ **item, 'status': 'waiting_human', @@ -177,6 +177,7 @@ def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> N {'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'order_review', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'fulfillment_prep', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'}, + {'code': 'freight_upload', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, ] assert fulfillment_state['primary_action']['execution_mode'] == 'navigate' @@ -232,6 +233,7 @@ def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> N {'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'order_review', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, + {'code': 'freight_upload', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, ] @@ -478,7 +480,7 @@ def test_order_task_with_superseded_candidate_cannot_borrow_current_candidate(ap def test_batch_projection_reports_unclassified_files_and_stage_status_from_own_summary() -> None: - """四阶段卡片只读取自身汇总;未归类文件必须显式计数,不能静默消失。""" + """五阶段卡片只读取自身汇总;未归类文件必须显式计数,不能静默消失。""" projection = _conversation_processing_from_work_items([ { 'work_item_type': 'order_task', 'work_item_no': 'OT-REVIEW', @@ -503,8 +505,36 @@ def test_batch_projection_reports_unclassified_files_and_stage_status_from_own_s assert projection['unclassified_summary'] == {'count': 1} +def test_batch_payload_exposes_five_nodes_and_unverified_legacy_completion_stays_freight_upload(app) -> None: + """新字段固定五节点,兼容字段同值,旧 technical completed 不得计作通知完成。""" + with app.app_context(): + projection = _conversation_processing_from_work_items([{ + 'work_item_type': 'order_task', 'work_item_no': 'OT-LEGACY-UPLOADED', + 'root_order_task_no': 'OT-LEGACY-UPLOADED', 'source_type': 'direct_pdf', + 'shipping_notice_no': 'SN-LEGACY-UPLOADED', 'has_formal_ot': True, + 'source_summary': {'document_id': 601, 'filename': 'legacy.pdf'}, + 'status': 'completed', 'stage': 'completed', + 'user_status': 'completed', 'user_stage': 'completed', + 'verified_upload_success': False, + 'available_actions': [], 'facts': {'upload_state': 'succeeded'}, + }]) + + assert [node['code'] for node in projection['lifecycle_nodes']] == [ + 'intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete', + ] + assert projection['four_stage_nodes'] == projection['lifecycle_nodes'] + freight = next(node for node in projection['lifecycle_nodes'] if node['code'] == 'freight_upload') + assert freight['summary']['needs_action'] == 1 + assert freight['summary']['completed'] == 0 + assert projection['summary']['completed'] == 0 + assert projection['status_groups']['completed'] == [] + assert [row['user_task_no'] for row in projection['status_groups']['waiting_human']] == [ + 'OT-LEGACY-UPLOADED', + ] + + def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_root() -> None: - """同一 EML 的两份订单 PDF 应在四阶段摘要中计为两项,而非一张父卡。""" + """同一 EML 的两份订单 PDF 应在五阶段摘要中计为两项,而非一张父卡。""" nodes = _batch_four_stage_nodes([{ 'work_item_type': 'order_task', 'work_item_no': 'INTAKE:SNI-DOUBLE', @@ -632,6 +662,38 @@ def test_conversation_status_groups_use_the_same_current_file_representative() - ] +@pytest.mark.parametrize('terminal_status', ['cancelled', 'archived']) +def test_cancelled_or_archived_file_stays_in_history_and_out_of_completion_metrics( + app, + terminal_status: str, +) -> None: + """取消或归档仅保留历史,不得进入会话完成、文件完成或第五阶段统计。""" + with app.app_context(): + work_items = [{ + 'work_item_type': 'order_task', + 'work_item_no': f'OT-{terminal_status.upper()}', + 'user_status': terminal_status, + 'user_stage': 'freight_uploading', + # 覆盖历史兼容载荷尚未写入 user_group 的回退路径。 + 'status': terminal_status, + 'stage': terminal_status, + 'source_summary': {'document_id': 570, 'filename': 'history.pdf'}, + }] + projection = _conversation_processing_from_work_items(work_items) + assert projection['summary']['completed'] == 0 + assert projection['summary']['history'] == 1 + assert projection['summary']['total_files'] == 0 + assert projection['summary']['completed_files'] == 0 + assert projection['completed'] == [] + assert [row['user_task_no'] for row in projection['history']] == [ + f'OT-{terminal_status.upper()}', + ] + assert [row['user_task_no'] for row in projection['status_groups'][terminal_status]] == [ + f'OT-{terminal_status.upper()}', + ] + assert all(node['summary']['total'] == 0 for node in projection['lifecycle_nodes']) + + def test_batch_ui_state_uses_the_same_current_file_representative_as_counts() -> None: """历史失败项不得在互斥统计后仍抢走批次当前按钮。""" work_items = [ @@ -1031,6 +1093,7 @@ def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) - {'code': 'intake_parse', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'order_review', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, + {'code': 'freight_upload', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, {'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'}, ] assert leaf['intake_parse_authorized'] is True @@ -1172,7 +1235,7 @@ def test_eml_candidate_review_leaf_opens_lifecycle_only_for_its_primary_document def test_conversation_projection_is_the_complete_batch_display_source(app) -> None: - """会话投影一次下发分组、EML 子文件、四阶段及 UI 动作,前端无需二次裁决。""" + """会话投影一次下发分组、EML 子文件、五阶段及 UI 动作,前端无需二次裁决。""" with app.app_context(): items = _aggregate_eml_order_task_work_items([ { @@ -1868,16 +1931,16 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u assert synced['status'] == 'automating' assert synced['stage'] == 'freight_uploading' - # 人工上传回执已落库时,Notice 终态必须覆盖尚未来得及同步的 OT 旧状态。 + # 历史 Notice.upload_status 不构成成功证据;未补齐 Attempt/预约单时仍须停在货代上传。 notice.upload_status = 'uploaded' order_task.status = 'automating' order_task.stage = 'freight_uploading' db.session.commit() - completed = _project_order_task_work_item(run) - assert completed['status'] == 'completed' - assert completed['stage'] == 'completed' - assert completed['user_status'] == 'completed' - assert all(node['status'] == 'passed' for node in completed['stage_nodes']) + unverified = _project_order_task_work_item(run) + assert unverified['status'] == 'waiting_human' + assert unverified['stage'] == 'freight_uploading' + assert unverified['user_status'] == 'waiting_human' + assert unverified['verified_upload_success'] is False def test_conversation_processing_rebuild_prefers_work_item_user_status(app): diff --git a/backend/tests/test_shipping_review_workbench_stage_layering.py b/backend/tests/test_shipping_review_workbench_stage_layering.py index ff64fae9..1c1770b5 100644 --- a/backend/tests/test_shipping_review_workbench_stage_layering.py +++ b/backend/tests/test_shipping_review_workbench_stage_layering.py @@ -242,8 +242,8 @@ def test_project_stage_for_task_without_domain_facts_is_order_creating(): assert stage['source'] == 'domain_facts' -def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage(): - """人工上传已完成时,旧 OT freight_uploading 阶段不能覆盖 Notice 终态。""" +def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload(): + """历史 Notice.upload_status 无成功 Attempt 时不得绕过货代上传核对。""" task = SimpleNamespace( id=1, order_task_id=9, @@ -253,8 +253,8 @@ def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage(): step_payload_json=None, ) stage = project_stage_for_task(task) - assert stage['code'] == 'completed' - assert stage['source'] == 'notice_terminal' + assert stage['code'] == 'freight_uploading' + assert stage['source'] == 'upload_success_unverified' def test_project_post_ot_automation_job_success_but_ot_created_is_failed(monkeypatch): diff --git a/backend/tests/test_shipping_upload_attempt.py b/backend/tests/test_shipping_upload_attempt.py index 9d94167e..c3efd246 100644 --- a/backend/tests/test_shipping_upload_attempt.py +++ b/backend/tests/test_shipping_upload_attempt.py @@ -18,7 +18,10 @@ from app.models import ( ShippingUploadAttempt, ) from app.services.shipping_notice.fulfillment_workflow import _rpa_callback_success -from app.services.shipping_notice.upload_attempt_service import complete_attempt, mark_attempt_result_unknown, start_rpa_attempt, void_rejected_artifact +from app.services.shipping_notice.upload_attempt_service import ( + complete_attempt, has_verified_upload_success, mark_attempt_result_unknown, + start_rpa_attempt, void_rejected_artifact, +) from app.services.shipping_notice.state_machine import resolve_task_ui_state @@ -64,10 +67,34 @@ def test_upload_callback_is_idempotent_and_locks_reservation(app): assert ShippingUploadAttempt.query.count() == 1 assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded' assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded' + # 三层成功事实齐全后,才允许任务进入业务「通知完成」。 + assert has_verified_upload_success(db.session.get(ShippingNotice, task.id)) is True with pytest.raises(ConflictError): start_rpa_attempt(task, artifact_id=artifact.id) +def test_legacy_uploaded_field_without_attempt_is_not_verified_success(app): + """历史 upload_status=uploaded 缺少成功 Attempt 时必须留在货代上传核对。""" + with app.app_context(): + task, _artifact, _reservation = _ready_artifact() + task.upload_status = 'uploaded' + db.session.flush() + + assert has_verified_upload_success(task) is False + + +def test_archived_upload_success_is_not_counted_as_completed(app): + """归档任务保留上传审计,但不能再计入当前通知完成统计。""" + with app.app_context(): + task, artifact, _reservation = _ready_artifact() + attempt = start_rpa_attempt(task, artifact_id=artifact.id) + complete_attempt(attempt, success=True, callback_id='callback-archived', freight_ref_no='REF-ARCHIVED') + task.lifecycle_status = 'archived' + db.session.flush() + + assert has_verified_upload_success(task) is False + + def test_failed_attempt_does_not_complete_reservation(app): """RPA 失败仅释放 Artifact 重试状态,不能把预约单错误标记为上传完成。""" with app.app_context(): diff --git a/docs/demand.md b/docs/demand.md index 18427eeb..337a3907 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -13,7 +13,10 @@ ### 当前业务阶段基线(2026-08) -业务人员只看到四个阶段:`接收解析 → 订单复核 → 通知准备 → 通知完成`(内部编码:`intake_parse`、`order_review`、`fulfillment_prep`、`upload_complete`)。订单复核确认后正式建单;库存处理和 Excel 生成属于通知准备;上传或登记回执后进入通知完成。`ui_state` 是唯一前端读模型,按钮由后端统一返回。阶段四的进入不等于上传成功:必须有服务端确认的上传 Attempt 和回执事实;同一 Gate 的全局处理按钮只在右侧“当前处理”出现一次。 +业务人员只看到五个阶段:`接收解析 → 订单复核 → 通知准备 → 货代上传 → 通知完成`(内部编码:`intake_parse`、`order_review`、`fulfillment_prep`、`freight_upload`、`upload_complete`)。订单复核确认后正式建单;库存处理和 Excel 生成属于通知准备;下载 Excel、RPA 上传、人工回执登记、失败重试和未知结果核对属于货代上传。`ui_state` 是唯一前端读模型,按钮由后端统一返回。 + +- **完成口径**:只有 `upload_status=uploaded`、全部预约单均为 `uploaded`、且存在关联 Artifact 的 `ShippingUploadAttempt.status=succeeded` 三项事实同时成立,才进入「通知完成」并计入任务/批次完成率。PDF 候选成功、技术 `completed`、回执文本、取消或归档均不得替代成功事实。 +- **恢复口径**:上传失败、RPA 运行中、人工待登记和历史无成功 Attempt 的 `uploaded` 都停在「货代上传」。未知结果必须先查询货代侧或登记核对证据,禁止自动重试;取消/归档是终态但不计为通知完成。同一 Gate 的全局处理按钮只在右侧“当前处理”出现一次。 - **模式**:直通处理(STP)+ 例外工作台。可信 PDF 自动建 Task 并推进至「Excel 已生成,待人工上传」;解析不确定进入人工复核;建单后异常优先在对话侧 Process Gate 轻量处理,复杂数据进复核工作台。 - **双工作台架构(2026-08-02 冻结)**:对话工作台 = 主入口/主状态/主进度/轻量操作;复核工作台 = 深度编辑与证据处理;Task 工作台 = 仅备用深链(非主导航)。后端工作流始终后台运行,前端只消费状态投影。权威线框见 [review-workbench-layout-plan.md](features/shipping-notice/review-workbench-layout-plan.md) §0。 diff --git a/docs/features/shipping-notice/business.md b/docs/features/shipping-notice/business.md index 5b629944..99e497d5 100644 --- a/docs/features/shipping-notice/business.md +++ b/docs/features/shipping-notice/business.md @@ -76,12 +76,13 @@ - 匹配结果有缺口时,缺货预约单继续等待补货;本轮已满足预约单仍可进入滚动制单 - 至少一个预约单满足时,生成包含全部当前可用预约单的**本轮发货 Excel**,并完成该文件的货代上传 -### 四阶段工作台速查(2026-08) +### 五阶段工作台速查(2026-08) - **接收解析**:核对邮件正文、当前附件和解析异常;模板匹配只在这里查看。需要替换文件或重新识别时,按“当前处理”提示操作。 - **订单复核**:核对订单字段、客户、冲突、重复和 Reservation;此阶段不处理库存数量或上传。 - **通知准备**:查看已经冻结的订单、每行库存来源/需求/可用/缺口和通知 Excel 状态;尚未生成匹配结果时,以右侧“当前处理”的提示为准。 -- **通知完成**:下载 Excel、按右侧“当前处理”登记人工上传或重试,并查看最近上传尝试与货代回执。进入本阶段不表示已经上传成功;只有系统显示已确认的上传结果才可视为完成。 +- **货代上传**:下载 Excel、按右侧“当前处理”执行 RPA、登记人工上传、处理失败或核对未知结果,并查看最近上传尝试与货代回执。未知结果不得自动重试。 +- **通知完成**:只读查看已核验的上传时间、货代回执、成功 Attempt 和预约单汇总。仅 Task 状态、全部预约单和成功 Attempt 三项事实同时满足时,才可视为完成并计入完成率;取消/归档不计完成。 同一问题只在右侧 **“当前处理”** 提供一个主操作按钮;页面中其他区域用于查看明细或填写被该按钮打开的表单,避免重复点击不同入口。 diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 39afc790..2a816468 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -5,22 +5,23 @@ > **同步维护**:流程、字段规则、人工确认节点等变更时,**须同时更新本文件与** **`business.md`**。\ > **Dify 文档维护原则**:Dify 编排仅在本文件维护,且以**节点级配置**为准;重点维护各节点的职责、输入、输出、条件、Tool 绑定与连线关系,不再额外维护独立 DSL 解读文档。\ -## 四阶段 UI 状态契约(2026-08) +## 五阶段 UI 状态契约(2026-08) -业务人员只看到四个阶段:`intake_parse`(接收解析)→ `order_review`(订单复核)→ `fulfillment_prep`(通知准备)→ `upload_complete`(通知完成)。`ui_state` 是唯一前端读模型;Gate/Execution 是业务门禁真相。正式 Task 的操作使用 `ui_state.actions.primary/secondary`,批次 / 生命周期投影的操作使用 `ui_state.primary_action/secondary_actions`;两者均由后端下发,前端不得根据领域字段自行推导阶段或按钮;`process_status` 已删除。 +业务人员只看到五个阶段:`intake_parse`(接收解析)→ `order_review`(订单复核)→ `fulfillment_prep`(通知准备)→ `freight_upload`(货代上传)→ `upload_complete`(通知完成)。`ui_state` 是唯一前端读模型;Gate/Execution 是业务门禁真相。正式 Task 的操作使用 `ui_state.actions.primary/secondary`,批次 / 生命周期投影的操作使用 `ui_state.primary_action/secondary_actions`;两者均由后端下发,前端不得根据领域字段自行推导阶段或按钮;`process_status` 已删除。 -### 四阶段工作面与动作宿主(2026-08) +### 五阶段工作面与动作宿主(2026-08) - 接收解析只展示邮件/附件、解析证据与原 PDF 的单文件重识别;模板匹配只在该阶段展示,不支持上传替代 PDF。 - 订单复核只展示字段、客户、冲突、重复和 Reservation 人工裁决;不得展示库存数量、缺口或上传操作。 - 通知准备只展示冻结订单、库存匹配行和 Excel 产物状态。任务详情的 `ui_state.stage_context.preparation` 是只读摘要;未生成匹配结果时必须明确显示当前 Gate,不能显示“处理结果已完成”。 -- 通知完成只展示 Excel、最新上传 Attempt 和回执。`upload_complete` 只是第四阶段工作面;只有可追溯 `ShippingUploadAttempt.status=succeeded` 才是上传成功。人工登记必须同时提交回执号和证据资产。 +- 货代上传展示 Excel、RPA 状态、人工上传登记、失败恢复、未知结果核对和最新上传 Attempt;`freight_upload_rpa` / `manual_upload_handoff` 的动作只落在此工作面。人工登记必须同时提交回执号和证据资产;未知结果禁止自动重试。 +- 通知完成只读展示上传时间、货代回执、成功 Attempt 和预约单汇总。只有 `has_verified_upload_success(task)`(Task `uploaded`、全部预约单 `uploaded`、关联 Artifact 存在 `ShippingUploadAttempt.status=succeeded`)才进入;历史 `uploaded/completed`、候选/PDF 成功、单独回执、取消或归档均不得进入完成统计。 - 桌面右栏 `ReviewCurrentProcessingCard` 是每个 Gate 唯一全局写入口;主区仅显示事实、行级局部操作或被右栏定位的裁决表单。`TaskTodoPanel` 在生命周期工作台仅作无界面动作执行宿主,禁止重复渲染 Gate 或主按钮。 - `stage_context` 不落库、不驱动状态、不授权动作,仅由正式任务详情与单票 `/ui-state` 按需返回;任务列表、聊天轻量投影不加载它,以避免 N+1 查询。 ### Dify 配置边界(2026-08) -本次四阶段工作面调整**无需修改 Dify**。Dify 不能创建/推进 Gate,不能确认客户、裁决订单、匹配库存、生成 Excel、上传货代或登记回执;这些写入只由 HXOPS 服务端 Gate 校验后的工作台动作执行。若管理员维护现有 `shipping_notice` Chatflow,仍只能保留只读 `get_task_status` Tool,并原样传递 HXOPS 注入的短效能力令牌;发现任何写 Tool 或由 Dify 推断“已完成”时,应停止发布并移除。 +本次五阶段工作面调整**无需修改 Dify**。Dify 不能创建/推进 Gate,不能确认客户、裁决订单、匹配库存、生成 Excel、上传货代或登记回执;这些写入只由 HXOPS 服务端 Gate 校验后的工作台动作执行。若管理员维护现有 `shipping_notice` Chatflow,仍只能保留只读 `get_task_status` Tool,并原样传递 HXOPS 注入的短效能力令牌;发现任何写 Tool 或由 Dify 推断“已完成”时,应停止发布并移除。 ## 2026-07-31 订单解析增强最终实施方案(待实施) @@ -363,7 +364,7 @@ L1 字段级:目标单元格 + 表头 + 相邻单元格 | `standard` | 默认 | 订单字段 + 明细;右侧阻断/库存异常摘要 | 常驻 PDF 列、常驻 AI、常驻完整检查、对话上下文 | | `evidence` | 字段「定位证据」 | PDF 证据抽屉(可固定)+ 当前字段/行编辑 | 强制整页跳变;重跑识别 | | `inventory` | 「查看库存问题」 | 异常行优先的明细 + 库存处理卡 | 重新识别 PDF;已通过行常驻展开 | -| `reparse` | 重新识别进行中 | 四阶段真实进度 | 展示/编辑旧 Draft 完整编辑区 | +| `reparse` | 重新识别进行中 | 五阶段真实进度 | 展示/编辑旧 Draft 完整编辑区 | | `confirm_progress` | 确认建单成功 | 真实 Task / auto_progress | 继续编辑已确认 Draft | 模式切换规则:除证据定位打开抽屉外,系统只提示模式、不强制跳变;文件切换保留当前模式与字段滚动位置;关闭证据抽屉后恢复滚动。业务写操作仍走既有 Case/Draft API 与乐观锁,布局层不得改后端状态机。 @@ -1726,7 +1727,7 @@ GET /api/admin/shipping-order-schema/published-contract ### 发货任务处置生命周期 -- 业务人员只看到四阶段:`接收解析 → 订单复核 → 通知准备 → 通知完成`;Gate/Execution 是业务判断真相,`ui_state` 是唯一前端读模型,任务处置使用独立的 `lifecycle_status=active|voided|archived`。 +- 业务人员只看到五阶段:`接收解析 → 订单复核 → 通知准备 → 货代上传 → 通知完成`;Gate/Execution 是业务判断真相,`ui_state` 是唯一前端读模型,任务处置使用独立的 `lifecycle_status=active|voided|archived`。 - 用户点击删除时,服务端以任务行锁重算资格并写入 `ShippingTaskEvent` 审计(操作者、请求 ID、原因和处置前后事实)。纯误建任务仅进入回收站;已有业务单、Candidate 消费、库存链接或导出 Artifact 的任务同时设为 `voided` 后进入回收站。存在修订后继的任务禁止 delete/void,只允许 archive,避免破坏版本链。 - `upload_status` 为 queued/pending/running/uploading/uploaded/succeeded/success、存在货代参考号/回执时,平台禁止 delete/void,只允许 archive。异步编排、队列、RPA 回调和上传入口必须统一检查 `task_is_active`。 - 回收站只允许恢复仍为 `active` 的纯误建任务;已作废或已归档任务不得恢复,必须走受控新建/修订业务流程。永久删除仅在第五阶段实现,并重新检查全部引用。 @@ -2481,9 +2482,9 @@ ui_state.actions -> 前端唯一可渲染的履约动作投影 - `checkpoint` 不再产生履约 UI 可写动作;它继续作为后端流程、自动推进和诊断状态使用。建任务前 Case 的复核动作不属于正式履约 Gate,仍由其独立的 Case 权限/状态契约管理。 - 每个 `PROCESS_GATE_DEFINITIONS` 项必须声明 `ui_placement.target_surface` 与 `ui_placement.target_anchor`。后端在投影当前 Gate 动作时将该位置一并写入 `ui_state.actions`;未知位置前端不得猜测或兜底渲染。 -- 页面仅提供稳定锚点(例如 `fulfillment_prep/excel_artifact`、`upload_complete/freight_upload`、`upload_complete/manual_upload`)。是否显示“重新生成 Excel”、RPA 重试或人工上传登记,完全由当前 Gate 的已授权动作决定;前端不得以生命周期、按钮码、前缀或任务状态自行放行。 +- 页面仅提供稳定锚点(例如 `fulfillment_prep/excel_artifact`、`freight_upload/freight_upload`、`freight_upload/manual_upload`)。是否显示“重新生成 Excel”、RPA 重试或人工上传登记,完全由当前 Gate 的已授权动作决定;前端不得以生命周期、按钮码、前缀或任务状态自行放行。 - `freight_upload_rpa` / `manual_upload_handoff` 可经 RecoveryPlan 授权 `regenerate_excel_artifact`:当前上传 Gate 负责权限、并发和版本校验,目标为 `artifact_generation`;RecoveryPlan 自己声明 `fulfillment_prep/excel_artifact`,优先于当前 Gate 的上传位置。只在当前 Artifact 为未上传 `ready`、无成功/未知回执、无 RPA 进行中且无活动 RecoveryPlan 时下发。执行时仅将旧 Artifact 标为 `superseded`、终止未完成上传并释放其 Reservation 占用,再生成新 Artifact;库存快照、行级匹配、人工短缺放行和人工补录不失效。 -- 已通过 `resolve_task_export_download` 校验的 Excel Artifact 可额外下发只读下载动作,并明确挂在 `upload_complete/excel_artifact`;这不是前端独立的操作栏,也不覆盖 Gate 对写动作的授权。 +- 已通过 `resolve_task_export_download` 校验的 Excel Artifact 可额外下发只读下载动作,并明确挂在 `freight_upload/excel_artifact`;这不是前端独立的操作栏,也不覆盖 Gate 对写动作的授权。 - Gate 写操作沿用既有版本校验与 `chat_process_gate_*` 审计;Artifact 下载沿用既有访问审计。二者均须保留操作者、时间、动作/访问内容及可追溯的对象快照/版本信息。 本次只调整 HXOPS 后端投影与前端展示契约,**无需修改 Dify 配置**。Dify 不裁决 Process Gate、不生成履约按钮、不调用 Excel/RPA/上传写路径;Dify 侧继续遵守本章 §2 的只读解释和受控复核边界。 diff --git a/docs/funclist.md b/docs/funclist.md index 12facf7d..211b851a 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -2,12 +2,13 @@ ## 知识库同步状态校验 -## 货代发货通知四阶段 +## 货代发货通知五阶段 - 接收解析:接收、解析和抽取订单字段。 - 订单复核:核对订单并确认正式建单。 - 通知准备:库存处理、匹配和生成发货通知 Excel;展示冻结订单、行级库存/缺口和 Excel 状态。 -- 通知完成:上传通知或登记上传回执;仅服务端确认的上传 Attempt 成功后显示完成结果。 +- 货代上传:下载 Excel、RPA 上传、人工上传回执登记、失败恢复和未知结果核对;未知结果禁止自动重试。 +- 通知完成:只读展示已核验的上传成功证据;仅 Task 聚合、全部预约单与成功 Upload Attempt 同时满足时显示并计入完成。 - 平台把文本提交给 Dify 后,会继续确认 Dify 的 `indexing_status`;只有 `completed` 才展示“同步:已完成”。 - Dify 返回 `error/failed` 或 60 秒内未完成索引时,同步任务、同步记录和文档卡片会显示失败原因;再次同步会重新提交失败文档。 diff --git a/docs/tec.md b/docs/tec.md index 7e0e20dc..bd8ca15d 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -4,7 +4,9 @@ ### 阶段与状态职责基线(2026-08) -业务阶段固定为 `intake_parse`、`order_review`、`fulfillment_prep`、`upload_complete` 四项(接收解析、订单复核、通知准备、通知完成);Gate/Execution 负责业务判断,`ui_state` 负责前端投影,`lifecycle_status` 独立表示 active/voided/archived,`process_status` 已删除。`ui_state.stage_context` 是正式任务详情按需返回的只读阶段事实,不是新的 State、数据库字段或动作权限来源;上传成功必须以 `ShippingUploadAttempt.status=succeeded` 为准。 +业务阶段固定为 `intake_parse`、`order_review`、`fulfillment_prep`、`freight_upload`、`upload_complete` 五项(接收解析、订单复核、通知准备、货代上传、通知完成);这是唯一用户可见生命周期投影,不是第二套状态机。Gate/Execution、Intake、Run/Unit、checkpoint、RPA 状态和 UploadAttempt 仍是执行事实;`ui_state` 负责前端投影,`lifecycle_status` 独立表示 active/voided/archived,`process_status` 已删除。`ui_state.stage_context` 是正式任务详情按需返回的只读阶段事实,不是新的 State、数据库字段或动作权限来源。 + +`has_verified_upload_success(task)` 是唯一完成谓词:Task 聚合 `upload_status=uploaded`、全部 `ShippingReservation.status=uploaded`、关联 `ShippingExportArtifact` 存在 `ShippingUploadAttempt.status=succeeded`。只有该谓词为真时技术投影为 `completed`、生命周期投影为 `upload_complete`;旧 `uploaded/completed`、候选/PDF 成功、单独回执、取消或归档不能进入完成。批次接口首选 `lifecycle_nodes`;`four_stage_nodes` 在一个发布周期内作为同值的五阶段兼容别名。 ### STP 阶段 0:字段契约与状态语义冻结(2026-07-30,项次派生 Phase 0 纠偏) diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue index d63aead0..2a580000 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue @@ -47,6 +47,8 @@ import type { OrderFieldValuePreview, OrderProfileCanvasRegion, OrderProfileDocumentMatchAnchor, + OrderProfileAnchorRule, + OrderCoordinateProfileDefinition, OrderProfileFieldRegion, OrderProfileRelativeRegion, OrderProfileBoundSample, @@ -384,6 +386,44 @@ const documentMatch = reactive({ minimumMargin: 0.15, }); const documentMatchDirty = ref(false); +/** 坐标框架默认关闭;仅管理员显式启用后才写入 anchor_frame 声明。 */ +const coordinateModel = reactive({ + type: 'legacy' as 'legacy' | 'anchor_frame', + anchors: [] as OrderProfileAnchorRule[], + maxTranslateX: 0.03, + maxTranslateY: 0.06, +}); +const coordinateModelDirty = ref(false); +const coordinateModelValid = computed(() => ( + coordinateModel.type === 'legacy' + || (coordinateModel.anchors.length > 0 + && coordinateModel.anchors.length <= 4 + && coordinateModel.anchors.every((anchor) => Boolean(anchor.text?.trim() && anchor.region)) + && Number.isFinite(coordinateModel.maxTranslateX) + && Number.isFinite(coordinateModel.maxTranslateY) + && coordinateModel.maxTranslateX >= 0 && coordinateModel.maxTranslateX <= 0.15 + && coordinateModel.maxTranslateY >= 0 && coordinateModel.maxTranslateY <= 0.2) +)); +const enableAnchorFrameFromDocumentAnchor = () => { + const source = documentMatch.requiredAnchors[0]; + if (!source?.label_region) return; + coordinateModel.type = 'anchor_frame'; + coordinateModel.anchors = [{ + anchor_id: `frame_${source.anchor_id}`.replace(/[^a-zA-Z0-9_]/g, '_').toLowerCase(), + text: source.label, + aliases: [], + match_mode: 'exact', + region: source.label_region, + position_locked: true, + minimum_evidence_level: 'coordinate', + }]; + coordinateModelDirty.value = true; +}; +const setCoordinateModelType = (type: 'legacy' | 'anchor_frame') => { + coordinateModel.type = type; + if (type === 'legacy') coordinateModel.anchors = []; + coordinateModelDirty.value = true; +}; /** * 共同画布的字段选项只决定视觉定位;coordinate 末端值源仍必须由 Schema 显式授权 * pdf_coordinate。XFA 的正式取值来自 datasets,不能因未授权 PDF 文本而在画布中消失。 @@ -521,7 +561,7 @@ const draftSaveAdapter = computed(() => ( adapterKey: valueAdapterKey.value, adapters: { xfa_dataset: { - hasUnsavedChanges: history.value.length > 0 || documentMatchDirty.value || xfaDirty.value, + hasUnsavedChanges: history.value.length > 0 || documentMatchDirty.value || coordinateModelDirty.value || xfaDirty.value, skipUnchangedManualSave: true, canSave: !xfaValidateBlocked.value, canValidate: !xfaDirty.value && !xfaValidateBlocked.value, @@ -538,7 +578,7 @@ const draftSaveAdapter = computed(() => ( applySavedDraft: async (saved) => valueAdapterDesk.applySavedDraft(saved as ShippingOrderDocumentProfile), }, coordinate_ocr: { - hasUnsavedChanges: history.value.length > 0 || documentMatchDirty.value, + hasUnsavedChanges: history.value.length > 0 || documentMatchDirty.value || coordinateModelDirty.value, skipUnchangedManualSave: false, canSave: issues.value.length === 0, canValidate: issues.value.length === 0, @@ -770,6 +810,7 @@ const issues = computed(() => { if (regions.value.some( (item) => item.kind === "order_field" && item.valueMode === "multi_line" && !item.stopAnchorText?.trim(), )) result.push("多行订单字段必须填写结束标签。"); + if (!coordinateModelValid.value) result.push(t('admin.shippingOrderProfiles.workbench.coordinateModelInvalid')); if (regions.value.some((item) => !normalizedCanvasRegion(item.region))) { result.push("存在无效的页面坐标框,请重新绘制该标注。"); } @@ -1377,7 +1418,7 @@ const definition = () => { })), }; }); - return { + const visualDefinition: OrderCoordinateProfileDefinition = { document_match: { document_type: "purchase_order" as const, page_pattern: "one_or_more" as const, @@ -1481,6 +1522,15 @@ const definition = () => { }; }), }; + if (coordinateModel.type === 'anchor_frame') { + visualDefinition.coordinate_model = { + type: 'anchor_frame', + anchors: coordinateModel.anchors.map((anchor) => ({ ...anchor })), + max_translate_x: coordinateModel.maxTranslateX, + max_translate_y: coordinateModel.maxTranslateY, + }; + } + return visualDefinition; }; /** * 保存当前草稿定义并附带当前标签租约。 @@ -2344,6 +2394,19 @@ const edit = async (profile: ShippingOrderDocumentProfile) => { documentMatch.minimumScore = definition.document_match.minimum_score; documentMatch.minimumMargin = definition.document_match.minimum_margin; documentMatchDirty.value = false; + const configuredModel = definition.coordinate_model; + if (configuredModel?.type === 'anchor_frame') { + coordinateModel.type = 'anchor_frame'; + coordinateModel.anchors = (configuredModel.anchors || []).map((anchor) => ({ ...anchor })); + coordinateModel.maxTranslateX = Number(configuredModel.max_translate_x ?? 0.03); + coordinateModel.maxTranslateY = Number(configuredModel.max_translate_y ?? 0.06); + } else { + coordinateModel.type = 'legacy'; + coordinateModel.anchors = []; + coordinateModel.maxTranslateX = 0.03; + coordinateModel.maxTranslateY = 0.06; + } + coordinateModelDirty.value = false; regions.value = restoreRegions(profile); history.value = []; future.value = []; @@ -2781,6 +2844,37 @@ onBeforeUnmount(() => {

{{ documentAnchorNotice }}

+
+ {{ t('admin.shippingOrderProfiles.workbench.coordinateModelTitle') }} +

{{ t('admin.shippingOrderProfiles.workbench.coordinateModelHint') }}

+ + +
+
{{ t('admin.shippingOrderProfiles.workbench.tableRegionSettings') }}