diff --git a/backend/app/api/admin/shipping_order_document_profiles.py b/backend/app/api/admin/shipping_order_document_profiles.py index e5fb05a5..eb2ad5f2 100644 --- a/backend/app/api/admin/shipping_order_document_profiles.py +++ b/backend/app/api/admin/shipping_order_document_profiles.py @@ -102,6 +102,20 @@ def suggest_order_document_profile_coordinate_reconstruction(): return _ok(service.suggest_coordinate_reconstruction(request.get_json(silent=True) or {}, actor_id=_actor_id())) +@admin_bp.route('/shipping-notice/order-document-profile-samples/order-field-suggestions', methods=['POST']) +@require_admin +def suggest_order_document_profile_order_fields(): + """从整页坐标与冻结 Header Schema 提供订单字段待复核候选。""" + return _private_ok(service.suggest_order_field_layouts(request.get_json(silent=True) or {}, actor_id=_actor_id())) + + +@admin_bp.route('/shipping-notice/order-document-profile-samples/order-field-values-preview', methods=['POST']) +@require_admin +def preview_order_document_profile_order_field_values(): + """按当前草稿定义读取订单字段候选值,页面刷新后仍可恢复复核证据。""" + return _private_ok(service.preview_order_field_values(request.get_json(silent=True) or {}, actor_id=_actor_id())) + + @admin_bp.route('/shipping-notice/order-document-profile-samples/ocr-coordinate-evidence', methods=['POST']) @require_admin def generate_order_document_profile_ocr_coordinate_evidence(): @@ -306,7 +320,38 @@ def add_order_document_profile_test_sample(suite_id: int): data = request.get_json(silent=True) or {} return _ok(quality.add_sample( suite_id=suite_id, document_id=data.get('document_id'), table_id=str(data.get('table_id') or ''), - expected_rows=data.get('expected_rows'), actor_id=_actor_id(), + expected_rows=data.get('expected_rows'), expected_order_fields=data.get('expected_order_fields'), actor_id=_actor_id(), + ), status=201) + + +@admin_bp.route('/shipping-notice/order-document-profile-test-suites//available-samples', methods=['GET']) +@require_admin +def list_order_document_profile_test_available_samples(suite_id: int): + """列出未参与当前模板建模、可用于盲测复核的同类样本。""" + from app.services.shipping_notice import document_profile_quality_service as quality + return _ok(quality.list_independent_samples(suite_id=suite_id, actor_id=_actor_id())) + + +@admin_bp.route('/shipping-notice/order-document-profile-test-suites//candidate-preview', methods=['POST']) +@require_admin +def preview_order_document_profile_test_candidate(suite_id: int): + """运行独立样本并返回字段与明细候选,供管理员逐项勾选复核。""" + from app.services.shipping_notice import document_profile_quality_service as quality + data = request.get_json(silent=True) or {} + return _private_ok(quality.preview_independent_sample( + suite_id=suite_id, document_id=data.get('document_id'), table_id=str(data.get('table_id') or ''), actor_id=_actor_id(), + )) + + +@admin_bp.route('/shipping-notice/order-document-profile-test-suites//reviewed-samples', methods=['POST']) +@require_admin +def confirm_order_document_profile_test_reviews(suite_id: int): + """将用户对自动候选的正确/错误勾选固化为现有盲测真值。""" + from app.services.shipping_notice import document_profile_quality_service as quality + data = request.get_json(silent=True) or {} + return _ok(quality.confirm_sample_reviews( + suite_id=suite_id, document_id=data.get('document_id'), table_id=str(data.get('table_id') or ''), + row_reviews=data.get('row_reviews'), order_field_reviews=data.get('order_field_reviews'), actor_id=_actor_id(), ), status=201) diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 8ea3de04..3287f6ce 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -1198,6 +1198,27 @@ def workspace_update_shipping_notice_candidate(candidate_no: str): ) +@workspace_shipping_notice_bp.route('/shipping-notice/candidates//promote', methods=['POST']) +def workspace_promote_shipping_notice_candidate(candidate_no: str): + """人工采纳 Dify 兜底识别的 Candidate。""" + user = _require_user() + from app.services.shipping_notice.candidate_service import promote_candidate + + return _ok(promote_candidate(user_id=user.id, candidate_no=candidate_no)) + + +@workspace_shipping_notice_bp.route('/shipping-notice/candidates//reject', methods=['POST']) +def workspace_reject_shipping_notice_candidate(candidate_no: str): + """人工驳回尚未进入履约的 Candidate。""" + user = _require_user() + body = request.get_json(silent=True) or {} + if not isinstance(body, dict): + raise ValidationError('请求体必须为对象') + from app.services.shipping_notice.candidate_service import reject_candidate + + return _ok(reject_candidate(user_id=user.id, candidate_no=candidate_no, reason=body.get('reason'))) + + @workspace_shipping_notice_bp.route( '/shipping-notice/candidates//duplicate-refresh', methods=['POST'], diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index 5ecd9f2b..5a8aa3a2 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -571,6 +571,14 @@ class ShippingNoticeCandidate(Base): __tablename__ = 'shipping_notice_candidates' __table_args__ = ( + CheckConstraint( + "candidate_status IN ('provisional', 'accepted', 'rejected', 'expired')", + name='ck_shipping_notice_candidates_status', + ), + CheckConstraint( + "acceptance_mode IS NULL OR acceptance_mode IN ('automatic', 'manual', 'legacy')", + name='ck_shipping_notice_candidates_acceptance_mode', + ), UniqueConstraint('candidate_no', name='uq_shipping_notice_candidates_candidate_no'), UniqueConstraint( 'intake_id', 'candidate_key', 'order_extraction_run_id', @@ -590,6 +598,7 @@ class ShippingNoticeCandidate(Base): 'business_fingerprint', ), Index('ix_shipping_notice_candidates_duplicate_status', 'duplicate_status'), + Index('ix_shipping_notice_candidates_fulfillment_gate', 'candidate_status', 'is_current_version'), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -613,6 +622,7 @@ class ShippingNoticeCandidate(Base): Boolean, default=True, server_default=text('true'), nullable=False, index=True, ) selected_before_superseded: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True) + candidate_status_before_superseded: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) extraction_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) classification_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True) field_confidence_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) @@ -628,7 +638,16 @@ class ShippingNoticeCandidate(Base): nullable=False, ) conflicts_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) - selected: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), nullable=False) + # `selected` is a legacy UI projection. Fulfillment must use candidate_status. + candidate_status: Mapped[str] = mapped_column( + String(32), default='provisional', server_default=text("'provisional'"), nullable=False, index=True, + ) + acceptance_mode: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + accepted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + accepted_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + acceptance_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + acceptance_policy_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + selected: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'), nullable=False) business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) fingerprint_strength: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) diff --git a/backend/app/models/shipping_document_profile_quality.py b/backend/app/models/shipping_document_profile_quality.py index c1367caf..3436c47d 100644 --- a/backend/app/models/shipping_document_profile_quality.py +++ b/backend/app/models/shipping_document_profile_quality.py @@ -22,7 +22,7 @@ class ShippingDocumentProfileTestSuite(Base): __tablename__ = 'shipping_document_profile_test_suites' __table_args__ = ( - UniqueConstraint('profile_id', name='uq_shipping_document_profile_test_suites_profile'), + UniqueConstraint('profile_id', 'profile_checksum', name='uq_shipping_document_profile_test_suites_profile_checksum'), CheckConstraint("status IN ('draft', 'approved', 'superseded')", name='ck_shipping_document_profile_test_suites_status'), ) @@ -45,7 +45,7 @@ class ShippingDocumentProfileTestSuite(Base): class ShippingDocumentProfileTestSample(Base): - """盲测样本文档及管理员确认的字段期望值;不与建 Profile 的样本自动复用。""" + """盲测样本文档及管理员确认的明细/订单字段真值;不与建 Profile 的样本自动复用。""" __tablename__ = 'shipping_document_profile_test_samples' __table_args__ = ( @@ -57,6 +57,7 @@ class ShippingDocumentProfileTestSample(Base): document_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_documents.id'), nullable=False) table_id: Mapped[str] = mapped_column(String(128), nullable=False) expected_rows_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list) + expected_order_fields_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) created_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) diff --git a/backend/app/services/shipping_notice/batch_from_intakes.py b/backend/app/services/shipping_notice/batch_from_intakes.py index b4c7d3a0..1f01f843 100644 --- a/backend/app/services/shipping_notice/batch_from_intakes.py +++ b/backend/app/services/shipping_notice/batch_from_intakes.py @@ -612,18 +612,6 @@ def create_shipping_batch_from_candidates( ) if intake.expires_at and intake.expires_at < now: raise ConflictError(code='SHIPPING_NOTICE.INTAKE_EXPIRED', message='接入记录已过期') - if not candidate.selected: - raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED', message='订单候选未选中') - if not candidate.is_current_version: - raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_SUPERSEDED', message='订单候选已被重新识别版本替代') - if candidate.consumed_task_id is not None: - raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费') - if str(candidate.validation_status or '') != 'ready' or candidate.conflicts_json: - raise ConflictError( - code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED', - message='订单候选仍有字段冲突或未完成审核', - details={'candidate_no': candidate.candidate_no, 'conflicts': list(candidate.conflicts_json or [])}, - ) document = db.session.get(ShippingNoticeDocument, int(candidate.primary_document_id)) if document is None or document.parse_status != 'parsed': raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_DOCUMENT_INVALID', message='订单候选主附件不可用') @@ -728,6 +716,8 @@ def create_shipping_batch_from_candidates( }) candidate.updated_at = now continue + from app.services.shipping_notice.candidate_service import ensure_candidate_fulfillment_ready + ensure_candidate_fulfillment_ready(candidate) create_items.append(candidate_to_notice_item(candidate, intake, document)) create_candidates.append(candidate) @@ -905,6 +895,7 @@ def create_shipping_batch_from_intakes( ShippingNoticeIntake.user_id == int(user_id), ShippingNoticeIntake.intake_no.in_(normalized), ShippingNoticeCandidate.selected.is_(True), + ShippingNoticeCandidate.candidate_status == 'accepted', ShippingNoticeCandidate.consumed_task_id.is_(None), ) .order_by(ShippingNoticeCandidate.id.asc()) diff --git a/backend/app/services/shipping_notice/candidate_service.py b/backend/app/services/shipping_notice/candidate_service.py index b5b85b29..ba5b4b9c 100644 --- a/backend/app/services/shipping_notice/candidate_service.py +++ b/backend/app/services/shipping_notice/candidate_service.py @@ -23,6 +23,26 @@ from app.services.shipping_notice.intake_service import can_force_create_shippin _ACTIONS = frozenset({'open_existing', 'create_revision', 'force_create'}) +def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> None: + """统一履约门禁:只有已接受、当前且无阻断问题的 Candidate 才能建单。""" + if str(candidate.candidate_status or '') != 'accepted': + raise ConflictError( + code='SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED', + message='订单候选尚未被接受,不能进入履约', + ) + if not candidate.selected: + raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED', message='订单候选未选中') + if not candidate.is_current_version: + raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_SUPERSEDED', message='订单候选已被重新识别版本替代') + if candidate.consumed_task_id is not None: + raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费') + if str(candidate.validation_status or '') != 'ready' or candidate.conflicts_json: + raise ConflictError( + code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED', + message='订单候选仍有字段冲突或未完成审核', + ) + + def _candidate_for_user(candidate_no: str, user_id: int, *, lock: bool = False) -> tuple[ShippingNoticeCandidate, ShippingNoticeIntake, ShippingNoticeDocument]: """按候选编号和用户加载 Candidate、Intake、Document;写路径可加行锁。""" query = ( @@ -97,7 +117,8 @@ def update_candidate(*, user_id: int, candidate_no: str, selected: bool | None = if selected is not None: if not isinstance(selected, bool): raise ValidationError(code='VALIDATION.INVALID_PARAM', message='selected 必须为布尔值') - candidate.selected = selected + # Selection is retained for legacy batch APIs but may not bypass acceptance. + candidate.selected = selected if candidate.candidate_status == 'accepted' else False if business_summary is not None: if not isinstance(business_summary, dict): raise ValidationError(code='VALIDATION.INVALID_PARAM', message='business_summary 必须为对象') @@ -126,6 +147,66 @@ def update_candidate(*, user_id: int, candidate_no: str, selected: bool | None = return _serialize_candidate_brief(candidate) +def _append_candidate_decision_history(candidate: ShippingNoticeCandidate, *, action: str, user_id: int, reason: str | None = None) -> None: + """记录人工采纳或驳回事件,便于审核回放。""" + structured = dict(candidate.structured_result_json or {}) + history = list(structured.get('manual_review_history') or []) + history.append({ + 'action': action, + 'actor_user_id': int(user_id), + 'reason': str(reason or '').strip() or None, + 'decided_at': datetime.utcnow().isoformat(), + }) + structured['manual_review_history'] = history + candidate.structured_result_json = structured + + +def promote_candidate(*, user_id: int, candidate_no: str) -> dict[str, Any]: + """人工采纳 Dify 兜底 Candidate;重复采纳请求保持幂等。""" + candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True) + if candidate.candidate_status == 'accepted': + return _serialize_candidate_brief(candidate) + if candidate.candidate_status != 'provisional': + raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_DECISION_FINAL', message='订单候选已被驳回或过期') + if str(candidate.extraction_source or '') not in {'dify_workflow', 'manual'}: + raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_PROMOTION_FORBIDDEN', message='仅 Dify 兜底候选允许人工采纳') + if candidate.consumed_task_id is not None or not candidate.is_current_version: + raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选不可再采纳') + _refresh_candidate(candidate, intake, document) + if candidate.validation_status != 'ready' or candidate.conflicts_json or candidate.duplicate_status not in {'none', 'unchecked'}: + raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED', message='请先完成字段和重复审核') + candidate.candidate_status = 'accepted' + candidate.acceptance_mode = 'manual' + candidate.accepted_at = datetime.utcnow() + candidate.accepted_by_id = int(user_id) + candidate.acceptance_reason = 'dify_candidate_promoted' + candidate.acceptance_policy_version = 'manual-review-v1' + candidate.selected = True + _append_candidate_decision_history(candidate, action='promoted', user_id=user_id) + db.session.commit() + return _serialize_candidate_brief(candidate) + + +def reject_candidate(*, user_id: int, candidate_no: str, reason: str | None = None) -> dict[str, Any]: + """人工驳回未消费 Candidate,并保留审计原因。""" + candidate, intake, _document = _candidate_for_user(candidate_no, user_id, lock=True) + if candidate.candidate_status == 'rejected': + return _serialize_candidate_brief(candidate) + if candidate.candidate_status != 'provisional' or candidate.consumed_task_id is not None or not candidate.is_current_version: + raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_DECISION_FINAL', message='订单候选不可再驳回') + candidate.candidate_status = 'rejected' + candidate.selected = False + candidate.acceptance_mode = None + candidate.accepted_at = None + candidate.accepted_by_id = None + candidate.acceptance_reason = str(reason or '').strip() or 'manual_rejected' + candidate.acceptance_policy_version = 'manual-review-v1' + candidate.updated_at = datetime.utcnow() + _append_candidate_decision_history(candidate, action='rejected', user_id=user_id, reason=reason) + db.session.commit() + return _serialize_candidate_brief(candidate) + + def refresh_candidate_duplicate(*, user_id: int, candidate_no: str) -> dict[str, Any]: """刷新单个 Candidate 的重复检测结果并清除陈旧决策。""" candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True) diff --git a/backend/app/services/shipping_notice/constants.py b/backend/app/services/shipping_notice/constants.py index a674c702..df46ada4 100644 --- a/backend/app/services/shipping_notice/constants.py +++ b/backend/app/services/shipping_notice/constants.py @@ -19,6 +19,7 @@ CP_CUSTOMER_REVIEW = "customer_review" CP_TASK_EXISTS = "task_exists" CP_RSV_REQ = "rsv_req" CP_UPLOAD_FAILED = "upload_failed" +CP_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown" CP_WAITING_UPLOAD = "waiting_upload" CP_REJECTED = "rejected" # Derived UI checkpoints (no separate pending_human_reason; from process_status) @@ -51,3 +52,4 @@ PH_INVENTORY_SOURCE_UNRESOLVED = "inventory_source_unresolved" PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED PH_UPLOAD_RPA_FAILED = "upload_rpa_failed" PH_UPLOAD_RPA_PENDING = "upload_rpa_pending" +PH_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown" diff --git a/backend/app/services/shipping_notice/document_candidate_persist.py b/backend/app/services/shipping_notice/document_candidate_persist.py index 8964c480..092acb27 100644 --- a/backend/app/services/shipping_notice/document_candidate_persist.py +++ b/backend/app/services/shipping_notice/document_candidate_persist.py @@ -233,8 +233,9 @@ def _upsert_candidate( intake_id=int(intake.id), primary_document_id=int(document.id), candidate_key=str(candidate_key), - selected=True, + selected=False, validation_status='pending', + candidate_status='provisional', ) db.session.add(row) row.primary_document_id = int(document.id) @@ -336,6 +337,11 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]: else {} ) document = db.session.get(ShippingNoticeDocument, int(cand.primary_document_id)) + action_buttons: list[str] = [] + if cand.candidate_status == 'provisional' and cand.consumed_task_id is None and cand.is_current_version: + action_buttons.extend(['edit', 'evidence', 'reject']) + if cand.validation_status == 'ready' and not blocking: + action_buttons.append('promote') return { 'candidate_no': cand.candidate_no, 'primary_document_id': cand.primary_document_id, @@ -343,6 +349,14 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]: 'po_number': cand.po_number, 'confidence': cand.confidence, 'validation_status': cand.validation_status, + 'candidate_status': cand.candidate_status, + 'acceptance_mode': cand.acceptance_mode, + 'accepted_at': cand.accepted_at.isoformat() if cand.accepted_at else None, + 'accepted_by_id': cand.accepted_by_id, + 'acceptance_reason': cand.acceptance_reason, + 'acceptance_policy_version': cand.acceptance_policy_version, + 'extraction_source': cand.extraction_source, + 'action_buttons': action_buttons, 'selected': bool(cand.selected), 'business_fingerprint': cand.business_fingerprint, 'fingerprint_strength': cand.fingerprint_strength, 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 de2c3e70..341233eb 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 @@ -132,6 +132,8 @@ class CoordinateHeaderFieldRegionSuggestion(CoordinateReconstructionModel): region: LayoutBBox text: str = '' + field_code: str | None = None + confidence: Literal['exact_alias', 'ambiguous', 'unmapped'] = 'unmapped' class HeaderFieldSuggestion(CoordinateReconstructionModel): 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 new file mode 100644 index 00000000..e288134d --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/order_field_extraction.py @@ -0,0 +1,489 @@ +""" +backend/app/services/shipping_notice/document_layout/order_field_extraction.py + +用途:从冻结的整页 PDF/OCR 字符坐标中确定性提取独立订单级字段。 +依赖:OrderCoordinateProfileV2、冻结 Schema 字段规则和 LayoutBBox。 +逻辑:订单工作流先唯一匹配模板,再调用本模块;本模块仅返回可追溯候选,绝不回读资产、数据库或调用模型。 +""" + +from __future__ import annotations + +import re +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field + +from app.services.shipping_notice.document_layout.contracts import LayoutBBox +from app.services.shipping_notice.document_layout.order_profile import ( + AnchorRelativeRegion, + AnchorRule, + OrderCoordinateProfileV2, + OrderFieldLayout, + RelativeRegion, +) +from app.services.shipping_notice.order_schema.field_rules import ( + normalize_order_field_value, + validate_order_field_value, +) + + +class OrderFieldExtraction(BaseModel): + """表示单个订单字段的脱敏运行期候选及其最小坐标证据。""" + + model_config = ConfigDict(extra='forbid') + + field_id: str + field_code: str + value: Any = None + status: Literal['confirmed', 'needs_review', 'unavailable'] + source: Literal['pdf_coordinate', 'ocr_coordinate'] | None = None + page_no: int | None = Field(default=None, ge=1) + anchor_bbox: LayoutBBox | None = None + value_bbox: LayoutBBox | None = None + glyph_indices: list[int] = Field(default_factory=list) + issues: list[str] = Field(default_factory=list) + + +def extract_order_fields( + *, profile: OrderCoordinateProfileV2, schema_fields: dict[str, dict[str, Any]], + coordinate_evidence: dict[str, Any], +) -> list[OrderFieldExtraction]: + """ + 用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。 + + Args: + profile: Run 冻结的 v2 坐标模板,不得包含待重新绑定字段。 + schema_fields: 以 stable field_id 为键的冻结启用 Schema 字段。 + coordinate_evidence: 冻结页尺寸、page_glyphs 与来源;不接受表格内 glyph 兜底。 + + Returns: + 每个已绑定布局对应一个候选,按模板声明顺序返回。 + """ + return [ + _extract_layout(layout=layout, schema_fields=schema_fields, coordinate_evidence=coordinate_evidence) + for layout in profile.order_field_layouts + ] + + +def _extract_layout( + *, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any], +) -> OrderFieldExtraction: + """处理一个订单字段布局,并把任何不确定性保留为 Review/Unavailable 而非猜测。""" + config = schema_fields.get(layout.field_id) + if config is None or not config.get('enabled', True) or config.get('scope') != 'header': + return _unavailable(layout, 'order_field_schema_binding_invalid') + pages = coordinate_evidence.get('pages') if isinstance(coordinate_evidence.get('pages'), dict) else {} + glyph_pages = coordinate_evidence.get('page_glyphs') if isinstance(coordinate_evidence.get('page_glyphs'), dict) else {} + sources = coordinate_evidence.get('sources') if isinstance(coordinate_evidence.get('sources'), dict) else {} + page_sources = sources.get('pages') if isinstance(sources.get('pages'), dict) else {} + candidates: list[tuple[int, list[dict[str, Any]], float, float, str]] = [] + 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 + if not _layout_applies_to_page(layout, page_no) or width <= 0 or height <= 0: + continue + glyphs = glyph_pages.get(str(page_no)) + source = str(page_sources.get(str(page_no)) or '') + if isinstance(glyphs, list) and source in {'pdf_coordinate', 'ocr_coordinate'}: + valid_glyphs = [] + for item in glyphs: + if not isinstance(item, dict): + continue + try: + _glyph_bbox(item) + except Exception: + continue + valid_glyphs.append(item) + candidates.append((page_no, valid_glyphs, width, height, source)) + if not candidates: + return _unavailable(layout, 'order_field_page_coordinate_evidence_missing') + + results: list[OrderFieldExtraction] = [] + for page_no, glyphs, width, height, source in candidates: + if not _source_allowed(layout, config=config, source=source): + results.append(_unavailable(layout, 'order_field_coordinate_source_not_allowed', page_no=page_no, source=source)) + continue + if layout.anchor is None: + results.append(_read_value_region( + layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source, + region=_absolute_relative_region(layout.fallback_value_region, width=width, height=height), anchor_bbox=None, + fallback=True, + )) + continue + matches = _find_anchor_matches(glyphs, layout.anchor, page_width=width, page_height=height) + if not matches: + reference_anchor = ( + _anchor_from_reference_region( + glyphs, anchor=layout.anchor, page_width=width, page_height=height, + ) + if _is_placeholder_anchor_text(layout.anchor.text) else None + ) + if reference_anchor is not None: + # Legacy manual regions can contain a placeholder label rather than + # the PDF text. The reference box is evidence of administrator + # intent, but it must remain review-only until the label is fixed. + results.append(_read_value_region( + layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source, + region=_absolute_anchor_region(layout.value_region, reference_anchor), + anchor_bbox=reference_anchor, fallback=False, + review_issue='order_field_anchor_text_mismatch', + )) + continue + results.append(_unavailable(layout, 'order_field_anchor_missing', page_no=page_no, source=source)) + continue + if len(matches) != 1: + results.append(OrderFieldExtraction( + field_id=layout.field_id, field_code=layout.field_code, status='needs_review', source=source, + page_no=page_no, issues=['order_field_anchor_ambiguous'], + )) + continue + anchor_bbox, _indices = matches[0] + results.append(_read_value_region( + layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source, + region=_absolute_anchor_region(layout.value_region, anchor_bbox), anchor_bbox=anchor_bbox, fallback=False, + )) + usable = [item for item in results if item.status != 'unavailable'] + if len(usable) == 1: + return usable[0] + if not usable: + return results[0] if results else _unavailable(layout, 'order_field_page_coordinate_evidence_missing') + values = {repr(item.value) for item in usable if item.value is not None} + # Repeated page headers are corroborating evidence, not a second business value. + # An ambiguous value on any selected page must still stop automatic acceptance. + if len(values) == 1 and not any(item.status == 'needs_review' for item in usable): + return usable[0] + first = usable[0].model_copy(deep=True) + first.status = 'needs_review' + first.issues = sorted(set(first.issues + ['order_field_page_value_conflict'])) + return first + + +def _read_value_region( + *, layout: OrderFieldLayout, config: dict[str, Any], glyphs: list[dict[str, Any]], page_no: int, + source: str, region: LayoutBBox, anchor_bbox: LayoutBBox | None, fallback: bool, + review_issue: str | None = None, +) -> OrderFieldExtraction: + """按视觉行合并值区文字,多行模式先以停止标签截断,再执行 Schema 规范化与校验。 + + ``right_of_anchor`` 使用锚点右侧的同一连续文本段,而不是严格依赖值框的 + 左边界;这能避免标签后的冒号进入值,也能容忍框选末尾少量字符。 + """ + selected = ( + _inline_right_of_anchor_glyphs(glyphs=glyphs, anchor_bbox=anchor_bbox, region=region) + if layout.value_mode == 'right_of_anchor' and anchor_bbox is not None + else [(index, item) for index, item in enumerate(glyphs) if _glyph_center_inside(item, region)] + ) + if layout.value_mode == 'multi_line': + selected = _stop_before_anchor( + selected, glyphs=glyphs, stop_anchors=layout.stop_anchors, anchor_bbox=anchor_bbox, + ) + text = _render_value(selected, multi_line=layout.value_mode == 'multi_line') + if layout.value_mode != 'multi_line': + text = text.split('\n', 1)[0].strip() + if layout.value_mode == 'right_of_anchor': + text = text.lstrip(':: ').strip() + if str(config.get('value_type') or '') == 'date': + text = _recover_trailing_date_glyph(text=text, glyphs=glyphs, region=region) + if not text: + return _unavailable(layout, 'order_field_value_missing', page_no=page_no, source=source, anchor_bbox=anchor_bbox, value_bbox=region) + try: + value = normalize_order_field_value(text, config) + except Exception: + return _review(layout, 'order_field_normalization_failed', page_no, source, anchor_bbox, region, selected) + if value is None or not validate_order_field_value(value, config): + return _review(layout, 'order_field_validation_failed', page_no, source, anchor_bbox, region, selected) + status: Literal['confirmed', 'needs_review'] = 'needs_review' if fallback or source != 'pdf_coordinate' or review_issue else 'confirmed' + issues = ['order_field_fallback_value_region'] if fallback else [] + if source == 'ocr_coordinate': + issues.append('order_field_ocr_coordinate_needs_review') + if review_issue: + issues.append(review_issue) + return OrderFieldExtraction( + field_id=layout.field_id, field_code=layout.field_code, value=value, status=status, source=source, + page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=region, + glyph_indices=[index for index, _item in selected], issues=issues, + ) + + +def _inline_right_of_anchor_glyphs( + *, glyphs: list[dict[str, Any]], anchor_bbox: LayoutBBox, region: LayoutBBox, +) -> list[tuple[int, dict[str, Any]]]: + """读取值框内标签右侧的文本,仅在框尾补齐被截断的同一个词。 + + 管理员的值框是字段分隔的主证据,不能按整行连续文本扩展。仅当框尾 + 截在英文/数字词中间时,才追加紧邻字符直至一个正常词间隔;这不会吞入 + 下一个字段,即使两个字段落在同一视觉行。 + + Args: + glyphs: 当前页面冻结的字符坐标。 + anchor_bbox: 已唯一定位的标签字符联合框。 + region: 管理员配置的相对值区投影框。 + + Returns: + 值框内文本及其被截断的当前词的原始 glyph 索引和字符。 + """ + anchor_center_y = (anchor_bbox.y0 + anchor_bbox.y1) / 2 + same_line = [ + (index, glyph) for index, glyph in enumerate(glyphs) + if _glyph_bbox(glyph).x0 >= anchor_bbox.x1 + and region.y0 <= (_glyph_bbox(glyph).y0 + _glyph_bbox(glyph).y1) / 2 <= region.y1 + and abs(((_glyph_bbox(glyph).y0 + _glyph_bbox(glyph).y1) / 2) - anchor_center_y) + <= max(anchor_bbox.y1 - anchor_bbox.y0, _glyph_bbox(glyph).y1 - _glyph_bbox(glyph).y0) * .55 + ] + ordered = sorted(same_line, key=lambda item: _glyph_bbox(item[1]).x0) + selected = [item for item in ordered if _glyph_center_inside(item[1], region)] + if not selected: + return [] + last_position = next( + (position for position in range(len(ordered) - 1, -1, -1) if ordered[position][0] == selected[-1][0]), + -1, + ) + previous = _glyph_bbox(selected[-1][1]) + for item in ordered[last_position + 1:]: + bbox = _glyph_bbox(item[1]) + typical_width = max((previous.x1 - previous.x0 + bbox.x1 - bbox.x0) / 2, .01) + # A normal word gap terminates the only permitted overrun. This admits + # ``Corporati`` -> ``Corporation`` but not a following address/field. + if bbox.x0 - previous.x1 > typical_width * .75: + break + selected.append(item) + previous = bbox + return selected + + +def _recover_trailing_date_glyph(*, text: str, glyphs: list[dict[str, Any]], region: LayoutBBox) -> str: + """补入紧贴日期值框右缘的单个数字,容忍管理员框选少一个字宽但不扩展到下一字段。""" + compact = re.sub(r'\s+', '', text) + if not re.fullmatch(r'(?:\d{4}[-/.]\d{1,2}[-/.]\d{1,2}|\d{1,2}[-/.]\d{1,2}[-/.]\d{1,3})', compact): + return text + candidates = [] + for glyph in glyphs: + try: + bbox = _glyph_bbox(glyph) + except Exception: + continue + if not str(glyph.get('text') or '').isdigit() or bbox.y1 < region.y0 or bbox.y0 > region.y1: + continue + glyph_width = max(bbox.x1 - bbox.x0, .01) + if 0 <= bbox.x0 - region.x1 <= glyph_width * 1.5: + candidates.append((bbox.x0, str(glyph.get('text') or ''))) + if len(candidates) != 1: + return text + return f'{text}{candidates[0][1]}' + + +def _find_anchor_matches( + glyphs: list[dict[str, Any]], anchor: AnchorRule, *, page_width: float | None = None, page_height: float | None = None, +) -> list[tuple[LayoutBBox, list[int]]]: + """在每个视觉行内执行精确标签匹配,返回去重后的字符联合框。""" + expected = [anchor.text, *anchor.aliases] + matches: list[tuple[LayoutBBox, list[int]]] = [] + for row in _visual_rows(list(enumerate(glyphs))): + # PDFium does not emit whitespace glyphs consistently, so labels are compared + # after whitespace folding while preserving a mapping back to real characters. + compact: list[tuple[int, dict[str, Any]]] = [ + pair for pair in row if str(pair[1].get('text') or '').strip() + ] + row_text = ''.join(str(item.get('text') or '') for _index, item in compact) + folded = row_text.casefold() + for label in expected: + normalized = re.sub(r'\s+', '', label).casefold() + start = 0 + while normalized and (position := folded.find(normalized, start)) >= 0: + consumed = compact[position:position + len(normalized)] + if len(consumed) == len(normalized) and _anchor_occurrence_is_exact( + compact, position=position, length=len(normalized), anchor=anchor, + ): + bbox = _union_bbox([item for _index, item in consumed]) + if _anchor_bbox_in_reference_region( + bbox, anchor=anchor, page_width=page_width, page_height=page_height, + ): + matches.append((bbox, [index for index, _item in consumed])) + start = position + max(len(label), 1) + unique: dict[tuple[float, float, float, float], tuple[LayoutBBox, list[int]]] = {} + for bbox, indices in matches: + unique[(bbox.x0, bbox.y0, bbox.x1, bbox.y1)] = (bbox, indices) + return list(unique.values()) + + +def _anchor_occurrence_is_exact( + row: list[tuple[int, dict[str, Any]]], *, position: int, length: int, anchor: AnchorRule, +) -> bool: + """精确模式拒绝嵌入其他字母数字串的标签,contains 模式才允许局部命中。""" + if anchor.match_mode != 'exact': + return True + before = row[position - 1][1] if position else None + first = row[position][1] + last = row[position + length - 1][1] + after = row[position + length][1] if position + length < len(row) else None + return not ( + (before is not None and str(before.get('text') or '').isalnum() and not _glyph_gap_is_word_boundary(before, first)) + or (after is not None and str(after.get('text') or '').isalnum() and not _glyph_gap_is_word_boundary(last, after)) + ) + + +def _glyph_gap_is_word_boundary(left: dict[str, Any], right: dict[str, Any]) -> bool: + """PDFium 常省略空白 glyph;相邻字符间的大间隔仍视为精确标签的词边界。""" + left_bbox, right_bbox = _glyph_bbox(left), _glyph_bbox(right) + typical_width = max(((left_bbox.x1 - left_bbox.x0) + (right_bbox.x1 - right_bbox.x0)) / 2, 0.01) + return right_bbox.x0 - left_bbox.x1 > typical_width * 0.75 + + +def _anchor_bbox_in_reference_region( + bbox: LayoutBBox, *, anchor: AnchorRule, page_width: float | None, page_height: float | None, +) -> bool: + """锚点配置了参考区时只接受该页相对位置内的命中,避免页眉重复标签干扰。""" + if anchor.region is None: + return True + if page_width is None or page_height is None or page_width <= 0 or page_height <= 0: + return False + region = _absolute_relative_region(anchor.region, width=page_width, height=page_height) + return _glyph_center_inside({'bbox': bbox.model_dump(mode='json')}, region) + + +def _anchor_from_reference_region( + glyphs: list[dict[str, Any]], *, anchor: AnchorRule, page_width: float, page_height: float, +) -> LayoutBBox | None: + """为历史占位标签保留参考框内的实际标签几何,且调用方必须降级为人工复核。""" + if anchor.region is None: + return None + region = _absolute_relative_region(anchor.region, width=page_width, height=page_height) + selected = [glyph for glyph in glyphs if _glyph_center_inside(glyph, region)] + return _union_bbox(selected) if selected else None + + +def _is_placeholder_anchor_text(value: str) -> bool: + """仅兼容工作台历史默认名;任何管理员自定义标签不匹配时仍必须失败关闭。""" + return re.fullmatch(r'订单字段标签\s*\d*', value.strip()) is not None + + +def _stop_before_anchor( + selected: list[tuple[int, dict[str, Any]]], *, glyphs: list[dict[str, Any]], stop_anchors: list[AnchorRule], + anchor_bbox: LayoutBBox | None, +) -> list[tuple[int, dict[str, Any]]]: + """多行值仅在当前锚点之后遇到首个停止标签时截断,避免页眉同名标签误伤。""" + stop_y: float | None = None + for anchor in stop_anchors: + for bbox, _indices in _find_anchor_matches(glyphs, anchor): + if anchor_bbox is not None and bbox.y0 <= anchor_bbox.y1: + continue + stop_y = bbox.y0 if stop_y is None else min(stop_y, bbox.y0) + return selected if stop_y is None else [item for item in selected if _glyph_bbox(item[1]).y0 < stop_y] + + +def _render_value(selected: list[tuple[int, dict[str, Any]]], *, multi_line: bool) -> str: + """按 y 聚类、x 排序渲染字符,保留多行字段的换行而不伪造空格。""" + rows = _visual_rows(selected) + rendered = [_render_visual_row(row) for row in rows] + return ('\n' if multi_line else ' ').join(item for item in rendered if item).strip() + + +def _render_visual_row(row: list[tuple[int, dict[str, Any]]]) -> str: + """以字距推断缺失的 PDF 空白;仅大于常规字符间隔时补一个普通空格。""" + rendered: list[str] = [] + previous: LayoutBBox | None = None + for _index, glyph in row: + bbox = _glyph_bbox(glyph) + if previous is not None: + typical_width = max((previous.x1 - previous.x0 + bbox.x1 - bbox.x0) / 2, 0.01) + if bbox.x0 - previous.x1 > typical_width * 0.75: + rendered.append(' ') + rendered.append(str(glyph.get('text') or '')) + previous = bbox + return ''.join(rendered).strip() + + +def _visual_rows(items: list[tuple[int, dict[str, Any]]]) -> list[list[tuple[int, dict[str, Any]]]]: + """将 bbox 中心 y 接近的字符归为视觉行,避免扫描页的微小坐标抖动拆行。""" + rows: list[list[tuple[int, dict[str, Any]]]] = [] + for item in sorted(items, key=lambda pair: (_glyph_bbox(pair[1]).y0, _glyph_bbox(pair[1]).x0)): + bbox = _glyph_bbox(item[1]) + if rows: + previous = rows[-1] + reference = _glyph_bbox(previous[0][1]) + tolerance = max((reference.y1 - reference.y0), (bbox.y1 - bbox.y0)) * 0.55 + if abs(((bbox.y0 + bbox.y1) / 2) - ((reference.y0 + reference.y1) / 2)) <= tolerance: + previous.append(item) + continue + rows.append([item]) + return [sorted(row, key=lambda pair: _glyph_bbox(pair[1]).x0) for row in rows] + + +def _layout_applies_to_page(layout: OrderFieldLayout, page_no: int) -> bool: + """执行订单字段页域;后续页重复值只在 all_pages 明确声明时作为冲突证据读取。""" + return ( + (layout.page_scope == 'first_page' and page_no == 1) + or layout.page_scope == 'all_pages' + or (layout.page_scope == 'exact_page' and page_no == layout.page_no) + ) + + +def _source_allowed(layout: OrderFieldLayout, *, config: dict[str, Any], source: str) -> bool: + """同时满足布局和 Schema 的坐标来源授权,OCR 永远不提升为 confirmed。""" + allowed = set(config.get('allowed_sources') or []) + if source not in allowed: + return False + required_levels = [layout.minimum_evidence_level] + if layout.anchor is not None: + required_levels.append(layout.anchor.minimum_evidence_level) + return not ('coordinate' in required_levels and source != 'pdf_coordinate') + + +def _absolute_relative_region(region: RelativeRegion | None, *, width: float, height: float) -> LayoutBBox: + """将固定低可靠度归一化页区投影为当前页面绝对框。""" + if region is None: + raise ValueError('fallback order field region is required') + return LayoutBBox(x0=region.x0 * width, y0=region.y0 * height, x1=region.x1 * width, y1=region.y1 * height) + + +def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutBBox) -> LayoutBBox: + """用标签框宽高投影相对值区,使整页平移或缩放不改变读取关系。""" + if region is None: + raise ValueError('anchored order field region is required') + width, height = anchor.x1 - anchor.x0, anchor.y1 - anchor.y0 + return LayoutBBox( + x0=anchor.x0 + region.x0 * width, y0=anchor.y0 + region.y0 * height, + x1=anchor.x0 + region.x1 * width, y1=anchor.y0 + region.y1 * height, + ) + + +def _glyph_bbox(glyph: dict[str, Any]) -> LayoutBBox: + """严格解析一枚冻结 glyph 的 bbox;坏坐标不会被修正后参与提取。""" + return LayoutBBox.model_validate(glyph.get('bbox')) + + +def _glyph_center_inside(glyph: dict[str, Any], region: LayoutBBox) -> bool: + """判断字符中心是否处于值区,边界字符仍归属到管理员确认的区域。""" + try: + bbox = _glyph_bbox(glyph) + except Exception: + return False + return region.x0 <= (bbox.x0 + bbox.x1) / 2 <= region.x1 and region.y0 <= (bbox.y0 + bbox.y1) / 2 <= region.y1 + + +def _union_bbox(glyphs: list[dict[str, Any]]) -> LayoutBBox: + """求连续标签字符的最小联合框,作为相对值区投影的唯一参考。""" + boxes = [_glyph_bbox(item) for item in glyphs] + return LayoutBBox(x0=min(item.x0 for item in boxes), y0=min(item.y0 for item in boxes), x1=max(item.x1 for item in boxes), y1=max(item.y1 for item in boxes)) + + +def _unavailable( + layout: OrderFieldLayout, issue: str, *, page_no: int | None = None, source: str | None = None, + anchor_bbox: LayoutBBox | None = None, value_bbox: LayoutBBox | None = None, +) -> OrderFieldExtraction: + """构造无可用坐标证据的失败关闭结果。""" + return OrderFieldExtraction(field_id=layout.field_id, field_code=layout.field_code, status='unavailable', source=source, page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=value_bbox, issues=[issue]) + + +def _review( + layout: OrderFieldLayout, issue: str, page_no: int, source: str, anchor_bbox: LayoutBBox | None, + value_bbox: LayoutBBox, selected: list[tuple[int, dict[str, Any]]], +) -> OrderFieldExtraction: + """构造带最小证据索引的人工复核候选。""" + return OrderFieldExtraction( + field_id=layout.field_id, field_code=layout.field_code, status='needs_review', source=source, + page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=value_bbox, + glyph_indices=[index for index, _item in selected], issues=[issue], + ) 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 8cee7c0e..b328a3f6 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile.py @@ -62,15 +62,82 @@ class RelativeRegion(OrderProfileModel): return self +class AnchorRelativeRegion(OrderProfileModel): + """表示相对锚点框宽高的值区偏移;允许标签右侧或下方落在锚点外。""" + + # Address values can be much wider than short labels such as "BILL TO". + # Keep a finite bound while accepting the deterministic suggestion geometry. + x0: float = Field(ge=-12, le=12) + y0: float = Field(ge=-12, le=12) + x1: float = Field(ge=-12, le=12) + y1: float = Field(ge=-12, le=12) + + @model_validator(mode='after') + def validate_area(self) -> 'AnchorRelativeRegion': + """拒绝零面积和反向偏移区域,确保运行期投影只有一个解释。""" + if self.x0 >= self.x1 or self.y0 >= self.y1: + raise ValueError('anchor-relative region must have positive area') + return self + + class AnchorRule(OrderProfileModel): """定义模板匹配或行启动使用的稳定静态文字锚点。""" anchor_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$') text: str = Field(min_length=1, max_length=160) + aliases: list[str] = Field(default_factory=list, max_length=16) match_mode: Literal['exact', 'contains'] = 'contains' region: RelativeRegion | None = None minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate' + @model_validator(mode='after') + def validate_aliases(self) -> 'AnchorRule': + """只接受有限、去重的精确别名,避免把模糊词表当作自由匹配规则。""" + aliases = [item.strip() for item in self.aliases] + if any(not item for item in aliases) or len({item.casefold() for item in aliases}) != len(aliases): + raise ValueError('anchor aliases must be non-empty and unique') + if self.text.casefold() in {item.casefold() for item in aliases}: + raise ValueError('anchor aliases must not repeat anchor text') + return self + + +class OrderFieldLayout(OrderProfileModel): + """定义独立订单级字段的锚点和值区;它绝不属于表头或物理明细行。""" + + layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$') + field_id: str = Field(min_length=1, max_length=128) + field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$') + page_scope: Literal['first_page', 'all_pages', 'exact_page'] = 'first_page' + page_no: int | None = Field(default=None, ge=1) + anchor: AnchorRule | None = None + # Anchored values use offsets relative to the anchor bbox; fixed-position + # fallback values are stored separately so they cannot be mistaken for anchors. + value_region: AnchorRelativeRegion | None = None + fallback_value_region: RelativeRegion | None = None + value_mode: Literal['single_line', 'multi_line', 'right_of_anchor', 'below_anchor'] = 'single_line' + stop_anchors: list[AnchorRule] = Field(default_factory=list) + normalizer_key: str | None = Field(default=None, min_length=1, max_length=64) + required: bool = False + minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate' + + @model_validator(mode='after') + def validate_order_field_layout(self) -> 'OrderFieldLayout': + """限制无锚点回退为单页值区,并要求多行字段有明确停止证据。""" + if self.page_scope == 'exact_page' and self.page_no is None: + raise ValueError('exact_page order field requires page_no') + if self.page_scope != 'exact_page' and self.page_no is not None: + raise ValueError('page_no is only allowed for exact_page order field') + if self.anchor is None: + if self.page_scope == 'all_pages': + raise ValueError('value-only order field must have a bounded page scope') + if self.value_region is not None or self.fallback_value_region is None: + raise ValueError('value-only order field requires one fallback value region') + elif self.value_region is None or self.fallback_value_region is not None: + raise ValueError('anchored order field requires one anchor-relative value region') + if self.value_mode == 'multi_line' and not self.stop_anchors: + raise ValueError('multi-line order field requires stop anchors') + return self + class FieldRegion(OrderProfileModel): """将一个管理员确认的坐标区域绑定至稳定 Schema field_code。""" @@ -141,12 +208,40 @@ class TerminationRule(OrderProfileModel): class DraftUnboundFieldRegion(OrderProfileModel): - """草稿阶段尚未绑定 Schema 的字段框;运行和发布均不得使用。""" + """草稿阶段尚未绑定 Schema 的字段框;仅迁移遗留项要求重新绑定。""" region_id: str = Field(pattern=r'^[a-z][a-z0-9_-]{0,95}$') parent_layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$') label: str = Field(min_length=1, max_length=160) region: RelativeRegion + requires_rebinding: bool = False + + +class DraftUnboundOrderFieldLayout(OrderProfileModel): + """Schema 迁移后暂失绑定的订单字段区域;保留证据布局但禁止发布或运行。""" + + layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$') + label: str = Field(min_length=1, max_length=160) + page_scope: Literal['first_page', 'all_pages', 'exact_page'] = 'first_page' + page_no: int | None = Field(default=None, ge=1) + anchor: AnchorRule | None = None + value_region: AnchorRelativeRegion | None = None + fallback_value_region: RelativeRegion | None = None + value_mode: Literal['single_line', 'multi_line', 'right_of_anchor', 'below_anchor'] = 'single_line' + stop_anchors: list[AnchorRule] = Field(default_factory=list) + minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate' + + @model_validator(mode='after') + def validate_unbound_order_field_layout(self) -> 'DraftUnboundOrderFieldLayout': + """复用订单字段的区域互斥与页作用域规则,避免迁移草稿保存坏坐标。""" + OrderFieldLayout( + layout_id=self.layout_id, field_id='draft_unbound', field_code='draft_unbound', + page_scope=self.page_scope, page_no=self.page_no, anchor=self.anchor, + value_region=self.value_region, fallback_value_region=self.fallback_value_region, + value_mode=self.value_mode, stop_anchors=self.stop_anchors, + minimum_evidence_level=self.minimum_evidence_level, + ) + return self class TableRegionProfile(OrderProfileModel): @@ -230,6 +325,8 @@ class OrderCoordinateProfileV2(OrderProfileModel): version: int = Field(ge=1) document_match: DocumentMatchProfile 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) @model_validator(mode='after') def validate_profile_rules(self) -> 'OrderCoordinateProfileV2': @@ -246,6 +343,15 @@ class OrderCoordinateProfileV2(OrderProfileModel): for table in self.table_regions: if not set(table.continuation_rule.required_anchor_ids).issubset(anchor_ids): raise ValueError('cross-page continuation anchor must be a document match anchor') + order_layout_ids = [item.layout_id for item in self.order_field_layouts] + if len(order_layout_ids) != len(set(order_layout_ids)): + raise ValueError('order field layout ids must be unique') + order_field_codes = [item.field_code for item in self.order_field_layouts] + if len(order_field_codes) != len(set(order_field_codes)): + raise ValueError('order field may bind only once') + unbound_ids = [item.layout_id for item in self.draft_unbound_order_field_layouts] + if len(unbound_ids) != len(set(unbound_ids)) or set(unbound_ids) & set(order_layout_ids): + raise ValueError('bound and unbound order field layout ids must be unique') return self 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 7a95b261..ebb497a8 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 @@ -45,6 +45,7 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout: tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)] 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 {} if not tables or not pages or not glyph_tables: return ProfileMatchResult(status='evidence_insufficient') @@ -57,6 +58,7 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout: profile = OrderCoordinateProfileV2( profile_code=str(raw.get('profile_code') or ''), version=int(raw.get('version') or 0), document_match=definition.get('document_match'), table_regions=definition.get('table_regions'), + order_field_layouts=definition.get('order_field_layouts') or [], ) except (TypeError, ValueError): continue @@ -64,11 +66,15 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout: if len(tables) < len(profile.table_regions): reasons.append('table_region_count_insufficient') required = profile.document_match.required_anchors - required_hits = [_anchor_present(anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, pages=pages) for anchor in required] + required_hits = [_anchor_present( + anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, + ) for anchor in required] if not all(required_hits): reasons.append('required_anchor_missing') optional = profile.document_match.optional_anchors - optional_hits = sum(_anchor_present(anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, pages=pages) for anchor in optional) + optional_hits = sum(_anchor_present( + anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, + ) for anchor in optional) hard_match = not reasons # Required evidence is mandatory rather than a soft score. Optional evidence only separates already valid templates. score = 1.0 if not optional else 0.8 + 0.2 * optional_hits / len(optional) @@ -92,14 +98,26 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout: ) -def _anchor_present(anchor: dict[str, Any], *, tables: list[dict[str, Any]], glyph_tables: dict[str, Any], pages: dict[str, Any]) -> bool: - """检查静态锚点是否在指定页面区域出现;不读取订单业务字段或 HTML 网格。""" +def _anchor_present( + anchor: dict[str, Any], *, tables: list[dict[str, Any]], glyph_tables: dict[str, Any], + page_glyphs: dict[str, Any], pages: dict[str, Any], +) -> bool: + """检查静态锚点是否在整页冻结字符中出现;旧快照才受限回退到表内证据。""" expected = str(anchor.get('text') or '').strip() - if not expected: + candidates = [expected, *[str(item).strip() for item in anchor.get('aliases') or []]] + if not expected or not all(candidates): return False - for table in tables: - glyphs = glyph_tables.get(str(table.get('table_id') or '')) - page = pages.get(str(table.get('page_no') or '')) + page_numbers = sorted({str(item.get('page_no') or '') for item in tables if item.get('page_no')}) + for page_no in page_numbers: + glyphs = page_glyphs.get(page_no) + # v1 frozen snapshots do not have page glyphs. Preserve historical matching + # rather than silently invalidating published profiles, but never merge rows here. + if not isinstance(glyphs, list): + glyphs = [ + glyph for table in tables if str(table.get('page_no') or '') == page_no + for glyph in (glyph_tables.get(str(table.get('table_id') or '')) or []) + ] + page = pages.get(page_no) if not isinstance(glyphs, list) or not isinstance(page, dict): continue selected = glyphs @@ -115,8 +133,8 @@ def _anchor_present(anchor: dict[str, Any], *, tables: list[dict[str, Any]], gly and y0 <= (float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 <= y1] text = ''.join(str(item.get('text') or '') for item in sorted(selected, key=lambda item: (item.get('bbox', {}).get('y0', 0), item.get('bbox', {}).get('x0', 0)))) if str(anchor.get('match_mode') or 'contains') == 'exact': - if expected.casefold() == text.casefold(): + if any(candidate.casefold() == text.casefold() for candidate in candidates): return True - elif expected.casefold() in text.casefold(): + elif any(candidate.casefold() in text.casefold() for candidate in candidates): return True return False diff --git a/backend/app/services/shipping_notice/document_layout/runtime.py b/backend/app/services/shipping_notice/document_layout/runtime.py index 39fcd493..c2bd6257 100644 --- a/backend/app/services/shipping_notice/document_layout/runtime.py +++ b/backend/app/services/shipping_notice/document_layout/runtime.py @@ -175,7 +175,7 @@ def build_mineru_table_snapshot( content=content, mineru=candidate, ) snapshot['layout_candidate'] = layout.model_dump(mode='json') - # 仅保存表格范围内的原生字符坐标,供管理员确认后的坐标模板在 Run 冻结快照中复现。 + # 冻结表格与整页字符坐标:明细重建只消费前者,订单级字段只能消费后者。 snapshot['coordinate_evidence'] = _table_coordinate_evidence( content=content, tables=tables, ) @@ -187,7 +187,7 @@ def build_mineru_table_snapshot( def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]]) -> dict[str, Any]: - """保存表内字符和内部页尺寸,使 v2 页面相对坐标可在冻结 Run 中精确换算。""" + """保存表内及整页原生字符和页尺寸,分别供明细与订单级字段确定性重放。""" from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages pages = {item.page_no: item for item in extract_native_pdf_pages(content)} @@ -211,9 +211,34 @@ def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]]) glyphs.append(item.model_dump(mode='json')) if glyphs: evidence[table_id] = glyphs + page_glyphs: dict[str, list[dict[str, Any]]] = {} + page_sources: dict[str, str] = {} + for page_no, page in pages.items(): + native_glyphs = [item.model_dump(mode='json') for item in page.characters] + if native_glyphs: + page_glyphs[str(page_no)] = native_glyphs + page_sources[str(page_no)] = 'pdf_coordinate' + continue + # Only scanned pages without a usable native text layer trigger OCR. OCR failure + # intentionally leaves this page without order-field evidence rather than guessing. + try: + from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines + + ocr_lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height) + ocr_glyphs = _ocr_page_characters(ocr_lines) + except Exception: + ocr_glyphs = [] + if ocr_glyphs: + page_glyphs[str(page_no)] = ocr_glyphs + page_sources[str(page_no)] = 'ocr_coordinate' return { 'version': 'shipping_order_coordinate_evidence.v1', 'tables': evidence, + # 订单字段锚点可能位于表格外;只保存同一冻结 PDF 的最小字符证据,不向 Dify 暴露。 + 'page_glyphs': page_glyphs, + 'sources': { + 'pages': page_sources, + }, # Internal runtime metadata only. It is removed with layout_snapshot before Dify input. 'pages': { str(page_no): {'width': page.width, 'height': page.height} @@ -222,6 +247,29 @@ def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]]) } +def _ocr_page_characters(lines: list[Any]) -> list[dict[str, Any]]: + """把整页 OCR 行均匀拆成字符证据;仅服务订单字段锚点,不参与表格 cell 自动接受。""" + result: list[dict[str, Any]] = [] + source_index = 0 + for line in lines: + text = str(getattr(line, 'text', '') or '').strip() + bbox = getattr(line, 'bbox', None) + if not text or bbox is None: + continue + width = (bbox.x1 - bbox.x0) / len(text) + if width <= 0: + continue + for index, character in enumerate(text): + if character.isspace(): + continue + result.append({'text': character, 'source_index': source_index, 'bbox': { + 'x0': bbox.x0 + index * width, 'y0': bbox.y0, + 'x1': bbox.x0 + (index + 1) * width, 'y1': bbox.y1, + }}) + source_index += 1 + return result + + def attach_mineru_layout_snapshots(result: Any, *, root_asset_bytes: bytes | None = None) -> None: """就地为 NoticeIntakeResult 的根文件或 EML 附件补充布局快照,失败不阻断文本解析。""" meta = result.meta if isinstance(getattr(result, 'meta', None), dict) else {} diff --git a/backend/app/services/shipping_notice/document_profile_quality_service.py b/backend/app/services/shipping_notice/document_profile_quality_service.py index 25f20607..38f1ddd2 100644 --- a/backend/app/services/shipping_notice/document_profile_quality_service.py +++ b/backend/app/services/shipping_notice/document_profile_quality_service.py @@ -3,12 +3,13 @@ services/shipping_notice/document_profile_quality_service.py 用途:治理订单文档 Profile 的盲测样本、执行结果和确定性自动建单资格。 依赖:Profile 服务、MinerU 当前布局快照、Profile 纯解析器与质量 ORM 模型。 -逻辑:管理员先固化独立样本的期望行,服务按冻结 Profile 执行比对;至少三份样本全部通过并批准后才放行自动建单。 +逻辑:管理员先固化一份独立样本的期望行,服务按冻结 Profile 执行比对;样本通过并批准后才放行自动建单。 """ from __future__ import annotations from datetime import datetime +from decimal import Decimal from typing import Any from app import db @@ -18,7 +19,9 @@ from app.models import ( ShippingDocumentProfileTestSample, ShippingDocumentProfileTestSuite, ShippingNoticeDocument, + ShippingNoticeIntake, ShippingOrderDocumentProfile, + ShippingOrderDocumentProfileSample, ) from app.services.shipping_notice.document_layout.html_table import parse_html_grid from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot @@ -28,12 +31,20 @@ from app.services.shipping_notice.document_layout.order_profile import ( reconstruct_order_profile_html, ) from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows -from app.services.shipping_notice.order_document_profile_service import _audit, _definition_contract +from app.services.shipping_notice.document_layout.order_field_extraction import ( + _is_placeholder_anchor_text, extract_order_fields, +) +from app.services.shipping_notice.order_document_profile_service import ( + _audit, _definition_contract, _ensure_page_coordinate_evidence, +) from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract +from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value -MINIMUM_BLIND_SAMPLES = 3 -HEADERLESS_MINIMUM_BLIND_SAMPLES = 5 +# 日常模板维护采用一份独立样本门槛;字段 confirmed、人工真值一致、 +# 多明细和声明的跨页覆盖等质量门禁仍然生效。 +MINIMUM_BLIND_SAMPLES = 1 +HEADERLESS_MINIMUM_BLIND_SAMPLES = 1 def _quality_checksum(profile: ShippingOrderDocumentProfile) -> str: @@ -101,6 +112,76 @@ def _coordinate_table_available(document_id: int, table_id: str) -> bool: ) +def _ensure_order_field_evidence( + *, document: ShippingNoticeDocument, layout: dict[str, Any], parser: OrderCoordinateProfileV2, +) -> dict[str, Any]: + """补齐模板订单字段涉及页面的整页字符坐标;表内坐标不能替代锚点证据。""" + required_pages: set[int] = set() + pages = (layout.get('coordinate_evidence') or {}).get('pages') if isinstance(layout.get('coordinate_evidence'), dict) else {} + known_pages = {int(page_no) for page_no in (pages or {}) if str(page_no).isdigit()} + for field in parser.order_field_layouts: + if field.page_scope == 'exact_page' and field.page_no: + required_pages.add(field.page_no) + elif field.page_scope == 'first_page': + required_pages.add(1) + else: + required_pages.update(known_pages) + for page_no in sorted(required_pages): + layout = _ensure_page_coordinate_evidence(document=document, layout=layout, page_no=page_no) + return layout + + +def _has_matching_key_order_field( + *, parser: OrderCoordinateProfileV2, schema_fields: dict[str, dict[str, Any]], layout: dict[str, Any], +) -> bool: + """筛除没有任何真实订单锚点命中的异版样本,避免盲测页面只展示 unavailable。""" + key_layouts = [ + item for item in parser.order_field_layouts + if item.anchor is not None and not _is_placeholder_anchor_text(item.anchor.text) + ] + if not key_layouts: + # Historical templates that only have manually named anchors retain the + # existing compatibility path; their evidence remains needs_review. + return True + extracted = { + item.field_code: item + for item in extract_order_fields( + profile=parser, schema_fields=schema_fields, + coordinate_evidence=layout.get('coordinate_evidence') or {}, + ) + } + return any( + extracted.get(item.field_code) is not None + and extracted[item.field_code].status != 'unavailable' + for item in key_layouts + ) + + +def _order_field_quality_failures( + *, parser: OrderCoordinateProfileV2, schema_fields: dict[str, dict[str, Any]], layout: dict[str, Any], + expected_values: dict[str, Any], sample_id: int, +) -> list[str]: + """将订单字段的坐标/格式状态纳入盲测;任何非 confirmed 结果都不能成为发布依据。""" + if not parser.order_field_layouts: + return [] + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + failures: list[str] = [] + for candidate in extract_order_fields( + profile=parser, schema_fields=schema_fields, coordinate_evidence=evidence, + ): + if candidate.status != 'confirmed': + failures.append(f'sample:{sample_id}:order_field:{candidate.field_code}:{candidate.status}') + else: + config = schema_fields.get(candidate.field_id) + try: + expected = normalize_order_field_value(expected_values.get(candidate.field_code), config or {}) + except Exception: + expected = None + if candidate.value != expected: + failures.append(f'sample:{sample_id}:order_field:{candidate.field_code}:mismatch') + return failures + + def _expected_rows(raw: Any) -> list[dict[str, Any]]: """校验人工录入的盲测真值,只接受行字段字典且不允许空集合。""" if not isinstance(raw, list) or not raw or any(not isinstance(item, dict) or not item for item in raw): @@ -108,24 +189,219 @@ def _expected_rows(raw: Any) -> list[dict[str, Any]]: return [dict(item) for item in raw] +def _expected_order_fields(raw: Any, *, parser: Any) -> dict[str, Any]: + """校验订单字段盲测真值;有订单布局时要求按 stable field_code 提供完整映射。""" + layouts = parser.order_field_layouts if isinstance(parser, OrderCoordinateProfileV2) else [] + if not layouts: + return {} + if not isinstance(raw, dict): + raise ValidationError('expected_order_fields is required for order field layouts', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID') + expected_codes = {item.field_code for item in layouts} + if set(raw) != expected_codes or any(value in (None, '') for value in raw.values()): + raise ValidationError('expected_order_fields must contain every configured order field', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID') + return dict(raw) + + +def _candidate_for_sample( + *, profile: ShippingOrderDocumentProfile, document_id: int, table_id: str, +) -> dict[str, Any]: + """运行当前 Profile 并返回供盲测复核的脱敏字段候选,不写入任何真值或执行记录。""" + parser = _definition_contract(profile) + document = db.session.get(ShippingNoticeDocument, int(document_id)) + layout = current_layout_snapshot(document) if document is not None else None + if document is None or not layout: + raise NotFoundError('Order document test sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') + if isinstance(parser, OrderCoordinateProfileV2): + layout = _ensure_order_field_evidence(document=document, layout=layout, parser=parser) + if not _coordinate_table_available(document_id, table_id): + raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') + schema_fields = { + str(item.get('field_id') or ''): item + for item in (profile.schema_version.definition_json or {}).get('fields') or [] + if isinstance(item, dict) and item.get('enabled', True) + } + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + raw_table = next(( + item for item in layout.get('tables') or [] + if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id) + ), None) + pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} + page = pages.get(str((raw_table or {}).get('page_no') or '')) + characters = (evidence.get('tables') or {}).get(str(table_id)) + if not isinstance(raw_table, dict) or not isinstance(page, dict) or not isinstance(characters, list): + raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') + try: + table_bbox = {'x0': 0, 'y0': 0, 'x1': float(page['width']), 'y1': float(page['height'])} + except (KeyError, TypeError, ValueError) as exc: + raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc + rows: list[dict[str, Any]] = [] + for region in parser.table_regions: + # Header-only pages can carry order fields without a physical line + # layout. They are valid template regions, but cannot reconstruct rows. + if not region.line_layouts: + continue + rows.extend(item.fields for item in reconstruct_coordinate_profile_rows( + characters=[item for item in characters if isinstance(item, dict)], table_bbox=table_bbox, + line_layouts=[item.model_dump() for item in region.line_layouts], table_region=region.region.model_dump(), + termination_rules=[item.model_dump() for item in region.termination_rules], + exclusion_regions=[item.model_dump() for item in region.exclusion_regions], + ) if not item.issues) + order_fields = [ + { + 'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status, + 'page_no': item.page_no, 'issues': list(item.issues), + } + for item in extract_order_fields(profile=parser, schema_fields=schema_fields, coordinate_evidence=evidence) + ] + return {'document_id': document.id, 'table_id': str(table_id), 'rows': rows, 'order_fields': order_fields} + contract = compile_table_header_contract(profile.schema_version.definition_json or {}) + parsed = parse_html_table_with_order_profile(_table_html(document.id, table_id), table_id=table_id, profile=parser, contract=contract) + return { + 'document_id': document.id, 'table_id': str(table_id), + 'rows': [dict(row.fields) for row in parsed.rows if row.status == 'parsed'], 'order_fields': [], + } + + +def _json_value(value: Any) -> Any: + """将日期和 Decimal 等运行期字段转换为 API/JSON 可展示的稳定值。""" + if isinstance(value, Decimal): + return str(value) + return value.isoformat() if hasattr(value, 'isoformat') else value + + +def list_independent_samples(*, suite_id: int, actor_id: int) -> dict[str, Any]: + """列出可用于当前盲测的同类专用订单,严格排除建模和已加入盲测的文档。""" + suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id)) + if suite is None: + raise NotFoundError('Order document profile test suite not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_FOUND') + profile = _profile(suite.profile_id) + parser = _definition_contract(profile) + schema_fields = { + str(item.get('field_id') or ''): item + for item in (profile.schema_version.definition_json or {}).get('fields') or [] + if isinstance(item, dict) and item.get('enabled', True) + } + excluded = { + item.document_id for item in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all() + } | {item.document_id for item in suite.samples} + result: list[dict[str, Any]] = [] + documents = ShippingNoticeDocument.query.join( + ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeDocument.intake_id, + ).filter( + ShippingNoticeIntake.purpose == 'order_document_profile_sample', + ).order_by(ShippingNoticeDocument.created_at.desc()).limit(200).all() + for document in documents: + if document.id in excluded: + continue + layout = current_layout_snapshot(document) or {} + if isinstance(parser, OrderCoordinateProfileV2): + layout = _ensure_order_field_evidence(document=document, layout=layout, parser=parser) + if not _has_matching_key_order_field(parser=parser, schema_fields=schema_fields, layout=layout): + continue + tables = layout.get('tables') if isinstance(layout.get('tables'), list) else [] + if layout.get('status') != 'ready' or not tables: + continue + for table in tables: + if not isinstance(table, dict) or not str(table.get('table_id') or ''): + continue + if isinstance(parser, OrderCoordinateProfileV2) and not _coordinate_table_available(document.id, str(table['table_id'])): + continue + result.append({ + 'document_id': document.id, 'table_id': str(table['table_id']), + 'page_no': int(table.get('page_no') or 1), 'filename': document.filename or '', + }) + return {'samples': result} + + +def preview_independent_sample(*, suite_id: int, document_id: int, table_id: str, actor_id: int) -> dict[str, Any]: + """读取一份可用独立样本的自动候选;复核确认前不写入盲测真值。""" + suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id)) + if suite is None or suite.status != 'draft': + raise ConflictError('Blind test suite is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE') + available = { + (item['document_id'], item['table_id']) + for item in list_independent_samples(suite_id=suite.id, actor_id=actor_id)['samples'] + } + if (int(document_id), str(table_id)) not in available: + raise ConflictError('Blind test sample must be independent of modelling samples', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT') + return _candidate_for_sample(profile=_profile(suite.profile_id), document_id=int(document_id), table_id=str(table_id)) + + +def confirm_sample_reviews(*, suite_id: int, document_id: int, table_id: str, row_reviews: Any, order_field_reviews: Any, actor_id: int) -> dict[str, Any]: + """把逐项正确/错误复核转换为既有盲测真值;未确认或错误未修正时拒绝写入。""" + candidate = preview_independent_sample( + suite_id=suite_id, document_id=document_id, table_id=table_id, actor_id=actor_id, + ) + if not isinstance(row_reviews, list) or len(row_reviews) != len(candidate['rows']): + raise ValidationError('Every candidate row requires a review', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID') + expected_rows: list[dict[str, Any]] = [] + for index, review in enumerate(row_reviews): + if not isinstance(review, dict) or review.get('correct') not in {True, False}: + raise ValidationError('Every candidate row requires a review', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID') + values = candidate['rows'][index] if review['correct'] else review.get('values') + if not isinstance(values, dict) or not values: + raise ValidationError('Incorrect row requires corrected values', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID') + expected_rows.append(dict(values)) + expected_order_fields: dict[str, Any] = {} + for field in candidate['order_fields']: + review = order_field_reviews.get(field['field_code']) if isinstance(order_field_reviews, dict) else None + if not isinstance(review, dict) or review.get('correct') not in {True, False}: + raise ValidationError('Every order field requires a review', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID') + value = field['value'] if review['correct'] else review.get('value') + if value in (None, ''): + raise ValidationError('Incorrect order field requires a corrected value', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID') + expected_order_fields[field['field_code']] = value + return add_sample( + suite_id=suite_id, document_id=document_id, table_id=table_id, expected_rows=expected_rows, + expected_order_fields=expected_order_fields, actor_id=actor_id, + ) + + def create_suite(*, profile_id: int, actor_id: int) -> dict[str, Any]: - """为草稿或发布 Profile 建立唯一盲测集;发布前完成审批以形成真正发布门禁。""" + """为当前 Profile checksum 建立独立盲测集,并将过期草稿集转为 superseded。 + + 核心逻辑:模板保存会改变草稿 definition hash,旧盲测真值不能为新定义背书。 + 同一模板因此按 checksum 保留历史集;再次打开盲测时只返回当前定义对应的集。 + + Args: + profile_id: 草稿或发布 Profile 主键。 + actor_id: 管理员主键,用于写入创建/过期审计。 + + Returns: + 当前 Profile checksum 对应的可维护盲测集摘要。 + """ profile = _profile(profile_id) - existing = ShippingDocumentProfileTestSuite.query.filter_by(profile_id=profile.id).first() + checksum = _quality_checksum(profile) + existing = ShippingDocumentProfileTestSuite.query.filter_by( + profile_id=profile.id, profile_checksum=checksum, + ).one_or_none() if existing is not None: return serialize_suite(existing) + stale_suites = ShippingDocumentProfileTestSuite.query.filter( + ShippingDocumentProfileTestSuite.profile_id == profile.id, + ShippingDocumentProfileTestSuite.status == 'draft', + ShippingDocumentProfileTestSuite.profile_checksum != checksum, + ).all() + for stale in stale_suites: + stale.status = 'superseded' + _audit(profile_id=profile.id, event_type='blind_test_suite_superseded', actor_id=actor_id, detail={ + 'suite_id': stale.id, + }) suite = ShippingDocumentProfileTestSuite( - profile_id=profile.id, profile_checksum=_quality_checksum(profile), created_by_id=actor_id, + profile_id=profile.id, profile_checksum=checksum, created_by_id=actor_id, ) db.session.add(suite) _audit(profile_id=profile.id, event_type='blind_test_suite_created', actor_id=actor_id, detail={ - 'profile_checksum': _quality_checksum(profile), + 'profile_checksum': checksum, }) db.session.commit() return serialize_suite(suite) -def add_sample(*, suite_id: int, document_id: int, table_id: str, expected_rows: Any, actor_id: int) -> dict[str, Any]: +def add_sample( + *, suite_id: int, document_id: int, table_id: str, expected_rows: Any, + expected_order_fields: Any = None, actor_id: int, +) -> dict[str, Any]: """增加独立盲测样本;批准后禁止继续更改真值。""" suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id)) if suite is None: @@ -144,7 +420,9 @@ def add_sample(*, suite_id: int, document_id: int, table_id: str, expected_rows: _table_html(document_id, table_id) sample = ShippingDocumentProfileTestSample( suite_id=suite.id, document_id=int(document_id), table_id=str(table_id), - expected_rows_json=_expected_rows(expected_rows), created_by_id=actor_id, + expected_rows_json=_expected_rows(expected_rows), + expected_order_fields_json=_expected_order_fields(expected_order_fields, parser=parser), + created_by_id=actor_id, ) db.session.add(sample) try: @@ -189,12 +467,24 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]: raise ConflictError('Profile changed after test suite creation', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_STALE') contract = compile_table_header_contract(profile.schema_version.definition_json or {}) parser = _definition_contract(profile) + schema_fields = { + str(item.get('field_id') or ''): item + for item in (profile.schema_version.definition_json or {}).get('fields') or [] + if isinstance(item, dict) and item.get('enabled', True) + } failures: list[str] = [] passed = 0 for sample in suite.samples: document = db.session.get(ShippingNoticeDocument, sample.document_id) layout = current_layout_snapshot(document) if document is not None else None if isinstance(parser, OrderCoordinateProfileV2): + field_failures = _order_field_quality_failures( + parser=parser, schema_fields=schema_fields, layout=layout or {}, + expected_values=dict(sample.expected_order_fields_json or {}), sample_id=sample.id, + ) + if field_failures: + failures.extend(field_failures) + continue evidence = (layout or {}).get('coordinate_evidence') if isinstance((layout or {}).get('coordinate_evidence'), dict) else {} pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} characters = (evidence.get('tables') or {}).get(sample.table_id) if isinstance(evidence.get('tables'), dict) else None @@ -210,6 +500,10 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]: continue actual_rows: list[dict[str, Any]] = [] for region in parser.table_regions: + # See candidate preview: a header-only page is evidence for order + # fields only and must not be sent to the line reconstruction engine. + if not region.line_layouts: + continue actual_rows.extend(item.fields for item in reconstruct_coordinate_profile_rows( characters=[item for item in characters if isinstance(item, dict)], table_bbox=table_bbox, line_layouts=[item.model_dump() for item in region.line_layouts], table_region=region.region.model_dump(), @@ -345,12 +639,53 @@ def promote_approved_suite_for_publish(*, profile: ShippingOrderDocumentProfile, run.profile_checksum = published_checksum +def _serialize_suite_sample(sample: ShippingDocumentProfileTestSample) -> dict[str, Any]: + """返回单份盲测样本的安全展示信息。 + + 核心逻辑:从当前布局快照反查表格所在页,仅公开文件名、文档和表格标识, + 不向工作台回传人工真值或订单正文。 + + Args: + sample: 已属于盲测集的样本 ORM 记录。 + + Returns: + 可用于工作台已加入样本清单的脱敏摘要。 + """ + document = db.session.get(ShippingNoticeDocument, sample.document_id) + layout = current_layout_snapshot(document) if document is not None else {} + table = next( + ( + item for item in (layout or {}).get('tables') or [] + if isinstance(item, dict) and str(item.get('table_id') or '') == sample.table_id + ), + None, + ) + return { + 'id': sample.id, + 'document_id': sample.document_id, + 'table_id': sample.table_id, + 'filename': str(document.filename or '') if document is not None else '', + 'page_no': int(table.get('page_no') or 1) if isinstance(table, dict) else 1, + } + + def serialize_suite(suite: ShippingDocumentProfileTestSuite) -> dict[str, Any]: - """返回不含订单正文的盲测治理摘要,供管理端确认发布状态。""" + """返回不含订单正文及真值的盲测治理摘要,供管理端维护与确认发布状态。 + + 核心逻辑:保留运行门禁汇总,并附带可删除样本的最小定位信息;真值仍只在 + 服务端保存,避免通过摘要接口泄露订单内容。 + + Args: + suite: 当前 Profile checksum 对应的盲测集。 + + Returns: + 含样本清单、执行摘要与批准状态的管理端 DTO。 + """ latest = suite.runs[-1] if suite.runs else None return { 'id': suite.id, 'profile_id': suite.profile_id, 'profile_checksum': suite.profile_checksum, 'status': suite.status, 'sample_count': len(suite.samples), + 'samples': [_serialize_suite_sample(sample) for sample in suite.samples], 'approved_at': suite.approved_at.isoformat() if suite.approved_at else None, 'latest_run': None if latest is None else { 'status': latest.status, 'sample_count': latest.sample_count, diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index d8e73c4b..2b899235 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -19,7 +19,7 @@ from flask import current_app from app import db from app.core.errors import ConflictError, ValidationError from app.models import ShippingTask, ShippingTaskEvent -from app.services.shipping_notice.constants import CP_UPLOADED, PH_UPLOAD_RPA_PENDING +from app.services.shipping_notice.constants import CP_UPLOADED, PH_UPLOAD_RPA_PENDING, PH_UPLOAD_RESULT_UNKNOWN from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task from app.services.shipping_notice.inventory_workflow import ( @@ -40,6 +40,7 @@ from app.services.shipping_notice.rpa import write_upload_trigger from app.services.shipping_notice.upload_attempt_service import ( complete_attempt, current_upload_artifact, + mark_attempt_result_unknown, record_manual_upload, start_rpa_attempt, ) @@ -734,15 +735,28 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: ) last_failed = latest_event(task, "upload_rpa_failed") if not last_failed or (last_failed.created_at < last_trigger.created_at): + attempt_id = (last_trigger.detail_json or {}).get('attempt_id') if isinstance(last_trigger.detail_json, dict) else None + from app.models import ShippingUploadAttempt + timed_out_attempt = db.session.get(ShippingUploadAttempt, attempt_id) if attempt_id else None + if timed_out_attempt is not None: + mark_attempt_result_unknown(timed_out_attempt) task.error_message = t("workflow.fulfillment.upload_timeout_error", lang=lang).format( timeout=timeout_seconds ) + task.pending_human_reason = PH_UPLOAD_RESULT_UNKNOWN + task.upload_status = 'unknown' log_task_event( task, - "upload_rpa_failed", + "upload_rpa_result_unknown", {"error": "timeout", "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds}, ) - db.session.flush() + db.session.commit() + return tool_response( + status="needs_human", + task=task, + message='货代上传结果未知,已冻结重试;请先核对货代结果并登记回执或明确拒绝。', + data=serialize_task_for_tool(task), + ) attempts = upload_rpa_attempts(task) if attempts >= max_attempts: diff --git a/backend/app/services/shipping_notice/order_document_profile_service.py b/backend/app/services/shipping_notice/order_document_profile_service.py index 68af9689..82629a04 100644 --- a/backend/app/services/shipping_notice/order_document_profile_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_service.py @@ -2,8 +2,9 @@ backend/app/services/shipping_notice/order_document_profile_service.py 用途:管理订单文档模板 Profile 的草稿、发布、退役和 Run 冻结快照。 -依赖:ShippingOrderDocumentProfile、订单 Schema 版本、document_layout.order_profile 纯契约。 -逻辑:草稿保存时把目标 field_code 转成稳定 field_id;发布时重新校验绑定 Schema 并原子替换当前版本。 +依赖:ShippingOrderDocumentProfile、盲测套件模型、订单 Schema 版本、document_layout.order_profile 纯契约。 +逻辑:草稿保存时把目标 field_code 转成稳定 field_id;发布时重新校验绑定 Schema 并原子替换当前版本; + 删除草稿前先清理关联盲测套件,避免 suites.profile_id 外键 500。 """ from __future__ import annotations @@ -25,6 +26,7 @@ from app.extensions import db from app.models import ( FileAsset, ShippingDocumentProfileTestSample, + ShippingDocumentProfileTestSuite, ShippingNoticeDocument, ShippingNoticeIntake, ShippingOrderDocumentProfile, @@ -48,6 +50,7 @@ from app.services.shipping_notice.document_layout.order_profile import ( order_profile_structure_fingerprint, reconstruct_order_profile_html, ) +from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields from app.services.shipping_notice.order_schema.compatibility import ( compare_profile_schema, is_replacement_compatible, @@ -76,6 +79,7 @@ def _match_summary(definition: dict[str, Any]) -> dict[str, Any]: 'minimum_score': match.get('minimum_score'), 'minimum_margin': match.get('minimum_margin'), 'table_region_count': len(definition.get('table_regions') or []), + 'order_field_layout_count': len(definition.get('order_field_layouts') or []), } @@ -100,6 +104,7 @@ def _definition_audit_summary(definition: dict[str, Any]) -> dict[str, Any]: line_layout_count = 0 header_layout_count = 0 field_codes: set[str] = set() + order_field_count = 0 for table_region in table_regions: if not isinstance(table_region, dict): continue @@ -111,9 +116,14 @@ def _definition_audit_summary(definition: dict[str, Any]) -> dict[str, Any]: for field_region in line_layout.get('field_regions') or []: if isinstance(field_region, dict) and field_region.get('field_code'): field_codes.add(str(field_region['field_code'])) + for order_field in definition.get('order_field_layouts') or []: + if isinstance(order_field, dict) and order_field.get('field_code'): + field_codes.add(str(order_field['field_code'])) + order_field_count += 1 return { 'table_region_count': len(table_regions), 'header_layout_count': header_layout_count, - 'line_layout_count': line_layout_count, 'bound_field_count': len(field_codes), + 'line_layout_count': line_layout_count, 'order_field_layout_count': order_field_count, + 'bound_field_count': len(field_codes), } @@ -220,6 +230,8 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio normalized = { 'document_match': raw.get('document_match'), 'table_regions': raw.get('table_regions'), + 'order_field_layouts': raw.get('order_field_layouts') or [], + 'draft_unbound_order_field_layouts': raw.get('draft_unbound_order_field_layouts') or [], } for table_region in normalized['table_regions'] or []: if not isinstance(table_region, dict): @@ -258,12 +270,52 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio {'field_id': str(profile_fields[target]['field_id']), 'field_code': target} for target in sorted(outputs) ] + for order_field in normalized['order_field_layouts']: + if not isinstance(order_field, dict): + continue + code = str(order_field.get('field_code') or '').strip() + field = profile_fields.get(code) + if field is None or field.get('scope') != 'header': + raise ValidationError('Order field binding must target a header Schema field', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID') + order_field['field_id'] = str(field['field_id']) + normalizer = order_field.get('normalizer_key') + if normalizer is not None and normalizer != field.get('normalizer_key'): + raise ValidationError('Order field normalizer must match Schema', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID') + order_field['normalizer_key'] = field.get('normalizer_key') + # `ocr_coordinate` is a minimum level, not an OCR-only restriction: native PDF + # coordinates are stronger evidence and remain valid at runtime. + allowed_sources = ( + ['pdf_coordinate'] + if order_field.get('minimum_evidence_level', 'coordinate') == 'coordinate' + else ['pdf_coordinate', 'ocr_coordinate'] + ) + schema_sources = field.get('allowed_sources') + if not isinstance(schema_sources, list) or not set(allowed_sources) & set(schema_sources): + raise ValidationError('Schema field does not allow order field coordinate source', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID') + order_field_codes = [ + str(item.get('field_code') or '').strip() + for item in normalized['order_field_layouts'] + if isinstance(item, dict) and str(item.get('field_code') or '').strip() + ] + duplicate_order_field_codes = sorted({ + code for code in order_field_codes if order_field_codes.count(code) > 1 + }) + if duplicate_order_field_codes: + # Expose the duplicate Schema codes before Pydantic returns a generic + # contract error, so the workbench can direct the administrator to it. + raise ValidationError( + 'Order field may bind only once', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID', + details={'reason': 'order_field_duplicate', 'field_codes': duplicate_order_field_codes}, + ) try: contract = OrderCoordinateProfileV2( profile_code='VALIDATION_PROFILE', version=1, document_match=normalized['document_match'], table_regions=normalized['table_regions'], + order_field_layouts=normalized['order_field_layouts'], + draft_unbound_order_field_layouts=normalized['draft_unbound_order_field_layouts'], ) except (TypeError, ValueError) as exc: raise ValidationError( @@ -273,6 +325,8 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio 'contract_version': contract.contract_version, 'document_match': contract.document_match.model_dump(), 'table_regions': [item.model_dump() for item in contract.table_regions], + 'order_field_layouts': [item.model_dump() for item in contract.order_field_layouts], + 'draft_unbound_order_field_layouts': [item.model_dump() for item in contract.draft_unbound_order_field_layouts], } @@ -293,6 +347,8 @@ def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderCoordina version=profile.version, document_match=definition.get('document_match'), table_regions=definition.get('table_regions'), + order_field_layouts=definition.get('order_field_layouts') or [], + draft_unbound_order_field_layouts=definition.get('draft_unbound_order_field_layouts') or [], ) @@ -489,6 +545,7 @@ def preview_profile_region( contract = OrderCoordinateProfileV2( profile_code=profile.profile_code, version=profile.version, document_match=definition['document_match'], table_regions=definition['table_regions'], + order_field_layouts=definition['order_field_layouts'], ) table_id = str(data.get('table_id') or '').strip() layout = _document_layout(document) @@ -587,6 +644,7 @@ def suggest_profile_header( contract = OrderCoordinateProfileV2( profile_code=profile.profile_code, version=profile.version, document_match=definition['document_match'], table_regions=definition['table_regions'], + order_field_layouts=definition['order_field_layouts'], ) table_id = str(data.get('table_id') or '').strip() layout = _document_layout(document) @@ -735,6 +793,359 @@ def _coordinate_characters(layout: dict[str, Any], table_id: str) -> list[dict[s return [item for item in characters if isinstance(item, dict)] +def _page_coordinate_characters(layout: dict[str, Any], *, page_no: int) -> tuple[list[dict[str, Any]], str | None]: + """读取整页字符证据供订单字段锚点建议使用,绝不以表格坐标代替页面坐标。""" + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + glyphs = (evidence.get('page_glyphs') or {}).get(str(page_no)) + source = (evidence.get('sources') or {}).get('pages', {}).get(str(page_no)) + if not isinstance(glyphs, list): + return [], None + return [item for item in glyphs if isinstance(item, dict)], str(source or '') or None + + +def _ensure_page_coordinate_evidence( + *, document: ShippingNoticeDocument, layout: dict[str, Any], page_no: int, +) -> dict[str, Any]: + """为历史表格样本补齐整页坐标,避免订单抬头因仅存表内字符而无法自动标记。""" + glyphs, source = _page_coordinate_characters(layout, page_no=page_no) + if glyphs and source in {'pdf_coordinate', 'ocr_coordinate'}: + return layout + if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'): + return layout + asset = db.session.get(FileAsset, document.asset_id) + if asset is None: + return layout + try: + from app.services.file_assets.service import read_asset_bytes + from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot + from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages + from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines + + native_page = next(item for item in extract_native_pdf_pages(read_asset_bytes(asset)) if item.page_no == page_no) + page_glyphs = [item.model_dump(mode='json') for item in native_page.characters] + page_source = 'pdf_coordinate' + if not page_glyphs: + page_glyphs = _ocr_lines_to_page_characters( + lines=extract_ocr_lines(native_page.image, page_width=native_page.width, page_height=native_page.height), + ) + page_source = 'ocr_coordinate' + if not page_glyphs: + return layout + next_snapshot = dict(layout) + evidence = dict(next_snapshot.get('coordinate_evidence') or {}) + pages = dict(evidence.get('pages') or {}) + pages[str(page_no)] = {'width': native_page.width, 'height': native_page.height} + page_map = dict(evidence.get('page_glyphs') or {}) + page_map[str(page_no)] = page_glyphs + sources = dict(evidence.get('sources') or {}) + source_pages = dict(sources.get('pages') or {}) + source_pages[str(page_no)] = page_source + sources['pages'] = source_pages + next_snapshot['coordinate_evidence'] = {**evidence, 'pages': pages, 'page_glyphs': page_map, 'sources': sources} + record_inline_layout_snapshot( + document, next_snapshot, + parser_key=f'mineru-pipeline+{page_source}:shipping_order_page_coordinate_evidence.v1', + ) + db.session.commit() + return next_snapshot + except Exception: + # A suggestion is optional. Preserve existing table annotation behavior if the source cannot be reread. + return layout + + +def _page_text_lines(glyphs: list[dict[str, Any]]) -> list[tuple[str, dict[str, float], list[dict[str, Any]]]]: + """将同一视觉行的字符压缩为文本和包围盒,供保守的标签精确匹配。""" + rows: list[list[dict[str, Any]]] = [] + for glyph in sorted(glyphs, key=lambda item: (float((item.get('bbox') or {}).get('y0', 0)), float((item.get('bbox') or {}).get('x0', 0)))): + bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None + if not bbox or not str(glyph.get('text') or '').strip(): + continue + center_y = (float(bbox.get('y0', 0)) + float(bbox.get('y1', 0))) / 2 + if rows: + previous = rows[-1][0].get('bbox') or {} + previous_y = (float(previous.get('y0', 0)) + float(previous.get('y1', 0))) / 2 + height = max(1.0, float(previous.get('y1', 0)) - float(previous.get('y0', 0))) + if abs(center_y - previous_y) <= height * .65: + rows[-1].append(glyph) + continue + rows.append([glyph]) + result: list[tuple[str, dict[str, float], list[dict[str, Any]]]] = [] + for row in rows: + ordered = sorted(row, key=lambda item: float((item.get('bbox') or {}).get('x0', 0))) + boxes = [item['bbox'] for item in ordered] + parts: list[str] = [] + previous_x1: float | None = None + previous_width = 0.0 + for item in ordered: + box = item['bbox'] + x0, x1 = float(box['x0']), float(box['x1']) + # Native PDF glyph streams usually omit whitespace. Restore a visual word gap + # so suggested anchor text remains usable in the workbench and template config. + if previous_x1 is not None and x0 - previous_x1 > max(1.5, previous_width * 1.45): + parts.append(' ') + parts.append(str(item.get('text') or '')) + previous_x1, previous_width = x1, max(1.0, x1 - x0) + result.append(( + ''.join(parts), + {'x0': min(float(box['x0']) for box in boxes), 'y0': min(float(box['y0']) for box in boxes), + 'x1': max(float(box['x1']) for box in boxes), 'y1': max(float(box['y1']) for box in boxes)}, + ordered, + )) + return result + + +def _anchor_text_key(value: str) -> str: + """按标签语义比较,忽略空白和常见分隔符但不尝试模糊纠错。""" + return re.sub(r'[^\w]+', '', value, flags=re.UNICODE).casefold() + + +def _inline_anchor_and_value_regions( + *, text: str, line_bbox: dict[str, float], glyphs: list[dict[str, Any]], label: str, width: float, height: float, +) -> tuple[dict[str, float], dict[str, float], str]: + """从字符 bbox 切分同行标签和值,绝不把同一行其他字段扩展进值框。""" + label_key = _anchor_text_key(label) + consumed: list[dict[str, Any]] = [] + consumed_start = 0 + key = '' + for index, glyph in enumerate(glyphs): + glyph_key = _anchor_text_key(str(glyph.get('text') or '')) + if not glyph_key: + continue + if label_key.startswith(key + glyph_key): + if not consumed: + consumed_start = index + consumed.append(glyph) + key += glyph_key + if key == label_key: + break + elif not consumed: + continue + else: + break + if not consumed or key != label_key: + consumed = glyphs[:1] + consumed_start = 0 + # Consume the label separator but never add it to the value area. + anchor_glyphs = list(consumed) + after_label = glyphs[consumed_start + len(consumed):] + while after_label and str(after_label[0].get('text') or '') in ':: ': + anchor_glyphs.append(after_label.pop(0)) + anchor_boxes = [item['bbox'] for item in anchor_glyphs] + anchor = { + 'x0': max(0.0, min(1.0, min(float(box['x0']) for box in anchor_boxes) / width)), + 'y0': max(0.0, min(1.0, min(float(box['y0']) for box in anchor_boxes) / height)), + 'x1': max(0.0, min(1.0, max(float(box['x1']) for box in anchor_boxes) / width)), + 'y1': max(0.0, min(1.0, max(float(box['y1']) for box in anchor_boxes) / height)), + } + if after_label: + normalized_text = text.casefold() + label_start = normalized_text.find(label.casefold()) + label_end = label_start + len(label) if label_start >= 0 else len(label) + while label_end < len(text) and text[label_end] in ':: ': + label_end += 1 + inline_value_text = text[label_end:].strip() + # PDF text can place independent key/value groups on the same visual row + # without a large glyph gap. Stop before the next explicit ``LABEL:``. + next_label = re.search(r'\s+[A-Za-z][A-Za-z0-9 ]{1,30}[::]', inline_value_text) + value_char_limit = ( + len([char for char in inline_value_text[:next_label.start()] if not char.isspace()]) + if next_label else None + ) + # A large character gap starts the next key/value group on a shared visual + # row. Keep only the first contiguous value rather than swallowing it. + value_glyphs = [after_label[0]] + for glyph in after_label[1:]: + previous = value_glyphs[-1]['bbox'] + current = glyph['bbox'] + previous_width = max(1.0, float(previous['x1']) - float(previous['x0'])) + if float(current['x0']) - float(previous['x1']) > previous_width * 3.5: + break + value_glyphs.append(glyph) + if value_char_limit is not None: + value_glyphs = value_glyphs[:max(1, value_char_limit)] + value_boxes = [item['bbox'] for item in value_glyphs] + # A relative percentage becomes visibly huge on tall PDFs. Keep the visual + # breathing room to at most one native page pixel around a single-line value. + vertical_padding = min(.0015, 1.0 / max(1.0, height)) + value = { + 'x0': max(anchor['x1'] + .003, min(float(box['x0']) for box in value_boxes) / width - .003), + 'y0': max(0.0, min(float(box['y0']) for box in value_boxes) / height - vertical_padding), + 'x1': min(.99, max(float(box['x1']) for box in value_boxes) / width + .003), + 'y1': min(1.0, max(float(box['y1']) for box in value_boxes) / height + vertical_padding), + } + return anchor, value, 'right_of_anchor' + value = { + 'x0': anchor['x0'], 'y0': min(.98, anchor['y1'] + .012), + 'x1': min(.96, max(anchor['x1'] + .2, anchor['x0'] + .45)), 'y1': min(1.0, anchor['y1'] + .075), + } + return anchor, value, 'below_anchor' + + +def _inline_value_text(*, text: str, label: str) -> str: + """返回与同行值框一致的首个值文本,供候选面板展示而不重复读取 PDF。""" + start = text.casefold().find(label.casefold()) + suffix = text[start + len(label):] if start >= 0 else '' + suffix = suffix.lstrip(':: ').strip() + next_label = re.search(r'\s+[A-Za-z][A-Za-z0-9 ]{1,30}[::]', suffix) + return (suffix[:next_label.start()] if next_label else suffix).strip() + + +def _generic_order_label_candidates( + *, lines: list[tuple[str, dict[str, float], list[dict[str, Any]]]], width: float, height: float, + table_start_y: float | None, known_anchor_keys: set[str], bound_line_indexes: set[int], source: str, +) -> list[dict[str, Any]]: + """为尚未配置 Schema 别名的 ``LABEL: value`` 生成未绑定订单字段候选。""" + candidates: list[dict[str, Any]] = [] + for line_index, (text, bbox, glyphs) in enumerate(lines): + # 只取明细表前的上半段抬头;紧贴表格的 QUALITY/SHIPMENT 等条款不属于订单字段。 + if table_start_y is not None and bbox['y0'] >= table_start_y - height * .18: + continue + match = re.match(r'^\s*([^::]{2,42}?)[::]', text) + if match is None: + continue + label = match.group(1).strip() + key = _anchor_text_key(label) + if line_index in bound_line_indexes or len(key) < 2 or key in known_anchor_keys or len(label.split()) > 3: + continue + anchor, value_region, value_mode = _inline_anchor_and_value_regions( + text=text, line_bbox=bbox, glyphs=glyphs, label=label, width=width, height=height, + ) + candidates.append({ + 'field_id': '', 'field_code': '', 'display_name': label, 'source': source, + 'status': 'suggested', 'binding_status': 'unbound', 'anchor_text': label, + 'anchor_region': anchor, + 'value_region': value_region, 'value_mode': value_mode, + 'suggested_value': _inline_value_text(text=text, label=label), + 'issue': 'order_field_schema_binding_required', + }) + return candidates + + +def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """ + 按当前未保存的 v2 定义重读订单字段值,供工作台刷新后展示复核证据。 + + 浏览器只能提交当前样本与受控定义;读取复用正式运行期锚点/相对区域算法, + 因此通用 Ship To、Bill To 标签不会依赖自动建议的标签过滤范围。 + """ + try: + document_id = int(data.get('document_id')) + page_no = int(data.get('page_no') or 1) + except (TypeError, ValueError) as exc: + raise ValidationError('document_id or page_no is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc + document = db.session.get(ShippingNoticeDocument, document_id) + if document is None: + raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') + schema_version = _require_schema_version(data.get('schema_version_id')) + definition = _normalize_definition(data.get('definition'), schema_version=schema_version) + profile = OrderCoordinateProfileV2( + profile_code='WORKBENCH_PREVIEW', version=1, + document_match=definition['document_match'], table_regions=definition['table_regions'], + order_field_layouts=definition['order_field_layouts'], + draft_unbound_order_field_layouts=definition['draft_unbound_order_field_layouts'], + ) + layout = _ensure_page_coordinate_evidence( + document=document, layout=_document_layout(document), page_no=page_no, + ) + fields_by_id = { + str(field['field_id']): field + for field in _schema_profile_fields(schema_version).values() + if field.get('scope') == 'header' + } + return { + 'page_no': page_no, + 'fields': [ + item.model_dump(mode='json') + for item in extract_order_fields( + profile=profile, schema_fields=fields_by_id, + coordinate_evidence=layout.get('coordinate_evidence') or {}, + ) + if item.page_no == page_no + ], + } + + +def suggest_order_field_layouts(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """ + 从冻结 Schema 的 Header 标签别名生成订单级字段的待复核锚点和值区建议。 + + 只使用整页 PDF/OCR 字符坐标;标签不唯一、无坐标或 Schema 未授权时保留问题码, + 绝不自动绑定或发布任何字段。 + """ + try: + document_id = int(data.get('document_id')) + page_no = int(data.get('page_no') or 1) + except (TypeError, ValueError) as exc: + raise ValidationError('document_id or page_no is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc + document = db.session.get(ShippingNoticeDocument, document_id) + if document is None: + raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') + schema_version = _require_schema_version(data.get('schema_version_id')) + layout = _document_layout(document) + layout = _ensure_page_coordinate_evidence(document=document, layout=layout, page_no=page_no) + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + page = (evidence.get('pages') or {}).get(str(page_no)) + glyphs, source = _page_coordinate_characters(layout, page_no=page_no) + if not isinstance(page, dict) or not glyphs or source not in {'pdf_coordinate', 'ocr_coordinate'}: + return {'page_no': page_no, 'order_field_candidates': [], 'issues': ['order_field_page_coordinate_unavailable'], 'status': 'needs_review'} + try: + width, height = float(page['width']), float(page['height']) + except (KeyError, TypeError, ValueError) as exc: + raise ValidationError('Page coordinate evidence is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc + lines = _page_text_lines(glyphs) + candidates: list[dict[str, Any]] = [] + known_anchor_keys: set[str] = set() + bound_line_indexes: set[int] = set() + for field in (schema_version.definition_json or {}).get('fields') or []: + if ( + not isinstance(field, dict) + or field.get('enabled') is False + or field.get('auto_annotation_enabled', True) is False + or field.get('scope') != 'header' + ): + continue + if source not in set(field.get('allowed_sources') or []): + continue + labels = [str(field.get('display_name') or '').strip(), *[str(item).strip() for item in field.get('aliases') or []]] + # Display text and alias often differ only by whitespace/case; count each visual hit once. + labels = list({key: item for item in labels if len(key := _anchor_text_key(item)) >= 2}.values()) + known_anchor_keys.update(_anchor_text_key(item) for item in labels) + hits = [ + (line_index, label, bbox) + for line_index, (text, bbox, _) in enumerate(lines) + for label in labels if _anchor_text_key(label) in _anchor_text_key(text) + ] + base = {'field_id': str(field.get('field_id') or ''), 'field_code': str(field.get('field_code') or ''), + 'display_name': str(field.get('display_name') or field.get('field_code') or ''), 'source': source} + if len(hits) != 1: + candidates.append({**base, 'status': 'ambiguous' if len(hits) > 1 else 'unavailable', + 'issue': 'order_field_anchor_ambiguous' if len(hits) > 1 else 'order_field_anchor_not_found'}) + continue + line_index, label, bbox = hits[0] + bound_line_indexes.add(line_index) + text, _, line_glyphs = lines[line_index] + anchor, value_region, value_mode = _inline_anchor_and_value_regions( + text=text, line_bbox=bbox, glyphs=line_glyphs, label=label, width=width, height=height, + ) + candidates.append({**base, 'status': 'suggested', 'anchor_text': label, 'anchor_region': anchor, + 'value_region': value_region, 'value_mode': value_mode, + 'suggested_value': _inline_value_text(text=text, label=label), + 'binding_status': 'bound', 'issue': None}) + table_starts = [ + float(item.get('bbox', {}).get('y0')) for item in layout.get('tables') or [] + if isinstance(item, dict) and isinstance(item.get('bbox'), dict) and item.get('bbox', {}).get('y0') is not None + ] + candidates.extend(_generic_order_label_candidates( + lines=lines, width=width, height=height, table_start_y=min(table_starts) if table_starts else None, + known_anchor_keys=known_anchor_keys, bound_line_indexes=bound_line_indexes, source=source, + )) + _audit(profile_id=None, document_id=document.id, event_type='order_field_suggestions_viewed', actor_id=actor_id, detail={ + 'page_no': page_no, 'candidate_count': len(candidates), 'suggested_count': sum(item['status'] == 'suggested' for item in candidates), + }) + db.session.commit() + return {'page_no': page_no, 'order_field_candidates': candidates, 'issues': [], 'status': 'needs_review'} + + def generate_ocr_coordinate_evidence(*, document_id: int, table_id: str, actor_id: int | None) -> dict[str, Any]: """ 为指定 PDF 表格补齐字符坐标证据;优先恢复原生文字层,仅在无文字层时执行 OCR。 @@ -853,6 +1264,27 @@ def _ocr_lines_to_characters(*, lines: list[Any], table_bbox: dict[str, Any]) -> return result +def _ocr_lines_to_page_characters(*, lines: list[Any]) -> list[dict[str, Any]]: + """将 OCR 行拆为整页字符坐标,专供订单抬头锚点候选,不与表格 cell 证据混用。""" + result: list[dict[str, Any]] = [] + source_index = 0 + for line in lines: + text = str(line.text or '') + box = line.bbox + if not text: + continue + width = (box.x1 - box.x0) / len(text) + for index, character in enumerate(text): + if not character.strip(): + continue + result.append({'text': character, 'source_index': source_index, 'bbox': { + 'x0': box.x0 + index * width, 'y0': box.y0, + 'x1': box.x0 + (index + 1) * width, 'y1': box.y1, + }}) + source_index += 1 + return result + + def _reconstructed_table_html(*, layout: dict[str, Any], raw_table: dict[str, Any], raw_settings: Any) -> str: """从持久化坐标证据和管理员确认的边界生成可审核重建表,缺任一条件均拒绝。""" try: @@ -1111,7 +1543,7 @@ def suggest_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | N data: document_id、table_id,以及可选的非负 row_offset。省略 row_offset 时建议全部行。 actor_id: 当前管理员 ID;保留与预览接口一致的授权边界。 Returns: - 仅含相对边界、少量列示例及确定性 line_no 建议的待审核配置;指定行时只返回该行。 + 仅含相对边界、少量列示例及字段规则驱动的待审核绑定;指定行时只返回该行。 """ try: document_id = int(data.get('document_id')) @@ -1129,6 +1561,14 @@ def suggest_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | N characters = _coordinate_characters(layout, table_id) if raw_table is None or not characters or not isinstance(raw_table.get('bbox'), dict): raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') + schema_fields: list[dict[str, Any]] = [] + if data.get('schema_version_id') is not None: + version = _require_schema_version(data.get('schema_version_id')) + schema_fields = [ + field for field in _schema_fields(version).values() + if field.get('auto_annotation_enabled', True) + and set(field.get('allowed_sources') or []) & {'pdf_coordinate', 'ocr_coordinate'} + ] suggestions = suggest_multi_subrow_layouts( characters=characters, table_bbox=raw_table['bbox'], ) @@ -1162,9 +1602,50 @@ def suggest_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | N } except (KeyError, TypeError, ValueError, ZeroDivisionError) as exc: raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc + header_suggestions = suggest_header_regions(characters=characters, table_bbox=raw_table['bbox']) + # Only exact, unique aliases can bind a column. Position is considered only after + # the label itself is proven, preventing shifted documents from remapping fields. + aliases: dict[str, str | None] = {} + for field in schema_fields: + code = str(field.get('field_code') or '').strip() + # A schema code is a stable, deterministic label variant: `unit_price` + # normalizes to `UNIT PRICE`. Include it alongside maintained aliases so + # common table headers bind without positional guessing. + for value in (code.replace('_', ' '), field.get('display_name'), *(field.get('aliases') or [])): + key = _anchor_text_key(str(value or '')) + if key: + aliases[key] = code if aliases.get(key, code) == code else None + for header in header_suggestions: + for field in header.fields: + key = _anchor_text_key(field.text) + code = aliases.get(key) + field.field_code = code + field.confidence = 'exact_alias' if code else ('ambiguous' if key in aliases else 'unmapped') + serialized = [] for item in suggestions: payload = item.model_dump() + if item.row_offset == 0 and schema_fields: + mapped_codes: list[str | None] = [None] * (len(item.column_boundaries) - 1) + mapped_indexes: dict[int, list[str]] = {} + for header in header_suggestions: + for field in header.fields: + if not field.field_code: + continue + center = (field.region.x0 + field.region.x1) / 2 + column_index = min( + range(len(mapped_codes)), + key=lambda index: abs( + center - (item.column_boundaries[index] + item.column_boundaries[index + 1]) / 2, + ), + ) + mapped_indexes.setdefault(column_index, []).append(field.field_code) + for column_index, codes in mapped_indexes.items(): + # Multiple exact labels pointing to one reconstructed column is still + # ambiguous; retain the visual candidate but require manual binding. + if len(set(codes)) == 1: + mapped_codes[column_index] = codes[0] + payload['suggested_field_codes'] = mapped_codes payload['region'] = { 'x0': table_region['x0'], 'x1': table_region['x1'], @@ -1173,7 +1654,7 @@ def suggest_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | N } serialized.append(payload) serialized_headers = [] - for item in suggest_header_regions(characters=characters, table_bbox=raw_table['bbox']): + for item in header_suggestions: payload = item.model_dump() region = payload['region'] payload['region'] = { @@ -1428,6 +1909,37 @@ def create_schema_migration_draft( if isinstance(item, dict) and item.get('field_id') and item.get('enabled', True) } definition = remap_profile_field_codes(source.definition_json or {}, target_schema.definition_json or {}) + unbound_order_fields = list(definition.get('draft_unbound_order_field_layouts') or []) + retained_order_fields: list[dict[str, Any]] = [] + for field in definition.get('order_field_layouts') or []: + if not isinstance(field, dict): + continue + field_id = str(field.get('field_id') or '') + if field_id not in breaking_ids: + retained_order_fields.append(field) + continue + resolution = resolutions[field_id] + replacement_id = str(resolution.get('replacement_field_id') or '') if isinstance(resolution, dict) else '' + if replacement_id: + replacement = target_fields.get(replacement_id) + original = next((item for item in (source_schema.definition_json or {}).get('fields') or [] + if isinstance(item, dict) and str(item.get('field_id')) == field_id), None) + if replacement is None or original is None or not is_replacement_compatible( + original, replacement, source_field_id=field_id, candidate_field_id=replacement_id, + ): + raise ValidationError('Replacement field is not contract-compatible', code='SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_INVALID') + field['field_id'] = replacement_id + field['field_code'] = str(replacement.get('field_code') or '') + retained_order_fields.append(field) + elif isinstance(resolution, dict) and resolution.get('action') == 'unbind': + unbound_order_fields.append({ + key: value for key, value in field.items() + if key not in {'field_id', 'field_code', 'normalizer_key', 'required'} + } | {'label': str(field.get('field_code') or field_id)}) + else: + raise ValidationError('Migration resolution is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_INVALID') + definition['order_field_layouts'] = retained_order_fields + definition['draft_unbound_order_field_layouts'] = unbound_order_fields for table in definition.get('table_regions') or []: if not isinstance(table, dict): continue @@ -1485,6 +1997,8 @@ def create_schema_migration_draft( 'parent_layout_id': str(layout.get('layout_id') or ''), 'label': str(field.get('field_code') or field_id), 'region': field.get('region'), + # Schema-breaking migrations require an explicit field decision. + 'requires_rebinding': True, }) else: raise ValidationError( @@ -1561,14 +2075,21 @@ def publish( code='SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT', ) if any( - table.get('draft_unbound_field_regions') + item.get('requires_rebinding') for table in (profile.definition_json or {}).get('table_regions', []) if isinstance(table, dict) + for item in (table.get('draft_unbound_field_regions') or []) + if isinstance(item, dict) ): raise ValidationError( 'All draft field regions must be bound before publish', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', ) + if (profile.definition_json or {}).get('draft_unbound_order_field_layouts'): + raise ValidationError( + 'All draft order field layouts must be bound before publish', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', + ) # 发布前先以草稿定义 checksum 执行训练/盲测门禁;不能先发布再补测。 from app.services.shipping_notice.document_profile_quality_service import ( assert_profile_publishable, @@ -1629,7 +2150,12 @@ def retire(profile_id: int, *, actor_id: int | None = None) -> dict[str, Any]: def delete_draft(profile_id: int) -> None: - """删除未发布草稿;不可变版本永久保留审计。""" + """ + 删除未发布草稿及其草稿盲测集;已发布/退役版本永久保留审计。 + + 核心逻辑:草稿允许绑定独立盲测套件,但 suites.profile_id 外键无 CASCADE; + 删除前先移除 suite(samples/runs 由 ORM cascade 清理),避免 IntegrityError 500。 + """ profile = db.session.get(ShippingOrderDocumentProfile, profile_id) if profile is None: raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') @@ -1638,6 +2164,12 @@ def delete_draft(profile_id: int) -> None: 'Only draft order document profile can be deleted', code='SHIPPING.ORDER_DOCUMENT_PROFILE_DELETE_BLOCKED', ) + # [STEP 1] 先清盲测套件;samples/runs 随 suite cascade delete-orphan + suite = ShippingDocumentProfileTestSuite.query.filter_by(profile_id=profile.id).first() + if suite is not None: + db.session.delete(suite) + db.session.flush() + # [STEP 2] 删除草稿 Profile 本体(样本表已有 DB CASCADE) db.session.delete(profile) db.session.commit() diff --git a/backend/app/services/shipping_notice/order_extraction.py b/backend/app/services/shipping_notice/order_extraction.py index 45489079..14d0873b 100644 --- a/backend/app/services/shipping_notice/order_extraction.py +++ b/backend/app/services/shipping_notice/order_extraction.py @@ -417,7 +417,8 @@ def persist_order_extraction_result( candidate.order_extraction_id = int(dynamic['extraction'].id) candidate.order_extraction_run_id = int(run_id) if run_id is not None else None candidate.is_current_version = True - candidate.extraction_source = extraction_source + automatic_acceptance = raw_order.get('_hxops_acceptance') == 'approved_deterministic_profile_v1' + candidate.extraction_source = 'approved_deterministic_profile' if automatic_acceptance else extraction_source candidate.classification_confidence = classification_confidence candidate.field_confidence_json = field_confidence candidate.missing_fields_json = list(assessment['missing_required_fields']) + list(assessment['missing_process_fields']) @@ -426,7 +427,14 @@ def persist_order_extraction_result( candidate.confidence = classification_confidence candidate.conflicts_json = blocking_conflicts candidate.validation_status = 'ready' if not reasons else 'needs_review' - candidate.selected = not reasons + # Only the backend's frozen approved-profile marker can automatically accept. + candidate.candidate_status = 'accepted' if automatic_acceptance else 'provisional' + candidate.acceptance_mode = 'automatic' if automatic_acceptance else None + candidate.accepted_at = datetime.utcnow() if automatic_acceptance else None + candidate.accepted_by_id = None + candidate.acceptance_reason = 'approved_deterministic_profile' if automatic_acceptance else None + candidate.acceptance_policy_version = 'deterministic-profile-v1' if automatic_acceptance else None + candidate.selected = bool(automatic_acceptance) identity = build_business_fingerprint(normalized) content = build_content_fingerprint(normalized) candidate.business_fingerprint = identity.get('fingerprint') @@ -493,12 +501,44 @@ def persist_order_extraction_result( candidate.duplicate_target_task_no = str(matches[0].get('task_no') or '').strip().upper() or None # [STEP] 仅无审核阻断原因时才选中自动打开;证据/冲突失败必须保持未选中, # 否则同 Intake 其它 ready Candidate 会被 selection 门禁整批挡住。 - candidate.selected = not reasons + candidate.selected = False candidate.validation_status = 'ready' if not reasons else 'needs_review' elif duplicate.get('blocking'): reasons.append('duplicate_decision_required') candidate.selected = False candidate.validation_status = 'needs_review' + # An approved template is automatic only after the same strict field and + # duplicate gates as a manual decision. A partial parse stays provisional. + automatic_eligible = ( + automatic_acceptance + and not reasons + and candidate.validation_status == 'ready' + and not duplicate.get('blocking') + ) + open_existing_eligible = ( + candidate.duplicate_resolution == 'open_existing' + and bool(candidate.duplicate_target_task_no) + and not reasons + and candidate.validation_status == 'ready' + ) + if open_existing_eligible: + # This does not admit a Dify result into new fulfillment. It only + # selects a strong duplicate for the dedicated existing-task path. + # Candidate acceptance remains exclusively automatic/manual/legacy. + candidate.candidate_status = 'provisional' + candidate.acceptance_mode = None + candidate.accepted_at = None + candidate.accepted_by_id = None + candidate.acceptance_reason = None + candidate.acceptance_policy_version = None + candidate.selected = True + elif not automatic_eligible: + candidate.candidate_status = 'provisional' + candidate.acceptance_mode = None + candidate.accepted_at = None + candidate.acceptance_reason = None + candidate.acceptance_policy_version = None + candidate.selected = False candidate.updated_at = datetime.utcnow() # Candidate 已关联本轮受控 FieldValue 后刷新影子识别;不读取其 LLM 摘要,也不触发自动确认。 from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution_safely @@ -506,10 +546,17 @@ def persist_order_extraction_result( refresh_candidate_shadow_resolution_safely(candidate) document_candidate_keys[int(document.id)].append(candidate_key) document_has_pending[int(document.id)] = document_has_pending[int(document.id)] or bool(reasons) - if candidate.selected and candidate.validation_status == 'ready' and auto_create_enabled: + if ( + candidate.selected + and candidate.validation_status == 'ready' + and ( + (candidate.candidate_status == 'accepted' and auto_create_enabled) + or candidate.duplicate_resolution == 'open_existing' + ) + ): auto_candidates.append(candidate) else: - if candidate.validation_status == 'ready' and not auto_create_enabled: + if candidate.candidate_status != 'accepted' and candidate.validation_status == 'ready' and not auto_create_enabled: candidate.selected = False reasons.append('auto_create_disabled') pending_item = { diff --git a/backend/app/services/shipping_notice/order_extraction_merge.py b/backend/app/services/shipping_notice/order_extraction_merge.py index ae49dadc..fa1bf624 100644 --- a/backend/app/services/shipping_notice/order_extraction_merge.py +++ b/backend/app/services/shipping_notice/order_extraction_merge.py @@ -168,6 +168,9 @@ def merge_unit_orders(*, orders: list[dict[str, Any]], schema_definition: dict[s po_numbers, line_keys = _order_identity(order, codes) match = None for candidate in merged: + # A Dify order may never inherit an approved-profile acceptance marker. + if candidate.get('_hxops_acceptance') != order.get('_hxops_acceptance'): + continue if str(candidate.get('source_intake_no') or '').strip().upper() != intake_no: continue candidate_pos, candidate_lines = _order_identity(candidate, codes) diff --git a/backend/app/services/shipping_notice/order_extraction_run_service.py b/backend/app/services/shipping_notice/order_extraction_run_service.py index ce3200b7..1d5e8eb5 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -380,8 +380,15 @@ def create_order_extraction_run( capability_code='shipping.order_extraction', ) schema_version = published_version() + binding_auto_create_enabled = bool((binding.config_json or {}).get('auto_create_enabled')) + from app.services.shipping_notice.order_schema.service import get_auto_creation_policy + + schema_auto_creation_policy = get_auto_creation_policy() + effective_auto_create_enabled = bool( + schema_auto_creation_policy.get('enabled') and binding_auto_create_enabled + ) quality_batch_id = binding.quality_batch_id - if bool((binding.config_json or {}).get('auto_create_enabled')): + if effective_auto_create_enabled: from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch require_approved_quality_batch( @@ -413,9 +420,14 @@ def create_order_extraction_run( intakes=intakes, schema_version=schema_version, ) - # 自动建单总开关与字段模板一起冻结,后续管理员变更不影响已创建 Run。 - from app.services.shipping_notice.order_schema.service import get_auto_creation_policy - snapshot['auto_creation_policy'] = get_auto_creation_policy() + # 自动建单必须同时通过 Schema 总开关、运行能力绑定和质量批次;任何一层关闭 + # 都冻结为影子模式,避免仅改 Schema 意外恢复自动履约。 + snapshot['auto_creation_policy'] = { + **schema_auto_creation_policy, + 'enabled': effective_auto_create_enabled, + 'schema_enabled': bool(schema_auto_creation_policy.get('enabled')), + 'runtime_binding_enabled': binding_auto_create_enabled, + } snapshot_hash = _sha256(snapshot) idempotency_key = _sha256({ 'user_id': user.id, @@ -458,7 +470,7 @@ def create_order_extraction_run( runtime_binding_id=binding.id, provider_agent_id=binding.provider_agent_id, quality_batch_id=quality_batch_id, - provider_config_json=binding_config, + provider_config_json={**binding_config, 'auto_create_enabled': effective_auto_create_enabled}, provider_snapshot_json={ 'provider_agent_id': binding.provider_agent_id, 'runtime_provider': binding.provider_agent.runtime_provider, @@ -599,7 +611,9 @@ def reparse_order_extraction_run( ).all() for candidate in source_candidates: candidate.selected_before_superseded = bool(candidate.selected) + candidate.candidate_status_before_superseded = candidate.candidate_status candidate.selected = False + candidate.candidate_status = 'expired' candidate.is_current_version = False source.superseded_by_run_id = run.id source.superseded_at = datetime.utcnow() @@ -1252,6 +1266,8 @@ def _restore_candidates_after_failed_reparse(run: ShippingOrderExtractionRun) -> candidate.is_current_version = True candidate.selected = bool(candidate.selected_before_superseded) candidate.selected_before_superseded = None + candidate.candidate_status = candidate.candidate_status_before_superseded or 'provisional' + candidate.candidate_status_before_superseded = None source.superseded_by_run_id = None source.superseded_at = None diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index e977d66d..1c17a3ff 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -26,6 +26,7 @@ from app.services.shipping_notice.document_layout.order_profile import ( ) from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows +from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value @@ -679,6 +680,10 @@ def parse_order_extraction_workflow_result(result: dict[str, Any]) -> list[dict[ if isinstance(raw, dict) and 'orders' in raw: raw = raw['orders'] continue + # Only the documented data wrapper is accepted; do not search arbitrary JSON. + if isinstance(raw, dict) and isinstance(raw.get('data'), dict) and 'orders' in raw['data']: + raw = raw['data']['orders'] + continue if not isinstance(raw, str) or json_decode_count >= 2: break try: @@ -711,6 +716,11 @@ def validate_unit_orders( } evidence_text = frozen_document_text_for_dify(document) or str(document.get('extracted_text') or '') for order in orders: + if strict_provider_evidence and any(str(key).startswith('_hxops_') for key in order): + raise ValidationError( + 'Workflow order contains reserved HXOPS fields', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE', + ) if str(order.get('source_intake_no') or '').strip().upper() != intake_no: raise ValidationError( 'Unit order source intake does not match the extraction unit', @@ -734,7 +744,19 @@ def validate_unit_orders( 'Unit order contains a field outside the frozen extraction contract', code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE', ) + if strict_provider_evidence and any(str(key).startswith('_hxops_') for key in field): + raise ValidationError( + 'Workflow field contains reserved HXOPS fields', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE', + ) for observation in field.get('observations') or [] if isinstance(field, dict) else []: + if strict_provider_evidence and isinstance(observation, dict) and any( + str(key).startswith('_hxops_') for key in observation + ): + raise ValidationError( + 'Workflow observation contains reserved HXOPS fields', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE', + ) if not isinstance(observation, dict) or int(observation.get('document_id') or 0) != int(unit.document_id): raise ValidationError( 'Unit observation references another document', @@ -748,7 +770,7 @@ def validate_unit_orders( code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE', ) _validate_locked_layout_fields(document, orders=orders) - return orders + return _merge_confirmed_profile_order_fields(run, unit=unit, orders=orders) def _validate_locked_layout_fields(document: dict[str, Any], *, orders: list[dict[str, Any]]) -> None: @@ -798,6 +820,63 @@ def _validate_locked_layout_fields(document: dict[str, Any], *, orders: list[dic ) +def _merge_confirmed_profile_order_fields(run: Any, *, unit: Any, orders: list[dict[str, Any]]) -> list[dict[str, Any]]: + """注入 confirmed 订单字段并拒绝 Provider 显式冲突;Provider 省略它们是合法的。""" + locked = { + str(item.get('field_id') or ''): item for item in _confirmed_profile_order_fields(run, unit=unit) + if item.get('field_id') + } + if not locked: + return orders + for order in orders: + returned: dict[str, set[str]] = {} + for field in order.get('header_fields') or []: + if not isinstance(field, dict) or str(field.get('field_id') or '') not in locked: + continue + for observation in field.get('observations') or []: + if isinstance(observation, dict): + returned.setdefault(str(field['field_id']), set()).add( + json.dumps(observation.get('value'), ensure_ascii=False, sort_keys=True), + ) + expected = { + field_id: {json.dumps(item.get('value'), ensure_ascii=False, sort_keys=True)} + for field_id, item in locked.items() + } + # Missing fields are expected: Dify never receives coordinate template values. + if any(returned.get(field_id, values) != values for field_id, values in expected.items() if field_id in returned): + raise ValidationError( + 'Workflow changed a confirmed order field', + code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE', + ) + header_fields = order.get('header_fields') if isinstance(order.get('header_fields'), list) else [] + by_id = {str(item.get('field_id') or ''): item for item in header_fields if isinstance(item, dict)} + for field_id, candidate in locked.items(): + # Replace any agreeing Provider observation with immutable coordinate evidence. + field = by_id.get(field_id) + observation = { + 'value': candidate.get('value'), 'document_id': int(unit.document_id), + 'quote': str(candidate.get('value') or '')[:1000], 'confidence': 1.0, + 'layout_evidence': { + 'page_no': candidate.get('page_no'), 'source': candidate.get('source'), + 'anchor_bbox': candidate.get('anchor_bbox'), 'value_bbox': candidate.get('value_bbox'), + 'glyph_indices': list(candidate.get('glyph_indices') or []), + }, + } + if field is None: + header_fields.append({ + 'field_id': field_id, 'observations': [observation], + '_hxops_order_field_evidence': True, + }) + else: + field['observations'] = [observation] + field['_hxops_order_field_evidence'] = True + order['header_fields'] = header_fields + # Only HXOPS can set this marker. Provider validation ran before this point; + # it grants coordinate evidence only, never automatic order acceptance. + order['_hxops_order_field_evidence'] = True + return orders + + def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, Any]] | None: """仅由盲测批准的唯一 Profile 实测行生成零 Provider 订单;其余交给模型补充。""" snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} @@ -819,10 +898,17 @@ def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, An # 文档出现多个模板表时不猜测其业务关系,即使其中一个模板已批准也回退 Dify/人工。 if len(profile_result.get('tables') or []) != 1 or len(approved_tables) != 1: return None + confirmed_order_fields = _confirmed_profile_order_fields(run, unit=unit) order = _build_approved_profile_order( unit=unit, intake=intake, schema=schema, definition=definition, table=approved_tables[0], + confirmed_order_fields=confirmed_order_fields, ) - return [order] if order is not None else None + if order is None: + return None + if confirmed_order_fields: + # `_build_approved_profile_order` has already merged and validated these fields. + pass + return [order] def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfileV2: @@ -831,12 +917,13 @@ def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfileV2: return OrderCoordinateProfileV2( profile_code=str(raw.get('profile_code') or ''), version=int(raw.get('version') or 0), document_match=definition.get('document_match'), table_regions=definition.get('table_regions'), + order_field_layouts=definition.get('order_field_layouts') or [], ) def _build_approved_profile_order( *, unit: Any, intake: dict[str, Any], schema: dict[str, Any], definition: dict[str, Any], - table: dict[str, Any], + table: dict[str, Any], confirmed_order_fields: list[dict[str, Any]] | None = None, ) -> dict[str, Any] | None: """ 把已批准 Profile 本次实际解析的唯一完整表格转换为零 Provider 订单。 @@ -847,6 +934,7 @@ def _build_approved_profile_order( schema: Dify 抽取契约元信息。 definition: Run 冻结 Schema 完整定义,用于 required/scope 门禁。 table: `_profile_table_candidates` 产生且已批准的单个表解析结果。 + confirmed_order_fields: 同一冻结模板产生的 confirmed 订单字段,作为独立 Header 证据合并。 Returns: 完整确定性订单;候选非唯一、含问题或缺必填字段时返回 None。 @@ -889,9 +977,28 @@ def _build_approved_profile_order( if len(unique) != 1: return None header_fields.append({'field_id': field_id, 'observations': [observations[0]]}) + present_header = {item['field_id'] for item in header_fields} + for candidate in confirmed_order_fields or []: + field_id = str(candidate.get('field_id') or '') + if not field_id: + continue + if field_id in present_header: + # Header table evidence and independent order-field evidence must never silently compete. + return None + header_fields.append({'field_id': field_id, '_hxops_order_field_evidence': True, 'observations': [{ + 'value': candidate.get('value'), 'document_id': int(unit.document_id), + 'quote': str(candidate.get('value') or '')[:1000], 'confidence': 1.0, + # Kept only in the internal deterministic result. The Dify manifest strips + # layout payloads and strict Provider validation rejects `_hxops_*` markers. + 'layout_evidence': { + 'page_no': candidate.get('page_no'), 'source': candidate.get('source'), + 'anchor_bbox': candidate.get('anchor_bbox'), 'value_bbox': candidate.get('value_bbox'), + 'glyph_indices': list(candidate.get('glyph_indices') or []), + }, + }]}) + present_header.add(field_id) if not line_groups: return None - present_header = {item['field_id'] for item in header_fields} for config in fields: if not config.get('required'): continue @@ -908,9 +1015,47 @@ def _build_approved_profile_order( 'source_intake_no': str(intake.get('intake_no') or ''), 'primary_document_id': int(unit.document_id), 'header_fields': header_fields, 'lines': line_groups, 'conflicts': [], + # Only this frozen approved-profile builder may add this internal marker. + '_hxops_acceptance': 'approved_deterministic_profile_v1', } +def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, Any]]: + """读取唯一匹配 v2 模板的 confirmed 订单字段;无页级证据或歧义时返回空锁集。""" + snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} + schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {} + definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {} + schema_fields = { + str(item.get('field_id') or ''): item for item in definition.get('fields') or [] + if isinstance(item, dict) and item.get('enabled', True) and item.get('scope') == 'header' + } + profiles = [ + item for item in snapshot.get('order_document_profiles') or [] + if isinstance(item, dict) and int(item.get('schema_version_id') or 0) == int(run.schema_version_id) + and isinstance(item.get('definition'), dict) + and item['definition'].get('contract_version') == 'order_coordinate_profile.v2' + ] + _intake, document = _unit_snapshot(run, unit) + layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {} + if not profiles or layout.get('status') != 'ready': + return [] + match = match_frozen_coordinate_profiles(profiles=profiles, layout=layout) + if match.status != 'unique_match': + return [] + raw = next(( + item for item in profiles + if item.get('profile_code') == match.profile_code and int(item.get('version') or 0) == match.version + and str(item.get('checksum') or '') == match.checksum + ), None) + if raw is None: + return [] + candidates = extract_order_fields( + profile=_frozen_coordinate_profile(raw), schema_fields=schema_fields, + coordinate_evidence=layout.get('coordinate_evidence') or {}, + ) + return [item.model_dump(mode='json') for item in candidates if item.status == 'confirmed'] + + def execute_order_extraction_workflow(*, run: Any, unit: Any, provider: Any, timeout_seconds: int, event_observer=None) -> tuple[list[dict[str, Any]], dict[str, Any]]: """调用绑定 Provider 的 Workflow,并把网络异常归类为可重试业务错误。""" try: diff --git a/backend/app/services/shipping_notice/order_schema/compatibility.py b/backend/app/services/shipping_notice/order_schema/compatibility.py index c27cf1ff..05f41b90 100644 --- a/backend/app/services/shipping_notice/order_schema/compatibility.py +++ b/backend/app/services/shipping_notice/order_schema/compatibility.py @@ -36,6 +36,9 @@ def referenced_field_ids(profile_definition: dict[str, Any] | None) -> set[str]: for target in field.get('target_fields') or []: if isinstance(target, dict) and target.get('field_id'): result.add(str(target['field_id'])) + for field in (profile_definition or {}).get('order_field_layouts') or []: + if isinstance(field, dict) and field.get('field_id'): + result.add(str(field['field_id'])) return result @@ -191,4 +194,10 @@ def remap_profile_field_codes( values = layout.get(key) if isinstance(values, list): layout[key] = [code_map.get(str(code), code) for code in values] + for field in result.get('order_field_layouts') or []: + if not isinstance(field, dict): + continue + target_field = target.get(str(field.get('field_id') or '')) + if target_field: + field['field_code'] = target_field.get('field_code') return result diff --git a/backend/app/services/shipping_notice/order_schema/diff.py b/backend/app/services/shipping_notice/order_schema/diff.py index 2ffc0962..dcc61ffa 100644 --- a/backend/app/services/shipping_notice/order_schema/diff.py +++ b/backend/app/services/shipping_notice/order_schema/diff.py @@ -14,6 +14,7 @@ from typing import Any _SCALAR_KEYS = ( 'field_code', 'scope', 'value_type', 'field_category', 'collection_mode', 'enabled', 'display_name', 'description', 'business_purpose', 'required', 'normalizer_key', + 'auto_annotation_enabled', 'relation_role', 'comparator_key', 'extraction_instruction', 'context_source', 'sensitivity_level', 'dify_exposure_policy', 'available_for_customer_identity', 'sequence', ) diff --git a/backend/app/services/shipping_notice/order_schema/field_rules.py b/backend/app/services/shipping_notice/order_schema/field_rules.py index 4cfb36e3..00c51c5b 100644 --- a/backend/app/services/shipping_notice/order_schema/field_rules.py +++ b/backend/app/services/shipping_notice/order_schema/field_rules.py @@ -8,7 +8,7 @@ backend/app/services/shipping_notice/order_schema/field_rules.py from __future__ import annotations -from datetime import date +from datetime import date, datetime from decimal import Decimal, InvalidOperation from typing import Any @@ -28,8 +28,16 @@ def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any: if value_type == 'integer': return int(str(value).replace(',', '').strip()) if value_type == 'date': - text = str(value).strip().replace('/', '-').replace('.', '-') - return date.fromisoformat(text) + text = str(value).strip() + # Purchase orders commonly print US-style dates (for example + # ``06/20/2026``). Accept only explicit, deterministic layouts so + # we restore coordinate candidates without treating free text as a date. + for pattern in ('%Y-%m-%d', '%Y/%m/%d', '%Y.%m.%d', '%Y%m%d', '%m/%d/%Y', '%m-%d-%Y', '%m.%d.%Y'): + try: + return datetime.strptime(text, pattern).date() + except ValueError: + continue + raise ValueError('invalid date') if value_type == 'boolean': if isinstance(value, bool): return value diff --git a/backend/app/services/shipping_notice/order_schema/runtime.py b/backend/app/services/shipping_notice/order_schema/runtime.py index 290813cb..b2631f1b 100644 --- a/backend/app/services/shipping_notice/order_schema/runtime.py +++ b/backend/app/services/shipping_notice/order_schema/runtime.py @@ -178,6 +178,15 @@ def _verified_observations( quote = str(item.get('quote') or '').strip() if document is None or value is None or not _validate(value, config): continue + layout_evidence = item.get('layout_evidence') if raw.get('_hxops_order_field_evidence') is True else None + if isinstance(layout_evidence, dict) and _valid_coordinate_evidence(layout_evidence): + verified.append({ + 'value': value, 'document': document, 'quote': quote or str(value), 'confidence': 1.0, + 'source_type': 'attachment_coordinate', 'extractor': 'order_profile_order_field', + 'evidence_ref': f"document:{int(document.id)}:order-field:{config['field_id']}:page:{int(layout_evidence['page_no'])}", + 'evidence_metadata': {'kind': 'order_field_coordinate', **layout_evidence}, + }) + continue frozen_text = str((frozen_evidence_text_by_document or {}).get(int(document.id)) or '') source_texts = [frozen_text, str(document.extracted_text or '')] if not quote or not any(quote in text for text in source_texts if text): @@ -203,6 +212,16 @@ def _verified_observations( return verified +def _valid_coordinate_evidence(raw: dict[str, Any]) -> bool: + """只接受后端确认的最小页级坐标证据,缺页号、来源或字符索引时不提升为已验证。""" + return ( + str(raw.get('source') or '') == 'pdf_coordinate' + and isinstance(raw.get('page_no'), int) and raw['page_no'] >= 1 + and isinstance(raw.get('anchor_bbox'), dict) and isinstance(raw.get('value_bbox'), dict) + and isinstance(raw.get('glyph_indices'), list) and bool(raw['glyph_indices']) + ) + + def _choose_value(observations: list[dict[str, Any]], config: dict[str, Any]) -> tuple[Any, str, str | None]: """按一致性、来源优先级和冲突策略选择字段值。""" if not observations: diff --git a/backend/app/services/shipping_notice/order_schema/service.py b/backend/app/services/shipping_notice/order_schema/service.py index 16ae7ed0..9b47ea41 100644 --- a/backend/app/services/shipping_notice/order_schema/service.py +++ b/backend/app/services/shipping_notice/order_schema/service.py @@ -1124,6 +1124,13 @@ def _coordinate_sources(value: Any) -> list[str]: return sources +def _default_auto_annotation_enabled(raw: dict[str, Any]) -> bool: + """仅让必填或建单关键字段默认参与画布自动标记,避免可选字段淹没候选。""" + return bool(raw.get('required')) or bool(raw.get('auto_create_key_field')) or ( + str(raw.get('business_purpose') or 'general') != 'general' + ) + + def save_draft( version_id: int, data: dict[str, Any], *, actor_id: int | None = None, request_id: str | None = None, @@ -1170,9 +1177,10 @@ def save_draft( validators = _string_list(raw.get('validator_keys', []), field='validator_keys') aliases = _string_list(raw.get('aliases', []), field='aliases') enum_options = _string_list(raw.get('enum_options', []), field='enum_options') + auto_annotation_enabled = raw.get('auto_annotation_enabled', _default_auto_annotation_enabled(raw)) relation_role = str(raw.get('relation_role') or '').strip() or None required = raw.get('required', False) - if not isinstance(enabled, bool) or not isinstance(required, bool): + if not isinstance(enabled, bool) or not isinstance(required, bool) or not isinstance(auto_annotation_enabled, bool): raise ValidationError('required must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') if not display_name or normalizer not in NORMALIZERS or comparator not in COMPARATORS: raise ValidationError('field display or transformation config is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID') @@ -1234,6 +1242,7 @@ def save_draft( 'minimum_confidence': round(minimum_confidence, 2) if minimum_confidence is not None else None, 'required': required, 'aliases': aliases, + 'auto_annotation_enabled': auto_annotation_enabled, 'normalizer_key': normalizer, 'validator_keys': validators, 'enum_options': enum_options, diff --git a/backend/app/services/shipping_notice/reservation_service.py b/backend/app/services/shipping_notice/reservation_service.py index 4b4f5391..2cb0ed1b 100644 --- a/backend/app/services/shipping_notice/reservation_service.py +++ b/backend/app/services/shipping_notice/reservation_service.py @@ -145,6 +145,7 @@ def record_inventory_verification( db.session.add(verification) db.session.flush() available_count = 0 + seen_reservation_ids: set[str] = set() for item in line_results: reservation_id = validated_reservation_id(item.get('reservation_id')) part_number = str(item.get('part_number') or '').strip() @@ -152,6 +153,11 @@ def record_inventory_verification( if reservation is None or reservation.part_number != part_number: raise ValidationError('Inventory result does not map to a frozen reservation', code='SHIPPING.RESERVATION_MISMATCH') required = _decimal(item.get('required_qty')) + # The frozen order is the quantity authority. A reduced or duplicate result + # must not turn an insufficient reservation into an exportable line. + if reservation_id in seen_reservation_ids or required != reservation.required_qty: + raise ValidationError('Inventory result quantity is inconsistent with the frozen reservation', code='SHIPPING.RESERVATION_MISMATCH') + seen_reservation_ids.add(reservation_id) available = _decimal(item.get('available_qty')) if Decimal(str(item.get('available_qty') or 0)) > 0 else Decimal('0') status = 'available' if available >= required else 'shortage' db.session.add(ShippingInventoryVerificationLine( diff --git a/backend/app/services/shipping_notice/state_machine.py b/backend/app/services/shipping_notice/state_machine.py index 69bdab59..06331eea 100644 --- a/backend/app/services/shipping_notice/state_machine.py +++ b/backend/app/services/shipping_notice/state_machine.py @@ -36,6 +36,7 @@ from app.services.shipping_notice.constants import ( CP_UPLOADED, CP_COMPLETED, CP_UPLOAD_FAILED, + CP_UPLOAD_RESULT_UNKNOWN, CP_UPLOAD_REQ, CP_WAITING_UPLOAD, PH_INV_UNAVAIL, @@ -48,6 +49,7 @@ from app.services.shipping_notice.constants import ( PH_SHORTAGE, PH_UPLOAD_RPA_FAILED, PH_UPLOAD_RPA_PENDING, + PH_UPLOAD_RESULT_UNKNOWN, RS_CONFIRMED, RS_PARSE_REVIEW, RS_REJECTED, @@ -121,6 +123,7 @@ CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = { CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"), CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"), CP_WAITING_UPLOAD: ("refresh", "retry_upload", "download_excel", "mark_manual_uploaded"), + CP_UPLOAD_RESULT_UNKNOWN: ("refresh", "download_excel", "mark_manual_uploaded"), CP_READY_MATCH: ("match_inventory",), CP_READY_EXPORT: ("generate_excel",), CP_EXPORT_READY: ("download_excel", "mark_manual_uploaded"), @@ -355,6 +358,11 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState: checkpoint=CP_UPLOAD_FAILED, human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_FAILED]), ) + if reason == PH_UPLOAD_RESULT_UNKNOWN: + return TaskUiState( + checkpoint=CP_UPLOAD_RESULT_UNKNOWN, + human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_RESULT_UNKNOWN]), + ) if reason == PH_RPA_PENDING or ( task.process_status == "waiting_inventory" and reason == PH_RPA_PENDING ): diff --git a/backend/app/services/shipping_notice/task_candidate_reconciliation.py b/backend/app/services/shipping_notice/task_candidate_reconciliation.py index 683fe321..f6882d35 100644 --- a/backend/app/services/shipping_notice/task_candidate_reconciliation.py +++ b/backend/app/services/shipping_notice/task_candidate_reconciliation.py @@ -15,7 +15,7 @@ from typing import Any from app.models import ShippingNoticeCandidate, ShippingTask from app.services.shipping_notice.constants import PH_RSV_REQ from app.services.shipping_notice.po_number import normalize_po_number -from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues +from app.services.shipping_notice.reservation_gate import reservation_gate_issues, task_reservation_gate_issues from app.services.shipping_notice.reservation_id import ( is_valid_reservation_id, validated_reservation_id, @@ -41,6 +41,13 @@ RECONCILE_FIELDS: tuple[str, ...] = ( ) +def _reconciliation_reservation_issues(task: ShippingTask) -> list[dict[str, Any]]: + """回填旧任务时以当前已接受订单字段投影状态;下游履约仍强制冻结 Snapshot。""" + if task.order_snapshot_id: + return task_reservation_gate_issues(task) + return reservation_gate_issues(current_line_field_values(task)) + + def _normalized_qty(value: Any) -> str: """数量稳定比较值。""" try: @@ -307,7 +314,7 @@ def apply_candidate_reconciliation_plan( ], ) open_rows = list_open_field_conflicts(task) - issues = task_reservation_gate_issues(task) + issues = _reconciliation_reservation_issues(task) step_payload = dict(task.step_payload_json or {}) step_payload['parse_validation'] = { 'status': 'needs_review', @@ -345,7 +352,7 @@ def apply_candidate_reconciliation_plan( 'updated_line_indexes': [], } - issues = task_reservation_gate_issues(task) + issues = _reconciliation_reservation_issues(task) open_rows = list_open_field_conflicts(task) step_payload = dict(task.step_payload_json or {}) step_payload['parse_validation'] = { diff --git a/backend/app/services/shipping_notice/task_order_field_editor.py b/backend/app/services/shipping_notice/task_order_field_editor.py index 78c43601..b5c41e8b 100644 --- a/backend/app/services/shipping_notice/task_order_field_editor.py +++ b/backend/app/services/shipping_notice/task_order_field_editor.py @@ -77,7 +77,7 @@ def current_order_field_display(task: ShippingTask) -> dict[str, Any]: """按当前字段目录顺序展示锁定 Schema 字段,历史缺失字段回退版本 sequence。""" extraction = _current_extraction(task) global_sequences = { - field.id: int(field.display_sequence or 0) + str(field.field_code): int(field.display_sequence or 0) for field in ShippingOrderField.query.filter_by(schema_id=extraction.schema_version.schema_id).all() } fields = sorted( @@ -86,7 +86,7 @@ def current_order_field_display(task: ShippingTask) -> dict[str, Any]: if item.get('enabled', True) ], key=lambda item: ( - global_sequences.get(str(item.get('field_id')), 1_000_000 + int(item.get('sequence') or 0)), + global_sequences.get(str(item.get('field_code')), 1_000_000 + int(item.get('sequence') or 0)), int(item.get('sequence') or 0), str(item.get('field_code') or ''), ), diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index f8a45bde..9b7c6573 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -26,6 +26,7 @@ from app.services.shipping_notice.constants import ( CP_RSV_REQ, CP_UPLOADED, CP_UPLOAD_FAILED, + CP_UPLOAD_RESULT_UNKNOWN, CP_UPLOAD_REQ, CP_WAITING_UPLOAD, PH_INV_UNAVAIL, @@ -88,6 +89,7 @@ _BLOCKED_CHECKPOINTS = { CP_NOTICE_TEXT_EXTRACTION_FAILED, CP_UPLOAD_REQ, CP_UPLOAD_FAILED, + CP_UPLOAD_RESULT_UNKNOWN, } diff --git a/backend/app/services/shipping_notice/upload_attempt_service.py b/backend/app/services/shipping_notice/upload_attempt_service.py index aa55e5ae..f8cd30dd 100644 --- a/backend/app/services/shipping_notice/upload_attempt_service.py +++ b/backend/app/services/shipping_notice/upload_attempt_service.py @@ -50,9 +50,13 @@ def start_rpa_attempt(task: ShippingTask, *, artifact_id: int | None = None, ide if existing is not None: if existing.artifact_id != artifact.id: raise ConflictError('Idempotency key belongs to another artifact', code='SHIPPING.UPLOAD_ATTEMPT_CONFLICT') + if existing.status == 'timed_out': + raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RESULT_UNKNOWN') return existing if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first(): raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED') + if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='timed_out').first(): + raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RESULT_UNKNOWN') attempt_no = (db.session.query(ShippingUploadAttempt).filter_by(artifact_id=artifact.id).count() + 1) attempt = ShippingUploadAttempt( artifact_id=artifact.id, attempt_no=attempt_no, mode='rpa', idempotency_key=key, @@ -96,7 +100,7 @@ def complete_attempt( raise ValidationError('Upload artifact is missing', code='SHIPPING.UPLOAD_ARTIFACT_REQUIRED') if attempt.status == 'succeeded' or artifact.status == 'uploaded': raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE') - if attempt.status not in {'pending', 'running'}: + if attempt.status not in {'pending', 'running', 'timed_out'}: raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE') attempt.callback_id = callback attempt.finished_at = datetime.utcnow() @@ -115,6 +119,13 @@ def complete_attempt( task.freight_ref_no = attempt.freight_ref_no _aggregate_task_upload_status(task) else: + # A missing callback may conceal a completed freight submission. A late + # transport error is not enough to safely release or retry that Artifact. + if attempt.status == 'timed_out' and not str(error_message or '').strip().lower().startswith('freight_rejected:'): + attempt.error_code = 'UPLOAD_RESULT_UNKNOWN' + attempt.error_message = str(error_message or 'Upload result remains unknown')[:500] + db.session.flush() + return attempt attempt.status = 'failed' message = str(error_message or 'RPA upload failed')[:500] attempt.error_code = 'FREIGHT_REJECTED' if str(error_message or '').strip().lower().startswith('freight_rejected:') else 'RPA_UPLOAD_FAILED' @@ -126,6 +137,18 @@ def complete_attempt( return attempt +def mark_attempt_result_unknown(attempt: ShippingUploadAttempt) -> ShippingUploadAttempt: + """超时后冻结 Artifact;仅迟到成功回调或货代明确拒绝才能解除未知结果。""" + if attempt.status != 'running': + return attempt + attempt.status = 'timed_out' + attempt.finished_at = datetime.utcnow() + attempt.error_code = 'UPLOAD_RESULT_UNKNOWN' + attempt.error_message = 'RPA callback timed out; freight submission must be reconciled before retry' + db.session.flush() + return attempt + + def record_manual_upload(task: ShippingTask, *, artifact_id: int | None, evidence_asset_no: str, operator_id: int, freight_ref_no: str | None = None) -> ShippingUploadAttempt: """登记人工上传成功;必须持有当前用户已上传的私有截图或回执资产。""" asset_no = str(evidence_asset_no or '').strip() diff --git a/backend/migrations/versions/029f0a1b2c3d_add_shipping_candidate_acceptance_lifecycle.py b/backend/migrations/versions/029f0a1b2c3d_add_shipping_candidate_acceptance_lifecycle.py new file mode 100644 index 00000000..c61f23d2 --- /dev/null +++ b/backend/migrations/versions/029f0a1b2c3d_add_shipping_candidate_acceptance_lifecycle.py @@ -0,0 +1,71 @@ +"""add shipping candidate acceptance lifecycle + +Revision ID: 029f0a1b2c3d +Revises: 028e9f0a1b2c +Create Date: 2026-07-27 10:00:00.000000 + +用途:将 Candidate 的人工选择投影与是否可履约的接受状态分离。 +依赖:shipping_notice_candidates、shipping_tasks、users。 +逻辑:已消费候选可安全回填 accepted;未消费历史候选一律回填 provisional,避免历史 +selected 标记绕过新的接受门禁。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = '029f0a1b2c3d' +down_revision = '028e9f0a1b2c' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """新增接受生命周期字段并以保守规则回填历史数据。""" + with op.batch_alter_table('shipping_notice_candidates') as batch: + batch.add_column(sa.Column('candidate_status', sa.String(length=32), server_default='provisional', nullable=False)) + batch.add_column(sa.Column('candidate_status_before_superseded', sa.String(length=32), nullable=True)) + batch.add_column(sa.Column('acceptance_mode', sa.String(length=32), nullable=True)) + batch.add_column(sa.Column('accepted_at', sa.DateTime(), nullable=True)) + batch.add_column(sa.Column('accepted_by_id', sa.Integer(), nullable=True)) + batch.add_column(sa.Column('acceptance_reason', sa.Text(), nullable=True)) + batch.add_column(sa.Column('acceptance_policy_version', sa.String(length=64), nullable=True)) + batch.create_check_constraint( + 'ck_shipping_notice_candidates_status', + "candidate_status IN ('provisional', 'accepted', 'rejected', 'expired')", + ) + batch.create_check_constraint( + 'ck_shipping_notice_candidates_acceptance_mode', + "acceptance_mode IS NULL OR acceptance_mode IN ('automatic', 'manual', 'legacy')", + ) + batch.create_foreign_key( + 'fk_shipping_notice_candidates_accepted_by_id', 'users', ['accepted_by_id'], ['id'], + ) + batch.create_index( + 'ix_shipping_notice_candidates_fulfillment_gate', ['candidate_status', 'is_current_version'], + ) + batch.alter_column('selected', server_default=sa.text('false')) + + # A consumed Candidate has an existing Task and is the only historical state that proves acceptance. + op.execute( + "UPDATE shipping_notice_candidates " + "SET candidate_status = 'accepted', acceptance_mode = 'legacy' " + "WHERE consumed_task_id IS NOT NULL" + ) + + +def downgrade() -> None: + """移除生命周期字段;旧 selected 投影保持原值以支持回滚。""" + with op.batch_alter_table('shipping_notice_candidates') as batch: + batch.alter_column('selected', server_default=sa.text('true')) + batch.drop_index('ix_shipping_notice_candidates_fulfillment_gate') + batch.drop_constraint('ck_shipping_notice_candidates_acceptance_mode', type_='check') + batch.drop_constraint('ck_shipping_notice_candidates_status', type_='check') + batch.drop_constraint('fk_shipping_notice_candidates_accepted_by_id', type_='foreignkey') + batch.drop_column('acceptance_policy_version') + batch.drop_column('acceptance_reason') + batch.drop_column('accepted_by_id') + batch.drop_column('accepted_at') + batch.drop_column('acceptance_mode') + batch.drop_column('candidate_status_before_superseded') + batch.drop_column('candidate_status') diff --git a/backend/migrations/versions/02af0b1c2d3e_add_order_field_blind_test_truth.py b/backend/migrations/versions/02af0b1c2d3e_add_order_field_blind_test_truth.py new file mode 100644 index 00000000..27309079 --- /dev/null +++ b/backend/migrations/versions/02af0b1c2d3e_add_order_field_blind_test_truth.py @@ -0,0 +1,31 @@ +"""add order field blind test truth + +Revision ID: 02af0b1c2d3e +Revises: 029f0a1b2c3d +Create Date: 2026-07-27 11:10:00.000000 + +用途:为订单文档模板盲测保存订单级字段的人工真值。 +依赖:shipping_document_profile_test_samples。 +逻辑:历史样本默认空对象,只有配置订单字段的新模板在服务层要求完整真值,避免旧模板迁移后失效。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = '02af0b1c2d3e' +down_revision = '029f0a1b2c3d' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """新增订单字段盲测真值列,并为历史明细模板安全回填空对象。""" + with op.batch_alter_table('shipping_document_profile_test_samples') as batch: + batch.add_column(sa.Column('expected_order_fields_json', sa.JSON(), nullable=False, server_default=sa.text("'{}'"))) + + +def downgrade() -> None: + """删除订单字段盲测真值列,回退到仅校验明细行的历史契约。""" + with op.batch_alter_table('shipping_document_profile_test_samples') as batch: + batch.drop_column('expected_order_fields_json') diff --git a/backend/migrations/versions/03bf1c2d3e4f_backfill_order_schema_auto_annotation.py b/backend/migrations/versions/03bf1c2d3e4f_backfill_order_schema_auto_annotation.py new file mode 100644 index 00000000..1f9a5aa5 --- /dev/null +++ b/backend/migrations/versions/03bf1c2d3e4f_backfill_order_schema_auto_annotation.py @@ -0,0 +1,67 @@ +"""backfill order schema auto annotation + +Revision ID: 03bf1c2d3e4f +Revises: 02af0b1c2d3e +Create Date: 2026-07-27 12:20:00.000000 + +用途:为已存在的订单 Schema 字段规则补齐自动标记开关。 +依赖:shipping_order_schema_versions.definition_json。 +逻辑:历史字段默认参与自动标记,保持其先前的别名和坐标来源行为;管理员可在后续草稿中逐字段关闭。 +""" + +from __future__ import annotations + +import copy + +from alembic import op +import sqlalchemy as sa + + +revision = '03bf1c2d3e4f' +down_revision = '02af0b1c2d3e' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """为现有版本 JSON 的每个字段写入兼容默认值,不改变其他配置。""" + bind = op.get_bind() + versions = sa.table( + 'shipping_order_schema_versions', + sa.column('id', sa.Integer), + sa.column('definition_json', sa.JSON), + ) + for row in bind.execute(sa.select(versions.c.id, versions.c.definition_json)).mappings(): + definition = copy.deepcopy(row['definition_json'] or {}) + fields = definition.get('fields') if isinstance(definition.get('fields'), list) else [] + changed = False + for field in fields: + if isinstance(field, dict) and 'auto_annotation_enabled' not in field: + field['auto_annotation_enabled'] = True + changed = True + if changed: + bind.execute( + versions.update().where(versions.c.id == row['id']).values(definition_json=definition), + ) + + +def downgrade() -> None: + """移除回填键;运行时代码仍对缺失键按 True 兼容。""" + bind = op.get_bind() + versions = sa.table( + 'shipping_order_schema_versions', + sa.column('id', sa.Integer), + sa.column('definition_json', sa.JSON), + ) + for row in bind.execute(sa.select(versions.c.id, versions.c.definition_json)).mappings(): + definition = copy.deepcopy(row['definition_json'] or {}) + fields = definition.get('fields') if isinstance(definition.get('fields'), list) else [] + changed = False + for field in fields: + if isinstance(field, dict) and 'auto_annotation_enabled' in field: + field.pop('auto_annotation_enabled') + changed = True + if changed: + bind.execute( + versions.update().where(versions.c.id == row['id']).values(definition_json=definition), + ) diff --git a/backend/migrations/versions/04cf1d2e3f4a_limit_order_schema_auto_annotation.py b/backend/migrations/versions/04cf1d2e3f4a_limit_order_schema_auto_annotation.py new file mode 100644 index 00000000..f5deed0e --- /dev/null +++ b/backend/migrations/versions/04cf1d2e3f4a_limit_order_schema_auto_annotation.py @@ -0,0 +1,76 @@ +"""limit order schema auto annotation + +Revision ID: 04cf1d2e3f4a +Revises: 03bf1c2d3e4f +Create Date: 2026-07-27 12:30:00.000000 + +用途:将历史 Schema 的自动标记范围收敛为关键字段。 +依赖:shipping_order_schema_versions.definition_json。 +逻辑:仅保留业务必填、自动建单关键或具名业务用途字段,避免可选字段在模板画布产生大量无关候选。 +""" + +from __future__ import annotations + +import copy + +from alembic import op +import sqlalchemy as sa + + +revision = '04cf1d2e3f4a' +down_revision = '03bf1c2d3e4f' +branch_labels = None +depends_on = None + + +def _is_key_field(field: dict) -> bool: + """保持与 Schema 保存默认值一致的关键字段判定,迁移不靠字段编码硬编码。""" + return bool(field.get('required')) or bool(field.get('auto_create_key_field')) or ( + str(field.get('business_purpose') or 'general') != 'general' + ) + + +def upgrade() -> None: + """将当前环境历史版本收敛为关键字段白名单,不改变字段语义或坐标来源。""" + bind = op.get_bind() + versions = sa.table( + 'shipping_order_schema_versions', + sa.column('id', sa.Integer), + sa.column('definition_json', sa.JSON), + ) + for row in bind.execute(sa.select(versions.c.id, versions.c.definition_json)).mappings(): + definition = copy.deepcopy(row['definition_json'] or {}) + fields = definition.get('fields') if isinstance(definition.get('fields'), list) else [] + changed = False + for field in fields: + if isinstance(field, dict): + enabled = _is_key_field(field) + if field.get('auto_annotation_enabled') != enabled: + field['auto_annotation_enabled'] = enabled + changed = True + if changed: + bind.execute( + versions.update().where(versions.c.id == row['id']).values(definition_json=definition), + ) + + +def downgrade() -> None: + """回退为上一个迁移的兼容全开状态,不改变其他字段配置。""" + bind = op.get_bind() + versions = sa.table( + 'shipping_order_schema_versions', + sa.column('id', sa.Integer), + sa.column('definition_json', sa.JSON), + ) + for row in bind.execute(sa.select(versions.c.id, versions.c.definition_json)).mappings(): + definition = copy.deepcopy(row['definition_json'] or {}) + fields = definition.get('fields') if isinstance(definition.get('fields'), list) else [] + changed = False + for field in fields: + if isinstance(field, dict) and field.get('auto_annotation_enabled') is not True: + field['auto_annotation_enabled'] = True + changed = True + if changed: + bind.execute( + versions.update().where(versions.c.id == row['id']).values(definition_json=definition), + ) diff --git a/backend/migrations/versions/05df1e2f3a4b_version_blind_test_suites_by_checksum.py b/backend/migrations/versions/05df1e2f3a4b_version_blind_test_suites_by_checksum.py new file mode 100644 index 00000000..7a7d5f81 --- /dev/null +++ b/backend/migrations/versions/05df1e2f3a4b_version_blind_test_suites_by_checksum.py @@ -0,0 +1,35 @@ +"""version blind test suites by profile checksum + +Revision ID: 05df1e2f3a4b +Revises: 04cf1d2e3f4a +Create Date: 2026-07-27 19:15:00.000000 + +用途:允许同一订单模板在定义变更后保留旧盲测审计,并为新 checksum 建立新盲测集。 +依赖:shipping_document_profile_test_suites。 +逻辑:旧的 profile 单列唯一约束会阻止新草稿盲测;迁移改为 profile/checksum 联合唯一。 +""" + +from alembic import op + + +revision = '05df1e2f3a4b' +down_revision = '04cf1d2e3f4a' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """将盲测集唯一性由 Profile 维度扩展到 Profile checksum 维度。""" + with op.batch_alter_table('shipping_document_profile_test_suites') as batch: + batch.drop_constraint('uq_shipping_document_profile_test_suites_profile', type_='unique') + batch.create_unique_constraint( + 'uq_shipping_document_profile_test_suites_profile_checksum', + ['profile_id', 'profile_checksum'], + ) + + +def downgrade() -> None: + """回退为每个 Profile 仅一个盲测集的历史约束。""" + with op.batch_alter_table('shipping_document_profile_test_suites') as batch: + batch.drop_constraint('uq_shipping_document_profile_test_suites_profile_checksum', type_='unique') + batch.create_unique_constraint('uq_shipping_document_profile_test_suites_profile', ['profile_id']) diff --git a/backend/tests/test_shipping_document_profile_quality.py b/backend/tests/test_shipping_document_profile_quality.py index f52ffd61..f0896b2a 100644 --- a/backend/tests/test_shipping_document_profile_quality.py +++ b/backend/tests/test_shipping_document_profile_quality.py @@ -3,7 +3,7 @@ backend/tests/test_shipping_document_profile_quality.py 用途:验证订单文档模板的独立盲测、批准资格和冻结 checksum 门禁。 依赖:Profile 服务、布局快照、模板盲测服务与测试数据库。 -逻辑:管理员固化三份独立样本真值;全部通过且批准后才可放行确定性自动建单。 +逻辑:管理员固化一份独立样本真值;通过且批准后才可放行确定性自动建单。 """ from __future__ import annotations @@ -111,17 +111,12 @@ def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, Use return profile, user, documents -def test_profile_auto_create_requires_three_passing_blind_samples_and_approval(app): - """关键断言:三样本全通过和管理员批准缺一不可,批准后样本不可篡改。""" +def test_profile_auto_create_requires_one_passing_blind_sample_and_approval(app): + """关键断言:一份独立样本通过并经批准后才能放行,批准后样本不可篡改。""" with app.app_context(): profile, user, documents = _published_profile_with_samples() suite = quality.create_suite(profile_id=profile.id, actor_id=user.id) assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum) - for document in documents[:2]: - quality.add_sample( - suite_id=suite['id'], document_id=document.id, table_id='table-1', - expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id, - ) executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id) assert executed['latest_run']['status'] == 'failed' with pytest.raises(Exception) as caught: @@ -129,10 +124,11 @@ def test_profile_auto_create_requires_three_passing_blind_samples_and_approval(a assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY' quality.add_sample( - suite_id=suite['id'], document_id=documents[2].id, table_id='table-1', + suite_id=suite['id'], document_id=documents[0].id, table_id='table-1', expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id, ) - quality.execute_suite(suite_id=suite['id'], actor_id=user.id) + executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id) + assert executed['latest_run']['status'] == 'passed' approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id) assert approved['status'] == 'approved' assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum) @@ -144,6 +140,43 @@ def test_profile_auto_create_requires_three_passing_blind_samples_and_approval(a assert getattr(immutable.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE' +def test_independent_sample_review_reuses_existing_truth_and_excludes_training_input(app): + """关键断言:只展示同类未建模样本,逐项确认后才将候选写为既有盲测真值。""" + with app.app_context(): + profile, user, documents = _published_profile_with_samples() + # 仅专用模板样本可供日常盲测选择;训练文档必须始终被排除。 + for document in documents: + db.session.get(ShippingNoticeIntake, document.intake_id).purpose = 'order_document_profile_sample' + db.session.add(ShippingOrderDocumentProfileSample( + profile_id=profile.id, document_id=documents[0].id, table_id='table-1', + sample_role='training', created_by_id=user.id, + )) + db.session.commit() + suite = quality.create_suite(profile_id=profile.id, actor_id=user.id) + + available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples'] + assert {item['document_id'] for item in available} == {documents[1].id, documents[2].id} + candidate = quality.preview_independent_sample( + suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', actor_id=user.id, + ) + assert candidate['rows'] == [{'part_number': 'PN-1', 'qty': 3}] + with pytest.raises(Exception) as incomplete: + quality.confirm_sample_reviews( + suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', + row_reviews=[{'correct': None, 'values': candidate['rows'][0]}], + order_field_reviews={}, actor_id=user.id, + ) + assert getattr(incomplete.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID' + + confirmed = quality.confirm_sample_reviews( + suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', + row_reviews=[{'correct': True, 'values': {}}], order_field_reviews={}, actor_id=user.id, + ) + assert confirmed['sample_count'] == 1 + sample = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0] + assert sample.expected_rows_json == candidate['rows'] + + def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid(app): """v2 盲测直接回放坐标字段,HTML 网格即使不存在也不能成为质量执行依赖。""" with app.app_context(): @@ -178,6 +211,44 @@ def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes'] +def test_coordinate_blind_preview_skips_header_only_regions(app): + """关键断言:仅含订单字段的页不重建物理行,候选预览不会因空布局报 500。""" + with app.app_context(): + profile, user, documents = _published_profile_with_samples() + profile.definition_json = { + 'contract_version': 'order_coordinate_profile.v2', 'document_match': {'required_anchors': []}, + 'table_regions': [ + {'region_id': 'lines', 'page_scope': 'exact_page', 'page_no': 1, + 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [{ + 'layout_id': 'main', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + 'field_regions': [{'field_id': 'part-id', 'field_code': 'part_number', + 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + 'allowed_sources': ['pdf_coordinate']}], + }]}, + {'region_id': 'header_only', 'page_scope': 'exact_page', 'page_no': 2, + 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, + 'header_layouts': [{'layout_id': 'header', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .1}, 'field_regions': []}], + 'line_layouts': []}, + ], + } + for document in documents: + glyphs = [ + {'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 20, 'x1': 23 + index * 4, 'y1': 30}} + for index, char in enumerate('PN-1') + ] + record_inline_layout_snapshot(document, { + 'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready', + 'tables': [{'table_id': 'table-1', 'page_no': 1}], + 'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}}, + }) + db.session.commit() + suite = quality.create_suite(profile_id=profile.id, actor_id=user.id) + candidate = quality._candidate_for_sample(profile=profile, document_id=documents[0].id, table_id='table-1') + assert suite['id'] > 0 + assert candidate['rows'] == [] + + def test_profile_checksum_change_invalidates_approved_quality_credential(app): """关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。""" with app.app_context(): @@ -195,6 +266,21 @@ def test_profile_checksum_change_invalidates_approved_quality_credential(app): assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum) +def test_profile_change_supersedes_stale_draft_suite_and_creates_current_suite(app): + """保存模板后必须建立新 checksum 的盲测集,旧草稿真值不得继续阻断或背书。""" + with app.app_context(): + profile, user, _documents = _published_profile_with_samples() + stale = quality.create_suite(profile_id=profile.id, actor_id=user.id) + profile.checksum = 'd' * 64 + db.session.commit() + + current = quality.create_suite(profile_id=profile.id, actor_id=user.id) + assert current['id'] != stale['id'] + assert current['profile_checksum'] == 'd' * 64 + stale_suite = db.session.get(ShippingDocumentProfileTestSuite, stale['id']) + assert stale_suite.status == 'superseded' + + def test_blind_test_sample_removal_is_audited_and_approved_suite_is_immutable(app): """盲测草稿可受控删除样本并留痕,批准后的真值不得再被篡改。""" with app.app_context(): @@ -205,8 +291,15 @@ def test_blind_test_sample_removal_is_audited_and_approved_suite_is_immutable(ap expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id, ) sample_id = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0].id + serialized = quality.serialize_suite(db.session.get(ShippingDocumentProfileTestSuite, suite['id'])) + # 关键断言:工作台只得到移除定位信息,绝不返回人工确认的字段真值。 + assert serialized['samples'] == [{ + 'id': sample_id, 'document_id': documents[0].id, 'table_id': 'table-1', + 'filename': 'q0.pdf', 'page_no': 1, + }] removed = quality.remove_sample(suite_id=suite['id'], sample_id=sample_id, actor_id=user.id) assert removed['sample_count'] == 0 + assert removed['samples'] == [] audit = ShippingOrderDocumentProfileAudit.query.filter_by(profile_id=profile.id).order_by( ShippingOrderDocumentProfileAudit.id.desc(), ).first() @@ -244,7 +337,7 @@ def test_draft_publish_requires_independent_training_and_multiline_blind_gate(ap assert getattr(missing_suite.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST' suite = quality.create_suite(profile_id=profile.id, actor_id=user.id) - # Use different documents than the training sample. One sample is real multi-line evidence. + # One independent sample is enough, but it must still be genuine multi-line evidence. record_inline_layout_snapshot(documents[1], { 'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready', 'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': '
PartQty
PN-13
PN-24
'}], @@ -252,28 +345,9 @@ def test_draft_publish_requires_independent_training_and_multiline_blind_gate(ap quality.add_sample(suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', expected_rows=[ {'part_number': 'PN-1', 'qty': 3}, {'part_number': 'PN-2', 'qty': 4}, ], actor_id=user.id) - quality.add_sample(suite_id=suite['id'], document_id=documents[2].id, table_id='table-1', expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id) - assert quality.execute_suite(suite_id=suite['id'], actor_id=user.id)['latest_run']['status'] == 'failed' - - # A third independent document is necessary even when one sample is multi-line. - extra = ShippingNoticeDocument( - intake_id=documents[2].intake_id, asset_id=documents[2].asset_id, document_type='attachment', - attachment_key='quality-extra.pdf', filename='quality-extra.pdf', content_hash='e' * 64, - classification='order_notice', parse_status='parsed', extracted_text='PN-1 3', - ) - db.session.add(extra) - db.session.flush() - record_inline_layout_snapshot(extra, { - 'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready', - 'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': '
PartQty
PN-13
'}], - }) - db.session.commit() - quality.add_sample(suite_id=suite['id'], document_id=extra.id, table_id='table-1', expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id) executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id) assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes'] quality.approve_suite(suite_id=suite['id'], actor_id=user.id) - # This legacy fixture cannot be republished under the v2-only write contract, - # but its current approved credential proves the draft gate accepts independent evidence. assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.structure_fingerprint) diff --git a/backend/tests/test_shipping_notice_candidate_migration.py b/backend/tests/test_shipping_notice_candidate_migration.py index 666f526f..a7d4cb6a 100644 --- a/backend/tests/test_shipping_notice_candidate_migration.py +++ b/backend/tests/test_shipping_notice_candidate_migration.py @@ -78,6 +78,55 @@ def test_candidate_content_fingerprint_migration_upgrade_and_downgrade(): migration.op = original_op +def test_candidate_acceptance_lifecycle_migration_is_conservative_and_reversible(): + """迁移只自动接受已消费记录,未消费 legacy selected 记录必须保持 provisional。""" + engine = sa.create_engine('sqlite:///:memory:') + metadata = sa.MetaData() + sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table('shipping_tasks', metadata, sa.Column('id', sa.Integer(), primary_key=True)) + sa.Table( + 'shipping_notice_candidates', metadata, + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('selected', sa.Boolean(), nullable=False, server_default=sa.text('true')), + sa.Column('is_current_version', sa.Boolean(), nullable=False, server_default=sa.text('true')), + sa.Column('consumed_task_id', sa.Integer(), nullable=True), + ) + metadata.create_all(engine) + migration = importlib.import_module( + 'migrations.versions.029f0a1b2c3d_add_shipping_candidate_acceptance_lifecycle' + ) + with engine.begin() as connection: + connection.execute(sa.text( + "INSERT INTO shipping_notice_candidates (id, selected, is_current_version, consumed_task_id) " + "VALUES (1, 1, 1, NULL), (2, 1, 1, 99)" + )) + operations = Operations(MigrationContext.configure(connection)) + original_op = migration.op + migration.op = operations + try: + migration.upgrade() + inspector = sa.inspect(connection) + columns = {column['name'] for column in inspector.get_columns('shipping_notice_candidates')} + assert { + 'candidate_status', 'candidate_status_before_superseded', 'acceptance_mode', + 'accepted_at', 'accepted_by_id', 'acceptance_reason', 'acceptance_policy_version', + } <= columns + statuses = connection.execute(sa.text( + 'SELECT id, candidate_status, acceptance_mode FROM shipping_notice_candidates ORDER BY id' + )).all() + assert statuses == [(1, 'provisional', None), (2, 'accepted', 'legacy')] + assert 'ix_shipping_notice_candidates_fulfillment_gate' in { + index['name'] for index in inspector.get_indexes('shipping_notice_candidates') + } + + migration.downgrade() + columns = {column['name'] for column in sa.inspect(connection).get_columns('shipping_notice_candidates')} + assert 'candidate_status' not in columns + assert 'acceptance_mode' not in columns + finally: + migration.op = original_op + + def _order_extraction_pre_migration_schema(engine: sa.Engine) -> None: """创建 e0f1 迁移所需的 d9 版本最小表结构与旧唯一约束。""" metadata = sa.MetaData() diff --git a/backend/tests/test_shipping_notice_intakes.py b/backend/tests/test_shipping_notice_intakes.py index cad4d868..c6cbe536 100644 --- a/backend/tests/test_shipping_notice_intakes.py +++ b/backend/tests/test_shipping_notice_intakes.py @@ -117,6 +117,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client): }, validation_status='needs_review', conflicts_json=[{'field': 'qty'}], + extraction_source='dify_workflow', selected=True, duplicate_resolution='open_existing', duplicate_target_task_no=existing.task_no, @@ -143,10 +144,40 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client): patched = patch_response.get_json()['data'] assert patched['selected'] is False assert patched['validation_status'] == 'ready' + + # 模拟重复任务在审核完成前被关闭,采纳必须重新通过实时重复门禁。 + with app.app_context(): + existing = ShippingTask.query.filter_by(task_no='SN-CANDIDATE-EXISTING-001').one() + db.session.delete(existing) + db.session.commit() + + promote_response = client.post( + '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001/promote', + headers=owner_headers, + ) + assert promote_response.status_code == 200 + promoted = promote_response.get_json()['data'] + assert promoted['candidate_status'] == 'accepted' + assert promoted['acceptance_mode'] == 'manual' + assert promoted['selected'] is True + + repeated = client.post( + '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001/promote', + headers=owner_headers, + ) + assert repeated.status_code == 200 + assert repeated.get_json()['data']['candidate_status'] == 'accepted' assert patched['conflicts'] == [] assert patched['content_fingerprint'] assert patched['duplicate_resolution'] is None + with app.app_context(): + db.session.add(ShippingTask( + task_no='SN-CANDIDATE-EXISTING-001', user_id=owner.id, + source_content_hash='candidate-api-content-hash', process_status='created', + )) + db.session.commit() + forbidden = client.patch( '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001', json={'selected': True}, @@ -349,6 +380,7 @@ def test_candidate_batch_gate_rejects_incomplete_expired_and_selection_drift(app validation_status='ready', conflicts_json=[], selected=True, + candidate_status='accepted', duplicate_status='none', ) db.session.add(candidate) @@ -402,6 +434,25 @@ def test_candidate_batch_gate_rejects_incomplete_expired_and_selection_drift(app assert none_selected.value.code == 'SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED' +def test_candidate_batch_gate_requires_accepted_lifecycle(app, shipping_user): + """provisional Candidate 即使保留旧 selected 标记,也绝不能绕过履约门禁。""" + from app.services.shipping_notice.candidate_service import ensure_candidate_fulfillment_ready + + with app.app_context(): + candidate = ShippingNoticeCandidate( + candidate_no='SNC-ACCEPTANCE-GATE', candidate_key='acceptance-gate', + intake_id=1, primary_document_id=1, selected=True, + candidate_status='provisional', is_current_version=True, + validation_status='ready', conflicts_json=[], + ) + with pytest.raises(ConflictError) as provisional: + ensure_candidate_fulfillment_ready(candidate) + assert provisional.value.code == 'SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED' + + candidate.candidate_status = 'accepted' + ensure_candidate_fulfillment_ready(candidate) + + def test_candidate_era_intake_without_candidates_cannot_fallback_to_single_eml_task(app, shipping_user): """v6 Intake 无 Candidate 时必须阻断,不得退回整封 EML 建一个旧式 Task。""" with app.app_context(): @@ -551,6 +602,7 @@ def test_one_eml_intake_candidates_create_one_batch_multiple_tasks(app, shipping validation_status='ready', conflicts_json=[], selected=True, + candidate_status='accepted', business_fingerprint=identity['fingerprint'], fingerprint_version=identity['version'], fingerprint_strength=identity['strength'], diff --git a/backend/tests/test_shipping_notice_order_extraction.py b/backend/tests/test_shipping_notice_order_extraction.py index 353358ab..1324957a 100644 --- a/backend/tests/test_shipping_notice_order_extraction.py +++ b/backend/tests/test_shipping_notice_order_extraction.py @@ -28,6 +28,7 @@ from app.models import ( ShippingTask, ShippingTaskEvent, ShippingOrderExtraction, + ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, @@ -37,6 +38,7 @@ from app.models import ( from app.services.chat.log_service import merge_chat_log_payload from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary from app.services.shipping_notice.order_extraction import persist_order_extraction_result +from app.services.shipping_notice.order_extraction_workflow import parse_order_extraction_workflow_result from app.services.shipping_notice.open_existing_reservation_backfill import ( backfill_exact_file_open_existing_reservations, ) @@ -449,11 +451,9 @@ def test_order_field_display_uses_current_catalog_sequence(app): with app.app_context(): _ensure_order_schema() version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() - fields = [dict(item) for item in (version.definition_json or {}).get('fields') or []] - sequence_by_code = {'qty': 1, 'part_number': 2, 'reservation_id': 3, 'po_number': 4} - for field in fields: - field['sequence'] = sequence_by_code.get(str(field.get('field_code')), 99) - version.definition_json = {**(version.definition_json or {}), 'fields': fields} + sequence_by_code = {'part_number': 1, 'qty': 2, 'reservation_id': 3, 'po_number': 4} + for field in ShippingOrderField.query.filter_by(schema_id=version.schema_id).all(): + field.display_sequence = sequence_by_code.get(str(field.field_code), 99) task = ShippingTask( task_no='SN-ORDER-DISPLAY-SEQUENCE', process_status='parsed', source_type='manual', po_number='PO-001', lines_json=[{'part_number': 'SKU-1', 'qty': 2}], @@ -522,8 +522,8 @@ def _add_extraction_intake( return intake, document -def test_persist_order_extraction_result_supports_multiple_orders_partial_success_and_replay(app): - """一个附件可产生多 Candidate;高置信订单自动建单,低置信订单保留,重试只回放。""" +def test_persist_order_extraction_result_keeps_provider_orders_provisional_and_replayable(app): + """Provider 结果无论置信度高低均先形成 provisional Candidate,重试只回放。""" with app.app_context(): user, session, intake, document, runtime_context = _seed_extraction_input() context_result = _build_test_extraction_context({'agent_runtime_context': runtime_context}) @@ -559,26 +559,20 @@ def test_persist_order_extraction_result_supports_multiple_orders_partial_succes } result = _persist_test_orders(payload) - # 断言一附件拆成两个 Candidate,仅高置信订单创建 Task,Intake 保留为部分完成。 - assert result['created_count'] == 1 + # Dify/Provider 结果不得直接建单;阶段二才允许受控确定性模板自动接受。 + assert result['created_count'] == 0 assert result['opened_existing_count'] == 0 - assert result['pending_count'] == 1 + assert result['pending_count'] == 2 assert result['non_shipping_count'] == 0 - assert result['created_with_missing_fields_count'] == 1 - assert result['message'] == ( - '已创建 1 个发货任务;另有 1 个订单需要补充信息或处理冲突。' - '其中 1 个新建任务仍缺少 Reservation ID,可通过自然对话补充。' - ) - assert result['batch_no'] + assert result['created_with_missing_fields_count'] == 0 + assert result['batch_no'] is None candidates = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).all() assert len(candidates) == 2 assert len({item.candidate_key for item in candidates}) == 2 + assert {item.candidate_status for item in candidates} == {'provisional'} + assert all(item.selected is False for item in candidates) tasks = ShippingTask.query.filter_by(user_id=int(user.id)).all() - assert len(tasks) == 1 - task = tasks[0] - assert task.process_status == 'pending_review' - assert task.pending_human_reason == 'rsv_req' - assert (task.step_payload_json or {})['process_field_gate']['missing_fields'] == ['reservation_id'] + assert tasks == [] db.session.refresh(intake) assert intake.parse_status == 'parsed' # 低置信订单仍未消费,因此 Intake 抽取终态必须保留为 partially_completed。 @@ -586,35 +580,13 @@ def test_persist_order_extraction_result_supports_multiple_orders_partial_succes db.session.refresh(document) assert len((document.order_extraction_result_json or {})['candidate_keys']) == 2 - # 断言后台或自然语言“继续”无法绕过字段门禁进入库存流程。 - app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True - progress = auto_progress({'task_id': task.task_no}) - assert progress['status'] == 'needs_human' - assert progress['checkpoint'] == 'rsv_req' - assert 'ensure_inventory' in progress['forbidden_next_tools'] - replay = _persist_test_orders(payload) assert replay['idempotent_replay'] is True - assert replay['created_count'] == 1 + assert replay['created_count'] == 0 assert replay['opened_existing_count'] == 0 - assert replay['pending_count'] == 1 - assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 1 + assert replay['pending_count'] == 2 + assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0 assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 2 - - edit_result = update_notice_line({ - 'task_id': task.task_no, - 'line_index': 0, - 'patch': { - 'reservation_id': '1000140351', - }, - 'comment': '用户通过自然对话补齐流程字段', - }) - db.session.refresh(task) - # 断言既有行更新 Tool 可完成自然对话补字段,并清除旧流程字段门禁。 - assert edit_result['status'] == 'ok' - assert task.pending_human_reason == 'low_confidence' - assert 'process_field_gate' not in (task.step_payload_json or {}) - assert task.current_order_extraction_id is not None assert session.user_id == user.id @@ -642,10 +614,38 @@ def test_shadow_mode_persists_ready_candidate_without_creating_task(app): assert result['pending_count'] == 1 assert result['pending_orders'][0]['reasons'] == ['auto_create_disabled'] assert candidate.validation_status == 'ready' + assert candidate.candidate_status == 'provisional' assert candidate.selected is False assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0 +def test_approved_deterministic_marker_is_the_only_automatic_acceptance_source(app): + """已批准固定模板的后端标记可自动接受;普通 Provider 结果仍须人工采纳。""" + with app.app_context(): + _user, _session, intake, document, runtime_context = _seed_extraction_input() + context = _build_test_extraction_context({'agent_runtime_context': runtime_context}) + order = _order( + intake_no=intake.intake_no, document_id=int(document.id), po_number='4510000001', + part_number='SKU-A', qty=10, include_process_fields=True, + ) + order['_hxops_acceptance'] = 'approved_deterministic_profile_v1' + + _persist_shadow_orders({'input_snapshot_hash': context['input_snapshot_hash'], 'orders': [order]}) + + candidate = ShippingNoticeCandidate.query.filter_by(intake_id=intake.id).one() + assert candidate.candidate_status == 'accepted' + assert candidate.acceptance_mode == 'automatic' + assert candidate.extraction_source == 'approved_deterministic_profile' + assert candidate.selected is True + + +def test_workflow_result_accepts_only_documented_data_orders_wrapper(): + """Dify End 允许 data.orders 包装,但不把内部接受字段当作可信输入。""" + assert parse_order_extraction_workflow_result({ + 'status': 'succeeded', 'outputs': {'orders': {'data': {'orders': [{'id': 'one'}]}}}, + }) == [{'id': 'one'}] + + def test_persist_order_extraction_result_consumes_empty_and_confident_non_shipping_results(app): """空 orders[] 与高置信非发货分类均不生成 Candidate,并返回明确的未建单事实。""" with app.app_context(): diff --git a/backend/tests/test_shipping_order_document_profile_service.py b/backend/tests/test_shipping_order_document_profile_service.py index 43ee619c..3b63096d 100644 --- a/backend/tests/test_shipping_order_document_profile_service.py +++ b/backend/tests/test_shipping_order_document_profile_service.py @@ -128,6 +128,195 @@ def test_coordinate_profile_v2_requires_schema_source_authorization_and_freezes_ assert saved['definition']['contract_version'] == 'order_coordinate_profile.v2' +def test_order_field_layout_is_independent_from_line_layout_and_freezes_header_field(app): + """订单级字段必须冻结 Header 身份,且不写入表头或物理行字段区域。""" + with app.app_context(): + schema = _schema_version() + schema.definition_json['fields'].append({ + 'field_id': 'po-field', 'field_code': 'po_number', 'scope': 'header', + 'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim', + 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'], + }) + definition = _coordinate_definition() + definition['order_field_layouts'] = [{ + 'layout_id': 'po_number', 'field_id': 'forged', 'field_code': 'po_number', + 'page_scope': 'first_page', + 'anchor': {'anchor_id': 'po_label', 'text': 'PO NO', 'aliases': ['PO NUMBER']}, + 'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1}, + 'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': True, + 'minimum_evidence_level': 'coordinate', + }] + saved = service.save_draft({ + 'profile_code': 'ORDER_FIELD', 'display_name': 'Order field', + 'schema_version_id': schema.id, 'definition': definition, + }, actor_id=None) + order_field = saved['definition']['order_field_layouts'][0] + assert order_field['field_id'] == 'po-field' + assert order_field['anchor']['aliases'] == ['PO NUMBER'] + assert all( + item['field_code'] != 'po_number' + for item in saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'] + ) + + +def test_order_field_layout_duplicate_returns_bound_schema_code(app): + """同一 Header 字段重复绑定时必须返回具体字段编码,不能退化成泛化契约错误。""" + with app.app_context(): + schema = _schema_version() + schema.definition_json['fields'].append({ + 'field_id': 'ship-to-field', 'field_code': 'ship_to_customer', 'scope': 'header', + 'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim', + 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'], + }) + definition = _coordinate_definition() + definition['order_field_layouts'] = [ + { + 'layout_id': f'ship_to_{index}', 'field_id': '', 'field_code': 'ship_to_customer', + 'page_scope': 'exact_page', 'page_no': 1, + 'anchor': {'anchor_id': f'ship_to_label_{index}', 'text': f'SHIP TO {index}'}, + 'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1}, + 'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False, + 'minimum_evidence_level': 'coordinate', + } + for index in (1, 2) + ] + with pytest.raises(Exception) as caught: + service.save_draft({ + 'profile_code': 'ORDER_FIELD_DUPLICATE', 'display_name': 'Order field duplicate', + 'schema_version_id': schema.id, 'definition': definition, + }, actor_id=None) + + # 关键断言:前端可用 details 精确指出重复字段,而不是只能显示通用配置无效。 + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID' + assert getattr(caught.value, 'details', {}).get('field_codes') == ['ship_to_customer'] + + +def test_order_field_layouts_can_share_one_anchor_with_distinct_layout_ids(app): + """账款客户和地址同一行时可共享标签证据,但必须各自保存为独立字段布局。""" + with app.app_context(): + schema = _schema_version() + schema.definition_json['fields'].extend([ + { + 'field_id': 'bill-to-customer', 'field_code': 'bill_to_customer', 'scope': 'header', + 'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim', + 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'], + }, + { + 'field_id': 'bill-to-address', 'field_code': 'bill_to_address', 'scope': 'header', + 'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim', + 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'], + }, + ]) + definition = _coordinate_definition() + shared_anchor = { + 'anchor_id': 'invoice_bill_sold_to', 'text': 'INVOICE BILL/SOLD TO', + 'region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .25}, + } + definition['order_field_layouts'] = [ + { + 'layout_id': 'bill_to_customer_layout', 'field_id': '', 'field_code': 'bill_to_customer', + 'page_scope': 'exact_page', 'page_no': 2, 'anchor': shared_anchor, + 'value_region': {'x0': 1, 'y0': 0, 'x1': 3, 'y1': 1}, + 'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False, + 'minimum_evidence_level': 'coordinate', + }, + { + 'layout_id': 'bill_to_address_layout', 'field_id': '', 'field_code': 'bill_to_address', + 'page_scope': 'exact_page', 'page_no': 2, 'anchor': shared_anchor, + 'value_region': {'x0': 3, 'y0': 0, 'x1': 10, 'y1': 1}, + 'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False, + 'minimum_evidence_level': 'coordinate', + }, + ] + saved = service.save_draft({ + 'profile_code': 'BILL_TO_SHARED_ANCHOR', 'display_name': 'Bill to shared anchor', + 'schema_version_id': schema.id, 'definition': definition, + }, actor_id=None) + + # 关键断言:共享标签没有重复绑定 Schema 字段,也不会复用 layout_id。 + assert [item['layout_id'] for item in saved['definition']['order_field_layouts']] == [ + 'bill_to_customer_layout', 'bill_to_address_layout', + ] + + +def test_order_field_layout_rejects_line_field_and_unbounded_value_only_mode(app): + """订单字段不得借用明细字段;无锚点坐标回退必须限制在单页。""" + with app.app_context(): + schema = _schema_version() + definition = _coordinate_definition() + definition['order_field_layouts'] = [{ + 'layout_id': 'invalid_line', 'field_id': '', 'field_code': 'part_number', + 'page_scope': 'all_pages', 'anchor': None, + 'value_region': None, + 'fallback_value_region': {'x0': .4, 'y0': .1, 'x1': .8, 'y1': .16}, + 'value_mode': 'single_line', 'stop_anchors': [], 'required': False, + 'minimum_evidence_level': 'coordinate', + }] + with pytest.raises(Exception) as caught: + service.save_draft({ + 'profile_code': 'INVALID_ORDER_FIELD', 'display_name': 'Invalid order field', + 'schema_version_id': schema.id, 'definition': definition, + }, actor_id=None) + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID' + + +def test_order_field_layout_freezes_schema_normalizer_and_rejects_a_mismatch(app): + """订单字段不能让浏览器替换 Schema 的规范化策略,保存结果必须冻结 Schema key。""" + with app.app_context(): + schema = _schema_version() + schema.definition_json['fields'].append({ + 'field_id': 'po-field', 'field_code': 'po_number', 'scope': 'header', + 'value_type': 'string', 'enabled': True, 'normalizer_key': 'uppercase_trim', + 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'], + }) + definition = _coordinate_definition() + definition['order_field_layouts'] = [{ + 'layout_id': 'po_number', 'field_id': '', 'field_code': 'po_number', + 'page_scope': 'exact_page', 'page_no': 1, + 'fallback_value_region': {'x0': .4, 'y0': .1, 'x1': .8, 'y1': .16}, + 'value_mode': 'single_line', 'stop_anchors': [], 'required': False, + 'minimum_evidence_level': 'coordinate', + }] + saved = service.save_draft({ + 'profile_code': 'ORDER_FIELD_NORMALIZER', 'display_name': 'Order field normalizer', + 'schema_version_id': schema.id, 'definition': definition, + }, actor_id=None) + assert saved['definition']['order_field_layouts'][0]['normalizer_key'] == 'uppercase_trim' + + definition['order_field_layouts'][0]['normalizer_key'] = 'trim' + with pytest.raises(Exception) as caught: + service.save_draft({ + 'profile_code': 'ORDER_FIELD_BAD_NORMALIZER', 'display_name': 'Bad normalizer', + 'schema_version_id': schema.id, 'definition': definition, + }, actor_id=None) + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID' + + +def test_order_field_ocr_minimum_level_keeps_native_pdf_as_stronger_allowed_source(app): + """OCR 最低证据允许更强的原生 PDF 坐标,不能把 Schema 授权错误收窄为 OCR-only。""" + with app.app_context(): + schema = _schema_version() + schema.definition_json['fields'].append({ + 'field_id': 'po-field', 'field_code': 'po_number', 'scope': 'header', + 'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim', + 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'], + }) + definition = _coordinate_definition() + definition['order_field_layouts'] = [{ + 'layout_id': 'po_number', 'field_id': '', 'field_code': 'po_number', + 'page_scope': 'first_page', 'anchor': {'anchor_id': 'po', 'text': 'PO NO'}, + 'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1}, 'value_mode': 'right_of_anchor', + 'stop_anchors': [], 'required': False, 'minimum_evidence_level': 'ocr_coordinate', + }] + + saved = service.save_draft({ + 'profile_code': 'ORDER_FIELD_OCR_MINIMUM', 'display_name': 'Order field OCR minimum', + 'schema_version_id': schema.id, 'definition': definition, + }, actor_id=None) + + assert saved['definition']['order_field_layouts'][0]['minimum_evidence_level'] == 'ocr_coordinate' + + def test_composite_coordinate_binding_freezes_all_registered_output_fields(app): """复合解析器的辅助输出也必须以 field_id 冻结;缺少任何输出字段时拒绝保存。""" with app.app_context(): @@ -359,6 +548,58 @@ def test_schema_migration_replaces_only_breaking_field_and_keeps_revalidation_st field = migrated['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0] assert field['field_id'] == 'replacement-field' assert field['field_code'] == 'supplier_part_number' + + +def test_schema_migration_preserves_unbound_order_field_region_and_blocks_publish(app, monkeypatch): + """删除订单字段时保留锚点/值区,并在管理员重新绑定前阻止新模板发布。""" + with app.app_context(): + monkeypatch.setattr( + 'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None, + ) + source_schema = _schema_version() + source_schema.definition_json = { + **source_schema.definition_json, + 'fields': [*source_schema.definition_json['fields'], { + 'field_id': 'po-field', 'field_code': 'po_number', 'scope': 'header', + 'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim', + 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'], + }], + } + db.session.commit() + definition = _coordinate_definition() + definition['order_field_layouts'] = [{ + 'layout_id': 'po_number', 'field_id': '', 'field_code': 'po_number', + 'page_scope': 'first_page', + 'anchor': {'anchor_id': 'po_label', 'text': 'PO NO'}, + 'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1}, + 'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False, + 'minimum_evidence_level': 'coordinate', + }] + draft = service.save_draft({ + 'profile_code': 'ORDER_FIELD_MIGRATION', 'display_name': 'Order field migration', + 'schema_version_id': source_schema.id, 'definition': definition, + }, actor_id=None) + published = service.publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version']) + source_schema.status = 'retired' + target_schema = ShippingOrderSchemaVersion( + schema_id=source_schema.schema_id, version=2, status='published', checksum='d' * 64, + published_at=datetime.utcnow(), definition_json={'fields': [ + dict(item) for item in source_schema.definition_json['fields'] if item['field_id'] != 'po-field' + ]}, + ) + db.session.add(target_schema) + db.session.commit() + migrated = service.create_schema_migration_draft( + published['id'], target_schema_version_id=target_schema.id, + resolutions={'po-field': {'action': 'unbind'}}, actor_id=None, + ) + assert migrated['definition']['order_field_layouts'] == [] + unbound = migrated['definition']['draft_unbound_order_field_layouts'][0] + assert unbound['layout_id'] == 'po_number' + assert unbound['anchor']['text'] == 'PO NO' + with pytest.raises(Exception) as caught: + service.publish(migrated['id'], actor_id=None, expected_lock_version=migrated['lock_version']) + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID' assert migrated['migration_status'] == 'needs_revalidation' model = db.session.get(ShippingOrderDocumentProfile, migrated['id']) @@ -1106,6 +1347,36 @@ def test_profile_sample_delete_only_allows_unreferenced_dedicated_samples(app, m assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED' +def test_delete_draft_cascades_blind_test_suite(app): + """关键断言:删除草稿 Profile 时一并清理盲测套件,避免外键约束导致 500。""" + with app.app_context(): + user = User(username='draft-delete-admin', email='draft-delete@example.com', role='admin', status='active') + schema = _schema_version() + db.session.add(user) + db.session.flush() + profile = ShippingOrderDocumentProfile( + profile_code='DRAFT_DELETE_SUITE', display_name='Draft delete suite', version=1, + status='draft', schema_version_id=schema.id, + structure_fingerprint='3' * 64, definition_json={}, checksum='3' * 64, + lock_version=1, + ) + db.session.add(profile) + db.session.flush() + suite = ShippingDocumentProfileTestSuite( + profile_id=profile.id, profile_checksum=profile.checksum or profile.structure_fingerprint, + created_by_id=user.id, + ) + db.session.add(suite) + db.session.commit() + suite_id = suite.id + profile_id = profile.id + + service.delete_draft(profile_id) + + assert db.session.get(ShippingOrderDocumentProfile, profile_id) is None + assert db.session.get(ShippingDocumentProfileTestSuite, suite_id) is None + + def test_profile_rejects_legacy_grid_definition(app): """关键断言:新 Profile 不能再混入 HTML 网格、表头行号或固定列映射。""" with app.app_context(): @@ -1169,8 +1440,8 @@ def test_workbench_draft_can_save_without_bound_fields(app): assert saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'] == [] -def test_workbench_draft_preserves_unbound_regions_but_publish_rejects_them(app): - """未绑定框可随草稿恢复,但在完成 Schema 绑定前禁止发布。""" +def test_workbench_auto_suggested_unbound_regions_do_not_block_publish(app, monkeypatch): + """自动标记的非关键候选可保留展示,不能阻断已经通过质量门禁的模板发布。""" with app.app_context(): schema = _schema_version() saved = service.save_draft({ @@ -1194,6 +1465,29 @@ def test_workbench_draft_preserves_unbound_regions_but_publish_rejects_them(app) }, }, actor_id=None) assert saved['definition']['table_regions'][0]['draft_unbound_field_regions'][0]['label'] == '未绑定列 1' + monkeypatch.setattr( + 'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None, + ) + assert service.publish(saved['id'], actor_id=None, expected_lock_version=saved['lock_version'])['status'] == 'published' + + +def test_schema_migration_unbound_regions_still_block_publish(app, monkeypatch): + """只有 Schema breaking migration 明确遗留的待绑定区域才会阻止发布。""" + with app.app_context(): + schema = _schema_version() + payload = _coordinate_definition() + payload['table_regions'][0]['draft_unbound_field_regions'] = [{ + 'region_id': 'migration-main-part-field', 'parent_layout_id': 'main', + 'label': 'part_number', 'region': {'x0': .1, 'y0': .4, 'x1': .3, 'y1': .5}, + 'requires_rebinding': True, + }] + saved = service.save_draft({ + 'profile_code': 'UNBOUND_MIGRATION', 'display_name': 'Unbound migration', + 'schema_version_id': schema.id, 'definition': payload, + }, actor_id=None) + monkeypatch.setattr( + 'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None, + ) with pytest.raises(Exception) as caught: service.publish(saved['id'], actor_id=None, expected_lock_version=saved['lock_version']) assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID' @@ -1358,3 +1652,294 @@ def test_coordinate_suggestion_can_return_only_requested_physical_row(app, monke # 当前行识别只返回 row_offset=1,首行建议不会混入响应。 assert [item['row_offset'] for item in result['subrow_layouts']] == [1] assert result['subrow_layouts'][0]['column_samples'] == [['VENDOR-20']] + + +def test_coordinate_suggestion_binds_line_columns_from_enabled_field_rules(app, monkeypatch): + """明细表头仅在唯一别名且字段启用自动标记时绑定相应列。""" + characters = [] + source_index = 0 + for row_index, row in enumerate([ + [('ITEMNO', 12), ('MATERIALNO', 100), ('QTY', 270)], + [('00020', 12), ('PART-20', 100), ('36', 270)], + ]): + for text, x0 in row: + for character_index, character in enumerate(text): + if character == ' ': + continue + characters.append({ + 'text': character, 'source_index': source_index, + 'bbox': { + 'x0': x0 + character_index * 5, 'y0': 10 + row_index * 20, + 'x1': x0 + (character_index + 1) * 5, 'y1': 20 + row_index * 20, + }, + }) + source_index += 1 + layout = { + 'tables': [{'table_id': 'schema-suggest', 'bbox': {'x0': 0, 'y0': 0, 'x1': 320, 'y1': 70}, + 'html': '
broken
'}], + 'coordinate_evidence': {'tables': {'schema-suggest': characters}, 'pages': {'1': {'width': 320, 'height': 70}}}, + } + version = SimpleNamespace(definition_json={'fields': [ + {'field_id': 'line', 'field_code': 'line_no', 'scope': 'line', 'enabled': True, + 'display_name': 'Item number', 'aliases': ['ITEM NO'], 'allowed_sources': ['pdf_coordinate']}, + {'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'enabled': True, + 'display_name': 'Material number', 'aliases': ['MATERIAL NO'], 'allowed_sources': ['pdf_coordinate']}, + {'field_id': 'qty', 'field_code': 'qty', 'scope': 'line', 'enabled': True, + 'display_name': 'Quantity', 'aliases': ['QTY'], 'allowed_sources': ['pdf_coordinate'], + 'auto_annotation_enabled': False}, + ]}) + monkeypatch.setattr(db.session, 'get', lambda model, object_id: object() if object_id == 106 else None) + monkeypatch.setattr(service, '_document_layout', lambda document: layout) + monkeypatch.setattr(service, '_require_schema_version', lambda value: version) + + with app.app_context(): + result = service.suggest_coordinate_reconstruction( + {'document_id': 106, 'table_id': 'schema-suggest', 'schema_version_id': 1}, actor_id=None, + ) + + header_codes = [field['field_code'] for field in result['header_regions'][0]['fields']] + assert header_codes == ['line_no', 'part_number', None] + # The disabled automatic marker never produces a table-header or detail-column binding. + assert result['subrow_layouts'][0]['suggested_field_codes'] == ['line_no', 'part_number', None] + + +def test_coordinate_suggestion_binds_line_columns_from_normalized_field_codes(app, monkeypatch): + """没有维护别名时,稳定 field_code 仍可精确对应常见空格表头。""" + characters = [] + for row_index, row in enumerate([ + [('ITEM NO', 12), ('UNIT PRICE', 90), ('ORDER QUANTITY', 210)], + [('00020', 12), ('941.760000', 90), ('30', 210)], + ]): + for text, x0 in row: + for character_index, character in enumerate(text): + if character != ' ': + characters.append({'text': character, 'bbox': { + 'x0': x0 + character_index * 5, 'y0': 10 + row_index * 20, + 'x1': x0 + (character_index + 1) * 5, 'y1': 20 + row_index * 20, + }}) + layout = { + 'tables': [{'table_id': 'code-suggest', 'bbox': {'x0': 0, 'y0': 0, 'x1': 320, 'y1': 70}}], + 'coordinate_evidence': {'tables': {'code-suggest': characters}, 'pages': {'1': {'width': 320, 'height': 70}}}, + } + version = SimpleNamespace(definition_json={'fields': [ + {'field_id': 'line', 'field_code': 'line_no', 'scope': 'line', 'enabled': True, + 'display_name': '项次', 'aliases': ['ITEM NO'], 'allowed_sources': ['pdf_coordinate']}, + {'field_id': 'price', 'field_code': 'unit_price', 'scope': 'line', 'enabled': True, + 'display_name': '单价', 'aliases': [], 'allowed_sources': ['pdf_coordinate']}, + {'field_id': 'quantity', 'field_code': 'order_quantity', 'scope': 'line', 'enabled': True, + 'display_name': '数量', 'aliases': [], 'allowed_sources': ['pdf_coordinate']}, + ]}) + monkeypatch.setattr(db.session, 'get', lambda model, object_id: object() if object_id == 107 else None) + monkeypatch.setattr(service, '_document_layout', lambda document: layout) + monkeypatch.setattr(service, '_require_schema_version', lambda value: version) + + with app.app_context(): + result = service.suggest_coordinate_reconstruction( + {'document_id': 107, 'table_id': 'code-suggest', 'schema_version_id': 1}, actor_id=None, + ) + + assert result['subrow_layouts'][0]['suggested_field_codes'] == [ + 'line_no', 'unit_price', 'order_quantity', + ] + + +def test_order_field_suggestions_use_page_glyphs_and_never_auto_confirm(app, monkeypatch): + """订单字段自动标记只从整页唯一标签生成 needs_review 的锚点和值区候选。""" + glyphs = [] + for text, x0, y0 in [('PO NO: 45001', 20, 20), ('BILL TO: ACME', 20, 45), ('PO NO: duplicate', 20, 70)]: + for index, character in enumerate(text): + if character != ' ': + glyphs.append({'text': character, 'bbox': { + 'x0': x0 + index * 5, 'y0': y0, 'x1': x0 + index * 5 + 4, 'y1': y0 + 8, + }}) + layout = { + 'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}], + 'coordinate_evidence': { + 'pages': {'1': {'width': 300, 'height': 200}}, + 'page_glyphs': {'1': glyphs}, + 'sources': {'pages': {'1': 'pdf_coordinate'}}, + }, + } + version = type('Version', (), {'definition_json': {'fields': [ + {'field_id': 'po', 'field_code': 'customer_po', 'display_name': 'PO Number', 'scope': 'header', + 'aliases': ['PO NO'], 'allowed_sources': ['pdf_coordinate']}, + {'field_id': 'bill', 'field_code': 'bill_to', 'display_name': 'Bill To', 'scope': 'header', + 'aliases': ['BILL TO'], 'allowed_sources': ['pdf_coordinate']}, + ]}})() + document = type('Document', (), {'id': 104})() + monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 104 else None) + monkeypatch.setattr(service, '_require_schema_version', lambda value: version) + monkeypatch.setattr(service, '_document_layout', lambda document: layout) + + with app.app_context(): + result = service.suggest_order_field_layouts( + {'document_id': 104, 'schema_version_id': 1, 'page_no': 1}, actor_id=None, + ) + + by_code = {item['field_code']: item for item in result['order_field_candidates']} + assert result['status'] == 'needs_review' + assert by_code['bill_to']['status'] == 'suggested' + assert by_code['bill_to']['value_mode'] == 'right_of_anchor' + assert by_code['customer_po']['status'] == 'ambiguous' + + +def test_order_field_suggestions_keep_unbound_visual_labels_for_manual_binding(app, monkeypatch): + """未维护别名的订单抬头标签仍要出现成对框选,管理员随后在工作台绑定 Schema。""" + glyphs = [] + for index, character in enumerate('PURCHASE ORDER DATE: 06/20/2026'): + if character != ' ': + glyphs.append({'text': character, 'bbox': {'x0': 20 + index * 5, 'y0': 20, 'x1': 24 + index * 5, 'y1': 28}}) + layout = { + 'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}], + 'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}}, + } + version = type('Version', (), {'definition_json': {'fields': []}})() + document = type('Document', (), {'id': 105})() + monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 105 else None) + monkeypatch.setattr(service, '_require_schema_version', lambda value: version) + monkeypatch.setattr(service, '_document_layout', lambda document: layout) + + with app.app_context(): + result = service.suggest_order_field_layouts({'document_id': 105, 'schema_version_id': 1}, actor_id=None) + + candidate = result['order_field_candidates'][0] + assert candidate['binding_status'] == 'unbound' + assert candidate['anchor_text'] == 'PURCHASE ORDER DATE' + assert candidate['field_code'] == '' + + +def test_order_field_suggestions_backfill_page_glyphs_for_legacy_table_only_snapshot(app, monkeypatch): + """历史样本仅有表内字符时,建议前必须补齐整页证据以识别表格外的订单抬头。""" + document = type('Document', (), {'id': 106, 'asset_id': 3, 'filename': 'legacy.pdf'})() + asset = object() + layout = { + 'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}], + 'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'tables': {'lines': []}}, + } + monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 106 else asset if object_id == 3 else None) + monkeypatch.setattr(service, '_document_layout', lambda item: layout) + monkeypatch.setattr(service, '_require_schema_version', lambda value: type('Version', (), {'definition_json': {'fields': []}})()) + monkeypatch.setattr(service, '_ensure_page_coordinate_evidence', lambda **kwargs: { + **layout, 'coordinate_evidence': {**layout['coordinate_evidence'], + 'page_glyphs': {'1': [{'text': 'P', 'bbox': {'x0': 20, 'y0': 20, 'x1': 24, 'y1': 28}}, {'text': 'O', 'bbox': {'x0': 25, 'y0': 20, 'x1': 29, 'y1': 28}}, {'text': ':', 'bbox': {'x0': 30, 'y0': 20, 'x1': 34, 'y1': 28}}]}, + 'sources': {'pages': {'1': 'pdf_coordinate'}}}, + }) + + with app.app_context(): + result = service.suggest_order_field_layouts({'document_id': 106, 'schema_version_id': 1}, actor_id=None) + + assert result['order_field_candidates'][0]['anchor_text'] == 'PO' + + +def test_order_field_suggestions_split_inline_label_from_value_and_exclude_terms(app, monkeypatch): + """标签框只覆盖冒号前文本,值框只覆盖同一行值;表格前条款不应成为未绑定订单字段。""" + glyphs = [] + for text, y0 in [('PURCHASE ORDER DATE: 06/20/2026', 20), ('QUALITY: IF ANY DISCREPANCY FOUND', 85)]: + for index, character in enumerate(text): + if character != ' ': + glyphs.append({'text': character, 'bbox': {'x0': 20 + index * 5, 'y0': y0, 'x1': 24 + index * 5, 'y1': y0 + 8}}) + layout = { + 'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}], + 'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}}, + } + document = type('Document', (), {'id': 107})() + monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 107 else None) + monkeypatch.setattr(service, '_document_layout', lambda item: layout) + monkeypatch.setattr(service, '_require_schema_version', lambda value: type('Version', (), {'definition_json': {'fields': []}})()) + + with app.app_context(): + result = service.suggest_order_field_layouts({'document_id': 107, 'schema_version_id': 1}, actor_id=None) + + candidate = result['order_field_candidates'][0] + assert candidate['anchor_region']['x1'] < candidate['value_region']['x0'] + assert candidate['value_region']['x1'] < .75 + assert all(item['anchor_text'] != 'QUALITY' for item in result['order_field_candidates']) + + +def test_order_field_suggestions_keep_value_box_to_first_same_line_value_group(app, monkeypatch): + """同一视觉行含多个键值组时,首个订单字段值框不得吞掉下一个字段。""" + glyphs = [] + for text, x0 in [('PO NO: 451883152', 20), ('VERSION: 2', 190)]: + for index, character in enumerate(text): + if character != ' ': + glyphs.append({'text': character, 'bbox': { + 'x0': x0 + index * 5, 'y0': 20, 'x1': x0 + index * 5 + 4, 'y1': 28, + }}) + layout = { + 'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}], + 'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}}, + } + version = type('Version', (), {'definition_json': {'fields': [{ + 'field_id': 'po', 'field_code': 'customer_po', 'display_name': 'Customer PO', 'aliases': ['PO NO'], + 'scope': 'header', 'allowed_sources': ['pdf_coordinate'], 'auto_annotation_enabled': True, + }]}})() + document = type('Document', (), {'id': 109})() + monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 109 else None) + monkeypatch.setattr(service, '_document_layout', lambda item: layout) + monkeypatch.setattr(service, '_require_schema_version', lambda value: version) + + with app.app_context(): + result = service.suggest_order_field_layouts({'document_id': 109, 'schema_version_id': 1}, actor_id=None) + + candidate = result['order_field_candidates'][0] + # VERSION starts at 190/300. The PO value box must end before that next key/value group. + assert candidate['value_region']['x1'] < .64 + + +def test_order_field_suggestions_stop_value_before_adjacent_same_line_label(app, monkeypatch): + """无明显字间距时,值框仍须在同一行下一个标签冒号前停止。""" + glyphs = [] + text = 'PO NO: 451883152 VERSION: 2' + for index, character in enumerate(text): + if character != ' ': + glyphs.append({'text': character, 'bbox': { + 'x0': 20 + index * 5, 'y0': 20, 'x1': 24 + index * 5, 'y1': 28, + }}) + layout = { + 'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}], + 'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}}, + } + version = type('Version', (), {'definition_json': {'fields': [{ + 'field_id': 'po', 'field_code': 'customer_po', 'display_name': 'Customer PO', 'aliases': ['PO NO'], + 'scope': 'header', 'allowed_sources': ['pdf_coordinate'], 'auto_annotation_enabled': True, + }]}})() + document = type('Document', (), {'id': 110})() + monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 110 else None) + monkeypatch.setattr(service, '_document_layout', lambda item: layout) + monkeypatch.setattr(service, '_require_schema_version', lambda value: version) + + with app.app_context(): + result = service.suggest_order_field_layouts({'document_id': 110, 'schema_version_id': 1}, actor_id=None) + + # VERSION begins at character 17, x=105; the PO value must stop before it. + candidate = result['order_field_candidates'][0] + assert candidate['value_region']['x1'] < .36 + assert candidate['suggested_value'] == '451883152' + # An 8px text line on a 200px page gets at most 1px top/bottom padding. + value_region = result['order_field_candidates'][0]['value_region'] + assert value_region['y1'] - value_region['y0'] <= .05 + + +def test_order_field_suggestions_do_not_duplicate_bound_schema_field_as_unbound_label(app, monkeypatch): + """同一视觉行已绑定 order_date 时,完整文档标签不得再生成第二个未绑定候选。""" + glyphs = [] + for index, character in enumerate('PURCHASE ORDER DATE: 06/20/2026'): + if character != ' ': + glyphs.append({'text': character, 'bbox': {'x0': 20 + index * 5, 'y0': 20, 'x1': 24 + index * 5, 'y1': 28}}) + layout = { + 'tables': [{'table_id': 'lines', 'bbox': {'x0': 0, 'y0': 100, 'x1': 300, 'y1': 200}}], + 'coordinate_evidence': {'pages': {'1': {'width': 300, 'height': 200}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}}, + } + document = type('Document', (), {'id': 108})() + version = type('Version', (), {'definition_json': {'fields': [{ + 'field_id': 'date', 'field_code': 'order_date', 'display_name': 'Order Date', 'aliases': [], + 'scope': 'header', 'allowed_sources': ['pdf_coordinate'], + }]}})() + monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 108 else None) + monkeypatch.setattr(service, '_document_layout', lambda item: layout) + monkeypatch.setattr(service, '_require_schema_version', lambda value: version) + + with app.app_context(): + result = service.suggest_order_field_layouts({'document_id': 108, 'schema_version_id': 1}, actor_id=None) + + assert [(item['field_code'], item.get('binding_status')) for item in result['order_field_candidates']] == [('order_date', 'bound')] diff --git a/backend/tests/test_shipping_order_extraction_quality_gate.py b/backend/tests/test_shipping_order_extraction_quality_gate.py index c239606b..2aca1ee4 100644 --- a/backend/tests/test_shipping_order_extraction_quality_gate.py +++ b/backend/tests/test_shipping_order_extraction_quality_gate.py @@ -21,6 +21,8 @@ from app.jobs.queue import claim_next_job from app.jobs.types import JobType from app.models import ( Agent, + AgentRuntimeBinding, + ShippingOrderSchema, ShippingOrderExtractionQualityBatch, ShippingOrderExtractionQualityLabel, ShippingOrderExtractionRun, @@ -253,6 +255,9 @@ def test_approved_batch_is_listed_and_frozen_on_run(app): provider_agent_id=binding.id, enabled=True, quality_batch_id=batch.id, config={'auto_create_enabled': True}, ) + schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one() + schema.auto_creation_policy_json = {'enabled': True} + db.session.commit() listed = list_approved_quality_batches(owner_agent_id=owner.id) run, reused = create_order_extraction_run( @@ -279,6 +284,30 @@ def test_approved_batch_is_listed_and_frozen_on_run(app): assert run.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_QUALITY_GATE_BLOCKED' +def test_disabled_schema_keeps_runtime_auto_create_binding_in_shadow_mode(app): + """质量批次已配置时,Schema 总开关关闭仍可创建影子 Run,且不得触发自动建单。""" + with app.app_context(): + user, owner, session, intake, _document = _seed_run_input(suffix='QUALITY-SHADOW') + provider = Agent.query.filter_by(exposure_mode='internal').first() + binding = AgentRuntimeBinding.query.filter_by( + owner_agent_id=owner.id, capability_code='shipping.order_extraction', + ).one() + binding.config_json = {'timeout_seconds': 900, 'max_attempts': 3, 'auto_create_enabled': True} + binding.provider_agent_id = provider.id + # The missing quality batch is intentional: schema-disabled execution is shadow-only. + binding.quality_batch_id = None + db.session.commit() + + run, reused = create_order_extraction_run( + user=user, agent_id=owner.id, conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + + assert reused is False + assert run.provider_config_json['auto_create_enabled'] is False + assert run.input_snapshot_json['auto_creation_policy']['schema_enabled'] is False + assert run.input_snapshot_json['auto_creation_policy']['runtime_binding_enabled'] is True + def test_quality_batch_admin_api_is_protected_and_returns_safe_summary(app, client): """质量批次列表仅管理员可读,且响应不暴露 Run、字段值、引文或单条标签。""" with app.app_context(): diff --git a/backend/tests/test_shipping_order_extraction_runs.py b/backend/tests/test_shipping_order_extraction_runs.py index 3d951f05..951bf062 100644 --- a/backend/tests/test_shipping_order_extraction_runs.py +++ b/backend/tests/test_shipping_order_extraction_runs.py @@ -206,6 +206,29 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app): assert ShippingOrderExtractionUnit.query.count() == 1 +def test_schema_auto_create_switch_cannot_bypass_disabled_runtime_binding(app): + """Schema 总开关开启时,未显式启用 Runtime Binding 的 Run 仍必须保持影子模式。""" + with app.app_context(): + user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-CREATE-GATE') + schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one() + schema.auto_creation_policy_json = {'enabled': True} + db.session.commit() + + run, reused = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, + intake_nos=[intake.intake_no], + ) + + assert reused is False + assert run.provider_config_json['auto_create_enabled'] is False + policy = run.input_snapshot_json['auto_creation_policy'] + assert policy == { + 'enabled': False, + 'schema_enabled': True, + 'runtime_binding_enabled': False, + } + + def test_run_v3_freezes_layout_schema_candidate_without_exposing_it_to_dify(app): """Run v3 应冻结真实 layout cell 映射,但 Workflow Manifest 必须完全剥离内部证据。""" from app.services.shipping_notice.document_layout.html_layout import build_html_layout_candidate @@ -1383,7 +1406,7 @@ def test_failed_reparse_restores_source_candidate_version(app): candidate = ShippingNoticeCandidate( candidate_no='SNC-REPARSE-RESTORE', intake_id=intake.id, primary_document_id=document.id, candidate_key='restore-version', order_extraction_run_id=source.id, - selected=True, is_current_version=True, validation_status='ready', + selected=True, candidate_status='accepted', is_current_version=True, validation_status='ready', ) db.session.add(candidate) db.session.commit() @@ -1395,6 +1418,8 @@ def test_failed_reparse_restores_source_candidate_version(app): assert candidate.is_current_version is False assert candidate.selected is False assert candidate.selected_before_superseded is True + assert candidate.candidate_status == 'expired' + assert candidate.candidate_status_before_superseded == 'accepted' transition_order_extraction_run(replacement, target_status='running') transition_order_extraction_run(replacement, target_status='failed', error_message='provider unavailable') db.session.flush() @@ -1402,6 +1427,8 @@ def test_failed_reparse_restores_source_candidate_version(app): assert candidate.is_current_version is True assert candidate.selected is True assert candidate.selected_before_superseded is None + assert candidate.candidate_status == 'accepted' + assert candidate.candidate_status_before_superseded is None assert source.superseded_by_run_id is None diff --git a/backend/tests/test_shipping_order_field_extraction.py b/backend/tests/test_shipping_order_field_extraction.py new file mode 100644 index 00000000..0b65e731 --- /dev/null +++ b/backend/tests/test_shipping_order_field_extraction.py @@ -0,0 +1,437 @@ +""" +tests/test_shipping_order_field_extraction.py + +用途:验证订单级字段锚点/相对区域确定性读取的失败关闭边界。 +依赖:order_field_extraction、订单 Profile 与冻结 Schema 字段规则。 +逻辑:覆盖独立订单字段,不经过明细物理行或 Dify,防止两类区域重新耦合。 +""" + +from __future__ import annotations + +from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields +from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfileV2 +from app.services.shipping_notice.document_layout.runtime import _ocr_page_characters +from app.services.shipping_notice.document_profile_quality_service import _order_field_quality_failures +from app.core.errors import ValidationError +from app.services.shipping_notice.order_extraction_workflow import ( + _build_approved_profile_order, + _merge_confirmed_profile_order_fields, +) + + +def _glyphs(*lines: tuple[str, float, float]) -> list[dict]: + """将测试文字按字符展开为坐标 glyph,模拟 PDFium 不保留空白字符的输出。""" + result = [] + for text, x, y in lines: + offset = 0 + for character in text: + if character != ' ': + result.append({'text': character, 'bbox': {'x0': x + offset * 4, 'y0': y, 'x1': x + offset * 4 + 3, 'y1': y + 8}}) + offset += 1 + return result + + +def _profile(*, layout: dict, page_scope: str = 'first_page') -> OrderCoordinateProfileV2: + """构造包含一个独立 header 字段的最小合法 v2 Profile。""" + return OrderCoordinateProfileV2.model_validate({ + 'profile_code': 'ORDER-FIELD-TEST', 'version': 1, + 'document_match': {'required_anchors': []}, + 'table_regions': [{'region_id': 'lines', 'region': {'x0': .6, 'y0': .6, 'x1': .9, 'y1': .9}, 'line_layouts': [], 'header_layouts': [{'layout_id': 'headers', 'region': {'x0': .6, 'y0': .6, 'x1': .9, 'y1': .7}}]}], + 'order_field_layouts': [{ + 'layout_id': 'po_field', 'field_id': 'po-id', 'field_code': 'customer_po', + 'page_scope': page_scope, **layout, + }], + }) + + +def _schema(**overrides: object) -> dict[str, dict]: + """提供允许 PDF/OCR 坐标且默认 string 的冻结 Header Schema 字段。""" + return {'po-id': { + 'field_id': 'po-id', 'field_code': 'customer_po', 'scope': 'header', 'enabled': True, + 'value_type': 'string', 'normalizer_key': 'trim', 'validator_keys': ['non_empty'], + 'allowed_sources': ['pdf_coordinate', 'ocr_coordinate'], **overrides, + }} + + +def _evidence(*, pages: dict[str, list[dict]], source: str = 'pdf_coordinate') -> dict: + """构造冻结页级证据;故意不提供 tables,证明订单字段不依赖明细区。""" + return { + 'pages': {page: {'width': 200, 'height': 200} for page in pages}, + 'page_glyphs': pages, + 'sources': {'pages': {page: source for page in pages}}, + } + + +def test_anchor_relative_value_is_confirmed_with_native_page_coordinates(): + """唯一 PO 标签右侧的原生字符经规范化后可确认为独立订单字段。""" + profile = _profile(layout={ + 'anchor': {'anchor_id': 'po', 'text': 'PO NO'}, + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, 'value_mode': 'right_of_anchor', + }) + result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence( + pages={'1': _glyphs(('PO NO 45001', 20, 20))}, + ))[0] + + # 关键断言:独立字段不依赖 table glyph,唯一锚点的 PDF 坐标才可提升 confirmed。 + assert result.status == 'confirmed' + assert result.value == '45001' + assert result.source == 'pdf_coordinate' + + +def test_wide_address_value_region_is_valid_relative_to_short_anchor(): + """地址值框可比短标签宽得多,自动标记后保存不得被相对区域上限拒绝。""" + profile = _profile(layout={ + 'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'}, + 'value_region': {'x0': 1.1, 'y0': 0, 'x1': 10.5, 'y1': 1}, + 'value_mode': 'right_of_anchor', + }) + + # 关键断言:仍有有限上限,但自动建议的长地址几何属于合法模板定义。 + assert profile.order_field_layouts[0].value_region.x1 == 10.5 + + +def test_duplicate_anchor_requires_review_instead_of_selecting_one(): + """同页两个 PO 标签存在歧义,绝不按先后顺序静默选择。""" + profile = _profile(layout={ + 'anchor': {'anchor_id': 'po', 'text': 'PO NO'}, + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, + }) + result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence( + pages={'1': _glyphs(('PO NO 1', 20, 20), ('PO NO 2', 20, 50))}, + ))[0] + + # 关键断言:多锚点只能进入人工复核。 + assert result.status == 'needs_review' + assert result.issues == ['order_field_anchor_ambiguous'] + + +def test_anchor_reference_region_and_exact_mode_reject_unrelated_label_occurrences(): + """锚点参考区与精确匹配共同排除页眉重复标签和更长单词中的局部文本。""" + profile = _profile(layout={ + 'anchor': {'anchor_id': 'po', 'text': 'PO', 'match_mode': 'exact', 'region': {'x0': 0, 'y0': .1, 'x1': .8, 'y1': .3}}, + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, + }) + result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence( + pages={'1': _glyphs(('PONUMBER 999', 20, 8), ('PO 45001', 20, 30), ('PO 111', 20, 120))}, + ))[0] + + # 关键断言:只允许参考区内独立 PO,避免选择页眉或 PONUMBER 的局部命中。 + assert result.status == 'confirmed' + assert result.value == '45001' + + +def test_legacy_placeholder_anchor_uses_its_reference_region_as_review_only_evidence(): + """历史手工默认标签不能丢值,但只能按原标注框降级为人工复核。""" + profile = _profile(layout={ + 'anchor': { + 'anchor_id': 'ship_to', 'text': '订单字段标签 1', + 'region': {'x0': .08, 'y0': .1, 'x1': .35, 'y1': .2}, + }, + 'value_region': {'x0': 1.1, 'y0': 0, 'x1': 5, 'y1': 1}, + }) + result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence( + pages={'1': _glyphs(('SHIP TO PARTY ACME', 20, 30))}, + ))[0] + + # 关键断言:占位标签不会伪装成已确认,但原锚点框内的值仍可恢复展示。 + assert result.status == 'needs_review' + assert result.value == 'ACME' + assert result.issues == ['order_field_anchor_text_mismatch'] + + +def test_non_placeholder_anchor_text_with_reference_region_still_fails_closed(): + """管理员自定义标签写错时不可退化为坐标猜值,避免历史兼容绕过锚点门禁。""" + profile = _profile(layout={ + 'anchor': { + 'anchor_id': 'ship_to', 'text': 'WRONG LABEL', + 'region': {'x0': .08, 'y0': .1, 'x1': .35, 'y1': .2}, + }, + 'value_region': {'x0': 1.1, 'y0': 0, 'x1': 5, 'y1': 1}, + }) + result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence( + pages={'1': _glyphs(('SHIP TO PARTY ACME', 20, 30))}, + ))[0] + + # 关键断言:兼容范围仅限系统默认占位标签,普通错配仍不可用。 + assert result.status == 'unavailable' + assert result.issues == ['order_field_anchor_missing'] + + +def test_all_pages_conflicting_repeated_value_requires_review(): + """每页重复字段值不一致必须记录冲突,不能将首页值静默确认为正式结果。""" + profile = _profile(page_scope='all_pages', layout={ + 'anchor': {'anchor_id': 'po', 'text': 'PO NO'}, + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, + }) + result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence( + pages={'1': _glyphs(('PO NO 45001', 20, 20)), '2': _glyphs(('PO NO 45002', 20, 20))}, + ))[0] + + # 关键断言:多页冲突只能进入人工复核。 + assert result.status == 'needs_review' + assert 'order_field_page_value_conflict' in result.issues + + +def test_missing_page_evidence_and_anchor_fail_closed(): + """没有整页坐标或找不到标签时均不可用,禁止退回表格/绝对坐标猜值。""" + profile = _profile(layout={ + 'anchor': {'anchor_id': 'po', 'text': 'PO NO'}, + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, + }) + no_page = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence={'pages': {'1': {'width': 200, 'height': 200}}})[0] + no_anchor = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence( + pages={'1': _glyphs(('ORDER 1', 20, 20))}, + ))[0] + + # 关键断言:两种证据缺口都没有可用值。 + assert no_page.status == 'unavailable' + assert no_anchor.status == 'unavailable' + + +def test_fallback_and_ocr_never_become_confirmed(): + """无锚点固定区和 OCR 字符均只可生成待复核候选。""" + fallback = _profile(layout={ + 'fallback_value_region': {'x0': .1, 'y0': .1, 'x1': .5, 'y1': .2}, + }) + fallback_result = extract_order_fields(profile=fallback, schema_fields=_schema(), coordinate_evidence=_evidence( + pages={'1': _glyphs(('45001', 30, 20))}, + ))[0] + anchored = _profile(layout={ + 'anchor': {'anchor_id': 'po', 'text': 'PO NO', 'minimum_evidence_level': 'ocr_coordinate'}, + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, 'minimum_evidence_level': 'ocr_coordinate', + }) + ocr_result = extract_order_fields(profile=anchored, schema_fields=_schema(), coordinate_evidence=_evidence( + pages={'1': _glyphs(('PO NO 45001', 20, 20))}, source='ocr_coordinate', + ))[0] + + # 关键断言:低可靠度模式与 OCR 必须保留人工复核状态。 + assert fallback_result.status == 'needs_review' + assert ocr_result.status == 'needs_review' + + +def test_multiline_stops_at_next_label_and_type_failure_requires_review(): + """地址值在下一个标签前截断;日期格式无效不能绕过 Schema validator。""" + address = _profile(layout={ + 'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'}, + 'value_region': {'x0': 0, 'y0': 1.1, 'x1': 5, 'y1': 5}, 'value_mode': 'multi_line', + 'stop_anchors': [{'anchor_id': 'ship_to', 'text': 'SHIP TO'}], + }) + address_result = extract_order_fields(profile=address, schema_fields=_schema(), coordinate_evidence=_evidence( + pages={'1': _glyphs(('BILL TO', 20, 20), ('ABC COMPANY', 20, 34), ('ROAD 1', 20, 46), ('SHIP TO NEXT', 20, 60))}, + ))[0] + date = _profile(layout={ + 'anchor': {'anchor_id': 'date', 'text': 'DATE'}, + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, + }) + date_result = extract_order_fields(profile=date, schema_fields=_schema(value_type='date', validator_keys=['iso_date']), coordinate_evidence=_evidence( + pages={'1': _glyphs(('DATE invalid', 20, 20))}, + ))[0] + + # 关键断言:地址不包含下一个区块,错误类型值不作为正式结果。 + assert address_result.value == 'ABC COMPANY\nROAD 1' + assert date_result.status == 'needs_review' + assert date_result.issues == ['order_field_normalization_failed'] + + +def test_common_purchase_order_slash_date_is_normalized(): + """美式订单日期应进入受控日期类型,而不是被误判为格式异常。""" + profile = _profile(layout={ + 'anchor': {'anchor_id': 'date', 'text': 'DATE'}, + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, + }) + result = extract_order_fields(profile=profile, schema_fields=_schema( + field_code='order_date', value_type='date', validator_keys=['iso_date'], + ), coordinate_evidence=_evidence(pages={'1': _glyphs(('DATE 06/20/2026', 20, 20))}))[0] + + # 关键断言:运行期值保持 date 对象,后续 JSON 序列化统一输出 ISO 日期。 + assert result.status == 'confirmed' + assert result.value.isoformat() == '2026-06-20' + + +def test_date_recovers_one_glyph_just_outside_value_frame(): + """关键断言:日期值框少一个字符宽时仅补紧邻末尾数字,避免候选无故消失。""" + profile = _profile(layout={ + 'anchor': {'anchor_id': 'date', 'text': 'DATE'}, + # The right edge falls just before the final ``6`` of 06/20/2026. + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 3.73, 'y1': 1}, + }) + result = extract_order_fields(profile=profile, schema_fields=_schema( + field_code='order_date', value_type='date', validator_keys=['iso_date'], + ), coordinate_evidence=_evidence(pages={'1': _glyphs(('DATE 06/20/2026', 20, 20))}))[0] + + # 断言仅相邻一个字宽的末尾数字可恢复为完整的受控日期。 + assert result.status == 'confirmed' + assert result.value.isoformat() == '2026-06-20' + + +def test_right_of_anchor_recovers_a_customer_name_cut_off_by_value_frame(): + """客户值框截在单词中间时,应跳过冒号并补全同一连续公司名称。""" + profile = _profile(layout={ + 'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'}, + # Right edge cuts ``Corporation`` before its last three characters. + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 3.5, 'y1': 1}, 'value_mode': 'right_of_anchor', + }) + result = extract_order_fields(profile=profile, schema_fields=_schema( + field_code='bill_to_customer', + ), coordinate_evidence=_evidence(pages={'1': _glyphs(( + 'BILL TO: Inventec Corporation BILL ADDRESS: 66 Street', 20, 20, + ))}))[0] + + # 关键断言:不能回传 ``: Inventec Corporati``,也不能吞入右侧地址字段。 + assert result.status == 'confirmed' + assert result.value == 'Inventec Corporation' + + +def test_right_of_anchor_never_extends_from_customer_value_box_into_address(): + """同一行客户和地址相邻时,客户值框不得扩展跨过词间隔。""" + profile = _profile(layout={ + 'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'}, + # This box already contains the full company name but ends before the address. + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 4.25, 'y1': 1}, 'value_mode': 'right_of_anchor', + }) + result = extract_order_fields(profile=profile, schema_fields=_schema( + field_code='bill_to_customer', + ), coordinate_evidence=_evidence(pages={'1': _glyphs(( + 'BILL TO: Inventec Corporation 66 Hou-Kang Street', 20, 20, + ))}))[0] + + # 关键断言:框尾后的地址首字符必须因词间隔被拒绝,不能混入客户名称。 + assert result.status == 'confirmed' + assert result.value == 'Inventec Corporation' + + +def test_multiline_stop_anchor_ignores_same_label_above_current_anchor(): + """页眉或其他区块中位于当前锚点上方的停止标签,不能截断账款地址。""" + address = _profile(layout={ + 'anchor': {'anchor_id': 'bill_to', 'text': 'BILL TO'}, + 'value_region': {'x0': 0, 'y0': 1.1, 'x1': 5, 'y1': 5}, 'value_mode': 'multi_line', + 'stop_anchors': [{'anchor_id': 'ship_to', 'text': 'SHIP TO'}], + }) + result = extract_order_fields(profile=address, schema_fields=_schema(), coordinate_evidence=_evidence( + pages={'1': _glyphs( + ('SHIP TO HEADER', 20, 8), ('BILL TO', 20, 30), ('ABC COMPANY', 20, 44), + ('ROAD 1', 20, 56), ('SHIP TO NEXT', 20, 72), + )}, + ))[0] + + # 关键断言:只以当前 BILL TO 后的 SHIP TO 作为停止条件。 + assert result.status == 'confirmed' + assert result.value == 'ABC COMPANY\nROAD 1' + + +def test_page_ocr_character_builder_preserves_page_coordinates_without_native_fallback(): + """扫描页 OCR 仅在原生字符缺失时可生成页级证据,空白字符不应成为可选锚点。""" + class _Box: + x0, y0, x1, y1 = 10, 20, 30, 28 + + class _Line: + text, bbox = 'PO 1', _Box() + + glyphs = _ocr_page_characters([_Line()]) + + # 关键断言:OCR 字符保留原页 y 坐标且剔除空白,供后续明确标为 ocr_coordinate。 + assert [item['text'] for item in glyphs] == ['P', 'O', '1'] + assert glyphs[0]['bbox']['y0'] == 20 + + +def test_quality_gate_rejects_unavailable_or_low_reliability_order_field_candidates(): + """盲测必须将订单字段的锚点缺失和固定坐标回退标为失败,而不是只核对明细行。""" + anchored = _profile(layout={ + 'anchor': {'anchor_id': 'po', 'text': 'PO NO'}, + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, + }) + missing = _order_field_quality_failures( + parser=anchored, schema_fields=_schema(), sample_id=7, + layout={'coordinate_evidence': _evidence(pages={'1': _glyphs(('ORDER 1', 20, 20))})}, expected_values={'customer_po': '45001'}, + ) + fallback = _profile(layout={'fallback_value_region': {'x0': .1, 'y0': .1, 'x1': .5, 'y1': .2}}) + low_reliability = _order_field_quality_failures( + parser=fallback, schema_fields=_schema(), sample_id=8, + layout={'coordinate_evidence': _evidence(pages={'1': _glyphs(('45001', 30, 20))})}, expected_values={'customer_po': '45001'}, + ) + + # 关键断言:没有 confirmed 证据的订单字段阻断盲测凭证。 + assert missing == ['sample:7:order_field:customer_po:unavailable'] + assert low_reliability == ['sample:8:order_field:customer_po:needs_review'] + + +def test_quality_gate_compares_confirmed_order_field_value_with_human_truth(): + """状态为 confirmed 仍必须逐字段等于人工真值,防止读到错误但格式合法的 PO。""" + profile = _profile(layout={ + 'anchor': {'anchor_id': 'po', 'text': 'PO NO'}, + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, + }) + failures = _order_field_quality_failures( + parser=profile, schema_fields=_schema(), sample_id=9, + layout={'coordinate_evidence': _evidence(pages={'1': _glyphs(('PO NO 45001', 20, 20))})}, + expected_values={'customer_po': '45002'}, + ) + + # 关键断言:格式合法但与人工真值不同的字段必须阻断盲测。 + assert failures == ['sample:9:order_field:customer_po:mismatch'] + + +def test_quality_gate_normalizes_order_field_truth_before_comparison(): + """JSON 盲测真值的日期字符串须按冻结 Schema 规范化后再与提取值比较。""" + profile = _profile(layout={ + 'anchor': {'anchor_id': 'date', 'text': 'DATE'}, + 'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, + }) + schema = _schema(field_code='order_date', value_type='date', validator_keys=['iso_date']) + profile.order_field_layouts[0].field_code = 'order_date' + failures = _order_field_quality_failures( + parser=profile, schema_fields=schema, sample_id=10, + layout={'coordinate_evidence': _evidence(pages={'1': _glyphs(('DATE 2026-08-01', 20, 20))})}, + expected_values={'order_date': '2026-08-01'}, + ) + + # 关键断言:同一日期的 JSON 字符串与运行时 date 对象不应产生伪 mismatch。 + assert failures == [] + + +def test_deterministic_order_merges_confirmed_order_field_and_required_header_gate(): + """确定性建单将独立 confirmed 字段合并为 Header,并用它满足必填订单字段。""" + order = _build_approved_profile_order( + unit=type('Unit', (), {'document_id': 42})(), intake={'intake_no': 'SNI-1'}, + schema={'schema_version_id': 1, 'checksum': 'a' * 64}, + definition={'fields': [ + {'field_id': 'po-id', 'field_code': 'customer_po', 'scope': 'header', 'enabled': True, 'required': True, 'collection_mode': 'llm_extraction'}, + {'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'enabled': True, 'required': True, 'collection_mode': 'llm_extraction'}, + ]}, + table={'rows': [{'status': 'parsed', 'issues': [], 'fields': [{'field_id': 'qty-id', 'value': 3, 'quote': '3'}]}]}, + confirmed_order_fields=[{ + 'field_id': 'po-id', 'value': '45001', 'page_no': 1, 'source': 'pdf_coordinate', + 'anchor_bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}, + 'value_bbox': {'x0': 25, 'y0': 10, 'x1': 50, 'y1': 20}, 'glyph_indices': [4, 5, 6], + }], + ) + + # 关键断言:订单字段与明细字段严格分域后仍可在最终订单 Header 合并。 + assert order is not None + assert {field['field_id'] for field in order['header_fields']} == {'po-id'} + assert order['header_fields'][0]['observations'][0]['layout_evidence']['page_no'] == 1 + + +def test_provider_omission_is_merged_but_override_of_confirmed_order_field_is_rejected(monkeypatch): + """Dify 不接收 confirmed 字段可省略;若自行返回冲突值,HXOPS 必须拒绝。""" + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workflow._confirmed_profile_order_fields', + lambda _run, unit: [{'field_id': 'po-id', 'value': '45001'}], + ) + unit = type('Unit', (), {'document_id': 42})() + omitted = [{'header_fields': []}] + merged = _merge_confirmed_profile_order_fields(object(), unit=unit, orders=omitted) + field = merged[0]['header_fields'][0] + assert field['field_id'] == 'po-id' + assert field['observations'][0]['value'] == '45001' + assert field['_hxops_order_field_evidence'] is True + assert merged[0]['_hxops_order_field_evidence'] is True + invalid = [{'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'DIFF'}]}]}] + + # 关键断言:模型不可覆盖模板已确认的订单字段。 + try: + _merge_confirmed_profile_order_fields(object(), unit=unit, orders=invalid) + except ValidationError as error: + assert error.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE' + else: + raise AssertionError('confirmed order field override must be rejected') diff --git a/backend/tests/test_shipping_order_profile_matcher.py b/backend/tests/test_shipping_order_profile_matcher.py index 73796bdc..962bcffe 100644 --- a/backend/tests/test_shipping_order_profile_matcher.py +++ b/backend/tests/test_shipping_order_profile_matcher.py @@ -52,3 +52,22 @@ def test_profile_matcher_requires_optional_score_threshold(): """可选锚点未命中导致得分低于模板阈值时不得自动匹配。""" result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['SUPPLIER A'], score=.95)], layout=_layout()) assert result.status == 'no_match' + + +def test_profile_matcher_uses_page_glyphs_for_anchor_outside_table(): + """模板静态锚点可位于表格外,必须从页级冻结证据匹配而非只读表内字符。""" + layout = _layout('LINE ITEMS') + layout['coordinate_evidence']['page_glyphs'] = {'1': [ + {'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}} + for index, char in enumerate('PURCHASE ORDER') + ]} + + result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=layout) + + # 关键断言:订单字段模板不再要求业务锚点错误地落在明细表格中。 + assert result.status == 'unique_match' + + +def test_profile_matcher_uses_table_glyphs_only_for_legacy_evidence(): + """缺少新 page_glyphs 的历史冻结快照继续保持兼容,不降低已有模板可回放性。""" + assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout()).status == 'unique_match' diff --git a/backend/tests/test_shipping_order_schema_runtime.py b/backend/tests/test_shipping_order_schema_runtime.py index f2aaba94..b2d09011 100644 --- a/backend/tests/test_shipping_order_schema_runtime.py +++ b/backend/tests/test_shipping_order_schema_runtime.py @@ -340,6 +340,42 @@ def _seed_documents() -> tuple[int, list[ShippingNoticeDocument], int]: return int(intake.id), [body, pdf], int(user.id) +def test_confirmed_order_field_coordinate_evidence_is_persisted_and_backend_marked_only(app): + """确认订单字段必须保留坐标元数据;未经过 Workflow 注入的标记不得提升 Provider 证据。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + po = service.save_field({'field_code': 'customer_po', 'scope': 'header', 'value_type': 'string'}, actor_id=None) + draft = service.create_draft({}, actor_id=None) + published = _save_and_publish(draft, [_config(po['id'], '客户 PO', value_type='string')]) + intake_id, documents, actor_id = _seed_documents() + coordinate = { + 'page_no': 1, 'source': 'pdf_coordinate', + 'anchor_bbox': {'x0': 10, 'y0': 10, 'x1': 30, 'y1': 20}, + 'value_bbox': {'x0': 35, 'y0': 10, 'x1': 70, 'y1': 20}, + 'glyph_indices': [4, 5, 6, 7, 8], + } + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [{'field_id': po['id'], '_hxops_order_field_evidence': True, 'observations': [{ + 'value': 'PO-100', 'document_id': documents[1].id, 'quote': 'PO-100', + 'layout_evidence': coordinate, + }]}], + 'lines': [], + }, + intake_id=intake_id, snapshot_hash='o' * 64, documents=documents, actor_id=actor_id, + ) + + observation = ShippingOrderFieldObservation.query.filter_by( + extraction_id=result['extraction'].id, field_id=po['id'], + ).one() + # 关键断言:最终记录可追溯到页号、锚点/值框与字符索引,而非 Provider 自报置信度。 + assert observation.evidence_verified is True + assert observation.extractor == 'order_profile_order_field' + assert observation.evidence_metadata_json == {'kind': 'order_field_coordinate', **coordinate} + assert observation.evidence_ref == f'document:{documents[1].id}:order-field:{po["id"]}:page:1' + + def test_dynamic_schema_contract_and_cross_document_persistence(app): """同一字段在 EML 与 PDF 一致时应 corroborated,并生成类型化值与 field_code 投影。""" with app.app_context(): diff --git a/backend/tests/test_shipping_rolling_fulfillment.py b/backend/tests/test_shipping_rolling_fulfillment.py index d3a188c6..36a59357 100644 --- a/backend/tests/test_shipping_rolling_fulfillment.py +++ b/backend/tests/test_shipping_rolling_fulfillment.py @@ -48,6 +48,37 @@ def test_rolling_verification_keeps_shortage_pending_and_later_releases_it(app): assert second.result_json['available_count'] == 1 +def test_inventory_verification_uses_frozen_quantity_and_rejects_duplicate_result(app): + """关键断言:库存侧不得缩小需求数量或用重复结果覆盖同一冻结预约单。""" + with app.app_context(): + task, user = _build_accepted_order(suffix='quantity-authority') + snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7) + db.session.commit() + line = snapshot.lines[0] + frozen_quantity = str(line.qty) + result = { + 'reservation_id': line.reservation_id, + 'part_number': line.part_number, + 'required_qty': '1', + 'available_qty': '1', + 'line_status': 'ok', + } + + with pytest.raises(ValidationError) as quantity_error: + record_inventory_verification( + task, inventory_snapshot_id=None, source_config_version='v1', line_results=[result], + ) + assert quantity_error.value.code == 'SHIPPING.RESERVATION_MISMATCH' + db.session.rollback() + + result['required_qty'] = frozen_quantity + with pytest.raises(ValidationError) as duplicate_error: + record_inventory_verification( + task, inventory_snapshot_id=None, source_config_version='v1', line_results=[result, result.copy()], + ) + assert duplicate_error.value.code == 'SHIPPING.RESERVATION_MISMATCH' + + def test_rolling_reservation_only_selects_unoccupied_lines_in_later_round(app): """A/B 首轮占用后,C 补货只能进入第二轮;首轮 Artifact 不得被覆盖或重复占用。""" with app.app_context(): diff --git a/backend/tests/test_shipping_upload_attempt.py b/backend/tests/test_shipping_upload_attempt.py index 2683d0bf..fa68b386 100644 --- a/backend/tests/test_shipping_upload_attempt.py +++ b/backend/tests/test_shipping_upload_attempt.py @@ -18,7 +18,8 @@ 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, start_rpa_attempt, void_rejected_artifact +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.state_machine import resolve_task_ui_state def _ready_artifact() -> tuple[ShippingTask, ShippingExportArtifact, ShippingReservation]: @@ -91,6 +92,57 @@ def test_trigger_delivery_failure_releases_artifact_for_a_later_retry(app): assert start_rpa_attempt(task, artifact_id=artifact.id).attempt_no == 2 +def test_timed_out_upload_is_frozen_until_reconciled(app): + """关键断言:回调超时不是失败,禁止重传;迟到成功或货代明确拒绝才可收口。""" + with app.app_context(): + task, artifact, reservation = _ready_artifact() + attempt = start_rpa_attempt(task, artifact_id=artifact.id) + mark_attempt_result_unknown(attempt) + + with pytest.raises(ConflictError) as retry_error: + start_rpa_attempt(task, artifact_id=artifact.id, idempotency_key=attempt.idempotency_key) + assert retry_error.value.code == 'SHIPPING.UPLOAD_RESULT_UNKNOWN' + assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploading' + assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved' + + complete_attempt(attempt, success=True, callback_id='late-success', freight_ref_no='F-LATE') + assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded' + assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded' + + +def test_unknown_upload_result_hides_retry_and_requires_reconciliation(app): + """关键断言:未知结果只允许核对或凭回执收口,UI 不得暴露重试上传动作。""" + with app.app_context(): + task, artifact, reservation = _ready_artifact() + attempt = start_rpa_attempt(task, artifact_id=artifact.id) + mark_attempt_result_unknown(attempt) + task.pending_human_reason = 'upload_result_unknown' + task.upload_status = 'unknown' + + state = resolve_task_ui_state(task) + assert state.checkpoint == 'upload_result_unknown' + assert state.human_options == ['refresh', 'download_excel', 'mark_manual_uploaded'] + assert 'retry_upload' not in state.human_options + assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved' + + +def test_timed_out_upload_requires_explicit_rejection_before_release(app): + """关键断言:未知结果中的普通失败不释放预约单,明确拒绝并授权作废才允许恢复。""" + with app.app_context(): + task, artifact, reservation = _ready_artifact() + attempt = start_rpa_attempt(task, artifact_id=artifact.id) + mark_attempt_result_unknown(attempt) + + complete_attempt(attempt, success=False, callback_id='late-network-error', error_message='network timeout') + assert attempt.status == 'timed_out' + assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploading' + assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved' + + complete_attempt(attempt, success=False, callback_id='late-freight-rejection', error_message='freight_rejected: invalid document') + void_rejected_artifact(task, artifact_id=artifact.id, operator_id=1, reason='货代明确拒绝') + assert db.session.get(ShippingReservation, reservation.id).status == 'pending' + + def test_only_explicit_rejection_can_void_and_release_artifact(app): """网络失败不能释放预约单;货代明确拒绝且有授权后才可重新进入库存核验。""" with app.app_context(): diff --git a/docs/demand.md b/docs/demand.md index 1063507d..60a7d4da 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -4,6 +4,8 @@ - 管理员在受控低清 PDF 画布上配置表头、明细物理行和字段区域,不输入坐标数字;翻页按页加载,离开未保存草稿必须确认。 - 表头行与明细行分别配置。表头识别只能给出当前冻结 Schema 的唯一精确别名建议,不能覆盖人工字段绑定;字段缺失、重复或不确定时保持未映射。 +- 订单级字段作为独立标注域:管理员可用标签锚点、相对值区、多行停止标签和受控规范化配置 Header 字段;不得把账款/送货客户、地址、PO 等标为明细表头或物理行字段。发布前盲测须验证每个订单字段的人工真值与页级字符坐标证据,`confirmed` 字段不可被 Dify 覆盖。 +- 字段规则版本必须保留:文档模板绑定稳定 `field_id` 与创建时 Schema 快照。新增或调整 Schema 版本不得清空既有模板绑定;仅发生字段语义、作用域、类型或证据能力等破坏性变化时,才要求受影响字段显式迁移和重新盲测。 ## 设备维保助手补充需求 @@ -590,6 +592,6 @@ - L6 要求所有 accepted Observation 具有稳定证据引用;无 cell 的纯文本表格只能形成复核原因,不能作为已验证后端表格证据。跨文档关联必须使用同 Document 强身份,禁止以 Qty 等常见值串接订单行。 - 自动建单配置位于“货代配置 → 订单字段模板”:管理员只维护一个自动建单总开关;每个字段独立标记为建单关键字段并设置自身最低置信度。每个 Run 冻结开关与字段快照;阈值不能绕过必填、证据、冲突、重复和 Reservation 等硬门禁。 - 终态且未消费的订单抽取 Run 支持“按当前规则重新识别”:创建新的可审计 Run,重新冻结当前 Schema、执行绑定、文档 Profile 与 ready 布局;旧候选在新版执行期间不可建单,新版失败后恢复旧版。失败 Run 的基础设施重试仍复用原冻结 Run,不得与重新识别混用。 -- **模板自动建单资格**:Profile 发布仅表示可作为受控解析候选,不等于可跳过 Dify。发布前必须有至少 1 份训练样本,且建立与训练/标注样本完全独立的盲测集;常规模板至少 3 份独立样本(无表头模板至少 5 份),其中至少 1 份为多明细真值;声明跨页时还必须覆盖带 `continuation_of` 的续页样本。所有样本按管理员确认真值通过并由管理员批准后才允许发布;资格与正式 Profile checksum 绑定,checksum 变化立即失效。唯一命中的已批准 Profile 才可确定性建单,未知、多模板、行解析异常或未批准时一律回退 Dify/人工复核。 +- **模板自动建单资格**:Profile 发布仅表示可作为受控解析候选,不等于可跳过 Dify。发布前必须有至少 1 份训练样本,且建立与训练/标注样本完全独立的盲测集;所有模板最低仅需 1 份独立样本,其中至少 1 份为多明细真值;声明跨页时还必须覆盖带 `continuation_of` 的续页样本。样本按管理员确认真值通过并由管理员批准后才允许发布;资格与正式 Profile checksum 绑定,checksum 变化立即失效。唯一命中的已批准 Profile 才可确定性建单,未知、多模板、行解析异常或未批准时一律回退 Dify/人工复核。 - **Dify 证据边界**:Dify 输出只能使用冻结 `extraction_contract` 中的 field_id,所有 Observation 必须引用当前 Unit 文档且 quote 可在冻结输入中逐字验证;不得回传确定性上下文字段或覆盖已锁定值。Dify 画布由管理员在最终验收时手工配置,HXOPS 不修改画布。 - **客户绑定与冻结**:订单原文、按 `order-customer-fingerprint.v1` 标准化生成的身份指纹、正式 `customer_id` 三层分离保存。Bill-to 是订购客户;只有已人工确认并写明理由的 Bill-to 匹配可以冻结为 Snapshot。调用方不能在冻结请求中自由传入客户或简码;Snapshot 固化客户简码和匹配规则版本,客户后续改名、合并或规则变化不回写历史。 diff --git a/docs/features/shipping-notice/order-extraction-workflow-dify-guide.md b/docs/features/shipping-notice/order-extraction-workflow-dify-guide.md index 5e4905ca..ff1615cd 100644 --- a/docs/features/shipping-notice/order-extraction-workflow-dify-guide.md +++ b/docs/features/shipping-notice/order-extraction-workflow-dify-guide.md @@ -10,10 +10,13 @@ 2. `parse_and_prepare_input` 直接读取 `manifest.document` 和可选的 `manifest.structured_table_candidates`;不得读取其他文档集合、确定性表格内部载荷或任何输入格式分支。 3. Code 节点不得期待或生成 HTML、bbox、token、cell_id、evidence_ref、field_code。结构化候选字段仅为 `column_index/field_id/value/quote`;表/行同时带 `status/issues`,候选顶层带 `field_policy`。 4. LLM 对 `field_policy=locked` 的字段必须原样保留稳定 `field_id/value/quote`,只能补充缺失字段;对 `suggested` 候选可结合当前文档短文本判断,但不得把自然语言表头改写为其他 field_id。 -5. `unit.intake_no` 必须写入每个订单 `source_intake_no`;`unit.document_id` 必须写入 `primary_document_id` 及每条 Observation 的 `document_id`。End 仍只输出 String 类型 `orders`,内容必须是 JSON 数组,不得附加 think/XML/Markdown 标签。 -6. 用 Dify 画布测试至少覆盖:无表格、needs_review 候选、locked 候选、零订单、多订单、缺 Reservation。确认输出合法后发布 Workflow;已创建 Run 不会随配置变更改变其冻结输入。 +5. HXOPS 的订单级字段模板在后端以页级字符坐标提取。模板已产生 `confirmed` 的 Header 字段不会注入 Dify,Dify 省略这些字段是合法的;Dify 只补充未配置、`needs_review` 或 `unavailable` 的 Header 字段。若 Workflow 仍输出同一已确认 `field_id`,其值必须与后端结果一致;发生冲突时 HXOPS 会拒绝该 Unit 输出,并以自己的页级坐标 Observation 替换一致的 Provider Observation。 +6. `unit.intake_no` 必须写入每个订单 `source_intake_no`;`unit.document_id` 必须写入 `primary_document_id` 及每条 Observation 的 `document_id`。End 输出 String 类型 `orders`;内容可为 JSON 数组、`{"orders":[...]}` 或 `{"data":{"orders":[...]}}`,不得附加 think/XML/Markdown 标签。 +7. 关闭 `retriever_resource`;该 Workflow 不得有知识库检索、工具调用、外部 HTTP、数据库读取或其他可取得 Unit 外信息的节点。 +8. LLM 节点必须显式设置 Temperature `0`、Top P `0.1`;关闭 Streaming、Memory 和 Conversation History;模型支持时启用 JSON Object 响应格式。不得依赖 Provider 默认参数。 +9. 用 Dify 画布测试至少覆盖:无表格、needs_review 候选、locked 候选、零订单、多订单、缺 Reservation,以及已确认订单字段原样保留与未确认订单字段补充。确认输出合法后发布 Workflow;已创建 Run 不会随配置变更改变其冻结输入。 -人工真值暂缓时,Dify 只能把 needs_review 候选作为补充上下文。不得在 Code 节点自行把候选提升为 accepted,不得据此开启自动建单,也不得宣称达到 95% 准确率。 +人工真值暂缓时,Dify 只能把 needs_review 候选作为补充上下文。Dify 结果无论置信度多高一律为 provisional,必须由用户在 HXOPS 人工采纳后才能进入履约;不得在 Code 节点输出 `_hxops_*` 内部字段、自行把候选提升为 accepted、开启自动建单或宣称达到 95% 准确率。唯一已发布且盲测批准的确定性模板由 HXOPS 后端标记为自动采纳,Dify 不能模拟该标记。 ### 单文档证据与跨文档订单的边界(必须遵守) @@ -25,6 +28,7 @@ - 单文档完全没有可证明字段时,LLM 返回 `{"orders":[]}`,属于成功空结果,不是校验失败。 - 只有 JSON 无法解析、订单/字段结构损坏、Schema/Intake/Document 不一致、Observation 指向其他 Document 等协议或来源越界,才进入失败分支。 - Dify 不可把没有锚点的 EML 证据猜测性并入某份 PDF;是否能合并、是否能创建订单只能由 HXOPS 后端决定。 +- 当前 Document 之外的任何邮件正文、附件或既有 Run 数据均不可读取、引用或作为“优先证据”。例如 AWS 料号只有在当前 `document_json` 中存在明确标签和逐字证据时才能返回;不得因其他 Unit 的 AWS 料号覆盖或补全当前 Unit 的 `Material` 等字段。 Reservation 的最终裁决也在 HXOPS:PDF 缺少 `reservation_id` 时,Dify 必须照常返回其可证明的 PO、料号、数量、项次等字段;EML 若有明确 Reservation 也只返回该 Document 自己的 Observation。后端仅在同 Intake、同 PO 下,且邮件/PDF 行可通过**唯一且一致**的 `part_number` 或 `line_no` 关联时,才把合法 Reservation 合并到最终行。重复料号、项次冲突、多个候选、Reservation 冲突或无强锚点时都不得自动补入,必须保留证据并进入 `needs_review`。 @@ -47,6 +51,9 @@ HXOPS 的“按当前规则重新识别”不会调用新的 Dify 节点,也 - [ ] 人工单元格真值和真实质量/性能指标全部达到 `technical.md` 阈值。 - [ ] Dify 已发布本手册定义的唯一画布,Start 仍只有 String `execution_manifest`。 +- [ ] 已关闭 Retriever Resource,且画布没有知识库检索、工具、HTTP 或跨文档读取节点。 +- [ ] LLM 参数已显式设置为 Temperature `0`、Top P `0.1`,并关闭 Streaming、Memory、Conversation History;支持时启用 JSON Object 输出。 +- [ ] 提示词只允许使用当前 `document_json`;未以其他邮件正文或附件的 AWS 料号、PO、Reservation 等信息补全当前 Unit。 - [ ] 保持 `auto_create_enabled=false` 完成至少 20 个测试环境真实 Run。 - [ ] 管理员诊断中证据追溯率、issue code 和失败单元均可解释;无错误合并、错误拆分或错误 Task。 - [ ] 业务负责人和技术负责人书面批准后才开启自动建单。 @@ -77,7 +84,7 @@ Start false -> Code: raise_validation_error -> Workflow Failed ``` -End 只能输出 `orders`。失败分支必须抛出异常,不能将校验错误伪装为成功的空订单。 +End 只能输出 `orders`。HXOPS 兼容 End 将其包装为 `data.orders`,但不接受任意深层 JSON 搜索。失败分支必须抛出异常,不能将校验错误伪装为成功的空订单。 ## 3. Start 节点 @@ -278,7 +285,7 @@ def main(execution_manifest: str): ## 5. LLM 节点:extract_orders -建议参数:Temperature `0`,Top P `0.1`,Streaming/Memory/Conversation History 全部关闭;支持时启用 JSON Object 响应格式。Reasoning 不得接入正文或输出。 +必须显式设置:Temperature `0`,Top P `0.1`,Streaming/Memory/Conversation History 全部关闭;支持时启用 JSON Object 响应格式。Reasoning 不得接入正文或输出。禁止保留空参数而依赖 Provider 默认值。 输入变量:`run_no`、`unit_id`、`source_intake_no`、`primary_document_id`、`schema_contract_json`、`document_json`、`table_candidates_json`、`readonly_context_json`、`header_field_ids_json`、`line_field_ids_json`,均来自 `parse_and_prepare_input`。 @@ -303,7 +310,7 @@ classification 必须根据当前 document_json.extracted_text 独立判断。do 必须严格匹配 schema 中每个 field_id 的 value_type:decimal/integer 必须返回 JSON 数字;boolean 必须返回 JSON 布尔值;date 的 value 必须为 `YYYY-MM-DD`。例如原文 `06/22/2026` 的 date value 必须输出 `2026-06-22`,但 quote 仍保留原文 `06/22/2026`。不符合类型或无法规范化时省略字段,不得原样输出非 ISO 日期。 -高风险行字段不得按位置或猜测映射:`line_no` 只能是订单行号(如 `00010`);`part_number` 是 HXOPS 内部料号,通常来自明确的 MPN、Supplier Part Number、Vendor Part Number 等供应商/制造商语义;`customer_part_number` 通常来自客户订单中的 `Material`、`Material No`、`Material Number`;`reservation_id` 只能是原文明确标注的 Reservation ID;`inventory_source_hint` 只能是明确库存源/仓库提示,绝不能填行号;`aws_part_number` 只能来自明确标注的 AWS SKU、AWS Part Number、APN 或同等 AWS 语义。若邮件正文或任一附件已有明确 AWS 料号,必须优先使用该证据,不能用 Material 覆盖。不得以料号、行号、描述、金额或数量互相替代。已发布的精确模板 Profile 可以覆盖裸表头的通常语义;例如确认模板中的 `Part Number -> customer_part_number`、`Vendor Item# -> part_number` 是合法契约,Dify 不得重新改写。 +高风险行字段不得按位置或猜测映射:`line_no` 只能是订单行号(如 `00010`);`part_number` 是 HXOPS 内部料号,通常来自明确的 MPN、Supplier Part Number、Vendor Part Number 等供应商/制造商语义;`customer_part_number` 通常来自客户订单中的 `Material`、`Material No`、`Material Number`;`reservation_id` 只能是原文明确标注的 Reservation ID;`inventory_source_hint` 只能是明确库存源/仓库提示,绝不能填行号;`aws_part_number` 只能来自**当前 `document_json`** 中明确标注的 AWS SKU、AWS Part Number、APN 或同等 AWS 语义。不得读取或用邮件正文、其他附件或其他 Unit 的 AWS 料号覆盖当前 Document 的 Material。不得以料号、行号、描述、金额或数量互相替代。已发布的精确模板 Profile 可以覆盖裸表头的通常语义;例如确认模板中的 `Part Number -> customer_part_number`、`Vendor Item# -> part_number` 是合法契约,Dify 不得重新改写。 `Item deleted`、`Cancelled` 等删除标记可能独占一行并作用于前一条视觉明细,而非标记后的下一条明细。只有 `table_candidates_json` 已按版面行关系明确将候选行标记为 `role=deleted` 时,才忽略该行;纯文本或拆行文本中不得自行推断删除标记归属,也不得自动删除任何订单行,应保留候选并进入后续复核。若 Reservation ID 没有 `Reservation ID`、`COM ID`、`Reservation Order`、`Reservation No`、`Resv ID`、`PR Number` 或 `External reservation ID` 等明确标签和对应的 5 位或 10 位纯数字,必须省略 `reservation_id`;`EXW AWS HUB`、仓库/站点、贸易术语、项次和料号绝不能填入该字段。 diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 6ebc8621..1d94cf36 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -89,7 +89,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open **阶段 6 Dify 手工配置**:无需修改画布。预算、Provider 并发和熔断全部由 HXOPS 管理;Dify 继续保持单文档无状态执行。管理员只在 HXOPS Runtime Binding 配置治理参数,不要在 Dify 内复制限流、循环重试或熔断逻辑。 -**阶段 7 当前结论(2026-07-21)**:自动建单由 Run 冻结的 `auto_create_enabled` 硬门禁控制,默认 `false`。关闭时仍完整持久化 Extraction、Decision、FieldValue、Candidate、重复检测和客户影子识别;满足全部业务门禁的 Candidate 保持 `validation_status=ready`、`selected=false`,增加 `auto_create_disabled` 待审原因,不创建或打开 Task。开启后也不能绕过分类置信度、必填/流程字段、逐字证据、动态 Schema、Reservation 安全、冲突和重复决策门禁。生产代码和测试只维护唯一 Manifest 契约。 +**阶段 7 当前结论(2026-07-21)**:自动建单由 Run 冻结的 `auto_create_enabled` 硬门禁控制,默认 `false`;它必须同时满足 Schema 总开关、`shipping.order_extraction` Runtime Binding 显式开启及已批准质量批次,任一层关闭即冻结为影子模式。关闭时仍完整持久化 Extraction、Decision、FieldValue、Candidate、重复检测和客户影子识别;满足全部业务门禁的 Candidate 保持 `validation_status=ready`、`selected=false`,增加 `auto_create_disabled` 待审原因,不创建或打开 Task。开启后也不能绕过分类置信度、必填/流程字段、逐字证据、动态 Schema、Reservation 安全、冲突和重复决策门禁。生产代码和测试只维护唯一 Manifest 契约。 ### L5 紧凑模型契约(2026-07-22) @@ -118,7 +118,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open ### L7 影子与正式切换准备(2026-07-22) -- 纯文本表格即使字段齐全也必须进入模型补充和后端 needs_review 门禁。Profile 发布本身只提供紧凑候选;只有唯一命中的 Profile 已完成独立盲测资格(至少 3 样本全通过、管理员批准且 checksum 未漂移)时,才可由该 Profile 的实际解析行零 Provider 建单。 +- 纯文本表格即使字段齐全也必须进入模型补充和后端 needs_review 门禁。Profile 发布本身只提供紧凑候选;只有唯一命中的 Profile 已完成独立盲测资格(至少 1 份样本通过、管理员批准且 checksum 未漂移)时,才可由该 Profile 的实际解析行零 Provider 建单。 - Profile 仍可生成不含 HTML/bbox/token 的紧凑候选供模型参考,并继续执行零 Qty 删除等候选清洗,但未获得 accepted cell 前不能直接生成订单。 - 自动建单只能在质量门禁满足时由 Schema 策略开启;它不依赖 Dify 输入格式开关。 - L7 最终工程 Review 覆盖 L0-L7 布局、Intake、Schema、订单抽取、Runtime Binding、质量门禁与迁移共 `247 passed`;前端生产构建通过。该记录的历史基线 head 为 `a72f8091a2b8`;当前货代履约链部署必须以 `023a4b5c6d7e` 为唯一 Alembic head,`git diff --check` 通过。静态检查确认 `build_deterministic_unit_orders` 不再调用纯文本表格解析器。 @@ -145,6 +145,8 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open 3. 每日试点记录管理员 `GET /api/admin/shipping-notice/order-extraction-runs/health` 的队列、Provider、HXOPS 落库与总时延 P50/P95、失败率、重试与积压;库存 RPA 从配置测试运行记录读取耗时,上传 RPA 从 `ShippingUploadAttempt.started_at/finished_at` 统计。试点累计数据形成正式容量 SLA 前,不提高并发或放开自动建单。 4. 恢复演练在测试环境完成:人为中断 Worker 后重启,确认 stale Job 被恢复、已有 Provider 结果只续做 HXOPS 落库、相同文件重试不重复建单;再从经批准的数据库备份与 RPA 共享目录备份恢复到隔离环境,核对 Artifact、Attempt、Reservation 和审计记录。演练记录必须包含环境、备份时间、操作者、耗时、校验结果及遗留问题;失败时保持自动建单和自动上传关闭。 +**货代上传结果未知(工程 Review)**:RPA trigger 已成功投递而回调超时时,不得把它等同于“上传失败”或自动重传。HXOPS 将对应 `ShippingUploadAttempt` 标记为 `timed_out`、保留 Artifact 为 `uploading`、保留 Reservation 为 `artifact_reserved`,并将任务置于 `upload_result_unknown` 检查点;该检查点不提供 `retry_upload`。货代迟到成功回调可正常收口;普通网络错误仍保持未知。只有货代明确拒绝(`freight_rejected:`)并由授权操作者执行 Artifact 作废,才可释放预约单进入下一轮核验。该机制不要求修改 Dify 画布。 + **阶段 7 Dify 手工配置补充**:上述容量、健康、恢复和备份均由 HXOPS/运维执行,Dify 不增加限流、重试、循环、恢复或自动建单节点。完成真实影子与试点验收后,仍需按本节既有唯一 Manifest 检查清单手工检查画布并留存截图/运行记录。 ### 阶段 3 客户指纹绑定与冻结(2026-07-22) @@ -2179,6 +2181,7 @@ API 层 - PDF 工具栏采用左侧编辑操作、中间上一页/页码/下一页、右侧缩放操作的固定布局;页码输入支持大页数文档直接跳转,页面标记只按精确页码渲染。 - 历史 `all_pages` 草稿缺少原始页码时按第 1 页恢复,重新保存后统一写入 `exact_page + page_no`,避免第 1 页标记泄漏到第 2 页。 - 自动标记优先从 PDF 原生文字层补齐字符坐标与页面尺寸,仅在原生文字层为空时调用 OCR;补证结果仍属于待人工复核证据。 +- 字段规则新增 `auto_annotation_enabled`:已启用且授权 PDF/OCR 坐标的 Header 字段才生成订单级标签/值框,Line 字段才按 `display_name + aliases` 的唯一精确表头命中生成表头字段框和对应明细字段框。默认仅业务必填、自动建单关键或具名业务用途字段参与;其余可选字段默认关闭,管理员可按需启用。关闭后保留字段的抽取语义和既有模板绑定,但不再参与新的自动标记。多个字段共享同一别名、同一重建列承载多个标签或无精确命中时一律保留未绑定候选并进入人工复核。 - 物理行和字段框描述可重复应用的行版式:横向边界用于字段取值;一个物理行包含多条视觉子行时,系统使用首条 `line_no` 锚定明细的真实字符坐标,将字段框校准到实际视觉 band(未标注的描述/备注行仍计入序号),再把同一纵向字段组按严格单调顺序对齐到后续明细。记录出现额外换行时,以 X 命中、注册解析器和有限字段形态辅助选择;最佳候选不唯一时字段留空并记录 `coordinate_profile_field_band_ambiguous`,禁止静默猜测。该机制避免父框留白、行距变化和可变换行造成错位,也防止料号尾数污染数量、单位或日期;覆盖父行全高的旧字段框和多 `row_offset` 模板继续按原兼容链路解析。 - 翻页时只选择当前页表格;当前页没有表格时清空表格与局部候选上下文,禁止复用上一页坐标证据。 - 局部候选可返回多条逻辑明细;右侧按“候选 → 字段清单”展示,参与当前标注的字段统一按绑定 Schema 顺序排列,字段名表头不计入候选条数。 diff --git a/docs/funclist.md b/docs/funclist.md index 8a72e51c..6b5d7fb6 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -34,6 +34,12 @@ # 智能HR请假管理功能清单 +## 订单级字段标注与确定性提取 + +- 已实现独立订单字段标注域(订单字段标签、值区、单行/多行模式、停止标签),与明细表头和物理行完全分离。 +- 已实现页级 PDF/OCR 字符证据的锚点定位与相对区域读取;仅唯一原生坐标、格式校验通过的结果可标记 `confirmed`,其余进入 `needs_review` 或 `unavailable`。 +- 已实现盲测订单字段真值、发布门禁与运行时合并;Dify 不得覆盖 `confirmed` 字段,配置说明见 `docs/features/shipping-notice/order-extraction-workflow-dify-guide.md`。 + ## 货代订单抽取异步 Run(阶段 0–5 已完成) - 已实现 `ShippingOrderExtractionRun` 领域生命周期、不可变 Intake/Document/Schema 输入快照和服务端幂等键。 @@ -652,7 +658,7 @@ | 订单抽取紧凑结构化候选 | 已实现 / 质量验收延期 | 唯一 Manifest、Run 冻结、无 HTML/bbox/token 泄漏、accepted 字段锁与完整表零 Provider;人工真值及 95% 指标暂缓。 | | 订单抽取 L6 证据裁决与诊断 | 已实现 / 质量验收延期 | Observation 证据引用、纯文本无 cell 转复核、同 Document 强身份关联、冲突阻断、Candidate/UI 原因码和脱敏管理员追溯率诊断。 | | 订单抽取 L7 启用准备 | 工程完成 / 阶段未验收 | 删除 Profile/纯文本零 Provider;自动建单要求当前 Schema 的已批准质量批次,并冻结到 Run、Worker 再核验。人工真值延期时无批准批次可选,自动建单保持关闭;影子 Run 和实际 Dify 验收尚缺。 | -| 订单文档 Profile 独立盲测资格 | 已实现 / 待真实样本验收 | 发布前必须存在训练样本;盲测与 annotation/training 完全独立,常规模板至少 3 份、无表头至少 5 份,包含多明细及所需跨页续页样本;全通过、批准并原子提升到正式 checksum 后,唯一命中 Profile 才可零 Provider 建单;未批准、多模板或异常行回退 Dify/人工。 | +| 订单文档 Profile 独立盲测资格 | 已实现 / 待真实样本验收 | 发布前必须存在训练样本;盲测与 annotation/training 完全独立,所有模板仅需 1 份样本,仍须包含多明细及所需跨页续页证据;通过、批准并原子提升到正式 checksum 后,唯一命中 Profile 才可零 Provider 建单;未批准、多模板或异常行回退 Dify/人工。 | | 订单客户指纹与 Snapshot 绑定 | 已实现 | Bill-to/Ship-to 原文与正式客户分层保存;Bill-to 人工确认须有理由并生成规则版本化指纹,冻结只采纳该确认结果并固化客户简码。 | - 订单文档模板支持大页数 PDF 的上一页/页码跳转/下一页导航、顶部撤销/重做/复制/删除/保存/缩放工具栏、可折叠紧凑标注工具轨,以及按页隔离的区域标记;复制支持 `Ctrl/Cmd+D`,删除支持 `Delete/Backspace`,配置侧栏不再重复放置操作入口。 - 订单文档模板自动标记支持原生 PDF 坐标优先补证、扫描件 OCR 兜底、页面尺寸修复和可重复多物理行版式候选重算。 diff --git a/docs/tec.md b/docs/tec.md index feaaf8b3..2195fc53 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -19,6 +19,7 @@ - L3 将 parser revision 提升为 `v3`。扫描 PDF 直接适配 RapidOCR 多边形坐标,OCR cell 必须同时通过 OpenCV 网格和全部非空 cell 文本一致性;EML HTML 只保留清洗后的 table DOM,并用逻辑网格表达 rowspan/colspan。OCR/HTML 均固定 needs_review,原始 OCR 响应、页面图、主动 HTML 和临时表格片段不入库或 Dify。 - L4 新增 layout.v1→冻结 Schema 映射层,复用现有 HTML Grid 安全规则并保留真实 cell/token evidence。Run snapshot 升级为 v3并冻结内部 `layout_schema_candidates`;跨页只读显式 continuation。Manifest 强制剥离布局及映射候选,needs_review 不参与当前确定性执行。 - 订单坐标 Profile v2 的真相是 `document_match + table_regions[]`:每个表区保存相对区域、独立 `header_layouts[]`、连续的 `line_layouts[]`、字段区域到稳定 `field_id + field_code` 的绑定、受控解析器、排除/终止和跨页规则。表头只参与建议、校准和匹配,不能决定字段;所有区域为 `0..1` 相对坐标,越界、正面积重叠、重复明细字段和错序物理行由后端拒绝。 +- 订单级字段使用与表格层严格分离的 `order_field_layouts[]`:以稳定 `field_id/field_code` 绑定 Header Schema,按页域唯一定位标签锚点,再投影相对值区。页级 PDF 原生字符优先、扫描页 OCR 兜底;无证据、重复锚点、格式异常和固定坐标回退均不得 `confirmed`。确定性结果保存页号、锚点/值框和字符索引;盲测逐字段校验人工真值,Dify 只能补充未确认字段。 - 多行明细使用 `line_layouts[]` 表达任意连续 N 行版式:`row_offset=0` 固定为 main,后续为 continuation;每行独立保存区域和字段区域。字段只可绑定 Schema 显式允许的 `pdf_coordinate`/`ocr_coordinate` 来源,字段 ID 由后端重写,浏览器不能提交自由正则、脚本或 Prompt。 - 坐标版式建议先按自适应 y-band 分组物理行,再以左侧行号识别逻辑明细起点;相同 `row_offset` 的文本片段按相对 x 中心聚类,以相邻中心中点生成边界。接口只自动绑定确定性的 `line_no`,其他字段仍由管理员根据列示例确认,建议状态固定为 `needs_review`。 - `shipping_order_document_profiles` 保存模板编码、版本、绑定 Schema、v2 定义校验值、完整定义、checksum 和乐观锁。同一模板只允许一个 published 版本;后续阶段的 Run 将冻结唯一匹配结果、Profile checksum、坐标证据和完整定义,发布/退役不会改变历史运行。 @@ -1264,7 +1265,7 @@ Dify - L6 Observation 通过 `evidence_ref + evidence_metadata_json` 保存文本、邮件头或 layout cell 证据身份。旧纯文本表格解析器只做候选检测,不再进入 verified Observation;accepted layout 仅按同 Document 强身份关联。 - L7 清理后 Worker 的零 Provider 分支只认 accepted layout;Profile/纯文本必须进入唯一 Manifest 上下文。 - L7 质量门禁独立保存匿名质量批次/双人标签,不保存订单字段值;Run 创建和 Worker 执行均复核当前 Schema、阈值、指标仍达标和双角色批准,避免配置后漂移或绕过。 -- **Profile 盲测资格门禁**:`shipping_document_profile_test_suites/samples/runs` 保存草稿/发布 Profile 的独立盲测集、管理员确认真值及不可变执行摘要,不复制订单正文。发布事务先以草稿定义 hash 校验至少 1 份训练样本、与 annotation/training 完全独立的盲测样本、常规模板至少 3 份(无表头至少 5 份)、至少 1 份多明细真值及跨页声明对应的 `continuation_of` 样本;全量通过并批准后,事务内将套件/执行记录的草稿 hash 原子提升为正式 Profile checksum。Run 创建只冻结正式 checksum 的 `auto_create_approved` 事实。确定性订单直接由该 Profile 的当前解析行生成,绝不借用其他 accepted layout 候选。Dify 输出在进入持久化前还会校验冻结 field_id 白名单、Unit document_id 和 quote 的逐字可验证性。 +- **Profile 盲测资格门禁**:`shipping_document_profile_test_suites/samples/runs` 保存草稿/发布 Profile 的独立盲测集、管理员确认真值及不可变执行摘要,不复制订单正文。盲测集以 `profile_id + profile_checksum` 唯一绑定;模板保存改变草稿定义 hash 后,旧草稿集转为 `superseded`,新定义必须新建盲测集。发布事务校验至少 1 份训练样本、与 annotation/training 完全独立的 1 份盲测样本、至少 1 份多明细真值及跨页声明对应的 `continuation_of` 样本;全量通过并批准后,事务内将套件/执行记录的草稿 hash 原子提升为正式 Profile checksum。Run 创建只冻结正式 checksum 的 `auto_create_approved` 事实。确定性订单直接由该 Profile 的当前解析行生成,绝不借用其他 accepted layout 候选。Dify 输出在进入持久化前还会校验冻结 field_id 白名单、Unit document_id 和 quote 的逐字可验证性。 - **坐标 Profile 治理审计**:`shipping_order_document_profiles` 增加 `template_mode`、`training_sample_count` 与无正文 `match_strategy_summary_json`;`shipping_order_document_profile_samples` 仅绑定 Document/Table/角色,`shipping_order_document_profile_audits` 只记录对象身份、事件和计数/checksum 摘要。样本、区域、字段绑定、盲测和版本事件使用同一追加式审计表,禁止保存锚点文本、坐标、PDF、HTML、MinIO URL 或凭据。 - **受控坐标预览**:页面授权写入 Redis,key 为随机令牌且 TTL 120 秒;每个 token 固定管理员、Profile、Document、page_no,并通过 `GETDEL` 原子消费。Redis 不可用时预览 fail-closed。PDF 只在后端渲染低清单页 PNG;文本候选和局部预览按 Profile 样本关联再次鉴权,响应设置 `Cache-Control: private, no-store`。OCR 只能经绑定样本的显式管理员请求生成,EML 复用 HTML 白名单清洗结果且不渲染可执行 DOM。 - **订单客户指纹与冻结门禁**:`ShippingOrderCustomerMatch` 保留 Bill-to/Ship-to 原文、标准化组件、`order-customer-fingerprint.v1` 指纹、候选快照和确认理由。只有 `bill_to.status=confirmed` 且存在客户/简码/指纹/规则版本时 `order_freeze_service` 才冻结 Snapshot;冻结服务不接受外部 `customer_id` 或 `customer_short_code`。Snapshot 的 `rule_versions_json.ordering_customer` 保存匹配 ID、指纹、规则版本、确认方法和人员时间,避免主数据变化改写历史履约事实。 diff --git a/frontend/src/features/admin/api/shipping-order-document-profile.api.ts b/frontend/src/features/admin/api/shipping-order-document-profile.api.ts index 956d8168..60896764 100644 --- a/frontend/src/features/admin/api/shipping-order-document-profile.api.ts +++ b/frontend/src/features/admin/api/shipping-order-document-profile.api.ts @@ -13,12 +13,17 @@ import type { OrderProfileSampleDocument, CoordinateReconstructionPreview, CoordinateReconstructionSuggestion, + OrderFieldLayoutSuggestionResponse, + OrderFieldValuePreviewResponse, CoordinateReconstructionSettings, OrderProfileSampleIntake, OrderProfileSamplePreview, OrderProfilePreviewPages, OrderProfileBoundSample, OrderProfilePageTextCandidates, + OrderProfileBlindTestInput, + OrderProfileBlindTestAvailableSample, + OrderProfileBlindTestCandidate, OrderProfileTestSuite, ShippingOrderDocumentProfile, } from '../types/shipping-order-document-profile.types'; @@ -73,16 +78,38 @@ export const previewOrderProfileCoordinateReconstruction = ( /** 从冻结字符坐标建议全部或指定物理行;rowOffset 省略时保持原有全量识别。 */ export const suggestOrderProfileCoordinateReconstruction = ( - documentId: number, tableId: string, rowOffset?: number, + documentId: number, tableId: string, rowOffset?: number, schemaVersionId?: number, ) => requestJson( '/api/admin/shipping-notice/order-document-profile-samples/coordinate-reconstruction-suggestion', { method: 'POST', - body: JSON.stringify({ document_id: documentId, table_id: tableId, row_offset: rowOffset }), + body: JSON.stringify({ document_id: documentId, table_id: tableId, row_offset: rowOffset, schema_version_id: schemaVersionId }), ...jsonAuth(), }, ); +/** 根据冻结 Header Schema 与整页字符坐标建议订单字段锚点和值区;结果始终需要人工确认。 */ +export const suggestOrderProfileOrderFields = ( + documentId: number, schemaVersionId: number, pageNo: number, +) => requestJson( + '/api/admin/shipping-notice/order-document-profile-samples/order-field-suggestions', { + method: 'POST', + body: JSON.stringify({ document_id: documentId, schema_version_id: schemaVersionId, page_no: pageNo }), + ...jsonAuth(), + }, +); + +/** 按当前未保存的工作台定义重读订单单头字段值,供刷新后的复核面板恢复证据。 */ +export const previewOrderProfileOrderFieldValues = ( + documentId: number, schemaVersionId: number, pageNo: number, definition: ShippingOrderDocumentProfile['definition'], +) => requestJson( + '/api/admin/shipping-notice/order-document-profile-samples/order-field-values-preview', { + method: 'POST', + body: JSON.stringify({ document_id: documentId, schema_version_id: schemaVersionId, page_no: pageNo, definition }), + ...jsonAuth(), + }, +); + /** 为扫描 PDF 生成 OCR 坐标证据;随后仍必须由管理员审核重建网格。 */ export const generateOrderProfileOcrCoordinateEvidence = (documentId: number, tableId: string) => requestJson<{ document_id: number; table_id: string; source: 'pdf' | 'ocr' }>( @@ -199,10 +226,29 @@ export const createOrderProfileTestSuite = (profileId: number) => requestJson> }) => requestJson( +export const addOrderProfileTestSample = (suiteId: number, payload: OrderProfileBlindTestInput) => requestJson( `/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/samples`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, ); +/** 从草稿盲测集中移除错误或不再适用的样本;批准后的测试集由服务端拒绝修改。 */ +export const removeOrderProfileTestSample = (suiteId: number, sampleId: number) => requestJson( + `/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/samples/${sampleId}`, + { method: 'DELETE', ...jsonAuth() }, +); + +/** 列出未参与当前模板标注/训练且可用于盲测的受控订单样本。 */ +export const listOrderProfileBlindTestAvailableSamples = (suiteId: number) => requestJson<{ samples: OrderProfileBlindTestAvailableSample[] }>( + `/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/available-samples`, auth(), +); +/** 自动运行独立样本,候选仅供管理员勾选复核,尚未写入真值。 */ +export const previewOrderProfileBlindTestCandidate = (suiteId: number, payload: { document_id: number; table_id: string }) => requestJson( + `/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/candidate-preview`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, +); +/** 将逐项勾选和必要更正值转为既有盲测真值。 */ +export const confirmOrderProfileBlindTestReviews = (suiteId: number, payload: { document_id: number; table_id: string; row_reviews: unknown[]; order_field_reviews: Record }) => requestJson( + `/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/reviewed-samples`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, +); + /** 执行当前盲测集,任何字段或行数差异都保留为发布阻断。 */ export const executeOrderProfileTestSuite = (suiteId: number) => requestJson( `/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/execute`, { method: 'POST', ...jsonAuth() }, diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileWorkbench.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileWorkbench.vue index 7e04c75c..ecbdcb1a 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileWorkbench.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileWorkbench.vue @@ -30,19 +30,24 @@ import { deleteOrderProfileSample, getOrderProfilePageTextCandidates, listOrderDocumentProfiles, - addOrderProfileTestSample, addOrderProfileTrainingSample, approveOrderProfileTestSuite, createOrderProfileTestSuite, + removeOrderProfileTestSample, executeOrderProfileTestSuite, + confirmOrderProfileBlindTestReviews, generateOrderProfileOcrCoordinateEvidence, getOrderProfileSampleTables, listOrderProfileBoundSamples, + listOrderProfileBlindTestAvailableSamples, listOrderProfileSamples, previewOrderProfileRegion, + previewOrderProfileOrderFieldValues, + previewOrderProfileBlindTestCandidate, publishOrderDocumentProfile, retireOrderDocumentProfile, suggestOrderProfileHeader, + suggestOrderProfileOrderFields, updateOrderProfileFromSample, suggestOrderProfileCoordinateReconstruction, } from "@/features/admin/api/shipping-order-document-profile.api"; @@ -50,8 +55,11 @@ import type { CoordinateReconstructionPreview, OrderProfileCanvasRegion, OrderProfileTestSuite, + OrderProfileBlindTestAvailableSample, + OrderProfileBlindTestCandidate, OrderProfileFieldRegion, OrderProfileRelativeRegion, + OrderFieldLayoutSuggestion, ShippingOrderDocumentProfile, } from "@/features/admin/types/shipping-order-document-profile.types"; import type { @@ -114,6 +122,7 @@ const headerSuggestions = ref< }>; }> >([]); +const orderFieldSuggestions = ref([]); const drawerOpen = ref(false); const selectedId = ref(null); const documentCanvas = ref<{ @@ -131,10 +140,15 @@ const suggestingRegions = ref(false); const suggestionProgress = ref(""); const creationKind = ref(null); const testSuite = ref(null); -const testRows = ref("[]"); +const blindTestSamples = ref([]); +const blindTestCandidate = ref(null); +const blindTestSelection = ref(""); +const blindTestRowReviews = ref }>>([]); +const blindTestFieldReviews = ref>({}); const history = ref([]); const future = ref([]); let previewTimer: number | null = null; +let orderFieldValueTimer: number | null = null; let pendingGestureId: string | null = null; let pendingFormEdit: OrderProfileCanvasRegion[] | null = null; @@ -147,6 +161,13 @@ const form = reactive({ changeNote: "", }); const regions = ref([]); +/** 编辑历史模板时仍保留其绑定的 retired Schema,避免 select 将真实绑定显示为空。 */ +const selectableSchemaVersions = computed(() => { + const boundSchemaId = active.value?.schema_version_id || form.schemaId; + return schemas.value.filter( + (item) => item.status !== "draft" && (item.status !== "retired" || item.id === boundSchemaId), + ); +}); const lineFields = computed( () => schemas.value @@ -160,22 +181,55 @@ const lineFields = computed( item.allowed_sources?.includes("pdf_coordinate"), ) || [], ); -const bindableFields = computed( +/** 订单单头区域只能绑定 Schema 中声明为 header 的坐标字段。 */ +const headerFields = computed( () => schemas.value .find((item) => item.id === form.schemaId) ?.definition?.fields.filter( (item) => item.enabled !== false && + item.scope === "header" && item.allowed_sources?.includes("pdf_coordinate"), ) || [], ); const pageRegions = computed(() => regions.value.filter((item) => item.pageNo === pageNo.value), ); +/** 右侧单头摘要以画布已标记区域为准,不能被临时建议状态覆盖。 */ +const annotatedOrderFields = computed(() => + pageRegions.value + .filter((item) => item.kind === "order_field") + .map((item) => { + const suggestion = orderFieldSuggestions.value.find( + (candidate) => candidate.field_code && candidate.field_code === item.fieldCode, + ); + return { + id: item.id, + fieldCode: item.fieldCode || null, + label: item.fieldCode ? schemaFieldLabel(item.fieldCode) : item.label, + value: item.suggestedValue || suggestion?.suggested_value || "", + status: item.fieldCode ? "needs_review" : t("admin.shippingOrderProfiles.workbench.unbound"), + }; + }), +); const selectedRegion = computed( () => pageRegions.value.find((item) => item.id === selectedId.value) || null, ); +/** 订单字段在整个模板内只能绑定一次;当前编辑项仍保留在可选列表。 */ +const selectableOrderHeaderFields = computed(() => { + const selected = selectedRegion.value; + const occupied = new Set( + regions.value + .filter( + (item) => item.kind === "order_field" && item.id !== selected?.id && item.fieldCode, + ) + .map((item) => item.fieldCode!), + ); + return headerFields.value.filter( + (field) => !field.field_code || !occupied.has(field.field_code), + ); +}); /** 返回当前选中表头字段的内部行布局 ID,供列级建议安全复用。 */ const selectedHeaderLayoutId = computed(() => { const selected = selectedRegion.value; @@ -211,10 +265,12 @@ const previewCandidateRows = computed(() => { sourceRows: preview.value!.source_row_indices[index + offset] || [], })); }); -/** 将候选字段编码转换为当前冻结 Schema 的业务名称,未知字段保留编码以便排查。 */ -const previewFieldLabel = (fieldCode: string) => - lineFields.value.find((item) => item.field_code === fieldCode) - ?.display_name || fieldCode; +/** 将任意订单字段编码转换为当前冻结 Schema 的业务名称,避免单头候选泄露内部编码。 */ +const schemaFieldLabel = (fieldCode: string) => + [...headerFields.value, ...lineFields.value].find( + (item) => item.field_code === fieldCode, + )?.display_name || fieldCode; +const previewFieldLabel = schemaFieldLabel; /** 根据所有页已确认表头的横向范围,为当前明细字段提供不覆盖人工值的跨页绑定建议。 */ const selectedFieldHeaderSuggestion = computed(() => { const selected = selectedRegion.value; @@ -238,7 +294,9 @@ const issues = computed(() => { const result: string[] = []; if (!form.documentId) result.push(t("admin.shippingOrderProfiles.workbench.issues.sample")); - if (!form.tableId) + // A draft already has its sample binding. Pages without a MinerU table can still + // carry order-level annotations, so only creation needs a current table selection. + if (!active.value && !form.tableId) result.push(t("admin.shippingOrderProfiles.workbench.issues.table")); if (!lineFields.value.length) result.push( @@ -246,6 +304,16 @@ const issues = computed(() => { ); if (!regions.value.some((item) => item.kind === "line")) result.push(t("admin.shippingOrderProfiles.workbench.issues.line")); + if (regions.value.some( + (item) => item.kind === "order_field" && item.valueMode === "multi_line" && !item.stopAnchorText?.trim(), + )) result.push("多行订单字段必须填写结束标签。"); + const duplicateOrderFieldCodes = regions.value + .filter((item) => item.kind === "order_field" && item.fieldCode) + .map((item) => item.fieldCode!) + .filter((code, index, all) => all.indexOf(code) !== index); + if (duplicateOrderFieldCodes.length) { + result.push(`订单字段 ${[...new Set(duplicateOrderFieldCodes)].join(", ")} 已在其他区域绑定;请编辑原区域或先解除原绑定。`); + } return result; }); const canStart = computed(() => @@ -286,6 +354,7 @@ const finishFormEdit = () => { history.value.push(prior); future.value = []; schedulePreview(); + scheduleOrderFieldSuggestionValues(); }; /** 撤销上一项区域、字段或删除操作。 */ const undo = () => { @@ -312,6 +381,10 @@ const addRegion = ( pageRegions.value.filter((item) => item.kind === effectiveKind).length + 1; const selectedLayout = selectedRegion.value?.kind === "line" ? selectedRegion.value : null; + const selectedOrderAnchor = + selectedRegion.value?.kind === "order_anchor" + ? selectedRegion.value + : pageRegions.value.find((item) => item.kind === "order_anchor") || null; const existingHeaderField = effectiveKind === "header_field" && drawnRegion ? pageRegions.value.find( @@ -376,9 +449,20 @@ const addRegion = ( }), region, parentId, + orderFieldId: + effectiveKind === "order_field" + ? `order_field_${pageNo.value}_${sequence}` + : effectiveKind === "order_anchor" + ? `order_field_${pageNo.value}_${sequence}` + : null, fieldCode: null, pageNo: pageNo.value, }; + if (effectiveKind === "order_field" && selectedOrderAnchor) { + // One label may support customer and address values on the same visual row. + // Keep a unique layout ID on the value box and reference the label by parentId. + item.parentId = selectedOrderAnchor.id; + } regions.value.push(item); selectedId.value = item.id; }; @@ -428,9 +512,12 @@ const removeSelected = () => { if (!selectedRegion.value) return; checkpoint(); const removedId = selectedRegion.value.id; - // A field cannot outlive its physical line, otherwise the v2 definition would silently drop it. + const removesSharedAnchor = selectedRegion.value.kind === "order_anchor"; + // Removing a shared label removes dependent value boxes; removing one value box + // preserves the label and any sibling customer/address field. regions.value = regions.value.filter( - (item) => item.id !== removedId && item.parentId !== removedId, + (item) => item.id !== removedId && item.parentId !== removedId && + (!removesSharedAnchor || item.parentId !== removedId), ); selectedId.value = null; schedulePreview(); @@ -459,32 +546,46 @@ const updateRegion = (id: string, region: OrderProfileRelativeRegion) => { } item.region = region; schedulePreview(); + scheduleOrderFieldSuggestionValues(); }; /** 将区域编辑器转换为严格 v2 定义;浏览器只发送白名单 field_code/解析器和相对区域。 */ const definition = () => { - const tableRegions = [...new Set(regions.value.map((item) => item.pageNo))] + const tableRegions = [...new Set( + regions.value + .filter((item) => item.kind === "line" || item.kind === "header_field") + .map((item) => item.pageNo), + )] .sort((left, right) => left - right) .map((regionPageNo) => { const pageItems = regions.value.filter( (item) => item.pageNo === regionPageNo, ); const lineRegions = pageItems.filter((item) => item.kind === "line"); + const boundLineFieldRegionIds = new Set(); + const boundLineFieldCodes = new Set(); const fieldRegionsFor = (layoutId: string): OrderProfileFieldRegion[] => pageItems .filter( (item) => item.kind === "field" && item.parentId === layoutId && - item.fieldCode, + item.fieldCode && + !boundLineFieldCodes.has(item.fieldCode), ) - .map((item) => ({ - field_id: "", - field_code: item.fieldCode!, - region: item.region, - extractor_key: "direct", - allowed_sources: ["pdf_coordinate"], - minimum_evidence_level: "coordinate", - })); + .map((item) => { + // The v2 contract assigns each Schema line field one coordinate source. + // Continuation-row frames remain visible, but cannot duplicate that binding. + boundLineFieldCodes.add(item.fieldCode!); + boundLineFieldRegionIds.add(item.id); + return { + field_id: "", + field_code: item.fieldCode!, + region: item.region, + extractor_key: "direct", + allowed_sources: ["pdf_coordinate"], + minimum_evidence_level: "coordinate", + }; + }); const headerLayouts = pageItems .filter((item) => item.kind === "header_field" && item.parentId) .reduce((layoutIds, item) => { @@ -558,7 +659,8 @@ const definition = () => { (item) => (item.kind === "field" || item.kind === "header_field") && item.parentId && - !item.fieldCode, + (!item.fieldCode || + (item.kind === "field" && !boundLineFieldRegionIds.has(item.id))), ) .map((item) => ({ region_id: item.id, @@ -579,6 +681,122 @@ const definition = () => { minimum_margin: 0.15, }, table_regions: tableRegions, + order_field_layouts: regions.value + .filter((item) => item.kind === "order_field" && item.fieldCode) + .map((item) => ({ + layout_id: item.orderFieldId || item.id, + field_id: "", + field_code: item.fieldCode!, + page_scope: "exact_page" as const, + page_no: item.pageNo, + anchor: (() => { + const anchor = regions.value.find( + (candidate) => + candidate.kind === "order_anchor" && + (candidate.id === item.parentId || candidate.orderFieldId === item.orderFieldId), + ); + return anchor + ? { + anchor_id: anchor.id, + text: anchor.label, + aliases: [], + match_mode: "exact" as const, + region: anchor.region, + minimum_evidence_level: "coordinate" as const, + } + : null; + })(), + value_region: (() => { + const anchor = regions.value.find( + (candidate) => + candidate.kind === "order_anchor" && + (candidate.id === item.parentId || candidate.orderFieldId === item.orderFieldId), + ); + if (!anchor) return null; + const width = anchor.region.x1 - anchor.region.x0; + const height = anchor.region.y1 - anchor.region.y0; + return { + x0: (item.region.x0 - anchor.region.x0) / width, + y0: (item.region.y0 - anchor.region.y0) / height, + x1: (item.region.x1 - anchor.region.x0) / width, + y1: (item.region.y1 - anchor.region.y0) / height, + }; + })(), + fallback_value_region: (() => { + const anchor = regions.value.find( + (candidate) => + candidate.kind === "order_anchor" && + (candidate.id === item.parentId || candidate.orderFieldId === item.orderFieldId), + ); + return anchor ? null : item.region; + })(), + value_mode: item.valueMode || "single_line", + stop_anchors: + item.valueMode === "multi_line" && item.stopAnchorText?.trim() + ? [{ + anchor_id: `stop_${item.orderFieldId || item.id}`, + text: item.stopAnchorText.trim(), + aliases: [], + match_mode: "exact" as const, + minimum_evidence_level: "coordinate" as const, + }] + : [], + normalizer_key: null, + required: false, + minimum_evidence_level: item.evidenceSource === "ocr_coordinate" ? "ocr_coordinate" as const : "coordinate" as const, + })), + draft_unbound_order_field_layouts: regions.value + .filter( + (item) => + item.kind === "order_field" && + !item.fieldCode, + ) + .map((item) => { + const layoutId = item.orderFieldId || item.id.replace(/^unbound-/, ""); + const anchor = regions.value.find( + (candidate) => + candidate.kind === "order_anchor" && + (candidate.id === item.parentId || candidate.orderFieldId === layoutId), + ); + const valueRegion = anchor + ? { + x0: (item.region.x0 - anchor.region.x0) / (anchor.region.x1 - anchor.region.x0), + y0: (item.region.y0 - anchor.region.y0) / (anchor.region.y1 - anchor.region.y0), + x1: (item.region.x1 - anchor.region.x0) / (anchor.region.x1 - anchor.region.x0), + y1: (item.region.y1 - anchor.region.y0) / (anchor.region.y1 - anchor.region.y0), + } + : null; + return { + layout_id: layoutId, + label: item.label, + page_scope: "exact_page" as const, + page_no: item.pageNo, + anchor: anchor + ? { + anchor_id: anchor.id.replace("unbound-", ""), + text: anchor.label, + aliases: [], + match_mode: "exact" as const, + region: anchor.region, + minimum_evidence_level: "coordinate" as const, + } + : null, + value_region: valueRegion, + fallback_value_region: anchor ? null : item.region, + value_mode: item.valueMode || "single_line", + stop_anchors: + item.valueMode === "multi_line" && item.stopAnchorText?.trim() + ? [{ + anchor_id: `stop_${layoutId}`, + text: item.stopAnchorText.trim(), + aliases: [], + match_mode: "exact" as const, + minimum_evidence_level: "coordinate" as const, + }] + : [], + minimum_evidence_level: item.evidenceSource === "ocr_coordinate" ? "ocr_coordinate" as const : "coordinate" as const, + }; + }), }; }; /** 首次保存创建草稿并绑定样本;后续保存只更新草稿状态,保持当前画布视图不变。 */ @@ -613,6 +831,7 @@ const save = async () => { profiles.value = profiles.value.map((item) => item.id === savedProfile.id ? savedProfile : item, ); + await refreshOrderFieldSuggestionValues(); return; } await loadPages(); @@ -635,7 +854,7 @@ const startWorkspace = async () => { } await save(); }; -/** 以冻结坐标建议生成待复核标记;仅确定项次,其余列必须由管理员显式绑定。 */ +/** 以启用的 Schema 字段规则和冻结坐标生成待复核标记,绝不自动发布模板。 */ const suggestRegions = async () => { if (!form.documentId || !form.tableId || suggestingRegions.value) return; suggestingRegions.value = true; @@ -643,6 +862,11 @@ const suggestRegions = async () => { "admin.shippingOrderProfiles.workbench.autoSuggestCheckingCoordinates", ); try { + const orderFields = await suggestOrderProfileOrderFields( + form.documentId, + form.schemaId, + pageNo.value, + ); let suggestion; try { suggestionProgress.value = t( @@ -651,6 +875,8 @@ const suggestRegions = async () => { suggestion = await suggestOrderProfileCoordinateReconstruction( form.documentId, form.tableId, + undefined, + form.schemaId, ); } catch (error) { if ( @@ -672,9 +898,11 @@ const suggestRegions = async () => { suggestion = await suggestOrderProfileCoordinateReconstruction( form.documentId, form.tableId, + undefined, + form.schemaId, ); } - if (!suggestion.subrow_layouts.length) { + if (!suggestion.subrow_layouts.length && !orderFields.order_field_candidates.some((item) => item.status === "suggested")) { suggestionProgress.value = t( "admin.shippingOrderProfiles.workbench.autoSuggestNoRows", ); @@ -695,16 +923,49 @@ const suggestRegions = async () => { id: `${headerId}-field-${fieldIndex + 1}`, kind: "header_field", parentId: headerId, - label: field.text || t("admin.shippingOrderProfiles.workbench.unboundColumn", { count: fieldIndex + 1 }), + label: field.field_code || field.text || t("admin.shippingOrderProfiles.workbench.unboundColumn", { count: fieldIndex + 1 }), region: field.region, - fieldCode: null, + fieldCode: field.field_code || null, pageNo: pageNo.value, }); } } + orderFieldSuggestions.value = orderFields.order_field_candidates; + for (const [index, candidate] of orderFields.order_field_candidates.entries()) { + if ( + candidate.status !== "suggested" || + !candidate.anchor_region || + !candidate.value_region || + !candidate.anchor_text + ) continue; + const orderFieldId = `order_field_${pageNo.value}_${candidate.field_code}_${index + 1}`; + regions.value.push({ + id: `${orderFieldId}_anchor`, + kind: "order_anchor", + label: candidate.anchor_text, + region: candidate.anchor_region, + orderFieldId, + pageNo: pageNo.value, + }, { + id: orderFieldId, + kind: "order_field", + label: candidate.field_code + ? candidate.display_name + : `${candidate.display_name} · ${t("admin.shippingOrderProfiles.workbench.unboundColumn", { count: index + 1 })}`, + region: candidate.value_region, + fieldCode: candidate.field_code || null, + orderFieldId, + valueMode: candidate.value_mode, + suggestedValue: candidate.suggested_value || null, + evidenceSource: candidate.source, + pageNo: pageNo.value, + }); + } const layouts = suggestion.subrow_layouts.sort( (left, right) => left.row_offset - right.row_offset, ); + // Field bindings remain reviewable, but physical row geometry is still useful + // when a header alias has not yet been configured for the detected line number. for (const layout of layouts) { const lineId = `line_${pageNo.value}_${layout.row_offset + 1}`; const region = layout.region || { @@ -726,7 +987,11 @@ const suggestRegions = async () => { layout.column_boundaries.slice(0, -1).forEach((left, index) => { const right = layout.column_boundaries[index + 1]; if (right === undefined) return; - const fieldCode = layout.suggested_field_codes[index] || null; + // Continuation rows retain their value frames but only the main physical + // row owns the Schema binding required by the v2 coordinate contract. + const fieldCode = layout.row_offset === 0 + ? layout.suggested_field_codes[index] || null + : null; regions.value.push({ id: `${lineId}-field-${index + 1}`, kind: "field", @@ -748,7 +1013,7 @@ const suggestRegions = async () => { }); } selectedId.value = - pageRegions.value.find((item) => item.kind === "field" && item.fieldCode) + pageRegions.value.find((item) => (item.kind === "field" || item.kind === "order_field") && item.fieldCode) ?.id || pageRegions.value[0]?.id || null; @@ -769,6 +1034,39 @@ const suggestRegions = async () => { suggestingRegions.value = false; } }; +/** + * 根据当前页冻结字符证据回填订单字段候选值。 + * 保存后的 Profile 只持久化锚点和相对值区;候选文本必须重新读取,不能依赖 + * 自动标记当次浏览器内存中的 suggestedValue。 + */ +const refreshOrderFieldSuggestionValues = async () => { + if (!form.documentId || !form.schemaId || !pageRegions.value.some((item) => item.kind === "order_field")) return; + try { + const result = await previewOrderProfileOrderFieldValues( + form.documentId, + form.schemaId, + pageNo.value, + definition(), + ); + const valuesByCode = new Map(result.fields.map((item) => [item.field_code, item])); + pageRegions.value + .filter((item) => item.kind === "order_field") + .forEach((field) => { + const extracted = field.fieldCode ? valuesByCode.get(field.fieldCode) : undefined; + if (extracted?.value) field.suggestedValue = extracted.value; + }); + } catch { + // Candidate text is supplemental UI evidence; a transient refresh failure must + // not hide the saved template or turn a successful load into an error state. + } +}; +/** 订单字段框或读取方式变化后延迟回读整页字符证据,避免地址字段停留在旧的空候选。 */ +const scheduleOrderFieldSuggestionValues = () => { + if (orderFieldValueTimer) window.clearTimeout(orderFieldValueTimer); + orderFieldValueTimer = window.setTimeout(() => { + void refreshOrderFieldSuggestionValues(); + }, 400); +}; /** 仅在草稿存在且字段区域已变化时,400ms 防抖刷新局部确定性候选。 */ const schedulePreview = () => { if (previewTimer) window.clearTimeout(previewTimer); @@ -871,6 +1169,7 @@ const selectPage = async (nextPageNo: number) => { previewState.value = "idle"; previewError.value = ""; await loadPages(); + await refreshOrderFieldSuggestionValues(); }; /** 请求当前或全部表头的只读精确别名建议;结果不自动修改人工字段绑定。 */ const suggestHeaders = async (currentOnly: boolean) => { @@ -928,9 +1227,127 @@ const loadSampleTables = async () => { fail(error); } }; +/** + * 合并同页、同文本、同坐标的订单字段标签,使一个原稿标签可服务多个值字段。 + * 核心逻辑:历史定义按字段分别持久化 anchor,恢复画布时将几何相同的锚点折叠 + * 为单一可编辑区域,并把各值框改为引用该区域,避免重叠标签无法选择。 + * @param items - 由冻结 v2 定义还原出的画布区域。 + * @returns 使用共享标签父区域的画布区域集合。 + */ +const mergeEquivalentOrderAnchors = (items: OrderProfileCanvasRegion[]) => { + const canonicalByKey = new Map(); + const anchorIds = new Map(); + const retained: OrderProfileCanvasRegion[] = []; + const anchorKey = (item: OrderProfileCanvasRegion) => [ + item.pageNo, item.label.trim().toLocaleLowerCase(), + item.region.x0, item.region.y0, item.region.x1, item.region.y1, + ].join("|"); + for (const item of items) { + if (item.kind !== "order_anchor") { + retained.push(item); + continue; + } + const canonicalId = canonicalByKey.get(anchorKey(item)); + if (canonicalId) { + anchorIds.set(item.id, canonicalId); + if (item.orderFieldId) anchorIds.set(`layout:${item.orderFieldId}`, canonicalId); + continue; + } + canonicalByKey.set(anchorKey(item), item.id); + anchorIds.set(item.id, item.id); + if (item.orderFieldId) anchorIds.set(`layout:${item.orderFieldId}`, item.id); + retained.push(item); + } + return retained.map((item) => item.kind === "order_field" + ? { + ...item, + parentId: item.parentId + ? anchorIds.get(item.parentId) || item.parentId + : item.orderFieldId + ? anchorIds.get(`layout:${item.orderFieldId}`) || null + : null, + } + : item, + ); +}; + /** 从 v2 定义恢复区域,供草稿重开后继续在画布上编辑。 */ const restoreRegions = (profile: ShippingOrderDocumentProfile) => { const restored: OrderProfileCanvasRegion[] = [ + ...(profile.definition.draft_unbound_order_field_layouts || []).flatMap((item) => { + const pageNo = item.page_scope === "exact_page" ? item.page_no || 1 : 1; + if (!item.anchor?.region || !item.value_region) { + return [{ + id: `unbound-${item.layout_id}`, + kind: "order_field" as const, + label: item.label, + region: item.fallback_value_region || { x0: .1, y0: .1, x1: .2, y1: .15 }, + fieldCode: null, + pageNo, + }]; + } + const anchor = item.anchor.region; + const width = anchor.x1 - anchor.x0; + const height = anchor.y1 - anchor.y0; + return [{ + id: `unbound-${item.anchor.anchor_id}`, + kind: "order_anchor" as const, + label: item.anchor.text, + region: anchor, + orderFieldId: item.layout_id, + pageNo, + }, { + id: `unbound-${item.layout_id}`, + kind: "order_field" as const, + label: item.label, + region: { + x0: anchor.x0 + item.value_region.x0 * width, + y0: anchor.y0 + item.value_region.y0 * height, + x1: anchor.x0 + item.value_region.x1 * width, + y1: anchor.y0 + item.value_region.y1 * height, + }, + fieldCode: null, + orderFieldId: item.layout_id, + pageNo, + }]; + }), + ...(profile.definition.order_field_layouts || []).filter((item) => !item.anchor).map((item) => ({ + id: item.layout_id, + kind: "order_field" as const, + label: schemaFieldLabel(item.field_code), + region: item.fallback_value_region || { x0: .1, y0: .1, x1: .2, y1: .15 }, + fieldCode: item.field_code, + pageNo: item.page_scope === "exact_page" ? item.page_no || 1 : 1, + })), + ...(profile.definition.order_field_layouts || []).flatMap((item) => { + if (!item.anchor?.region || !item.value_region) return []; + const anchor = item.anchor.region; + const width = anchor.x1 - anchor.x0; + const height = anchor.y1 - anchor.y0; + return [{ + id: item.anchor.anchor_id, + kind: "order_anchor" as const, + label: item.anchor.text, + region: anchor, + orderFieldId: item.layout_id, + pageNo: item.page_scope === "exact_page" ? item.page_no || 1 : 1, + }, { + id: item.layout_id, + kind: "order_field" as const, + label: schemaFieldLabel(item.field_code), + region: { + x0: anchor.x0 + item.value_region.x0 * width, + y0: anchor.y0 + item.value_region.y0 * height, + x1: anchor.x0 + item.value_region.x1 * width, + y1: anchor.y0 + item.value_region.y1 * height, + }, + fieldCode: item.field_code, + orderFieldId: item.layout_id, + valueMode: item.value_mode, + stopAnchorText: item.stop_anchors[0]?.text || null, + pageNo: item.page_scope === "exact_page" ? item.page_no || 1 : 1, + }]; + }), ...profile.definition.table_regions.flatMap((table) => { const regionPageNo = restoreOrderProfileRegionPageNo(table); const headerLayoutIds = new Set( @@ -942,8 +1359,10 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => { id: `${header.layout_id}-field-${index}`, kind: "header_field" as const, label: item.field_code, - region: item.region, + // Keep the binding as well as its visible label. Without fieldCode, a + // reopened draft serializes this saved header as an unbound region. fieldCode: item.field_code, + region: item.region, parentId: header.layout_id, pageNo: regionPageNo, })), @@ -987,7 +1406,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => { ]; }), ]; - return restored; + return mergeEquivalentOrderAnchors(restored); }; /** 选择草稿时恢复绑定样本、页面和 v2 区域;历史版本只可复制为新草稿。 */ const edit = async (profile: ShippingOrderDocumentProfile) => { @@ -1006,6 +1425,7 @@ const edit = async (profile: ShippingOrderDocumentProfile) => { bound.find((item) => item.sample_role === "annotation")?.document_id || 0; await loadSampleTables(); await loadPages(); + await refreshOrderFieldSuggestionValues(); } catch (error) { fail(error); } @@ -1018,45 +1438,86 @@ const publish = async (profile: ShippingOrderDocumentProfile) => { fail(error); } }; -/** 打开草稿盲测;真值需要管理员显式填写,不能从解析候选自动复制。 */ +/** 打开草稿盲测并加载严格排除建模证据后的可选独立样本。 */ const openBlindTest = async (profile: ShippingOrderDocumentProfile) => { try { await edit(profile); testSuite.value = await createOrderProfileTestSuite(profile.id); + blindTestSamples.value = (await listOrderProfileBlindTestAvailableSamples(testSuite.value.id)).samples; + blindTestCandidate.value = null; + blindTestSelection.value = ""; } catch (error) { fail(error); } }; -/** 将当前绑定样本加入盲测,发布门禁会进一步校验独立性、多明细和跨页覆盖。 */ -const addBlindTestSample = async () => { - if (!testSuite.value || !form.documentId || !form.tableId) return; +/** 运行用户选择的独立样本,并初始化逐行、逐订单字段的显式正确/错误复核。 */ +const loadBlindTestCandidate = async () => { + if (!testSuite.value || !blindTestSelection.value) return; try { - const expectedRows = JSON.parse(testRows.value); - if ( - !Array.isArray(expectedRows) || - !expectedRows.length || - expectedRows.some( - (row) => - !row || - typeof row !== "object" || - Array.isArray(row) || - !Object.keys(row).length, - ) - ) { - throw new Error( - t("admin.shippingOrderProfiles.blindTest.expectedRowsInvalid"), - ); - } - testSuite.value = await addOrderProfileTestSample(testSuite.value.id, { - document_id: form.documentId, - table_id: form.tableId, - expected_rows: expectedRows, + const [documentId, tableId] = blindTestSelection.value.split("|"); + if (!documentId || !tableId) return; + blindTestCandidate.value = await previewOrderProfileBlindTestCandidate(testSuite.value.id, { + document_id: Number(documentId), table_id: tableId, }); + blindTestRowReviews.value = blindTestCandidate.value.rows.map((row) => ({ correct: null, values: { ...row } })); + blindTestFieldReviews.value = Object.fromEntries(blindTestCandidate.value.order_fields.map((field) => [ + field.field_code, { correct: null, value: field.value }, + ])); + } catch (error) { + fail(error); + } +}; +/** 确认全部候选后写入既有真值结构;错误项必须由管理员提供更正值。 */ +const confirmBlindTestCandidate = async () => { + if (!testSuite.value || !blindTestCandidate.value) return; + try { + testSuite.value = await confirmOrderProfileBlindTestReviews(testSuite.value.id, { + document_id: blindTestCandidate.value.document_id, table_id: blindTestCandidate.value.table_id, + row_reviews: blindTestRowReviews.value, order_field_reviews: blindTestFieldReviews.value, + }); + blindTestSamples.value = (await listOrderProfileBlindTestAvailableSamples(testSuite.value.id)).samples; + blindTestCandidate.value = null; + blindTestSelection.value = ""; message.success(t("admin.shippingOrderProfiles.updated")); } catch (error) { fail(error); } }; +/** 从草稿盲测移除已加入的失败样本,并重置当前候选以避免引用已删除真值。 */ +const removeBlindTestSample = async (sampleId: number) => { + if (!testSuite.value || testSuite.value.status !== "draft") return; + try { + testSuite.value = await removeOrderProfileTestSample(testSuite.value.id, sampleId); + blindTestSamples.value = (await listOrderProfileBlindTestAvailableSamples(testSuite.value.id)).samples; + blindTestCandidate.value = null; + blindTestSelection.value = ""; + blindTestRowReviews.value = []; + blindTestFieldReviews.value = {}; + message.success(t("admin.shippingOrderProfiles.blindTest.sampleRemoved")); + } catch (error) { + fail(error); + } +}; +/** 将错误明细的手工 JSON 更正限制为单行字段对象,避免隐藏地沿用错误候选。 */ +const updateBlindTestRowCorrection = (index: number, event: Event) => { + const input = event.target as HTMLTextAreaElement; + try { + const values = JSON.parse(input.value); + if (!values || typeof values !== "object" || Array.isArray(values)) throw new Error(); + const review = blindTestRowReviews.value[index]; + if (!review) return; + review.values = values; + } catch { + message.error(t("admin.shippingOrderProfiles.blindTest.correctionInvalid")); + } +}; +/** 写入订单字段复核结果;候选初始化失败时不允许隐式创建不完整的真值。 */ +const updateBlindTestFieldReview = (fieldCode: string, patch: { correct?: boolean; value?: unknown }) => { + const review = blindTestFieldReviews.value[fieldCode]; + if (!review) return; + if (patch.correct !== undefined) review.correct = patch.correct; + if (patch.value !== undefined) review.value = patch.value; +}; /** 将当前选择的受控样本另行绑定为训练证据;服务端禁止其再用于盲测。 */ const addTrainingSample = async () => { if (!active.value || !form.documentId || !form.tableId) return; @@ -1072,9 +1533,9 @@ const addTrainingSample = async () => { fail(error); } }; -/** 运行并批准盲测;批准失败时服务端返回不满足的字段/行门禁。 */ +/** 运行并批准草稿盲测;已批准的套件只读,避免重复调用导致服务端门禁报错。 */ const runBlindTest = async (approve = false) => { - if (!testSuite.value) return; + if (!testSuite.value || testSuite.value.status !== "draft") return; try { testSuite.value = await executeOrderProfileTestSuite(testSuite.value.id); if (approve) @@ -1191,9 +1652,9 @@ const loadProfiles = async () => { ]); profiles.value = profileRows; samples.value = sampleRows; - schemas.value = state.versions.filter( - (item) => item.status !== "draft" && item.definition, - ); + // Keep all version snapshots in memory. An existing Profile may reference a + // retired snapshot, which must remain editable/readable until an explicit migration. + schemas.value = state.versions.filter((item) => item.definition); form.schemaId ||= schemas.value.find((item) => item.status === "published")?.id || 0; }; @@ -1260,6 +1721,8 @@ const handleShortcut = (event: KeyboardEvent) => { h: "header_field", l: "line", f: "field", + o: "order_field", + a: "order_anchor", x: "exclusion", }; const kind = kindByKey[event.key.toLowerCase()]; @@ -1422,8 +1885,8 @@ onBeforeUnmount(() => { >