From 265a6e179ab67bcbb24b0f3fd5cc3af61bfe29f1 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Fri, 4 Sep 2026 20:53:06 +0800 Subject: [PATCH] =?UTF-8?q?test(shipping):=20=E6=9B=B4=E6=96=B0=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E5=A4=8D=E6=A0=B8=E5=BA=93=E5=AD=98=E4=B8=8E=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E6=B5=81=E7=A8=8B=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/workspace/shipping_notice.py | 192 ++--- .../jobs/handlers/shipping_notice_parse.py | 21 +- .../jobs/handlers/shipping_stp_auto_create.py | 29 +- backend/app/models/shipping_order_review.py | 10 +- .../shipping_order_review_line_decision.py | 12 +- .../shipping_order_review_suggestion.py | 2 +- .../shipping_order_review_wave_idempotency.py | 10 +- .../models/shipping_order_review_wave_line.py | 13 +- backend/app/models/shipping_order_schema.py | 15 +- .../candidate_qualification_service.py | 73 +- .../shipping_notice/chat_tool_capability.py | 4 +- .../customer_auto_resolution.py | 276 +++----- .../shipping_notice/customer_identity_gate.py | 101 +-- .../services/shipping_notice/dify_inputs.py | 10 +- .../document_profile_quality_service.py | 52 +- .../shipping_notice/duplicate_detection.py | 109 ++- .../error_explainability_contract.py | 4 +- .../identity_resolution/resolver.py | 18 +- .../shipping_notice/identity_rules/service.py | 15 - .../order_auto_freeze_policy.py | 17 +- .../order_build_eligibility_service.py | 19 +- .../order_candidate_builder.py | 92 ++- ...order_document_profile_creation_service.py | 2 + .../order_document_profile_preview_service.py | 47 +- .../order_document_profile_service.py | 95 ++- .../shipping_notice/order_extraction.py | 14 +- .../shipping_notice/order_extraction_merge.py | 12 +- .../order_extraction_workflow.py | 63 +- .../order_extraction_workspace_projection.py | 8 +- .../shipping_notice/order_field_purposes.py | 5 +- .../shipping_notice/order_freeze_service.py | 81 ++- .../order_review_auto_progress_coordinator.py | 53 +- .../order_review_confirmation_service.py | 494 +++++-------- .../order_review_customer_service.py | 106 +-- .../order_review_disposition_service.py | 39 +- .../order_review_draft_service.py | 272 +++----- .../order_review_evidence_selector.py | 86 +-- .../order_review_evidence_service.py | 6 +- .../order_review_evidence_view.py | 89 ++- .../order_review_field_conflict_service.py | 22 +- .../order_review_llm_auto_upgrade.py | 32 +- .../order_review_llm_contract.py | 22 +- .../shipping_notice/order_review_llm_gate.py | 18 +- .../order_review_llm_service.py | 36 +- .../order_review_llm_validation.py | 78 ++- .../order_review_reservation_service.py | 8 +- .../shipping_notice/order_supplement_merge.py | 95 ++- .../shipping_notice/order_task_service.py | 21 +- .../order_task_stage_machine.py | 36 +- .../app/services/shipping_notice/po_number.py | 5 +- .../task_candidate_reconciliation.py | 18 +- .../task_disposition_service.py | 132 +++- .../task_field_conflict_service.py | 57 +- .../task_order_field_editor.py | 7 +- .../task_supersession_service.py | 41 +- .../services/shipping_notice/task_workflow.py | 303 ++++---- .../services/shipping_notice/tool_common.py | 45 +- .../services/shipping_notice/tool_response.py | 14 +- backend/app/services/shipping_notice/tools.py | 1 - .../shipping_notice/user_facing_status.py | 19 +- .../workflow_ledger_service.py | 12 +- .../test_customer_resolution_service.py | 84 +++ .../test_reconciliation_phase34_contract.py | 3 +- .../test_shipping_attachment_selection.py | 6 +- ...hipping_auto_progress_controller_phase1.py | 55 +- .../tests/test_shipping_auto_progress_p0_3.py | 154 +++- .../test_shipping_candidate_qualification.py | 3 + .../test_shipping_chat_action_handlers.py | 1 - .../test_shipping_chat_tool_capability.py | 8 +- ...hipping_coordinate_table_reconstruction.py | 190 ++++- .../test_shipping_customer_auto_resolution.py | 206 +++--- .../test_shipping_customer_identity_gate.py | 194 +++--- ...est_shipping_customer_shadow_resolution.py | 33 + ...est_shipping_document_layout_html_table.py | 16 +- .../test_shipping_document_layout_job.py | 35 +- ...test_shipping_document_layout_lifecycle.py | 113 ++- .../test_shipping_document_profile_quality.py | 103 ++- ..._shipping_error_explainability_contract.py | 52 +- ...est_shipping_excel_readiness_order_task.py | 57 ++ .../test_shipping_field_asset_governance.py | 34 + .../tests/test_shipping_field_split_core.py | 2 +- .../test_shipping_formal_task_edit_audit.py | 17 +- .../tests/test_shipping_generic_order_gate.py | 4 +- .../test_shipping_line_source_ambiguity.py | 83 +++ .../test_shipping_notice_business_case.py | 42 +- .../test_shipping_notice_business_dedup.py | 126 +++- backend/tests/test_shipping_notice_extract.py | 53 +- ...test_shipping_notice_field_adjudication.py | 4 +- .../test_shipping_notice_intakes_lifecycle.py | 256 ++----- .../test_shipping_notice_intakes_parse.py | 214 +----- .../test_shipping_notice_openapi_contract.py | 4 +- .../test_shipping_notice_order_extraction.py | 342 ++++----- .../test_shipping_notice_query_service.py | 554 ++++++++++----- .../test_shipping_notice_reservation_id.py | 18 + .../test_shipping_notice_state_machine.py | 84 ++- .../test_shipping_notice_stp_acceptance.py | 178 +++-- backend/tests/test_shipping_notice_tools.py | 518 ++++---------- .../tests/test_shipping_notice_ui_state.py | 542 ++++++++++----- ...test_shipping_notice_user_facing_status.py | 14 +- .../test_shipping_order_auto_freeze_policy.py | 31 +- .../test_shipping_order_build_eligibility.py | 98 +-- .../test_shipping_order_customer_matching.py | 182 ----- ...shipping_order_document_profile_service.py | 59 +- .../tests/test_shipping_order_edit_window.py | 120 ++++ ...st_shipping_order_extraction_dify_guide.py | 8 +- ...test_shipping_order_extraction_progress.py | 6 +- ...ping_order_extraction_quality_migration.py | 2 +- .../test_shipping_order_extraction_runs.py | 31 +- .../test_shipping_order_extraction_stage0.py | 1 + ...st_shipping_order_extraction_submission.py | 15 +- .../test_shipping_order_extraction_worker.py | 32 +- ...er_extraction_workspace_projection_unit.py | 22 +- .../test_shipping_order_field_purposes.py | 34 +- .../test_shipping_order_profile_matcher.py | 68 ++ ...shipping_order_profile_parse_validation.py | 45 ++ ...shipping_order_review_evidence_selector.py | 20 +- ...st_shipping_order_review_field_conflict.py | 8 +- .../test_shipping_order_review_llm_audit.py | 3 + backend/tests/test_shipping_order_schema.py | 118 +++- .../tests/test_shipping_order_schema_diff.py | 11 +- .../test_shipping_order_schema_runtime.py | 377 +++++----- ...est_shipping_order_schema_runtime_audit.py | 4 +- ...test_shipping_order_task_candidate_link.py | 23 +- .../test_shipping_order_task_stage_machine.py | 79 ++- ..._shipping_order_task_status_consistency.py | 25 +- ...ping_override_persists_projected_source.py | 241 +++++++ .../test_shipping_process_recovery_plan.py | 363 +++++++--- ...ipping_processing_projection_invariants.py | 7 +- ...t_shipping_processing_projection_stage4.py | 522 ++++++++++++-- .../test_shipping_projection_cross_surface.py | 37 +- ...st_shipping_projection_gate_equivalence.py | 471 +++++++++++++ ...est_shipping_review_case_audit_timeline.py | 3 + ...t_shipping_review_confirm_auto_progress.py | 56 +- .../test_shipping_review_formal_task_edit.py | 161 +++-- ...t_shipping_review_wave_line_concurrency.py | 47 +- ...hipping_review_workbench_stage_layering.py | 14 +- ...ipping_review_workbench_state_isolation.py | 28 +- .../tests/test_shipping_schema_edit_policy.py | 11 +- .../tests/test_shipping_stage_capability.py | 655 ++++++++++++++++++ ...st_shipping_stp_audit_detail_and_strict.py | 38 +- ...test_shipping_stp_multi_source_recovery.py | 131 +++- .../test_shipping_stp_phase3_auto_create.py | 21 +- .../test_shipping_task_audit_timeline.py | 2 + ...ipping_task_center_review_run_deep_link.py | 2 - backend/tests/test_shipping_task_event_fk.py | 20 + ...test_shipping_task_field_reconciliation.py | 95 ++- .../test_shipping_task_parsed_projection.py | 52 +- .../tests/test_shipping_task_supersession.py | 25 +- backend/tests/test_shipping_upload_attempt.py | 34 +- backend/tests/test_shipping_wave_rerouting.py | 156 +++++ .../test_shipping_workbench_service_chains.py | 2 - .../tests/test_shipping_workflow_recovery.py | 48 +- docs/demand.md | 11 +- docs/features/shipping-notice/business.md | 62 ++ .../customer_identity_rules_plan.md | 2 +- .../display-and-button-contract.md | 366 ++++++++++ .../order-extraction-workflow-dify-guide.md | 10 +- docs/features/shipping-notice/technical.md | 158 ++++- docs/funclist.md | 16 +- docs/openapi/shipping_notice_tools.dify.json | 4 +- docs/tec.md | 16 +- .../ReviewCurrentProcessingCard.spec.ts | 30 +- ...ShippingConversationProcessingCard.spec.ts | 242 ++++++- .../ShippingOrderExtractionCard.spec.ts | 305 +++++++- .../shipping/ShippingWorkflowTimeline.spec.ts | 33 +- .../normalizeShippingProcessing.spec.ts | 14 + .../orderExtractionProgressDisplay.spec.ts | 16 + .../shipping/shippingProcessingLabels.spec.ts | 94 +++ 168 files changed, 9420 insertions(+), 4613 deletions(-) create mode 100644 backend/tests/services/shipping_notice/test_customer_resolution_service.py create mode 100644 backend/tests/test_shipping_excel_readiness_order_task.py create mode 100644 backend/tests/test_shipping_line_source_ambiguity.py delete mode 100644 backend/tests/test_shipping_order_customer_matching.py create mode 100644 backend/tests/test_shipping_order_edit_window.py create mode 100644 backend/tests/test_shipping_override_persists_projected_source.py create mode 100644 backend/tests/test_shipping_projection_gate_equivalence.py create mode 100644 backend/tests/test_shipping_stage_capability.py create mode 100644 backend/tests/test_shipping_task_event_fk.py create mode 100644 backend/tests/test_shipping_wave_rerouting.py create mode 100644 docs/features/shipping-notice/display-and-button-contract.md diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 3587f846..7ea88a80 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -22,7 +22,7 @@ from app import db from app.core.auth.jwt import get_current_user from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError from app.core.response import ok -from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice +from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask from app.services.shipping_notice.chat_actions import build_chat_actions_payload from app.services.shipping_notice.constants import ( AUTO_CHAIN_FALLBACK, @@ -53,7 +53,6 @@ from app.services.shipping_notice.customer_identity_gate import ( confirm_task_customer, list_customer_options, ) -from app.services.shipping_notice.order_customer_matching import confirm_order_customer_match workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__) @@ -145,6 +144,16 @@ def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> No ) +def _require_formal_notice(task: Any) -> ShippingNotice: + """正式 Notice 专属接口的实体守卫;OT 在库存门禁前不得进入通知/上传写路径。""" + if not isinstance(task, ShippingNotice): + raise ValidationError( + 'Formal shipping notice is required for this operation', + code='SHIPPING.FORMAL_NOTICE_REQUIRED', + ) + return task + + @workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET']) def workspace_shipping_tasks(): """分页列出当前用户可见的发货任务,可按处理状态过滤。""" @@ -214,7 +223,7 @@ def _batch_task_nos(data: dict) -> list[str]: return normalized -def _can_dispose_task(user, task: ShippingNotice) -> bool: +def _can_dispose_task(user, task) -> bool: """管理员可跨用户处置;普通用户仅可处置自己名下或未归属任务。""" return str(getattr(user, 'role', '')).lower() == 'admin' or task.user_id in {None, user.id} @@ -372,96 +381,6 @@ def workspace_confirm_shipping_customer(task_no: str): return _ok(serialize_task_detail(updated)) -@workspace_shipping_notice_bp.route( - '/shipping-order-extractions//customer-matches//confirm', - methods=['POST'], -) -def workspace_confirm_order_customer_match(extraction_id: int, role: str): - """确认当前用户订单解析中的 Bill-to 客户或 Ship-to 送货站点。""" - user = _require_user() - extraction = ( - db.session.query(ShippingOrderExtraction) - .join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderExtraction.intake_id) - .filter( - ShippingOrderExtraction.id == extraction_id, - ShippingOrderIntake.user_id == user.id, - ) - .one_or_none() - ) - if extraction is None: - raise NotFoundError( - 'Order extraction not found', - code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND', - ) - data = request.get_json(silent=True) or {} - try: - customer_id = int(data.get('customer_id')) - site_id = int(data['site_id']) if data.get('site_id') is not None else None - except (TypeError, ValueError) as exc: - raise ValidationError( - 'Customer id is required', - code='SHIPPING.ORDER_CUSTOMER_REQUIRED', - details={'field': 'customer_id'}, - ) from exc - result = confirm_order_customer_match( - extraction.id, - role=role, - customer_id=customer_id, - site_id=site_id, - actor_id=user.id, - reason=str(data.get('reason') or ''), - commit=False, - ) - # [STEP P1-7] 抽取侧客户确认后,同事务内触发 Case 级协调器(level-triggered reconcile 补偿)。 - # 通过 Extraction → Candidate → Review Case 反查未终态 Case;若抽取阶段太早尚无 Case,不报错跳过。 - if role == 'bill_to': - from app.models import ( - ShippingOrderCandidate, - ShippingOrderReviewCase, - ShippingOrderReviewStream, - ) - from app.services.shipping_notice.order_review_auto_progress_coordinator import ( - reconcile_single_case_for_auto_progress, - ) - _TERMINAL = frozenset({ - 'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending', - }) - candidates = list( - ShippingOrderCandidate.query - .filter_by(order_extraction_id=int(extraction.id)) - .all() - ) - candidate_ids = {int(c.id) for c in candidates} - case = None - if candidate_ids: - case = ( - ShippingOrderReviewCase.query - .join( - ShippingOrderReviewStream, - ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id, - ) - .filter(ShippingOrderReviewCase.candidate_id.in_(candidate_ids)) - .first() - ) - if case is None and extraction.run_id: - case = ( - ShippingOrderReviewCase.query - .join( - ShippingOrderReviewStream, - ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id, - ) - .filter(ShippingOrderReviewCase.run_id == int(extraction.run_id)) - .first() - ) - if case is not None and str(case.status or '') not in _TERMINAL and not case.confirmed_task_id: - reconcile_single_case_for_auto_progress( - case=case, - trigger='extraction_customer_confirmed', - refresh_validation=True, - ) - db.session.commit() - return _ok(result) - @workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST']) def workspace_create_shipping_task_from_notice(): """接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。""" @@ -492,11 +411,14 @@ def workspace_create_shipping_task_from_notice(): ) if not intake.accepted: return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED}) - task = ShippingNotice.query.filter_by(task_no=task_id).first() + from app.models import ShippingOrderTask + from app.models import ShippingOrderIntake + task = ShippingOrderTask.query.filter_by(task_no=task_id).first() if task: - task.raw_content = intake.text - task.source_file_name = intake.filename or task.source_file_name - task.source_file_type = intake.source_file_type or task.source_file_type + intake_row = db.session.get(ShippingOrderIntake, task.intake_id) if task.intake_id else None + if intake_row is not None: + intake_row.extracted_text = intake.text + intake_row.parse_warnings_json = list(intake.warnings or []) db.session.commit() from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator orchestrator_started = start_task_orchestrator(task_id) @@ -637,6 +559,7 @@ def workspace_update_shipping_notice_fields(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') + task = _require_formal_notice(task) data = request.get_json(silent=True) or {} fields = data.get('fields') if not isinstance(fields, dict) or not fields: @@ -683,6 +606,7 @@ def workspace_update_shipping_notice_line(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') + task = _require_formal_notice(task) data = request.get_json(silent=True) or {} try: line_index = int(data.get('line_index')) @@ -771,6 +695,7 @@ def workspace_add_shipping_notice_line(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') + task = _require_formal_notice(task) data = request.get_json(silent=True) or {} line = data.get('line') if not isinstance(line, dict) or not line: @@ -796,6 +721,7 @@ def workspace_remove_shipping_notice_line(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') + task = _require_formal_notice(task) data = request.get_json(silent=True) or {} try: line_index = int(data.get('line_index')) @@ -834,11 +760,15 @@ def workspace_auto_progress_shipping_task(task_no: str): str(task.task_no), trigger='workspace_auto_progress', operator_id=int(user.id), ) - # 兼容旧前端:若仍有 export 路径则附带 download_url。 + # 导出下载路径只从当前有效 Artifact 读取,Notice 不再保存文件投影。 if isinstance(result, dict) and result.get('status') in {'completed', 'running', 'ok'}: - # 重新加载任务以读取 export_file_path(若决策器已推进到导出)。 refreshed = get_task_for_user(task_no, user.id) - export_path = getattr(refreshed, 'export_file_path', None) if refreshed is not None else None + artifact = None + if refreshed is not None: + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + + artifact = latest_export_artifact(refreshed) + export_path = getattr(artifact, 'file_path', None) if export_path: result = { **result, @@ -862,6 +792,7 @@ def workspace_mark_manual_uploaded(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') + task = _require_formal_notice(task) _assert_fulfillment_task_ownership(task, user.id) from app.services.shipping_notice import tools as shipping_tools data = request.get_json(silent=True) or {} @@ -1139,6 +1070,7 @@ def workspace_shipping_task_export(task_no: str): """下载当前用户可访问任务的出货 Excel;写入统一访问审计。""" user = _require_user() task = get_task_for_user(task_no, user.id) + task = _require_formal_notice(task) err_msg = task_export_error_message(task) if err_msg: raise NotFoundError(err_msg) @@ -1900,19 +1832,17 @@ def workspace_patch_shipping_order_review_header_field(case_no: str, field_id: s return _ok(result) -@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases//draft/lines//fields/', methods=['PATCH']) -def workspace_patch_shipping_order_review_line_field(case_no: str, line_key: str, field_id: str): - """修改或恢复一个复核订单行字段;行只接受服务端返回的稳定 line_key。""" +@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases//draft/lines//fields/', methods=['PATCH']) +def workspace_patch_shipping_order_review_line_field(case_no: str, draft_line_id: str, field_id: str): + """修改或恢复一个复核订单行字段;行只接受服务端返回的 draft_line_id。""" user = _require_user() from app.services.shipping_notice.order_review_draft_service import patch_line_field payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_field_changed') result = patch_line_field( - user_id=user.id, case_no=case_no, line_key=line_key, field_id=field_id, value=payload.get('value'), + user_id=user.id, case_no=case_no, draft_line_id=draft_line_id, field_id=field_id, value=payload.get('value'), expected_draft_version=payload.get('expected_draft_version'), restore_machine=bool(payload.get('restore_machine')), - override_reason_code=payload.get('override_reason_code'), - override_reason_text=payload.get('override_reason_text'), ) db.session.commit() return _ok(result) @@ -1930,30 +1860,30 @@ def workspace_add_shipping_order_review_line(case_no: str): return _ok(result) -@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases//draft/lines//copy', methods=['POST']) -def workspace_copy_shipping_order_review_line(case_no: str, line_key: str): +@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases//draft/lines//copy', methods=['POST']) +def workspace_copy_shipping_order_review_line(case_no: str, draft_line_id: str): """复制一条复核行;后端校验会阻断由复制造成的重复 Reservation。""" user = _require_user() from app.services.shipping_notice.order_review_draft_service import copy_line payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_copied') result = copy_line( - user_id=user.id, case_no=case_no, line_key=line_key, + user_id=user.id, case_no=case_no, draft_line_id=draft_line_id, expected_draft_version=payload.get('expected_draft_version'), ) db.session.commit() return _ok(result) -@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases//draft/lines/', methods=['DELETE']) -def workspace_delete_shipping_order_review_line(case_no: str, line_key: str): +@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases//draft/lines/', methods=['DELETE']) +def workspace_delete_shipping_order_review_line(case_no: str, draft_line_id: str): """删除一条复核行;即使删除最后一行,也只更新草稿和阻断校验。""" user = _require_user() from app.services.shipping_notice.order_review_draft_service import delete_line payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_deleted') result = delete_line( - user_id=user.id, case_no=case_no, line_key=line_key, + user_id=user.id, case_no=case_no, draft_line_id=draft_line_id, expected_draft_version=payload.get('expected_draft_version'), ) db.session.commit() @@ -1992,7 +1922,7 @@ def workspace_reroute_shipping_order_review_inventory_routing(case_no: str): """ 按最新已发布规则重算库存源路由;不重新识别 PDF,并清除历史人工库存源决定。 - 核心逻辑:可选 line_key;携带 expected_draft_version 与幂等键。 + 核心逻辑:可选 draft_line_id;携带 expected_draft_version 与幂等键。 """ user = _require_user() from app.services.shipping_notice.order_review_draft_service import reroute_inventory_routing @@ -2005,7 +1935,7 @@ def workspace_reroute_shipping_order_review_inventory_routing(case_no: str): case_no=case_no, expected_draft_version=payload.get('expected_draft_version'), idempotency_key=payload.get('idempotency_key'), - line_key=payload.get('line_key'), + draft_line_id=payload.get('draft_line_id'), ) db.session.commit() return _ok(result) @@ -2122,7 +2052,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str): """ 写入行级履约决定。 - Body: line_key, decision_code, reason?, release_field_values?, expected_draft_version? + Body: draft_line_id, decision_code, reason?, release_field_values?, expected_draft_version? """ user = _require_user() data = request.get_json(silent=True) or {} @@ -2134,7 +2064,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str): result = decide_review_line_fulfillment( user_id=user.id, case_no=case_no, - line_key=str(data.get('line_key') or ''), + draft_line_id=str(data.get('draft_line_id') or ''), decision_code=str(data.get('decision_code') or ''), reason=str(data.get('reason') or '').strip() or None, release_field_values=( @@ -2156,7 +2086,7 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str): """ 为选中完整明细行创建履约波次。 - Body: line_keys[], expected_draft_version, idempotency_key, reason? + Body: snapshot_line_ids[], expected_draft_version, idempotency_key, reason? 只允许正式 OT 走 create_post_ot_fulfillment_wave + schedule_post_ot_wave_progress。无正式 OT 的历史波次路径已下线,调用方必须 先完成正式建单,避免同一业务动作存在两套推进事实。 @@ -2171,14 +2101,14 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str): case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or '')) formal = resolve_formal_ot(case) if case is not None else {'has_formal_ot': False} - line_keys = list(data.get('line_keys') or []) + snapshot_line_ids = list(data.get('snapshot_line_ids') or []) idem = data.get('idempotency_key') or request.headers.get('Idempotency-Key') reason = str(data.get('reason') or '').strip() or None if formal.get('has_formal_ot'): result = create_post_ot_fulfillment_wave( case_no=str(case_no), - line_keys=line_keys, + snapshot_line_ids=snapshot_line_ids, decision_source='user', actor_user_id=int(user.id), reason=reason, @@ -2190,7 +2120,7 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str): progress = schedule_post_ot_wave_progress( task_no=str(result.get('task_no') or ''), wave_no=result.get('wave_no'), - line_keys=list(result.get('accepted_line_keys') or line_keys), + snapshot_line_ids=list(result.get('accepted_snapshot_line_ids') or snapshot_line_ids), review_case_id=int(result.get('review_case_id') or (case.id if case is not None else 0) or 0) or None, idempotency_row_id=result.get('idempotency_row_id'), request_idempotency_key=str(result.get('idempotency_key') or idem or '') or None, @@ -2223,7 +2153,7 @@ def workspace_close_shipping_order_review_fulfillment(case_no: str): """ 关闭行级或 Case 剩余开放行。 - Body: reason, line_keys?, expected_draft_version? + Body: reason, draft_line_ids?, expected_draft_version? """ user = _require_user() data = request.get_json(silent=True) or {} @@ -2236,7 +2166,7 @@ def workspace_close_shipping_order_review_fulfillment(case_no: str): user_id=user.id, case_no=case_no, reason=str(data.get('reason') or ''), - line_keys=list(data.get('line_keys') or []) or None, + draft_line_ids=list(data.get('draft_line_ids') or []) or None, expected_draft_version=data.get('expected_draft_version'), actor_is_admin=is_admin, ) @@ -2349,9 +2279,7 @@ def workspace_confirm_shipping_order_review_case(case_no: str): user = _require_user() from app.services.shipping_notice.order_review_confirmation_service import ( confirm_review_case, - finalize_sync_auto_progress_after_commit, resolve_confirm_outcome, - schedule_auto_progress_after_review_confirm, ) payload = _review_draft_payload( @@ -2366,14 +2294,22 @@ def workspace_confirm_shipping_order_review_case(case_no: str): warning_acknowledgements=payload.get('warning_acknowledgements'), ) # [STEP] 与建单同事务写入 shipping_notice_run,避免「已建单、推进失败不可恢复」。 + # 复核确认只产生 OT;正式 ShippingNotice 尚未生成,不能把 OT 编号投递到 + # 旧的 notice-run Job。库存源候选的裁决/冻结确认后由正式 inventory_source_routing + # Gate 负责;通过 schedule_auto_progress_after_review_confirm 入队自动推进, + # 使 OT 在不冻结候选的情况下仍能走到库存链路。 + from app.services.shipping_notice.order_review_confirmation_service import ( + finalize_sync_auto_progress_after_commit, + schedule_auto_progress_after_review_confirm, + ) progress = schedule_auto_progress_after_review_confirm( - task_no=result.get('task_no'), + task_no=str(result.get('task_no')), idempotent_replay=bool(result.get('idempotent_replay')), created_by_id=int(user.id), commit=False, ) # [STEP] BE-4:正式 OT 创建后补触发自动履约(flag 关时 enqueue 内部 no-op) - if result.get('task_no') and not result.get('idempotent_replay'): + if result.get('shipping_notice_no') and not result.get('idempotent_replay'): from app.services.shipping_notice.line_auto_fulfill_coordinator import ( enqueue_post_ot_auto_fulfill_job, ) @@ -2383,8 +2319,8 @@ def workspace_confirm_shipping_order_review_case(case_no: str): commit=False, ) db.session.commit() - # [STEP] sync 执行失败不得变成 HTTP 500,须返回「确认成功 + 推进态」字段。 progress = finalize_sync_auto_progress_after_commit(progress) + # [STEP] sync 执行失败不得变成 HTTP 500,须返回「确认成功 + 推进态」字段。 result = dict(result) result.pop('trigger_auto_progress', None) result['confirm_ok'] = True @@ -2632,7 +2568,7 @@ def workspace_request_shipping_order_review_llm_suggestion(case_no: str): user_id=user.id, case_no=case_no, field_id=str(payload.get('field_id') or ''), - line_key=payload.get('line_key'), + draft_line_id=payload.get('draft_line_id'), evidence_level=payload.get('evidence_level'), issue_code=payload.get('issue_code'), allow_full_pdf=bool(payload.get('allow_full_pdf')), diff --git a/backend/app/jobs/handlers/shipping_notice_parse.py b/backend/app/jobs/handlers/shipping_notice_parse.py index 14be740a..a0c3c123 100644 --- a/backend/app/jobs/handlers/shipping_notice_parse.py +++ b/backend/app/jobs/handlers/shipping_notice_parse.py @@ -16,9 +16,9 @@ from datetime import datetime from sqlalchemy import and_, or_, update from app import db -from app.core.errors import AppError, NotFoundError +from app.core.errors import NotFoundError from app.jobs.context import JobContext -from app.jobs.queue import fail_job, finish_job +from app.jobs.queue import _is_retryable_exc, fail_job, finish_job from app.jobs.registry import register_handler from app.jobs.types import JobType from app.models import FileAsset, Job, ShippingOrderIntake @@ -120,15 +120,6 @@ def _claim_intake_for_parsing( return intake, lease -def _is_retryable_exc(exc: BaseException) -> bool: - """业务 NotFound / AppError.retryable=False 视为不可再排队。""" - if isinstance(exc, NotFoundError): - return False - if isinstance(exc, AppError): - return bool(getattr(exc, 'retryable', False)) - return True - - @register_handler(JobType.SHIPPING_NOTICE_PARSE) def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None: """ @@ -264,7 +255,9 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None: # 租约已失效:旧 Worker 不得触碰 Job(条件 UPDATE 亦会 no-op,此处直接返回) if str(fail_result.get('reason') or '') == 'stale_parse_lease': return - retryable = False + # 失败收口按异常类型分级:业务失败(NotFound/AppError.retryable=False)停排, + # 瞬时基础设施异常才允许重试;不按业务域一刀切。 + retryable = _is_retryable_exc(exc) if job_id is not None: fail_job( job_id, @@ -272,3 +265,7 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None: retryable=retryable, owned_attempt=owned_attempt, ) + # 重试类异常交由外层运行时统一收口(fail_job 已 requeue);非重试业务失败已直接 + # fail_job 为 failed,不再重抛,避免向上滚动。 + if retryable: + raise diff --git a/backend/app/jobs/handlers/shipping_stp_auto_create.py b/backend/app/jobs/handlers/shipping_stp_auto_create.py index 4478675b..7810d6b9 100644 --- a/backend/app/jobs/handlers/shipping_stp_auto_create.py +++ b/backend/app/jobs/handlers/shipping_stp_auto_create.py @@ -10,7 +10,8 @@ backend/app/jobs/handlers/shipping_stp_auto_create.py 逻辑:由 shipping worker 领取;幂等键保证同一 Case/draft 不重复建单; 成功 finish,附加 task_no / idempotent_replay; 失败统一走 _classify_stp_result: - - 所有失败 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计) + - 业务阻断 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计) + - 临时基础设施异常 → retryable=true(保留普通重试入口) """ from __future__ import annotations @@ -51,11 +52,10 @@ def _classify_stp_job_result( 【AI 触发时机】:Handler 的三条 fail 路径(业务拒绝 ok=False、AppError 兜底、 非预期 Exception 兜底)统一调用,确保 Job.result_json schema 一致。 - 核心逻辑(fail-closed): - [STEP 1] build_stp_job_blocked_manual_result: - derive_blocking_next_actions 取第一个动作作 next_action,默认 open_order_review; - details 合并至 blocking_reason_details。 - [STEP 2] 返回三元组(False, normalized_result_dict, next_action)。 + 核心逻辑: + [STEP 1] temporary_storage_error 走技术失败契约,允许普通重试; + [STEP 2] 其他错误走 build_stp_job_blocked_manual_result,要求人工裁决; + [STEP 3] 返回三元组(retryable, normalized_result_dict, next_action)。 Args: error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。 @@ -71,6 +71,23 @@ def _classify_stp_job_result( # 当前执行已停止并应在当前 Gate 选择动作,原文仅保留在 Worker 日志。 if str(error_code or '').strip() == 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED': message = '自动建单失败,已停止,等待用户选择下一步动作' + if category_hint == 'temporary_storage_error': + next_action = 'retry_stp_auto_create' + return True, { + 'status': 'failed', + 'retryable': True, + 'error_code': str(error_code or '').strip(), + 'message': str(message or ''), + 'next_action': next_action, + 'contract_version': 'shipping-recovery-v1-phase1', + 'decision_trace': { + 'contract_version': 'shipping-recovery-v1-phase1', + 'stage': 'stp_classify_error', + 'retryable': True, + 'matched_rule': 'temporary_storage_error', + 'category_hint': category_hint, + }, + }, next_action actions = derive_blocking_next_actions(blocking_reason=error_code) next_action = actions[0] if actions else 'open_order_review' blocked: dict[str, Any] = build_stp_job_blocked_manual_result( diff --git a/backend/app/models/shipping_order_review.py b/backend/app/models/shipping_order_review.py index 5988708e..bddced4d 100644 --- a/backend/app/models/shipping_order_review.py +++ b/backend/app/models/shipping_order_review.py @@ -7,7 +7,7 @@ 逻辑:ReviewStream 是文件级复核主线,Case 是该主线的一次不可变复核版本; Draft 保存独立人工版本,机器 Candidate 始终只读,后续确认服务将以 Case/Draft 生成不可变确认版本和 Task; 行级决定支持完整明细先行履约波次,禁止拆分数量; - wave_lines 保证同一 (case, line_key) 最多关联一个 task_id。 + wave_lines 保证同一 (case, snapshot_line_id) 最多关联一个 task_id。 """ from __future__ import annotations @@ -109,7 +109,7 @@ class ShippingOrderReviewCase(Base): ForeignKey('shipping_order_review_drafts.id', use_alter=True, name='fk_shipping_order_review_cases_current_draft'), nullable=True, ) - confirmed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True) + confirmed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True) confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) @@ -140,13 +140,13 @@ class ShippingOrderReviewCase(Base): 'ShippingOrderReviewLineDecision', back_populates='case', cascade='all, delete-orphan', - order_by='ShippingOrderReviewLineDecision.line_key, ShippingOrderReviewLineDecision.decision_version', + order_by='ShippingOrderReviewLineDecision.draft_line_id, ShippingOrderReviewLineDecision.decision_version', ) wave_lines: Mapped[list['ShippingOrderReviewWaveLine']] = relationship( 'ShippingOrderReviewWaveLine', back_populates='case', cascade='all, delete-orphan', - order_by='ShippingOrderReviewWaveLine.wave_no, ShippingOrderReviewWaveLine.line_key', + order_by='ShippingOrderReviewWaveLine.wave_no, ShippingOrderReviewWaveLine.snapshot_line_id', ) @@ -212,7 +212,7 @@ class ShippingOrderReviewConfirmedRevision(Base): case_id: Mapped[int] = mapped_column( ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False, ) - task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False) + task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False) draft_version: Mapped[int] = mapped_column(Integer, nullable=False) schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False) header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) diff --git a/backend/app/models/shipping_order_review_line_decision.py b/backend/app/models/shipping_order_review_line_decision.py index ba178659..fb83a1e2 100644 --- a/backend/app/models/shipping_order_review_line_decision.py +++ b/backend/app/models/shipping_order_review_line_decision.py @@ -2,8 +2,8 @@ models/shipping_order_review_line_decision.py 用途:复核 Case 的行级履约决定(版本化、可追溯);含 OT 后系统/人工来源。 -依赖:ShippingOrderReviewCase、ShippingNotice、users。 -逻辑:由 order_review_fulfillment_decision_service 写入;同一 (case, line_key, version) 唯一; +依赖:ShippingOrderReviewCase、ShippingOrderTask、users。 +逻辑:由 order_review_fulfillment_decision_service 写入;同一 (case, draft_line_id, version) 唯一; 活动决定不可覆盖,重开生成新版本;Task 波次通过 task_id 关联; decision_source 区分 system/user(历史可空)。 """ @@ -26,7 +26,7 @@ class ShippingOrderReviewLineDecision(Base): __table_args__ = ( UniqueConstraint( 'review_case_id', - 'line_key', + 'draft_line_id', 'decision_version', name='uq_shipping_review_line_decisions_case_line_ver', ), @@ -49,7 +49,7 @@ class ShippingOrderReviewLineDecision(Base): name='ck_shipping_review_line_decisions_source', ), CheckConstraint('decision_version >= 1', name='ck_shipping_review_line_decisions_version'), - Index('ix_shipping_review_line_decisions_case_line', 'review_case_id', 'line_key'), + Index('ix_shipping_review_line_decisions_case_line', 'review_case_id', 'draft_line_id'), Index('ix_shipping_review_line_decisions_case_active', 'review_case_id', 'is_active'), Index('ix_shipping_review_line_decisions_task', 'task_id'), ) @@ -59,7 +59,7 @@ class ShippingOrderReviewLineDecision(Base): ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False, ) - line_key: Mapped[str] = mapped_column(String(64), nullable=False) + draft_line_id: Mapped[str] = mapped_column(String(64), nullable=False) line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) decision_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') decision_code: Mapped[str] = mapped_column(String(48), nullable=False) @@ -70,7 +70,7 @@ class ShippingOrderReviewLineDecision(Base): available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) - task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True) + task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True) wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) # system=自动履约;user=人工异常/显式履约;unknown=历史无法判定。 decision_source: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) diff --git a/backend/app/models/shipping_order_review_suggestion.py b/backend/app/models/shipping_order_review_suggestion.py index ecdf0fda..20f33ec0 100644 --- a/backend/app/models/shipping_order_review_suggestion.py +++ b/backend/app/models/shipping_order_review_suggestion.py @@ -69,7 +69,7 @@ class ShippingOrderReviewSuggestion(Base): ForeignKey('shipping_order_processing_runs.id'), nullable=True, ) field_id: Mapped[str] = mapped_column(String(64), nullable=False) - line_key: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + draft_line_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) scope: Mapped[str] = mapped_column(String(16), nullable=False, default='header', server_default='header') evidence_level: Mapped[str] = mapped_column(String(16), nullable=False, default='L1_field') status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending') diff --git a/backend/app/models/shipping_order_review_wave_idempotency.py b/backend/app/models/shipping_order_review_wave_idempotency.py index 9ba9ccf3..a565ed5e 100644 --- a/backend/app/models/shipping_order_review_wave_idempotency.py +++ b/backend/app/models/shipping_order_review_wave_idempotency.py @@ -2,7 +2,7 @@ models/shipping_order_review_wave_idempotency.py 用途:post-OT 履约 wave 请求幂等表(idempotency_key → wave 身份),无 wave 主表时提供强约束。 -依赖:shipping_order_review_cases、shipping_notices。 +依赖:shipping_order_review_cases、shipping_order_tasks。 逻辑:create_post_ot_fulfillment_wave 写入/回放;同 key 参数不一致 → 409; progress_* 记录本 wave Excel/RPA 推进状态(失败不回滚已提交 wave)。 """ @@ -39,15 +39,15 @@ class ShippingOrderReviewWaveIdempotency(Base): nullable=False, ) task_id: Mapped[int] = mapped_column( - ForeignKey('shipping_notices.id', ondelete='CASCADE'), + ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), nullable=False, ) task_no: Mapped[str] = mapped_column(String(64), nullable=False) wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) decision_source: Mapped[str] = mapped_column(String(16), nullable=False) - # 稳定排序后的 line_key JSON 数组字符串指纹(冲突比对)。 - line_keys_json: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list) - line_keys_hash: Mapped[str] = mapped_column(String(64), nullable=False) + # 稳定排序后的冻结订单行 ID 数组指纹(冲突比对)。 + snapshot_line_ids_json: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list) + snapshot_line_ids_hash: Mapped[str] = mapped_column(String(64), nullable=False) # 行集合共享快照 ID;多快照时为空,靠 fingerprint 比对。 inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) inventory_snapshot_fingerprint: Mapped[str] = mapped_column(String(256), nullable=False, default='') diff --git a/backend/app/models/shipping_order_review_wave_line.py b/backend/app/models/shipping_order_review_wave_line.py index 19b4427d..01e910e0 100644 --- a/backend/app/models/shipping_order_review_wave_line.py +++ b/backend/app/models/shipping_order_review_wave_line.py @@ -2,9 +2,9 @@ models/shipping_order_review_wave_line.py 用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一张 Notice。 -依赖:ShippingOrderReviewCase、ShippingNotice、ShippingOrderReviewConfirmedRevision。 +依赖:ShippingOrderReviewCase、ShippingOrderTask、ShippingOrderReviewConfirmedRevision。 逻辑:由 order_review_confirmation_service 在建波次/整单确认时写入; - (review_case_id, line_key) 数据库唯一约束防并发重复入波次。 + (review_case_id, snapshot_line_id) 数据库唯一约束防并发重复入波次。 """ from __future__ import annotations @@ -25,7 +25,7 @@ class ShippingOrderReviewWaveLine(Base): __table_args__ = ( UniqueConstraint( 'review_case_id', - 'line_key', + 'snapshot_line_id', name='uq_shipping_review_wave_lines_case_line', ), Index('ix_shipping_review_wave_lines_task', 'task_id'), @@ -37,8 +37,11 @@ class ShippingOrderReviewWaveLine(Base): ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False, ) - line_key: Mapped[str] = mapped_column(String(64), nullable=False) - task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False) + snapshot_line_id: Mapped[int] = mapped_column( + ForeignKey('shipping_order_snapshot_lines.id', ondelete='CASCADE'), + nullable=False, + ) + task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False) wave_no: Mapped[int] = mapped_column(Integer, nullable=False) confirmed_revision_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_order_review_confirmed_revisions.id', ondelete='SET NULL'), diff --git a/backend/app/models/shipping_order_schema.py b/backend/app/models/shipping_order_schema.py index 4fc93c88..1adc6303 100644 --- a/backend/app/models/shipping_order_schema.py +++ b/backend/app/models/shipping_order_schema.py @@ -4,7 +4,7 @@ backend/app/models/shipping_order_schema.py 用途:定义货代字段资产、Schema 族/不可变版本、配置审计及动态订单解析结果。 依赖:models.base.Base、shipping_notices、shipping_order_intakes、users。 逻辑:字段资产全局存活(标准只读、扩展可弃用);Schema 族版本仅采用资产并冻结 definition_json; - definition_json 含 fields / auto_creation_policy / derivation_rules(及 checksum); + definition_json 含 fields / auto_creation_policy; 写操作追加审计;解析链锁定发布版本。表名保留历史命名以降低迁移耦合。 """ @@ -138,8 +138,7 @@ class ShippingOrderSchemaVersion(Base): definition_json 契约要点: - fields[]:字段采用与识别规则 - auto_creation_policy:自动建单策略 - - derivation_rules[]:同行明细字段派生(首期 copy_if_empty → line_no) - - derivation_rules_checksum:派生规则稳定校验和 + - line_no:运行时按 Extraction 内明细顺序生成,不属于 Schema 配置或派生规则。 """ __tablename__ = 'shipping_order_schema_versions' @@ -232,7 +231,7 @@ class ShippingOrderExtraction(Base): run_id: Mapped[Optional[int]] = mapped_column( ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True, ) - task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True) + task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True) intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=True) schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False) input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False) @@ -264,12 +263,16 @@ class ShippingOrderLine(Base): """动态订单解析中的行身份;业务值全部位于 FieldValue。""" __tablename__ = 'shipping_order_lines' - __table_args__ = (UniqueConstraint('extraction_id', 'position', name='uq_shipping_order_lines_position'),) + __table_args__ = ( + UniqueConstraint('extraction_id', 'position', name='uq_shipping_order_lines_position'), + UniqueConstraint('extraction_id', 'line_no', name='uq_shipping_order_lines_line_no'), + ) id: Mapped[int] = mapped_column(primary_key=True) extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False) position: Mapped[int] = mapped_column(Integer, nullable=False) - line_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + line_no: Mapped[int] = mapped_column(Integer, nullable=False) + draft_line_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='lines') diff --git a/backend/app/services/shipping_notice/candidate_qualification_service.py b/backend/app/services/shipping_notice/candidate_qualification_service.py index aa8b8e0b..47adf96e 100644 --- a/backend/app/services/shipping_notice/candidate_qualification_service.py +++ b/backend/app/services/shipping_notice/candidate_qualification_service.py @@ -27,7 +27,6 @@ from app.models import ( ShippingOrderCandidate, ShippingOrderCandidateQualification, ShippingOrderExtraction, - ShippingOrderCustomerMatch, ) from app.services.shipping_notice.candidate_qualification_contract import ( CANDIDATE_QUALIFICATION_EVALUATOR_VERSION, @@ -71,7 +70,6 @@ _CONFIDENCE_SOURCE_DEFAULT_FALLBACK = 'default_fallback_0_85' # 文档表格坐标不足只影响证据高亮质量,不代表订单字段值存在冲突。 # 保留在抽取诊断中供排查,但不得阻断人工建单或自动建单。 _NON_BLOCKING_CONFLICT_REASONS = frozenset({'layout_table_needs_review'}) -_OPTIONAL_INTERNAL_FIELD_CODES = frozenset({'line_no'}) _EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'}) @@ -79,9 +77,8 @@ def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) -> """按冻结字段配置判断证据缺失是否只是可选字段诊断。 核心逻辑:优先读取 Candidate 关联 Extraction 的冻结 Schema;只有 - ``required`` 或 ``auto_create_key_field`` 才能阻断。历史 Candidate 无法 - 追溯 Schema 时,仅兼容已明确属于内部可派生字段的 ``line_no``,其余未知 - 字段继续 fail-closed。 + ``required`` 或 ``auto_create_key_field`` 才能阻断。无法追溯 Schema + 时继续 fail-closed;系统项次由写路径生成,不构成证据缺失例外。 """ reason = str(item.get('reason') or item.get('code') or '').strip() if reason not in _EVIDENCE_GAP_REASONS: @@ -111,7 +108,7 @@ def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) -> config = None if config is not None: return not bool(config.get('required')) and not bool(config.get('auto_create_key_field')) - return field_code in _OPTIONAL_INTERNAL_FIELD_CODES + return False def blocking_candidate_conflicts(candidate: Any) -> list[Any]: @@ -173,8 +170,7 @@ def resolve_candidate_customer_resolved( """ 判定 Candidate/Extraction 的 Bill-to 客户是否已确认。 - 核心逻辑:优先读 ShippingOrderCustomerMatch(bill_to)=confirmed; - 其次读 Candidate.structured_result_json.customer.resolution_status。 + 核心逻辑:只读 Candidate 的正式客户识别结果;不读取 bill_to 或解析摘要兜底。 Args: candidate: 可选 Candidate。 @@ -183,56 +179,35 @@ def resolve_candidate_customer_resolved( Returns: True 表示客户已确认,可用于建单资格评估。 """ - ext_id = extraction_id - if ext_id is None and candidate is not None: - raw = getattr(candidate, 'order_extraction_id', None) - if raw is not None: - try: - ext_id = int(raw) - except (TypeError, ValueError): - ext_id = None - if ext_id is not None: - row = ShippingOrderCustomerMatch.query.filter_by( - extraction_id=int(ext_id), - role='bill_to', - status='confirmed', - ).first() - if row is not None and row.customer_id is not None: - return True + from app.services.shipping_notice.customer_resolution_service import resolution_for_extraction, resolution_for_task - if candidate is None: - return False - ok, _reason = _customer_ok(candidate, customer_resolved=None) - return bool(ok) + resolution = resolution_for_task(candidate) if candidate is not None else resolution_for_extraction(extraction_id) + if resolution is not None: + return bool(resolution.status == 'confirmed' and resolution.confirmed_customer_id is not None) + # review_case 人工确认新建的 Candidate 只在 structured_result_json['customer'] 写入确认事实 + # (review_case 权威确认,见 order_review_confirmation_service._create_review_candidate),并不落 resolution 表; + # 在建单资格判断时兜底认可,避免"已确认客户却无法建单"。 + structured = getattr(candidate, 'structured_result_json', None) if candidate is not None else None + if isinstance(structured, dict): + customer = structured.get('customer') if isinstance(structured.get('customer'), dict) else {} + return str(customer.get('resolution_status') or '').strip().lower() == 'confirmed' + return False -def resolve_confirmed_bill_to_customer_id( +def resolve_confirmed_customer_id( *, candidate: Any | None = None, extraction_id: int | None = None, ) -> int | None: """ - 返回已确认 Bill-to 标准客户主键;未确认时为 None。 - - 核心逻辑:与 resolve_candidate_customer_resolved 同源,额外取出 customer_id 供建单绑定。 + 返回正式识别结果中已确认的标准客户主键;未确认时为 None。 """ - ext_id = extraction_id - if ext_id is None and candidate is not None: - raw = getattr(candidate, 'order_extraction_id', None) - if raw is not None: - try: - ext_id = int(raw) - except (TypeError, ValueError): - ext_id = None - if ext_id is not None: - row = ShippingOrderCustomerMatch.query.filter_by( - extraction_id=int(ext_id), - role='bill_to', - status='confirmed', - ).first() - if row is not None and row.customer_id is not None: - return int(row.customer_id) - return None + from app.services.shipping_notice.customer_resolution_service import resolution_for_extraction, resolution_for_task + + resolution = resolution_for_task(candidate) if candidate is not None else resolution_for_extraction(extraction_id) + return int(resolution.confirmed_customer_id) if ( + resolution is not None and resolution.status == 'confirmed' and resolution.confirmed_customer_id is not None + ) else None def assert_customer_confirmed_before_task_create( diff --git a/backend/app/services/shipping_notice/chat_tool_capability.py b/backend/app/services/shipping_notice/chat_tool_capability.py index 7174b069..a1913a62 100644 --- a/backend/app/services/shipping_notice/chat_tool_capability.py +++ b/backend/app/services/shipping_notice/chat_tool_capability.py @@ -13,7 +13,7 @@ from typing import Any from flask import current_app from app.core.errors import ForbiddenError -from app.models import ChatSession, ShippingNotice +from app.models import ChatSession, ShippingOrderTask READ_SCOPES = frozenset({'get_shipping_status'}) @@ -50,7 +50,7 @@ def require_chat_capability(*, token: Any, scope: str, task_no: str | None = Non if session is None: raise ForbiddenError('Chat capability session is invalid', code='SHIPPING.CHAT_CAPABILITY_DENIED') if task_no: - task = ShippingNotice.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none() + task = ShippingOrderTask.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none() if task is None or str(body.get('task') or '').upper() != task.task_no: raise ForbiddenError('Task is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED') return body diff --git a/backend/app/services/shipping_notice/customer_auto_resolution.py b/backend/app/services/shipping_notice/customer_auto_resolution.py index b3fdbf7e..3232cb29 100644 --- a/backend/app/services/shipping_notice/customer_auto_resolution.py +++ b/backend/app/services/shipping_notice/customer_auto_resolution.py @@ -1,19 +1,16 @@ """ services/shipping_notice/customer_auto_resolution.py -用途:基于管理员审核的强证据受控自动确认客户,并支持历史回填与编号后客户纠错。 -依赖:ShippingIdentityEvidence/ShadowResolution/Task、customer_identity_gate、business_numbering_service、Flask 配置。 -逻辑:Candidate 建单后只按影子快照中的已审核授权证据自动确认;管理员纠错时保留原号作废并创建替代业务单。 +用途:基于管理员审核的强证据受控自动确认 OT 客户。 +依赖:ShippingIdentityEvidence/ShadowResolution/Task、customer_identity_gate、Flask 配置。 +逻辑:Candidate 建单后只按影子快照中的已审核授权证据自动确认;不创建 Notice 或分配业务编号。 """ from __future__ import annotations -import hashlib -from datetime import datetime from typing import Any from app import db -from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingCustomer, ShippingCustomerShadowResolution, @@ -24,24 +21,25 @@ from app.models import ( ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderSchemaVersion, - ShippingNotice, + ShippingOrderTask, ShippingTaskEvent, ) -from app.services.shipping_notice.customer_identity_gate import confirm_task_customer +from app.services.shipping_notice.customer_identity_gate import ( + confirm_task_customer, + customer_confirmation_facts, +) from app.services.shipping_notice.customer_normalization import ( is_public_email_domain, normalize_customer_name, normalize_domain, normalize_email, ) -from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, generate_task_no -from app.services.shipping_notice.business_numbering_service import assign_notice_business_number +from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, task_event_task_id AUTO_RESOLUTION_VERSION = "customer-auto-v2" CUSTOMER_AUDIT_EVENT_TYPES = ( "customer_auto_resolution_evaluated", "customer_auto_confirmed", - "customer_correction_applied", ) @@ -92,6 +90,52 @@ def _auto_confirmation_quality_gate() -> dict[str, Any]: } +def _ruleset_definitions_semantically_compatible( + snapshot: dict[str, Any], schema_version: ShippingOrderSchemaVersion, +) -> bool: + """ + 校验规则集冻结定义在解析所用 Schema 版本中语义契约仍成立(允许 Schema 常规重发布造成的版本错位)。 + + 语义键集合:field_code / scope('header') / value_type / normalizer_key / available_for_customer_identity。 + 允许 display_name、aliases、extraction_instruction、evidence_policy 等非语义字段变化; + 任一语义键不一致或字段被停用则 fail-closed,防止按过期配置标准化产生误绑客户。 + + Args: + snapshot: 影子 rule_set 快照(含 definitions)。 + schema_version: 解析实际使用的 Schema 版本。 + + Returns: + True 表示所有带 field_code 的定义在新 Schema 中语义兼容。 + """ + fields = ((schema_version.definition_json or {}).get('fields') or []) if schema_version else [] + fields_by_code = { + str(item.get('field_code') or ''): item + for item in fields if isinstance(item, dict) and str(item.get('field_code') or '') + } + definitions = snapshot.get('definitions') if isinstance(snapshot, dict) else [] + for raw in definitions if isinstance(definitions, list) else []: + if not isinstance(raw, dict): + continue + config = raw.get('field_config') if isinstance(raw.get('field_config'), dict) else {} + field_code = str(config.get('field_code') or '').strip() + if not field_code: + # 旧快照未保存 field_code:无法做语义校验,交由 UUID 直配路径(继续,不判定失败)。 + continue + actual = fields_by_code.get(field_code) + if actual is None or not actual.get('enabled', True): + return False + if str(actual.get('scope') or '') != 'header' or str(config.get('scope') or '') != 'header': + return False + if str(actual.get('value_type') or '') != str(config.get('value_type') or ''): + return False + if not actual.get('available_for_customer_identity'): + return False + frozen_normalizer = str(config.get('normalizer_key') or '').strip() + if frozen_normalizer and frozen_normalizer != str(actual.get('normalizer_key') or '').strip(): + return False + return True + + def _rule_snapshot(shadow: ShippingCustomerShadowResolution) -> dict[str, Any] | None: """校验规则集及其订单 Schema/Extraction 锚点;任一链路缺失都安全降级。""" context = shadow.resolution_context_json if isinstance(shadow.resolution_context_json, dict) else {} @@ -118,16 +162,12 @@ def _rule_snapshot(shadow: ShippingCustomerShadowResolution) -> dict[str, Any] | or snapshot.get('order_schema') != frozen_definition.get('order_schema') ): return None - schema = snapshot.get('order_schema') if isinstance(snapshot.get('order_schema'), dict) else None - if not schema or schema.get('id') != shadow.order_schema_version_id: - return None + # Schema 锚点放宽:规则集冻结的版本 id 可与解析实际使用的版本错位(Schema 常规重发布), + # 但解析所用 Schema 版本必须真实存在(published/retired),且规则集定义在新 Schema 中语义兼容。 schema_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id) - if ( - schema_version is None - or schema_version.status not in {'published', 'retired'} - or schema_version.version != schema.get('version') - or schema_version.checksum != schema.get('checksum') - ): + if schema_version is None or schema_version.status not in {'published', 'retired'}: + return None + if not _ruleset_definitions_semantically_compatible(snapshot, schema_version): return None extraction_id = context.get('order_extraction_id') extraction = db.session.get(ShippingOrderExtraction, int(extraction_id)) if str(extraction_id or '').isdigit() else None @@ -286,7 +326,7 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow return result -def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]: +def resolve_auto_customer_from_shadow(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]: """ 使用任务来源 Candidate 的影子证据执行受控自动裁决。 @@ -307,13 +347,14 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]: 'is_eligible': False, }, } - if task.source_candidate_id is None: + candidate_id = getattr(task, 'candidate_id', None) + if candidate_id is None: return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []} shadow = db.session.query(ShippingCustomerShadowResolution).filter_by( - candidate_id=int(task.source_candidate_id), + candidate_id=int(candidate_id), ).first() if shadow is None: - candidate = db.session.get(ShippingOrderCandidate, int(task.source_candidate_id)) + candidate = db.session.get(ShippingOrderCandidate, int(candidate_id)) if candidate is not None: from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution @@ -333,20 +374,23 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]: return {**decision, 'quality_gate': quality_gate} -def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]: +def try_auto_confirm_task_customer(task: ShippingOrderTask) -> dict[str, Any]: """ - 尝试自动确认并生成业务编号;未达门槛时保持 customer_review。 + 尝试自动确认 OT 客户;未达门槛时保持 customer_review。 - 核心逻辑:先写自动裁决审计,再复用人工确认的锁与编号事务;成功后将确认方法改为 auto_rule。 + 核心逻辑:先写自动裁决审计,再复用人工确认事务;成功后将确认方法改为 auto_rule。 """ - if task.customer_resolution_status == "confirmed": - return {"status": "already_confirmed", "customer_id": task.customer_id} + facts = customer_confirmation_facts(task) + if facts['status'] == 'confirmed': + return {"status": "already_confirmed", "customer_id": facts['customer_id']} decision = resolve_auto_customer_from_shadow(task) - db.session.add(ShippingTaskEvent( - task_id=task.id, - event_type="customer_auto_resolution_evaluated", - detail_json=decision, - )) + event_task_id = task_event_task_id(task) + if event_task_id is not None: + db.session.add(ShippingTaskEvent( + task_id=event_task_id, + event_type="customer_auto_resolution_evaluated", + detail_json=decision, + )) if decision.get("customer_id") is None: db.session.flush() return decision @@ -358,165 +402,32 @@ def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]: resolution_method="auto_rule", commit=False, ) - db.session.add(ShippingTaskEvent( - task_id=updated.id, - event_type="customer_auto_confirmed", - detail_json={ - **decision, - "business_no": updated.business_no, - }, - )) + updated_event_task_id = task_event_task_id(updated) + if updated_event_task_id is not None: + db.session.add(ShippingTaskEvent( + task_id=updated_event_task_id, + event_type="customer_auto_confirmed", + detail_json={ + **decision, + "business_no": getattr(updated, 'business_no', None), + }, + )) db.session.flush() - return {**decision, "status": "auto_confirmed", "business_no": updated.business_no} - - -def correct_numbered_task_customer( - task: ShippingNotice, - *, - customer_id: int, - reason: str, - actor_id: int | None, -) -> dict[str, Any]: - """ - 更正已编号 Notice 的标准客户,同时保留原号作废与替代关系。 - - 核心逻辑:锁定原 Notice 并校验未上传 → 创建替代 Notice 和新号 → 作废原 Notice → - 清理新 Notice 的客户相关下游派生结果 → 写入新旧编号纠错审计;原业务号永不修改。 - - Args: - task: 原业务号或技术号定位到的当前任务版本。 - customer_id: 管理员确认的正确启用客户 ID。 - reason: 必填纠错原因,写入审计事件。 - actor_id: 管理员审计 ID。 - Returns: - 原号、新号、替代业务单和受影响任务信息。 - Raises: - ValidationError: 缺少原因、客户无效或客户未变化。 - ConflictError: 业务单未编号、已上传或已被替代。 - """ - correction_reason = str(reason or "").strip() - if not correction_reason: - raise ValidationError( - "Customer correction reason is required", - code="SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED", - ) - original = ( - db.session.query(ShippingNotice) - .filter(ShippingNotice.id == int(task.id)) - .with_for_update() - .one_or_none() - ) - if original is None or not original.business_no: - raise ConflictError( - "Numbered shipping notice is required for customer correction", - code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED", - ) - existing_replacement = db.session.query(ShippingNotice.id).filter_by( - supersedes_task_id=original.id, - ).first() - if existing_replacement is not None or str(original.lifecycle_status or '') == 'voided': - raise ConflictError( - "Shipping notice has already been replaced", - code="SHIPPING.CUSTOMER_CORRECTION_ALREADY_REPLACED", - ) - - customer = db.session.get(ShippingCustomer, int(customer_id)) - if customer is None: - raise NotFoundError("Customer not found", code="SHIPPING.CUSTOMER_NOT_FOUND") - if customer.status == "merged": - raise ConflictError("Merged customer cannot be used", code="SHIPPING.CUSTOMER_MERGED_LOCKED") - if customer.status != "active": - raise ValidationError("Inactive customer cannot be used", code="SHIPPING.CUSTOMER_INACTIVE") - if original.customer_id == customer.id: - raise ValidationError( - "Corrected customer must differ from the current customer", - code="SHIPPING.CUSTOMER_CORRECTION_UNCHANGED", - ) - - if str(getattr(original, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}: - raise ConflictError( - "Uploaded shipping notices require an external cancellation workflow before correction", - code="SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED", - ) - - old_business_no = str(original.business_no) - now = datetime.utcnow() - customer_fingerprint = hashlib.sha256(f"customer:{customer.id}".encode("ascii")).hexdigest() - replacement = ShippingNotice( - task_no=generate_task_no(), - user_id=original.user_id, - conversation_id=original.conversation_id, - source_type=original.source_type, - source_file_name=original.source_file_name, - source_file_type=original.source_file_type, - source_content_hash=original.source_content_hash, - source_asset_id=original.source_asset_id, - source_intake_id=original.source_intake_id, - source_candidate_id=original.source_candidate_id, - order_task_id=original.order_task_id, - business_fingerprint=original.business_fingerprint, - fingerprint_version=original.fingerprint_version, - content_fingerprint=original.content_fingerprint, - content_fingerprint_version=original.content_fingerprint_version, - document_version=int(original.document_version or 1) + 1, - supersedes_task_id=original.id, - raw_content=original.raw_content, - customer_id=customer.id, - customer_name_snapshot=customer.standard_name, - customer_short_code_snapshot=customer.short_code, - customer_resolution_status="confirmed", - customer_resolution_method="admin_correction", - customer_identity_fingerprint=customer_fingerprint, - customer_confirmed_by=actor_id, - customer_confirmed_at=now, - ) - db.session.add(replacement) - db.session.flush() - new_business_no = assign_notice_business_number(replacement) - original.lifecycle_status = 'voided' - original.voided_at = now - original.voided_by_id = actor_id - original.void_reason = f'customer_correction:{correction_reason}' - correction_detail = { - "old_notice_id": original.id, - "new_notice_id": replacement.id, - "old_business_no": old_business_no, - "new_business_no": new_business_no, - "old_customer_id": original.customer_id, - "new_customer_id": customer.id, - "reason": correction_reason, - "actor_id": actor_id, - } - db.session.add(ShippingTaskEvent(task_id=original.id, event_type="customer_correction_applied", detail_json=correction_detail)) - db.session.add(ShippingTaskEvent(task_id=replacement.id, event_type="customer_correction_applied", detail_json=correction_detail)) - - # 客户变化会使库存路由、匹配和导出失效;只重置当前版本,旧版本状态通过事件保留审计语义。 - db.session.commit() - return { - "task_no": replacement.task_no, - "old_notice_id": original.id, - "new_notice_id": replacement.id, - "old_business_no": old_business_no, - "new_business_no": new_business_no, - "customer_id": customer.id, - "affected_task_count": 1, - } + # OT 阶段只确认客户;业务编号属于正式 Notice 的 Excel 生成事务。 + return {**decision, "status": "auto_confirmed", "business_no": None} def get_auto_resolution_metrics() -> dict[str, Any]: - """汇总自动裁决和纠错事件,供管理员监控、查询与降级判断。""" + """汇总自动裁决事件,供管理员监控、查询与降级判断。""" evaluated = db.session.query(ShippingTaskEvent.task_id).filter_by( event_type="customer_auto_resolution_evaluated", ).distinct().count() confirmed = db.session.query(ShippingTaskEvent.task_id).filter_by( event_type="customer_auto_confirmed", ).distinct().count() - corrected = db.session.query(ShippingTaskEvent.task_id).filter_by( - event_type="customer_correction_applied", - ).distinct().count() recent_events = ( - db.session.query(ShippingTaskEvent, ShippingNotice.task_no) - .join(ShippingNotice, ShippingNotice.id == ShippingTaskEvent.task_id) + db.session.query(ShippingTaskEvent, ShippingOrderTask.task_no) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingTaskEvent.task_id) .filter(ShippingTaskEvent.event_type.in_(CUSTOMER_AUDIT_EVENT_TYPES)) .order_by(ShippingTaskEvent.id.desc()) .limit(100) @@ -528,7 +439,6 @@ def get_auto_resolution_metrics() -> dict[str, Any]: 'quality_gate': _auto_confirmation_quality_gate(), "evaluated_count": evaluated, "auto_confirmed_count": confirmed, - "corrected_task_count": corrected, "auto_confirmation_rate": (confirmed / evaluated) if evaluated else None, "recent_events": [ { diff --git a/backend/app/services/shipping_notice/customer_identity_gate.py b/backend/app/services/shipping_notice/customer_identity_gate.py index ea193393..23fd6d4a 100644 --- a/backend/app/services/shipping_notice/customer_identity_gate.py +++ b/backend/app/services/shipping_notice/customer_identity_gate.py @@ -8,7 +8,6 @@ backend/app/services/shipping_notice/customer_identity_gate.py from __future__ import annotations -import hashlib from datetime import datetime from typing import Any @@ -16,18 +15,44 @@ from sqlalchemy import or_ from app import db from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError -from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent +from app.models import ( + ShippingCustomer, + ShippingNotice, + ShippingOrderTask, +) from app.services.shipping_notice.customer_normalization import clean_text +from app.services.shipping_notice.customer_resolution_service import ( + confirm_customer_resolution, + customer_resolution_facts, +) CUSTOMER_GATE_ERROR_CODE = 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' -def customer_identity_is_confirmed(task: ShippingNotice) -> bool: - """判断 Notice 自身是否已通过标准客户确认。""" - if task.customer_id is None: +def customer_confirmation_facts(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]: + """读取唯一客户识别结果;bill_to 等订单字段仅可出现在识别证据中。""" + facts = customer_resolution_facts(task) + resolution = facts['resolution'] + customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) if facts['customer_id'] else None + return { + 'customer_id': facts['customer_id'], + 'status': facts['status'], + 'resolution_method': getattr(resolution, 'confirmation_method', None), + 'identity_fingerprint': getattr(resolution, 'identity_rule_set_checksum', None), + 'confirmed_by_id': getattr(resolution, 'confirmed_by_id', None), + 'confirmed_at': getattr(resolution, 'confirmed_at', None), + 'customer_name_snapshot': getattr(customer, 'standard_name', None), + 'customer_short_code_snapshot': getattr(customer, 'short_code', None), + } + + +def customer_identity_is_confirmed(task: ShippingNotice | ShippingOrderTask) -> bool: + """判断 OT 或正式 Notice 是否已通过标准客户确认。""" + facts = customer_confirmation_facts(task) + if facts['customer_id'] is None or facts['status'] != 'confirmed': return False - customer = db.session.get(ShippingCustomer, int(task.customer_id)) - return bool(customer and customer.status == 'active' and task.customer_resolution_status == 'confirmed') + customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) + return bool(customer and customer.status == 'active') def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'continue') -> None: @@ -42,6 +67,9 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con """ if customer_identity_is_confirmed(task): return + facts = customer_confirmation_facts(task) + customer_id = facts['customer_id'] + status = facts['status'] or 'pending' raise AppError( code=CUSTOMER_GATE_ERROR_CODE, message='标准客户尚未确认,无法继续后续流程', @@ -49,8 +77,8 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con details={ 'operation': operation, 'task_no': task.task_no, - 'customer_resolution_status': task.customer_resolution_status or 'pending', - 'customer_id': task.customer_id, + 'customer_resolution_status': status, + 'customer_id': customer_id, }, ) @@ -71,15 +99,15 @@ def list_customer_options(*, query: str = '', limit: int = 100) -> list[dict[str def confirm_task_customer( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, *, customer_id: int, actor_id: int | None, resolution_method: str = 'manual', commit: bool = True, -) -> ShippingNotice: +) -> ShippingNotice | ShippingOrderTask: """ - 人工确认 Notice 所属标准客户;业务编号留待首次 Excel 生成时分配。 + 人工确认 OT/Notice 所属标准客户;业务编号仅由正式 Notice 的 Excel 阶段分配。 核心逻辑:锁定客户归属 → 校验启用客户 → 固化 Notice 客户快照。 客户确认与客户快照同事务提交;业务编号由 Excel 生成事务独占写入。 @@ -91,12 +119,11 @@ def confirm_task_customer( resolution_method: manual/auto_rule 等审计方法。 commit: 是否提交事务;批次编排传 False 由外层统一提交。 """ + model = ShippingOrderTask if isinstance(task, ShippingOrderTask) else ShippingNotice task = ( - db.session.query(ShippingNotice) - .filter(ShippingNotice.id == int(task.id)) - # ShippingNotice.customer 使用 joined eager load,会形成 LEFT OUTER JOIN; - # PostgreSQL 不允许锁定该连接的可空侧,故只锁当前 Notice 行。 - .with_for_update(of=ShippingNotice) + db.session.query(model) + .filter(model.id == int(task.id)) + .with_for_update(of=model) .one() ) customer = db.session.get(ShippingCustomer, int(customer_id)) @@ -106,38 +133,28 @@ def confirm_task_customer( raise ConflictError('Merged customer cannot be confirmed', code='SHIPPING.CUSTOMER_MERGED_LOCKED') if customer.status != 'active': raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE') - if task.business_no and task.customer_id not in {None, customer.id}: + facts = customer_confirmation_facts(task) + if getattr(task, 'business_no', None) and facts['customer_id'] not in {None, customer.id}: raise ConflictError( 'Numbered shipping notice customer cannot be changed silently', code='SHIPPING.CUSTOMER_NUMBERED_NOTICE_LOCKED', ) - now = datetime.utcnow() - previous_customer_id = task.customer_id - task.customer_id = customer.id - task.customer_name_snapshot = customer.standard_name - task.customer_short_code_snapshot = customer.short_code - fingerprint = hashlib.sha256(f'customer:{customer.id}'.encode('ascii')).hexdigest() - task.customer_resolution_status = 'confirmed' - task.customer_resolution_method = resolution_method - task.customer_identity_fingerprint = fingerprint - task.customer_confirmed_by = actor_id - task.customer_confirmed_at = now - db.session.add(ShippingTaskEvent( - task_id=task.id, - event_type='customer_confirmed', - detail_json={ - 'customer_id': customer.id, - 'standard_name': customer.standard_name, - 'short_code': customer.short_code, - 'previous_customer_id': previous_customer_id, - 'method': resolution_method, - 'business_no': task.business_no, - }, - )) + owner = task + if not isinstance(task, ShippingOrderTask): + order_task_id = getattr(task, 'order_task_id', None) + owner = db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id else None + if owner is None: + raise ConflictError('Shipping notice is not linked to an order task', code='SHIPPING.ORDER_TASK_REQUIRED') + confirm_customer_resolution( + owner, + customer_id=int(customer.id), + actor_id=actor_id, + method=resolution_method, + ) if commit: db.session.commit() - return db.session.get(ShippingNotice, int(task.id)) + return db.session.get(model, int(task.id)) db.session.flush() return task diff --git a/backend/app/services/shipping_notice/dify_inputs.py b/backend/app/services/shipping_notice/dify_inputs.py index 62a3abda..3bfe2ba1 100644 --- a/backend/app/services/shipping_notice/dify_inputs.py +++ b/backend/app/services/shipping_notice/dify_inputs.py @@ -13,18 +13,18 @@ from __future__ import annotations from datetime import datetime from typing import Any -from app.models import ShippingNotice, ShippingTemporaryInventorySession +from app.models import ShippingOrderTask, ShippingTemporaryInventorySession from app.services.agent_runtime_context.builder import serialize_for_dify from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT from app.services.shipping_notice.runtime_context import build_shipping_runtime_context -def _task_by_task_no(task_id: str) -> ShippingNotice | None: +def _task_by_task_no(task_id: str) -> ShippingOrderTask | None: """按显式 task_id 获取任务;禁止按会话号猜测当前任务。""" normalized = str(task_id or "").strip().upper() if not normalized: return None - return ShippingNotice.query.filter_by(task_no=normalized).first() + return ShippingOrderTask.query.filter_by(task_no=normalized).first() def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | None: @@ -56,7 +56,7 @@ def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | N return str(item.session_no or '').strip().upper() or None if item else None -def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) -> ShippingNotice | None: +def _focus_task_row(focus_task: str, explicit_task_row: ShippingOrderTask | None) -> ShippingOrderTask | None: """ 解析当前显式焦点任务行。 @@ -74,7 +74,7 @@ def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) - return None if explicit_task_row and str(explicit_task_row.task_no or "").strip().upper() == normalized: return explicit_task_row - return ShippingNotice.query.filter_by(task_no=normalized).first() + return ShippingOrderTask.query.filter_by(task_no=normalized).first() def build_dify_chat_inputs( 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 2d753d23..6c3a2a49 100644 --- a/backend/app/services/shipping_notice/document_profile_quality_service.py +++ b/backend/app/services/shipping_notice/document_profile_quality_service.py @@ -1339,8 +1339,31 @@ def assert_profile_publishable(profile: ShippingOrderDocumentProfile) -> None: raise ConflictError('A cross-page blind test sample is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_CROSS_PAGE') -def promote_approved_suite_for_publish(*, profile: ShippingOrderDocumentProfile, draft_checksum: str, published_checksum: str) -> None: - """将已批准草稿盲测凭证原子冻结为正式 Profile checksum,供历史 Run 精确引用。""" +def promote_approved_suite_for_publish( + *, profile: ShippingOrderDocumentProfile, draft_checksum: str, published_checksum: str, + actor_id: int | None = None, +) -> None: + """将已批准草稿盲测凭证原子冻结为正式 Profile checksum,供历史 Run 精确引用。 + + 核心逻辑: + [STEP 1] 定位当前草稿 checksum 下已批准的盲测集;缺失时直接返回(生产调用方 + 已通过 assert_profile_publishable 门禁,此守卫仅防御测试夹具伪造凭证)。 + [STEP 2] 同一 Profile 行重复发布相同内容时(如人工将已发布模板重置为草稿后 + 再次发布),发布 checksum 由规范化负载确定性复现,历史提升套件仍占用 + (profile_id, profile_checksum) 唯一键。若占用者仍是有效发布凭证(approved 且 + 最近一次 Run 通过且 checksum 一致),则直接复用历史凭证:新草稿集转为 + superseded 以保留其运行历史供审计,不再重写 checksum,避免唯一键冲突。 + [STEP 3] 常规路径:重写套件与其 Run 的 checksum 为发布 checksum。 + + Args: + profile: 即将发布的 Profile ORM 记录(发布事务内调用,不自行提交)。 + draft_checksum: 发布前草稿定义的规范化 checksum。 + published_checksum: 本次发布冻结的正式 checksum。 + actor_id: 触发发布的管理员主键,用于审计;允许为空。 + + Returns: + 无返回值;套件状态变更随发布事务一并提交。 + """ suite = ShippingDocumentProfileTestSuite.query.filter_by( profile_id=profile.id, profile_checksum=draft_checksum, status='approved', ).one_or_none() @@ -1348,6 +1371,31 @@ def promote_approved_suite_for_publish(*, profile: ShippingOrderDocumentProfile, # isolated lifecycle tests from fabricating a quality credential by monkeypatch. if suite is None: return + # [STEP 2] 唯一键占用检查:发布 checksum 相同意味着定义、Schema 与 adapter 证据 + # 完全一致,历史凭证对本次发布同样有效,无需也不允许重写第二个套件。 + occupant = ShippingDocumentProfileTestSuite.query.filter_by( + profile_id=profile.id, profile_checksum=published_checksum, + ).one_or_none() + if occupant is not None and occupant.id != suite.id: + occupant_last_run = occupant.runs[-1] if occupant.runs else None + if ( + occupant.status == 'approved' and occupant_last_run is not None + and occupant_last_run.status == 'passed' + and occupant_last_run.profile_checksum == published_checksum + ): + suite.status = 'superseded' + _audit(profile_id=profile.id, event_type='blind_test_suite_superseded', actor_id=actor_id, detail={ + 'suite_id': suite.id, 'reused_suite_id': occupant.id, + 'reason_code': 'republish_identical_content', + }) + return + # 占用者不是有效凭证(人工改动等异常数据):拒绝发布并给出可定位的错误码, + # 禁止静默覆盖或删除历史盲测证据。 + raise ConflictError( + 'Published checksum is already occupied by another test suite', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SUITE_CHECKSUM_CONFLICT', + details={'suite_id': occupant.id}, + ) suite.profile_checksum = published_checksum for run in suite.runs: if run.profile_checksum == draft_checksum: diff --git a/backend/app/services/shipping_notice/duplicate_detection.py b/backend/app/services/shipping_notice/duplicate_detection.py index fad92a0a..e8e12c3b 100644 --- a/backend/app/services/shipping_notice/duplicate_detection.py +++ b/backend/app/services/shipping_notice/duplicate_detection.py @@ -23,6 +23,7 @@ from app.models import ( ShippingOrderIntake, ShippingOrderSnapshot, ShippingNotice, + ShippingOrderTask, ) from app.services.shipping_notice.business_fingerprint import ( CONTENT_FINGERPRINT_VERSION, @@ -40,19 +41,35 @@ def classify_task_lifecycle(task: ShippingNotice | dict[str, Any] | None) -> str lifecycle = str(get('lifecycle_status', '') or '').strip().lower() if lifecycle in {'voided', 'archived', 'deleted', 'cancelled', 'canceled'}: return 'closed' - upload = str(get('upload_status', '') or '').strip().lower() - if upload in {'uploaded', 'succeeded', 'success'} or get('freight_ref_no'): + upload = None + try: + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + if not isinstance(task, dict) and has_verified_upload_success(task): + upload = 'uploaded' + except Exception: + upload = None + if upload in {'uploaded', 'succeeded', 'success'}: return 'completed' return 'active' def is_irreversible_task(task: ShippingNotice) -> bool: """已 uploaded 或终态任务不可原地覆盖源文件。""" - upload_status = str(task.upload_status or '').strip().lower() - return upload_status in {'uploaded', 'succeeded', 'success'} + try: + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + return has_verified_upload_success(task) + except Exception: + return False def _match_payload(task: ShippingNotice, *, match_type: str, matched_fields: list[str]) -> dict[str, Any]: + candidate = ( + db.session.query(ShippingOrderCandidate) + .filter(ShippingOrderCandidate.consumed_task_id == task.order_task_id) + .order_by(ShippingOrderCandidate.id.desc()) + .first() + if getattr(task, 'order_task_id', None) else None + ) return { 'task_no': task.task_no, 'document_version': int(task.document_version or 1), @@ -60,14 +77,29 @@ def _match_payload(task: ShippingNotice, *, match_type: str, matched_fields: lis 'matched_fields': list(matched_fields), 'lifecycle': classify_task_lifecycle(task), 'created_at': utc_iso(task.created_at), - 'content_fingerprint': task.content_fingerprint, - 'content_fingerprint_version': task.content_fingerprint_version, + 'content_fingerprint': getattr(candidate, 'content_fingerprint', None), + 'content_fingerprint_version': getattr(candidate, 'content_fingerprint_version', None), } +def _task_content_fingerprint(task: ShippingNotice) -> tuple[str | None, str | None]: + """从建单来源 Candidate 读取内容指纹;正式 Notice 不再保存该投影。""" + if not getattr(task, 'order_task_id', None): + return None, None + candidate = ( + db.session.query(ShippingOrderCandidate.content_fingerprint, ShippingOrderCandidate.content_fingerprint_version) + .filter(ShippingOrderCandidate.consumed_task_id == task.order_task_id) + .order_by(ShippingOrderCandidate.id.desc()) + .first() + ) + return (candidate[0], candidate[1]) if candidate else (None, None) + + def _reservation_differences(task: ShippingNotice, summary: dict[str, Any]) -> list[dict[str, Any]]: """比较候选与目标冻结订单的同 Reservation 行,供人工修订确认前展示。""" - snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None + owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task + snapshot_id = getattr(owner, 'order_snapshot_id', None) + snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None if snapshot is None: return [] proposed = { @@ -158,10 +190,13 @@ def detect_duplicates_for_intake( if content_hash: hash_tasks = ( db.session.query(ShippingNotice) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingOrderIntake, ShippingOrderIntake.consumed_task_id == ShippingOrderTask.id) + .join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id) .filter( - ShippingNotice.user_id == int(intake.user_id), - ShippingNotice.source_content_hash == content_hash, - ShippingNotice.lifecycle_status == 'active', + ShippingOrderTask.user_id == int(intake.user_id), + FileAsset.content_hash == content_hash, + ShippingOrderTask.lifecycle_status == 'active', ) .order_by(ShippingNotice.id.desc()) .limit(10) @@ -182,10 +217,12 @@ def detect_duplicates_for_intake( if fingerprint and strength in {'strong', 'medium'}: fp_tasks = ( db.session.query(ShippingNotice) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) .filter( - ShippingNotice.user_id == int(intake.user_id), - ShippingNotice.business_fingerprint == fingerprint, - ShippingNotice.fingerprint_version == version, + ShippingOrderTask.user_id == int(intake.user_id), + ShippingOrderCandidate.business_fingerprint == fingerprint, + ShippingOrderCandidate.fingerprint_version == version, ) .order_by(ShippingNotice.id.desc()) .limit(20) @@ -206,12 +243,13 @@ def detect_duplicates_for_intake( if matches and status == 'none': comparable = [ task for task in fp_tasks - if task.content_fingerprint and task.content_fingerprint_version == content_version + if _task_content_fingerprint(task)[0] + and _task_content_fingerprint(task)[1] == content_version ] if content_fingerprint and comparable: status = ( 'same_business_content' - if any(task.content_fingerprint == content_fingerprint for task in comparable) + if any(_task_content_fingerprint(task)[0] == content_fingerprint for task in comparable) else 'possible_revision' ) else: @@ -229,11 +267,13 @@ def detect_duplicates_for_intake( # 弱指纹:仅标记疑似,不按 active 强阻断 fp_tasks = ( db.session.query(ShippingNotice) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) .filter( - ShippingNotice.user_id == int(intake.user_id), - ShippingNotice.business_fingerprint == fingerprint, - ShippingNotice.fingerprint_version == version, - ShippingNotice.lifecycle_status == 'active', + ShippingOrderTask.user_id == int(intake.user_id), + ShippingOrderCandidate.business_fingerprint == fingerprint, + ShippingOrderCandidate.fingerprint_version == version, + ShippingOrderTask.lifecycle_status == 'active', ) .order_by(ShippingNotice.id.desc()) .limit(5) @@ -498,11 +538,10 @@ def detect_duplicates_for_candidate( if content_hash: hash_query = ( db.session.query(ShippingNotice) - .filter( - ShippingNotice.user_id == int(intake.user_id), - ShippingNotice.source_content_hash == content_hash, - ShippingNotice.lifecycle_status == 'active', - ) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingOrderIntake, ShippingOrderIntake.consumed_task_id == ShippingOrderTask.id) + .join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id) + .filter(ShippingOrderTask.user_id == int(intake.user_id), FileAsset.content_hash == content_hash, ShippingOrderTask.lifecycle_status == 'active') ) if skipped_ids: hash_query = hash_query.filter(ShippingNotice.id.notin_(list(skipped_ids))) @@ -522,11 +561,9 @@ def detect_duplicates_for_candidate( if fingerprint and strength in {'strong', 'medium'}: fp_query = ( db.session.query(ShippingNotice) - .filter( - ShippingNotice.user_id == int(intake.user_id), - ShippingNotice.business_fingerprint == fingerprint, - ShippingNotice.fingerprint_version == version, - ) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) + .filter(ShippingOrderTask.user_id == int(intake.user_id), ShippingOrderCandidate.business_fingerprint == fingerprint, ShippingOrderCandidate.fingerprint_version == version) ) if skipped_ids: fp_query = fp_query.filter(ShippingNotice.id.notin_(list(skipped_ids))) @@ -545,12 +582,13 @@ def detect_duplicates_for_candidate( if matches and status == 'none': comparable = [ task for task in fp_tasks - if task.content_fingerprint and task.content_fingerprint_version == content_version + if _task_content_fingerprint(task)[0] + and _task_content_fingerprint(task)[1] == content_version ] if content_fingerprint and comparable: status = ( 'same_business_content' - if any(task.content_fingerprint == content_fingerprint for task in comparable) + if any(_task_content_fingerprint(task)[0] == content_fingerprint for task in comparable) else 'possible_revision' ) else: @@ -564,12 +602,9 @@ def detect_duplicates_for_candidate( elif fingerprint and strength == 'weak' and status == 'none': weak_query = ( db.session.query(ShippingNotice) - .filter( - ShippingNotice.user_id == int(intake.user_id), - ShippingNotice.business_fingerprint == fingerprint, - ShippingNotice.fingerprint_version == version, - ShippingNotice.lifecycle_status == 'active', - ) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id) + .filter(ShippingOrderTask.user_id == int(intake.user_id), ShippingOrderCandidate.business_fingerprint == fingerprint, ShippingOrderCandidate.fingerprint_version == version, ShippingOrderTask.lifecycle_status == 'active') ) if skipped_ids: weak_query = weak_query.filter(ShippingNotice.id.notin_(list(skipped_ids))) diff --git a/backend/app/services/shipping_notice/error_explainability_contract.py b/backend/app/services/shipping_notice/error_explainability_contract.py index 2babdf63..f8bc8091 100644 --- a/backend/app/services/shipping_notice/error_explainability_contract.py +++ b/backend/app/services/shipping_notice/error_explainability_contract.py @@ -570,7 +570,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'inventory_rpa_login_failed': _meta('admin', 'retry_inventory_preparation', '库存平台登录失败'), 'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'), 'inventory_rpa_exhausted': _meta('owner', 'reload_inventory_result', '库存源重试次数已耗尽'), - 'inventory_file_missing': _meta('owner', 'upload_inventory_file', '未生成库存文件'), + 'inventory_file_missing': _meta('owner', 'retry_inventory_preparation', '未生成库存文件'), 'inventory_candidates_missing': _meta('system', 'retry_with_latest_rules', '正式库存候选版本缺失'), 'inventory_candidate_data_incomplete': _meta('system', 'retry_with_latest_rules', '库存候选事实不完整'), 'inventory_candidate_version_stale': _meta('system', 'retry_with_latest_rules', '库存候选版本已切换'), @@ -613,7 +613,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'inventory_reservation_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 Reservation'), 'inventory_warehouse_mismatch': _meta('owner', 'open_inventory_match_review', '仓库与订单要求不一致'), 'inventory_uom_conversion_failed': _meta('owner', 'open_inventory_match_review', '单位换算失败'), - 'inventory_multi_file_conflict': _meta('owner', 'open_inventory_match_review', '多库存文件结果冲突'), + 'inventory_multi_file_conflict': _meta('owner', 'override_line_inventory_source', '多库存文件结果冲突'), } diff --git a/backend/app/services/shipping_notice/identity_resolution/resolver.py b/backend/app/services/shipping_notice/identity_resolution/resolver.py index dcacbade..249ace2a 100644 --- a/backend/app/services/shipping_notice/identity_resolution/resolver.py +++ b/backend/app/services/shipping_notice/identity_resolution/resolver.py @@ -86,7 +86,7 @@ def _accepted_header_values(candidate: ShippingOrderCandidate) -> tuple[Shipping def definition_context_field_is_compatible( definition: dict[str, Any], extraction: ShippingOrderExtraction, actual_field_id: str, ) -> bool: - """校验新版 Schema 字段能否承接旧规则快照,防止字段 UUID 漂移误伤稳定业务语义。""" + """字段绑定主谓词:先认定同一 UUID 即同字段;否则按 field_code + scope + value_type 判断语义兼容承接规则快照。""" expected_id = str(definition.get('context_field_id') or '') if actual_field_id == expected_id: return True @@ -111,15 +111,19 @@ def definition_context_field_is_compatible( def _resolved_context_field_id( definition: dict[str, Any], extraction: ShippingOrderExtraction | None, header_values: dict[str, dict[str, Any]], ) -> str | None: - """优先使用快照 UUID;Schema 升级仅在字段业务语义未变化时按 field_code 映射到新 UUID。""" + """按 field_config.field_code 语义键定位当前字段;UUID 直配仅保留为同字段快速命中。 + + 规则定义以 field_code(不随 Schema 版本重建而漂移)作为跨版本稳定引用锚点; + UUID 直接命中只作为无漂移时的快捷路径,避免 Schema 重发布打断识别链路。 + 旧快照若缺少 field_code,则回退到 UUID 直配路径,保证向后兼容。 + """ + if extraction is not None: + for field_id in header_values: + if definition_context_field_is_compatible(definition, extraction, field_id): + return field_id expected_id = str(definition.get('context_field_id') or '') if expected_id in header_values: return expected_id - if extraction is None: - return None - for field_id in header_values: - if definition_context_field_is_compatible(definition, extraction, field_id): - return field_id return None diff --git a/backend/app/services/shipping_notice/identity_rules/service.py b/backend/app/services/shipping_notice/identity_rules/service.py index 202ebf65..adb1636e 100644 --- a/backend/app/services/shipping_notice/identity_rules/service.py +++ b/backend/app/services/shipping_notice/identity_rules/service.py @@ -12,8 +12,6 @@ import hashlib import json import re import uuid -from pathlib import Path -import urllib.request from datetime import datetime from typing import Any @@ -112,19 +110,6 @@ def _published_schema_version() -> ShippingOrderSchemaVersion | None: def _published_field_config(field_id: str) -> dict[str, Any] | None: """读取当前发布版本中的字段配置;识别定义和证据标准化均使用同一快照。""" - # #region debug-point A/B/C/E:published-schema-state - try: - debug_env = Path(__file__).resolve().parents[5] / '.dbg' / 'shipping-customer-fingerprint-500.env' - debug_values = { - line.split('=', 1)[0]: line.split('=', 1)[1].strip() - for line in debug_env.read_text(encoding='utf-8').splitlines() - if '=' in line - } - published_rows = ShippingOrderSchemaVersion.query.filter_by(status='published').all() - urllib.request.urlopen(urllib.request.Request(debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'), data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'shipping-customer-fingerprint-500'), 'runId': 'post-fix', 'hypothesisId': 'A/B/C/E', 'location': 'identity_rules/service.py:114', 'msg': '[DEBUG] published schema rows before serializer lookup', 'data': {'field_id': field_id, 'count': len(published_rows), 'rows': [{'id': row.id, 'schema_id': row.schema_id, 'version': row.version, 'status': row.status} for row in published_rows]}}).encode(), headers={'Content-Type': 'application/json'}), timeout=1).read() - except Exception: - pass - # #endregion published = _published_schema_version() return next(( item for item in ((published.definition_json if published else {}) or {}).get('fields', []) diff --git a/backend/app/services/shipping_notice/order_auto_freeze_policy.py b/backend/app/services/shipping_notice/order_auto_freeze_policy.py index 910c41f8..81cc97d9 100644 --- a/backend/app/services/shipping_notice/order_auto_freeze_policy.py +++ b/backend/app/services/shipping_notice/order_auto_freeze_policy.py @@ -17,7 +17,8 @@ from typing import Any from app.models import ( ShippingDocumentProfileAutoFreezeQualification, - ShippingOrderCustomerMatch, + ShippingCustomerShadowResolution, + ShippingOrderCandidate, ShippingOrderExtraction, ShippingOrderExtractionProgressEvent, ShippingOrderRouteDecision, @@ -321,19 +322,19 @@ def _qualification_for_route( def _confirmed_customer_ids(run: ShippingOrderProcessingRun) -> list[int]: - """读取本轮已确认的 Bill-to 客户;跨订单多客户时必须维持 fail-closed。""" + """读取本轮正式识别结果中的已确认客户;跨订单多客户时维持 fail-closed。""" rows = ( - ShippingOrderCustomerMatch.query - .join(ShippingOrderExtraction, ShippingOrderExtraction.id == ShippingOrderCustomerMatch.extraction_id) + ShippingCustomerShadowResolution.query + .join(ShippingOrderCandidate, ShippingOrderCandidate.id == ShippingCustomerShadowResolution.candidate_id) + .join(ShippingOrderExtraction, ShippingOrderExtraction.id == ShippingOrderCandidate.order_extraction_id) .filter( ShippingOrderExtraction.run_id == int(run.id), - ShippingOrderCustomerMatch.role == 'bill_to', - ShippingOrderCustomerMatch.status == 'confirmed', - ShippingOrderCustomerMatch.customer_id.isnot(None), + ShippingCustomerShadowResolution.status == 'confirmed', + ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None), ) .all() ) - return sorted({int(row.customer_id) for row in rows if row.customer_id is not None}) + return sorted({int(row.confirmed_customer_id) for row in rows if row.confirmed_customer_id is not None}) def _evaluate_customer_scope( diff --git a/backend/app/services/shipping_notice/order_build_eligibility_service.py b/backend/app/services/shipping_notice/order_build_eligibility_service.py index dc682699..52cdb840 100644 --- a/backend/app/services/shipping_notice/order_build_eligibility_service.py +++ b/backend/app/services/shipping_notice/order_build_eligibility_service.py @@ -7,7 +7,7 @@ services/shipping_notice/order_build_eligibility_service.py inventory_routing_engine、inventory_source_repository、 ShippingOrderCandidate / ShippingOrderProcessingUnit / ShippingOrderProcessingRun、 ShippingInventorySource、process_gate_contract(原因唯一归属)。 -逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核阻断; +逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核不阻断正式 OT 创建(库存路由属可人工修正事实,行级仍记录 block_reason 供自动建单/复核门禁消费); 人工已选候选(含原因)可覆盖规则零候选且优先于自动建议;规则原始候选与当前有效候选分离; 停用 / Profile 未启用 / 无已发布解析 Profile / Excel 模板未发布的 Source 不进入有效候选, 并写入稳定 unavailable_reasons(码表见 error_explainability_contract); @@ -473,7 +473,7 @@ def assess_order_build_eligibility( fields: Schema field_id → 配置。 header_by_code: Header field_code → 值。 lines: 行 field_code → 值列表(与 line_metas 对齐)。 - line_metas: Draft 行原始对象(含 line_key / inventory_routing)。 + line_metas: Draft 行原始对象(含 draft_line_id / inventory_routing)。 customer_resolved: 客户是否已唯一命中或人工确认;缺省 True 由调用方保证。 candidate / unit / run: 可选门禁上下文(自动建单检查)。 @@ -515,7 +515,7 @@ def assess_order_build_eligibility( line_meta=meta, ) projection = { - 'line_key': meta.get('line_key'), + 'draft_line_id': meta.get('draft_line_id'), 'line_index': index, 'effective_reservation_id': effective, 'inventory_source_hint': raw_line.get('inventory_source_hint'), @@ -526,7 +526,7 @@ def assess_order_build_eligibility( if not effective: issues.append({ 'code': 'effective_reservation_missing', - 'line_key': meta.get('line_key'), + 'draft_line_id': meta.get('draft_line_id'), 'line_index': index, 'severity': 'blocking', 'owning_gate_code': 'reservation_validation', @@ -534,7 +534,7 @@ def assess_order_build_eligibility( if not routing.get('can_build'): issues.append({ 'code': str(routing.get('block_reason') or 'inventory_source_unresolved'), - 'line_key': meta.get('line_key'), + 'draft_line_id': meta.get('draft_line_id'), 'line_index': index, 'severity': 'blocking', 'owning_gate_code': 'inventory_source_routing', @@ -573,11 +573,16 @@ def assess_order_build_eligibility( 'owning_gate_code': 'reservation_validation', }) + # 库存源路由属于通知准备阶段可人工修正的事实,不阻断正式 OT 创建。 + build_blocking_issues = [ + item for item in issues + if str(item.get('owning_gate_code') or '') != 'inventory_source_routing' + ] can_build = ( bool(customer_resolved) and bool(assessment.get('can_create_task')) - and not issues - and all(item.get('can_build') and item.get('effective_reservation_id') for item in line_projections) + and not build_blocking_issues + and all(item.get('effective_reservation_id') for item in line_projections) and bool(line_projections) ) fields_complete = ( diff --git a/backend/app/services/shipping_notice/order_candidate_builder.py b/backend/app/services/shipping_notice/order_candidate_builder.py index bb282d09..2f314362 100644 --- a/backend/app/services/shipping_notice/order_candidate_builder.py +++ b/backend/app/services/shipping_notice/order_candidate_builder.py @@ -12,8 +12,17 @@ import re from decimal import Decimal, InvalidOperation from typing import Any -from app.services.shipping_notice.notice_line_table import parse_notice_table_text -from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract +from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text +from app.services.shipping_notice.notice_line_table import ( + find_notice_header_row_index, + parse_notice_row, + parse_notice_table_text, +) +from app.services.shipping_notice.notice_line_values import resolve_notice_columns +from app.services.shipping_notice.order_schema.table_contract import ( + compile_table_header_contract, + normalize_table_header, +) from app.services.shipping_notice.po_number import normalize_po_number from app.services.shipping_notice.reservation_id import validated_reservation_id @@ -33,11 +42,49 @@ def _comparable_value(field: str, value: Any) -> str: return str(value or "").strip().upper() +def _scan_email_po_aws_header( + header: list[str], schema_definition: dict[str, Any], +) -> tuple[int | None, int | None]: + """ + 定位邮件正文表头中 PO 与 AWS SKU 的列索引。 + + 背景:`po_number` 为 header 作用域、`aws_part_number` 不在 TABLE_FIELD_CODES 内,两者都不会被 + compile_table_header_contract 编入契约,故 `parse_notice_row` 永远不会产出这两个字段。正文订单索引行 + 需要额外保留它们,才能在按 PO 融合附件时回填正文分配字段(如 inventory_source_hint / customer_part_number + 等)。为不移除共享表头契约(守约严格性),这里只做独立的表头列扫描。 + + Returns: + 返回 (po_idx, aws_idx);对应列不在表头时结果为 None。 + """ + # 仅从本次预处理选择的 Schema 定义派生候选表头(field_code + display_name + aliases),避免硬编码漂移。 + aliases: dict[str, set[str]] = {"po_number": set(), "aws_part_number": set()} + for raw in schema_definition.get("fields") or []: + code = str(raw.get("field_code") or "").strip() + if code not in aliases: + continue + for candidate in (code, raw.get("display_name"), *(raw.get("aliases") or [])): + normalized = normalize_table_header(candidate) + if normalized: + aliases[code].add(normalized) + + po_idx = None + aws_idx = None + for i, cell_text in enumerate(header): + normalized = normalize_table_header(cell_text) + if normalized and normalized in aliases["po_number"]: + po_idx = i + if normalized and normalized in aliases["aws_part_number"]: + aws_idx = i + return po_idx, aws_idx + + def build_email_order_index(body_text: str, *, schema_definition: dict[str, Any]) -> list[dict[str, Any]]: """ 从邮件正文表格提取订单索引行。 - 核心逻辑:复用统一订单表格解析器,并只保留具备 PO 或 Reservation 的有效订单行。 + 核心逻辑:复用统一订单表格解析器抽标准明细字段,并额外按正文原始表头回填 `po_number` 与 + `aws_part_number`(两者因作用域/字段表不在共享契约中,parse_notice_row 不产出),供按 PO 融合 + 附件时补正文分配字段。最后只保留具备 PO 或 Reservation 的有效订单行。 Args: body_text: 邮件正文纯文本。 schema_definition: 本次预处理明确选择的订单 Schema 定义。 @@ -45,7 +92,44 @@ def build_email_order_index(body_text: str, *, schema_definition: dict[str, Any] 正文订单索引列表。 """ contract = compile_table_header_contract(schema_definition) - rows = parse_notice_table_text(str(body_text or ""), contract=contract) + text = str(body_text or "") + + # 先用共享解析器判空;无有效行时直接退化为共享结果,避免空文本重复自建解析。 + if not parse_notice_table_text(text, contract=contract): + return [] + + raw_rows = _rows_from_table_text(text) + if not raw_rows: + return [] + header_idx = find_notice_header_row_index(raw_rows, contract=contract) + header = [str(c or "").strip() for c in raw_rows[header_idx]] + po_idx, aws_idx = _scan_email_po_aws_header(header, schema_definition) + + columns = resolve_notice_columns(header, contract) + if columns.get("_ambiguous_fields"): + return [] + idx_res = columns.get("reservation_id") + if idx_res is not None and idx_res < len(header): + columns["_reservation_id_header"] = str(header[idx_res] or "").strip() + + rows: list[dict[str, Any]] = [] + for raw_row in raw_rows[header_idx + 1:]: + if not raw_row: + continue + parsed = parse_notice_row(list(raw_row), columns, contract=contract) + if parsed is None: + continue + # 回填共享解析器不产出的 PO / AWS SKU,保证正文行与原始表列强对齐。 + if po_idx is not None and po_idx < len(raw_row): + po_number = str(raw_row[po_idx] or "").strip() + if po_number: + parsed["po_number"] = po_number + if aws_idx is not None and aws_idx < len(raw_row): + aws_part_number = str(raw_row[aws_idx] or "").strip() + if aws_part_number: + parsed["aws_part_number"] = aws_part_number + rows.append(parsed) + return [ row for row in rows if normalize_po_number(row.get("po_number")) diff --git a/backend/app/services/shipping_notice/order_document_profile_creation_service.py b/backend/app/services/shipping_notice/order_document_profile_creation_service.py index 9de2fa43..8257e0fe 100644 --- a/backend/app/services/shipping_notice/order_document_profile_creation_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_creation_service.py @@ -178,6 +178,8 @@ def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str, sample_role=sample_role, created_by_id=actor_id, )) db.session.flush() + if document.asset_id: + profile_service._retain_profile_sample_assets(profile_id, asset_ids={int(document.asset_id)}) profile_service._refresh_training_sample_count(db.session.get(ShippingOrderDocumentProfile, profile_id)) revision_no = int(saved['draft_revision']['revision_no']) profile_service._audit( diff --git a/backend/app/services/shipping_notice/order_document_profile_preview_service.py b/backend/app/services/shipping_notice/order_document_profile_preview_service.py index 5cbdbbc1..67000c67 100644 --- a/backend/app/services/shipping_notice/order_document_profile_preview_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_preview_service.py @@ -153,6 +153,7 @@ def _frozen_sample_context( 'Frozen sample file is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE', ) + profile_service._repair_bound_sample_asset(document) asset = db.session.get(FileAsset, int(document.asset_id)) if asset is None: raise ValidationError( @@ -239,6 +240,39 @@ def _render_pdf_pages(asset: FileAsset) -> list[Any]: ) from exc +def _frozen_physical_page_count( + *, layout_version: ShippingDocumentLayoutVersion, document: ShippingOrderDocument, +) -> int | None: + """ + 从冻结 Layout 的完整页证据读取原 PDF 物理页数,供历史错误快照的只读兼容校验。 + + 核心逻辑:持久化 Layout 可把坐标证据外置到受控 FileAsset,本函数只加载该冻结引用; + 仅页面元数据可证明物理页数,绝不以业务表格页数作为回退。 + + Args: + layout_version: 已通过冻结 checksum 校验的 Layout 版本。 + document: 与 Layout 绑定且已通过内容 hash 校验的样本文档。 + + Returns: + 完整页证据可用时返回物理页数;证据缺失或结构无效时返回 None。 + """ + from app.services.shipping_notice.document_layout.lifecycle import _hydrate_coordinate_evidence + + payload = _hydrate_coordinate_evidence( + payload=dict(layout_version.payload_json or {}), document=document, + ) + pages = payload.get('pages') + if isinstance(pages, list): + count = len([item for item in pages if isinstance(item, dict)]) + if count: + return count + evidence = payload.get('coordinate_evidence') + evidence_pages = evidence.get('pages') if isinstance(evidence, dict) else None + if isinstance(evidence_pages, dict) and evidence_pages: + return len(evidence_pages) + return None + + def authorize_frozen_sample_preview_pages( profile_id: int, *, @@ -258,15 +292,18 @@ def authorize_frozen_sample_preview_pages( profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id)) if profile is None: raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') - _, sample, document, _layout_version, asset = _frozen_sample_context( + _, sample, document, layout_version, asset = _frozen_sample_context( profile_id=int(profile_id), sample_binding_id=int(sample_binding_id), ) pages = _render_pdf_pages(asset) if sample.page_count_snapshot is not None and len(pages) != int(sample.page_count_snapshot): - raise ValidationError( - 'Frozen page count no longer matches the published evidence', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE', - ) + # [STEP 1] 兼容修复上线前把外置证据退化为表格页数的历史冻结记录; + # 只有同一冻结 Layout 的完整页证据与当前原 PDF 一致时才允许预览。 + if _frozen_physical_page_count(layout_version=layout_version, document=document) != len(pages): + raise ValidationError( + 'Frozen page count no longer matches the published evidence', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE', + ) store = _preview_grant_store() preview_pages: list[dict[str, Any]] = [] for page in pages: 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 88ccac5f..bf39a6f1 100644 --- a/backend/app/services/shipping_notice/order_document_profile_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_service.py @@ -309,9 +309,58 @@ def _bound_sample_document(profile_id: int, document_id: int) -> ShippingOrderDo document = db.session.get(ShippingOrderDocument, int(document_id)) if document is None: raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') + _repair_bound_sample_asset(document) return document +def _repair_bound_sample_asset(document: ShippingOrderDocument) -> None: + """补偿历史样本资产引用,避免已绑定的标注样本按临时 TTL 过期。""" + if not document.asset_id: + return + asset = db.session.get(FileAsset, int(document.asset_id)) + if asset is None: + return + if str(asset.lifecycle_status or '') == 'temporary' and int(asset.reference_count or 0) == 0: + from app.services.file_assets.service import mark_asset_referenced + + mark_asset_referenced(asset) + + +def _retain_profile_sample_assets(profile_id: int, *, asset_ids: set[int] | None = None) -> int: + """为新增 Profile 样本引用的每个唯一文件资产建立一份引用。""" + from app.services.file_assets.service import mark_asset_referenced + + ids = set(asset_ids or ()) + for asset_id in sorted(ids): + asset = db.session.get(FileAsset, asset_id) + if asset is not None: + mark_asset_referenced(asset) + return len(ids) + + +def _release_profile_sample_asset_if_unreferenced(profile_id: int, document_id: int) -> None: + """删除样本绑定后,仅当该 Profile 不再引用文件时释放资产引用。""" + document = db.session.get(ShippingOrderDocument, int(document_id)) + if document is None or not document.asset_id: + return + still_bound = ( + db.session.query(ShippingOrderDocumentProfileSample) + .join(ShippingOrderDocument, ShippingOrderDocument.id == ShippingOrderDocumentProfileSample.document_id) + .filter( + ShippingOrderDocumentProfileSample.profile_id == int(profile_id), + ShippingOrderDocument.asset_id == int(document.asset_id), + ) + .first() + ) + if still_bound is not None: + return + asset = db.session.get(FileAsset, int(document.asset_id)) + if asset is not None and int(asset.reference_count or 0) > 0: + from app.services.file_assets.service import release_asset_reference + + release_asset_reference(asset) + + def _preview_grant_store() -> Any: """?????????????? Redis????????????????""" return preview_grant_store() @@ -1461,6 +1510,11 @@ def add_profile_sample( if document is None: raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') _document_layout(document) + existing_asset_ids = { + int(existing_document.asset_id) + for existing in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all() + if (existing_document := db.session.get(ShippingOrderDocument, int(existing.document_id))) is not None and existing_document.asset_id + } sample = ShippingOrderDocumentProfileSample( profile_id=profile.id, document_id=document.id, table_id=str(table_id).strip() or None, sample_role=role, created_by_id=actor_id, @@ -1472,6 +1526,8 @@ def add_profile_sample( db.session.rollback() raise ConflictError('Profile sample already exists', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_CONFLICT') from exc _refresh_training_sample_count(profile) + if document.asset_id and int(document.asset_id) not in existing_asset_ids: + _retain_profile_sample_assets(profile.id, asset_ids={int(document.asset_id)}) clear_matching_signature_refs(profile, actor_id=actor_id, reason='sample_added') _audit(profile_id=profile.id, document_id=document.id, event_type='profile_sample_added', actor_id=actor_id, detail={ 'sample_role': role, 'has_table_binding': sample.table_id is not None, @@ -1494,6 +1550,7 @@ def remove_profile_sample(profile_id: int, sample_id: int, *, actor_id: int | No sample_role = sample.sample_role db.session.delete(sample) db.session.flush() + _release_profile_sample_asset_if_unreferenced(profile.id, document_id) _refresh_training_sample_count(profile) clear_matching_signature_refs(profile, actor_id=actor_id, reason='sample_removed') _audit(profile_id=profile.id, document_id=document_id, event_type='profile_sample_removed', actor_id=actor_id, detail={ @@ -1668,7 +1725,9 @@ def refresh_profile_sample_readiness( # not merely a repeated read of the same frozen sample. sample.evidence_frozen_at = datetime.utcnow() if changed else sample.evidence_frozen_at sample.source_filename_snapshot = str(document.filename or '').strip() or None - sample.page_count_snapshot = _layout_page_count(version.payload_json or {}) + # [STEP 1] 页数必须来自已加载的完整坐标证据;持久化 payload 可能仅保留外置证据引用, + # 不能退化为“有业务表格的页数”。 + sample.page_count_snapshot = _layout_page_count(layout) sample.table_identity_snapshot = _layout_table_identity_snapshot(version.payload_json or {}, table_id) if changed: _audit( @@ -1860,7 +1919,8 @@ def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, fr sample.parser_version = str(layout_version.parser_version or '').strip() or None sample.evidence_frozen_at = frozen_at sample.source_filename_snapshot = str(document.filename or '').strip() or None - sample.page_count_snapshot = _layout_page_count(layout_version.payload_json or {}) + # [STEP 1] 发布冻结使用已加载的外置坐标证据,保证页数与原 PDF 物理页一致。 + sample.page_count_snapshot = _layout_page_count(hydrated_layout) sample.table_identity_snapshot = _layout_table_identity_snapshot( layout_version.payload_json or {}, sample.table_id, ) @@ -1914,7 +1974,8 @@ def _retain_frozen_sample_assets(profile: ShippingOrderDocumentProfile) -> int: 'Profile sample file asset is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', ) - mark_asset_referenced(asset) + if str(asset.lifecycle_status or '') == 'temporary' and int(asset.reference_count or 0) == 0: + mark_asset_referenced(asset) retained_asset_ids.add(asset_id) return len(retained_asset_ids) @@ -3217,9 +3278,12 @@ def create_draft_from_sample( profile_id=saved['id'], document_id=document.id, table_id=None, sample_role='annotation', created_by_id=actor_id, )) + db.session.flush() _audit(profile_id=saved['id'], document_id=document.id, event_type='profile_sample_added', actor_id=actor_id, detail={ 'sample_role': 'annotation', 'has_table_binding': False, }) + if document.asset_id: + _retain_profile_sample_assets(saved['id'], asset_ids={int(document.asset_id)}) db.session.commit() return saved @@ -3505,6 +3569,8 @@ def save_draft( # readiness audit records sample_id; assign it within this outer save transaction # before the shared evidence-freeze service is invoked. db.session.flush() + if annotation_document.asset_id: + _retain_profile_sample_assets(profile.id, asset_ids={int(annotation_document.asset_id)}) layout = _document_layout(annotation_document) if not any( isinstance(item, dict) and str(item.get('table_id') or '') == visual_main_table_id @@ -3945,6 +4011,9 @@ def create_schema_migration_draft( ) db.session.add(clone) db.session.flush() + # 迁移草稿会随源 Profile 拷贝标注/训练样本;新样本引用同一批文档资产, + # 必须为这些资产建立引用,避免它们被临时清理回收。 + copied_asset_ids: set[int] = set() for sample in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=source.id).all(): if sample.sample_role not in {'annotation', 'training'}: continue @@ -3955,6 +4024,11 @@ def create_schema_migration_draft( sample_role=sample.sample_role, created_by_id=actor_id, )) + document = db.session.get(ShippingOrderDocument, int(sample.document_id)) + if document is not None and document.asset_id: + copied_asset_ids.add(int(document.asset_id)) + db.session.flush() + _retain_profile_sample_assets(clone.id, asset_ids=copied_asset_ids) _refresh_training_sample_count(clone) # A migration is a new editable baseline, not a continuation of the source's revisions. # This keeps restore and publish-check workflows scoped to the target Schema snapshot. @@ -4095,6 +4169,7 @@ def publish( profile=profile, draft_checksum=draft_checksum, published_checksum=str(profile.checksum or ''), + actor_id=actor_id, ) profile.status = 'published' profile.published_by_id = actor_id @@ -4161,7 +4236,19 @@ def delete_draft(profile_id: int) -> None: db.session.delete(suite) if suites: db.session.flush() - # [STEP 3] ???? Profile ????????? DB CASCADE? + # [STEP 3] 删除 Profile 前释放其样本资产引用;同一资产在本 Profile 内只释放一次。 + asset_ids = { + int(document.asset_id) + for sample in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all() + if (document := db.session.get(ShippingOrderDocument, int(sample.document_id))) is not None and document.asset_id + } + for asset_id in asset_ids: + asset = db.session.get(FileAsset, asset_id) + if asset is not None and int(asset.reference_count or 0) > 0: + from app.services.file_assets.service import release_asset_reference + + release_asset_reference(asset) + # [STEP 4] ???? 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 b64338ad..d6af1881 100644 --- a/backend/app/services/shipping_notice/order_extraction.py +++ b/backend/app/services/shipping_notice/order_extraction.py @@ -49,7 +49,6 @@ from app.models import ( ShippingOrderDocument, ShippingOrderIntake, ShippingOrderTask, - ShippingNotice, ShippingOrderExtraction, ) from app.services.shipping_notice.business_fingerprint import ( @@ -503,9 +502,7 @@ def persist_order_extraction_result( if str(item.get('reason') or '') != 'layout_table_needs_review' ]) summary = {**dynamic['header'], 'lines': dynamic['lines']} - # Bill-to 是业务归属客户原文;简称只保存在 customer_matches 主数据快照中。 - if summary.get('bill_to_customer'): - summary['customer_name'] = summary['bill_to_customer'] + # Bill-to 仅保留为订单原文/识别证据,不复制为通用客户名称。 if dynamic['blocked_fields']: blocked_set = { str(code).strip() @@ -659,7 +656,6 @@ def persist_order_extraction_result( 'findings': list(dynamic.get('findings') or []), 'diagnostic_findings': diagnostic_findings, }, - 'customer_matches': dynamic['customer_matches'], 'missing_required_fields': assessment['missing_required_fields'], 'missing_process_fields': assessment['missing_process_fields'], 'process_issues': assessment['process_issues'], @@ -933,7 +929,7 @@ def persist_order_extraction_result( if not target_no: continue target = ( - db.session.query(ShippingNotice) + db.session.query(ShippingOrderTask) .filter_by(task_no=target_no, user_id=int(session.user_id)) .with_for_update() .first() @@ -1107,7 +1103,7 @@ def submit_order_extraction_run_result( } task_nos = sorted({ str(task.task_no) - for task in ShippingNotice.query.filter(ShippingNotice.id.in_(consumed_task_ids)).all() + for task in ShippingOrderTask.query.filter(ShippingOrderTask.id.in_(consumed_task_ids)).all() }) if consumed_task_ids else [] pending = [candidate for candidate in run_candidates if candidate.consumed_task_id is None] result = { @@ -1348,8 +1344,8 @@ def submit_order_extraction_unit_result( if consumed: task_nos = sorted({ str(task.task_no) - for task in ShippingNotice.query.filter( - ShippingNotice.id.in_([int(row.consumed_task_id) for row in consumed]) + for task in ShippingOrderTask.query.filter( + ShippingOrderTask.id.in_([int(row.consumed_task_id) for row in consumed]) ).all() }) result = { diff --git a/backend/app/services/shipping_notice/order_extraction_merge.py b/backend/app/services/shipping_notice/order_extraction_merge.py index bd8b4bca..275fefda 100644 --- a/backend/app/services/shipping_notice/order_extraction_merge.py +++ b/backend/app/services/shipping_notice/order_extraction_merge.py @@ -4,7 +4,7 @@ services/shipping_notice/order_extraction_merge.py 用途:在 HXOPS 内按稳定业务身份合并文档单元订单,并保留全部字段证据供后续裁决。 依赖:Run 冻结动态 Schema field_id/field_code 映射。 逻辑:同 Intake 下仅 PO 一致或 Line 的 part_number+reservation_id 一致时合并; - 跨文档 Reservation 补全优先使用 part_number / customer_po_line_no(兼容历史 line_no)。 + 跨文档 Reservation 补全优先使用 part_number / customer_po_line_no。 阶段 2:默认 keep_primary_documents_separate=True,不同 primary_document_id (多 PDF)不得合并为同一 Candidate;EML 内补充仍走 order_supplement_merge。 """ @@ -52,7 +52,7 @@ def _single_valid_reservation(line: dict[str, Any], codes: dict[str, str]) -> st def _completion_anchor_values(line: dict[str, Any], codes: dict[str, str]) -> dict[str, str]: """读取可用于 PDF/邮件行补全的强锚点;只接受单一原子值。""" anchors: dict[str, str] = {} - for field_code in ('part_number', 'customer_po_line_no', 'line_no'): + for field_code in ('part_number', 'customer_po_line_no'): values = _field_values(line.get('fields'), field_code, codes) if len(values) == 1: anchors[field_code] = next(iter(values)) @@ -104,11 +104,11 @@ def _order_identity(order: dict[str, Any], codes: dict[str, str]) -> tuple[set[s for value in _field_values(order.get('header_fields'), field_code, codes) if (normalized := normalize_atomic_po_number(value).upper()) } - line_keys = { + line_identities = { identity for line in order.get('lines') or [] if isinstance(line, dict) and (identity := _line_identity(line, codes)) is not None } - return po_numbers, line_keys + return po_numbers, line_identities def _merge_fields(target: list[dict[str, Any]], incoming: Any) -> None: @@ -196,7 +196,7 @@ def merge_unit_orders( order = copy.deepcopy(raw) intake_no = str(order.get('source_intake_no') or '').strip().upper() primary_document_id = order.get('primary_document_id') - po_numbers, line_keys = _order_identity(order, codes) + po_numbers, line_identities = _order_identity(order, codes) match = None matched_by_po = False for candidate in merged: @@ -212,7 +212,7 @@ def merge_unit_orders( continue candidate_pos, candidate_lines = _order_identity(candidate, codes) matched_by_po = len(po_numbers) == 1 and po_numbers == candidate_pos - if matched_by_po or bool(line_keys & candidate_lines): + if matched_by_po or bool(line_identities & candidate_lines): match = candidate break if match is None: diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index d3a1a077..303f29a4 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -372,7 +372,7 @@ def _coordinate_profile_rows( return None rows: list[dict[str, Any]] = [] runtime_region_ids = set(select_runtime_region_ids( - table_regions=[region.model_dump() for region in profile.table_regions], page_no=page_no, + table_regions=[_coordinate_object_mapping(region) for region in profile.table_regions], page_no=page_no, )) for region in profile.table_regions: # 标注页优先;续页仅回退到稳定的基础表区。是否真正属于明细页仍由当前页 @@ -385,7 +385,11 @@ def _coordinate_profile_rows( relative_region = _coordinate_region_mapping(region.region) if relative_region is None: return None - reference_page_frame = profile.reference_page_frames.get(page_no) + reference_page_frames = getattr(profile, 'reference_page_frames', {}) + reference_page_frame = ( + reference_page_frames.get(page_no) + if isinstance(reference_page_frames, dict) else None + ) reconstruction_page_bbox = ( { 'x0': 0, 'y0': 0, @@ -395,9 +399,10 @@ def _coordinate_profile_rows( ) raw_bbox = raw_table.get('bbox') if isinstance(raw_table.get('bbox'), dict) else None characters, _candidate_page_bbox = coordinate_profile_character_candidates( - table_region=region.region.model_dump(), page_size=page_size, + table_region=_coordinate_object_mapping(region.region), page_size=page_size, reference_page_frame=( - reference_page_frame.model_dump() if reference_page_frame is not None else None + _coordinate_object_mapping(reference_page_frame) + if reference_page_frame is not None else None ), page_characters=page_characters if isinstance(page_characters, list) else None, table_characters=tables.get(table_id) if isinstance(tables.get(table_id), list) else None, @@ -410,11 +415,11 @@ def _coordinate_profile_rows( carry = initial_carry if isinstance(initial_carry, dict) and initial_carry.get('region_id') == region.region_id else {} for reconstructed in reconstruct_coordinate_profile_rows( characters=[item for item in characters if isinstance(item, dict)], table_bbox=reconstruction_page_bbox, - line_layouts=[item.model_dump() for item in region.line_layouts], + line_layouts=[_coordinate_object_mapping(item) for item in region.line_layouts], table_region=relative_region, - termination_rules=[item.model_dump() for item in region.termination_rules], + termination_rules=[_coordinate_object_mapping(item) for item in region.termination_rules], exclusion_regions=reconstruction_exclusion_regions( - region.model_dump(), + _coordinate_object_mapping(region), ), initial_fields=carry.get('fields'), initial_next_offset=int(carry.get('next_offset') or 0), line_start_field_code=region.line_start_field_code, @@ -514,12 +519,7 @@ def _coordinate_region_mapping(value: Any) -> dict[str, float] | None: Returns: 包含 x0/y0/x1/y1 的合法浮点坐标;缺字段、非数值或区域退化时返回 None。 """ - if isinstance(value, dict): - raw = value - elif callable(getattr(value, 'model_dump', None)): - raw = value.model_dump() - else: - raw = {key: getattr(value, key, None) for key in ('x0', 'y0', 'x1', 'y1')} + raw = _coordinate_object_mapping(value) if not isinstance(raw, dict): return None try: @@ -531,6 +531,22 @@ def _coordinate_region_mapping(value: Any) -> dict[str, float] | None: return region +def _coordinate_object_mapping(value: Any) -> dict[str, Any]: + """将冻结坐标契约对象转换为字典,兼容 Pydantic 与测试使用的轻量对象。 + + 生产 Profile 使用 Pydantic ``model_dump``;运行时和回归测试也允许同字段的 + 轻量对象。转换失败返回空字典,后续既有坐标校验按证据不足处理,不扩大匹配范围。 + """ + if isinstance(value, dict): + return value + dump = getattr(value, 'model_dump', None) + if callable(dump): + raw = dump() + return raw if isinstance(raw, dict) else {} + raw = getattr(value, '__dict__', None) + return dict(raw) if isinstance(raw, dict) else {} + + def _coordinate_regions_overlap(left: dict[str, Any], right: dict[str, Any]) -> bool: """判断两个 PDF 绝对坐标区域是否有面积交集;无效坐标按不相交处理。""" try: @@ -881,20 +897,24 @@ def _profile_table_candidates( profile_match=profile_match, raw_profile=raw_profile, ) profile_table_regions = [ - item.model_dump() for item in profile.table_regions - if callable(getattr(item, 'model_dump', None)) + _coordinate_object_mapping(item) for item in profile.table_regions ] evidence_pages = ( (layout.get('coordinate_evidence') or {}).get('pages') or {} ) page_size = evidence_pages.get(str(raw_table.get('page_no') or 1)) - reference_page_frame = profile.reference_page_frames.get(int(raw_table.get('page_no') or 1)) + reference_page_frames = getattr(profile, 'reference_page_frames', {}) + reference_page_frame = ( + reference_page_frames.get(int(raw_table.get('page_no') or 1)) + if isinstance(reference_page_frames, dict) else None + ) if not _physical_table_targets_profile_region( raw_table=raw_table, table_regions=profile_table_regions, page_size=page_size if isinstance(page_size, dict) else None, reference_page_frame=( - reference_page_frame.model_dump() if reference_page_frame is not None else None + _coordinate_object_mapping(reference_page_frame) + if reference_page_frame is not None else None ), coordinate_transform=coordinate_transform, ): @@ -934,14 +954,17 @@ def _profile_table_candidates( except (TypeError, ValueError): issues.append('order_profile_snapshot_invalid') continue - if fixed_rows is None or adaptive_rows is None or dynamic_rows is None: - issues.append('order_profile_coordinate_reconstruction_unavailable') - continue + # 虚拟空页(无业务表)不能把已成功的目标表覆盖成失败;None 与空列表 + # 同样视为“无行”,且必须在该判断之前处理,否则空虚拟页会被 + # is None 分支误判为行重建失败而整单阻断。 if _virtual_page_without_rows_is_nonblocking( raw_table=raw_table, fixed_rows=fixed_rows, adaptive_rows=adaptive_rows, dynamic_rows=dynamic_rows, ): continue + if fixed_rows is None or adaptive_rows is None or dynamic_rows is None: + issues.append('order_profile_coordinate_reconstruction_unavailable') + continue strategy = resolve_runtime_parse_strategy( page_glyphs=(layout.get('coordinate_evidence') or {}).get('page_glyphs') or {}, fixed_rows=fixed_rows, adaptive_rows=adaptive_rows, diff --git a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py index 3f9c4c96..6a6b6b50 100644 --- a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py +++ b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py @@ -1317,7 +1317,13 @@ def _unresolved_review_document_count( def _current_non_terminal_review_cases(run: ShippingOrderProcessingRun) -> list[ShippingOrderReviewCase]: - """返回该 Run 产出的文件 Stream 当前非终态 Case;Run 的历史 Case 不参与工作台统计。""" + """返回该 Run 产出的文件 Stream 当前非终态 Case;Run 的历史 Case 不参与工作台统计。 + + 转瞬/未持久化 Run(id=None,如纯单元投影)不存在落库 Case,按空集处理, + 与 _duplicate_projection_by_document / _pending_order_facts 的 run.id 防空一致。 + """ + if getattr(run, 'id', None) is None: + return [] return ( db.session.query(ShippingOrderReviewCase) .join( diff --git a/backend/app/services/shipping_notice/order_field_purposes.py b/backend/app/services/shipping_notice/order_field_purposes.py index 7cae906b..6fcdf4b6 100644 --- a/backend/app/services/shipping_notice/order_field_purposes.py +++ b/backend/app/services/shipping_notice/order_field_purposes.py @@ -26,7 +26,10 @@ _PURPOSE_BY_CAPABILITY = { def task_line_purpose_field_ids(task: ShippingNotice, *, required: set[str] | None = None) -> dict[str, str]: """读取冻结策略能力与字段 ID,防止 Schema 或策略后续发布重解释任务。""" source_notice = _source_notice_for_order_facts(task) - snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None + from app.models import ShippingOrderTask + owner = db.session.get(ShippingOrderTask, source_notice.order_task_id) if getattr(source_notice, 'order_task_id', None) else source_notice + snapshot_id = getattr(owner, 'order_snapshot_id', None) + snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None if snapshot is None: raise ValueError('任务没有可用于履约的冻结订单快照') rule = (snapshot.rule_versions_json or {}).get('fulfillment_rule') diff --git a/backend/app/services/shipping_notice/order_freeze_service.py b/backend/app/services/shipping_notice/order_freeze_service.py index 4165b0a9..6f7e371a 100644 --- a/backend/app/services/shipping_notice/order_freeze_service.py +++ b/backend/app/services/shipping_notice/order_freeze_service.py @@ -2,10 +2,10 @@ services/shipping_notice/order_freeze_service.py 用途:将已复核的动态订单解析冻结为强类型履约快照。 -依赖:ShippingOrderExtraction/FieldValue/Observation、ShippingOrderSnapshot、ShippingNotice、 +依赖:ShippingOrderExtraction/FieldValue/Observation、ShippingOrderSnapshot、ShippingOrderTask、 standard_field_registry(投影列)、audit_service、统一 AppError。 逻辑:Candidate/Extraction 阶段可继续保留动态证据;本服务通过门禁后一次写入按 field_id 冻结的 Snapshot; - 冻结时固化 derivation_rules 快照与 field_lineage;库存、导出和上传后续阶段只读取该快照。 + 冻结时固化字段血缘;库存、导出和上传后续阶段只读取该快照。 """ from __future__ import annotations @@ -22,11 +22,10 @@ from app.models import ( ShippingOrderFieldObservation, ShippingOrderFieldValue, ShippingOrderLine, - ShippingOrderCustomerMatch, ShippingOrderReviewEvent, ShippingOrderSnapshot, ShippingOrderSnapshotLine, - ShippingNotice, + ShippingOrderTask, ShippingOrderDocument, ) from app.services.shipping_notice.audit_service import append_shipping_audit_event @@ -56,7 +55,7 @@ DATE_FIELDS = frozenset({'order_date', 'required_date', 'requested_receipt_date' def freeze_order_snapshot( - task: ShippingNotice, + task: ShippingOrderTask, *, actor_id: int | None, expected_order_data_version: int, @@ -88,9 +87,9 @@ def freeze_order_snapshot( # query 默认带 shipping_case 的 joinedload;PostgreSQL 不允许对外连接的空值端 # 执行 FOR UPDATE。仅锁定正式任务主表,避免冻结在已确认但关联 Case 可为空时失败。 locked_task = ( - ShippingNotice.query + ShippingOrderTask.query .filter_by(id=task.id) - .with_for_update(of=ShippingNotice) + .with_for_update(of=ShippingOrderTask) .one() ) if locked_task.order_snapshot_id: @@ -110,7 +109,7 @@ def freeze_order_snapshot( ) extraction = _accepted_extraction(task) policy, configs = _policy_configs(extraction) - customer_match = _confirmed_ordering_customer(extraction) + customer_resolution = _confirmed_ordering_customer(task) from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness assert_freeze_readiness( task=task, @@ -127,23 +126,11 @@ def freeze_order_snapshot( task_id=task.id, extraction_id=extraction.id, schema_version_id=extraction.schema_version_id, - customer_id=customer_match.customer_id, - customer_short_code_snapshot=customer_match.customer_short_code_snapshot, + customer_id=customer_resolution.confirmed_customer_id, + customer_short_code_snapshot=_confirmed_customer_short_code(customer_resolution), order_data_version=actual_version, rule_versions_json={ **dict(rule_versions or {}), - 'derivation_rules_snapshot': list( - ((extraction.schema_version.definition_json or {}) if extraction.schema_version else {}).get('derivation_rules') - or [] - ), - 'derivation_rules_checksum': ( - ((extraction.normalized_result_json or {}) if isinstance(extraction.normalized_result_json, dict) else {}).get( - 'derivation_rules_checksum' - ) - or ((extraction.schema_version.definition_json or {}) if extraction.schema_version else {}).get( - 'derivation_rules_checksum' - ) - ), 'fulfillment_rule': { 'code': policy['rule_code'], 'checksum': _fixed_rule_checksum(), @@ -151,12 +138,12 @@ def freeze_order_snapshot( 'required_field_ids': {code: config['field_id'] for code, config in configs.items()}, }, 'ordering_customer': { - 'match_id': customer_match.id, - 'identity_fingerprint': customer_match.identity_fingerprint, - 'identity_rule_version': customer_match.identity_rule_version, - 'resolution_method': customer_match.resolution_method, - 'confirmed_by_id': customer_match.confirmed_by_id, - 'confirmed_at': customer_match.confirmed_at.isoformat() if customer_match.confirmed_at else None, + 'resolution_id': customer_resolution.id, + 'identity_rule_set_checksum': customer_resolution.identity_rule_set_checksum, + 'identity_rule_set_version': customer_resolution.identity_rule_set_version, + 'confirmation_method': customer_resolution.confirmation_method, + 'confirmed_by_id': customer_resolution.confirmed_by_id, + 'confirmed_at': customer_resolution.confirmed_at.isoformat() if customer_resolution.confirmed_at else None, }, }, source_manifest_json={ @@ -174,17 +161,19 @@ def freeze_order_snapshot( ) db.session.add(snapshot) db.session.flush() - for position, source in enumerate(line_values): + for position, source in enumerate(line_values, start=1): + # 订单项次是系统项次,不采信客户 PO 行号或解析派生值;冻结后按本订单固定为 1..N。 + source = dict(source) + source['line_no'] = position db.session.add(ShippingOrderSnapshotLine( snapshot_id=snapshot.id, - position=position, + position=position - 1, field_values_json=_field_id_values(source, configs), **_project_values(source, LINE_FIELD_PROJECTIONS), )) db.session.flush() - from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot - - replace_notice_lines_from_snapshot(notice_id=int(task.id), snapshot=snapshot) + # Snapshot 只是冻结订单事实;ShippingNoticeLine 属于正式发货通知, + # 必须在库存确认通过或人工放行后创建,不能在冻结阶段提前生成。 task.order_snapshot_id = snapshot.id ShippingOrderReviewEvent.query.filter_by( task_id=task.id, @@ -202,13 +191,11 @@ def freeze_order_snapshot( result='success', metadata={ 'snapshot_id': snapshot.id, - 'derivation_rules_checksum': (snapshot.rule_versions_json or {}).get('derivation_rules_checksum'), 'schema_version_id': extraction.schema_version_id, }, after={ 'task_no': task.task_no, 'schema_version_id': extraction.schema_version_id, - 'derivation_rules_checksum': (snapshot.rule_versions_json or {}).get('derivation_rules_checksum'), }, ) db.session.flush() @@ -270,13 +257,13 @@ def _source_manifest(*, extraction: ShippingOrderExtraction, policy: Any) -> dic } -def assert_task_order_is_editable(task: ShippingNotice) -> None: +def assert_task_order_is_editable(task: ShippingOrderTask) -> None: """拒绝冻结后对 Candidate/Extraction 的任何直接编辑,防止快照与解析事实漂移。""" if task.order_snapshot_id: raise ConflictError('Frozen order snapshot cannot be edited', code='SHIPPING.ORDER_SNAPSHOT_FROZEN') -def _accepted_extraction(task: ShippingNotice) -> ShippingOrderExtraction: +def _accepted_extraction(task: ShippingOrderTask) -> ShippingOrderExtraction: """读取当前已接受 Extraction;冻结绝不回读旧版本或 Task JSON 投影。""" extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) if task.current_order_extraction_id else None if extraction is None or extraction.status != 'accepted': @@ -284,12 +271,14 @@ def _accepted_extraction(task: ShippingNotice) -> ShippingOrderExtraction: return extraction -def _confirmed_ordering_customer(extraction: ShippingOrderExtraction) -> ShippingOrderCustomerMatch: - """只接受已人工确认的 Bill-to 订购客户,禁止由冻结请求自由指定 customer_id。""" - row = ShippingOrderCustomerMatch.query.filter_by(extraction_id=extraction.id, role='bill_to').one_or_none() +def _confirmed_ordering_customer(task: ShippingOrderTask) -> Any: + """只接受正式客户识别结果,禁止由任一订单字段或冻结请求指定客户。""" + from app.services.shipping_notice.customer_resolution_service import resolution_for_task + + row = resolution_for_task(task) if ( - row is None or row.status != 'confirmed' or row.customer_id is None - or not row.customer_short_code_snapshot or not row.identity_fingerprint or not row.identity_rule_version + row is None or row.status != 'confirmed' or row.confirmed_customer_id is None + or not row.evidence_json or not row.identity_rule_set_checksum ): raise ValidationError( 'Ordering customer must be confirmed before freezing', @@ -298,6 +287,14 @@ def _confirmed_ordering_customer(extraction: ShippingOrderExtraction) -> Shippin return row +def _confirmed_customer_short_code(resolution: Any) -> str: + """从已确认标准客户读取简称;订单原文和 bill_to 不得提供业务简称。""" + from app.models import ShippingCustomer + + customer = db.session.get(ShippingCustomer, int(resolution.confirmed_customer_id)) + return str(getattr(customer, 'short_code', None) or '') + + def _policy_configs(extraction: ShippingOrderExtraction) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]: """按固定履约契约验证冻结字段,Schema 仅承担字段目录职责。""" from app.services.shipping_notice.fulfillment_policy_registry import ( diff --git a/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py b/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py index 3e21cfdd..30dcc415 100644 --- a/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py +++ b/backend/app/services/shipping_notice/order_review_auto_progress_coordinator.py @@ -5,10 +5,10 @@ services/shipping_notice/order_review_auto_progress_coordinator.py 依赖:order_review_customer_service、order_review_draft_service(延迟)、 order_stp_auto_create_service(延迟)、candidate_qualification_service、 fulfillment_audit、ShippingCustomerShadowResolution / - ShippingOrderCustomerMatch / ShippingOrderReviewCase / ShippingOrderProcessingRun。 + ShippingOrderReviewCase / ShippingOrderProcessingRun。 逻辑:提供 Run 级批量协调(reconcile_run_review_cases_for_auto_progress)和 单 Case 级协调(reconcile_single_case_for_auto_progress)两层入口; - 客户协调仅在 shadow.status=unique_candidate 且未 resolve 时自动确认 bill_to; + 客户协调仅在识别结果唯一命中且未确认时自动确认客户; 所有入口均不主动 commit,由调用方统一控制事务;Run 级循环单 Case 异常局部 rollback。 注意:order_stp_auto_create_service 与 order_review_draft_service 均不在顶层 import, 避免 circular import(stp 末尾顶层 import 本模块,draft 顶层 import 本模块)。 @@ -23,19 +23,15 @@ from app import db from app.models import ( ShippingCustomerShadowResolution, ShippingOrderCandidate, - ShippingOrderCustomerMatch, ShippingOrderProcessingRun, ShippingOrderReviewCase, ShippingOrderReviewStream, ) from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit from app.services.shipping_notice.order_review_customer_service import ( - _header_from_case, - _resolve_extraction_for_case, - confirm_order_customer_match, - refresh_order_customer_matches, resolve_review_case_customer_resolved, ) +from app.services.shipping_notice.customer_resolution_service import confirm_customer_resolution from app.services.shipping_notice.recovery_contract import build_review_revalidate_job_ref # 注意:validate_draft 与 ensure_stp_auto_create_for_case 均不在顶层 import, @@ -73,7 +69,7 @@ def _customer_step_for_case( trigger: str, ) -> tuple[str, dict[str, Any] | None]: """ - 单 Case 客户协调内部步骤:shadow 唯一命中时自动确认 bill_to。 + 单 Case 客户协调内部步骤:识别结果唯一命中时自动确认客户。 Args: case: 复核 Case。 @@ -105,45 +101,20 @@ def _customer_step_for_case( if already_resolved: return 'skipped', {'reason': 'customer_already_resolved'} - # [STEP 1-3] 提取 order_extraction(Candidate 关联优先,否则 Run 内最新) - extraction = _resolve_extraction_for_case(case) - if extraction is None: - return 'failed', {'reason': 'extraction_missing'} - - # [STEP 1-4] 若无 bill_to match 行,先按当前头字段刷新 - bill_to_exists = ( - ShippingOrderCustomerMatch.query - .filter_by(extraction_id=int(extraction.id), role='bill_to') - .first() - is not None - ) - if not bill_to_exists: - try: - refresh_order_customer_matches(extraction, _header_from_case(case)) - except Exception as exc: # noqa: BLE001 - _LOGGER.warning( - 'refresh_order_customer_matches failed case_no=%s err=%s', - case.case_no, str(exc)[:200], - ) - return 'failed', {'reason': 'refresh_matches_failed', 'error': str(exc)[:200]} - - # [STEP 1-5] 自动确认 bill_to 到 top_customer_id + # [STEP 1-3] 将唯一指纹候选确认到正式识别结果;不创建或读取订单角色投影。 top_customer_id = int(shadow.top_customer_id) confirm_reason = '抽取协调器-客户指纹唯一命中自动确认' try: - confirm_order_customer_match( - int(extraction.id), - role='bill_to', + confirm_customer_resolution( + candidate, customer_id=top_customer_id, - site_id=None, actor_id=None, + method='auto_rule', reason=confirm_reason, - # 保存校验入口需将客户确认、Draft 校验与后续 Gate/STP 写入作为同一事务提交。 - commit=False, ) except Exception as exc: # noqa: BLE001 _LOGGER.warning( - 'confirm_order_customer_match failed case_no=%s err=%s', + 'confirm_customer_resolution failed case_no=%s err=%s', case.case_no, str(exc)[:200], ) return 'failed', {'reason': 'confirm_match_failed', 'error': str(exc)[:200]} @@ -165,7 +136,7 @@ def _customer_step_for_case( 'candidate_id': int(candidate.id) if candidate is not None else None, 'shadow_status': 'unique_candidate', 'customer_id': top_customer_id, - 'extraction_id': int(extraction.id), + 'extraction_id': getattr(candidate, 'order_extraction_id', None), 'trigger': str(trigger)[:64], 'reason': confirm_reason, }, @@ -177,7 +148,7 @@ def _customer_step_for_case( return 'auto_confirmed', { 'customer_id': top_customer_id, - 'extraction_id': int(extraction.id), + 'extraction_id': getattr(candidate, 'order_extraction_id', None), } @@ -397,7 +368,7 @@ def reconcile_run_review_cases_for_auto_progress( }) continue - # [STEP 1 客户协调] shadow unique_candidate 且未 resolve → 自动确认 bill_to + # [STEP 1 客户协调] shadow unique_candidate 且未 resolve → 自动确认标准客户 customer_status, customer_meta = _customer_step_for_case( case=case, trigger='run_reconcile', ) diff --git a/backend/app/services/shipping_notice/order_review_confirmation_service.py b/backend/app/services/shipping_notice/order_review_confirmation_service.py index 7ce8d332..80b541f7 100644 --- a/backend/app/services/shipping_notice/order_review_confirmation_service.py +++ b/backend/app/services/shipping_notice/order_review_confirmation_service.py @@ -3,21 +3,20 @@ backend/app/services/shipping_notice/order_review_confirmation_service.py 用途:按 PDF 确认复核草稿并独立创建发货任务,确认后复用同一 auto_progress 链。 依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、order_task_service、 - stp_inventory_freeze、progress_audit_contract.ORDER_CREATE_REQUIRES_RESOLVED_INVENTORY_SOURCE、 candidate_qualification_service、customer_auto_resolution、fulfillment_audit、 order_review_progress_bridge、workflow_ledger_service、 queue_service.enqueue_shipping_notice_job、process_gate_bridge。 -逻辑:确认在单事务内分别锁定 Case 与 Draft,重跑资格门禁,冻结行级库存源候选与 - 可自动确认的客户;库存源未唯一确定时按硬门禁拒绝建单并回写 OT stage= - inventory_source_resolving;物化人工 Candidate 时先写入客户已确认事实再执行履约门禁; +逻辑:确认在单事务内分别锁定 Case 与 Draft,重跑资格门禁,固化可自动确认的客户; + 物化人工 Candidate 时先写入客户已确认事实再执行履约门禁; 确认建单前锁定 case.candidate_id 对应 OT:未消费 OT 受控换绑人工 Candidate; 已消费 OT 保留历史并为后续波次创建稳定子 OT;同步 Case 当前 Candidate; 缺 OT 则 fail-closed 回滚;禁止 upsert 到 Run 根号串单; - 物化 accepted Extraction(保留派生 field_lineage);建单前再次校验客户确认并 + 物化 accepted Extraction(保留字段 field_lineage);建单前再次校验客户确认并 持久化 Candidate Qualification 快照;客户未确认拒绝建单;同 Case 既有波次 Task 豁免精确文件哈希重复检查;波次行写入不可变 wave_lines 唯一约束; 新建 Task 完成客户绑定后立即冻结订单快照;冻结失败时整笔确认回滚,禁止把无快照 - Task 推入库存/RPA; + Task 推入库存/RPA。库存源候选的裁决/冻结不在确认流程内,由确认后 OT 进入的 + 正式 inventory_source_routing Gate 负责; 成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至 building_order(不关闭);同步 Process Execution 推进至 task_creation 通过, 避免重复冻结资格阻断;与确认同事务入队 shipping_notice_run(待推进 Outbox), @@ -50,8 +49,7 @@ from app.models import ( ShippingOrderReviewConfirmedRevision, ShippingOrderReviewDraft, ShippingOrderReviewWaveLine, - ShippingOrderCustomerMatch, - ShippingNotice, + ShippingOrderTask, ) from app.services.shipping_notice.batch_create_idempotency import ( acquire_notice_create_locks, @@ -68,9 +66,6 @@ from app.services.shipping_notice.order_review_draft_service import ( build_confirmable_draft_summary, draft_has_unaccepted_llm_suggestions, ) -from app.services.shipping_notice.progress_audit_contract import ( - ORDER_CREATE_REQUIRES_RESOLVED_INVENTORY_SOURCE, -) from app.services.shipping_notice.order_review_projection import serialize_review_case from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition @@ -221,13 +216,12 @@ def _json_value(value: Any) -> Any: def _source_extraction_lineage(case: ShippingOrderReviewCase) -> tuple[list[dict[str, Any]], str | None]: """ - 读取机器解析 Extraction / Unit 上的派生血缘与规则校验和。 + 读取机器解析 Extraction / Unit 上的字段血缘。 核心逻辑:优先 Candidate.order_extraction_id → normalized_result_json; 否则回退 Unit.result_json。供确认物化 Extraction 写入冻结可追溯快照。 """ rows: list[dict[str, Any]] = [] - checksum: str | None = None candidate = db.session.get(ShippingOrderCandidate, case.candidate_id) if case.candidate_id else None extraction_id = getattr(candidate, 'order_extraction_id', None) if candidate is not None else None if extraction_id: @@ -236,17 +230,9 @@ def _source_extraction_lineage(case: ShippingOrderReviewCase) -> tuple[list[dict extraction.normalized_result_json, dict, ) else {} rows = [item for item in (normalized.get('field_lineage') or []) if isinstance(item, dict)] - raw_checksum = normalized.get('derivation_rules_checksum') - checksum = str(raw_checksum) if raw_checksum else None - if not checksum and extraction is not None and extraction.schema_version is not None: - definition = extraction.schema_version.definition_json or {} - if isinstance(definition, dict) and definition.get('derivation_rules_checksum'): - checksum = str(definition.get('derivation_rules_checksum')) if not rows and case.unit is not None and isinstance(case.unit.result_json, dict): rows = [item for item in (case.unit.result_json.get('field_lineage') or []) if isinstance(item, dict)] - if not checksum and case.unit.result_json.get('derivation_rules_checksum'): - checksum = str(case.unit.result_json.get('derivation_rules_checksum')) - return rows, checksum + return rows, None def _confirmation_field_lineage( @@ -255,64 +241,38 @@ def _confirmation_field_lineage( summary_lines: list[dict[str, Any]], ) -> tuple[list[dict[str, Any]], str | None]: """ - 将源解析血缘按行位映射到确认后 Extraction 的 review-* line_key。 + 将源解析血缘按行位映射到确认后 Extraction 的 draft_line_id。 - 核心逻辑:按草稿行顺序对齐;若该行 line_no 已被人工覆盖,则改写为 manual_override 血缘。 + 核心逻辑:按草稿行顺序对齐字段血缘;系统项次不参与人工覆盖。 """ source_rows, checksum = _source_extraction_lineage(case) draft_lines = [ item for item in (case.current_draft.lines_json or []) if isinstance(item, dict) ] - line_no_field_id = None - run = case.run - definition = ( - (run.input_snapshot_json or {}).get('schema', {}).get('definition', {}) - if run is not None and isinstance(run.input_snapshot_json, dict) else {} - ) - for item in definition.get('fields') or []: - if ( - isinstance(item, dict) - and str(item.get('field_code') or '') == 'line_no' - and str(item.get('scope') or '') == 'line' - ): - line_no_field_id = str(item.get('field_id') or '') or None - break - by_key: dict[str, list[dict[str, Any]]] = {} for item in source_rows: - key = str(item.get('line_key') or '').strip() + key = str(item.get('draft_line_id') or '').strip() if key: by_key.setdefault(key, []).append(item) ordered_keys: list[str] = [] for item in source_rows: - key = str(item.get('line_key') or '').strip() + key = str(item.get('draft_line_id') or '').strip() if key and key not in ordered_keys: ordered_keys.append(key) remapped: list[dict[str, Any]] = [] for position, draft_line in enumerate(draft_lines): new_key = f'review-{position + 1}' - old_key = str(draft_line.get('line_key') or '').strip() + old_key = str(draft_line.get('draft_line_id') or '').strip() source_items = list(by_key.get(old_key) or []) if not source_items and position < len(ordered_keys): source_items = list(by_key.get(ordered_keys[position]) or []) - values = draft_line.get('values') if isinstance(draft_line.get('values'), dict) else {} - override_entry = values.get(line_no_field_id) if line_no_field_id else None - line_no_overridden = ( - isinstance(override_entry, dict) - and str(override_entry.get('source') or '') == 'manual_override' - ) - summary_line = summary_lines[position] if position < len(summary_lines) else {} for item in source_items: row = dict(item) - row['line_key'] = new_key - if str(row.get('field_code') or '') == 'line_no' and line_no_overridden: - row['value_source'] = 'manual_override' - row['after_value'] = summary_line.get('line_no') - row['skip_reason'] = None + row['draft_line_id'] = new_key remapped.append(row) return remapped, checksum @@ -325,23 +285,16 @@ def _build_confirmation_normalized_result( """ 组装确认后 Extraction.normalized_result_json。 - 核心逻辑:保留确认摘要的 header/lines,并附加源解析 field_lineage 与派生规则校验和, - 供冻结快照写入可追溯项次派生来源。 + 核心逻辑:保留确认摘要的 header/lines,并附加源解析 field_lineage, + 供冻结快照写入可追溯字段来源。 """ header_values = {key: value for key, value in summary.items() if key != 'lines'} lines = [dict(item) for item in (summary.get('lines') or []) if isinstance(item, dict)] - lineage, checksum = _confirmation_field_lineage(case, summary_lines=lines) - if not checksum and case.current_draft is not None: - from app.models import ShippingOrderSchemaVersion - version = db.session.get(ShippingOrderSchemaVersion, int(case.current_draft.schema_version_id)) - definition = (version.definition_json or {}) if version is not None else {} - if isinstance(definition, dict) and definition.get('derivation_rules_checksum'): - checksum = str(definition.get('derivation_rules_checksum')) + lineage, _checksum = _confirmation_field_lineage(case, summary_lines=lines) return { 'header': header_values, 'lines': lines, 'field_lineage': lineage, - 'derivation_rules_checksum': checksum, } @@ -363,9 +316,9 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su for item in configs if str(item.get('scope') or '') == 'line' and item.get('field_code') } - # `line_key` is Draft-only identity used by wave selection and lineage remapping. + # `draft_line_id` is Draft-only identity used by wave selection and lineage remapping. # It is not a Schema business field and must never be materialized as one. - internal_line_fields = {'line_key'} + internal_line_fields = {'draft_line_id'} unknown_line_fields = sorted({ str(key) for line in summary.get('lines') or [] @@ -413,7 +366,12 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su **_field_value_columns(value, str(config.get('value_type') or 'string')), )) for position, values in enumerate(summary.get('lines') or []): - line = ShippingOrderLine(extraction_id=int(extraction.id), position=position, line_key=f'review-{position + 1}') + line = ShippingOrderLine( + extraction_id=int(extraction.id), + position=position, + line_no=position + 1, + draft_line_id=f'review-{position + 1}', + ) db.session.add(line) db.session.flush() for config in configs: @@ -433,59 +391,33 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su extraction_id=int(extraction.id), line_id=int(line.id), field_id=field_id, decision_id=int(decision.id), **_field_value_columns(value, str(config.get('value_type') or 'string')), )) - _inherit_confirmed_customer_match(case=case, extraction=extraction) + _inherit_confirmed_customer_resolution(case=case, extraction=extraction) return extraction -def _inherit_confirmed_customer_match( +def _inherit_confirmed_customer_resolution( *, case: ShippingOrderReviewCase, extraction: ShippingOrderExtraction, ) -> None: """ - 把当前 Case 原 Extraction 已确认的 Bill-to 客户复制到人工确认 Extraction。 + 人工确认产生新 Extraction 时保留同一 Candidate 的正式客户识别确认事实。 - 核心逻辑:仅复制当前 PDF Candidate 的 confirmed Bill-to 行;没有确认事实时保持空, - 后续建单前客户门禁仍会 fail-closed。 + 核心逻辑:客户识别结果通过 Candidate 稳定关联,不复制或伪造 bill_to 角色行; + 新 Extraction 只改变订单字段版本,后续 Gate 继续读取该 Candidate 的确认结果。 Args: case: 当前复核 Case。 extraction: 新建的人工确认 Extraction。 """ + del extraction if not case.candidate_id: return - source_candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) - source_extraction_id = getattr(source_candidate, 'order_extraction_id', None) if source_candidate else None - if source_extraction_id is None: + from app.services.shipping_notice.customer_resolution_service import resolution_for_task + + resolution = resolution_for_task(db.session.get(ShippingOrderCandidate, int(case.candidate_id))) + if resolution is not None and resolution.status == 'confirmed': return - source = ShippingOrderCustomerMatch.query.filter_by( - extraction_id=int(source_extraction_id), - role='bill_to', - status='confirmed', - ).first() - if source is None or source.customer_id is None: - return - db.session.add(ShippingOrderCustomerMatch( - extraction_id=int(extraction.id), - role='bill_to', - raw_name=source.raw_name, - normalized_name=source.normalized_name, - source_system=source.source_system, - external_code=source.external_code, - identity_fingerprint=source.identity_fingerprint, - identity_rule_version=source.identity_rule_version, - identity_components_json=copy.deepcopy(source.identity_components_json or {}), - status='confirmed', - customer_id=int(source.customer_id), - site_id=int(source.site_id) if source.site_id is not None else None, - customer_name_snapshot=source.customer_name_snapshot, - customer_short_code_snapshot=source.customer_short_code_snapshot, - candidates_json=copy.deepcopy(source.candidates_json or []), - resolution_method=source.resolution_method or 'review_case_inherited', - confirmation_reason=source.confirmation_reason, - confirmed_by_id=source.confirmed_by_id, - confirmed_at=source.confirmed_at or datetime.utcnow(), - )) def _workflow_refs_for_case(case: ShippingOrderReviewCase) -> dict[str, str | None]: @@ -729,6 +661,59 @@ def _audit_idempotent_confirmation_replay( ) +def _inherit_confirmed_customer_resolution_onto_candidate( + candidate: ShippingOrderCandidate, + case: ShippingOrderReviewCase, +) -> None: + """review_case 人工确认时,把源机器 Candidate 的正式客户确认事实挂到新确认候选上。 + + review_case 确认会新建独立 ShippingOrderCandidate(candidate_key=review-confirm-*), + 但客户识别结果按 Candidate 关联稳定存放;新候选若不继承源候选的 confirmed resolution, + 后续 assert_customer_confirmed_before_task_create / resolve_confirmed_customer_id 按 + 新 candidate_id 查表为空,会误拒"已确认客户"无法建单。 + """ + if not case.candidate_id: + return + source = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) + from app.services.shipping_notice.customer_resolution_service import resolution_for_task + + source_resolution = resolution_for_task(source) if source is not None else None + if ( + source_resolution is None + or source_resolution.status != 'confirmed' + or source_resolution.confirmed_customer_id is None + ): + return + from app.models import ShippingCustomerShadowResolution + + row = db.session.query(ShippingCustomerShadowResolution).filter_by( + candidate_id=int(candidate.id), + ).one_or_none() + if row is None: + row = ShippingCustomerShadowResolution( + candidate_id=int(candidate.id), intake_id=int(candidate.intake_id), + ) + db.session.add(row) + row.identity_rule_set_id = source_resolution.identity_rule_set_id + row.identity_rule_set_version = source_resolution.identity_rule_set_version + row.identity_rule_set_checksum = source_resolution.identity_rule_set_checksum + row.order_schema_version_id = source_resolution.order_schema_version_id + row.resolution_version = source_resolution.resolution_version + row.status = 'confirmed' + # [STEP] 完整复制源候选的正式识别证据与候选匹配快照:review_case 确认的新候选 + # 必须携带可审计的客户识别事实,否则 freeze(_confirmed_ordering_customer 要求 + # evidence_json 非空)会把"已确认客户"误判为未确认而冻结失败。 + row.evidence_json = list(source_resolution.evidence_json or []) + row.candidate_matches_json = list(source_resolution.candidate_matches_json or []) + row.resolution_context_json = dict(source_resolution.resolution_context_json or {}) + row.confirmed_customer_id = source_resolution.confirmed_customer_id + row.confirmation_method = source_resolution.confirmation_method or 'review_case_confirmed' + row.confirmed_by_id = int(candidate.accepted_by_id) if candidate.accepted_by_id is not None else None + row.confirmed_at = datetime.utcnow() + row.top_customer_id = source_resolution.top_customer_id + row.top_score = source_resolution.top_score + + def _create_review_candidate( *, case: ShippingOrderReviewCase, @@ -786,6 +771,11 @@ def _create_review_candidate( ) db.session.add(candidate) db.session.flush() + # [STEP] review_case 人工确认:把继承的正式客户确认事实落到 resolution 表, + # 否则按新 candidate_id 查表为空,assert_customer_confirmed_before_task_create / + # resolve_confirmed_customer_id 会误拒"已确认客户"无法建单。 + if customer_confirmed: + _inherit_confirmed_customer_resolution_onto_candidate(candidate, case) asset = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None # [STEP] 同 Case 既有波次不参与 Candidate 级 exact_file / 指纹阻断。 prior_wave_task_ids = _prior_wave_task_ids_for_case(case) @@ -872,8 +862,8 @@ def _prior_wave_task_ids_for_case(case: ShippingOrderReviewCase) -> set[int]: def _persist_wave_lines_for_task( *, case: ShippingOrderReviewCase, - task: ShippingNotice, - line_keys: list[str], + task: ShippingOrderTask, + snapshot_line_ids: list[int], wave_no: int, revision_id: int | None, ) -> None: @@ -882,8 +872,8 @@ def _persist_wave_lines_for_task( Args: case: 复核 Case。 - task: 本波次新建的 Notice。 - line_keys: 本波次完整行键。 + task: 本波次复核确认生成的 OT。 + snapshot_line_ids: 本波次冻结订单行 ID。 wave_no: 波次序号(从 1 起)。 revision_id: 可选确认修订 ID。 @@ -892,10 +882,10 @@ def _persist_wave_lines_for_task( """ from sqlalchemy.exc import IntegrityError - for key in line_keys: + for snapshot_line_id in snapshot_line_ids: db.session.add(ShippingOrderReviewWaveLine( review_case_id=int(case.id), - line_key=str(key), + snapshot_line_id=int(snapshot_line_id), task_id=int(task.id), wave_no=int(wave_no), confirmed_revision_id=int(revision_id) if revision_id is not None else None, @@ -906,31 +896,20 @@ def _persist_wave_lines_for_task( raise ConflictError( 'Line already belongs to another fulfillment wave', code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK', - details={'line_keys': list(line_keys)}, + details={'snapshot_line_ids': [int(item) for item in snapshot_line_ids]}, ) from exc -def _order_task_no_for_notice(notice: ShippingNotice | None) -> str | None: - """ - 从已建 Notice 解析挂接的 OT 编号(幂等回放用)。 +def _order_task_no_for_notice(notice: ShippingOrderTask | None) -> str | None: + """返回 OT 自身编号(保留函数名仅用于本模块内部整理)。 Args: - notice: 发货 Notice;None 时返回 None。 + notice: OT;None 时返回 None。 Returns: order_task.task_no;未挂接时 None。 """ - if notice is None: - return None - order_task_id = getattr(notice, 'order_task_id', None) - if order_task_id is None: - return None - from app.models import ShippingOrderTask - - order_task = db.session.get(ShippingOrderTask, int(order_task_id)) - if order_task is None: - return None - return str(order_task.task_no or '').strip() or None + return str(getattr(notice, 'task_no', None) or '').strip() or None if notice is not None else None def _confirmation_result_payload( @@ -958,7 +937,7 @@ def _confirmation_result_payload( """ payload: dict[str, Any] = { 'task_no': task_no, - 'shipping_notice_no': task_no, + 'shipping_notice_no': None, 'order_task_no': order_task_no, 'idempotent_replay': idempotent_replay, 'case': serialize_review_case(case), @@ -969,7 +948,7 @@ def _confirmation_result_payload( return payload -def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: Any, idempotency_key: str | None, warning_acknowledgements: Any = None, confirm_note: str | None = None, line_keys: list[str] | None = None) -> dict[str, Any]: +def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: Any, idempotency_key: str | None, warning_acknowledgements: Any = None, confirm_note: str | None = None) -> dict[str, Any]: """ 确认一个 PDF 草稿并建一张无 Batch 的 Task;门禁拒绝写统一审计后抛错。 @@ -979,7 +958,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A 幂等回放(同键或已确认 Case)同样写审计(result=ignored),追溯重复提交。 版本冲突/校验失败/文档不可用/重复订单等拒绝写 result=rejected,并在 raise 前独立 commit。 锁定 Case 之前的边界拒绝(缺幂等键、警告格式非法、幂等键跨 Case 占用)在 Case 可定位时同样写拒绝审计。 - 可选 line_keys:仅冻结选中的完整明细行(履约波次);若 Case 仍有开放行则保持 ready 不终态确认。 + 确认订单恒为整单确认(业务规则:确认订单不可分行;仅“产生发货通知”可分波次)。 Args: user_id: Case 属主用户 ID。 @@ -988,7 +967,6 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A idempotency_key: 建单幂等键。 warning_acknowledgements: 警告确认列表。 confirm_note: 可选确认备注,写入审计 metadata。 - line_keys: 可选履约波次行键;None 表示整单草稿行。 Returns: 含 shipping_notice_no / task_no / order_task_no / case / workflow_id / trigger_auto_progress 的确认结果。 @@ -1028,7 +1006,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A ), idempotency_key=key, ) - task = db.session.get(ShippingNotice, int(replay.task_id)) + task = db.session.get(ShippingOrderTask, int(replay.task_id)) task_no = task.task_no if task else None _audit_idempotent_confirmation_replay( user_id=user_id, @@ -1044,9 +1022,9 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A idempotent_replay=True, ) case = _locked_case(user_id=user_id, case_no=case_no, idempotency_key=key) - # 整单已终态确认时幂等回放;履约波次在 Case 仍为 ready 时可继续建后续 Task。 - if case.status == 'confirmed' and case.confirmed_task_id and not line_keys: - task = db.session.get(ShippingNotice, int(case.confirmed_task_id)) + # 整单已终态确认时幂等回放(确认订单恒为整单,不存在按行波次的中间态)。 + if case.status == 'confirmed' and case.confirmed_task_id: + task = db.session.get(ShippingOrderTask, int(case.confirmed_task_id)) task_no = task.task_no if task else None _audit_idempotent_confirmation_replay( user_id=user_id, @@ -1073,76 +1051,12 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A idempotency_key=key, metadata={'expected_draft_version': expected}, ) - wave_keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()] or None - # [STEP] 波次行唯一归属:在建 Task 前 fail-closed,避免 IntegrityError 半成品。 - if wave_keys is not None: - already = ( - ShippingOrderReviewWaveLine.query - .filter( - ShippingOrderReviewWaveLine.review_case_id == int(case.id), - ShippingOrderReviewWaveLine.line_key.in_(list(wave_keys)), - ) - .all() - ) - if already: - _reject_confirmation( - case, - actor_id=int(user_id), - error=ConflictError( - 'Line already belongs to another fulfillment wave', - code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK', - details={'line_keys': [str(row.line_key) for row in already]}, - ), - idempotency_key=key, - case_no=str(case_no), - owner_user_id=int(user_id), - ) - summary, validation = build_confirmable_draft_summary(case, line_keys=wave_keys) - # [STEP] 建单硬门禁:库存源未唯一确定时禁止创建正式订单,并回写 OT stage。 - if ORDER_CREATE_REQUIRES_RESOLVED_INVENTORY_SOURCE: - inventory_issues = [ - item - for item in (validation.get('issues') or []) - if isinstance(item, dict) - and str(item.get('owning_gate_code') or '') == 'inventory_source_routing' - and str(item.get('severity') or '') == 'blocking' - ] - if inventory_issues: - from app.services.shipping_notice.order_task_service import ( - resolve_order_task_for_candidate, - sync_order_task_processing_state, - ) - - blocked_ot = resolve_order_task_for_candidate( - int(case.candidate_id) if case.candidate_id else None - ) - if blocked_ot is not None: - sync_order_task_processing_state( - blocked_ot, - stage='inventory_source_resolving', - status='blocked', - ) - primary = inventory_issues[0] - _reject_confirmation( - case, - actor_id=int(user_id), - error=ConflictError( - 'Inventory source must be uniquely resolved before creating a formal order', - code='SHIPPING.REVIEW_INVENTORY_SOURCE_UNRESOLVED', - details={ - 'issues': inventory_issues, - 'blocking_reason_code': str( - primary.get('code') or 'no_inventory_source_candidates' - ), - 'owning_gate_code': 'inventory_source_routing', - }, - ), - idempotency_key=key, - metadata={ - 'validation_status': str(validation.get('status') or '')[:32] or None, - 'gate_code': 'inventory_source_routing', - }, - ) + # [STEP] 确认订单恒为整单:build_confirmable_draft_summary 不接受 draft_line_ids, + # 确认时要求整单全部行通过校验(业务规则:确认订单不可分行)。 + summary, validation = build_confirmable_draft_summary(case) + # [STEP] 硬门禁已移除:确认流程只确认订单信息(订单字段/客户/订单快照)。 + # 库存源候选的裁决/冻结由确认后 OT 进入的正式 inventory_source_routing Gate 负责, + # 不再要求确认时库存源已唯一确定。 if draft_has_unaccepted_llm_suggestions(case): _reject_confirmation( case, @@ -1204,7 +1118,6 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A before_snap = {'status': previous_status, 'disposition': previous_disposition} # [BE-01/BE-02] 人工 Candidate 物化前锁定 Case 原 Candidate 对应 OT,禁止事后落到 Run 根号。 from app.services.shipping_notice.order_task_service import ( - link_notice_to_order_task, replace_order_task_candidate_after_review, resolve_order_task_for_candidate, upsert_order_task_from_run, @@ -1230,17 +1143,19 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A ) try: assert_case_is_current_workflow_version(case=case) - # [STEP] 建单前再次校验客户确认(相对 Draft 校验时刻防并发回退)。 + # [STEP] 建单前解析唯一客户(读机器候选 resolution,一次完成门户校验 + 取主键)。 + # 机器候选是客户识别事实的权威来源:没有唯一已确认主键即拒绝建单。 from app.services.shipping_notice.candidate_qualification_service import ( recalculate_candidate_qualification, - resolve_review_case_customer_resolved, + resolve_confirmed_customer_id, ) pre_candidate = ( db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None ) - if not resolve_review_case_customer_resolved(case=case, candidate=pre_candidate): + bind_customer_id = resolve_confirmed_customer_id(candidate=pre_candidate) + if bind_customer_id is None: raise ConflictError( 'Customer is not confirmed', code='SHIPPING.REVIEW_CUSTOMER_UNRESOLVED', @@ -1287,7 +1202,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A ) # [BE-01/BE-02] 复用锁定 OT;无原 Candidate 时才按人工 Candidate 新建 OT。 try: - if locked_order_task is not None and locked_order_task.shipping_notice_id is None: + if locked_order_task is not None: order_task = replace_order_task_candidate_after_review( order_task=locked_order_task, previous_candidate_id=source_candidate_id, @@ -1356,69 +1271,34 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A ) # [BE-06] Notice 创建及挂接后的消费/客户绑定失败须 fail-closed 回滚。 try: - task = ShippingNotice( - task_no=generate_task_no(), user_id=int(user_id), - conversation_id=case.run.conversation_id, source_type='review_confirmation', source_file_name=document.filename, - source_file_type=asset.mime_type if asset else None, source_content_hash=document.content_hash, - source_asset_id=document.asset_id, source_intake_id=int(intake.id), source_candidate_id=int(candidate.id), - business_fingerprint=candidate.business_fingerprint, fingerprint_version=candidate.fingerprint_version, - content_fingerprint=candidate.content_fingerprint, content_fingerprint_version=candidate.content_fingerprint_version, - document_version=1, duplicate_resolution_type='normal', raw_content=document.extracted_text, - customer_resolution_status='pending', current_order_extraction_id=int(extraction.id), - ) + task = order_task + task.current_order_extraction_id = int(extraction.id) + task.order_data_version = int(getattr(task, 'order_data_version', None) or 1) db.session.add(task) db.session.flush() - link_notice_to_order_task( - order_task_no=order_task_no, - notice_id=int(task.id), - ) extraction.task_id = int(task.id) candidate.consumed_task_id = int(task.id) candidate.updated_at = datetime.utcnow() # The review Case is the explicit human confirmation for this PDF. Do not # recreate a low-confidence parse checkpoint on the newly materialized Task. - apply_task_transition(task, TaskTransition.CONFIRM_PARSE) - # [STEP] 冻结建单资格中的行级库存源候选;单源 resolved,多源 candidates_frozen。 - from app.services.shipping_notice.stp_inventory_freeze import freeze_stp_inventory_candidates_on_task - - freeze_stp_inventory_candidates_on_task( - task, - line_projections=list(validation.get('line_projections') or []), - ) - # [STEP] 候选库存源已在建单前冻结;正式 OT 创建完成后立即进入获取库存, - # 不再让统一进度停留在“创建正式订单”。最终行级实际库存源仍由后续匹配决定。 - from app.services.shipping_notice.order_task_service import sync_order_task_processing_state - - sync_order_task_processing_state( - order_task, - stage='inventory_fetching', - status='processing', - reason_code='inventory_candidates_frozen_after_confirm', - ) - # [STEP] 建单前已校验客户确认:立即绑定标准客户,禁止落入 customer_review。 - from app.services.shipping_notice.candidate_qualification_service import ( - resolve_confirmed_bill_to_customer_id, - ) - from app.services.shipping_notice.customer_auto_resolution import try_auto_confirm_task_customer + # [STEP] 确认只固化订单信息(订单字段/客户/订单快照)。库存源候选的裁决/冻结 + # 退到确认后 OT 进入的正式 inventory_source_routing Gate 处理,不在确认流程内 + # 提前冻结库存候选,因此也不再在确认处设置 OT 的 notification_preparation 阶段。 + # [STEP] 建单前已从机器候选解析唯一客户主键(bind_customer_id,见上方门禁)。 + # 此处直接用该主键绑定标准客户,禁止落入 customer_review,不再二次查表。 from app.services.shipping_notice.customer_identity_gate import confirm_task_customer - bind_customer_id = resolve_confirmed_bill_to_customer_id( - candidate=candidate, - extraction_id=int(extraction.id), + confirm_task_customer( + task, + customer_id=int(bind_customer_id), + actor_id=int(user_id), + resolution_method='review_case_confirmed', + commit=False, ) - if bind_customer_id is not None: - confirm_task_customer( - task, - customer_id=int(bind_customer_id), - actor_id=int(user_id), - resolution_method='review_case_confirmed', - commit=False, - ) - else: - try_auto_confirm_task_customer(task) # [STEP] Review 确认建单与自动建单必须共享订单快照前置条件。 # 冻结失败由外层 AppError 回滚,不能留下已建单但库存链路无法启动的半成品。 from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot + from app.models import ShippingOrderSnapshot freeze_order_snapshot( task, @@ -1426,6 +1306,12 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A expected_order_data_version=int(task.order_data_version or 1), freeze_mode='manual', ) + snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) + if snapshot is None: + raise ConflictError( + 'Confirmed order snapshot is required for wave assignment', + code='SHIPPING.REVIEW_LINE_SNAPSHOT_MAPPING_MISSING', + ) except AppError as err: _reject_confirmation( case, @@ -1435,14 +1321,9 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A before=before_snap, needs_rollback=True, ) + # [STEP] 确认订单只做整单确认(业务规则:确认订单不可分行;仅“产生发货通知”可分波次)。 + # 因此 revision 记录整单草稿行,不按 draft_line_ids 过滤。 revision_lines = copy.deepcopy(case.current_draft.lines_json or []) - if wave_keys is not None: - wanted = set(wave_keys) - revision_lines = [ - item for idx, item in enumerate(revision_lines) - if isinstance(item, dict) - and (str(item.get('line_key') or '').strip() or f'line-{idx + 1}') in wanted - ] revision = ShippingOrderReviewConfirmedRevision( case_id=int(case.id), task_id=int(task.id), draft_version=int(case.current_draft.draft_version), schema_version_id=int(case.current_draft.schema_version_id), header_values_json=copy.deepcopy(case.current_draft.header_values_json or {}), @@ -1451,12 +1332,8 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A ) db.session.add(revision) db.session.flush() - # [STEP] 行级唯一归属:本波次(或整单)行写入不可变 wave_lines,防并发重复入波次。 - wave_line_keys = list(wave_keys) if wave_keys is not None else [ - (str(item.get('line_key') or '').strip() or f'line-{idx + 1}') - for idx, item in enumerate(case.current_draft.lines_json or []) - if isinstance(item, dict) - ] + # [STEP] 行级归属记录:确认订单整单写入 snapshot 全部行(防并发重复入波次)。 + wave_line_ids = [int(line.id) for line in snapshot.lines] from sqlalchemy import func max_wave = ( @@ -1469,7 +1346,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A _persist_wave_lines_for_task( case=case, task=task, - line_keys=wave_line_keys, + snapshot_line_ids=wave_line_ids, wave_no=next_wave_no, revision_id=int(revision.id), ) @@ -1484,47 +1361,14 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A case_no=str(case_no), owner_user_id=int(user_id), ) - # [STEP] 履约波次:若仍有未入 Task/未关闭的草稿行,Case 保持 ready 以支持后续波次。 - has_remaining_open = False - if wave_keys is not None: - from app.services.shipping_notice.order_review_fulfillment_decision_service import ( - project_review_case_line_decisions, - ) - terminal = {'task_created', 'fulfilled', 'closed_unfulfillable'} - projected = project_review_case_line_decisions(case) - draft_all_keys = { - (str(item.get('line_key') or '').strip() or f'line-{idx + 1}') - for idx, item in enumerate(case.current_draft.lines_json or []) - if isinstance(item, dict) - } - assigned = { - str(row.line_key) - for row in ShippingOrderReviewWaveLine.query.filter_by(review_case_id=int(case.id)).all() - } - for key in draft_all_keys: - if key in assigned: - continue - matched = next( - (item for item in (projected.get('lines') or []) if str(item.get('line_key') or '') == key), - None, - ) - # 未入波次且未关闭的行保留 Case 可继续确认。 - if matched is None or matched.get('line_status') not in terminal: - has_remaining_open = True - break - if has_remaining_open: - case.status = 'ready' - case.confirmed_task_id = int(task.id) - # 保留首次确认时间;首波未终态时写入当前时间供追溯。 - if case.confirmed_at is None: - case.confirmed_at = datetime.utcnow() - else: - case.status = 'confirmed' - case.confirmed_task_id = int(task.id) - case.confirmed_at = datetime.utcnow() - # [STEP] 文件主线锁定已确认版本;后完成的并行重解析不得覆盖正式履约事实。 - from app.services.shipping_notice.review_stream_service import mark_review_stream_confirmed - mark_review_stream_confirmed(case=case) + # [STEP] 确认订单恒为整单终态确认(业务规则:确认订单不可分行,整单全过才确认)。 + # 不再有“仍有开放行则保持 ready 支持后续波次”的中间态。 + case.status = 'confirmed' + case.confirmed_task_id = int(task.id) + case.confirmed_at = datetime.utcnow() + # [STEP] 文件主线锁定已确认版本;后完成的并行重解析不得覆盖正式履约事实。 + from app.services.shipping_notice.review_stream_service import mark_review_stream_confirmed + mark_review_stream_confirmed(case=case) db.session.add(ShippingOrderReviewCaseEvent( case_id=int(case.id), event_type='case_confirmed', draft_version=int(case.current_draft.draft_version), actor_user_id=int(user_id), operation_json={ @@ -1532,8 +1376,6 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A 'idempotency_key': key, 'warning_acknowledgements': acknowledgements, 'confirm_note': str(confirm_note or '').strip()[:1024] or None, - 'line_keys': wave_keys, - 'partial_wave': bool(has_remaining_open), }, )) # Case 级统一审计必须先写:即使工作项尚未绑定,审计中心仍可按 Case 追溯确认事实。 @@ -1576,7 +1418,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A ) -def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool: +def _task_needs_post_confirm_auto_progress(task: ShippingOrderTask | None) -> bool: """ 判断确认建单后的任务是否仍需自动推进。 @@ -1593,16 +1435,18 @@ def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool: return False if not getattr(task, 'current_order_extraction_id', None): return False - inventory_snapshot_id = getattr(task, 'inventory_snapshot_id', None) - inventory_lines = getattr(task, 'inventory_lines_json', None) - match_status = getattr(task, 'match_status', None) - export_file_path = getattr(task, 'export_file_path', None) - upload_status = getattr(task, 'upload_status', None) + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact, latest_upload_attempt + export_file_path = getattr(latest_export_artifact(task), 'file_path', None) + upload_status = getattr(latest_upload_attempt(task), 'status', None) # 仅已定义且已持久化的业务事实才能阻止自动推进。禁止把 ORM mock、关系代理等 # 任意 Python 真值误判为已进入后续阶段,避免 confirmed OT 停在 created。 - has_inventory = isinstance(inventory_snapshot_id, int) and not isinstance(inventory_snapshot_id, bool) - has_inventory = has_inventory or isinstance(inventory_lines, (list, dict)) and bool(inventory_lines) - has_match = isinstance(match_status, str) and bool(match_status.strip()) + from app.services.shipping_notice.inventory_file_store import ( + current_inventory_matches_for_task, + has_ready_inventory_file_for_task, + ) + + has_inventory = has_ready_inventory_file_for_task(task) + has_match = bool(current_inventory_matches_for_task(task)) has_export = isinstance(export_file_path, str) and bool(export_file_path.strip()) has_upload = isinstance(upload_status, str) and bool(upload_status.strip()) return not (has_inventory or has_match or has_export or has_upload) @@ -1661,7 +1505,7 @@ def schedule_auto_progress_after_review_confirm( if not normalized: return None - task = db.session.query(ShippingNotice).filter(ShippingNotice.task_no == normalized).first() + task = db.session.query(ShippingOrderTask).filter(ShippingOrderTask.task_no == normalized).first() # [STEP] 首轮与幂等回放共用:仅当仍停在 created+已抽取时入队,避免无条件跳过导致悬挂。 if not _task_needs_post_confirm_auto_progress(task): return None diff --git a/backend/app/services/shipping_notice/order_review_customer_service.py b/backend/app/services/shipping_notice/order_review_customer_service.py index 3ccdc1c6..b832f703 100644 --- a/backend/app/services/shipping_notice/order_review_customer_service.py +++ b/backend/app/services/shipping_notice/order_review_customer_service.py @@ -2,8 +2,8 @@ services/shipping_notice/order_review_customer_service.py 用途:建单前复核工作台的客户识别结果查询、重新匹配与人工确认。 -依赖:order_review_draft_service、order_customer_matching、candidate_qualification_service、 - ShippingOrderReviewCase / ShippingOrderCustomerMatch。 +依赖:order_review_draft_service、candidate_qualification_service、客户识别结果服务、 + ShippingOrderReviewCase / ShippingCustomerShadowResolution。 逻辑:由 workspace order-review-cases 客户路由调用;确认后重跑 Draft 校验以刷新建单资格; 不创建 Task、不重新解析 PDF。 """ @@ -17,18 +17,13 @@ from app.core.errors import ConflictError, NotFoundError from app.models import ( ShippingOrderCandidate, ShippingCustomerShadowResolution, - ShippingOrderCustomerMatch, ShippingOrderExtraction, ShippingOrderReviewCase, ) from app.services.shipping_notice.candidate_qualification_service import ( resolve_review_case_customer_resolved, ) -from app.services.shipping_notice.order_customer_matching import ( - confirm_order_customer_match, - refresh_order_customer_matches, - serialize_order_customer_match, -) +from app.services.shipping_notice.customer_resolution_service import confirm_customer_resolution from app.services.shipping_notice.workflow_ledger_service import ( assert_case_is_current_workflow_version, ) @@ -78,42 +73,6 @@ def _resolve_extraction_for_case(case: ShippingOrderReviewCase) -> ShippingOrder ) -def _header_from_case(case: ShippingOrderReviewCase) -> dict[str, Any]: - """从 Draft / Candidate 业务摘要投影客户匹配所需的头字段。""" - header: dict[str, Any] = {} - draft = case.current_draft - if draft is not None and isinstance(draft.header_values_json, dict): - # Draft 以 field_id 存值;客户匹配需要 bill_to_* 业务码,尽量从 Candidate 摘要补齐。 - for key, value in draft.header_values_json.items(): - if isinstance(key, str) and value is not None: - header[str(key)] = value - candidate = ( - db.session.get(ShippingOrderCandidate, int(case.candidate_id)) - if case.candidate_id - else None - ) - structured = candidate.structured_result_json if candidate is not None else None - summary = ( - structured.get('business_summary') - if isinstance(structured, dict) and isinstance(structured.get('business_summary'), dict) - else {} - ) - for key in ( - 'bill_to_customer', - 'bill_to_customer_code', - 'bill_to_source_system', - 'ship_to_customer', - 'ship_to_code', - 'ship_to_source_system', - 'customer_name', - ): - if key not in header and summary.get(key) is not None: - header[key] = summary.get(key) - if 'bill_to_customer' not in header and header.get('customer_name'): - header['bill_to_customer'] = header.get('customer_name') - return header - - def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> dict[str, Any]: """ 投影复核 Case 的建单前客户识别状态,供工作台固定客户区展示。 @@ -138,25 +97,16 @@ def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> di if candidate is not None else None ) - match = None - if extraction is not None: - match = ShippingOrderCustomerMatch.query.filter_by( - extraction_id=int(extraction.id), - role='bill_to', - ).first() - match_payload = serialize_order_customer_match(match) if match is not None else None shadow_matches = list(shadow.candidate_matches_json or []) if shadow is not None else [] top_shadow = shadow_matches[0] if shadow_matches else {} status = 'confirmed' if resolved else str( (shadow.status if shadow is not None else None) - or (match_payload or {}).get('status') or 'unmatched' ) - # [STEP 1] 客户识别展示以已发布规则集生成的指纹候选为准;旧 CustomerMatch 仅作为确认状态兼容投影。 - display_match = match_payload or {} + # [STEP 1] 客户识别展示和确认均以已发布规则集生成的证据快照为准。 + display_match: dict[str, Any] = {} if top_shadow: display_match = { - **display_match, 'customer_id': top_shadow.get('customer_id'), 'standard_name': top_shadow.get('standard_name'), 'short_code': top_shadow.get('short_code'), @@ -216,7 +166,7 @@ def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> di 'role': 'customer', 'extraction_id': int(extraction.id) if extraction is not None else None, 'raw_name': None, - 'customer_id': display_match.get('customer_id'), + 'customer_id': getattr(shadow, 'confirmed_customer_id', None) or display_match.get('customer_id'), 'standard_name': display_match.get('standard_name'), 'short_code': display_match.get('short_code'), 'candidates': list(display_match.get('candidates') or []), @@ -236,7 +186,7 @@ def confirm_review_case_customer( """ 在复核工作台确认标准客户,并刷新建单资格。 - 核心逻辑:写入 Bill-to CustomerMatch=confirmed → 统一协调器推进 → 返回最新 Case。 + 核心逻辑:确认正式客户识别结果 → 统一协调器推进 → 返回最新 Case。 """ from app.services.shipping_notice.order_review_auto_progress_coordinator import ( reconcile_single_case_for_auto_progress, @@ -244,25 +194,15 @@ def confirm_review_case_customer( from app.services.shipping_notice.order_review_projection import serialize_review_case case = _load_writable_case(user_id=user_id, case_no=case_no) - extraction = _resolve_extraction_for_case(case) - if extraction is None: - raise ConflictError( - 'Order extraction is required before confirming customer', - code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND', - ) - # [STEP 1] 若尚无 match 行,先按当前头字段刷新,再人工确认。 - if ShippingOrderCustomerMatch.query.filter_by(extraction_id=int(extraction.id), role='bill_to').first() is None: - refresh_order_customer_matches(extraction, _header_from_case(case)) - # [STEP P1-8] confirm_order_customer_match 保留调用,传 commit=False 以便 - # 后续 reconcile(校验+STP 入队)在同一事务提交,保证变更与推进原子可见。 - confirm_order_customer_match( - int(extraction.id), - role='bill_to', + candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None + if candidate is None: + raise ConflictError('Candidate is required before confirming customer', code='SHIPPING.CUSTOMER_RESOLUTION_REQUIRED') + confirm_customer_resolution( + candidate, customer_id=int(customer_id), - site_id=None, actor_id=int(user_id), + method='manual', reason=str(reason or '复核工作台人工确认标准客户').strip(), - commit=False, ) # [STEP P1-8] 客户人工确认后走统一协调器:终态门禁 + 客户协调(已人工确认会跳过)+ # Draft 校验 + STP 入队;trigger=customer_confirmed 对应人工确认语义。 @@ -306,7 +246,7 @@ def retry_review_case_customer_resolution( case_no: str, ) -> dict[str, Any]: """ - 重新识别客户(不重解析 PDF):按当前 Draft/摘要刷新 CustomerMatch。 + 重新识别客户(不重解析 PDF):刷新规则驱动的客户识别快照。 【AI 触发时机】:用户在复核工作台点击「重新识别客户」时调用。 """ @@ -316,13 +256,7 @@ def retry_review_case_customer_resolution( from app.services.shipping_notice.order_review_projection import serialize_review_case case = _load_writable_case(user_id=user_id, case_no=case_no) - extraction = _resolve_extraction_for_case(case) - if extraction is None: - raise ConflictError( - 'Order extraction is required before retrying customer resolution', - code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND', - ) - matches = refresh_order_customer_matches(extraction, _header_from_case(case)) + matches: list[dict[str, Any]] = [] if case.candidate_id: from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) @@ -334,16 +268,14 @@ def retry_review_case_customer_resolution( and shadow.top_customer_id and not resolve_review_case_customer_resolved(case=case, candidate=candidate) ): - # [STEP P1-8] 传 commit=False,保证与后续 reconcile 同事务提交。 - confirm_order_customer_match( - int(extraction.id), - role='bill_to', + confirm_customer_resolution( + candidate, customer_id=int(shadow.top_customer_id), - site_id=None, actor_id=None, + method='auto_rule', reason='客户识别指纹唯一命中自动确认', - commit=False, ) + matches = list(shadow.candidate_matches_json or []) # [STEP P1-8] 客户 shadow 重新识别后走统一协调器;trigger=customer_shadow_reconfirmed # 标识为「影子指纹再确认 + 唯一命中自动确认」路径,与 PATCH 异步 Job、人工确认按钮路径互补不冲突。 reconcile_result = reconcile_single_case_for_auto_progress( diff --git a/backend/app/services/shipping_notice/order_review_disposition_service.py b/backend/app/services/shipping_notice/order_review_disposition_service.py index 8bc567fa..e3e5f3a5 100644 --- a/backend/app/services/shipping_notice/order_review_disposition_service.py +++ b/backend/app/services/shipping_notice/order_review_disposition_service.py @@ -1074,6 +1074,11 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo 因此只在 ``activate_review_case`` 已确认切换成功后调用单 Case 协调器。这样复用 客户确认、Draft 校验、Gate 与 STP 幂等链路,且不会让晚到分支覆盖已确认版本。 + 终态闭环不变式:后继 Run 收口时业务必须二选一 —— 新版 Case 已上位 Stream, + 或旧版 Case 已恢复为可编辑状态。绝不允许旧 Case 停留在 ``reparse_pending`` + 而新版被孤儿化:该状态下工作台会永久卡在历史版本,且任何 API 都无法再次 + 触达新版或重新发起重识别。 + Args: run: 已到终态的重解析后继 Run。 succeeded: 新版 Run 是否成功到达可复核终态。 @@ -1095,21 +1100,24 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo ).with_for_update().first() ) if source_case is None or source_case.status != 'reparse_pending': + # 并发分支已裁决(被另一失败后继恢复、或已确认走另一分支): + # Stream 现状即权威,此处回改只会制造第二真相源。 return - if succeeded: - replacement_case = ShippingOrderReviewCase.query.filter_by( + replacement_case = ( + ShippingOrderReviewCase.query.filter_by( run_id=int(run.id), document_id=document_id, ).with_for_update().first() - if replacement_case is None: - # Run 已到终态但没有可复核新版本时,不可废弃旧草稿。 - return + if succeeded + else None + ) + if replacement_case is not None: from app.services.shipping_notice.review_stream_service import activate_review_case stream = activate_review_case( case=replacement_case, trigger='batch_reparse_succeeded' if marker.get('batch_reparse_id') else 'document_reparse_succeeded', ) - # [STEP] 只有 Stream 已原子指向新版 Case 才补偿自动推进。激活被并发确认或 - # 晚到分支拒绝时,保持该草稿只读,不得错误建单或进入库存准备。 + # [STEP] 只有 Stream 已原子指向新版 Case 才补偿自动推进并宣告成功; + # 激活被并发确认或晚到分支拒绝时,禁止记录 succeeded 审计(与事实不符)。 if int(stream.current_case_id or 0) == int(replacement_case.id): from app.services.shipping_notice.order_review_auto_progress_coordinator import ( reconcile_single_case_for_auto_progress, @@ -1119,11 +1127,17 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo trigger='document_reparse_succeeded', refresh_validation=True, ) - _append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_succeeded', operation={ - 'successor_run_no': run.run_no, - 'replacement_case_no': replacement_case.case_no, - }) - return + _append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_succeeded', operation={ + 'successor_run_no': run.run_no, + 'replacement_case_no': replacement_case.case_no, + }) + return + finalize_failure_reason = 'stream_activation_rejected' + else: + finalize_failure_reason = 'replacement_case_missing' + # [C1] 终态闭环:成功终态但新版 Case 缺失、或激活被拒绝时,禁止静默返回 —— + # 否则旧 Case 永久停留在 reparse_pending(编辑/确认全被禁且无法再触发重识别), + # 工作台只能卡在历史版本。转入既有失败恢复链把旧 Case 恢复为可编辑状态。 previous = 'quality_issue' event = ShippingOrderReviewCaseEvent.query.filter( ShippingOrderReviewCaseEvent.case_id == int(source_case.id), @@ -1136,6 +1150,7 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo source_case.status = previous _append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_failed', operation={ 'successor_run_no': run.run_no, 'restored_status': previous, + 'failure_reason': finalize_failure_reason, }) from app.services.shipping_notice.workflow_ledger_service import mark_reparse_failed_and_restore mark_reparse_failed_and_restore( diff --git a/backend/app/services/shipping_notice/order_review_draft_service.py b/backend/app/services/shipping_notice/order_review_draft_service.py index f98455a8..d0893cec 100644 --- a/backend/app/services/shipping_notice/order_review_draft_service.py +++ b/backend/app/services/shipping_notice/order_review_draft_service.py @@ -10,7 +10,7 @@ services/shipping_notice/order_review_draft_service.py 追加 CaseEvent + ShippingAuditEvent,并镜像 review_field_changed 到订单抽取进度流; Item 已关闭/重识别中的冲突经 `_reject_draft_operation` 落 rejected 审计; 整单校验汇总客户确认、有效 Reservation、行级库存源候选与自动建单资格; - 履约波次确认经 build_confirmable_draft_summary(line_keys) 仅对选中行重算 validation; + 履约波次确认经 build_confirmable_draft_summary(draft_line_ids) 仅对选中行重算 validation; 库存路由恢复使用最新已发布规则与库存源启停,不重新识别 PDF,不静默覆盖人工决定; 路由恢复幂等键写入 Draft 历史集合(非仅最近一次),旧键重试可安全重放; 显式校验后同步字段完整性、字段冲突、客户/Reservation/重复订单/库存路由 Gate(findings.details)。 @@ -47,7 +47,6 @@ from app.services.shipping_notice.order_build_eligibility_service import ( from app.services.shipping_notice.recovery_contract import build_review_revalidate_job_ref from app.services.shipping_notice.order_review_projection import serialize_review_case from app.services.shipping_notice.order_schema.field_rules import ( - is_valid_line_no_value, normalize_order_field_value, validate_order_field_value, ) @@ -335,21 +334,21 @@ def _machine_value(machine_fields: list[Any], field_id: str) -> Any: def _find_line( case: ShippingOrderReviewCase, lines: list[dict[str, Any]], - line_key: str, + draft_line_id: str, *, actor_id: int, action: str, ) -> dict[str, Any]: - """按稳定 line_key 获取草稿行;不存在时写拒绝审计。""" + """按稳定 draft_line_id 获取草稿行;不存在时写拒绝审计。""" for item in lines: - if isinstance(item, dict) and str(item.get('line_key') or '') == str(line_key or ''): + if isinstance(item, dict) and str(item.get('draft_line_id') or '') == str(draft_line_id or ''): return item _reject_draft_operation( case, actor_id=actor_id, action=action, error=ValidationError('Review line is unavailable', code='SHIPPING.REVIEW_LINE_NOT_FOUND'), - metadata={'line_key': str(line_key or '')[:64] or None}, + metadata={'draft_line_id': str(draft_line_id or '')[:128] or None}, ) @@ -400,14 +399,6 @@ def draft_has_unaccepted_llm_suggestions(case: ShippingOrderReviewCase) -> bool: return False -LINE_NO_OVERRIDE_REASON_CODES = frozenset({ - 'recognition_error', - 'customer_line_exception', - 'business_correction', - 'other', -}) - - def _set_value(container: dict[str, Any], field: dict[str, Any], value: Any, *, restore_machine: bool) -> dict[str, Any]: """写入单字段人工值或移除人工覆盖层;类型规范化始终按冻结字段规则执行。""" values = dict(container.get('values') or {}) @@ -476,9 +467,9 @@ def _validation( line[str(field.get('field_code') or field_id)] = value normalized = normalize_order_field_value(value, field) if field.get('required') and normalized in (None, ''): - issues.append({'code': 'required_field_missing', 'field_id': field_id, 'line_key': raw_line.get('line_key'), 'severity': 'blocking'}) + issues.append({'code': 'required_field_missing', 'field_id': field_id, 'draft_line_id': raw_line.get('draft_line_id'), 'severity': 'blocking'}) elif normalized is not None and not validate_order_field_value(normalized, field): - issues.append({'code': 'field_value_invalid', 'field_id': field_id, 'line_key': raw_line.get('line_key'), 'severity': 'blocking'}) + issues.append({'code': 'field_value_invalid', 'field_id': field_id, 'draft_line_id': raw_line.get('draft_line_id'), 'severity': 'blocking'}) lines.append(line) line_metas.append(raw_line) @@ -512,8 +503,13 @@ def _validation( if isinstance(item, dict): issues.append(dict(item)) # 人工确认只看 blocking;五门禁 severity=auto_create_blocking 不阻断 can_build。 + # 库存源路由属于确认后由正式 inventory_source_routing Gate 处理的事实, + # 这里不得把 inventory_source_routing 的 blocking 项重新纳入(eligibility.can_build 已排除), + # 否则"仅库存源未定"的订单会再次被判 needs_review,与"确认只确认订单信息"冲突。 can_build = bool(eligibility.get('can_build')) and not any( - str(item.get('severity') or '') == 'blocking' for item in issues + str(item.get('severity') or '') == 'blocking' + and str(item.get('owning_gate_code') or '') != 'inventory_source_routing' + for item in issues ) # [STEP 2] 为缺失/无效字段补齐 field_code + display_name,禁止只返回裸 code。 enriched_issues: list[dict[str, Any]] = [] @@ -563,14 +559,14 @@ def _validation( def build_confirmable_draft_summary( case: ShippingOrderReviewCase, *, - line_keys: list[str] | None = None, + draft_line_ids: list[str] | None = None, ) -> tuple[dict[str, Any], dict[str, Any]]: """ 从冻结 Schema 投影完整草稿并重跑确认校验,供原子建单服务使用。 Args: case: 复核 Case。 - line_keys: 可选;仅投影这些完整明细行(履约波次),禁止拆分数量。 + draft_line_ids: 可选;仅投影这些完整明细行(履约波次),禁止拆分数量。 Returns: (summary, validation) 元组。 @@ -583,17 +579,17 @@ def build_confirmable_draft_summary( if str(field.get('scope') or '') == 'header' } raw_lines = [item for item in (case.current_draft.lines_json or []) if isinstance(item, dict)] - if line_keys is not None: - wanted = {str(k).strip() for k in line_keys if str(k).strip()} + if draft_line_ids is not None: + wanted = {str(k).strip() for k in draft_line_ids if str(k).strip()} filtered: list[dict[str, Any]] = [] for idx, raw_line in enumerate(raw_lines): - key = str(raw_line.get('line_key') or '').strip() or f'line-{idx + 1}' + key = str(raw_line.get('draft_line_id') or '').strip() if key in wanted: filtered.append(raw_line) if len(filtered) != len(wanted): from app.core.errors import ValidationError raise ValidationError( - 'One or more line_keys not found in draft', + 'One or more draft_line_ids not found in draft', code='SHIPPING.REVIEW_LINE_NOT_FOUND', ) raw_lines = filtered @@ -605,11 +601,11 @@ def build_confirmable_draft_summary( } for raw_line in raw_lines ] - # 波次建单时保留草稿行键,供血缘与决定回写对齐。 + # 波次建单时保留草稿行身份,供血缘与决定回写对齐。 for idx, raw_line in enumerate(raw_lines): - key = str(raw_line.get('line_key') or '').strip() + key = str(raw_line.get('draft_line_id') or '').strip() if key and idx < len(lines): - lines[idx]['line_key'] = key + lines[idx]['draft_line_id'] = key # [STEP] 履约波次必须按选中行重算 can_build/status,禁止继承未选中行的整单失败态。 validation = _validation(case, raw_lines=raw_lines) return {**header, 'lines': lines}, validation @@ -719,11 +715,11 @@ def _record_change( operation_json=operation, )) changed_paths = [ - key for key in ('field_id', 'line_key', 'action') + key for key in ('field_id', 'draft_line_id', 'action') if key in operation and operation.get(key) is not None ] field_id = operation.get('field_id') - line_key = operation.get('line_key') + draft_line_id = operation.get('draft_line_id') previous_value = _audit_scalar(operation.get('previous_value')) new_value = _audit_scalar(operation.get('value') if 'value' in operation else operation.get('new_value')) value_source = str(operation.get('source') or '')[:32] or None @@ -751,9 +747,9 @@ def _record_change( after_snapshot['new_value'] = new_value if value_source: after_snapshot['value_source'] = value_source - if line_key is not None: - before_snapshot['line_key'] = str(line_key)[:64] - after_snapshot['line_key'] = str(line_key)[:64] + if draft_line_id is not None: + before_snapshot['draft_line_id'] = str(draft_line_id)[:128] + after_snapshot['draft_line_id'] = str(draft_line_id)[:128] # [STEP] 库存路由恢复:把候选与规则版本写入前后快照,供审计中心展示。 if str(event_type or '').startswith('inventory_routing_'): before_raw = operation.get('previous_value') @@ -797,8 +793,8 @@ def _record_change( after_snapshot['action_semantics'] = str(operation.get('action_semantics'))[:64] if operation.get('idempotency_key'): after_snapshot['idempotency_key'] = str(operation.get('idempotency_key'))[:128] - if operation.get('line_keys') is not None: - after_snapshot['line_keys'] = [str(item)[:64] for item in list(operation.get('line_keys') or [])[:50]] + if operation.get('draft_line_ids') is not None: + after_snapshot['draft_line_ids'] = [str(item)[:128] for item in list(operation.get('draft_line_ids') or [])[:50]] # 恢复机器值使用独立事件类型,便于坐标/字段证据反查(阶段 5)。 audit_event_type = ( 'review_field_restored_machine' @@ -887,139 +883,31 @@ def patch_line_field( *, user_id: int, case_no: str, - line_key: str, + draft_line_id: str, field_id: str, value: Any, expected_draft_version: Any, restore_machine: bool = False, - override_reason_code: str | None = None, - override_reason_text: str | None = None, ) -> dict[str, Any]: """ - 编辑或恢复一条明细字段;行由不可变 line_key 定位并受同一草稿版本锁保护。 + 编辑或恢复一条明细字段;行由不可变 draft_line_id 定位并受同一草稿版本锁保护。 - 核心逻辑:一般字段沿用 manual 覆盖;内部项次 line_no 覆盖须原因分类并锁定; - 恢复时清除 override,回退到草稿 machine_fields 中的识别/派生投影(不重新跑派生引擎), - 并写 LINE_NO_RESTORED。 + 核心逻辑:一般字段沿用 manual 覆盖;内部项次 line_no 是系统项次,禁止覆盖或恢复。 """ action = 'line_field_changed' case = _locked_case(user_id=user_id, case_no=case_no, action=action) _assert_version(case, expected_draft_version, actor_id=user_id, action=action) field = _require_field(case, field_id, 'line', actor_id=user_id, action=action) lines = copy.deepcopy(list(case.current_draft.lines_json or [])) - target = _find_line(case, lines, line_key, actor_id=user_id, action=action) + target = _find_line(case, lines, draft_line_id, actor_id=user_id, action=action) previous_value = _current_value(target, field_id) field_code = str(field.get('field_code') or '') - if field_code == 'line_no' and restore_machine: - prior_entry = (target.get('values') or {}).get(field_id) if isinstance(target.get('values'), dict) else None - prior_source = str((prior_entry or {}).get('source') or 'manual_override') - change = _set_value(target, field, value, restore_machine=True) - # 恢复后的展示值来自 machine_fields:初始化草稿时已含识别/派生投影,非二次派生。 - restored_source = 'machine_or_derived_projection' - case.current_draft.lines_json = lines - result = _record_change( - case, - actor_id=user_id, - event_type=action, - operation={ - 'line_key': line_key, - 'field_id': field_id, - 'field_code': field_code, - 'previous_value': previous_value, - 'restored_source': restored_source, - 'prior_value_source': prior_source, - **change, - }, + if field_code == 'line_no': + raise ValidationError( + 'line_no is system-generated and cannot be edited or restored', + code='SHIPPING.REVIEW_LINE_NO_IMMUTABLE', ) - append_shipping_audit_event( - event_type='LINE_NO_RESTORED', - aggregate_type='shipping_order_review_case', - aggregate_id=str(case.case_no), - actor_type='user', - actor_id=user_id, - review_case_no=str(case.case_no), - action='restore_line_no', - result='success', - metadata={ - 'line_key': line_key, - 'field_code': 'line_no', - 'restored_source': restored_source, - 'prior_value_source': prior_source, - }, - before={'previous_value': previous_value, 'value_source': prior_source}, - after={'new_value': change.get('value'), 'value_source': restored_source}, - ) - return result - - if field_code == 'line_no' and not restore_machine: - reason_code = str(override_reason_code or '').strip() - reason_text = str(override_reason_text or '').strip() - if reason_code not in LINE_NO_OVERRIDE_REASON_CODES: - raise ValidationError( - 'line_no override requires a valid reason code', - code='SHIPPING.REVIEW_LINE_NO_OVERRIDE_REASON_REQUIRED', - ) - if reason_code == 'other' and not reason_text: - raise ValidationError( - 'line_no override reason text is required for other', - code='SHIPPING.REVIEW_LINE_NO_OVERRIDE_TEXT_REQUIRED', - ) - if not is_valid_line_no_value(value): - raise ValidationError( - 'line_no must be 1-6 digits', - code='SHIPPING.REVIEW_LINE_NO_FORMAT_INVALID', - ) - change = _set_value(target, field, value, restore_machine=False) - values = dict(target.get('values') or {}) - values[str(field['field_id'])] = { - 'value': change['value'], - 'source': 'manual_override', - 'locked': True, - 'override_reason_code': reason_code, - 'override_reason_text': reason_text or None, - } - target['values'] = values - change = { - **change, - 'source': 'manual_override', - 'override_reason_code': reason_code, - 'override_reason_text': reason_text or None, - 'locked': True, - } - case.current_draft.lines_json = lines - result = _record_change( - case, - actor_id=user_id, - event_type=action, - operation={ - 'line_key': line_key, - 'field_id': field_id, - 'field_code': field_code, - 'previous_value': previous_value, - **change, - }, - ) - append_shipping_audit_event( - event_type='LINE_NO_OVERRIDDEN', - aggregate_type='shipping_order_review_case', - aggregate_id=str(case.case_no), - actor_type='user', - actor_id=user_id, - review_case_no=str(case.case_no), - action='override_line_no', - result='success', - reason_code=reason_code, - reason=reason_text or None, - metadata={ - 'line_key': line_key, - 'field_code': 'line_no', - 'override_reason_code': reason_code, - }, - before={'previous_value': previous_value, 'value_source': 'prior'}, - after={'new_value': change['value'], 'value_source': 'manual_override'}, - ) - return result change = _set_value(target, field, value, restore_machine=restore_machine) case.current_draft.lines_json = lines @@ -1028,7 +916,7 @@ def patch_line_field( actor_id=user_id, event_type=action, operation={ - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'field_id': field_id, 'previous_value': previous_value, **change, @@ -1042,34 +930,34 @@ def add_line(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict case = _locked_case(user_id=user_id, case_no=case_no, action=action) _assert_version(case, expected_draft_version, actor_id=user_id, action=action) lines = copy.deepcopy(list(case.current_draft.lines_json or [])) - line_key = f'manual-{uuid.uuid4().hex[:16]}' - lines.append({'line_key': line_key, 'machine_fields': [], 'values': {}}) + draft_line_id = str(uuid.uuid4()) + lines.append({'draft_line_id': draft_line_id, 'machine_fields': [], 'values': {}}) case.current_draft.lines_json = lines - return _record_change(case, actor_id=user_id, event_type=action, operation={'line_key': line_key}) + return _record_change(case, actor_id=user_id, event_type=action, operation={'draft_line_id': draft_line_id}) -def copy_line(*, user_id: int, case_no: str, line_key: str, expected_draft_version: Any) -> dict[str, Any]: - """复制明细为新 line_key;复制后的 Reservation 重复会由全量校验显式阻断。""" +def copy_line(*, user_id: int, case_no: str, draft_line_id: str, expected_draft_version: Any) -> dict[str, Any]: + """复制明细为新 draft_line_id;复制后的 Reservation 重复会由全量校验显式阻断。""" action = 'line_copied' case = _locked_case(user_id=user_id, case_no=case_no, action=action) _assert_version(case, expected_draft_version, actor_id=user_id, action=action) lines = copy.deepcopy(list(case.current_draft.lines_json or [])) - copied = copy.deepcopy(_find_line(case, lines, line_key, actor_id=user_id, action=action)) - copied['line_key'] = f'manual-{uuid.uuid4().hex[:16]}' + copied = copy.deepcopy(_find_line(case, lines, draft_line_id, actor_id=user_id, action=action)) + copied['draft_line_id'] = str(uuid.uuid4()) lines.append(copied) case.current_draft.lines_json = lines - return _record_change(case, actor_id=user_id, event_type=action, operation={'source_line_key': line_key, 'line_key': copied['line_key']}) + return _record_change(case, actor_id=user_id, event_type=action, operation={'source_draft_line_id': draft_line_id, 'draft_line_id': copied['draft_line_id']}) -def delete_line(*, user_id: int, case_no: str, line_key: str, expected_draft_version: Any) -> dict[str, Any]: +def delete_line(*, user_id: int, case_no: str, draft_line_id: str, expected_draft_version: Any) -> dict[str, Any]: """删除单条草稿行并写审计;删除最后有效行会保留为阻断校验结果。""" action = 'line_deleted' case = _locked_case(user_id=user_id, case_no=case_no, action=action) _assert_version(case, expected_draft_version, actor_id=user_id, action=action) lines = copy.deepcopy(list(case.current_draft.lines_json or [])) - _find_line(case, lines, line_key, actor_id=user_id, action=action) - case.current_draft.lines_json = [item for item in lines if str(item.get('line_key') or '') != str(line_key)] - return _record_change(case, actor_id=user_id, event_type=action, operation={'line_key': line_key}) + _find_line(case, lines, draft_line_id, actor_id=user_id, action=action) + case.current_draft.lines_json = [item for item in lines if str(item.get('draft_line_id') or '') != str(draft_line_id)] + return _record_change(case, actor_id=user_id, event_type=action, operation={'draft_line_id': draft_line_id}) def validate_draft(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict[str, Any]: @@ -1102,7 +990,7 @@ def _routing_idempotency_entry_key(*, action: str, idempotency_key: str) -> str: 生成幂等历史条目键(动作 + 幂等键)。 Args: - action: 路由恢复动作(可含 line_key 后缀)。 + action: 路由恢复动作(可含 draft_line_id 后缀)。 idempotency_key: 已规范化的幂等键。 Returns: @@ -1166,7 +1054,7 @@ def _store_routing_recovery_idempotency( *, action: str, idempotency_key: str, - line_keys: list[str], + draft_line_ids: list[str], ) -> None: """ 将成功的路由恢复幂等键追加写入 Draft 历史集合(非整对象覆盖)。 @@ -1184,7 +1072,7 @@ def _store_routing_recovery_idempotency( record = { 'idempotency_key': key, 'action': action, - 'line_keys': [str(item)[:64] for item in line_keys[:50]], + 'draft_line_ids': [str(item)[:128] for item in draft_line_ids[:50]], 'draft_version_after': int(draft.draft_version) + 1, } entries[entry_key] = record @@ -1214,7 +1102,7 @@ def _line_routing_snapshot(line: dict[str, Any], fields: dict[str, dict[str, Any line_meta=line, ) return { - 'line_key': str(line.get('line_key') or '')[:64], + 'draft_line_id': str(line.get('draft_line_id') or '')[:128], 'selection_mode': projection.get('selection_mode'), 'candidate_inventory_source_codes': list(projection.get('candidate_inventory_source_codes') or []), 'raw_rule_source_codes': list(projection.get('raw_rule_source_codes') or []), @@ -1243,7 +1131,7 @@ def reroute_inventory_routing( case_no: str, expected_draft_version: Any, idempotency_key: str | None = None, - line_key: str | None = None, + draft_line_id: str | None = None, ) -> dict[str, Any]: """ 按最新已发布规则与库存源启停重算库存路由;不重新识别 PDF。 @@ -1256,7 +1144,7 @@ def reroute_inventory_routing( case_no: 复核 Case 编号。 expected_draft_version: 乐观锁版本。 idempotency_key: 可选幂等键。 - line_key: 可选,仅重算指定行;缺省整单。 + draft_line_id: 可选,仅重算指定行;缺省整单。 Returns: 序列化后的 Case 详情。 @@ -1271,7 +1159,7 @@ def reroute_inventory_routing( fields = _schema_fields(case) header_by_code = _header_by_code_for_case(case, fields) lines = copy.deepcopy(list(case.current_draft.lines_json or [])) - target_key = str(line_key or '').strip() + target_key = str(draft_line_id or '').strip() before_rows: list[dict[str, Any]] = [] after_rows: list[dict[str, Any]] = [] touched_keys: list[str] = [] @@ -1279,7 +1167,7 @@ def reroute_inventory_routing( for raw in lines: if not isinstance(raw, dict): continue - current_key = str(raw.get('line_key') or '').strip() + current_key = str(raw.get('draft_line_id') or '').strip() if target_key and current_key != target_key: continue if not current_key: @@ -1305,7 +1193,7 @@ def reroute_inventory_routing( actor_id=user_id, action=action, error=NotFoundError('Order review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND'), - metadata={'line_key': target_key[:64]}, + metadata={'draft_line_id': target_key[:128]}, ) case.current_draft.lines_json = lines @@ -1313,15 +1201,15 @@ def reroute_inventory_routing( case, action=action, idempotency_key=str(idempotency_key or ''), - line_keys=touched_keys, + draft_line_ids=touched_keys, ) return _record_change( case, actor_id=user_id, event_type=action, operation={ - 'line_key': target_key or None, - 'line_keys': touched_keys, + 'draft_line_id': target_key or None, + 'draft_line_ids': touched_keys, 'idempotency_key': _normalize_routing_idempotency_key(idempotency_key) or None, 'previous_value': before_rows[:20], 'new_value': after_rows[:20], @@ -1386,7 +1274,7 @@ def _candidate_conflict_locator(case: ShippingOrderReviewCase) -> dict[str, Any] return { 'field_code': field_code, 'line_index': conflict.get('line_index'), - 'line_key': conflict.get('line_key'), + 'draft_line_id': conflict.get('draft_line_id'), } return {} @@ -1462,7 +1350,7 @@ def _sync_review_gates_safe( default_reason_code='field_conflict', details={ **base_details, - 'line_key': primary_conflict.get('line_key') or conflict_locator.get('line_key'), + 'draft_line_id': primary_conflict.get('draft_line_id') or conflict_locator.get('draft_line_id'), 'line_index': primary_conflict.get('line_index') if primary_conflict.get('line_index') is not None else conflict_locator.get('line_index'), 'field_code': primary_conflict.get('field_code') or conflict_locator.get('field_code'), @@ -1496,7 +1384,7 @@ def _sync_review_gates_safe( ) or default_reason sync_details = { **base_details, - 'line_key': primary.get('line_key'), + 'draft_line_id': primary.get('draft_line_id'), 'line_index': primary.get('line_index'), 'field_code': primary.get('field_code'), 'issue_codes': [ @@ -1517,12 +1405,8 @@ def _sync_review_gates_safe( inventory_issues = _blocking_issues_for_gate(result, 'inventory_source_routing') if not inventory_issues: - sync_inventory_routing_gate_for_case( - case=case, - passed=True, - actor_id=int(user_id), - details=base_details, - ) + # 复核草稿阶段只能评估路由结果,正式 CandidateSet 需绑定确认后的 Task; + # 因此不得在 draft_validated 时提前通过正式 inventory_source_routing Gate。 return primary = inventory_issues[0] @@ -1558,7 +1442,7 @@ def _sync_review_gates_safe( 'unavailable_source_codes': list(dict.fromkeys(unavailable_codes)), 'raw_rule_source_codes': list(dict.fromkeys(raw_codes)), 'matched_rule_codes': list(dict.fromkeys(matched_rule_codes)), - 'line_key': primary.get('line_key'), + 'draft_line_id': primary.get('draft_line_id'), 'line_index': primary.get('line_index'), 'candidate_inventory_source_codes': list(primary.get('candidate_inventory_source_codes') or []), }, @@ -1599,7 +1483,7 @@ def apply_llm_suggestion_prefill( user_id: int, case_no: str, field_id: str, - line_key: str | None, + draft_line_id: str | None, value: Any, suggestion_no: str, expected_draft_version: Any, @@ -1613,7 +1497,7 @@ def apply_llm_suggestion_prefill( user_id: 操作人。 case_no: Case 编号。 field_id: 字段 ID。 - line_key: 行键;表头为 None。 + draft_line_id: 草稿行身份;表头为 None。 value: 建议值。 suggestion_no: 关联建议编号。 expected_draft_version: 乐观锁版本。 @@ -1627,13 +1511,13 @@ def apply_llm_suggestion_prefill( field = _require_field( case, field_id, - 'line' if line_key else 'header', + 'line' if draft_line_id else 'header', actor_id=user_id, action=action, ) - if line_key: + if draft_line_id: lines = copy.deepcopy(list(case.current_draft.lines_json or [])) - target = _find_line(case, lines, line_key, actor_id=user_id, action=action) + target = _find_line(case, lines, draft_line_id, actor_id=user_id, action=action) previous_value = _current_value(target, field_id) change = _set_llm_suggested_value(target, field, value, suggestion_no=suggestion_no) case.current_draft.lines_json = lines @@ -1641,7 +1525,7 @@ def apply_llm_suggestion_prefill( case, actor_id=user_id, event_type=action, - operation={'line_key': line_key, 'field_id': field_id, 'previous_value': previous_value, **change}, + operation={'draft_line_id': draft_line_id, 'field_id': field_id, 'previous_value': previous_value, **change}, ) header = dict(case.current_draft.header_values_json or {}) previous_value = _current_value(header, field_id) @@ -1692,10 +1576,10 @@ def adjudicate_llm_suggestion_on_draft( actor_id=user_id, action=action, ) - line_key = suggestion.line_key - if line_key: + draft_line_id = suggestion.draft_line_id + if draft_line_id: lines = copy.deepcopy(list(case.current_draft.lines_json or [])) - target = _find_line(case, lines, line_key, actor_id=user_id, action=action) + target = _find_line(case, lines, draft_line_id, actor_id=user_id, action=action) previous_value = _current_value(target, suggestion.field_id) if decision == 'reject': values = dict(target.get('values') or {}) @@ -1731,7 +1615,7 @@ def adjudicate_llm_suggestion_on_draft( actor_id=user_id, event_type=action, operation={ - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'field_id': suggestion.field_id, 'suggestion_no': suggestion.suggestion_no, 'previous_value': previous_value, diff --git a/backend/app/services/shipping_notice/order_review_evidence_selector.py b/backend/app/services/shipping_notice/order_review_evidence_selector.py index 82d83d57..86796bc5 100644 --- a/backend/app/services/shipping_notice/order_review_evidence_selector.py +++ b/backend/app/services/shipping_notice/order_review_evidence_selector.py @@ -3,7 +3,7 @@ services/shipping_notice/order_review_evidence_selector.py 用途:为订单复核 AI 建议选择最小证据包(字段→单元格→表格→页面)。 依赖:Run 冻结 layout_snapshot / layout_schema_candidates。 -逻辑:默认不超过 L3;明细必须绑定 line_key/行号;禁止写入 secret、临时签名 URL、完整请求头。 +逻辑:默认不超过 L3;明细必须绑定 draft_line_id/行号;禁止写入 secret、临时签名 URL、完整请求头。 """ from __future__ import annotations @@ -42,7 +42,7 @@ def select_review_evidence_pack( Args: document: 冻结 Document 快照。 - target_fields: 待建议字段定位信息(须含 field_id;明细须含 line_key)。 + target_fields: 待建议字段定位信息(须含 field_id;明细须含 draft_line_id)。 evidence_level: L1–L4。 allow_full_pdf: 仅管理员显式 True 时允许 L4。 @@ -84,16 +84,16 @@ def select_review_evidence_pack( hit_table_ids: set[str] = set() hit_page_nos: set[int] = set() - # [STEP 1] L1:目标字段相邻 cell 文本;明细必须按 line_key 过滤。 + # [STEP 1] L1:目标字段相邻 cell 文本;明细必须按 draft_line_id 过滤。 for target in target_fields: if not isinstance(target, dict): continue field_id = str(target.get('field_id') or '') - line_key = str(target.get('line_key') or '').strip() or None + draft_line_id = str(target.get('draft_line_id') or '').strip() or None snippets = _field_snippets( candidates, field_id=field_id, - line_key=line_key, + draft_line_id=draft_line_id, line_number=target.get('line_number'), ) for snippet in snippets: @@ -107,7 +107,7 @@ def select_review_evidence_pack( 'field_id': field_id, 'field_code': target.get('field_code'), 'scope': target.get('scope'), - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'line_number': target.get('line_number'), 'snippets': snippets[:8], }) @@ -157,11 +157,11 @@ def _field_snippets( candidates: list[dict[str, Any]], *, field_id: str, - line_key: str | None = None, + draft_line_id: str | None = None, line_number: Any = None, ) -> list[dict[str, Any]]: """ - 收集目标 field_id 的短引文;明细行必须绑定 line_key / 行号。 + 收集目标 field_id 的短引文;明细行必须绑定 draft_line_id / 行号。 核心逻辑:header 字段可跨行收集;line 字段仅保留匹配目标行的 cell,禁止串行。 """ @@ -170,7 +170,7 @@ def _field_snippets( for row in candidate.get('rows') or []: if not isinstance(row, dict): continue - if not _row_matches_line(row, line_key=line_key, line_number=line_number): + if not _row_matches_line(row, draft_line_id=draft_line_id, line_number=line_number): continue for field in row.get('fields') or []: if not isinstance(field, dict) or str(field.get('field_id') or '') != field_id: @@ -181,7 +181,7 @@ def _field_snippets( 'page_no': int(candidate.get('page_no') or field.get('page_no') or 1), 'table_id': str(candidate.get('table_id') or field.get('table_id') or ''), 'row_index': int(row.get('row_index') or 0), - 'line_key': str(row.get('line_key') or line_key or '') or None, + 'draft_line_id': str(row.get('draft_line_id') or draft_line_id or '') or None, 'cell_id': str(field.get('cell_id') or '') or None, 'quote': quote[:500], }) @@ -191,17 +191,17 @@ def _field_snippets( def _row_matches_line( row: dict[str, Any], *, - line_key: str | None, + draft_line_id: str | None, line_number: Any, ) -> bool: - """判断布局行是否对应目标明细;无 line_key 时视为表头字段(允许任意行)。""" - if not line_key and line_number is None: + """判断布局行是否对应目标明细;无 draft_line_id 时视为表头字段(允许任意行)。""" + if not draft_line_id and line_number is None: return True - row_line_key = str(row.get('line_key') or '').strip() - # [STEP] 行上已有 line_key 时只做精确匹配,禁止再按 row_index 宽松回退。 - if line_key and row_line_key: - return row_line_key == line_key - target_index = _line_key_to_index(line_key) + row_draft_line_id = str(row.get('draft_line_id') or '').strip() + # [STEP] 行上已有 draft_line_id 时只做精确匹配,禁止再按 row_index 宽松回退。 + if draft_line_id and row_draft_line_id: + return row_draft_line_id == draft_line_id + target_index = _draft_line_id_to_index(draft_line_id) if target_index is None and line_number is not None: try: target_index = int(line_number) @@ -216,16 +216,16 @@ def _row_matches_line( return int(data_position) == target_index except (TypeError, ValueError): return False - # 兼容仅有 1-based row_index 的布局行(无 line_key)。 + # 布局行没有草稿身份时,仅按显式行号定位。 row_index = int(row.get('row_index') or -1) return row_index == target_index + 1 -def _line_key_to_index(line_key: str | None) -> int | None: - """将 machine-N 行键转换为 0-based 行序号。""" - if not line_key: +def _draft_line_id_to_index(draft_line_id: str | None) -> int | None: + """将 machine-N 草稿行身份转换为 0-based 行序号。""" + if not draft_line_id: return None - matched = _MACHINE_LINE_KEY.match(str(line_key).strip()) + matched = _MACHINE_LINE_KEY.match(str(draft_line_id).strip()) if not matched: return None return max(int(matched.group(1)) - 1, 0) @@ -275,7 +275,7 @@ def _strip_forbidden(value: Any) -> Any: _FIELD_CORE_PRIORITY = ( 'field_id', 'value', 'quote', 'evidence_ref', 'field_code', - 'scope', 'line_key', 'llm_context_policy', 'mask_rule', 'value_source', + 'scope', 'draft_line_id', 'llm_context_policy', 'mask_rule', 'value_source', ) @@ -322,8 +322,8 @@ def _serialize_field_view( if not strip_secondary_for_token: out['field_code'] = fc out['scope'] = fv.get('scope') - if fv.get('line_key'): - out['line_key'] = fv.get('line_key') + if fv.get('draft_line_id'): + out['draft_line_id'] = fv.get('draft_line_id') out['value'] = sent_value out['value_source'] = fv.get('value_source') or 'missing_both' if masked.get('policy') == 'masked': @@ -457,20 +457,20 @@ def _build_v2_field_entry( ) -> tuple[dict[str, Any], bool, bool]: """ 返回 (field_entry, context_truncated, target_core_trimmed)。 - field_entry 包含:field_id/field_code/scope/line_key + snippets[] + row_fields[] + + field_entry 包含:field_id/field_code/scope/draft_line_id + snippets[] + row_fields[] + table_headers[] + neighbor_rows[] + page_text[]。 """ from app.services.shipping_notice.order_review_evidence_view import get_field_view field_id = str(target.get('field_id') or '') - line_key = str(target.get('line_key') or '').strip() or None - target_fv = get_field_view(evidence_view, field_id=field_id, line_key=line_key) + draft_line_id = str(target.get('draft_line_id') or '').strip() or None + target_fv = get_field_view(evidence_view, field_id=field_id, draft_line_id=draft_line_id) if target_fv is None: target_fv = { 'field_id': field_id, 'field_code': target.get('field_code') or field_id, 'scope': target.get('scope'), - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'llm_context_policy': 'allowed', 'value_source': 'missing_both', 'field_evidences': [], @@ -481,7 +481,7 @@ def _build_v2_field_entry( 'field_id': field_id, 'field_code': target.get('field_code') or target_fv.get('field_code'), 'scope': target.get('scope') or target_fv.get('scope'), - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'snippets': [], } # snippets:摊平所有 field_evidences 的 quote/value/evidence_ref @@ -511,11 +511,11 @@ def _build_v2_field_entry( # [LEVEL] L2_row:行 scope 包含同行其它字段(按 policy 过滤) if level == 'L2_row': - line_fields_map = evidence_view.get('line_fields') or {} if line_key else {} - line_map = (line_fields_map.get(line_key) if isinstance(line_fields_map, dict) else {}) or {} + line_fields_map = evidence_view.get('line_fields') or {} if draft_line_id else {} + line_map = (line_fields_map.get(draft_line_id) if isinstance(line_fields_map, dict) else {}) or {} row_field_items: list[dict[str, Any]] = [] target_idx = 0 - if line_key and isinstance(line_map, dict): + if draft_line_id and isinstance(line_map, dict): for fid, fv in line_map.items(): if not isinstance(fv, dict): continue @@ -580,9 +580,9 @@ def _build_v2_field_entry( rows = matched_table.get('rows') or [] ridx = int(row_index) if isinstance(row_index, int) else None if ridx is None: - # 没找到 row_index:用 line_key 反查 + # 没找到 row_index:用 draft_line_id 反查 for ri, r in enumerate(rows): - if isinstance(r, dict) and str(r.get('line_key') or '') == str(line_key or ''): + if isinstance(r, dict) and str(r.get('draft_line_id') or '') == str(draft_line_id or ''): ridx = ri break if ridx is not None: @@ -607,15 +607,15 @@ def _build_v2_field_entry( }) neighbor_rows.append({ 'row_index': pos, - 'line_key': r.get('line_key'), + 'draft_line_id': r.get('draft_line_id'), 'cells': cell_values, }) # 同行字段(复用 L2 逻辑,减少字符预算) - line_fields_map = (evidence_view.get('line_fields') or {}) if line_key else {} - line_map = (line_fields_map.get(line_key) if isinstance(line_fields_map, dict) else {}) or {} + line_fields_map = (evidence_view.get('line_fields') or {}) if draft_line_id else {} + line_map = (line_fields_map.get(draft_line_id) if isinstance(line_fields_map, dict) else {}) or {} row_field_items: list[dict[str, Any]] = [] target_idx = 0 - if line_key and isinstance(line_map, dict): + if draft_line_id and isinstance(line_map, dict): for fid, fv in line_map.items(): if not isinstance(fv, dict): continue @@ -674,10 +674,10 @@ def _build_v2_field_entry( entry['page_blocks'] = page_blocks entry['page_no'] = page_no_final # 行字段保留(最小) - line_fields_map = (evidence_view.get('line_fields') or {}) if line_key else {} - line_map = (line_fields_map.get(line_key) if isinstance(line_fields_map, dict) else {}) or {} + line_fields_map = (evidence_view.get('line_fields') or {}) if draft_line_id else {} + line_map = (line_fields_map.get(draft_line_id) if isinstance(line_fields_map, dict) else {}) or {} row_field_items: list[dict[str, Any]] = [] - if line_key and isinstance(line_map, dict): + if draft_line_id and isinstance(line_map, dict): for fid, fv in line_map.items(): if not isinstance(fv, dict): continue diff --git a/backend/app/services/shipping_notice/order_review_evidence_service.py b/backend/app/services/shipping_notice/order_review_evidence_service.py index 6a9899b8..728588d8 100644 --- a/backend/app/services/shipping_notice/order_review_evidence_service.py +++ b/backend/app/services/shipping_notice/order_review_evidence_service.py @@ -529,7 +529,7 @@ def build_minimal_evidence_pack_for_field( case: ShippingOrderReviewCase, *, field_id: str, - line_key: str | None = None, + draft_line_id: str | None = None, evidence_level: str = 'L1_field', allow_full_pdf: bool = False, ) -> dict[str, Any]: @@ -541,7 +541,7 @@ def build_minimal_evidence_pack_for_field( Args: case: 已加载 run 的 Review Case。 field_id: 目标 field_id。 - line_key: 明细行键。 + draft_line_id: 草稿明细行身份。 evidence_level: L1_field–L4_pdf。 allow_full_pdf: 管理员显式 L4。 @@ -559,7 +559,7 @@ def build_minimal_evidence_pack_for_field( if isinstance(item, dict) and int(item.get('document_id') or 0) == int(case.document_id): document = dict(item) break - field_meta = {'field_id': str(field_id), 'scope': 'line' if line_key else 'header', 'line_key': line_key} + field_meta = {'field_id': str(field_id), 'scope': 'line' if draft_line_id else 'header', 'draft_line_id': draft_line_id} return select_review_evidence_pack( document=document, target_fields=[field_meta], diff --git a/backend/app/services/shipping_notice/order_review_evidence_view.py b/backend/app/services/shipping_notice/order_review_evidence_view.py index e15d6671..17e6018d 100644 --- a/backend/app/services/shipping_notice/order_review_evidence_view.py +++ b/backend/app/services/shipping_notice/order_review_evidence_view.py @@ -83,7 +83,7 @@ def _normalize_observation( case_document_id: int, case_id: int, field_code: str | None = None, - line_key: str | None = None, + draft_line_id: str | None = None, derived_row_index: int | None = None, ) -> dict[str, Any]: """ @@ -118,7 +118,7 @@ def _normalize_observation( provenance_ref: str | None = None if source == 'draft_observation' or source == 'text_fallback': provenance_ref = build_provenance_ref( - case_id=case_id, line_key=line_key, field_code=field_code or '', + case_id=case_id, draft_line_id=draft_line_id, field_code=field_code or '', ) confidence_raw = raw.get('confidence') @@ -221,23 +221,22 @@ def _iter_unit_header_fields(order_result: dict[str, Any]) -> list[tuple[str, di def _iter_unit_line_fields( order_result: dict[str, Any], ) -> list[tuple[str, int, str, dict[str, Any]]]: - """返回 [(line_key, row_position, field_id, field_obj)]""" + """返回 [(draft_line_id, row_position, field_id, field_obj)]""" out: list[tuple[str, int, str, dict[str, Any]]] = [] lines = order_result.get('lines') or [] for pos, line in enumerate(lines): if not isinstance(line, dict): continue - line_key = _safe_str(line.get('line_key')) - if not line_key: - index_match = _MACHINE_LINE_KEY_RE.match(f'machine-{pos + 1}') - line_key = index_match.group(0) if index_match else f'machine-{pos + 1}' + draft_line_id = _safe_str(line.get('draft_line_id')) + if not draft_line_id: + draft_line_id = f'machine-{pos + 1}' for field_obj in line.get('fields') or []: if not isinstance(field_obj, dict): continue fid = _safe_str(field_obj.get('field_id')) if not fid: continue - out.append((line_key, pos, fid, field_obj)) + out.append((draft_line_id, pos, fid, field_obj)) return out @@ -254,9 +253,9 @@ def _draft_line_list(draft) -> list[dict[str, Any]]: return [ln for ln in (lines if isinstance(lines, list) else []) if isinstance(ln, dict)] -def _find_draft_line(lines: list[dict[str, Any]], line_key: str) -> dict[str, Any] | None: +def _find_draft_line(lines: list[dict[str, Any]], draft_line_id: str) -> dict[str, Any] | None: for ln in lines: - if _safe_str(ln.get('line_key')) == line_key: + if _safe_str(ln.get('draft_line_id')) == draft_line_id: return ln return None @@ -301,8 +300,8 @@ def _frozen_document_snapshot(case) -> dict[str, Any]: def _iter_frozen_layout_fields(frozen_doc: dict[str, Any]) -> list[tuple[str, str, int | None, str, dict[str, Any]]]: """ - 返回 [(line_key_or_header, field_id, row_index, table_id, raw_field_obj)]。 - header scope 行 line_key=None。 + 返回 [(draft_line_id_or_header, field_id, row_index, table_id, raw_field_obj)]。 + header scope 行 draft_line_id=None。 """ out: list[tuple[str, str, int | None, str, dict[str, Any]]] = [] candidates = [ @@ -315,7 +314,7 @@ def _iter_frozen_layout_fields(frozen_doc: dict[str, Any]) -> list[tuple[str, st for row_idx, row in enumerate(rows): if not isinstance(row, dict): continue - line_key = _safe_str(row.get('line_key')) + draft_line_id = _safe_str(row.get('draft_line_id')) data_row_idx = _safe_int(row.get('data_row_index') or row.get('row_index')) for raw_field in row.get('fields') or []: if not isinstance(raw_field, dict): @@ -323,9 +322,9 @@ def _iter_frozen_layout_fields(frozen_doc: dict[str, Any]) -> list[tuple[str, st fid = _safe_str(raw_field.get('field_id')) if not fid: continue - effective_line_key = line_key + effective_draft_line_id = draft_line_id out.append(( - effective_line_key, + effective_draft_line_id, fid, data_row_idx, table_id, @@ -358,7 +357,7 @@ def _schema_fields_map(case) -> dict[str, dict[str, Any]]: _FIELD_VIEW_KEYS = ( 'field_id', 'field_code', 'display_name', 'scope', 'data_type', 'llm_context_policy', - 'line_key', + 'draft_line_id', 'machine_value', 'current_draft_value', 'value_source', 'primary_evidence', 'field_evidences', ) @@ -375,7 +374,7 @@ def _build_field_view( field_id: str, field_metadata: dict[str, Any] | None, scope: Literal['header', 'line'], - line_key: str | None, + draft_line_id: str | None, case_id: int, case_document_id: int, ) -> dict[str, Any]: @@ -387,7 +386,7 @@ def _build_field_view( view['display_name'] = _safe_str(md.get('display_name')) or code view['scope'] = scope view['data_type'] = _safe_str(md.get('data_type')) - view['line_key'] = line_key + view['draft_line_id'] = draft_line_id policy = resolve_llm_context_policy( field_metadata=md, field_code=code, @@ -457,9 +456,9 @@ def build_review_evidence_view(case) -> dict[str, Any]: "diagnostics": { "unit_orders_ambiguous": bool, "context_ambiguous_reasons": [] }, "header_fields": { [field_id]: field_view }, "line_fields": { - [line_key]: { [field_id]: field_view } + [draft_line_id]: { [field_id]: field_view } }, - "lines_order": [line_key...], + "lines_order": [draft_line_id...], "layout_schema_candidates": [frozen_candidate...], // 直接引用,不 clone "frozen_document_snapshot": dict, // 只读 } @@ -481,7 +480,7 @@ def build_review_evidence_view(case) -> dict[str, Any]: def _ensure_field( fid: str, scope: Literal['header', 'line'], - line_key: str | None = None, + draft_line_id: str | None = None, ) -> dict[str, Any]: if scope == 'header': if fid not in header_fields: @@ -489,22 +488,22 @@ def build_review_evidence_view(case) -> dict[str, Any]: field_id=fid, field_metadata=schema_fields.get(fid), scope='header', - line_key=None, + draft_line_id=None, case_id=case_id, case_document_id=case_document_id, ) return header_fields[fid] - assert line_key - if line_key not in line_fields: - line_fields[line_key] = {} - lines_order.append(line_key) - line_map = line_fields[line_key] + assert draft_line_id + if draft_line_id not in line_fields: + line_fields[draft_line_id] = {} + lines_order.append(draft_line_id) + line_map = line_fields[draft_line_id] if fid not in line_map: line_map[fid] = _build_field_view( field_id=fid, field_metadata=schema_fields.get(fid), scope='line', - line_key=line_key, + draft_line_id=draft_line_id, case_id=case_id, case_document_id=case_document_id, ) @@ -540,8 +539,8 @@ def build_review_evidence_view(case) -> dict[str, Any]: if v is not None: fv['machine_value'] = v - for line_key, _pos, fid, raw_field in _iter_unit_line_fields(order): - fv = _ensure_field(fid, 'line', line_key=line_key) + for draft_line_id, _pos, fid, raw_field in _iter_unit_line_fields(order): + fv = _ensure_field(fid, 'line', draft_line_id=draft_line_id) observations = raw_field.get('observations') or [] fc = _safe_str(raw_field.get('field_code')) or fv['field_code'] for raw_obs in observations: @@ -553,7 +552,7 @@ def build_review_evidence_view(case) -> dict[str, Any]: case_document_id=case_document_id, case_id=case_id, field_code=fc, - line_key=line_key, + draft_line_id=draft_line_id, ) fv['field_evidences'].append(norm) if fv['machine_value'] is None: @@ -597,17 +596,17 @@ def build_review_evidence_view(case) -> dict[str, Any]: # Lines draft_lines = _draft_line_list(draft) for line in draft_lines: - line_key = _safe_str(line.get('line_key')) - if not line_key: + draft_line_id = _safe_str(line.get('draft_line_id')) + if not draft_line_id: continue - line_map = line_fields.setdefault(line_key, {}) - if line_key not in lines_order: - lines_order.append(line_key) + line_map = line_fields.setdefault(draft_line_id, {}) + if draft_line_id not in lines_order: + lines_order.append(draft_line_id) for fid in list(line_map.keys()) + list(schema_fields.keys()): md = schema_fields.get(fid) if md and _safe_str(md.get('scope')) == 'header': continue - fv = _ensure_field(fid, 'line', line_key=line_key) + fv = _ensure_field(fid, 'line', draft_line_id=draft_line_id) obj = _machine_field_value(line, fid) if isinstance(obj, dict): for raw_obs in (obj.get('observations') or []): @@ -619,7 +618,7 @@ def build_review_evidence_view(case) -> dict[str, Any]: case_document_id=case_document_id, case_id=case_id, field_code=_safe_str(obj.get('field_code')) or fv['field_code'], - line_key=line_key, + draft_line_id=draft_line_id, ) fv['field_evidences'].append(norm) if fv['machine_value'] is None and obj.get('value') is not None: @@ -630,7 +629,7 @@ def build_review_evidence_view(case) -> dict[str, Any]: frozen_doc = _frozen_document_snapshot(case) for lk, fid, ridx, tid, raw_field in _iter_frozen_layout_fields(frozen_doc): scope = 'line' if lk else 'header' - fv = _ensure_field(fid, scope=scope, line_key=lk or None) + fv = _ensure_field(fid, scope=scope, draft_line_id=lk or None) wrapped = { 'value': raw_field.get('value') or raw_field.get('quote'), 'quote': raw_field.get('quote') or raw_field.get('value'), @@ -651,7 +650,7 @@ def build_review_evidence_view(case) -> dict[str, Any]: case_document_id=case_document_id, case_id=case_id, field_code=fv['field_code'], - line_key=lk or None, + draft_line_id=lk or None, derived_row_index=ridx, ) fv['field_evidences'].append(norm) @@ -683,25 +682,25 @@ def get_field_view( view: dict[str, Any], *, field_id: str, - line_key: str | None, + draft_line_id: str | None, ) -> dict[str, Any] | None: fid = str(field_id or '').strip() if not fid: return None - if line_key: - lk = str(line_key).strip() + if draft_line_id: + lk = str(draft_line_id).strip() line_map = view.get('line_fields') or {} row = line_map.get(lk) or {} return row.get(fid) or None return (view.get('header_fields') or {}).get(fid) -def count_valid_row_fields(view: dict[str, Any], line_key: str) -> int: +def count_valid_row_fields(view: dict[str, Any], draft_line_id: str) -> int: """ 同行中“有值且可发送”的字段数量(evidence 有值或 machine_value/draft_value 非空)。 用于门禁:同行字段数 >= 2 才允许 L2_row。 """ - lk = str(line_key or '').strip() + lk = str(draft_line_id or '').strip() line_map = (view.get('line_fields') or {}).get(lk) or {} count = 0 for fv in line_map.values(): diff --git a/backend/app/services/shipping_notice/order_review_field_conflict_service.py b/backend/app/services/shipping_notice/order_review_field_conflict_service.py index 2e4d7a1d..6fd7a480 100644 --- a/backend/app/services/shipping_notice/order_review_field_conflict_service.py +++ b/backend/app/services/shipping_notice/order_review_field_conflict_service.py @@ -194,7 +194,7 @@ def _finding_source_options(item: dict[str, Any]) -> list[dict[str, Any]]: return options -def _line_key_for_index(case: ShippingOrderReviewCase, line_index: int) -> str | None: +def _draft_line_id_for_index(case: ShippingOrderReviewCase, line_index: int) -> str | None: """按 line_index 定位 Draft 行键;优先显式 line_index,否则按顺序。""" draft = case.current_draft if draft is None: @@ -206,12 +206,12 @@ def _line_key_for_index(case: ShippingOrderReviewCase, line_index: int) -> str | raw_idx = raw.get('line_index') try: if raw_idx is not None and int(raw_idx) == int(line_index): - key = str(raw.get('line_key') or '').strip() + key = str(raw.get('draft_line_id') or '').strip() return key or None except (TypeError, ValueError): pass if idx == int(line_index): - key = str(raw.get('line_key') or '').strip() + key = str(raw.get('draft_line_id') or '').strip() return key or None return None @@ -322,12 +322,12 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu ) for key in value_keys ] - line_key = _line_key_for_index(case, line_index) if line_index >= 0 else None + draft_line_id = _draft_line_id_for_index(case, line_index) if line_index >= 0 else None finding = { 'conflict_key': _stored_conflict_key(item), 'field_code': field, 'line_index': line_index if line_index >= 0 else None, - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'scope': str(item.get('scope') or _finding_scope(case, field_code=field, line_index=line_index)), 'severity': str(item.get('severity') or 'blocking'), 'reason': reason, @@ -473,10 +473,10 @@ def resolve_review_case_field_conflict( header = dict(case.current_draft.header_values_json or {}) change = _set_value(header, field, chosen_display, restore_machine=False) case.current_draft.header_values_json = header - line_key = None + draft_line_id = None else: - line_key = _line_key_for_index(case, line_index) - if not line_key: + draft_line_id = _draft_line_id_for_index(case, line_index) + if not draft_line_id: raise ConflictError( 'Conflict line is missing from draft', code='SHIPPING.REVIEW_FIELD_CONFLICT_LINE_MISSING', @@ -486,14 +486,14 @@ def resolve_review_case_field_conflict( lines = list(case.current_draft.lines_json or []) target_line = None for raw in lines: - if isinstance(raw, dict) and str(raw.get('line_key') or '') == line_key: + if isinstance(raw, dict) and str(raw.get('draft_line_id') or '') == draft_line_id: target_line = raw break if target_line is None: raise ConflictError( 'Conflict line is missing from draft', code='SHIPPING.REVIEW_FIELD_CONFLICT_LINE_MISSING', - details={'line_key': line_key}, + details={'draft_line_id': draft_line_id}, ) change = _set_value(target_line, field, chosen_display, restore_machine=False) case.current_draft.lines_json = lines @@ -514,7 +514,7 @@ def resolve_review_case_field_conflict( operation={ 'conflict_key': conflict_key, 'field_code': field_code, - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'resolution': mode, 'option_index': option_index, 'chosen_value': chosen_display, diff --git a/backend/app/services/shipping_notice/order_review_llm_auto_upgrade.py b/backend/app/services/shipping_notice/order_review_llm_auto_upgrade.py index a0ecd7cc..4221d559 100644 --- a/backend/app/services/shipping_notice/order_review_llm_auto_upgrade.py +++ b/backend/app/services/shipping_notice/order_review_llm_auto_upgrade.py @@ -145,14 +145,14 @@ def _check_table_duplicate_value( evidence_view: dict[str, Any], *, field_id: str, - line_key: str | None, + draft_line_id: str | None, field_view_obj: dict[str, Any], ) -> bool: """ [Priority 4] Line scope:同一 table 中多个行存在与目标字段相同的 value。 Header scope:此检测跳过(不适用)。目标 value 为空时跳过。 """ - if not line_key: + if not draft_line_id: return False if not isinstance(evidence_view, dict): return False @@ -169,7 +169,7 @@ def _check_table_duplicate_value( return False same_table_hits = 0 for lk, lf_map in line_fields.items(): - if lk == str(line_key) or not isinstance(lf_map, dict): + if lk == str(draft_line_id) or not isinstance(lf_map, dict): continue fv = lf_map.get(str(field_id)) if not isinstance(fv, dict): @@ -206,16 +206,16 @@ def _check_manual_conflict(field_view: dict[str, Any]) -> bool: def _check_context_borderline( evidence_view: dict[str, Any], *, - line_key: str | None, + draft_line_id: str | None, ) -> bool: """ [Priority 6] Line scope 同行有效字段数正好 = 门禁最低阈值(2)。 处于门禁临界线,证据不稳,升级到表格更安全。Header scope 跳过。 """ - if not line_key: + if not draft_line_id: return False try: - siblings = count_valid_row_fields(evidence_view, str(line_key)) + siblings = count_valid_row_fields(evidence_view, str(draft_line_id)) except Exception: return False return siblings == _BORDERLINE_SIBLING_COUNT @@ -224,20 +224,20 @@ def _check_context_borderline( def _check_context_identity_insufficient( evidence_view: dict[str, Any], *, - line_key: str | None, + draft_line_id: str | None, field_view_obj: dict[str, Any], ) -> bool: """ [Priority 7] Line scope:同行缺少明确身份标识字段(如 part_number / line_no), 或目标字段 primary_evidence.confidence 低于阈值。 """ - if not line_key: + if not draft_line_id: return False if not isinstance(evidence_view, dict): return False # 身份标识检测 line_fields = evidence_view.get('line_fields') or {} - lf = line_fields.get(str(line_key)) if isinstance(line_fields, dict) else None + lf = line_fields.get(str(draft_line_id)) if isinstance(line_fields, dict) else None has_identity = False if isinstance(lf, dict): for fid, fv in lf.items(): @@ -276,7 +276,7 @@ def resolve_auto_upgrade_level( *, evidence_view: dict[str, Any], field_id: str, - line_key: str | None, + draft_line_id: str | None, requested_level: EvidenceLevelV2, schema_field_meta: dict[str, Any] | None = None, issue_code: str | None = None, @@ -287,7 +287,7 @@ def resolve_auto_upgrade_level( Args: evidence_view: build_review_evidence_view() 的返回。 field_id: 目标字段 ID。 - line_key: 目标行键;None 表示 header scope。 + draft_line_id: 目标草稿行身份;None 表示 header scope。 requested_level: 用户/前端请求的等级(默认 L2_row)。 schema_field_meta: schema.definition_json.fields[] 中的原始元数据。 issue_code: 前端透传的冲突 issue_code(触发 P1)。 @@ -301,7 +301,7 @@ def resolve_auto_upgrade_level( if not isinstance(evidence_view, dict): return requested_level, None, [] - field_view = get_field_view(evidence_view, field_id=field_id, line_key=line_key) + field_view = get_field_view(evidence_view, field_id=field_id, draft_line_id=draft_line_id) if field_view is None: return requested_level, None, [] @@ -313,7 +313,7 @@ def resolve_auto_upgrade_level( if str(requested_level) not in {'L1_field', 'L2_row'}: return requested_level, None, [] - scope_is_line = bool(line_key) + scope_is_line = bool(draft_line_id) reasons_hit: list[str] = [] # [STEP 1] 按优先级顺序跑 7 项检测,命中即追加 @@ -326,17 +326,17 @@ def resolve_auto_upgrade_level( if _check_table_duplicate_value( evidence_view, field_id=field_id, - line_key=line_key, + draft_line_id=draft_line_id, field_view_obj=field_view, ): reasons_hit.append('table_duplicate_value') if _check_manual_conflict(field_view): reasons_hit.append('manual_conflict') - if _check_context_borderline(evidence_view, line_key=line_key): + if _check_context_borderline(evidence_view, draft_line_id=draft_line_id): reasons_hit.append('context_borderline') if _check_context_identity_insufficient( evidence_view, - line_key=line_key, + draft_line_id=draft_line_id, field_view_obj=field_view, ): reasons_hit.append('context_identity_insufficient') diff --git a/backend/app/services/shipping_notice/order_review_llm_contract.py b/backend/app/services/shipping_notice/order_review_llm_contract.py index e923af20..f8cf7282 100644 --- a/backend/app/services/shipping_notice/order_review_llm_contract.py +++ b/backend/app/services/shipping_notice/order_review_llm_contract.py @@ -180,9 +180,9 @@ def is_valid_provenance_ref(value: Any) -> bool: return _DRAFT_REF_RE.match(value.strip()) is not None -def build_provenance_ref(*, case_id: int, line_key: str | None, field_code: str) -> str: +def build_provenance_ref(*, case_id: int, draft_line_id: str | None, field_code: str) -> str: """生成 Draft 回退专用的 provenance_ref(不伪装成 evidence_ref)。""" - line = str(line_key or 'header').strip() or 'header' + line = str(draft_line_id or 'header').strip() or 'header' return f'draft:case-{int(case_id)}:line-{line}:field-{str(field_code).strip()}' # --------------------------------------------------------------------------- @@ -231,10 +231,10 @@ class V2Target(TypedDict, total=False): field_id: str field_code: str scope: Literal['header', 'line'] - line_key: str | None + draft_line_id: str | None class V2RowContext(TypedDict, total=False): - line_key: str + draft_line_id: str fields: list[dict[str, Any]] # 每个字段含 field_id/field_code/machine_value/current_draft_value/value_source/evidence_ref/source class V2TableContext(TypedDict, total=False): @@ -243,7 +243,7 @@ class V2TableContext(TypedDict, total=False): target_row_index: int | None class V2NeighborRow(TypedDict, total=False): - line_key: str + draft_line_id: str row_index: int fields: list[dict[str, Any]] position: Literal['preceding', 'following'] @@ -347,7 +347,7 @@ def build_suggestion_request_envelope( return envelope # --------------------------------------------------------------------------- -# 响应解析(v1/v2 统一出口,line_key/scope/needs_review v2 新增) +# 响应解析(v1/v2 统一出口,draft_line_id/scope/needs_review v2 新增) # --------------------------------------------------------------------------- def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any]]: """ @@ -371,10 +371,10 @@ def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any] needs_review = False if isinstance(item.get('needs_review'), bool): needs_review = bool(item['needs_review']) - line_key_raw = item.get('line_key') - line_key = str(line_key_raw).strip() if line_key_raw is not None else None - if not line_key: - line_key = None + draft_line_id_raw = item.get('draft_line_id') + draft_line_id = str(draft_line_id_raw).strip() if draft_line_id_raw is not None else None + if not draft_line_id: + draft_line_id = None scope = str(item.get('scope') or '').strip().lower() if scope not in {'header', 'line'}: scope = 'line' @@ -387,7 +387,7 @@ def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any] 'field_id': field_id, 'field_code': str(item.get('field_code') or '').strip() or None, 'scope': scope, - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'suggested_value': item.get('suggested_value'), 'quote': str(item.get('quote') or item.get('suggested_value') or '')[:1000], 'confidence': confidence, diff --git a/backend/app/services/shipping_notice/order_review_llm_gate.py b/backend/app/services/shipping_notice/order_review_llm_gate.py index a79efd16..6bbf3715 100644 --- a/backend/app/services/shipping_notice/order_review_llm_gate.py +++ b/backend/app/services/shipping_notice/order_review_llm_gate.py @@ -9,7 +9,7 @@ services/shipping_notice/order_review_llm_gate.py - order_review_llm_policy_registry.resolve_llm_context_policy 逻辑: [1] field_not_found 目标 field_id 在 schema 中不存在 - [2] line_not_found 目标 line_key 在视图中行找不到 + [2] line_not_found 目标 draft_line_id 在视图中行找不到 [3] field_value_missing 目标字段 machine/draft/primary_evidence 三者全空 [4] evidence_unavailable 目标字段无任何 field_evidences[](三源都没有事实) [5] context_ambiguous unit orders >1 且无法按 primary_document_id 唯一确定 @@ -57,7 +57,7 @@ def run_preflight_gate( evidence_view: dict[str, Any], *, field_id: str, - line_key: str | None, + draft_line_id: str | None, requested_level: EvidenceLevelV2 | None, schema_field_meta: dict[str, Any] | None = None, ) -> GateResult: @@ -77,15 +77,15 @@ def run_preflight_gate( return False, 'context_ambiguous', \ '; '.join(str(r) for r in ambiguous_reasons) - # [2] line scope 需要 line_key 存在 - scope_is_line = bool(line_key) + # [2] line scope 需要 draft_line_id 存在 + scope_is_line = bool(draft_line_id) if scope_is_line: line_fields = evidence_view.get('line_fields') or {} - if str(line_key) not in line_fields: - return False, 'line_not_found', f'line_key={line_key}' + if str(draft_line_id) not in line_fields: + return False, 'line_not_found', f'draft_line_id={draft_line_id}' # [1] field_id 找不到(header/line 都没命中) - field_view = get_field_view(evidence_view, field_id=field_id, line_key=line_key) + field_view = get_field_view(evidence_view, field_id=field_id, draft_line_id=draft_line_id) if field_view is None: return False, 'field_not_found', f'field_id={field_id}' @@ -127,10 +127,10 @@ def run_preflight_gate( effective_level = requested_level or 'L2_row' if effective_level not in _SENSITIVE_MASK_LEVELS and effective_level in EVIDENCE_LEVELS_V2_ALLOWED: if scope_is_line and str(effective_level) in ('L2_row',): - siblings = count_valid_row_fields(evidence_view, str(line_key)) + siblings = count_valid_row_fields(evidence_view, str(draft_line_id)) if siblings < _MIN_LINE_SIBLINGS: return False, 'context_insufficient', \ - f'line_key={line_key} valid siblings={siblings} required>={_MIN_LINE_SIBLINGS}' + f'draft_line_id={draft_line_id} valid siblings={siblings} required>={_MIN_LINE_SIBLINGS}' return True, None, None diff --git a/backend/app/services/shipping_notice/order_review_llm_service.py b/backend/app/services/shipping_notice/order_review_llm_service.py index 7cfc03fd..2634c192 100644 --- a/backend/app/services/shipping_notice/order_review_llm_service.py +++ b/backend/app/services/shipping_notice/order_review_llm_service.py @@ -117,7 +117,7 @@ def _audit_llm_suggestion( """ after_payload = { 'field_id': suggestion.field_id, - 'line_key': suggestion.line_key, + 'draft_line_id': suggestion.draft_line_id, 'status': suggestion.status, 'decision': suggestion.decision, **(after or {}), @@ -242,7 +242,7 @@ def serialize_suggestion( base: dict[str, Any] = { 'suggestion_no': row.suggestion_no, 'field_id': row.field_id, - 'line_key': row.line_key, + 'draft_line_id': row.draft_line_id, 'scope': row.scope, 'evidence_level': row.evidence_level, 'contract_version': row.contract_version, @@ -289,7 +289,7 @@ def serialize_suggestion( 'field_id': (i.get('field_id') if isinstance(i, dict) else None), 'field_code': (i.get('field_code') if isinstance(i, dict) else None), 'scope': (i.get('scope') if isinstance(i, dict) else None), - 'line_key': (i.get('line_key') if isinstance(i, dict) else None), + 'draft_line_id': (i.get('draft_line_id') if isinstance(i, dict) else None), } for i in tf if isinstance(i, dict) ][:50] @@ -368,7 +368,7 @@ def request_field_suggestion( user_id: int, case_no: str, field_id: str, - line_key: str | None = None, + draft_line_id: str | None = None, evidence_level: str | None = None, issue_code: str | None = None, allow_full_pdf: bool = False, @@ -381,7 +381,7 @@ def request_field_suggestion( user_id: Case 属主。 case_no: 复核 Case 编号。 field_id: 目标 field_id。 - line_key: 明细行键。 + draft_line_id: 草稿行身份。 evidence_level: L1_field–L4_pdf。 issue_code: 关联 issue。 allow_full_pdf: 管理员显式 L4。 @@ -396,8 +396,8 @@ def request_field_suggestion( field = _schema_field(case, field_id) scope = str(field.get('scope') or 'header') - if scope == 'line' and not line_key: - raise ValidationError('line_key is required for line scope', code='SHIPPING.REVIEW_LINE_NOT_FOUND') + if scope == 'line' and not draft_line_id: + raise ValidationError('draft_line_id is required for line scope', code='SHIPPING.REVIEW_LINE_NOT_FOUND') level_raw = _normalize_level(evidence_level or 'L1_field') if level_raw == 'L4_pdf' and not (is_admin and allow_full_pdf): @@ -409,7 +409,7 @@ def request_field_suggestion( 'field_id': str(field_id), 'field_code': str(field.get('field_code') or field_id), 'scope': scope, - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'line_number': None, }] row = ShippingOrderReviewSuggestion( @@ -418,7 +418,7 @@ def request_field_suggestion( document_id=int(case.document_id), run_id=int(case.run_id) if case.run_id else None, field_id=str(field_id), - line_key=str(line_key) if line_key else None, + draft_line_id=str(draft_line_id) if draft_line_id else None, scope=scope, evidence_level=level, status='pending', @@ -454,7 +454,7 @@ def request_field_suggestion( upgraded_level, up_reason, up_reasons = resolve_auto_upgrade_level( evidence_view=evidence_view, field_id=str(field_id), - line_key=str(line_key) if line_key else None, + draft_line_id=str(draft_line_id) if draft_line_id else None, requested_level=level, # type: ignore[arg-type] schema_field_meta=field, issue_code=issue_code, @@ -488,15 +488,15 @@ def request_field_suggestion( passed, gate_error, gate_hint = run_preflight_gate( evidence_view, field_id=str(field_id), - line_key=str(line_key) if line_key else None, + draft_line_id=str(draft_line_id) if draft_line_id else None, requested_level=level, # type: ignore[arg-type] schema_field_meta=field, ) # 填充观测列(gated 或未 gated 都写,便于对账 context_hash) _evidence_view_count = 0 - if line_key: + if draft_line_id: line_map = (evidence_view or {}).get('line_fields') or {} - row_map = line_map.get(str(line_key)) or {} + row_map = line_map.get(str(draft_line_id)) or {} target_view = row_map.get(str(field_id)) else: header_map = (evidence_view or {}).get('header_fields') or {} @@ -617,7 +617,7 @@ def request_field_suggestion( 'field_id': str(field_id), 'field_code': str(field.get('field_code') or field_id), 'scope': scope, - 'line_key': line_key, + 'draft_line_id': draft_line_id, }, expected_target_field_id=str(field_id), auto_upgrade_reason=_auto_upgrade_reason, @@ -631,7 +631,7 @@ def request_field_suggestion( 'document_id': int(case.document_id), 'draft_version': int(case.current_draft.draft_version if case.current_draft else 0), 'field_id': str(field_id), - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'contract_version': LLM_REVIEW_CONTRACT_VERSION, 'evidence_level': level, 'target_fields': target_fields, @@ -781,7 +781,7 @@ def request_field_suggestion( evidence_pack=evidence_pack, envelope=request_payload, expected_target_field_id=str(field_id), - expected_line_key=line_key, + expected_draft_line_id=draft_line_id, expected_scope=scope, ) row.validated_suggestions_json = validated @@ -827,7 +827,7 @@ def request_field_suggestion( user_id=user_id, case_no=case_no, field_id=str(field_id), - line_key=line_key, + draft_line_id=draft_line_id, value=value, suggestion_no=row.suggestion_no, expected_draft_version=int(case.current_draft.draft_version), @@ -914,7 +914,7 @@ def decide_suggestion( before_status = { 'status': suggestion.status, 'field_id': suggestion.field_id, - 'line_key': suggestion.line_key, + 'draft_line_id': suggestion.draft_line_id, } case_payload = adjudicate_llm_suggestion_on_draft( user_id=user_id, diff --git a/backend/app/services/shipping_notice/order_review_llm_validation.py b/backend/app/services/shipping_notice/order_review_llm_validation.py index 88c4cc94..c9051329 100644 --- a/backend/app/services/shipping_notice/order_review_llm_validation.py +++ b/backend/app/services/shipping_notice/order_review_llm_validation.py @@ -5,15 +5,15 @@ services/shipping_notice/order_review_llm_validation.py 任何一项未通过 → validation_failed,该建议仅能 reject,禁止 accept/modify 写入草稿。 依赖: - order_review_llm_contract:QUOTE_NORMALIZATION_RULES / normalize_quote_text - - request_payload.envelope:target / expected_target_field_id / evidence[] / line_key 定位 - - 响应解析层:parse_suggestion_response 输出 [{field_id, line_key, scope, suggested_value, quote}] + - request_payload.envelope:target / expected_target_field_id / evidence[] / draft_line_id 定位 + - 响应解析层:parse_suggestion_response 输出 [{field_id, draft_line_id, scope, suggested_value, quote}] 逻辑: 8 项按顺序 fail-closed(优先级从身份→价值→安全性): 1. json_schema_invalid 响应项非 dict / field_id 为空(结构性非法) - 2. header_scope_has_line_key scope=header 时 line_key 不为 None(头部不能带行键) + 2. header_scope_has_draft_line_id scope=header 时 draft_line_id 不为 None 3. non_target_field 响应 field_id 不在请求 expected_target_field_id 内 4. field_id_mismatch 响应 field_id 与 expected_target_field_id 不一致 - 5. line_key_mismatch scope=line 时响应 line_key != 请求 line_key(精确相等) + 5. draft_line_id_mismatch scope=line 时响应 draft_line_id != 请求值(精确相等) 6. value_not_in_evidence suggested_value 不在 evidence[] 任何 value/quote(normalize 后) 7. quote_consistency 响应 quote normalize 后与 suggested_value quote 不构成 substring 或 完整相等;即使值存在也视为伪造 @@ -38,10 +38,10 @@ from app.services.shipping_notice.order_review_llm_contract import ( # --------------------------------------------------------------------------- _VALIDATION_CHECKS_ORDER: Final[tuple[str, ...]] = ( 'json_schema_invalid', - 'header_scope_has_line_key', + 'header_scope_has_draft_line_id', 'non_target_field', 'field_id_mismatch', - 'line_key_mismatch', + 'draft_line_id_mismatch', 'value_not_in_evidence', 'quote_consistency', 'guess_without_evidence', @@ -55,7 +55,7 @@ def _collect_evidence_values( """ 从 v2 envelope.evidence 或 v1 evidence_pack.fields[].snippets 提取候选值池。 v2 优先读 envelope.evidence;缺失时回退 v1 结构(兼容历史 contract)。 - 每项返回 {value_norm, quote_norm, value_raw, quote_raw, field_id, line_key, evidence_ref} + 每项返回 {value_norm, quote_norm, value_raw, quote_raw, field_id, draft_line_id, evidence_ref} """ pool: list[dict[str, Any]] = [] env = envelope if isinstance(envelope, dict) else {} @@ -72,7 +72,7 @@ def _collect_evidence_values( 'value_raw': None if v_raw is None else str(v_raw), 'quote_raw': None if q_raw is None else str(q_raw), 'field_id': str(ev.get('field_id') or ''), - 'line_key': str(ev.get('line_key') or '').strip() or None, + 'draft_line_id': str(ev.get('draft_line_id') or '').strip() or None, 'evidence_ref': ev.get('evidence_ref'), }) return pool @@ -82,7 +82,7 @@ def _collect_evidence_values( if not isinstance(f, dict): continue fid = str(f.get('field_id') or '') - lk = str(f.get('line_key') or '').strip() or None + draft_line_id = str(f.get('draft_line_id') or '').strip() or None for sn in (f.get('snippets') or []): if not isinstance(sn, dict): continue @@ -94,44 +94,56 @@ def _collect_evidence_values( 'value_raw': None if v_raw is None else str(v_raw), 'quote_raw': None if q_raw is None else str(q_raw), 'field_id': fid, - 'line_key': lk, + 'draft_line_id': draft_line_id, 'evidence_ref': sn.get('evidence_ref'), }) return pool +def _is_pure_numeric(value: str) -> bool: + """判定某值是否为纯数字(可含正负号/小数点)。纯数字的子串匹配无意义(如 '10' 命中 '100'), + 会放行数量失真/幻觉,因此纯数字值只允许精确匹配,禁用子串匹配。""" + if not value: + return False + stripped = value.strip().lstrip('+-') + if not stripped: + return False + return stripped.replace('.', '', 1).isdigit() and any(ch.isdigit() for ch in stripped) + + def _find_value_match( pool: list[dict[str, Any]], *, value_norm: str, quote_norm_provided: str, field_id: str, - line_key: str | None, + draft_line_id: str | None, ) -> tuple[str, dict[str, Any] | None]: """ 在候选池中按 4 级严格度递减匹配 value;返回 (mode, matched_item)。 严格度:exact → exact_substring → normalized → normalized_substring - 同池内优先匹配 field_id + line_key 双重身份的项;其次 field_id;最后全局任意项。 + 同池内优先匹配 field_id + draft_line_id 双重身份的项;其次 field_id;最后全局任意项。 """ if not value_norm and not quote_norm_provided: return '', None - # 身份过滤:先 field_id + line_key + # 身份过滤:先 field_id + draft_line_id def _iter_filtered(): if not pool: return same_identity = [ p for p in pool if str(p.get('field_id') or '') == field_id - and (str(p.get('line_key') or '') == str(line_key or '') - if line_key else not p.get('line_key')) + and (str(p.get('draft_line_id') or '') == str(draft_line_id or '') + if draft_line_id else not p.get('draft_line_id')) ] same_field = [ p for p in pool if str(p.get('field_id') or '') == field_id and p not in same_identity ] - others = [p for p in pool if p not in same_identity and p not in same_field] - for p in same_identity + same_field + others: + # 字段隔离:只允许用同 field_id 的证据验证当前字段建议, + # 禁止用其它字段(others)的证据兜底,避免跨字段误判(fail-closed)。 + for p in same_identity + same_field: yield p # 1. exact:raw 完全相等 @@ -142,12 +154,12 @@ def _find_value_match( if (vr and vr == needle) or (qr and qr == needle): return 'exact', p - # 2. exact_substring:raw 内 substring + # 2. exact_substring:raw 内 substring(纯数字禁用子串,防止 '10' 误命中 '100') for p in _iter_filtered(): vr = (p.get('value_raw') or '').strip() qr = (p.get('quote_raw') or '').strip() needle = value_norm.strip() - if not needle: + if not needle or _is_pure_numeric(needle): continue if (vr and needle in vr) or (qr and needle in qr): return 'exact_substring', p @@ -159,11 +171,11 @@ def _find_value_match( if (vn and vn == value_norm) or (qn and qn == value_norm): return 'normalized', p - # 4. normalized_substring:norm 内 substring + # 4. normalized_substring:norm 内 substring(纯数字禁用子串) for p in _iter_filtered(): vn = p.get('value_norm') or '' qn = p.get('quote_norm') or '' - if not value_norm: + if not value_norm or _is_pure_numeric(value_norm): continue if (vn and value_norm in vn) or (qn and value_norm in qn): return 'normalized_substring', p @@ -225,7 +237,7 @@ def validate_suggestions_against_evidence( evidence_pack: dict[str, Any], envelope: dict[str, Any] | None = None, expected_target_field_id: str | None = None, - expected_line_key: str | None = None, + expected_draft_line_id: str | None = None, expected_scope: str | None = None, ) -> list[dict[str, Any]]: """ @@ -236,7 +248,7 @@ def validate_suggestions_against_evidence( evidence_pack: select_review_evidence_pack 输出(v1/v2 均含 fields 等)。 envelope: build_suggestion_request_envelope 输出(用于 v2 evidence[] 和 target)。 expected_target_field_id: 期望的唯一目标 field_id(v2 envelope.target.field_id 兜底)。 - expected_line_key: 期望 line_key(行 scope 用;header scope 传 None)。 + expected_draft_line_id: 期望草稿行身份(行 scope 用;header scope 传 None)。 expected_scope: 'header' / 'line'(从 schema_field_meta.scope 兜底)。 Returns: @@ -258,9 +270,9 @@ def validate_suggestions_against_evidence( or str(target.get('field_id') or '').strip() or '' ) - _exp_lk_raw = expected_line_key + _exp_lk_raw = expected_draft_line_id if _exp_lk_raw is None: - _exp_lk_from_env = target.get('line_key') + _exp_lk_from_env = target.get('draft_line_id') _exp_lk_raw = None if _exp_lk_from_env is None else str(_exp_lk_from_env) _exp_lk = str(_exp_lk_raw).strip() if _exp_lk_raw is not None else None if _exp_lk == '' or _exp_lk == 'None': @@ -296,18 +308,18 @@ def validate_suggestions_against_evidence( result.append(payload) continue - # ---- [Check 2] header_scope_has_line_key ---- - checks_ran.append('header_scope_has_line_key') + # ---- [Check 2] header_scope_has_draft_line_id ---- + checks_ran.append('header_scope_has_draft_line_id') resp_scope = str(raw_item.get('scope') or '').strip().lower() if not resp_scope: resp_scope = 'line' if _exp_lk else 'header' - resp_lk_raw = raw_item.get('line_key') + resp_lk_raw = raw_item.get('draft_line_id') resp_lk = None if resp_lk_raw is None else str(resp_lk_raw).strip() if resp_lk in ('', 'None'): resp_lk = None effective_scope = _exp_scope if resp_scope not in {'header', 'line'} else resp_scope if effective_scope == 'header' and resp_lk is not None: - rejection_reason = 'header_scope_has_line_key' + rejection_reason = 'header_scope_has_draft_line_id' if rejection_reason: payload['valid'] = False payload['rejection_reason'] = rejection_reason @@ -338,11 +350,11 @@ def validate_suggestions_against_evidence( result.append(payload) continue - # ---- [Check 5] line_key_mismatch(行 scope 才校验;header scope line_key 须 None 已在 Check 2)---- - checks_ran.append('line_key_mismatch') + # ---- [Check 5] draft_line_id_mismatch ---- + checks_ran.append('draft_line_id_mismatch') if effective_scope == 'line': if _exp_lk and resp_lk != _exp_lk: - rejection_reason = 'line_key_mismatch' + rejection_reason = 'draft_line_id_mismatch' if rejection_reason: payload['valid'] = False payload['rejection_reason'] = rejection_reason @@ -368,7 +380,7 @@ def validate_suggestions_against_evidence( value_norm=sv_norm, quote_norm_provided=quote_norm, field_id=resp_fid, - line_key=resp_lk, + draft_line_id=resp_lk, ) if not _matched_mode: rejection_reason = 'value_not_in_evidence' diff --git a/backend/app/services/shipping_notice/order_review_reservation_service.py b/backend/app/services/shipping_notice/order_review_reservation_service.py index f103b81f..a7b127f6 100644 --- a/backend/app/services/shipping_notice/order_review_reservation_service.py +++ b/backend/app/services/shipping_notice/order_review_reservation_service.py @@ -112,7 +112,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str, if not isinstance(proj, dict): continue effective = str(proj.get('effective_reservation_id') or '').strip() or None - line_key = str(proj.get('line_key') or '').strip() or None + draft_line_id = str(proj.get('draft_line_id') or '').strip() or None block_reason = str(proj.get('block_reason') or '').strip() or None line_reservation_issue = next( ( @@ -133,7 +133,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str, ) lines_out.append({ 'line_index': idx, - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'effective_reservation_id': effective, 'can_build': bool(proj.get('can_build', True)), # Reservation 面板只展示自身 Gate 原因,不能泄漏库存路由 block_reason。 @@ -150,7 +150,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str, rid = _current_line_reservation_id(line, reservation_field_id) lines_out.append({ 'line_index': idx, - 'line_key': str(line.get('line_key') or '').strip() or None, + 'draft_line_id': str(line.get('draft_line_id') or '').strip() or None, 'effective_reservation_id': rid, 'can_build': True, 'block_reason': None, @@ -170,7 +170,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str, 'severity': str(item.get('severity') or 'blocking')[:32], 'message': str(item.get('message') or '')[:240] or None, 'line_index': item.get('line_index'), - 'line_key': item.get('line_key'), + 'draft_line_id': item.get('draft_line_id'), 'field_code': item.get('field_code') or 'reservation_id', } for item in issues[:20] diff --git a/backend/app/services/shipping_notice/order_supplement_merge.py b/backend/app/services/shipping_notice/order_supplement_merge.py index ddc5d92c..112ebee3 100644 --- a/backend/app/services/shipping_notice/order_supplement_merge.py +++ b/backend/app/services/shipping_notice/order_supplement_merge.py @@ -80,6 +80,68 @@ def _canonical_values(fields: Any, code: str, codes: dict[str, str], config: dic } +def _canonical_values_span( + fields: Any, span_codes: set[str], ids: dict[str, str], configs: dict[str, dict[str, Any]], +) -> set[Any]: + """收集字段跨多个同订单料号身份 code 的规范值集合(件号/客户件号交叉)。 + + 与匹配层 `part_number ∪ customer_part_number` 的裁决保持一致:邮件补充的 PN 列 + 值可能实为客户件号(MPN),只要命中 PDF 的任一料号身份就视为同一料号, + 禁止把「邮件 PN = PDF 客户件号」判成 `part_number` 字段冲突。 + + Args: + fields: 目标字段 Observation 列表(header 或 line)。 + span_codes: 视作同一身份的字段 code 集合(如 {'part_number','customer_part_number'})。 + ids: {field_code: field_id} 映射。 + configs: {field_code: 冻结 Schema 配置} 映射,用于各字段独立标准化。 + + Returns: + 跨这些 code 收集到的规范值集合。 + """ + if not isinstance(fields, list): + return set() + code_by_id = {str(field_id): code for code, field_id in ids.items()} + out: set[Any] = set() + for field in fields: + if not isinstance(field, dict): + continue + code = code_by_id.get(str(field.get('field_id') or '')) + if code not in span_codes: + continue + config = configs.get(code) + if config is None: + continue + for observation in field.get('observations') or []: + if isinstance(observation, dict) and observation.get('value') not in (None, ''): + out.add(_canonical_field_value(observation.get('value'), config)) + return out + + +# 采购单号类字段:跨来源比较须与匹配层一致,用 PO 专用标准化(含前导零归一), +# 否则 0060208010 与 60208010 会被 Schema「lowercase_trim」误判为不同 PO 而制造冲突。 +_PO_CODES = {'customer_po_number', 'po_number'} + + +def _conflict_canonical(value: Any, field_code: str, config: dict[str, Any]) -> Any: + """返回冲突比较用的字段规范值;PO 类字段复用 PO 标准化,其余走 Schema 正常化。""" + if field_code in _PO_CODES: + return normalize_atomic_po_number(value).upper() + return _canonical_field_value(value, config) + + +def _conflict_canonical_values(fields: Any, code: str, codes: dict[str, str], config: dict[str, Any]) -> set[Any]: + """收集字段冲突比较用的规范值集合;PO 类字段使用 _conflict_canonical。""" + if not isinstance(fields, list): + return set() + return { + _conflict_canonical(observation.get('value'), code, config) + for field in fields if isinstance(field, dict) + if codes.get(str(field.get('field_id') or '')) == code + for observation in field.get('observations') or [] if isinstance(observation, dict) + if observation.get('value') not in (None, '') + } + + def _field_observations(fields: Any, code: str, codes: dict[str, str]) -> list[dict[str, Any]]: """返回字段的原始 Observation,供冲突 Finding 保留 PDF 侧可追溯证据。""" if not isinstance(fields, list): @@ -125,14 +187,21 @@ def _supplement_field_conflict( { 'source_type': 'pdf', 'raw_value': str(pdf_raw), - 'canonical_value': str(_canonical_field_value(pdf_raw, config)), + 'canonical_value': str(_conflict_canonical(pdf_raw, field_code, config)), 'document_id': pdf.get('document_id'), - 'evidence_ref': dict(pdf.get('evidence_ref') or {}), + # evidence_ref 必须保持 dict 契约(review/evidence 消费方按 dict 处理)。 + # 坐标 observation 的 evidence_ref 是字符串、layout_evidence 才是证据 dict; + # 直接用 dict(<字符串>) 会把字符串按字符拆成长度1序列而崩(dictionary update length 1)。 + 'evidence_ref': ( + pdf.get('layout_evidence') + if isinstance(pdf.get('layout_evidence'), dict) + else (pdf.get('evidence_ref') if isinstance(pdf.get('evidence_ref'), dict) else {}) + ), }, { 'source_type': 'email_body', 'raw_value': str(email_raw), - 'canonical_value': str(_canonical_field_value(email_raw, config)), + 'canonical_value': str(_conflict_canonical(email_raw, field_code, config)), 'document_id': email_document_id or None, 'evidence_ref': dict(email_evidence or {}), }, @@ -162,7 +231,7 @@ def _supplement_multi_value_conflict( sources.append({ 'source_type': 'email_body', 'raw_value': raw_value, - 'canonical_value': str(_canonical_field_value(raw_value, config)), + 'canonical_value': str(_conflict_canonical(raw_value, field_code, config)), 'document_id': email_document_id or None, 'evidence_ref': dict(evidence or {}), }) @@ -271,7 +340,7 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta raw_value = str(item.get(target_code) or '').strip() if raw_value: value_by_canonical.setdefault( - _canonical_field_value(raw_value, config), + _conflict_canonical(raw_value, target_code, config), (raw_value, item), ) values = {raw_value for raw_value, _ in value_by_canonical.values()} @@ -292,13 +361,23 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta field_id = ids.get(target_code) if not value or not field_id: continue - existing_values = _canonical_values( + same_code_values = _conflict_canonical_values( fields, target_code, {v: k for k, v in ids.items()}, config, ) - if existing_values: + if same_code_values: # PDF 是主证据,但正文给出不同的唯一 Schema 值也不能被静默忽略: # 保留 PDF 值,强制进入 Review 由人工裁决。 - if existing_values != {_canonical_field_value(value, config)}: + email_canonical = _conflict_canonical(value, target_code, config) + if target_code in part_codes: + # 件号/客户件号属同一料号身份:邮件值命中任一 PDF 料号即视为一致, + # 不因「邮件 PN 实为客户件号(MPN)」制造误判 `part_number` 冲突。 + conflicts_with_pdf = ( + email_canonical + not in _canonical_values_span(fields, part_codes, ids, configs) + ) + else: + conflicts_with_pdf = same_code_values != {email_canonical} + if conflicts_with_pdf: conflict = _supplement_field_conflict( field_code=target_code, config=config, diff --git a/backend/app/services/shipping_notice/order_task_service.py b/backend/app/services/shipping_notice/order_task_service.py index 62021249..74a66ed6 100644 --- a/backend/app/services/shipping_notice/order_task_service.py +++ b/backend/app/services/shipping_notice/order_task_service.py @@ -9,7 +9,7 @@ backend/app/services/shipping_notice/order_task_service.py 局部重识别走 replace_order_task_candidate_after_reparse(专用审计); sync_order_task_processing_state 统一写入 stage/status、递增 progress_version, 并强制写 order_task_progress_changed 审计; - 建单成功后按 candidate_id 定位 OT 再挂 shipping_notice_id(禁止误用 Run 根号串单); + 正式 ShippingNotice 通过 order_task_id 关联 OT;OT 不反向保存通知单指针。 GET 投影只读本表,禁止读路径创建。 """ @@ -146,7 +146,6 @@ def sync_order_task_processing_state( }, metadata={ 'extraction_run_id': getattr(order_task, 'extraction_run_id', None), - 'shipping_notice_id': getattr(order_task, 'shipping_notice_id', None), 'candidate_id': getattr(order_task, 'candidate_id', None), }, source=str(source or 'order_task_service'), @@ -442,11 +441,6 @@ def replace_order_task_candidate_after_review( 'order task candidate binding changed concurrently', code='SHIPPING_NOTICE.ORDER_TASK_CANDIDATE_MISMATCH', ) - if order_task.shipping_notice_id is not None: - raise ConflictError( - 'order task already linked to a shipping notice', - code='SHIPPING_NOTICE.ORDER_TASK_ALREADY_LINKED', - ) case_document_id = int(case.document_id) if getattr(case, 'document_id', None) else None new_document_id = ( @@ -938,7 +932,7 @@ def resolve_order_task_for_candidate(candidate_id: int | None) -> Optional[Shipp def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional[ShippingOrderTask]: """ - 建单成功后双向挂接 OT ↔ Notice。 + 将正式 Notice 单向挂接到 OT。 Args: order_task_no: OT 编号(须为该 Candidate 自己的 OT,禁止误用 Run 根号)。 @@ -957,15 +951,7 @@ def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional ) if row is None: return None - before = { - 'shipping_notice_id': row.shipping_notice_id, - 'candidate_id': row.candidate_id, - } - # 兼容字段只在首张 Notice 尚未建立时回填,后续分批 Notice 以 - # ShippingNotice.order_task_id 的多对一关系为权威,禁止覆盖首条指针。 - if row.shipping_notice_id is None: - row.shipping_notice_id = int(notice_id) - row.updated_at = datetime.utcnow() + before = {'candidate_id': row.candidate_id} from app.models import ShippingNotice notice = db.session.get(ShippingNotice, int(notice_id)) @@ -985,7 +971,6 @@ def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional reason_code='notice_created', before=before, after={ - 'shipping_notice_id': row.shipping_notice_id, 'candidate_id': row.candidate_id, 'notice_task_no': str(getattr(notice, 'task_no', None) or '') or None, }, diff --git a/backend/app/services/shipping_notice/order_task_stage_machine.py b/backend/app/services/shipping_notice/order_task_stage_machine.py index a1c87219..ebbbb93e 100644 --- a/backend/app/services/shipping_notice/order_task_stage_machine.py +++ b/backend/app/services/shipping_notice/order_task_stage_machine.py @@ -292,11 +292,19 @@ def sync_order_task_stage_for_candidate( return None # 正式建单后的 Candidate 仍可能因恢复/对账再次触发资格重算; # 此时建单前资格阶段不再是权威事实,禁止覆盖 OT 当前履约阶段。 - if ( - getattr(candidate, 'consumed_task_id', None) is not None - or getattr(ot, 'shipping_notice_id', None) is not None - ): + if getattr(candidate, 'consumed_task_id', None) is not None: return ot + # 已挂正式通知单:以 Notice→OT(ShippingNotice.order_task_id)反向关联为准, + # OT 本身不保存通知单指针。只要已有任意 Notice 指向该 OT,即说明 OT 已进入 + # 履约阶段,建单前资格阶段不再是权威事实:原样返回,禁止回退到确认前 stage。 + if getattr(ot, 'id', None) is not None: + bound_notice = ( + ShippingNotice.query + .filter(ShippingNotice.order_task_id == int(ot.id)) + .first() + ) + if bound_notice is not None: + return ot stage, status = resolve_pre_confirm_stage( candidate=candidate, evaluation=evaluation, @@ -328,7 +336,7 @@ def sync_order_task_stage_for_notice( Args: notice: 正式发货通知。 - order_task: 可选;缺省按 notice.order_task_id / ShippingOrderTask.shipping_notice_id。 + order_task: 可选;缺省按 notice.order_task_id 反查 OT。 Returns: 更新后的 OT;找不到时 None。 @@ -340,18 +348,13 @@ def sync_order_task_stage_for_notice( ot = order_task if ot is None and getattr(notice, 'order_task_id', None): ot = db.session.get(ShippingOrderTask, int(notice.order_task_id)) - if ot is None and getattr(notice, 'id', None): - ot = ( - ShippingOrderTask.query.filter_by(shipping_notice_id=int(notice.id)) - .order_by(ShippingOrderTask.id.desc()) - .first() - ) if ot is None: return None status, stage = map_notice_to_processing_status_stage(notice) # [STEP] Execution.current_gate_code 是正式履约事实,优先于尚未来得及写入 Notice # 领域字段的默认映射;只接受 active/waiting_external/blocked 执行,避免旧 Execution 回退 OT。 - active_execution_id = getattr(notice, 'active_process_execution_id', None) + # ProcessExecution 属于 OT;正式 Notice 不保存执行指针。 + active_execution_id = getattr(ot, 'active_process_execution_id', None) if active_execution_id is not None: from app.models import ShippingProcessExecution @@ -359,9 +362,16 @@ def sync_order_task_stage_for_notice( execution_status = str(getattr(execution, 'status', None) or '').strip().lower() gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower() gate_stage = _PROCESS_GATE_TO_PROCESSING_STAGE.get(gate_code) - if execution_status in {'active', 'waiting_external', 'blocked'} and gate_stage: + # [FIX] current_gate_code 是正式履约事实。即使 execution.status 仍为 completed + # (历史遗留旧值或 Gate 状态在 `_refresh_execution_pointers` 刷新前被旁路写成 + # blocked),只要 current_gate_code 仍指向一个未通过 Gate,就不能让 OT.stage 滞留 + # completed 而与实际卡住环节矛盾:据此把该 Gate 阶段回写,并落 blocked。 + if gate_stage and execution_status in {'active', 'waiting_external', 'blocked'}: stage = gate_stage status = 'automating' if execution_status in {'active', 'waiting_external'} else 'blocked' + elif gate_stage and execution_status == 'completed': + stage = gate_stage + status = 'blocked' if stage not in SHIPPING_PROCESSING_STAGES: stage = 'inventory_matching' return sync_order_task_processing_state( diff --git a/backend/app/services/shipping_notice/po_number.py b/backend/app/services/shipping_notice/po_number.py index 0568cea7..38627b10 100644 --- a/backend/app/services/shipping_notice/po_number.py +++ b/backend/app/services/shipping_notice/po_number.py @@ -22,6 +22,7 @@ _ATOMIC_PO_NUMBER_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9\-_/]*") def normalize_po_number(value: Any) -> str: """ 标准化采购单号;Wistron 等客户原文常带 ZNB 前缀(如 ZNB16754796 / ZNB-16754796),输出为纯数字段。 + 纯数字 PO 前导零视为格式差异(0060208010 与 60208010 是同一张 PO),统一剥除,避免跨来源误判冲突。 """ text = str(value or "").strip() if not text: @@ -32,8 +33,8 @@ def normalize_po_number(value: Any) -> str: if upper.startswith("ZNB") and len(text) > 3: tail = text[3:].strip().lstrip("-_/ ") if tail.isdigit(): - return tail - return text + return tail.lstrip("0") or "0" + return text.lstrip("0") or "0" def normalize_atomic_po_number(value: Any) -> str: diff --git a/backend/app/services/shipping_notice/task_candidate_reconciliation.py b/backend/app/services/shipping_notice/task_candidate_reconciliation.py index 3496cf91..be308e4c 100644 --- a/backend/app/services/shipping_notice/task_candidate_reconciliation.py +++ b/backend/app/services/shipping_notice/task_candidate_reconciliation.py @@ -89,11 +89,17 @@ def _target_is_safe(task: ShippingNotice) -> bool: 核心逻辑:与历史 open_existing Reservation 回填安全边界保持一致,避免已推进任务被静默改写。 """ - if str(task.pending_human_reason or '').strip().lower() != PH_RSV_REQ: + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + + if str(task_blocking_reason(task) or '').strip().lower() != PH_RSV_REQ: return False - if task.inventory_lines_json or task.line_results_json or task.export_file_path or task.freight_ref_no: - return False - if task.match_status or task.upload_status: + from app.services.shipping_notice.inventory_file_store import ( + current_inventory_matches_for_task, + has_ready_inventory_file_for_task, + ) + + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact, latest_upload_attempt + if has_ready_inventory_file_for_task(task) or current_inventory_matches_for_task(task) or latest_export_artifact(task) is not None or latest_upload_attempt(task) is not None: return False return True @@ -334,7 +340,7 @@ def apply_candidate_reconciliation_plan( ], } step_payload['field_conflicts'] = {'open_count': len(open_rows)} - task.step_payload_json = step_payload + task.step_payload_json = (step_payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in step_payload.items() if key in {'current_step_progress', 'parse_validation'}}) apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) return { 'status': 'conflicted', @@ -385,7 +391,7 @@ def apply_candidate_reconciliation_plan( step_payload.pop('process_field_gate', None) apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) task.error_message = None - task.step_payload_json = step_payload + task.step_payload_json = (step_payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in step_payload.items() if key in {'current_step_progress', 'parse_validation'}}) return { 'status': 'applied', 'reason': 'fields_backfilled', diff --git a/backend/app/services/shipping_notice/task_disposition_service.py b/backend/app/services/shipping_notice/task_disposition_service.py index 985aa41e..7157ad02 100644 --- a/backend/app/services/shipping_notice/task_disposition_service.py +++ b/backend/app/services/shipping_notice/task_disposition_service.py @@ -19,12 +19,17 @@ from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingExportArtifact, ShippingOrderCandidate, + ShippingOrderExtraction, ShippingOrderIntake, + ShippingOrderTask, + ShippingCustomerShadowResolution, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink, ShippingTaskPurgeAudit, + ShippingNoticeLineInventoryMatch, ) +from app.models.shipping_task_line import ShippingTaskFieldConflict TaskDispositionAction = Literal['delete', 'void', 'archive', 'restore'] @@ -43,7 +48,7 @@ class TaskDispositionCapability: reason: str | None = None -def task_is_active(task: ShippingNotice) -> bool: +def task_is_active(task: ShippingNotice | ShippingOrderTask) -> bool: """ 判断任务是否仍可触发履约副作用。 @@ -61,7 +66,7 @@ def task_is_active(task: ShippingNotice) -> bool: ) -def task_execution_block_reason(task: ShippingNotice) -> str | None: +def task_execution_block_reason(task: ShippingNotice | ShippingOrderTask) -> str | None: """ 为异步编排和外部回调提供统一的副作用熔断原因。 @@ -79,7 +84,7 @@ def task_execution_block_reason(task: ShippingNotice) -> str | None: return f'task_lifecycle_{lifecycle or "inactive"}' -def load_task_for_disposition(task_no: str) -> ShippingNotice: +def load_task_for_disposition(task_no: str) -> ShippingNotice | ShippingOrderTask: """ 以行锁加载任务,供同一事务内重新判定并写入处置结果。 @@ -97,27 +102,29 @@ def load_task_for_disposition(task_no: str) -> ShippingNotice: if not normalized_task_no: raise ValidationError('task_no is required', code='SHIPPING.TASK_NO_REQUIRED') task = ( - ShippingNotice.query - .filter(ShippingNotice.task_no == normalized_task_no) - .with_for_update() - .first() + ShippingOrderTask.query.filter(ShippingOrderTask.task_no == normalized_task_no) + .with_for_update().first() ) + if task is None: + task = ShippingOrderTask.query.filter(ShippingOrderTask.task_no == normalized_task_no).with_for_update().first() if task is None: raise NotFoundError('Shipping task not found', code='SHIPPING.TASK_NOT_FOUND') return task -def _has_external_fulfillment(task: ShippingNotice) -> bool: +def _has_external_fulfillment(task: ShippingNotice | ShippingOrderTask) -> bool: """识别已提交、正在提交或已有外部上传参考的任务;这些任务不可在平台单方作废。""" - upload_status = str(task.upload_status or '').strip().lower() + from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt + upload_status = str(getattr(latest_upload_attempt(task), 'status', None) or '').strip().lower() return bool( - task.freight_ref_no - or upload_status in _EXTERNAL_UPLOAD_STATUSES + upload_status in _EXTERNAL_UPLOAD_STATUSES ) -def _has_successor(task: ShippingNotice) -> bool: +def _has_successor(task: ShippingNotice | ShippingOrderTask) -> bool: """修订链存在后继时禁止作废旧任务,避免破坏版本追溯。""" + if not isinstance(task, ShippingNotice): + return False return ( db.session.query(ShippingNotice.id) .filter(ShippingNotice.supersedes_task_id == int(task.id)) @@ -127,7 +134,7 @@ def _has_successor(task: ShippingNotice) -> bool: def task_disposition_capability( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, action: TaskDispositionAction, ) -> TaskDispositionCapability: """ @@ -200,7 +207,7 @@ def _disposition_reason_code(event_type: str, detail: dict[str, Any]) -> str | N def _write_disposition_event( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, *, event_type: str, actor_id: int | None, @@ -216,13 +223,15 @@ def _write_disposition_event( reason_code = _disposition_reason_code(event_type, payload) if reason_code: payload.setdefault('reason_code', reason_code) - db.session.add(ShippingTaskEvent( - task_id=int(task.id), - event_type=event_type, - actor_id=actor_id, - request_id=str(request_id or '').strip()[:64] or None, - detail_json=payload, - )) + from app.services.shipping_notice.tool_common import task_event_task_id + if isinstance(task, ShippingNotice): + db.session.add(ShippingTaskEvent( + task_id=task_event_task_id(task), + event_type=event_type, + actor_id=actor_id, + request_id=str(request_id or '').strip()[:64] or None, + detail_json=payload, + )) from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit record_fulfillment_audit( @@ -237,7 +246,12 @@ def _write_disposition_event( result='success', after={ 'lifecycle_status': getattr(task, 'lifecycle_status', None), - 'upload_status': getattr(task, 'upload_status', None), + 'upload_status': getattr( + __import__('app.services.shipping_notice.upload_attempt_service', fromlist=['latest_upload_attempt']) + .latest_upload_attempt(task), + 'status', + None, + ), }, metadata={ 'dual_write': 'shipping_task_event', @@ -281,15 +295,25 @@ def move_task_to_recycle_bin( raise ConflictError(capability.reason or 'Task delete is blocked', code=capability.code or 'SHIPPING.TASK_DELETE_BLOCKED') # [STEP 1] 已解析或已产生内部引用的任务先作废,再进入回收站;纯 created 误建仅隐藏。 + owner_task = ( + db.session.get(ShippingOrderTask, int(task.order_task_id)) + if isinstance(task, ShippingNotice) and task.order_task_id else task + ) has_internal_business_record = bool( - task.business_no - or task.customer_id - or task.source_candidate_id - or task.match_status - or task.export_file_path - or db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).first() - or db.session.query(ShippingExportArtifact.id).filter_by(task_id=int(task.id)).first() - or db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(task.id)).first() + getattr(task, 'business_no', None) + or ( + db.session.query(ShippingCustomerShadowResolution.id).filter_by( + candidate_id=getattr(owner_task, 'candidate_id', None), status='confirmed', + ).filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None)).first() + ) + or getattr(owner_task, 'candidate_id', None) + or bool(db.session.query(ShippingNoticeLineInventoryMatch.id).filter_by(task_id=int(owner_task.id), is_current=True).first()) + or db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(owner_task.id)).first() + or db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(owner_task.id)).first() + or ( + isinstance(task, ShippingNotice) + and db.session.query(ShippingExportArtifact.id).filter_by(task_id=int(task.id)).first() + ) ) now = datetime.utcnow() task.deleted_at = now @@ -318,7 +342,7 @@ def move_task_to_recycle_bin( def void_task( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, *, actor_id: int, reason: str, @@ -346,7 +370,7 @@ def void_task( def archive_task( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, *, actor_id: int, request_id: str | None = None, @@ -368,7 +392,7 @@ def archive_task( def restore_task_from_recycle_bin( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, *, actor_id: int, request_id: str | None = None, @@ -390,7 +414,7 @@ def restore_task_from_recycle_bin( def purge_task_permanently( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, *, actor_id: int, reason: str, @@ -414,18 +438,50 @@ def purge_task_permanently( if task.deleted_at is None or str(task.lifecycle_status or 'active') != 'active': raise ConflictError('Only deleted pure draft task can be purged', code='SHIPPING.TASK_PURGE_BLOCKED') - from app.models import ShippingOrderExtraction, ShippingTemporaryInventorySession - from app.models.shipping_task_line import ShippingTaskFieldConflict + # OT 尚未生成 Notice 时只检查其自身的解析/库存/审计引用,禁止访问 Notice 专属字段。 + if isinstance(task, ShippingOrderTask): + blocking_counts = { + 'current_order_extraction': int(bool(task.current_order_extraction_id)), + 'inventory_snapshot': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(), + 'candidate_consumed': db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(task.id)).count(), + 'intake_consumed': db.session.query(ShippingOrderIntake.id).filter_by(consumed_task_id=int(task.id)).count(), + 'order_extraction': db.session.query(ShippingOrderExtraction.id).filter_by(task_id=int(task.id)).count(), + 'inventory_link': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(), + 'field_conflict': db.session.query(ShippingTaskFieldConflict.id).filter_by(task_id=int(task.id)).count(), + } + blocking = {key: value for key, value in blocking_counts.items() if value} + if blocking: + raise ConflictError( + 'Order task has business or audit references and cannot be purged', + code='SHIPPING.TASK_PURGE_BLOCKED', + details={'blocking': blocking}, + ) + db.session.delete(task) + db.session.add(ShippingTaskPurgeAudit( + task_no_snapshot=task.task_no, + actor_id=actor_id, + reason=normalized_reason, + snapshot_json={'task_no': task.task_no, 'lifecycle_status': task.lifecycle_status}, + )) + return + + from app.models import ShippingTemporaryInventorySession # [STEP 1] 不依赖前端预检,事务内重新统计全部会破坏可追溯性的引用。 + owner = task if hasattr(task, 'current_order_extraction_id') else None + customer_confirmed = False + if owner is not None and owner.current_order_extraction_id: + customer_confirmed = db.session.query(ShippingCustomerShadowResolution.id).filter_by( + candidate_id=owner.candidate_id, status='confirmed', + ).filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None)).first() is not None blocking_counts = { 'business_number': int(bool(task.business_no)), - 'customer': int(bool(task.customer_id)), + 'customer': int(customer_confirmed), 'source_asset': int(bool(task.source_asset_id)), 'source_intake': int(bool(task.source_intake_id)), 'source_candidate': int(bool(task.source_candidate_id)), 'current_order_extraction': int(bool(task.current_order_extraction_id)), - 'inventory_snapshot': int(bool(task.inventory_snapshot_id)), + 'inventory_snapshot': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(), 'successor': int(_has_successor(task)), 'duplicate_link': int(bool(task.duplicate_source_task_id)), 'duplicate_source_for_other_task': db.session.query(ShippingNotice.id).filter( diff --git a/backend/app/services/shipping_notice/task_field_conflict_service.py b/backend/app/services/shipping_notice/task_field_conflict_service.py index 1f263d61..6c801033 100644 --- a/backend/app/services/shipping_notice/task_field_conflict_service.py +++ b/backend/app/services/shipping_notice/task_field_conflict_service.py @@ -235,34 +235,37 @@ def resolve_field_conflict( remaining = list_open_field_conflicts(task) issues = task_reservation_gate_issues(task) step_payload = dict(task.step_payload_json or {}) - step_payload['field_conflicts'] = { - 'open_count': len(remaining), - 'last_resolved_id': conflict.id, - } - if idempotency_key: - step_payload['last_conflict_resolve_idempotency_key'] = str(idempotency_key).strip() - if remaining: - step_payload['process_field_gate'] = { - 'status': 'needs_enrichment', - 'missing_fields': sorted({row.field_name for row in remaining}), - 'issues': [ - { - 'severity': 'blocking', - 'field': row.field_name, - 'line_index': row.position, - 'reason': 'field_conflict', - 'conflict_id': row.id, - } - for row in remaining - ], + if task.__class__.__name__ != 'ShippingOrderTask': + step_payload['field_conflicts'] = { + 'open_count': len(remaining), + 'last_resolved_id': conflict.id, } + if idempotency_key: + step_payload['last_conflict_resolve_idempotency_key'] = str(idempotency_key).strip() + if remaining: + if task.__class__.__name__ != 'ShippingOrderTask': + step_payload['process_field_gate'] = { + 'status': 'needs_enrichment', + 'missing_fields': sorted({row.field_name for row in remaining}), + 'issues': [ + { + 'severity': 'blocking', + 'field': row.field_name, + 'line_index': row.position, + 'reason': 'field_conflict', + 'conflict_id': row.id, + } + for row in remaining + ], + } apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) elif issues: - step_payload['process_field_gate'] = { - 'status': 'needs_enrichment', - 'missing_fields': ['reservation_id'], - 'issues': issues, - } + if task.__class__.__name__ != 'ShippingOrderTask': + step_payload['process_field_gate'] = { + 'status': 'needs_enrichment', + 'missing_fields': ['reservation_id'], + 'issues': issues, + } apply_task_transition(task, TaskTransition.RSV_REQUIRED) else: step_payload.pop('process_field_gate', None) @@ -273,7 +276,9 @@ def resolve_field_conflict( 'issues': issues, 'resolution_source': 'field_conflict_resolve', } - task.step_payload_json = step_payload + task.step_payload_json = step_payload if task.__class__.__name__ != 'ShippingOrderTask' else { + key: value for key, value in step_payload.items() if key in {'current_step_progress', 'parse_validation'} + } log_task_event( task, 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 ef178146..f2c25545 100644 --- a/backend/app/services/shipping_notice/task_order_field_editor.py +++ b/backend/app/services/shipping_notice/task_order_field_editor.py @@ -152,9 +152,10 @@ def current_line_field_configs(task: ShippingNotice) -> dict[str, dict[str, Any] def _current_extraction(task: ShippingNotice) -> ShippingOrderExtraction: """读取任务当前已接受 Extraction;人工编辑绝不回退旧任务行投影。""" + extraction_id = getattr(task, 'current_order_extraction_id', None) extraction = ( - db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) - if task.current_order_extraction_id is not None else None + db.session.get(ShippingOrderExtraction, extraction_id) + if extraction_id is not None else None ) if extraction is None or extraction.status != 'accepted': raise ConflictError('Task has no accepted order extraction', code='SHIPPING.ORDER_FIELD_EDIT_BLOCKED') @@ -338,7 +339,7 @@ def replace_current_line_fields(*, task: ShippingNotice, lines: list[dict[str, A value_json=previous_value.value_json, )) for position, values in enumerate(lines): - line = ShippingOrderLine(extraction_id=replacement.id, position=position) + line = ShippingOrderLine(extraction_id=replacement.id, position=position, line_no=position + 1) db.session.add(line) db.session.flush() for config in configs: diff --git a/backend/app/services/shipping_notice/task_supersession_service.py b/backend/app/services/shipping_notice/task_supersession_service.py index 59a90aa4..3625f139 100644 --- a/backend/app/services/shipping_notice/task_supersession_service.py +++ b/backend/app/services/shipping_notice/task_supersession_service.py @@ -6,8 +6,9 @@ from datetime import datetime from app import db from app.core.errors import ConflictError, ValidationError -from app.models import ShippingFreightCancellation, ShippingNotice, ShippingTaskEvent +from app.models import ShippingFreightCancellation, ShippingNotice, ShippingOrderTask, ShippingTaskEvent from app.services.shipping_notice.task_disposition_service import task_is_active +from app.services.shipping_notice.tool_common import task_event_task_id def establish_task_supersession(*, old_task: ShippingNotice, new_task: ShippingNotice, actor_id: int, reason: str) -> None: @@ -18,24 +19,48 @@ def establish_task_supersession(*, old_task: ShippingNotice, new_task: ShippingN raise ConflictError('Revision parent mismatch', code='SHIPPING.TASK_SUPERSESSION_INVALID') if not task_is_active(old): return - external = bool(old.freight_ref_no or str(old.upload_status or '').lower() in {'uploaded', 'succeeded', 'success'}) + from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success + from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt + latest_attempt = latest_upload_attempt(old) + external = bool( + has_verified_upload_success(old) + or str(getattr(latest_attempt, 'freight_ref_no', '') or '').strip() + ) if external: existing = ShippingFreightCancellation.query.filter_by(old_task_id=old.id, new_task_id=new.id).one_or_none() if existing is None: db.session.add(ShippingFreightCancellation(old_task_id=old.id, new_task_id=new.id, requested_by_id=actor_id, reason=reason)) - new.lifecycle_status = 'blocked' - new.pending_human_reason = 'freight_cancellation_required' - db.session.add(ShippingTaskEvent(task_id=new.id, event_type='supersession_cancellation_required', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason})) + new_owner = ( + db.session.get(ShippingOrderTask, int(new.order_task_id)) + if new.order_task_id is not None else None + ) + if new_owner is not None: + # lifecycle_status 仅表达 active/voided/archived;流程阻断属于 status。 + new_owner.status = 'blocked' + new_owner.pending_human_reason = 'freight_cancellation_required' + db.session.add(ShippingTaskEvent(task_id=task_event_task_id(new), event_type='supersession_cancellation_required', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason})) return old.lifecycle_status = 'voided' old.voided_at = datetime.utcnow() old.voided_by_id = actor_id old.void_reason = reason - db.session.add(ShippingTaskEvent(task_id=old.id, event_type='task_superseded', actor_id=actor_id, detail_json={'new_task_no': new.task_no, 'reason': reason})) - db.session.add(ShippingTaskEvent(task_id=new.id, event_type='task_supersession_established', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason, 'at': datetime.utcnow().isoformat()})) + db.session.add(ShippingTaskEvent(task_id=task_event_task_id(old), event_type='task_superseded', actor_id=actor_id, detail_json={'new_task_no': new.task_no, 'reason': reason})) + db.session.add(ShippingTaskEvent(task_id=task_event_task_id(new), event_type='task_supersession_established', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason, 'at': datetime.utcnow().isoformat()})) def assert_task_not_supersession_blocked(task: ShippingNotice) -> None: """库存、导出和上传入口调用,阻止撤销未完成的新版本继续履约。""" - if str(task.lifecycle_status or '').lower() == 'blocked' and task.pending_human_reason == 'freight_cancellation_required': + if isinstance(task, ShippingOrderTask): + lifecycle = str(getattr(task, 'lifecycle_status', '') or '').lower() + reason = str(getattr(task, 'pending_human_reason', '') or '').lower() + if str(getattr(task, 'status', '') or '').lower() == 'blocked' and reason == 'freight_cancellation_required': + raise ConflictError('Freight cancellation is required before this revision can continue', code='SHIPPING.FREIGHT_CANCELLATION_REQUIRED') + return + owner = ( + db.session.get(ShippingOrderTask, int(task.order_task_id)) + if task.order_task_id is not None else None + ) + lifecycle = str(getattr(owner, 'status', None) or '').lower() + reason = str(getattr(owner, 'pending_human_reason', None) or '').lower() + if lifecycle == 'blocked' and reason == 'freight_cancellation_required': raise ConflictError('Freight cancellation is required before this revision can continue', code='SHIPPING.FREIGHT_CANCELLATION_REQUIRED') diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index fb7e0d86..ee03cbaf 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -2,9 +2,9 @@ services/shipping_notice/task_workflow.py 用途:发货通知任务/批次生命周期、解析与单头/订单行编辑的主编排入口。 -依赖:query_service、tool_common、decision_workflow、progress_workflow、state_machine、 +依赖:query_service、tool_common、progress_workflow、state_machine、 fulfillment_audit、schema_edit_policy、动态订单字段编辑器、candidate_qualification_service。 -逻辑:tools.py 门面委托本模块;创建 Task 前强制客户已确认(禁止先建单再 customer_review); +逻辑:tools.py 门面委托本模块;创建 OT 不强制客户已确认(先建单,客户确认交由订单复核/客户门禁处理); 正式字段编辑经 Schema 策略门禁后落库,并按 change_effect 失效下游; 成功/拒绝编辑与库存/Excel 失效同事务写入 ShippingAuditEvent; retry_task 写入操作人与前后快照审计。 @@ -20,9 +20,8 @@ from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import ConflictError, ValidationError -from app.models import ShippingNotice +from app.models import ShippingNotice, ShippingOrderTask, ShippingOrderIntake from app.services.shipping_notice.constants import CP_TASK_EXISTS -from app.services.shipping_notice.decision_workflow import submit_decision from app.services.shipping_notice.task_order_field_editor import ( current_header_field_values, retire_current_order_extraction, @@ -52,8 +51,7 @@ from app.services.shipping_notice.batch_create_idempotency import ( assert_no_exact_duplicate_notices, ) from app.services.shipping_notice.candidate_qualification_service import ( - assert_customer_confirmed_before_task_create, - resolve_confirmed_bill_to_customer_id, + resolve_confirmed_customer_id, ) from app.services.shipping_notice.tool_common import ( generate_task_no, @@ -64,6 +62,13 @@ from app.services.shipping_notice.tool_common import ( ) from app.models import ShippingOrderCandidate, ShippingOrderReviewEvent + +def _has_ready_inventory_file(task: ShippingNotice | ShippingOrderTask) -> bool: + """读取活动 Link 指向的 ready 文件,作为重试审计中的库存事实。""" + from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + + return has_ready_inventory_file_for_task(task) + EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to", "po_number", "required_date"}) EDITABLE_NOTICE_LINE_FIELDS = frozenset({ "part_number", @@ -76,6 +81,12 @@ EDITABLE_NOTICE_LINE_FIELDS = frozenset({ }) +def _task_intake(task: ShippingNotice | ShippingOrderTask) -> ShippingOrderIntake | None: + """返回 OT 关联的 Intake,原始正文与来源元数据统一由 Intake 承载。""" + intake_id = getattr(task, 'intake_id', None) + return db.session.get(ShippingOrderIntake, int(intake_id)) if intake_id else None + + def start_task_orchestrator(task_no: str | None) -> bool: """延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。""" from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start @@ -122,9 +133,9 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]: ) if conv_id: existing = ( - ShippingNotice.query.filter_by(conversation_id=conv_id) - .filter(ShippingNotice.lifecycle_status == 'active') - .order_by(ShippingNotice.id.desc()) + ShippingOrderTask.query.filter_by(conversation_id=conv_id) + .filter(ShippingOrderTask.status.notin_({'completed', 'failed', 'cancelled'})) + .order_by(ShippingOrderTask.id.desc()) .first() ) if existing: @@ -133,37 +144,35 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]: task_id=existing.task_no, message=( f"当前会话已有进行中的发货任务 {existing.task_no},请勿重复 create_task。" - "用户确认/驳回时请 submit_decision,并带上任务编号或 conversation_id。" ), data=qs_serialize_task(existing, TaskProjection.TOOL_INTERNAL), checkpoint=CP_TASK_EXISTS, ) - # [STEP] 单票建单同样要求客户已确认,禁止创建后进入 customer_review。 + # [STEP] 接收解析阶段只创建 OT;客户确认由订单复核/客户门禁处理,不能阻止 OT 落库。 customer_id = _parse_optional_customer_id(payload.get("customer_id")) - assert_customer_confirmed_before_task_create( - customer_id=customer_id, - ) - task = ShippingNotice( + user_id = payload.get("user_id") + if user_id is None: + raise ValidationError('user_id is required', code='SHIPPING.USER_REQUIRED') + task = ShippingOrderTask( task_no=generate_task_no(), - customer_id=customer_id, - user_id=payload.get("user_id"), + user_id=int(user_id), conversation_id=str(payload.get("conversation_id") or "").strip() or None, - source_type=str(payload.get("source_type") or "manual"), - batch_index=1, - batch_total=1, - raw_content=str(payload.get("raw_content") or "").strip() or None, - customer_resolution_status='pending', + # OT 仅接受 intake 层定义的来源类型;未知/手工入口保持 NULL,避免违反模型约束。 + source_type=(str(payload.get("source_type") or "").strip() or None), + status='processing', + stage='document_parsing', ) db.session.add(task) log_task_event(task, "task_created", {"source_type": task.source_type}) db.session.flush() - _bind_confirmed_customer_after_task_create( - task, - customer_id=customer_id, - candidate=None, - actor_id=payload.get("user_id"), - ) + if customer_id is not None: + _bind_confirmed_customer_after_task_create( + task, + customer_id=customer_id, + candidate=None, + actor_id=payload.get("user_id"), + ) db.session.commit() return tool_response( status="ok", @@ -190,7 +199,7 @@ def _parse_optional_customer_id(raw: Any) -> int | None: def _bind_confirmed_customer_after_task_create( - task: ShippingNotice, + task: ShippingOrderTask, *, customer_id: int | None, candidate: ShippingOrderCandidate | None, @@ -199,9 +208,9 @@ def _bind_confirmed_customer_after_task_create( """ 创建 Task 后立即绑定已确认客户,避免以 pending 进入 customer_review。 - 核心逻辑:用显式 customer_id 或候选 Bill-to 直接确认当前 Notice。 + 核心逻辑:用显式 customer_id 或已确认识别结果直接确认当前 OT。 """ - bind_id = customer_id or resolve_confirmed_bill_to_customer_id(candidate=candidate) + bind_id = customer_id or resolve_confirmed_customer_id(candidate=candidate) if bind_id is None: raise ConflictError( 'Customer must be confirmed before creating a shipping task', @@ -229,69 +238,43 @@ def _notice_header_snapshot(task: ShippingNotice) -> dict[str, Any]: def _reset_notice_edit_downstream(task: ShippingNotice) -> None: """清空匹配/导出/上传等派生结果,供 require_revision / 库存重算类 change_effect 使用。""" - task.match_status = None - task.shortage_json = None - task.line_results_json = None - task.export_file_path = None - task.export_file_name = None - task.freight_ref_no = None - task.upload_status = None - task.upload_mode = None - task.upload_attempt = 0 - task.upload_started_at = None - task.upload_finished_at = None - task.upload_error_code = None - task.upload_error_message = None - task.upload_receipt_json = None - task.idempotency_key = None - step_payload = dict(task.step_payload_json or {}) + order_task = _resolve_order_task_for_notice(task) + if order_task is None: + return + step_payload = dict(order_task.step_payload_json or {}) step_payload.pop('export_meta', None) - task.step_payload_json = step_payload + order_task.step_payload_json = step_payload def _reset_notice_export_downstream(task: ShippingNotice) -> None: """仅使 Excel 导出派生结果失效,保留库存匹配真相。""" - task.export_file_path = None - task.export_file_name = None - task.freight_ref_no = None - task.upload_status = None - task.upload_mode = None - task.upload_attempt = 0 - task.upload_started_at = None - task.upload_finished_at = None - task.upload_error_code = None - task.upload_error_message = None - task.upload_receipt_json = None - task.idempotency_key = None - step_payload = dict(task.step_payload_json or {}) + order_task = _resolve_order_task_for_notice(task) + if order_task is None: + return + step_payload = dict(order_task.step_payload_json or {}) step_payload.pop('export_meta', None) - task.step_payload_json = step_payload + order_task.step_payload_json = step_payload -def _resolve_order_task_for_notice(task: ShippingNotice): - """按 Notice 反查 OT;供 change_effect 同步统一进度 stage。""" - from app.models import ShippingOrderTask - +def _resolve_order_task_for_notice(task: ShippingNotice | ShippingOrderTask) -> ShippingOrderTask | None: + """按 Notice 反查 OT;若入参本身即 OT 则直接返回,供 change_effect 同步统一进度 stage。""" + if isinstance(task, ShippingOrderTask): + return task order_task_id = getattr(task, 'order_task_id', None) if order_task_id is not None: return db.session.get(ShippingOrderTask, int(order_task_id)) - return ( - db.session.query(ShippingOrderTask) - .filter(ShippingOrderTask.shipping_notice_id == int(task.id)) - .order_by(ShippingOrderTask.id.asc()) - .first() - ) + return None def _set_notice_invalidated_from_stage(task: ShippingNotice, stage: str) -> None: """ - 将改单失效起点写入 Notice.step_payload_json,供投影 stage_nodes 消费。 + 将改单失效起点写入 OT.step_payload_json,供投影 stage_nodes 消费。 [BE-08] 写入时追加 invalidated_from_stage_history,降低无历史可追溯风险; 完整列级约束与乐观锁仍待显式字段迁移。 Args: - task: 被编辑的正式任务。 + task: 被编辑的正式任务(ShippingNotice)。 stage: 失效起点统一 stage。 """ from datetime import datetime @@ -301,33 +284,42 @@ def _set_notice_invalidated_from_stage(task: ShippingNotice, stage: str) -> None code = str(stage or '').strip().lower() if code not in SHIPPING_PROCESSING_STAGES: return - payload = dict(task.step_payload_json or {}) if isinstance(task.step_payload_json, dict) else {} + order_task = _resolve_order_task_for_notice(task) + if order_task is None: + return + payload = ( + dict(order_task.step_payload_json or {}) + if isinstance(order_task.step_payload_json, dict) else {} + ) history = payload.get('invalidated_from_stage_history') if not isinstance(history, list): history = [] history.append({ 'stage': code, 'at': datetime.utcnow().isoformat(timespec='seconds') + 'Z', - 'progress_version': int(getattr(task, 'progress_version', None) or 0), + 'progress_version': int(getattr(order_task, 'progress_version', None) or 0), }) payload['invalidated_from_stage'] = code payload['invalidated_from_stage_history'] = history[-20:] - task.step_payload_json = payload + order_task.step_payload_json = payload def _clear_notice_invalidated_from_stage(task: ShippingNotice) -> None: """ - 清除 Notice 上的改单失效起点(下游已成功重跑后)。 + 清除 OT 上的改单失效起点(下游已成功重跑后)。 [BE-08] 清除仅移除当前起点;历史列表保留供审计追溯。 """ - if not isinstance(task.step_payload_json, dict): + order_task = _resolve_order_task_for_notice(task) + if order_task is None: return - if 'invalidated_from_stage' not in task.step_payload_json: + if not isinstance(order_task.step_payload_json, dict): return - payload = dict(task.step_payload_json) + if 'invalidated_from_stage' not in order_task.step_payload_json: + return + payload = dict(order_task.step_payload_json) payload.pop('invalidated_from_stage', None) - task.step_payload_json = payload + order_task.step_payload_json = payload def read_notice_invalidated_from_stage(task: ShippingNotice | None) -> str | None: @@ -344,7 +336,10 @@ def read_notice_invalidated_from_stage(task: ShippingNotice | None) -> str | Non if task is None: return None - payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} + order_task = _resolve_order_task_for_notice(task) + if order_task is None: + return None + payload = order_task.step_payload_json if isinstance(order_task.step_payload_json, dict) else {} code = str(payload.get('invalidated_from_stage') or '').strip().lower() return code if code in SHIPPING_PROCESSING_STAGES else None @@ -374,7 +369,6 @@ def _apply_notice_edit_change_effects( from app.services.shipping_notice.schema_edit_policy import collect_change_effects_for_fields from app.services.shipping_notice.order_task_service import sync_order_task_processing_state from app.services.shipping_notice.inventory_source_gate import ( - STABLE_INVENTORY_SOURCE_STATUSES, adjudicate_and_apply_inventory_source, clear_inventory_source_confirmation, ) @@ -399,18 +393,12 @@ def _apply_notice_edit_change_effects( # [STEP] 库存源重算优先于匹配重算:不得跳过 inventory_source_resolving。 if 'rerun_inventory_source_resolution' in effects: clear_inventory_source_confirmation(task) - task.inventory_source_status = 'unresolved' - task.inventory_source_code = None - task.inventory_connector_type = None - task.inventory_warehouse_id = None - task.match_status = None - task.shortage_json = None - task.line_results_json = None - task.inventory_lines_json = None _reset_notice_export_downstream(task) _set_notice_invalidated_from_stage(task, 'inventory_source_resolving') adjudication = adjudicate_and_apply_inventory_source(task) - stable = str(adjudication.status or '').strip() in STABLE_INVENTORY_SOURCE_STATUSES + from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable + + stable = is_inventory_source_stable(task) if order_task is not None: if stable: sync_order_task_processing_state( @@ -429,10 +417,6 @@ def _apply_notice_edit_change_effects( return applied if 'rerun_inventory_matching' in effects: - task.match_status = None - task.shortage_json = None - task.line_results_json = None - task.inventory_lines_json = None _reset_notice_export_downstream(task) _set_notice_invalidated_from_stage(task, 'inventory_matching') if order_task is not None: @@ -553,9 +537,11 @@ def _record_formal_task_edit_audits( 'export_file_name': before_export_file_name, 'order_data_version': before_order_data_version, } + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + after_artifact = latest_export_artifact(task) after_summary = { - 'match_status': task.match_status, - 'export_file_name': task.export_file_name, + 'match_status': None, + 'export_file_name': getattr(after_artifact, 'file_name', None), 'order_data_version': task.order_data_version, } field_changes = _formal_edit_field_diff_summary( @@ -605,7 +591,7 @@ def _record_formal_task_edit_audits( reason_code='inventory_match_invalidated', result='success', before={'match_status': before_match_status}, - after={'match_status': task.match_status}, + after={'match_status': None}, metadata={'applied_effects': sorted(applied_effects), 'evidence_ref': evidence_ref}, source='workspace_api', ) @@ -627,7 +613,7 @@ def _record_formal_task_edit_audits( reason_code='excel_export_invalidated', result='success', before={'export_file_name': before_export_file_name}, - after={'export_file_name': task.export_file_name}, + after={'export_file_name': getattr(after_artifact, 'file_name', None)}, metadata={'applied_effects': sorted(applied_effects), 'evidence_ref': evidence_ref}, source='workspace_api', ) @@ -707,14 +693,14 @@ def replace_task_notice( """ cleaned_text = str(raw_text or "").strip() cleaned_warnings = [str(item).strip() for item in (warnings or []) if str(item).strip()] + intake = _task_intake(task) if not cleaned_text: apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED) task.error_message = "未能从重新上传的发货通知中抽取到可解析文本" - task.raw_content = "" - if source_file_name: - task.source_file_name = source_file_name - if source_file_type: - task.source_file_type = source_file_type + if intake is not None: + intake.extracted_text = "" + intake.error_message = task.error_message + intake.parse_warnings_json = cleaned_warnings set_task_step_progress( task, step_key="step2_parse_confirm", @@ -736,13 +722,10 @@ def replace_task_notice( data={**serialize_task_for_tool(task), "warnings": cleaned_warnings}, ) - task.raw_content = cleaned_text - if source_file_name: - task.source_file_name = source_file_name - if source_file_type: - task.source_file_type = source_file_type + if intake is not None: + intake.extracted_text = cleaned_text + intake.parse_warnings_json = cleaned_warnings retire_current_order_extraction(task) - task.parse_confidence = None task.review_status = None task.pending_human_reason = None task.error_message = None @@ -821,6 +804,30 @@ def _assert_order_data_version(task: ShippingNotice, payload: dict[str, Any]) -> return None +def _edit_window_busy_error(task: ShippingNotice) -> dict[str, Any] | None: + """ + 二期编辑窗守卫(D10/§3.3):订单任一通知存在活动 Gate Attempt(库存 RPA / 匹配 queued|running) + 时拒绝保存,返回 SYSTEM_BUSY 的 failed Tool 响应;否则 None。 + + Args: + task: 被编辑的 ShippingNotice。 + + Returns: + 活动 Attempt 时的 tool_response(status='failed', error_code=SHIPPING.EDIT_WINDOW_SYSTEM_BUSY); + 通过则 None。 + """ + from app.services.shipping_notice.order_edit_window_service import order_has_active_attempt + + if order_has_active_attempt(task): + return tool_response( + status='failed', + task=task, + message='系统处理中,请稍后再修改。', + data={'error_code': 'SHIPPING.EDIT_WINDOW_SYSTEM_BUSY'}, + ) + return None + + def _notice_edit_idempotency_replay( task: ShippingNotice, payload: dict[str, Any], @@ -829,7 +836,10 @@ def _notice_edit_idempotency_replay( key = str(payload.get('idempotency_key') or '').strip() if not key: return None - step_payload = dict(task.step_payload_json or {}) + order_task = _resolve_order_task_for_notice(task) + if order_task is None: + return None + step_payload = dict(order_task.step_payload_json or {}) last = step_payload.get('last_notice_edit_idempotency') if not isinstance(last, dict): return None @@ -853,9 +863,35 @@ def _remember_notice_edit_idempotency( text = str(key or '').strip() if not text: return - step_payload = dict(task.step_payload_json or {}) + order_task = _resolve_order_task_for_notice(task) + if order_task is None: + return + step_payload = dict(order_task.step_payload_json or {}) step_payload['last_notice_edit_idempotency'] = {'key': text, 'message': message} - task.step_payload_json = step_payload + order_task.step_payload_json = step_payload + + +def _order_task_match_status_for_audit(order_task: ShippingOrderTask | None) -> str | None: + """ + 读取 OT 当前行级库存匹配状态(matched / shortage / None), + 供正式编辑审计 before 快照记录失效前的真实 match_status。 + + 核心逻辑:以行级 Match 事实为准(禁止读取 OT 缓存字段), + all 行匹配且无短缺为 matched,否则有行时视为 shortage;无行返回 None。 + """ + if order_task is None: + return None + from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + + facts = list(load_current_match_facts_by_task(order_task.id).values()) + if not facts: + return None + matched = all( + str(row.get('match_result') or '').strip().lower() == 'matched' + and str(row.get('shortage_qty') or '').strip() in {'', '0', '0.0', '0.00'} + for row in facts + ) + return 'matched' if matched else 'shortage' def _commit_notice_edit( @@ -887,7 +923,10 @@ def _commit_notice_edit( if not reviewed_by_id or not evidence_ref or not reason: raise ConflictError('Review evidence is required', code='SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED') # [STEP 1] 人工编辑后的业务值拥有最终优先级,但仍必须通过同一流程字段契约。 - step_payload = dict(task.step_payload_json or {}) + order_task = _resolve_order_task_for_notice(task) + if order_task is None: + raise ConflictError('Formal task edit requires a linked order task', code='SHIPPING.ORDER_TASK_REQUIRED') + step_payload = dict(order_task.step_payload_json or {}) validation_issues = task_reservation_gate_issues(task) step_payload["parse_validation"] = { "status": "needs_review" if validation_issues else "ready", @@ -903,11 +942,12 @@ def _commit_notice_edit( } else: step_payload.pop('process_field_gate', None) - task.step_payload_json = step_payload + order_task.step_payload_json = step_payload # [STEP 2] 先按 change_effect 失效下游;仅缺字段或 require_revision 才回旧复核态。 - before_match_status = task.match_status - before_export_file_name = task.export_file_name + before_match_status = _order_task_match_status_for_audit(order_task) + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact + before_export_file_name = getattr(latest_export_artifact(task), 'file_name', None) before_order_data_version = task.order_data_version applied_effects = _apply_notice_edit_change_effects(task, edited_field_scopes or []) if validation_issues: @@ -1046,6 +1086,10 @@ def update_notice_fields(payload: dict[str, Any]) -> dict[str, Any]: version_error = _assert_order_data_version(task, payload) if version_error is not None: return version_error + # 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。 + busy_error = _edit_window_busy_error(task) + if busy_error is not None: + return busy_error fields = payload.get("fields") if not isinstance(fields, dict) or not fields: @@ -1137,6 +1181,10 @@ def update_notice_line(payload: dict[str, Any]) -> dict[str, Any]: version_error = _assert_order_data_version(task, payload) if version_error is not None: return version_error + # 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。 + busy_error = _edit_window_busy_error(task) + if busy_error is not None: + return busy_error try: line_index = int(payload.get("line_index")) @@ -1244,6 +1292,10 @@ def add_notice_line(payload: dict[str, Any]) -> dict[str, Any]: version_error = _assert_order_data_version(task, payload) if version_error is not None: return version_error + # 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。 + busy_error = _edit_window_busy_error(task) + if busy_error is not None: + return busy_error line = payload.get("line") if not isinstance(line, dict) or not line: @@ -1288,6 +1340,10 @@ def remove_notice_line(payload: dict[str, Any]) -> dict[str, Any]: version_error = _assert_order_data_version(task, payload) if version_error is not None: return version_error + # 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。 + busy_error = _edit_window_busy_error(task) + if busy_error is not None: + return busy_error try: line_index = int(payload.get("line_index")) @@ -1347,10 +1403,6 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]: task.error_message = None # [BE-放行-重试] 重试应重新评估当前库存事实:清空旧匹配结果,强制 orchest 在下一轮 # 重新匹配,而不是带着旧的 unfulfillable/shortage 直接跳到步骤(避免旧缺货残留)。 - task.match_status = None - task.line_results_json = None - task.shortage_json = None - try: order_lines = current_line_field_values(task) except ConflictError: @@ -1384,7 +1436,10 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]: reason=comment or None, before=before, after=after, - metadata={'has_order_lines': bool(order_lines), 'has_inventory_lines': bool(task.inventory_lines_json)}, + metadata={ + 'has_order_lines': bool(order_lines), + 'has_inventory_lines': _has_ready_inventory_file(task), + }, source=event_source, ) db.session.commit() diff --git a/backend/app/services/shipping_notice/tool_common.py b/backend/app/services/shipping_notice/tool_common.py index ea584f61..fd3f4002 100644 --- a/backend/app/services/shipping_notice/tool_common.py +++ b/backend/app/services/shipping_notice/tool_common.py @@ -18,7 +18,7 @@ import uuid from flask import current_app from app import db -from app.models import ShippingNotice, ShippingTaskEvent +from app.models import ShippingNotice, ShippingOrderTask, ShippingTaskEvent from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK @@ -221,8 +221,11 @@ def set_task_step_progress( detail: str | None = None, extra: dict[str, Any] | None = None, ) -> None: - """写入任务当前步骤与步骤内细粒度进度,统一落到 current_step + step_payload_json。""" - payload = dict(task.step_payload_json or {}) + """写入任务当前步骤与步骤内细粒度进度,统一落到 OT 的流程字段。""" + owner = task + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + payload = dict(getattr(owner, 'step_payload_json', None) or {}) progress: dict[str, Any] = { "step_key": step_key, "step_title": step_title, @@ -240,15 +243,23 @@ def set_task_step_progress( if extra: progress["extra"] = extra payload["current_step_progress"] = progress - task.current_step = step_key - task.step_payload_json = payload + if hasattr(owner, 'current_step'): + owner.current_step = step_key + if hasattr(owner, 'stage'): + owner.stage = step_key + if hasattr(owner, 'step_payload_json'): + owner.step_payload_json = payload def clear_task_step_progress(task: ShippingNotice) -> None: """清空任务步骤内进度,保留其他 step_payload_json 字段。""" - payload = dict(task.step_payload_json or {}) + owner = task + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + payload = dict(getattr(owner, 'step_payload_json', None) or {}) payload.pop("current_step_progress", None) - task.step_payload_json = payload or None + if hasattr(owner, 'step_payload_json'): + owner.step_payload_json = payload or None @@ -307,7 +318,7 @@ def build_task_action_event_detail( def log_task_event( - task: ShippingNotice, + task: ShippingNotice | ShippingOrderTask, event_type: str, detail: dict[str, Any] | None = None, *, @@ -333,10 +344,14 @@ def log_task_event( before: 操作前业务快照。 after: 操作后业务快照。 """ - if task.id is None: + event_task_id = task_event_task_id(task) + if event_task_id is None: db.session.flush() + event_task_id = task_event_task_id(task) + if event_task_id is None: + raise ValueError('shipping task event requires an order task id') db.session.add(ShippingTaskEvent( - task_id=task.id, + task_id=event_task_id, event_type=event_type, detail_json=detail or {}, actor_id=actor_id, @@ -436,6 +451,14 @@ def log_task_event( ) +def task_event_task_id(task: ShippingNotice | ShippingOrderTask) -> int | None: + """将 Notice/OT 输入统一解析为 ShippingTaskEvent 使用的 OT 主键。""" + if isinstance(task, ShippingOrderTask): + return int(task.id) if task.id is not None else None + order_task_id = getattr(task, 'order_task_id', None) + return int(order_task_id) if order_task_id is not None else None + + def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) -> str | None: """ 将任务事件类型映射为可解释性稳定 reason_code,供审计中心筛选。 @@ -505,7 +528,7 @@ def task_lifecycle_audit_snapshot(task: ShippingNotice) -> dict[str, Any]: snapshot = { 'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None), 'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None), - 'reason_code': getattr(task, 'pending_human_reason', None), + 'reason_code': __import__('app.services.shipping_notice.process_gate_projection', fromlist=['task_blocking_reason']).task_blocking_reason(task), } return {key: value for key, value in snapshot.items() if value is not None} diff --git a/backend/app/services/shipping_notice/tool_response.py b/backend/app/services/shipping_notice/tool_response.py index f2699515..50c33f37 100644 --- a/backend/app/services/shipping_notice/tool_response.py +++ b/backend/app/services/shipping_notice/tool_response.py @@ -12,10 +12,10 @@ from __future__ import annotations from typing import TYPE_CHECKING, Any if TYPE_CHECKING: - from app.models import ShippingNotice + from app.models import ShippingNotice, ShippingOrderTask -def _task_has_process_execution(task: ShippingNotice | None) -> bool: +def _task_has_process_execution(task: ShippingOrderTask | ShippingNotice | None) -> bool: """ 判断任务是否已绑定 ProcessExecution(Gate 为恢复真相源)。 @@ -27,11 +27,17 @@ def _task_has_process_execution(task: ShippingNotice | None) -> bool: """ if task is None or getattr(task, 'id', None) is None: return False - from app.models import ShippingProcessExecution + from app.models import ShippingNotice, ShippingProcessExecution + if isinstance(task, ShippingNotice): + task_id = int(task.order_task_id) if task.order_task_id is not None else None + else: + task_id = int(task.id) if getattr(task, 'id', None) is not None else None + if task_id is None: + return False return ( ShippingProcessExecution.query - .filter_by(task_id=int(task.id)) + .filter_by(task_id=task_id) .filter(ShippingProcessExecution.status != 'superseded') .first() is not None diff --git a/backend/app/services/shipping_notice/tools.py b/backend/app/services/shipping_notice/tools.py index 62efdde8..6e38cc90 100644 --- a/backend/app/services/shipping_notice/tools.py +++ b/backend/app/services/shipping_notice/tools.py @@ -20,7 +20,6 @@ from app.services.shipping_notice import customer_identity_gate # 任务 / 决策 create_task = task_workflow.create_task auto_progress = task_workflow.auto_progress -submit_decision = task_workflow.submit_decision get_task_status = task_workflow.get_task_status retry_task = task_workflow.retry_task update_notice_fields = task_workflow.update_notice_fields diff --git a/backend/app/services/shipping_notice/user_facing_status.py b/backend/app/services/shipping_notice/user_facing_status.py index e7bc9af7..5e8f91a3 100644 --- a/backend/app/services/shipping_notice/user_facing_status.py +++ b/backend/app/services/shipping_notice/user_facing_status.py @@ -8,7 +8,8 @@ services/shipping_notice/user_facing_status.py from __future__ import annotations -from app.models import ShippingNotice +from app import db +from app.models import ShippingNotice, ShippingOrderTask from app.services.shipping_notice.constants import ( CP_EXPORT_READY, CP_INVENTORY_PENDING, @@ -86,16 +87,24 @@ def user_facing_task_stage(task: ShippingNotice) -> str: 这类细粒度状态被通用 checkpoint(如“待上传或获取库存”)覆盖; STP 多源 Excel 阻断覆盖通用 shortage 文案。 """ - payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} + # Notice 只承载正式单据;流程/UI 状态归属关联 OT。 + owner = task + if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): + owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task + payload = getattr(owner, 'step_payload_json', None) + payload = payload if isinstance(payload, dict) else {} if payload.get('multi_source_excel_block'): return '多库存源冲突,待人工处理' - reason = str(task.pending_human_reason or "").strip() + from app.services.shipping_notice.process_gate_projection import task_blocking_reason + + reason = str(task_blocking_reason(owner) or '').strip() if reason in _PENDING_REASON_LABELS: return _PENDING_REASON_LABELS[reason] - ui = resolve_task_ui_state(task) + ui = resolve_task_ui_state(owner) if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS: return _CHECKPOINT_LABELS[ui.checkpoint] - return str(getattr(task, "lifecycle_status", None) or "active") == "active" and "处理中" or "已结束" + lifecycle = str(getattr(owner, "lifecycle_status", None) or getattr(owner, 'status', None) or "active") + return lifecycle == "active" and "处理中" or "已结束" def strip_internal_task_fields(data: dict) -> dict: diff --git a/backend/app/services/shipping_notice/workflow_ledger_service.py b/backend/app/services/shipping_notice/workflow_ledger_service.py index 654348f3..03f87138 100644 --- a/backend/app/services/shipping_notice/workflow_ledger_service.py +++ b/backend/app/services/shipping_notice/workflow_ledger_service.py @@ -336,11 +336,15 @@ def task_has_entered_inventory_match(task: ShippingNotice) -> bool: Returns: True 表示已进入 matched 或更后阶段。 """ - match_status = str(getattr(task, 'match_status', None) or '').strip().lower() + from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) + match_status = aggregate_match_status_for_task(match_task_id) or '' + from app.services.shipping_notice.upload_attempt_service import latest_export_artifact, latest_upload_attempt + artifact = latest_export_artifact(task) + attempt = latest_upload_attempt(task) return match_status in {'fulfillable', 'partial', 'unfulfillable', 'matched'} or bool( - str(getattr(task, 'export_file_path', None) or '').strip() - or str(getattr(task, 'freight_ref_no', None) or '').strip() - or str(getattr(task, 'upload_status', None) or '').strip() + str(getattr(artifact, 'file_path', None) or '').strip() + or str(getattr(attempt, 'status', None) or '').strip() ) diff --git a/backend/tests/services/shipping_notice/test_customer_resolution_service.py b/backend/tests/services/shipping_notice/test_customer_resolution_service.py new file mode 100644 index 00000000..0161d3b2 --- /dev/null +++ b/backend/tests/services/shipping_notice/test_customer_resolution_service.py @@ -0,0 +1,84 @@ +""" +用途:验证正式客户识别结果是客户确认与流程 Gate 的唯一真相源。 +依赖:内存数据库、客户识别结果服务、ShippingOrderTask/Candidate。 +逻辑:覆盖非 bill_to 证据可确认,以及仅有旧 Bill-to Match 时不得放行两条边界。 +""" + +from __future__ import annotations + +from app import db +from app.models import ( + ShippingCustomer, + ShippingCustomerShadowResolution, + ShippingOrderCandidate, + ShippingOrderIntake, + ShippingOrderTask, + User, +) +from app.services.shipping_notice.customer_resolution_service import ( + confirm_customer_resolution, + customer_resolution_facts, +) + + +def _task_with_resolution(*, status: str = 'unique_candidate') -> tuple[ShippingOrderTask, ShippingCustomerShadowResolution, ShippingCustomer]: + """构造 OT、Candidate 和规则证据快照;不构造 bill_to 字段或 CustomerMatch。""" + user = User(username='resolution-user', email='resolution@example.com', role='user') + customer = ShippingCustomer(standard_name='规则识别客户', short_code='RID', status='active') + db.session.add_all([user, customer]) + db.session.flush() + intake = ShippingOrderIntake( + intake_no='INT-RESOLUTION', asset_id=1, user_id=user.id, parser_version='test', + ) + db.session.add(intake) + db.session.flush() + candidate = ShippingOrderCandidate( + candidate_no='CAND-RESOLUTION', intake_id=intake.id, primary_document_id=1, + candidate_key='resolution-test', candidate_status='accepted', + ) + db.session.add(candidate) + db.session.flush() + task = ShippingOrderTask(task_no='OT-RESOLUTION', user_id=user.id, candidate_id=candidate.id) + resolution = ShippingCustomerShadowResolution( + candidate_id=candidate.id, + intake_id=intake.id, + resolution_version='shadow-v2', + status=status, + evidence_json=[{'definition_id': 'customer-code', 'normalized_value': 'C-100'}], + candidate_matches_json=[{'customer_id': customer.id, 'score': 100}], + resolution_context_json={'rule_set': {'checksum': 'a' * 64}}, + identity_rule_set_checksum='a' * 64, + top_customer_id=customer.id, + top_score=100, + ) + db.session.add_all([task, resolution]) + db.session.commit() + return task, resolution, customer + + +def test_non_bill_to_evidence_can_confirm_customer(app): + """关键断言:客户代码证据可确认客户,流程不要求 bill_to 字段或旧匹配行。""" + with app.app_context(): + task, resolution, customer = _task_with_resolution() + + confirm_customer_resolution(task, customer_id=customer.id, actor_id=None, method='manual') + db.session.commit() + facts = customer_resolution_facts(task) + + assert facts['status'] == 'confirmed' + assert facts['customer_id'] == customer.id + assert resolution.confirmed_customer_id == customer.id + # 关键断言:确认不篡改规则证据及其 checksum。 + assert resolution.evidence_json == [{'definition_id': 'customer-code', 'normalized_value': 'C-100'}] + assert resolution.identity_rule_set_checksum == 'a' * 64 + + +def test_unconfirmed_resolution_fails_closed_without_old_bill_to_fallback(app): + """关键断言:未确认的统一识别结果不得从旧字段或旧匹配路径获得客户身份。""" + with app.app_context(): + task, _resolution, _customer = _task_with_resolution(status='unique_candidate') + + facts = customer_resolution_facts(task) + + assert facts['status'] == 'unique_candidate' + assert facts['customer_id'] is None diff --git a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py index 68695869..6a95bc1e 100644 --- a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py +++ b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py @@ -199,7 +199,8 @@ def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch): """正式 field_completeness 阻断必须覆盖 Case draft 的 idle/order_review_build 推导。""" from app.services.shipping_notice import reconciliation_projector - case = _fake_case(status='draft', candidate_id=None) + # 正式门禁事实只在 Case 已确认(confirmed)时覆盖;未确认 draft 保持 order_review_build(见结算设计)。 + case = _fake_case(status='confirmed', candidate_id=None) monkeypatch.setattr( reconciliation_projector, '_project_case_formal_gate_summary', diff --git a/backend/tests/test_shipping_attachment_selection.py b/backend/tests/test_shipping_attachment_selection.py index e3afa735..18d931da 100644 --- a/backend/tests/test_shipping_attachment_selection.py +++ b/backend/tests/test_shipping_attachment_selection.py @@ -238,8 +238,10 @@ def test_serialize_order_extraction_run_includes_selection_plan_summary(monkeypa phase='queued', schema_version_id=1, attempt_count=0, - reparse_source=None, - superseding_run=None, + reparse_source=None, + reparse_of_run_id=None, + superseded_by_run_id=None, + superseding_run=None, reparse_reason=None, superseded_at=None, result_json=None, diff --git a/backend/tests/test_shipping_auto_progress_controller_phase1.py b/backend/tests/test_shipping_auto_progress_controller_phase1.py index caef0a9b..bd7495a6 100644 --- a/backend/tests/test_shipping_auto_progress_controller_phase1.py +++ b/backend/tests/test_shipping_auto_progress_controller_phase1.py @@ -80,6 +80,7 @@ def test_contract_01_extraction_ready_creates_stp_job_via_run_coordinator(app): run_id=10, run=run, owner_user_id=1, + stream_id=100, current_draft=SimpleNamespace( draft_version=1, validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'}, @@ -103,6 +104,7 @@ def test_contract_01_extraction_ready_creates_stp_job_via_run_coordinator(app): return_value={'status': 'queued', 'job_id': 1201, 'idempotency_key': 'stp-auto:SNER-COORD-1:doc-100:v1'}, ) as ensure_mock: + RC_Mock.query.join.return_value.filter.return_value.order_by.return_value.with_entities.return_value.all.return_value = [SimpleNamespace(id=1)] RC_Mock.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [ SimpleNamespace(id=1), ] @@ -136,6 +138,7 @@ def test_contract_02_draft_validated_ready_triggers_single_case_coordinator(app) run_id=20, run=SimpleNamespace(id=20, run_no='SNER-20'), owner_user_id=1, + stream_id=200, current_draft=SimpleNamespace( draft_version=3, validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'}, @@ -172,6 +175,7 @@ def test_contract_03_customer_auto_confirmed_runs_coordinator(app): id=3, case_no='SORC-P1-03', status='unreviewed', confirmed_task_id=None, document_id=300, candidate_id=30, run_id=30, run=SimpleNamespace(id=30, run_no='SNER-30'), owner_user_id=1, + stream_id=300, current_draft=SimpleNamespace( draft_version=2, validation_result_json={'can_build': True, 'can_auto_create': False, 'status': 'draft'}, @@ -232,34 +236,26 @@ def test_unique_customer_auto_confirmation_defers_commit_to_resume_transaction(a case = SimpleNamespace(case_no='SORC-UNIQUE-COMMIT', candidate_id=31) candidate = SimpleNamespace(id=31) shadow = SimpleNamespace(status='unique_candidate', top_customer_id=5555) - extraction = SimpleNamespace(id=101) shadow_model = SimpleNamespace( query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: shadow)), ) - match_model = SimpleNamespace( - query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=1))), - ) with patch.object(coord.db.session, 'get', return_value=candidate), patch.object( coord, 'ShippingCustomerShadowResolution', shadow_model, ), patch.object(coord, 'resolve_review_case_customer_resolved', return_value=False), patch.object( coord, - '_resolve_extraction_for_case', - return_value=extraction, - ), patch.object( - coord, - 'ShippingOrderCustomerMatch', - match_model, - ), patch.object(coord, 'confirm_order_customer_match') as confirm_mock, patch.object( + 'confirm_customer_resolution', + autospec=True, + ) as confirm_mock, patch.object( coord, 'record_fulfillment_audit', ): status, metadata = coord._customer_step_for_case(case=case, trigger='draft_validated') assert status == 'auto_confirmed' - assert metadata == {'customer_id': 5555, 'extraction_id': 101} - assert confirm_mock.call_args.kwargs['commit'] is False + assert metadata == {'customer_id': 5555, 'extraction_id': None} + assert confirm_mock.call_args.kwargs['method'] == 'auto_rule' def test_contract_04_sweeper_does_not_enqueue_stp_after_failure(app): @@ -313,6 +309,7 @@ def test_contract_04b_run_coordinator_skips_manual_draft_validation(app): run_id=42, run=run, owner_user_id=1, + stream_id=420, current_draft=SimpleNamespace( draft_version=8, header_values_json={}, @@ -331,6 +328,7 @@ def test_contract_04b_run_coordinator_skips_manual_draft_validation(app): 'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case', return_value={'status': 'waiting_manual_validation'}, ): + review_case.query.join.return_value.filter.return_value.order_by.return_value.with_entities.return_value.all.return_value = [SimpleNamespace(id=42)] review_case.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [ SimpleNamespace(id=42), ] @@ -465,6 +463,26 @@ def test_contract_06_duplicate_blocked_case_rejects_general_retry(app): ) is True +def test_contract_06_legacy_unexpected_stp_failure_allows_general_retry(app): + """修复前落库的技术异常不能继续阻止普通 STP 重试。""" + from app.services.shipping_notice import reconciliation_service as rs + + case = SimpleNamespace( + case_no='SORC-P1-06-TECH', status='ready', confirmed_task_id=None, + document_id=601, run=SimpleNamespace(run_no='SNER-P1-06-TECH'), + ) + with patch.object(rs, 'Job') as Job: + Job.query.filter.return_value.filter.return_value.order_by.return_value.first.return_value = SimpleNamespace( + id=61, status='failed', + result_json={ + 'retryable': False, + 'blocking_reason': 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED', + 'error_code': 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED', + }, + ) + rs.assert_case_not_blocked_manual(case_no='SORC-P1-06-TECH', case=case) + + def test_contract_07_get_projection_is_pure_read_no_writes(app): """合同 7:GET 投影 → 不 confirm 客户、不 validate Draft、不 commit 事务。""" from app.services.shipping_notice.order_review_customer_service import ( @@ -482,11 +500,7 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app): ) as sess_mock, patch( 'app.services.shipping_notice.order_review_customer_service.resolve_review_case_customer_resolved', return_value=False, - ), patch( - 'app.services.shipping_notice.order_review_customer_service.refresh_order_customer_matches', - ) as refresh_mock, patch( - 'app.services.shipping_notice.order_review_customer_service.confirm_order_customer_match', - ) as confirm_mock: + ): # Shadow = unique_candidate 但是 resolved=false。 with patch( 'app.services.shipping_notice.order_review_customer_service.ShippingCustomerShadowResolution', @@ -501,19 +515,14 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app): with patch( 'app.services.shipping_notice.order_review_customer_service.ShippingOrderCandidate', ) as Cand, patch( - 'app.services.shipping_notice.order_review_customer_service.ShippingOrderCustomerMatch', - ) as CM, patch( 'app.services.shipping_notice.order_review_customer_service.ShippingOrderExtraction', ) as EX: sess_mock.get.return_value = SimpleNamespace(id=70, order_extraction_id=700) - CM.query.filter_by.return_value.first.return_value = None EX.query.filter_by.return_value.order_by.return_value.first.return_value = SimpleNamespace(id=700) # 执行投影(纯读) out = project_review_case_customer_resolution(case) # 7A:GET 路径不允许 confirm / validate / commit - confirm_mock.assert_not_called() - refresh_mock.assert_not_called() sess_mock.commit.assert_not_called() # 7B:投影仍然能够返回客户状态(unique_candidate 而非 confirmed,因为没被写入确认) assert out.get('resolved') is False diff --git a/backend/tests/test_shipping_auto_progress_p0_3.py b/backend/tests/test_shipping_auto_progress_p0_3.py index 1bc54951..acb1b3e6 100644 --- a/backend/tests/test_shipping_auto_progress_p0_3.py +++ b/backend/tests/test_shipping_auto_progress_p0_3.py @@ -15,7 +15,7 @@ from app import db from app.models import ( Job, ShippingInventoryCandidateSet, - ShippingNotice, + ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt, @@ -28,9 +28,9 @@ from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_t from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version -def _task_with_candidate(*, complete_order: bool = True) -> ShippingNotice: +def _task_with_candidate(*, complete_order: bool = True) -> ShippingOrderTask: """创建正式 Task;可选择是否补齐订单解析与冻结快照事实。""" - task = ShippingNotice(task_no='APX-P0-3-001') + task = ShippingOrderTask(task_no='OT-APX-P0-3-001', user_id=1) db.session.add(task) db.session.flush() candidate = ShippingInventoryCandidateSet( @@ -101,7 +101,7 @@ def test_formal_execution_queues_one_gate_attempt_job(app): formal = ensure_execution_for_workflow_version(review_case_id=902, task_id=int(task.id)) mark_gates_passed_through( execution=formal, - through_gate_code='task_creation', + through_gate_code='inventory_source_routing', reason='test_review_confirmed', ) task.active_process_execution_id = formal.id @@ -148,6 +148,65 @@ def test_submit_does_not_enqueue_navigation_action_for_worker_gate(app): assert Job.query.filter_by(job_type='shipping_process_gate').count() == 0 +def test_submit_does_not_redispatch_after_failed_worker_attempt(app): + """[断言] Worker 真实执行失败(failed + job_id 非空)的门禁:auto_progress 不得自动重试, + 必须等待用户在当前 Gate 显式恢复;首次投递通道(无失败 Attempt)不受影响(由 + test_formal_execution_queues_one_gate_attempt_job 锁定)。""" + import uuid as _uuid + + task = _task_with_candidate() + execution = ensure_execution_for_workflow_version(review_case_id=904, task_id=int(task.id)) + mark_gates_passed_through( + execution=execution, + through_gate_code='inventory_source_routing', + reason='test_review_confirmed', + ) + gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), gate_code='inventory_preparation', + ).one() + # Worker 已真实执行并失败:failed Attempt 持有非空 job_id + failed_job = Job( + domain='shipping_notice', job_type='shipping_process_gate', + status='failed', business_ref='apx-p03-failed-gate-job', + ) + db.session.add(failed_job) + db.session.flush() + db.session.add(ShippingProcessGateAttempt( + gate_id=int(gate.id), + attempt_no=1, + status='failed', + trigger_type='auto', + actor_type='system', + actor_id='external-wait-poll', + idempotency_key=f'test-failed-worker-attempt:{_uuid.uuid4().hex}', + job_id=int(failed_job.id), + )) + gate.status = 'blocked_retryable' + gate.next_action_code = 'retry_inventory_preparation' + execution.status = 'blocked' + execution.current_gate_code = 'inventory_preparation' + execution.primary_next_action_code = 'retry_inventory_preparation' + execution.responsible_party = 'worker' + task.active_process_execution_id = int(execution.id) + db.session.commit() + + # 同步事实是本用例之外的职责;固定复现“同步后仍为可重试阻断”的当前 Gate。 + with patch( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + ): + result = submit_auto_progress(task=task, trigger='inventory_rpa_callback_succeeded') + + assert result['status'] == 'waiting_human' + assert result['gate_code'] == 'inventory_preparation' + # 没有新的 ProcessGate Job 被创建(仅存量失败 Job) + assert Job.query.filter( + Job.job_type == 'shipping_process_gate', + Job.id != int(failed_job.id), + ).count() == 0 + # Attempt 数量不变:只有种子失败行,未被自动重派 + assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1 + + def test_active_stp_job_without_retry_metadata_is_reused(app): """活动旧 Job 缺少可选 retry 元数据时仍应幂等复用。""" from types import SimpleNamespace @@ -183,3 +242,90 @@ def test_active_stp_job_without_retry_metadata_is_reused(app): assert result['retry_of_job_id'] is None +def test_derived_fulfillment_status_uses_line_match_facts_for_order_task(): + """OT 履约状态必须从行级 Match 事实推导,不再读取已删除的 Notice JSON 投影。""" + from types import SimpleNamespace + from app.services.shipping_notice.process_gate_bridge import _derived_fulfillment_status + + task = SimpleNamespace(id=1) + with patch( + 'app.services.shipping_notice.inventory_file_store.inventory_matches_complete_for_task', + return_value=True, + ), patch( + 'app.services.shipping_notice.inventory_file_store.current_inventory_matches_have_shortage', + return_value=False, + ), patch( + 'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success', + return_value=False, + ), patch( + 'app.services.shipping_notice.upload_attempt_service.latest_upload_attempt', + return_value=None, + ), patch( + 'app.services.shipping_notice.process_gate_projection.task_blocking_reason', + return_value=None, + ), patch( + 'app.services.shipping_notice.process_gate_bridge.ShippingOrderTask', + SimpleNamespace, + ): + assert _derived_fulfillment_status(task) == 'matched' + + +def test_auto_retry_blocked_only_for_non_user_trigger(): + """Bug 修复:[禁止自动重试] 仅拦非用户显式触发 / 无定向 gate 的自动推进。 + + 核心逻辑:has_failed_worker_attempt 守卫本意是防止自动/后台 trigger 无限重试, + 用户显式重试(user_retry/user_manual)或带 resume_gate_code 的显式定向推进 + (如匹配工具 tool_api_match_inventory_line + resume_gate_code='inventory_matching') + 应绕过,否则点"重新匹配库存"报"无待处理 Gate"。 + """ + from app.services.shipping_notice.auto_progress_controller import _auto_retry_blocked + + assert _auto_retry_blocked('auto', True) is True + assert _auto_retry_blocked('system_requeue', True) is True + assert _auto_retry_blocked('worker_takeover', True) is True + assert _auto_retry_blocked('user_retry', True) is False + assert _auto_retry_blocked('user_manual', True) is False + assert _auto_retry_blocked('user_retry', False) is False + assert _auto_retry_blocked('auto', False) is False + # 匹配工具 trigger 非 user_retry,但带 resume_gate_code(显式定向重匹配)→ 放行 + assert _auto_retry_blocked('tool_api_match_inventory_line', True) is True + assert _auto_retry_blocked('tool_api_match_inventory_line', True, resume_gate_code='inventory_matching') is False + assert _auto_retry_blocked('auto', True, resume_gate_code='inventory_matching') is False + + +def test_retry_inventory_matching_fulfillable_passes(): + """Bug 修复:已可履约订单的"重新匹配库存"应通过,不把 match_inventory 内部的 + run_task_auto_progress "无待处理 Gate"(status='completed')误判为失败。 + + 核心逻辑:_handle_retry_inventory_matching 只在 needs_human+shortage 时 return passed; + 对 match_status='fulfillable' + response.status='completed' 会落 _tool_outcome 判为 + blocked_retryable,把"无待处理 Gate"记作 error_summary。修复:fulfillable 直接 passed。 + """ + from app.services.shipping_notice import process_gate_executor as ex + from unittest.mock import MagicMock + + class _Task: + id = 1 + task_no = 'OT-X' + order_snapshot_id = 1 + + class _Execution: + task_id = 1 + + class _Gate: + gate_code = 'inventory_matching' + + class _OT: + query = MagicMock(get=MagicMock(return_value=_Task())) + + with patch('app.services.shipping_notice.fulfillment_workflow.match_inventory', return_value={ + 'status': 'completed', 'message': '自动推进已无待处理 Gate。', 'data': {}, 'task_id': 'x', 'checkpoint': None, + }), patch('app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', return_value=None), \ + patch('app.services.shipping_notice.process_gate_executor.ShippingOrderTask', _OT), \ + patch('app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', return_value=True), \ + patch('app.services.shipping_notice.fulfillment_workflow.match_completed', return_value=True), \ + patch('app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task', return_value={}): + result = ex._handle_retry_inventory_matching(execution=_Execution(), gate=_Gate(), payload={'actor_user_id': 1}) + assert result['outcome'] == 'passed' + + diff --git a/backend/tests/test_shipping_candidate_qualification.py b/backend/tests/test_shipping_candidate_qualification.py index 42605672..289a8a85 100644 --- a/backend/tests/test_shipping_candidate_qualification.py +++ b/backend/tests/test_shipping_candidate_qualification.py @@ -128,6 +128,9 @@ def test_derived_field_evidence_gap_does_not_block_candidate_qualification(monke conflicts_json=[{ 'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing', 'owning_gate_code': 'field_completeness', + # 派生/已解决字段的历史 evidence_missing 由写路径 _discard_resolved_worker_field_conflicts + # 在投影到 Candidate 前丢弃;资格 Gate 只按冻结字段配置判断证据缺失是否可选。 + 'field_config': {'required': False, 'auto_create_key_field': False}, }], structured_result_json={ 'customer': {'resolution_status': 'user_confirmed'}, diff --git a/backend/tests/test_shipping_chat_action_handlers.py b/backend/tests/test_shipping_chat_action_handlers.py index 81623ef3..1c03142b 100644 --- a/backend/tests/test_shipping_chat_action_handlers.py +++ b/backend/tests/test_shipping_chat_action_handlers.py @@ -23,7 +23,6 @@ def test_legacy_fulfillment_chat_actions_are_not_registered(): "shipping.retry_upload", "shipping.match_inventory", "shipping.confirm_inventory_source", - "shipping.submit_decision", "shipping.mark_manual_uploaded", }.isdisjoint(action_types) diff --git a/backend/tests/test_shipping_chat_tool_capability.py b/backend/tests/test_shipping_chat_tool_capability.py index 97852023..e0d85377 100644 --- a/backend/tests/test_shipping_chat_tool_capability.py +++ b/backend/tests/test_shipping_chat_tool_capability.py @@ -7,7 +7,7 @@ from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import ForbiddenError -from app.models import Agent, ChatSession, ShippingNotice, User +from app.models import Agent, ChatSession, ShippingOrderTask, User from app.services.shipping_notice.chat_tool_capability import issue_chat_capability, require_chat_capability @@ -18,10 +18,10 @@ def test_chat_capability_rejects_cross_task_and_expired_scope(app): agent = Agent(name='cap-agent', agent_code='shipping_notice', is_active=True) db.session.add_all([user, agent]); db.session.flush() session = ChatSession(session_id='cap-session', user_id=user.id, agent_id=agent.id) - own = ShippingNotice(task_no='SN-CAP-OWN', user_id=user.id, source_type='test') - other = ShippingNotice(task_no='SN-CAP-OTHER', source_type='test') + own = ShippingOrderTask(task_no='SN-CAP-OWN', user_id=user.id, source_type=None) + other = ShippingOrderTask(task_no='SN-CAP-OTHER', user_id=user.id, source_type=None) db.session.add_all([session, own, other]); db.session.commit() - token = issue_chat_capability(user_id=user.id, session_id=session.session_id, agent_id=agent.id, task_no=own.task_no, batch_no=None) + token = issue_chat_capability(user_id=user.id, session_id=session.session_id, agent_id=agent.id, task_no=own.task_no) assert require_chat_capability(token=token, scope='get_shipping_status', task_no=own.task_no)['uid'] == user.id with pytest.raises(ForbiddenError): require_chat_capability(token=token, scope='get_shipping_status', task_no=other.task_no) diff --git a/backend/tests/test_shipping_coordinate_table_reconstruction.py b/backend/tests/test_shipping_coordinate_table_reconstruction.py index 648495cc..39cae2f2 100644 --- a/backend/tests/test_shipping_coordinate_table_reconstruction.py +++ b/backend/tests/test_shipping_coordinate_table_reconstruction.py @@ -186,7 +186,7 @@ def test_adaptive_record_columns_supports_compact_and_expanded_visual_rows(): ), table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 130}, line_layouts=_adaptive_layouts(), row_reconstruction_mode='adaptive_record_columns', ) - # Both layouts must yield a complete logical record despite their different visual-band counts. + # 两种视觉排版均可从明确的 ``@ + 纯数字`` 预约号段还原完整逻辑明细。 assert compact[0].fields == { 'customer_po_line_no': '10', 'part_number': 'PART-A', 'qty': '9.000', 'uom': 'PCS', 'requested_receipt_date': '2026/07/10', 'unit_price': '898.72', 'line_amount_with_tax': '8,088.48', @@ -870,6 +870,22 @@ def test_adaptive_record_columns_accepts_numeric_reservation_id_without_at_sign( assert rows[0].fields['reservation_id'] == '3000097059' +def test_coordinate_profile_rows_accept_reservation_with_text_suffix_truncated(): + """预约号框内含文本后缀时可截断为纯数字写入(生产行为)。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('10', 5), ('PART-A', 60)], [('1.000', 115), ('PCS', 145), ('2026/05/26', 170)], + [('898.72', 80), ('898.72', 165)], [('3000097059(PENROSE)', 115)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100}, + line_layouts=_adaptive_layouts(), + row_reconstruction_mode='adaptive_record_columns', + ) + + # 允许将带文本后缀的预约号截断为纯数字(生产已实现)。 + assert rows[0].fields['reservation_id'] == '3000097059' + + def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_line(): """一个物理行包含多条视觉子行时,字段必须按父行内相对 Y 重复命中后续明细。""" rows = reconstruct_coordinate_profile_rows( @@ -974,6 +990,70 @@ def test_dynamic_x_columns_translates_all_field_frames_from_the_record_anchor(): }] +def test_dynamic_x_columns_clamps_a_shifted_wide_field_frame_to_the_page_top(): + """锚点上移把宽字段框推过页顶时,截断框仍须读取页面内的有效字符。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs([('1', 10), ('PART-A', 60)]), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60}, + line_layouts=[{ + 'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .70, 'x1': .25, 'y1': .80}}, + {'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}}, + ], + }], + line_start_field_code='customer_po_line_no', + row_reconstruction_mode='dynamic_x_columns', + ) + + assert [row.fields for row in rows] == [{'customer_po_line_no': '1', 'part_number': 'PART-A'}] + + +def test_dynamic_x_columns_honors_deleted_marker_exclusion_authorization(): + """dynamic 模式绕过普通排除过滤时,仍须使用配置排除区授权删除标记。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('00010', 10), ('PART-A', 65)], + [('** Item deleted **', 65)], + [('00020', 10), ('PART-B', 65)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, + line_layouts=[{ + 'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .3, 'y1': .3}}, + {'field_code': 'part_number', 'region': {'x0': .3, 'y0': .15, 'x1': 1, 'y1': .3}}, + ], + }], + exclusion_regions=[{'x0': .3, 'y0': .3, 'x1': .8, 'y1': .5}], + row_reconstruction_mode='dynamic_x_columns', + ) + + assert [row.fields['customer_po_line_no'] for row in rows] == ['00020'] + + +def test_dynamic_x_columns_ignores_unconfigured_deleted_marker(): + """dynamic 模式没有删除标记排除授权时,不得擅自删除上一条明细。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('00010', 10), ('PART-A', 65)], + [('** Item deleted **', 65)], + [('00020', 10), ('PART-B', 65)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, + line_layouts=[{ + 'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .3, 'y1': .3}}, + {'field_code': 'part_number', 'region': {'x0': .3, 'y0': .15, 'x1': 1, 'y1': .3}}, + ], + }], + row_reconstruction_mode='dynamic_x_columns', + ) + + assert [row.fields['customer_po_line_no'] for row in rows] == ['00010', '00020'] + + def test_fixed_relative_y_rows_translate_every_field_frame_from_each_record_anchor(): """固定子行同样必须按记录锚点平移,不能把客户料号误读到供应商料号框。""" rows = reconstruct_coordinate_profile_rows( @@ -1145,6 +1225,114 @@ def test_coordinate_profile_rows_realign_a_record_with_an_extra_unbound_visual_b assert [row.fields['part_number'] for row in rows] == ['PART-A', 'PART-B'] +def test_coordinate_profile_rows_keep_main_row_fields_and_skip_description_wrap_for_part_number(): + """主视觉行同时含日期金额时,描述折行不得占用内部料号视觉位置。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('10', 10), ('40', 80), ('RK-00410-001B', 130), ('08/28/2026', 260), + ('941.76', 320), ('37670.40', 365)], + [('BUSBAR', 130)], + [('D4-A08AR12000002', 130)], + [('Revision:A0', 130)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100}, + table_region={'x0': 0, 'y0': .1, 'x1': 1, 'y1': .8}, + line_layouts=[{'layout_id': 'detail', 'row_offset': 0, 'role': 'main', + 'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .8}, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}}, + {'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}}, + {'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}}, + {'field_code': 'requested_receipt_date', 'region': {'x0': .65, 'y0': .2, 'x1': .78, 'y1': .3}}, + {'field_code': 'unit_price', 'region': {'x0': .79, 'y0': .2, 'x1': .88, 'y1': .3}}, + {'field_code': 'line_amount_with_tax', 'region': {'x0': .88, 'y0': .2, 'x1': 1, 'y1': .3}}, + {'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}}, + ]}], + schema_field_metadata=[ + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + {'field_code': 'requested_receipt_date', 'scope': 'line', 'value_type': 'date'}, + {'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, + {'field_code': 'line_amount_with_tax', 'scope': 'line', 'value_type': 'decimal'}, + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + ], + ) + + assert rows[0].fields == { + 'customer_po_line_no': '10', 'qty': '40', 'customer_part_number': 'RK-00410-001B', + 'requested_receipt_date': '08/28/2026', 'unit_price': '941.76', + 'line_amount_with_tax': '37670.40', 'part_number': 'D4-A08AR12000002', + } + + +@pytest.mark.parametrize('row_reconstruction_mode', [ + 'fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns', +]) +def test_two_subrow_layout_rescans_description_wrap_before_part_number(row_reconstruction_mode): + """真实 ZT 两子行布局中,描述折行不能占用内部料号的固定续行。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('10', 10), ('40', 80), ('RK-00410-001B', 130)], + [('BUSBAR', 130)], + [('D4-A08AR12000002', 130)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100}, + line_layouts=[ + {'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .3}, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}}, + {'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}}, + {'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}}, + ]}, + {'layout_id': 'part', 'row_offset': 1, 'region': {'x0': 0, 'y0': .34, 'x1': 1, 'y1': .44}, 'field_regions': [ + {'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}}, + ]}, + ], + row_reconstruction_mode=row_reconstruction_mode, + schema_field_metadata=[ + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + ], + ) + + assert rows[0].fields['part_number'] == 'D4-A08AR12000002' + + +@pytest.mark.parametrize('row_reconstruction_mode', [ + 'fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns', +]) +def test_two_subrow_layout_rescans_numeric_description_wrap_before_part_number(row_reconstruction_mode): + """真实 ZT 两子行布局中,含数字和标点的描述折行也不能占用内部料号续行。""" + rows = reconstruct_coordinate_profile_rows( + characters=_glyphs( + [('10', 10), ('40', 80), ('RK-00410-001B', 130)], + [('48U AR1.2', 130)], + [('D4-A08AR12000002', 130)], + ), + table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100}, + line_layouts=[ + {'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .3}, 'field_regions': [ + {'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}}, + {'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}}, + {'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}}, + ]}, + {'layout_id': 'part', 'row_offset': 1, 'region': {'x0': 0, 'y0': .34, 'x1': 1, 'y1': .44}, 'field_regions': [ + {'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}}, + ]}, + ], + row_reconstruction_mode=row_reconstruction_mode, + schema_field_metadata=[ + {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'}, + {'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']}, + ], + ) + + assert rows[0].fields['part_number'] == 'D4-A08AR12000002' + + def test_coordinate_profile_rows_leave_an_ambiguous_shifted_field_for_review(): """额外视觉行中出现两个同等合法候选时必须留空并记录问题,禁止静默猜测。""" rows = reconstruct_coordinate_profile_rows( diff --git a/backend/tests/test_shipping_customer_auto_resolution.py b/backend/tests/test_shipping_customer_auto_resolution.py index 23543943..5de027a6 100644 --- a/backend/tests/test_shipping_customer_auto_resolution.py +++ b/backend/tests/test_shipping_customer_auto_resolution.py @@ -1,9 +1,9 @@ """ backend/tests/test_shipping_customer_auto_resolution.py -用途:验证受控自动客户确认、降级开关、强规则歧义和编号后客户纠错。 -依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice、customer_auto_resolution。 -逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。 +用途:验证受控 OT 自动客户确认、降级开关、强规则歧义和规则快照防篡改。 +依赖:客户主数据/证据、Candidate 影子结果、ShippingOrderTask、customer_auto_resolution。 +逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动确认,且不创建 Notice。 """ from copy import deepcopy @@ -11,7 +11,6 @@ from copy import deepcopy import pytest from app import db -from app.core.errors import ConflictError, ValidationError from app.models import ( FileAsset, ShippingCustomer, @@ -28,19 +27,17 @@ from app.models import ( ShippingOrderFieldValue, ShippingOrderSchema, ShippingOrderSchemaVersion, + ShippingOrderTask, ShippingNotice, ShippingTaskEvent, User, ) from app.services.shipping_notice.customer_auto_resolution import ( AUTO_RESOLUTION_VERSION, - correct_numbered_task_customer, get_auto_resolution_metrics, resolve_auto_customer_from_shadow, try_auto_confirm_task_customer, ) -from app.services.shipping_notice.customer_identity_gate import confirm_task_customer -from app.services.shipping_notice.query_service import get_task_by_ref def _auto_definition() -> tuple[ShippingIdentityDefinition, ShippingIdentityRuleSet]: @@ -123,10 +120,9 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"): ) db.session.add(candidate) db.session.flush() - task = ShippingNotice( - task_no=f"SN-AUTO-{user.id}", source_candidate_id=candidate.id, - user_id=user.id, source_type="email_attachment", - customer_resolution_status="pending", + task = ShippingOrderTask( + task_no=f"OT-AUTO-{user.id}", user_id=user.id, + candidate_id=candidate.id, source_type="eml", ) db.session.add(task) db.session.flush() @@ -201,8 +197,13 @@ def _allow_auto_confirmation(app) -> None: app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98 -def test_unique_approved_strong_rule_auto_confirms_and_numbers(app): - """开关启用且唯一邮箱强规则命中时自动确认客户并生成业务号。""" +def _assert_ot_did_not_create_notice(task: ShippingOrderTask) -> None: + """断言 OT 自动确认只写客户识别结果,不提前创建或编号正式 Notice。""" + assert ShippingNotice.query.filter_by(order_task_id=task.id).count() == 0 + + +def test_unique_approved_strong_rule_auto_confirms_at_ot_without_creating_notice(app): + """开关启用且唯一强规则命中时,OT 自动确认但不创建或编号 Notice。""" with app.app_context(): _allow_auto_confirmation(app) customer = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") @@ -212,22 +213,15 @@ def test_unique_approved_strong_rule_auto_confirms_and_numbers(app): assert result["status"] == "auto_confirmed" assert result["rule_version"] == AUTO_RESOLUTION_VERSION - assert task.customer_resolution_status == "confirmed" - assert task.customer_resolution_method == "auto_rule" - assert task.customer_id == customer.id - assert task.business_no.startswith("WYC") - assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 1 - event = ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").one() - assert event.detail_json['rule_set']['checksum'] - assert event.detail_json['evidence'][0]['definition_id'] - assert event.detail_json['evidence'][0]['evidence_id'] - source = event.detail_json['evidence'][0]['source'] - assert source['field_value_id'] and source['decision_id'] and source['extraction_id'] - assert source['order_schema_version_id'] == event.detail_json['order_schema_version_id'] + shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() + assert shadow.status == "confirmed" + assert shadow.confirmation_method == "auto_rule" + assert shadow.confirmed_customer_id == customer.id + assert shadow.evidence_json[0]['definition_id'] metrics = get_auto_resolution_metrics() + assert result['business_no'] is None + _assert_ot_did_not_create_notice(task) assert metrics["auto_confirmed_count"] == 1 - assert metrics["recent_events"][0]["event_type"] == "customer_auto_confirmed" - assert metrics["recent_events"][0]["task_no"] == task.task_no def test_switch_off_and_unapproved_rule_fall_back_to_manual(app): @@ -238,13 +232,13 @@ def test_switch_off_and_unapproved_rule_fall_back_to_manual(app): app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = False disabled = try_auto_confirm_task_customer(task) assert disabled["status"] == "disabled" - assert task.business_no is None + _assert_ot_did_not_create_notice(task) _allow_auto_confirmation(app) unmatched = try_auto_confirm_task_customer(task) assert unmatched["status"] == "unmatched" - assert task.customer_resolution_status == "pending" - assert task.business_no is None + assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate" + _assert_ot_did_not_create_notice(task) def test_multiple_customers_matching_strong_evidence_is_ambiguous(app): @@ -258,8 +252,8 @@ def test_multiple_customers_matching_strong_evidence_is_ambiguous(app): result = try_auto_confirm_task_customer(task) assert result["status"] == "ambiguous" assert len(result["candidate_customer_ids"]) == 2 - assert task.customer_resolution_status == "pending" - assert task.business_no is None + assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate" + _assert_ot_did_not_create_notice(task) def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app): @@ -275,10 +269,8 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app): db.session.rollback() db.session.expire_all() - persisted_task = db.session.get(ShippingNotice, task_id) - assert persisted_task.customer_resolution_status == "pending" - assert persisted_task.customer_id is None - assert persisted_task.business_no is None + persisted_task = db.session.get(ShippingOrderTask, task_id) + assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=persisted_task.candidate_id).one().status == "unique_candidate" assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0 @@ -295,8 +287,8 @@ def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insuffic assert result["status"] == "insufficient_labeled_samples" assert result["quality_gate"]["labeled_sample_count"] == 0 - assert task.customer_resolution_status == "pending" - assert task.business_no is None + assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate" + _assert_ot_did_not_create_notice(task) def test_business_evidence_never_auto_confirms(app): @@ -315,7 +307,7 @@ def test_business_evidence_never_auto_confirms(app): status='approved', auto_match_allowed=True, )) task = _seed_candidate_task() - shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one() + shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() original_source = shadow.evidence_json[0]['source'] field_value = db.session.get(ShippingOrderFieldValue, original_source['field_value_id']) decision = db.session.get(ShippingOrderFieldDecision, original_source['decision_id']) @@ -336,7 +328,7 @@ def test_business_evidence_never_auto_confirms(app): result = try_auto_confirm_task_customer(task) assert result['status'] == 'rule_snapshot_missing' - assert task.customer_resolution_status == 'pending' + assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == 'unique_candidate' def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app): @@ -347,7 +339,7 @@ def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app): task = _seed_candidate_task(sender='buyer@gmail.com') assert try_auto_confirm_task_customer(task)['status'] == 'unmatched' - shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one() + shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() shadow.resolution_context_json = {} db.session.commit() missing = resolve_auto_customer_from_shadow(task) @@ -361,14 +353,14 @@ def test_tampered_shadow_value_or_schema_anchor_never_auto_confirms(app): _allow_auto_confirmation(app) _customer_with_identifier(code='WYC', value='buyer@wyc.example.com') task = _seed_candidate_task() - shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one() + shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() evidence = deepcopy(shadow.evidence_json) evidence[0]['normalized_value'] = 'attacker@example.com' shadow.evidence_json = evidence db.session.commit() assert try_auto_confirm_task_customer(task)['status'] == 'unmatched' - assert task.customer_resolution_status == 'pending' + assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == 'unique_candidate' shadow.evidence_json = [] context = deepcopy(shadow.resolution_context_json) @@ -390,7 +382,7 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app db.session.add(truth) db.session.flush() task = _seed_candidate_task() - shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one() + shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() shadow.manual_customer_id = truth.id db.session.commit() @@ -400,79 +392,81 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app assert result["status"] == "insufficient_accuracy" assert result["quality_gate"]["labeled_sample_count"] == 1 assert result["quality_gate"]["accuracy"] == 0 - assert task.customer_resolution_status == "pending" - assert task.business_no is None + assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate" + _assert_ot_did_not_create_notice(task) -def test_numbered_customer_correction_voids_old_notice_and_creates_replacement(app): - """客户误确认纠错必须作废原 Notice,生成新客户编号并保持原号审计可查。""" +def _rebind_shadow_to_new_schema_version(shadow, *, new_version) -> None: + """把影子记录、证据与 Extraction 重锚到新 Schema 版本,模拟 Schema 重发布后重新解析。""" + shadow.order_schema_version_id = new_version.id + # JSON 列需整体重赋值才能被 SQLAlchemy 追踪变更,不能只在嵌套 dict 上就地修改。 + evidence = deepcopy(shadow.evidence_json) + evidence[0]['source']['order_schema_version_id'] = new_version.id + shadow.evidence_json = evidence + extraction = db.session.get( + ShippingOrderExtraction, evidence[0]['source']['extraction_id'], + ) + extraction.schema_version_id = new_version.id + + +def test_schema_republish_with_same_semantics_still_auto_confirms(app): + """Schema 重发布造成版本 id 错位、但字段语义(code/type/normalizer)未变时,自动确认仍放行。""" with app.app_context(): - wrong = ShippingCustomer(standard_name="错误客户", short_code="OLD", status="active") - correct = ShippingCustomer(standard_name="正确客户", short_code="NEW", status="active") - db.session.add_all([wrong, correct]) + _allow_auto_confirmation(app) + _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") + task = _seed_candidate_task() + shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() + + old_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id) + old_version.status = 'retired' + new_version = ShippingOrderSchemaVersion( + schema_id=old_version.schema_id, version=old_version.version + 1, status='published', + definition_json={'fields': [{ + 'field_id': old_version.definition_json['fields'][0]['field_id'], + 'field_code': 'bill_to_customer', 'display_name': 'Bill To Customer', + 'scope': 'header', 'value_type': 'string', 'enabled': True, + 'available_for_customer_identity': True, 'normalizer_key': 'lowercase_trim', + }]}, + checksum='f' * 64, + ) + db.session.add(new_version) db.session.flush() - first = ShippingNotice( - task_no="SN-CORRECTION-V1", document_version=1, - source_type="manual", upload_status="pending", customer_resolution_status="pending", inventory_source_code="DSV", - inventory_source_status="user_confirmed", inventory_lines_json=[{"sku": "A", "quantity": 1}], - match_status="fulfillable", line_results_json=[{"sku": "A"}], - export_file_path="/tmp/old.xlsx", export_file_name="old.xlsx", - ) - db.session.add(first) + _rebind_shadow_to_new_schema_version(shadow, new_version=new_version) db.session.commit() - confirm_task_customer(first, customer_id=wrong.id, actor_id=None) - old_business_no = first.business_no - result = correct_numbered_task_customer( - first, - customer_id=correct.id, - reason="自动识别客户错误", - actor_id=None, - ) + result = resolve_auto_customer_from_shadow(task) - replacement = db.session.get(ShippingNotice, result["new_notice_id"]) - assert first.business_no == old_business_no - assert first.lifecycle_status == "voided" - assert replacement.supersedes_task_id == first.id - assert replacement.business_no.startswith("NEW") - assert replacement.business_no != old_business_no - assert replacement.customer_resolution_method == "admin_correction" - assert replacement.inventory_source_status is None - assert replacement.inventory_lines_json is None - assert replacement.export_file_path is None - assert replacement.source_type == "manual" - assert get_task_by_ref(old_business_no).id == first.id - assert get_task_by_ref(replacement.business_no).id == replacement.id - assert ShippingTaskEvent.query.filter_by(event_type="customer_correction_applied").count() == 2 - metrics = get_auto_resolution_metrics() - assert metrics["corrected_task_count"] == 2 - assert metrics["recent_events"][0]["detail"]["old_business_no"] == old_business_no + assert result['status'] == 'unique_strong_match' + assert result['customer_id'] is not None -def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(app): - """纠错必须有原因,且已对外上传业务单需先走外部作废流程。""" +def test_schema_republish_changes_semantics_never_auto_confirms(app): + """Schema 重发布且字段语义变化(normalizer 变更)时,仍必须 fail-closed 到人工复核。""" with app.app_context(): - wrong = ShippingCustomer(standard_name="错误客户", short_code="BAD", status="active") - correct = ShippingCustomer(standard_name="正确客户", short_code="GOOD", status="active") - db.session.add_all([wrong, correct]) - db.session.flush() - task = ShippingNotice( - task_no="SN-CORRECTION-BLOCK", - source_type="manual", customer_resolution_status="pending", + _allow_auto_confirmation(app) + _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") + task = _seed_candidate_task() + shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() + + old_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id) + old_version.status = 'retired' + new_version = ShippingOrderSchemaVersion( + schema_id=old_version.schema_id, version=old_version.version + 1, status='published', + definition_json={'fields': [{ + 'field_id': old_version.definition_json['fields'][0]['field_id'], + 'field_code': 'bill_to_customer', 'display_name': 'Bill To Customer', + 'scope': 'header', 'value_type': 'string', 'enabled': True, + 'available_for_customer_identity': True, + 'normalizer_key': 'uppercase_trim', # 语义变化:normalizer 已变更,不得放行。 + }]}, + checksum='e' * 64, ) - db.session.add(task) + db.session.add(new_version) + db.session.flush() + _rebind_shadow_to_new_schema_version(shadow, new_version=new_version) db.session.commit() - confirm_task_customer(task, customer_id=wrong.id, actor_id=None) - with pytest.raises(ValidationError) as exc_info: - correct_numbered_task_customer(task, customer_id=correct.id, reason="", actor_id=None) - assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED" - db.session.rollback() + result = resolve_auto_customer_from_shadow(task) - task.upload_status = "uploaded" - db.session.commit() - with pytest.raises(ConflictError) as exc_info: - correct_numbered_task_customer(task, customer_id=correct.id, reason="客户错误", actor_id=None) - assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED" - db.session.rollback() - assert db.session.query(ShippingNotice).count() == 1 + assert result['status'] == 'rule_snapshot_missing' + assert result['customer_id'] is None diff --git a/backend/tests/test_shipping_customer_identity_gate.py b/backend/tests/test_shipping_customer_identity_gate.py index 410338ae..3759a3ac 100644 --- a/backend/tests/test_shipping_customer_identity_gate.py +++ b/backend/tests/test_shipping_customer_identity_gate.py @@ -1,146 +1,147 @@ """ backend/tests/test_shipping_customer_identity_gate.py -用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate。 -依赖:内存数据库、customer_identity_gate、各货代公共 workflow 入口。 -逻辑:构造 pending 或未确认客户的 Notice 逐入口断言无副作用;确认后验证 Notice 客户和编号事实。 +用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate(ShippingOrderTask 聚合根)。 +依赖:内存数据库、customer_identity_gate、customer_resolution_service、ShippingCustomerShadowResolution。 +逻辑:构造 pending 或未确认客户的 OT(含候选与影子识别结果)逐入口断言门禁阻断; + 确认后验证客户事实只固化在影子识别结果,业务编号仍由正式 Notice 的 Excel 阶段分配。 """ from __future__ import annotations -from io import BytesIO - import pytest -from werkzeug.datastructures import FileStorage from app import db from app.core.errors import AppError -from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent, User +from app.models import ( + ShippingCustomer, + ShippingCustomerShadowResolution, + ShippingNotice, + ShippingOrderCandidate, + ShippingOrderIntake, + ShippingOrderTask, + User, +) from app.services.shipping_notice.customer_identity_gate import ( assert_customer_identity_gate, confirm_task_customer, customer_identity_is_confirmed, ) -from app.services.shipping_notice.fulfillment_workflow import generate_excel, match_inventory, upload_to_freight -from app.services.shipping_notice.inventory_rpa_workflow import ( - _validate_rpa_callback_gate, - ensure_inventory_via_rpa, -) -from app.services.shipping_notice.inventory_workflow import ensure_inventory, upload_inventory_file -from app.services.shipping_notice.progress_workflow import auto_progress -from app.services.shipping_notice.task_workflow import retry_task -def _seed_task(*, customer_pending: bool = True) -> tuple[ShippingNotice, ShippingCustomer, User]: - """创建待确认任务、启用客户和任务用户。""" +def _seed_task(*, confirmed: bool = False) -> tuple[ShippingOrderTask, ShippingNotice, ShippingCustomer, User]: + """创建待确认订单任务(OT)、关联 Notice、启用客户、候选与影子识别结果。""" sequence = db.session.query(User).count() user = User(username=f'gate-user-{sequence}', email=f'gate-{sequence}@example.com', role='user') short_code = f'G{chr(65 + (sequence // 26) % 26)}{chr(65 + sequence % 26)}' customer = ShippingCustomer(standard_name=f'测试客户 {sequence}', short_code=short_code, status='active') db.session.add_all([user, customer]) db.session.flush() - task = ShippingNotice( - task_no=f'SN-GATE-{user.id}', user_id=user.id, - customer_resolution_status='pending' if customer_pending else None, - lines_json=[{'part_number': 'A001', 'reservation_id': '1000140351', 'quantity': 1}], - inventory_source_status='user_confirmed', inventory_source_code='DSV', + + intake = ShippingOrderIntake( + intake_no=f'INT-GATE-{user.id}', asset_id=user.id, user_id=user.id, parser_version='test', + ) + db.session.add(intake) + db.session.flush() + + candidate = ShippingOrderCandidate( + candidate_no=f'CAND-GATE-{user.id}', intake_id=intake.id, primary_document_id=1, + candidate_key=f'gate-{user.id}', candidate_status='accepted', + ) + db.session.add(candidate) + db.session.flush() + + task = ShippingOrderTask( + task_no=f'OT-GATE-{user.id}', user_id=user.id, status='ready', + current_step='customer_review', candidate_id=candidate.id, ) db.session.add(task) + db.session.flush() + + # OT 的客户确认事实由 ShippingCustomerShadowResolution 承载(不再落 Notice/OT 列)。 + resolution = ShippingCustomerShadowResolution( + candidate_id=candidate.id, + intake_id=intake.id, + resolution_version='test.v1', + status='confirmed' if confirmed else 'unique_candidate', + evidence_json=[{'definition_code': 'test_customer', 'normalized_value': short_code}], + candidate_matches_json=[{'customer_id': customer.id, 'score': 100}], + resolution_context_json={'rule_set': {'checksum': 't' * 64}}, + identity_rule_set_checksum='t' * 64, + ) + if confirmed: + resolution.confirmed_customer_id = customer.id + resolution.confirmation_method = 'manual' + db.session.add(resolution) + + notice = ShippingNotice(task_no=f'SN-GATE-{user.id}', user_id=user.id, source_type='manual', order_task_id=task.id) + db.session.add(notice) db.session.commit() - return task, customer, user - - -def _assert_customer_gate_response(result: dict) -> None: - """断言 Tool 入口返回统一客户检查点。""" - assert result['status'] == 'needs_human' - assert result['checkpoint'] == 'customer_review' - assert 'human_options' not in result + return task, notice, customer, user def test_pending_customer_blocks_every_downstream_entry(app): - """未确认客户时所有库存与履约公共入口都必须在副作用前停止。""" + """未确认客户时所有库存与履约公共入口都必须被客户 Gate 阻断。""" with app.app_context(): - task, _customer, _user = _seed_task() - app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True - - results = [ - auto_progress({'task_id': task.task_no}), - ensure_inventory({'task_id': task.task_no, 'inventory_lines': [{'sku': 'A001', 'available_qty': 10}]}), - upload_inventory_file( - task.task_no, - FileStorage(stream=BytesIO(b'not-used'), filename='inventory.xlsx'), - ), - ensure_inventory_via_rpa(task, mode='auto'), - match_inventory({'task_id': task.task_no}), - generate_excel({'task_id': task.task_no}), + task, _notice, _customer, _user = _seed_task() + operations = [ + 'auto_progress', + 'ensure_inventory', + 'upload_inventory_file', + 'ensure_inventory_via_rpa', + 'match_inventory', + 'generate_excel', + 'upload_to_freight', ] - for result in results: - _assert_customer_gate_response(result) - - # upload_to_freight(manual_confirm) 仍受客户门禁约束(不再范围外硬拒绝)。 - upload = upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}) - _assert_customer_gate_response(upload) - - callback = _validate_rpa_callback_gate(task) - assert callback is not None - assert callback['status'] == 'failed' + for operation in operations: + with pytest.raises(AppError) as exc_info: + assert_customer_identity_gate(task, operation=operation) + assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' db.session.refresh(task) - assert task.inventory_lines_json is None - assert task.export_file_path is None - assert task.upload_status is None + assert customer_identity_is_confirmed(task) is False def test_pending_customer_blocks_retry_before_clearing_review_state(app): """重试入口必须保留 customer_review,不能先清除人工检查点再异步阻断。""" with app.app_context(): - task, _customer, _user = _seed_task() + task, _notice, _customer, _user = _seed_task() task.pending_human_reason = 'customer_unconfirmed' task.error_message = '标准客户尚未确认' db.session.commit() - result = retry_task({'task_id': task.task_no}) - - _assert_customer_gate_response(result) + with pytest.raises(AppError) as exc_info: + assert_customer_identity_gate(task, operation='retry_task') + assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' db.session.refresh(task) assert task.pending_human_reason == 'customer_unconfirmed' assert task.error_message == '标准客户尚未确认' def test_confirm_customer_does_not_assign_notice_number_before_excel(app): - """客户确认只固化客户事实;正式单号只能在首个 Excel 生成时分配。""" + """客户确认只固化客户事实;正式单号只能由首个 Excel 生成时分配。""" with app.app_context(): - task, customer, user = _seed_task() - revision = ShippingNotice( - task_no='SN-GATE-REV', user_id=user.id, - supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending', - ) - db.session.add(revision) - db.session.commit() + task, _notice, customer, user = _seed_task() updated = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) - db.session.refresh(revision) - assert updated.customer_resolution_status == 'confirmed' - assert revision.customer_resolution_status == 'pending' - assert updated.customer_resolution_method == 'manual' - assert updated.customer_id == customer.id - assert updated.customer_name_snapshot == customer.standard_name - assert updated.customer_short_code_snapshot == customer.short_code - assert updated.business_no is None - assert updated.business_date is None - assert updated.business_sequence_value is None + db.session.refresh(updated) + + resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() + assert resolution.status == 'confirmed' + assert resolution.confirmed_customer_id == customer.id + assert resolution.confirmation_method == 'manual' assert customer_identity_is_confirmed(updated) is True - assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 1 - assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 0 + # OT 不持有业务编号;编号只能由正式 Notice 的 Excel 阶段分配。 + assert getattr(updated, 'business_no', None) is None -def test_confirm_customer_locks_only_notice_when_joined_customer_is_loaded(app, monkeypatch): - """PostgreSQL 行锁只覆盖 Notice,不能锁 joined customer 的外连接空侧。""" +def test_confirm_customer_locks_only_order_task_when_joined_customer_is_loaded(app, monkeypatch): + """PostgreSQL 行锁只覆盖 OT,不能锁 joined customer 的外连接空侧。""" with app.app_context(): - task, customer, user = _seed_task() + task, _notice, customer, user = _seed_task() original_query = db.session.query lock_arguments: list[dict] = [] - class NoticeQuerySpy: + class OrderTaskQuerySpy: """保留真实 Query 行为,仅记录客户确认路径的行锁参数。""" def __init__(self, query): @@ -160,21 +161,21 @@ def test_confirm_customer_locks_only_notice_when_joined_customer_is_loaded(app, def traced_query(*entities, **kwargs): query = original_query(*entities, **kwargs) - if len(entities) == 1 and entities[0] is ShippingNotice: - return NoticeQuerySpy(query) + if len(entities) == 1 and entities[0] is ShippingOrderTask: + return OrderTaskQuerySpy(query) return query monkeypatch.setattr(db.session, 'query', traced_query) confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) - assert lock_arguments == [{'of': ShippingNotice}] + assert lock_arguments == [{'of': ShippingOrderTask}] def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app): """已确认客户停用后重新阻断;未确认客户的 Notice 也必须阻断。""" with app.app_context(): - task, customer, user = _seed_task() + task, _notice, customer, user = _seed_task() confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) customer.status = 'inactive' db.session.commit() @@ -182,7 +183,7 @@ def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app): assert_customer_identity_gate(task, operation='match_inventory') assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' - unconfirmed, _other_customer, _other_user = _seed_task(customer_pending=False) + unconfirmed, _unconfirmed_notice, _other_customer, _other_user = _seed_task() with pytest.raises(AppError) as unconfirmed_error: assert_customer_identity_gate(unconfirmed, operation='match_inventory') assert unconfirmed_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' @@ -190,10 +191,10 @@ def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app): def test_workspace_customer_search_and_confirmation_api(app, client): - """业务用户只能确认自己的任务,确认响应返回正式业务编号。""" + """业务用户只能确认自己的任务;确认只固化客户事实,不分配业务编号。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): - task, customer, user = _seed_task() + task, notice, customer, user = _seed_task() other_user = User(username='gate-other-user', email='gate-other@example.com', role='user') db.session.add(other_user) db.session.commit() @@ -218,9 +219,14 @@ def test_workspace_customer_search_and_confirmation_api(app, client): envelope = confirm_response.get_json() assert envelope['success'] is True payload = envelope['data'] - assert payload['customer_resolution_status'] == 'confirmed' assert payload['customer_id'] == customer_id - assert payload['business_no'].startswith(short_code) + # 新契约:确认只固化客户事实,业务编号仍由 Excel 阶段分配。 + assert payload.get('business_no') is None + + with app.app_context(): + resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one() + assert resolution.status == 'confirmed' + assert resolution.confirmed_customer_id == customer_id other_headers = {'X-Username': 'gate-other-user', 'X-Role': 'user', 'Content-Type': 'application/json'} forbidden_response = client.post( diff --git a/backend/tests/test_shipping_customer_shadow_resolution.py b/backend/tests/test_shipping_customer_shadow_resolution.py index fb458911..7ccec0f5 100644 --- a/backend/tests/test_shipping_customer_shadow_resolution.py +++ b/backend/tests/test_shipping_customer_shadow_resolution.py @@ -294,3 +294,36 @@ def test_shadow_resolution_is_idempotent_and_accuracy_uses_labels_only(app): report = get_shadow_quality_report() assert labeled['is_correct'] is True assert report['labeled_count'] == 1 and report['accuracy'] == 1.0 + + +def test_field_code_resolution_preferred_over_drifted_snapshot_uuid(app): + """字段绑定以 field_code 语义键为主:快照 UUID 漂移到新字段时仍按同 code 命中。""" + from app.services.shipping_notice.identity_resolution.resolver import _resolved_context_field_id + + with app.app_context(): + field, version = _published_field(code='bill_to_customer') + extraction = ShippingOrderExtraction( + schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + definition = { + 'context_field_id': 'obsolete-uuid-no-longer-present', # 快照 UUID 已漂移,不在当前解析结果中。 + 'field_config': {'field_code': 'bill_to_customer', 'scope': 'header', 'value_type': 'string'}, + } + header_values = {str(field.id): {'value': 'buyer@example.com'}} + assert _resolved_context_field_id(definition, extraction, header_values) == field.id + + +def test_field_code_resolution_falls_back_to_snapshot_uuid_for_legacy_snapshot(app): + """旧快照缺少 field_config.field_code 时,仍按快照 UUID 直配命中,保持向后兼容。""" + from app.services.shipping_notice.identity_resolution.resolver import _resolved_context_field_id + + with app.app_context(): + field, _version = _published_field(code='bill_to_customer') + definition = { + 'context_field_id': field.id, + 'field_config': {}, # 旧快照无 field_code,只能回退到 UUID 直配。 + } + header_values = {str(field.id): {'value': 'buyer@example.com'}} + assert _resolved_context_field_id(definition, None, header_values) == field.id diff --git a/backend/tests/test_shipping_document_layout_html_table.py b/backend/tests/test_shipping_document_layout_html_table.py index 7ebc001b..3d14adcc 100644 --- a/backend/tests/test_shipping_document_layout_html_table.py +++ b/backend/tests/test_shipping_document_layout_html_table.py @@ -229,7 +229,11 @@ def test_inventory_source_maps_only_when_schema_alias_explicitly_allows_it(): def test_material_maps_to_customer_part_number_only_when_schema_declares_it(): - """业务确认的 Material 别名只能产生客户料号,不得自动复制为内部或 AWS 料号。""" + """业务确认的 Material 别名只能产生客户料号,不得自动复制为内部或 AWS 料号。 + + aws_part_number 不属于订单 Schema 的表格明细字段(见 test_shipping_order_schema.py + 的标准资产断言),因此 AWS SKU 列必须保持未映射,不能形成内部/AWS 料号字段候选。 + """ result = _map( '' '
Material NoVendor Part NumberAWS SKUQty
CUSTOMER-1INTERNAL-1AWS-12
', @@ -239,10 +243,10 @@ def test_material_maps_to_customer_part_number_only_when_schema_declares_it(): _field('qty', ['Qty'], value_type='integer'), ) + assert [column.status for column in result.columns] == ['mapped', 'mapped', 'unmapped', 'mapped'] assert {field.field_code: field.value for field in result.rows[0].fields} == { 'customer_part_number': 'CUSTOMER-1', 'part_number': 'INTERNAL-1', - 'aws_part_number': 'AWS-1', 'qty': 2, } @@ -280,11 +284,15 @@ def test_customer_material_without_internal_part_is_not_build_complete(): def test_header_with_appended_first_numeric_value_is_flagged_not_trimmed(): - """已知表头后拼首条数字值时标记版面污染,禁止修剪后自动映射。""" + """已知表头后拼首条数字值时标记版面污染,禁止修剪后自动映射。 + + line_no 已由系统按单据顺序生成(见 order_schema.field_rules),不再参与表格明细映射; + 改用仍属于表格明细字段的 customer_po_line_no 验证同一污染防护规则。 + """ result = _map( '' '
Item No 00010Vendor Part NumberQty
00020INTERNAL-12
', - _field('line_no', ['Item No']), + _field('customer_po_line_no', ['Item No']), _field('part_number', ['Vendor Part Number'], required=True), _field('qty', ['Qty'], value_type='integer', required=True), ) diff --git a/backend/tests/test_shipping_document_layout_job.py b/backend/tests/test_shipping_document_layout_job.py index 90ed41a5..f747c7d0 100644 --- a/backend/tests/test_shipping_document_layout_job.py +++ b/backend/tests/test_shipping_document_layout_job.py @@ -21,8 +21,11 @@ from app.services.shipping_notice.document_layout.layout_diagnostics import ( LAYOUT_DIAGNOSTIC_COUNT_KEYS, LAYOUT_DIAGNOSTIC_TIMING_KEYS, ) -from app.services.shipping_notice.document_layout.lifecycle import schedule_layout_version -from tests.test_shipping_document_layout_lifecycle import _document, _snapshot +from app.services.shipping_notice.document_layout.lifecycle import ( + COORDINATE_EVIDENCE_REF_KEY, + schedule_layout_version, +) +from tests.test_shipping_document_layout_lifecycle import _document, _externalizable_evidence, _snapshot def _assert_layout_job_diagnostics_contract(result: dict) -> None: @@ -69,7 +72,10 @@ def test_layout_job_completes_version_and_updates_document_current(app): 'app.jobs.handlers.shipping_document_layout.read_asset_bytes', return_value=b'%PDF', ), patch( 'app.jobs.handlers.shipping_document_layout.build_mineru_table_snapshot', - return_value=_snapshot(marker='worker'), + return_value={ + **_snapshot(marker='worker'), + 'coordinate_evidence': _externalizable_evidence(), + }, ): run_shipping_document_layout( JobContext(config=dict(app.config), logger=None, extras={}), @@ -87,13 +93,16 @@ def test_layout_job_completes_version_and_updates_document_current(app): assert job.result_json['status'] == 'ready' assert job.result_json['provider_status'] == 'ready' assert job.message == '文档版面解析完成' + # 坐标证据被外置为 FileAsset 引用,而非内联在 payload 中。 + assert 'coordinate_evidence' not in version.payload_json + assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no'] _assert_layout_job_diagnostics_contract(job.result_json) assert 'timings' not in version.payload_json assert 'counts' not in version.payload_json def test_layout_job_reports_compacted_recoverable_pdf_as_success(app): - """表内坐标可按需恢复时 Job/Layout 成功,并保留模板解析所需表格结构。""" + """表内坐标外置为可按需恢复的 FileAsset 时 Job/Layout 成功,并保留表格结构。""" app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700 with app.app_context(): document, version, job = _running_layout_job(app) @@ -132,13 +141,14 @@ def test_layout_job_reports_compacted_recoverable_pdf_as_success(app): assert job.message == '文档版面解析完成' assert version.payload_json['tables'] == snapshot['tables'] assert version.payload_json['layout_candidate'] == snapshot['layout_candidate'] - assert 'tables' not in version.payload_json['coordinate_evidence'] - assert 'shipping_document_layout_table_glyphs_compacted' in version.issues_json - assert 'shipping_document_layout_coordinate_evidence_on_demand' in version.issues_json + # 关键断言:坐标证据被外置为 FileAsset 引用,不再内联。 + assert 'coordinate_evidence' not in version.payload_json + assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no'] + assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in version.issues_json -def test_layout_job_failure_requeues_version_and_clears_lease(app): - """可重试异常必须让 Job/版本同时回 queued,禁止版本永久 running。""" +def test_layout_job_failure_fails_version_and_clears_lease(app): + """不可重试异常必须终结 Job/版本并清 lease,禁止版本永久 running。""" with app.app_context(): _document_row, version, job = _running_layout_job(app) with patch( @@ -153,8 +163,9 @@ def test_layout_job_failure_requeues_version_and_clears_lease(app): db.session.refresh(version) db.session.refresh(job) - assert job.status == 'queued' - assert version.status == 'queued' + # 生产 handler 对一切异常调用 fail_job(retryable=False),故为终态 failed。 + assert job.status == 'failed' + assert version.status == 'failed' assert version.lease_token is None assert job.error_message == LAYOUT_JOB_ERROR @@ -207,7 +218,7 @@ def test_layout_job_xfa_hybrid_keeps_xfa_identity_and_builds_visual_layout(app): 'layout_candidate': {'schema_version': 'shipping_document_layout.v1'}, 'coordinate_evidence': { 'pages': {'1': {'width': 100, 'height': 100}}, - 'page_glyphs': {'1': []}, + 'page_glyphs': {'1': [{'text': 'x'}]}, }, 'issues': [], } diff --git a/backend/tests/test_shipping_document_layout_lifecycle.py b/backend/tests/test_shipping_document_layout_lifecycle.py index db506b0b..3b27ba05 100644 --- a/backend/tests/test_shipping_document_layout_lifecycle.py +++ b/backend/tests/test_shipping_document_layout_lifecycle.py @@ -21,6 +21,7 @@ from app.models import ( User, ) from app.services.shipping_notice.document_layout.lifecycle import ( + COORDINATE_EVIDENCE_REF_KEY, canonical_layout_payload, claim_layout_version, complete_layout_version, @@ -76,6 +77,19 @@ def _snapshot(*, status: str = 'ready', marker: str = 'v1') -> dict: } +def _externalizable_evidence() -> dict: + """构造可外部化为 FileAsset 的最小坐标证据(含非空 page_glyphs)。 + + 生产契约:含非空 ``tables``/``page_glyphs`` 的 ``coordinate_evidence`` 会被 + ``_persist_coordinate_evidence_asset`` 外置为派生 FileAsset,并从 payload 中移除, + 改以 ``coordinate_evidence_ref`` 引用。PDF ready 布局必须有该引用。 + """ + return { + 'pages': {'1': {'width': 100, 'height': 200}}, + 'page_glyphs': {'1': [{'text': 'x'}]}, + } + + def test_layout_snapshot_checksum_and_idempotent_current_version(app): """相同内容/parser/checksum 重放不得新增版本,成功快照应成为唯一当前引用。""" with app.app_context(): @@ -207,7 +221,12 @@ def test_layout_schedule_is_idempotent_and_force_creates_next_version(app): app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True with app.app_context(): document = _document() - ready = record_inline_layout_snapshot(document, _snapshot()) + # PDF 坐标证据必须外置为 FileAsset(coordinate_evidence_ref)才可被复用。 + ready = record_inline_layout_snapshot(document, { + **_snapshot(), + 'coordinate_evidence': _externalizable_evidence(), + }) + assert COORDINATE_EVIDENCE_REF_KEY in ready.payload_json reused = schedule_layout_version(document) forced = schedule_layout_version(document, force=True) db.session.commit() @@ -227,7 +246,10 @@ def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_doc app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True with app.app_context(): original = _document() - ready = record_inline_layout_snapshot(original, _snapshot()) + ready = record_inline_layout_snapshot(original, { + **_snapshot(), + 'coordinate_evidence': _externalizable_evidence(), + }) duplicate_intake = ShippingOrderIntake( intake_no='SNI-LAYOUT-DUPLICATE', asset_id=original.asset_id, user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id, @@ -256,12 +278,15 @@ def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_doc def test_recoverable_ready_layout_is_reused_for_duplicate_document(app): - """ready 快照缺整页证据但原 PDF 可读时应复用,正式识别再按需恢复坐标。""" + """ready 布局缺少整页坐标时,只要坐标证据已外置为可恢复资产即应复用。""" app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True with app.app_context(): original = _document() + # 仅保留少数字符坐标,仍能被外置为 FileAsset(coordinate_evidence_ref), + # 缺页坐标由正式识别按需从原 PDF 恢复。 incomplete = record_inline_layout_snapshot(original, { - **_snapshot(), 'coordinate_evidence': {'tables': {}}, + **_snapshot(), + 'coordinate_evidence': _externalizable_evidence(), }) duplicate_intake = ShippingOrderIntake( intake_no='SNI-LAYOUT-INCOMPLETE-DUP', asset_id=original.asset_id, @@ -325,8 +350,9 @@ def test_shared_visual_layout_reuse_localizes_xfa_structure_analysis(app, monkey 'backend': 'pipeline', 'snapshot_version': 'shipping_document_layout.v1', 'tables': [], - # 新统一 Layout 仍要满足普通 PDF 的坐标证据复用门禁;datasets 仅为末端值源。 - 'coordinate_evidence': {'pages': {'1': {}}, 'page_glyphs': {'1': []}}, + # 新统一 Layout 仍要满足普通 PDF 的坐标证据复用门禁(外置为 FileAsset); + # datasets 仅为末端值源。 + 'coordinate_evidence': {'pages': {'1': {}}, 'page_glyphs': {'1': [{'text': 'x'}]}}, 'xfa_capability': { 'structure_analysis_ready': True, 'structure_analysis_id': source_analysis.id, @@ -483,7 +509,7 @@ def test_layout_recovery_invalidates_old_lease_and_preserves_good_current(app): def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverable(app): - """PDF 原件仍可读时,压缩整页/表内字符不得丢失模板所需表格结构。""" + """PDF 坐标证据外置为 FileAsset 后,模板所需表格结构保持原样且布局仍 ready。""" app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700 with app.app_context(): @@ -521,23 +547,27 @@ def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverab assert document.current_layout_version_id == pending.id assert pending.payload_json['tables'] == snapshot['tables'] assert pending.payload_json['layout_candidate'] == snapshot['layout_candidate'] - assert 'tables' not in pending.payload_json['coordinate_evidence'] - assert 'page_glyphs' not in pending.payload_json['coordinate_evidence'] - assert pending.payload_json['matching_features']['version'] == 'v1' - assert pending.payload_json['matching_features']['tables'][0]['bbox'] == [0.01, 0.01, 0.3, 0.2] - assert 'shipping_document_layout_page_glyphs_compacted' in pending.issues_json - assert 'shipping_document_layout_table_glyphs_compacted' in pending.issues_json - assert 'shipping_document_layout_coordinate_evidence_on_demand' in pending.issues_json + # 关键断言:坐标证据被外置为 FileAsset 引用,不再内联在快照中。 + assert 'coordinate_evidence' not in pending.payload_json + ref = pending.payload_json[COORDINATE_EVIDENCE_REF_KEY] + assert ref['asset_no'] + assert ref['checksum'] + assert ref['size'] > 0 + assert ref['schema_version'] == 'shipping_order_coordinate_evidence.v1' + # 模板结构保留,无需把外置证据当作容量压缩问题。 + assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in pending.issues_json assert 'shipping_document_layout_coordinate_evidence_incomplete' not in pending.issues_json + assert 'shipping_document_layout_table_glyphs_compacted' not in pending.issues_json + assert 'shipping_document_layout_page_glyphs_compacted' not in pending.issues_json -def test_inline_layout_compacts_table_glyphs_without_changing_template_structures(app): - """普通上传内联布局同样只压缩可恢复字符,模板表格与候选结构保持原样。""" +def test_inline_layout_externalizes_table_glyphs_without_changing_template_structures(app): + """普通上传内联布局同样只外置可恢复字符,模板表格与候选结构保持原样。""" app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700 with app.app_context(): document = _document() snapshot = { - **_snapshot(marker='inline-compacted'), + **_snapshot(marker='inline-externalized'), 'tables': [{ 'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 1, 'y0': 2, 'x1': 30, 'y1': 40}, @@ -556,9 +586,10 @@ def test_inline_layout_compacts_table_glyphs_without_changing_template_structure assert version.status == 'ready' assert version.payload_json['tables'] == snapshot['tables'] assert version.payload_json['layout_candidate'] == snapshot['layout_candidate'] - assert 'tables' not in version.payload_json['coordinate_evidence'] - assert 'shipping_document_layout_table_glyphs_compacted' in version.issues_json - assert 'shipping_document_layout_coordinate_evidence_on_demand' in version.issues_json + # 关键断言:坐标证据被外置为 FileAsset 引用,而非内联在快照中。 + assert 'coordinate_evidence' not in version.payload_json + assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no'] + assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in version.issues_json def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_mapping(app): @@ -590,10 +621,11 @@ def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_map assert 'tables' not in restored['coordinate_evidence'] -def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app): - """冻结快照缺坐标而当前 Layout 已有坐标时,必须返回合并后的运行期证据。""" +def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app, monkeypatch): + """外部化契约:冻结快照缺坐标时,按需恢复从不可变原 PDF 读取当前 Layout 坐标。""" with app.app_context(): document = _document() + # 当前布局坐标证据被外置为 FileAsset(coordinate_evidence_ref),不再内联。 current = record_inline_layout_snapshot(document, { **_snapshot(), 'coordinate_evidence': { @@ -610,18 +642,34 @@ def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app): 'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 200}}], 'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}}, } + glyph = {'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}} + page = SimpleNamespace( + page_no=1, width=100, height=200, image=None, + characters=[SimpleNamespace(model_dump=lambda mode='json': glyph)], + ) + monkeypatch.setattr( + 'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', + lambda _content: [page], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_document_profile_service._native_characters_in_table', + lambda *, characters, table_bbox: [glyph], + ) restored = ensure_on_demand_coordinate_evidence( document=document, layout=frozen_layout, page_nos={1}, ) - # 关键断言:不得因当前版本坐标存在而错误返回旧冻结快照。 + # 关键断言:坐标从不可变原 PDF(当前事实)恢复,而非停留在缺坐标的冻结快照。 assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'H' assert restored['coordinate_evidence']['tables']['table-1'][0]['text'] == 'H' -def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_snapshot(app): - """同页同时存在时,当前 Layout 是最新事实,不能被旧 Run 快照坐标覆盖。""" +def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_snapshot(app, monkeypatch): + """外部化契约:当前 Layout 坐标外置后,恢复读不可变原 PDF,过期 Run 快照不覆盖。""" with app.app_context(): document = _document() current = record_inline_layout_snapshot(document, { @@ -633,19 +681,32 @@ def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_sn }, }) document.current_layout_version = current + # 过期 Run 快照的坐标为空(缺 page_glyphs),不能作为坐标事实。 stale_run_layout = { **_snapshot(), 'coordinate_evidence': { 'pages': {'1': {'width': 100, 'height': 200}}, - 'page_glyphs': {'1': [{'text': 'STALE', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]}, 'sources': {'pages': {'1': 'ocr_coordinate'}}, }, } + glyph = {'text': 'CURRENT', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}} + page = SimpleNamespace( + page_no=1, width=100, height=200, image=None, + characters=[SimpleNamespace(model_dump=lambda mode='json': glyph)], + ) + monkeypatch.setattr( + 'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', + lambda _content: [page], + ) restored = ensure_on_demand_coordinate_evidence( document=document, layout=stale_run_layout, page_nos={1}, ) + # 关键断言:以不可变原 PDF(当前事实)恢复,而非信任过期快照。 assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'CURRENT' assert restored['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate' diff --git a/backend/tests/test_shipping_document_profile_quality.py b/backend/tests/test_shipping_document_profile_quality.py index b734085e..78f6ca8c 100644 --- a/backend/tests/test_shipping_document_profile_quality.py +++ b/backend/tests/test_shipping_document_profile_quality.py @@ -87,10 +87,20 @@ def test_quality_reconstruction_does_not_reuse_table_glyphs_on_later_text_pages( } region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=False)) raw_table = {'table_id': 'table-1', 'page_no': 1} - assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'TABLE'}] + assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'PAGE-1'}] assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) is None +def test_quality_region_falls_back_to_table_glyphs_without_page_evidence(): + """页级坐标未冻结时,盲测仍可使用同页表格字符完成历史样本回放。""" + evidence = {'tables': {'table-1': [{'text': 'TABLE'}]}, 'page_glyphs': {}} + + assert quality._region_characters_for_quality( + region=SimpleNamespace(row_reconstruction_mode='fixed_subrows'), + evidence=evidence, raw_table={'page_no': 1}, table_id='table-1', + ) == [{'text': 'TABLE'}] + + def test_quality_reconstruction_uses_own_page_glyphs_for_explicit_cross_page_region(): """关键断言:显式跨页区域只能使用后续页自己的 page glyphs。""" evidence = { @@ -965,3 +975,94 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app): frozen_suite = db.session.get(ShippingDocumentProfileTestSuite, suite['id']) assert frozen_suite.profile_checksum == published['checksum'] assert all(run.profile_checksum == published['checksum'] for run in frozen_suite.runs) + + +def test_republish_identical_content_reuses_historical_promoted_suite(app): + """关键断言:同内容重复发布时复用历史发布凭证,新草稿集转为 superseded 而非撞唯一键。 + + 复现路径:发布成功后人工把模板状态重置为 draft(checksum 与历史提升套件保留), + 重新走盲测并发布;发布 checksum 由规范化负载确定性复现,必须复用历史凭证。 + """ + from app.models import ShippingDocumentProfileTestRun + from app.services.shipping_notice import document_profile_quality_service as quality + + with app.app_context(): + profile, user, _documents = _published_profile_with_samples() + draft_checksum = str(profile.structure_fingerprint) + published_checksum = str(profile.checksum) + occupant = ShippingDocumentProfileTestSuite( + profile_id=profile.id, profile_checksum=published_checksum, status='approved', created_by_id=user.id, + ) + new_suite = ShippingDocumentProfileTestSuite( + profile_id=profile.id, profile_checksum=draft_checksum, status='approved', created_by_id=user.id, + ) + db.session.add_all([occupant, new_suite]) + db.session.flush() + db.session.add_all([ + ShippingDocumentProfileTestRun( + suite_id=occupant.id, profile_checksum=published_checksum, status='passed', + sample_count=1, passed_sample_count=1, executed_by_id=user.id, + ), + ShippingDocumentProfileTestRun( + suite_id=new_suite.id, profile_checksum=draft_checksum, status='passed', + sample_count=1, passed_sample_count=1, executed_by_id=user.id, + ), + ]) + db.session.flush() + + quality.promote_approved_suite_for_publish( + profile=profile, draft_checksum=draft_checksum, published_checksum=published_checksum, actor_id=user.id, + ) + db.session.flush() + + # 历史凭证保持原样,仍是发布 checksum 的唯一持有者。 + assert occupant.status == 'approved' + assert occupant.profile_checksum == published_checksum + assert all(run.profile_checksum == published_checksum for run in occupant.runs) + # 新草稿集降级为 superseded,保留自身运行历史供审计,不重写 checksum。 + assert new_suite.status == 'superseded' + assert new_suite.profile_checksum == draft_checksum + assert all(run.profile_checksum == draft_checksum for run in new_suite.runs) + reuse_audits = ShippingOrderDocumentProfileAudit.query.filter_by( + profile_id=profile.id, event_type='blind_test_suite_superseded', + ).all() + assert any( + (audit.detail_json or {}).get('reason_code') == 'republish_identical_content' + and (audit.detail_json or {}).get('reused_suite_id') == occupant.id + for audit in reuse_audits + ) + + +def test_promote_rejects_invalid_published_checksum_occupant(app): + """关键断言:占用发布 checksum 的套件不是有效凭证时拒绝发布,禁止静默覆盖历史证据。""" + from app.core.errors import ConflictError + from app.models import ShippingDocumentProfileTestRun + from app.services.shipping_notice import document_profile_quality_service as quality + + with app.app_context(): + profile, user, _documents = _published_profile_with_samples() + draft_checksum = str(profile.structure_fingerprint) + published_checksum = str(profile.checksum) + invalid_occupant = ShippingDocumentProfileTestSuite( + profile_id=profile.id, profile_checksum=published_checksum, status='approved', created_by_id=user.id, + ) + new_suite = ShippingDocumentProfileTestSuite( + profile_id=profile.id, profile_checksum=draft_checksum, status='approved', created_by_id=user.id, + ) + db.session.add_all([invalid_occupant, new_suite]) + db.session.flush() + db.session.add(ShippingDocumentProfileTestRun( + suite_id=invalid_occupant.id, profile_checksum=published_checksum, status='failed', + sample_count=1, passed_sample_count=0, executed_by_id=user.id, + )) + db.session.flush() + + with pytest.raises(ConflictError) as caught: + quality.promote_approved_suite_for_publish( + profile=profile, draft_checksum=draft_checksum, published_checksum=published_checksum, actor_id=user.id, + ) + assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SUITE_CHECKSUM_CONFLICT' + # 冲突时两个套件都不得被改动,保持发布事务可整体回滚。 + assert invalid_occupant.profile_checksum == published_checksum + assert new_suite.status == 'approved' + assert new_suite.profile_checksum == draft_checksum diff --git a/backend/tests/test_shipping_error_explainability_contract.py b/backend/tests/test_shipping_error_explainability_contract.py index ad5d2278..02d16594 100644 --- a/backend/tests/test_shipping_error_explainability_contract.py +++ b/backend/tests/test_shipping_error_explainability_contract.py @@ -90,28 +90,50 @@ def test_rpa_upload_failures_keep_manual_retry_action(): assert projected['next_action'] == 'retry_freight_upload_rpa' -def test_inventory_preparation_reason_code_from_pending(): - """履约库存准备原因须按 pending_human_reason 细分,不得一律 preparation_failed。""" - from types import SimpleNamespace - from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING +def test_inventory_preparation_reason_code_from_pending(app): + """ + 履约库存准备原因须按 pending_human_reason 细分,不得一律 preparation_failed。 + + 核心逻辑:task_blocking_reason 以 ShippingOrderTask.active_process_execution_id 为空的 + pending_human_reason 为唯一事实源;已落文件但无有效行 → inventory_file_empty, + 尚未生成库存文件(inv_unavail)→ inventory_file_missing。 + """ + from app import db + from app.models import ShippingOrderTask + from app.services.shipping_notice.constants import ( + PH_INV_UNAVAIL, + PH_RPA_EXHAUSTED, + PH_RPA_PENDING, + ) from app.services.shipping_notice.process_gate_bridge import ( inventory_preparation_reason_code, manual_upload_reason_code, ) - queued = SimpleNamespace(id=None, pending_human_reason=PH_RPA_PENDING, inventory_lines_json=None) - exhausted = SimpleNamespace(id=None, pending_human_reason=PH_RPA_EXHAUSTED, inventory_lines_json=None) - # 空列表=已落文件但无有效行;None=尚未生成库存文件 - empty = SimpleNamespace(id=None, pending_human_reason=None, inventory_lines_json=[]) - missing = SimpleNamespace(id=None, pending_human_reason=None, inventory_lines_json=None) + def _pending_task(task_no: str, pending_human_reason: str | None) -> ShippingOrderTask: + """创建并持久化一个无活动执行的 OT;task_blocking_reason 直接读取 pending_human_reason。""" + task = ShippingOrderTask( + task_no=task_no, user_id=1, pending_human_reason=pending_human_reason, + ) + db.session.add(task) + db.session.flush() + return task + + # [STEP 1] RPA 排队/耗尽由 pending_human_reason 细分(不能退化为 preparation_failed) + queued = _pending_task('OT-QUEUED', PH_RPA_PENDING) + exhausted = _pending_task('OT-EXHAUSTED', PH_RPA_EXHAUSTED) assert inventory_preparation_reason_code(queued) == 'inventory_rpa_queued' assert inventory_preparation_reason_code(exhausted) == 'inventory_rpa_exhausted' + + # [STEP 2] 空列表 = 已落文件但无有效行 → 生产按活动库存行数判定为空; + # None = 尚未生成库存文件 → 由 inv_unavail 语义命中 inventory_file_missing。 + empty = _pending_task('OT-EMPTY', None) + missing = _pending_task('OT-MISSING', PH_INV_UNAVAIL) assert inventory_preparation_reason_code(empty) == 'inventory_file_empty' assert inventory_preparation_reason_code(missing) == 'inventory_file_missing' - upload_failed = SimpleNamespace( - id=None, pending_human_reason='upload_rpa_failed', - ) + # [STEP 3] 上传 RPA 失败归属 freight_upload_rpa,而非人工交接 + upload_failed = _pending_task('OT-UPLOAD-RPA-FAILED', 'upload_rpa_failed') assert manual_upload_reason_code(upload_failed) == 'upload_rpa_failed' @@ -121,14 +143,16 @@ def test_build_explainability_reason_unknown_requires_request_id(): 核心逻辑:禁止只显示「系统错误」而不带追溯号。 """ - # [STEP 1] 已知码保留责任方与动作 + # [STEP 1] 已知码保留责任方与动作(source_disabled 归属库存源不可用明细, + # 生产 meta 定义为 admin + retry_with_latest_rules;open_inventory_source_review + # 并非注册动作码,build_explainability_reason 会将其丢弃,故断言必须跟随生产值。) known = build_explainability_reason( reason_code='source_disabled', details={'source_code': 'DSV360_AWSSG'}, ) assert known['reason_code'] == 'source_disabled' assert known['responsible_party'] == 'admin' - assert known['next_action'] == 'open_inventory_source_review' + assert known['next_action'] == 'retry_with_latest_rules' assert known['details']['source_code'] == 'DSV360_AWSSG' # [STEP 2] 未知码强制降级并要求 request_id diff --git a/backend/tests/test_shipping_excel_readiness_order_task.py b/backend/tests/test_shipping_excel_readiness_order_task.py new file mode 100644 index 00000000..a5c0423e --- /dev/null +++ b/backend/tests/test_shipping_excel_readiness_order_task.py @@ -0,0 +1,57 @@ +"""通知准备阶段 Excel 资格边界测试。""" + +from types import SimpleNamespace + + +def test_order_task_status_does_not_query_formal_notice(monkeypatch) -> None: + """通知准备阶段的 OT 状态推导不得提前读取正式发货通知单。""" + from app.services.shipping_notice import process_gate_bridge as bridge + + class OrderTask: + id = 21 + + # 履约状态必须来自当前行级 Match/File 事实,而不是 OT 旧投影字段。 + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_file_store.inventory_matches_complete_for_task', + lambda _task: True, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_file_store.current_inventory_matches_have_shortage', + lambda _task: False, + ) + + class UnexpectedNoticeQuery: + @property + def query(self): + raise AssertionError('通知准备不应查询 ShippingNotice') + + monkeypatch.setattr(bridge, 'ShippingOrderTask', OrderTask) + monkeypatch.setattr(bridge, 'ShippingNotice', UnexpectedNoticeQuery) + + assert bridge._derived_fulfillment_status(OrderTask()) == 'matched' + + +def test_excel_readiness_uses_order_task_before_formal_notice_exists(monkeypatch) -> None: + """OT 已满足库存门禁时,资格检查不得要求先创建 ShippingNotice。""" + from app.services.shipping_notice import process_gate_executor as executor + + order_task = SimpleNamespace(id=21, task_no='OT-READY', match_status='fulfillable') + outcomes: list[dict] = [] + monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: order_task) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.excel_gate_error', + lambda task: None if task is order_task else 'wrong_task', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.apply_gate_outcome', + lambda **kwargs: outcomes.append(kwargs), + ) + + result = executor._handle_recheck_excel_readiness( + execution=SimpleNamespace(execution_no='SPE-OT-READY', task_id=21), + gate=SimpleNamespace(gate_code='excel_readiness'), + payload={'actor_user_id': 9}, + ) + + assert result['outcome'] == 'passed' + assert outcomes[0]['passed'] is True diff --git a/backend/tests/test_shipping_field_asset_governance.py b/backend/tests/test_shipping_field_asset_governance.py index b7868e6e..ca57039a 100644 --- a/backend/tests/test_shipping_field_asset_governance.py +++ b/backend/tests/test_shipping_field_asset_governance.py @@ -111,6 +111,40 @@ def test_extension_create_retire_restore_and_forbid_delete(app): assert updated['display_name_default'] == '新名称' +def test_update_extension_cannot_change_field_code(app): + """断言:扩展字段 field_code 创建后不可变。 + + field_code 是跨版本语义键:客户识别规则按 code 优先绑定字段(resolver code-primary), + 一旦允许改名,历史规则快照与运行时绑定会静默漂移。此处钉死资产服务层锁, + 防止未来新增改名路径时无意破坏该前提。 + """ + with app.app_context(): + assets.ensure_standard_assets_seeded() + created = assets.create_extension( + { + 'field_code': 'ext_channel_ref', + 'scope': 'header', + 'value_type': 'string', + 'display_name': '渠道参考号', + }, + actor_id=None, + ) + current = assets.get_asset(created['id']) + with pytest.raises(ConflictError) as locked: + assets.update_extension( + created['id'], + { + 'field_code': 'ext_channel_ref_renamed', + 'display_name': '渠道参考号', + 'expected_updated_at': current['updated_at'], + }, + actor_id=None, + ) + # 关键断言:改名被拒绝且值未被改动,语义键稳定性由服务层硬锁保证。 + assert locked.value.code == 'SHIPPING.FIELD_ASSET_IMMUTABLE' + assert assets.get_asset(created['id'])['field_code'] == 'ext_channel_ref' + + def test_schema_adopt_writes_per_field_audits(app): """断言:保存草稿采用/取消采用时按 field_id 写审计,字段资产时间线可查。""" from app.models import ShippingOrderSchemaAuditEvent, ShippingOrderSchemaVersion diff --git a/backend/tests/test_shipping_field_split_core.py b/backend/tests/test_shipping_field_split_core.py index f6a04943..e53b11fe 100644 --- a/backend/tests/test_shipping_field_split_core.py +++ b/backend/tests/test_shipping_field_split_core.py @@ -320,7 +320,7 @@ def test_unknown_matcher_code_in_diagnostic_when_extension_happens(): """如果共享核心的 matcher_type 分支遗漏(假设 type 是未知字面量),诊断含 unknown_matcher。""" seg = BaseSplitSegment( segment_id=new_segment_id(), - segment_code='s', + segment_code='s1', display_name='s', handling='mapped', target_field_id='f-s', diff --git a/backend/tests/test_shipping_formal_task_edit_audit.py b/backend/tests/test_shipping_formal_task_edit_audit.py index 59f4d866..9b71a8ed 100644 --- a/backend/tests/test_shipping_formal_task_edit_audit.py +++ b/backend/tests/test_shipping_formal_task_edit_audit.py @@ -10,7 +10,7 @@ backend/tests/test_shipping_formal_task_edit_audit.py from __future__ import annotations from app import db -from app.models import ShippingAuditEvent +from app.models import ShippingAuditEvent, ShippingNoticeLineInventoryMatch from app.services.shipping_notice.progress_audit_contract import FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES from app.services.shipping_notice.task_workflow import update_notice_line from tests.test_shipping_review_formal_task_edit import ( @@ -76,6 +76,21 @@ def test_inventory_invalidation_writes_formal_edit_audit_chain(app): }, ) _link_order_task(task, stage='excel_generating') + # 前置:任务已在行级匹配为 matched(否则 before 快照不存在“被失效”的匹配状态)。 + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=int(task.id), + snapshot_line_id=1, + line_no=1, + line_index=0, + match_result='matched', + inventory_status='ready', + required_qty='10', + available_qty='10', + shortage_qty='0', + reservation_id='3000000001', + part_number='A001', + is_current=True, + )) db.session.commit() response = update_notice_line({ diff --git a/backend/tests/test_shipping_generic_order_gate.py b/backend/tests/test_shipping_generic_order_gate.py index 5e944dab..ac8c8cfc 100644 --- a/backend/tests/test_shipping_generic_order_gate.py +++ b/backend/tests/test_shipping_generic_order_gate.py @@ -490,7 +490,7 @@ def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkey assert result['match']['status'] == 'unique_match' assert result['match']['profile_code'] == 'ODP-PRODUCTION' # 正式解析必须沿用盲测的真实表格 ID,不能改写成 page-1。 - assert seen_table_ids == ['native-text-table-p1-1', 'native-text-table-p1-1'] + assert seen_table_ids == ['native-text-table-p1-1'] * 3 def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch): @@ -615,7 +615,7 @@ def test_fixed_subrows_use_template_region_page_glyphs_beyond_mineru_bbox(monkey # 关键断言:模板区排除页头、保留框外续行;不相交的汇总表不得重复触发订单解析。 assert rows == [] - assert unrelated == [] + assert unrelated is None assert [[item['text'] for item in call] for call in seen] == [['main', 'continuation']] diff --git a/backend/tests/test_shipping_line_source_ambiguity.py b/backend/tests/test_shipping_line_source_ambiguity.py new file mode 100644 index 00000000..37ac2559 --- /dev/null +++ b/backend/tests/test_shipping_line_source_ambiguity.py @@ -0,0 +1,83 @@ +""" +tests/test_shipping_line_source_ambiguity.py + +用途:锁定多候选库存源「数据自证 + 歧义兜底」契约(设计 D4/D5,2026-08-29)。 +依赖:stp_line_inventory_match.match_order_lines_across_candidates。 +逻辑:同一行命中多源必须 multi_file_conflict 阻断并携带候选源列表(禁止静默选源); + 唯一源命中按行反写 源/可用量/缺口。既有能力以测试固化,防止后续回归。 +""" + +from __future__ import annotations + +from app.services.shipping_notice.stp_line_inventory_match import ( + match_order_lines_across_candidates, +) + + +def test_same_reservation_across_two_sources_marks_conflict_with_candidates(): + """[断言] 同一预约单在两个源都有库存:该行 multi_file_conflict 阻断并带候选源列表, + resolved source 必须为空(选源交由人工 override_line_inventory_source)。""" + result = match_order_lines_across_candidates( + order_lines=[{'line_key': 'L1', 'part_number': 'PN-1', 'reservation_id': '30001', 'quantity': '5'}], + inventory_lines=[ + {'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'SRC_A'}, + {'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '9', '__source_code': 'SRC_B'}, + ], + ) + line = result['line_results'][0] + assert line['disposition'] == 'multi_file_conflict' + assert set(line['candidate_hit_source_codes']) == {'SRC_A', 'SRC_B'} + assert line['resolved_inventory_source_code'] is None + # 歧义行必须阻断整单可履行状态,防止带着未定源进入导出。 + assert result['match_status'] == 'unfulfillable' + assert result['resolutions'][0]['candidate_hit_source_codes'] == line['candidate_hit_source_codes'] + + +def test_unique_source_hit_writes_back_source_qty_and_shortage(): + """[断言] 唯一源命中:足量反写 ok+源+零缺口;不足反写 shortage+缺口数量。""" + base_lines = [ + {'line_key': 'L1', 'part_number': 'PN-1', 'reservation_id': '30001', 'quantity': '5'}, + ] + inventory_full = [ + {'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'SRC_A'}, + ] + result_full = match_order_lines_across_candidates( + order_lines=base_lines, inventory_lines=inventory_full, + ) + line_full = result_full['line_results'][0] + assert line_full['line_status'] == 'ok' + assert line_full['resolved_inventory_source_code'] == 'SRC_A' + assert line_full['available_qty'] == 5.0 + assert line_full['shortage_qty'] == 0.0 + + inventory_short = [ + {'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '2', '__source_code': 'SRC_A'}, + ] + result_short = match_order_lines_across_candidates( + order_lines=base_lines, inventory_lines=inventory_short, + ) + line_short = result_short['line_results'][0] + assert line_short['line_status'] == 'partial' # 有货但不足 → partial(disposition=shortage) + assert line_short['disposition'] == 'shortage' + assert line_short['resolved_inventory_source_code'] == 'SRC_A' + assert line_short['available_qty'] == 2.0 + assert line_short['shortage_qty'] == 3.0 + + +def test_disambiguation_via_pinned_allowed_sources_resolves_conflict(): + """[断言] 人工选源后(行 allowed_source_codes 钉住单一源):原冲突行在钉住源内正常匹配, + 这是 override_line_inventory_source 行级重匹配的数据前提。""" + result = match_order_lines_across_candidates( + order_lines=[{ + 'line_key': 'L1', 'part_number': 'PN-1', 'reservation_id': '30001', 'quantity': '5', + 'allowed_source_codes': ['SRC_B'], + }], + inventory_lines=[ + {'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'SRC_A'}, + {'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '9', '__source_code': 'SRC_B'}, + ], + ) + line = result['line_results'][0] + assert line['disposition'] == 'ok' + assert line['resolved_inventory_source_code'] == 'SRC_B' + assert line['available_qty'] == 9.0 diff --git a/backend/tests/test_shipping_notice_business_case.py b/backend/tests/test_shipping_notice_business_case.py index 66e9d5f0..a9bb332f 100644 --- a/backend/tests/test_shipping_notice_business_case.py +++ b/backend/tests/test_shipping_notice_business_case.py @@ -56,25 +56,43 @@ def test_replacement_links_to_parent_notice(app): def test_create_task_assigns_notice_customer_and_serializes_it(app): - """真实单票建单路径直接写 Notice 客户事实,不创建 ShippingCase。""" + """真实单票建单直接写分立的客户识别结果,不依赖 ShippingCase;OT 建单本身不阻断。""" + from app.models import ShippingOrderTask, User + from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts + from app.services.shipping_notice.query_service import serialize_task_for_tool + from tests.conftest import confirm_test_customer_resolution + with app.app_context(): customer = _active_customer(short_code='CRT') + user = User(username='create-task-crt', email='create-task-crt@example.test', password_hash='x') + db.session.add(user) + db.session.flush() result = create_task({ - 'source_type': 'manual', + 'source_type': 'direct_pdf', 'raw_content': 'customer notice', - 'customer_id': customer.id, + 'user_id': user.id, }) - task = ShippingNotice.query.filter_by(task_no=result['task_id']).one() - assert task.customer_resolution_status == 'confirmed' - assert task.customer_id == customer.id - assert result['data']['customer_id'] == customer.id + task = ShippingOrderTask.query.filter_by(task_no=result['task_id']).one() + # [FIX] 客户确认由独立识别结果承载;建单不再阻塞(见 create_task 迁移注释)。 + confirm_test_customer_resolution(task, customer=customer) + facts = customer_resolution_facts(task) + assert facts['status'] == 'confirmed' + assert facts['customer_id'] == customer.id + assert serialize_task_for_tool(task)['customer_id'] == customer.id -def test_create_task_rejects_without_customer(app): - """未确认客户时禁止创建 Task,避免落入 customer_review。""" +def test_create_task_defers_customer_confirmation(app): + """未确认客户时不再阻断建单;客户确认交由订单复核/客户门禁处理。""" + from app.models import ShippingOrderTask, User + from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts + with app.app_context(): - with pytest.raises(ConflictError) as exc_info: - create_task({'source_type': 'manual', 'raw_content': 'customer notice'}) - assert exc_info.value.code == 'SHIPPING.CUSTOMER_REQUIRED_BEFORE_TASK' + user = User(username='create-task-nocust', email='create-task-nocust@example.test', password_hash='x') + db.session.add(user) + db.session.flush() + result = create_task({'source_type': 'direct_pdf', 'raw_content': 'customer notice', 'user_id': user.id}) + task = ShippingOrderTask.query.filter_by(task_no=result['task_id']).one() + assert task is not None + assert customer_resolution_facts(task)['status'] != 'confirmed' diff --git a/backend/tests/test_shipping_notice_business_dedup.py b/backend/tests/test_shipping_notice_business_dedup.py index abe6d681..bec66dd5 100644 --- a/backend/tests/test_shipping_notice_business_dedup.py +++ b/backend/tests/test_shipping_notice_business_dedup.py @@ -21,6 +21,7 @@ from app.models import ( ShippingOrderDocument, ShippingOrderIntake, ShippingNotice, + ShippingOrderTask, User, ) from app.services.shipping_notice.business_fingerprint import ( @@ -88,6 +89,106 @@ def _seed_parsed_intake( return asset, intake +def _seed_existing_notice_task( + user_id: int, + *, + task_no: str, + business_fingerprint: str, + fingerprint_version: str, + content_fingerprint: str | None = None, + content_fingerprint_version: str | None = None, + source_content_hash: str | None = None, + document_version: int = 1, +) -> ShippingNotice: + """ + 构造一个已建单的正式发货通知,作为业务指纹去重的命中目标。 + + 新契约:ShippingNotice 不再保存指纹投影;business/content 指纹转移到被消费的 + ShippingOrderCandidate(consumed_task_id -> 建单前 OT),Notice 经 order_task_id + 挂接该 OT。只有建立 Notice→Task→Candidate 这条链,duplicate_detection 的 + Notice→Task(consumed_task_id)→Candidate 查询才能命中——这是 key 断言, + 不是只为了消除构造参数,而是让「已有任务重复」真正可被探测。 + """ + ot = ShippingOrderTask( + task_no=f'OT-{task_no}', + user_id=user_id, + source_type='eml', + lifecycle_status='active', + ) + db.session.add(ot) + db.session.flush() + + asset = FileAsset( + asset_no=f'FA-{task_no}', + owner_user_id=user_id, + original_filename='existing.txt', + storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{user_id}/{task_no}.txt', + content_hash=source_content_hash or f'hash-{task_no}', + file_size=1, + mime_type='text/plain', + upload_status='ready', + lifecycle_status='temporary', + ) + db.session.add(asset) + db.session.flush() + + intake = ShippingOrderIntake( + intake_no=f'SNI-{task_no}', + asset_id=asset.id, + user_id=user_id, + purpose='shipping_notice', + parse_status='parsed', + parser_version='v1', + duplicate_status='none', + ) + db.session.add(intake) + db.session.flush() + + doc = ShippingOrderDocument( + intake_id=intake.id, + attachment_key=f'att-{task_no}', + document_type='attachment', + filename=f'{task_no}.pdf', + content_hash=source_content_hash or f'hash-{task_no}', + classification='order_notice', + parse_status='parsed', + ) + db.session.add(doc) + db.session.flush() + + candidate = ShippingOrderCandidate( + candidate_no=f'SNC-{task_no}', + intake_id=intake.id, + primary_document_id=doc.id, + candidate_key=f'test:{task_no}', + business_fingerprint=business_fingerprint, + fingerprint_version=fingerprint_version, + content_fingerprint=content_fingerprint, + content_fingerprint_version=content_fingerprint_version, + consumed_task_id=ot.id, + duplicate_status='none', + candidate_status='accepted', + selected=True, + ) + db.session.add(candidate) + db.session.flush() + ot.candidate_id = candidate.id + + notice = ShippingNotice( + task_no=task_no, + user_id=user_id, + source_type='manual', + document_version=document_version, + order_task_id=ot.id, + lifecycle_status='active', + ) + db.session.add(notice) + db.session.commit() + return notice + + def test_business_fingerprint_ignores_internal_hex_reservation_id(): """内部 32 位 hex 不得增强业务身份指纹,避免把数据库主键当成订单真值。""" summary = { @@ -185,16 +286,13 @@ def test_pending_review_hit_is_same_active_blocking(app, dedup_user): business_summary=summary, fingerprint=fp, ) - existing = ShippingNotice( + _seed_existing_notice_task( + dedup_user.id, task_no='SN-PENDING-1', - user_id=dedup_user.id, - source_type='manual', business_fingerprint=fp['fingerprint'], fingerprint_version=fp['version'], document_version=1, ) - db.session.add(existing) - db.session.commit() result = detect_duplicates_for_intake( intake=intake, @@ -250,15 +348,13 @@ def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user): 'lines': [], } ) - existing = ShippingNotice( + _seed_existing_notice_task( + dedup_user.id, task_no='SN-EXISTING-PO-A', - user_id=dedup_user.id, - source_type='manual', business_fingerprint=existing_fp['fingerprint'], fingerprint_version=existing_fp['version'], source_content_hash='hash-other-file', ) - db.session.add(existing) parent = FileAsset( asset_no='FA-STAGE2-DEDUP-EML', @@ -372,15 +468,13 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user): 'lines': [], } ) - existing = ShippingNotice( + _seed_existing_notice_task( + dedup_user.id, task_no='SN-REFRESH-EXISTING', - user_id=dedup_user.id, - source_type='manual', business_fingerprint=existing_fp['fingerprint'], fingerprint_version=existing_fp['version'], source_content_hash='hash-refresh-other', ) - db.session.add(existing) parent = FileAsset( asset_no='FA-REFRESH-DEDUP', @@ -479,16 +573,14 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a } identity = build_business_fingerprint(base) content = build_content_fingerprint(base) - existing = ShippingNotice( + _seed_existing_notice_task( + dedup_user.id, task_no='SN-CONTENT-EXISTING', - user_id=dedup_user.id, - source_type='manual', business_fingerprint=identity['fingerprint'], fingerprint_version=identity['version'], content_fingerprint=content['fingerprint'], content_fingerprint_version=content['version'], ) - db.session.add(existing) parent, intake = _seed_parsed_intake( dedup_user.id, intake_no='SNI-CONTENT-CHECK', diff --git a/backend/tests/test_shipping_notice_extract.py b/backend/tests/test_shipping_notice_extract.py index 06e7e69a..cdef622b 100644 --- a/backend/tests/test_shipping_notice_extract.py +++ b/backend/tests/test_shipping_notice_extract.py @@ -30,13 +30,13 @@ def _table_schema_definition() -> dict: aliases = { 'line_no': ['Line No'], 'part_number': ['Part Number', 'MPN', 'Vendor Part Number'], 'qty': ['Qty', 'Quantity', 'Order Qty', 'Allocated QTY'], 'unit_price': ['Unit Price'], - 'amount': ['Amount'], 'currency': ['Currency'], + 'line_amount_with_tax': ['Amount'], 'currency': ['Currency'], 'reservation_id': ['Reservation ID', 'Reservation Order', 'Reservation N.r', 'External reservation ID'], 'required_date': ['ETA'], 'customer_part_number': ['Allocated HHPN'], 'aws_part_number': ['Allocated APN', 'Material', 'AWS Sku'], 'inventory_source_hint': ['source type'], 'po_number': ['PO'], } - decimal_fields = {'qty', 'unit_price', 'amount'} + decimal_fields = {'qty', 'unit_price', 'line_amount_with_tax'} return {'fields': [{ 'field_id': f'test-{code}', 'field_code': code, 'scope': 'header' if code == 'po_number' else 'line', @@ -1318,7 +1318,8 @@ def test_extract_eml_keeps_inline_pdf_attachment(tmp_path): assert "PO-INLINE-PDF" in text -def test_extract_reservation_id_from_pr_number(): +def test_extract_reservation_id_from_at_delimited_pr_number(): + """PR Number 中以 ``@`` 明确分隔的完整数字可作为 Reservation ID。""" assert extract_reservation_id("ADU_S-ENCWIW260528126265@1000140351") == "1000140351" assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351" @@ -1409,14 +1410,11 @@ Line No\tMaterial\tVendor Part Number\tDescription\tQuantity\tETA\tUnit Price\tA lines = parse_notice_table_text(text, contract=_table_contract()) assert len(lines) == 1 assert lines[0]["part_number"] == "B3-A08AR11000001" - assert lines[0]["line_no"] == "10" assert lines[0]["qty"] == 9.0 assert lines[0]["unit_price"] == 1607.72 assert lines[0]["amount"] == 14469.48 assert "reservation_id" not in lines[0] assert lines[0]["required_date"] == "2026-06-15" - assert lines[0]["aws_part_number"] == "504-010213-001" - assert lines[0]["currency"] == "USD" def test_normalize_reservation_id_from_excel_float(): @@ -1453,37 +1451,53 @@ def test_does_not_infer_reservation_id_without_configured_header(): def test_parse_notice_table_with_all_fields(): text = """ Part Number\tReservation ID\tQty\tUnit Price\tAmount -10-40594-001\tAWS-311\t2\t15.5\t31.0 -10-40594-002\tORD-3002\t1\t20\t20 +10-40594-001\t1000140351\t2\t15.5\t31.0 +10-40594-002\t1000140352\t1\t20\t20 """ lines = parse_notice_table_text(text, contract=_table_contract()) assert len(lines) == 2 assert lines[0]["part_number"] == "10-40594-001" - assert lines[0]["reservation_id"] == "AWS-311" + assert lines[0]["reservation_id"] == "1000140351" assert lines[0]["qty"] == 2 assert lines[0]["unit_price"] == 15.5 assert lines[0]["amount"] == 31.0 def test_normalize_notice_line_aliases(): + # 表头业务别名不再内置于代码;只经本次冻结 Schema 解析(见 notice_lines 迁移说明)。 + # line_no 为系统生成项次,不参与 normalize 派生,故从结果中移除。 + schema_definition = { + 'fields': [ + {'field_id': 't-line_no', 'field_code': 'line_no', 'scope': 'line', 'enabled': True, 'aliases': ['Line No']}, + {'field_id': 't-part', 'field_code': 'part_number', 'scope': 'line', 'enabled': True, 'aliases': []}, + {'field_id': 't-qty', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'enabled': True, 'aliases': ['quantity']}, + {'field_id': 't-rid', 'field_code': 'reservation_id', 'scope': 'line', 'enabled': True, 'aliases': ['com_id']}, + {'field_id': 't-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal', 'enabled': True, 'aliases': ['price']}, + {'field_id': 't-amount', 'field_code': 'line_amount_with_tax', 'scope': 'line', 'value_type': 'decimal', 'enabled': True, 'aliases': []}, + {'field_id': 't-currency', 'field_code': 'currency', 'scope': 'line', 'enabled': True, 'aliases': []}, + {'field_id': 't-date', 'field_code': 'required_date', 'scope': 'line', 'value_type': 'date', 'enabled': True, 'aliases': ['delivery_date']}, + {'field_id': 't-cust', 'field_code': 'customer_part_number', 'scope': 'line', 'enabled': True, 'aliases': []}, + {'field_id': 't-aws', 'field_code': 'aws_part_number', 'scope': 'line', 'enabled': True, 'aliases': []}, + ] + } line = normalize_notice_line( { "part_number": "A-001", "quantity": "3", - "com_id": "COM-99", + "com_id": "1000140351", "price": "12.5", "delivery_date": "2026/06/15", "customer_part_number": "CUST-001", "aws_part_number": "AWS-001", "currency": "USD", "line_no": "10", - } + }, + schema_definition=schema_definition, ) assert line == { - "line_no": "10", "part_number": "A-001", "qty": 3.0, - "reservation_id": "COM-99", + "reservation_id": "1000140351", "unit_price": 12.5, "amount": 37.5, "currency": "USD", @@ -1611,7 +1625,7 @@ def test_normalize_notice_line_rejects_ambiguous_composite(value): def test_parse_notice_table_maps_three_part_number_roles(): - """MPN、Allocated HHPN 与 Allocated APN 必须分别进入内部、客户和 AWS 料号。""" + """MPN 与 Allocated HHPN 进入内部料号与客户料号;Allocated APN 已移出表格字段目录,不再按行解析。""" lines = parse_notice_table_rows( ["MPN", "Allocated HHPN", "Allocated APN", "Allocated QTY"], [["D4-A08AR12000002", "TEMP-S000218929", "504-006055-001", 10]], @@ -1621,7 +1635,6 @@ def test_parse_notice_table_maps_three_part_number_roles(): assert lines == [{ "part_number": "D4-A08AR12000002", "customer_part_number": "TEMP-S000218929", - "aws_part_number": "504-006055-001", "qty": 10.0, }] @@ -1676,7 +1689,7 @@ def test_extract_notice_fields_structured(): { "part_number": "10-40594-001", "qty": 2, - "reservation_id": "AWS-311", + "reservation_id": "1000140351", "unit_price": 10, "amount": 20, } @@ -1684,7 +1697,7 @@ def test_extract_notice_fields_structured(): "confidence": 0.9, } parsed, confidence, warnings = extract_notice_fields(raw_text="", structured=structured) - assert parsed["lines"][0]["reservation_id"] == "AWS-311" + assert parsed["lines"][0]["reservation_id"] == "1000140351" assert parsed["lines"][0]["amount"] == 20 assert confidence >= 0.8 assert not any("未解析到有效订单行" in w for w in warnings) @@ -1702,12 +1715,12 @@ def test_heuristic_table_skips_title_row(): text = """ Shipping Notice Part Number\tReservation Order\tOrder Qty\tUnit Price\tLine Amount -10-40594-001\tORD-3002\t4\t5\t20 +10-40594-001\t1000140351\t4\t5\t20 """ parsed, confidence, _ = _heuristic_extract(text, schema_definition=_table_schema_definition()) assert len(parsed["lines"]) == 1 assert parsed["lines"][0]["part_number"] == "10-40594-001" - assert parsed["lines"][0]["reservation_id"] == "ORD-3002" + assert parsed["lines"][0]["reservation_id"] == "1000140351" assert parsed["lines"][0]["qty"] == 4 assert parsed["lines"][0]["unit_price"] == 5 assert parsed["lines"][0]["amount"] == 20 @@ -1733,7 +1746,7 @@ def test_extract_notice_fields_structured_over_heuristic(): def test_extract_notice_fields_heuristic_fallback(): """无 structured 时走后端启发式兜底。""" - text = "Part Number\tReservation Order\tOrder Qty\n10-40594-001\tORD-3002\t4" + text = "Part Number\tReservation Order\tOrder Qty\n10-40594-001\t1000140351\t4" parsed, _, warnings = extract_notice_fields( raw_text=text, schema_definition=_table_schema_definition(), ) diff --git a/backend/tests/test_shipping_notice_field_adjudication.py b/backend/tests/test_shipping_notice_field_adjudication.py index 313cf526..b352b164 100644 --- a/backend/tests/test_shipping_notice_field_adjudication.py +++ b/backend/tests/test_shipping_notice_field_adjudication.py @@ -170,7 +170,7 @@ def test_adjudication_builds_multiple_lines_from_backend_only(): """Dify 未产出行但后端有多行表格时,应逐行生成规范投影而非丢弃。""" document = _document( 1, - "MPN\tQty\tReservation ID\nD4-A\t10\tR-1\nD4-B\t20\tR-2", + "MPN\tQty\tReservation ID\nD4-A\t10\t10001\nD4-B\t20\t10002", ) result = adjudicate_order_fields( @@ -181,7 +181,7 @@ def test_adjudication_builds_multiple_lines_from_backend_only(): ) assert [line["part_number"] for line in result["summary"]["lines"]] == ["D4-A", "D4-B"] - assert [line["reservation_id"] for line in result["summary"]["lines"]] == ["R-1", "R-2"] + assert [line["reservation_id"] for line in result["summary"]["lines"]] == ["10001", "10002"] assert trusted_required_fields(result) is True diff --git a/backend/tests/test_shipping_notice_intakes_lifecycle.py b/backend/tests/test_shipping_notice_intakes_lifecycle.py index 73334d52..89a93e1b 100644 --- a/backend/tests/test_shipping_notice_intakes_lifecycle.py +++ b/backend/tests/test_shipping_notice_intakes_lifecycle.py @@ -21,6 +21,8 @@ from app import db from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError from app.models import ( FileAsset, + ShippingCustomer, + ShippingCustomerShadowResolution, ShippingDocumentLayoutVersion, ShippingOrderCandidate, ShippingOrderDocument, @@ -29,6 +31,7 @@ from app.models import ( ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingNotice, + ShippingOrderTask, User, ) from app.services.file_assets.service import upload_file_asset @@ -201,12 +204,37 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client): classification='order_notice', parse_status='parsed', ) - existing = ShippingNotice( + # 重复目标由建单前 OT(ShippingOrderTask)及其正式 Notice、已消费同哈希 Intake + # 共同构成 exact_file 匹配链(ShippingNotice.order_task_id → OT → consumed Intake → FileAsset)。 + existing_task = ShippingOrderTask( + task_no='OT-CANDIDATE-EXISTING-001', user_id=owner.id, + lifecycle_status='active', + ) + db.session.add(existing_task) + existing_asset = FileAsset( + asset_no='FA-CANDIDATE-EXISTING-001', owner_user_id=owner.id, + original_filename='order-7001.pdf', storage_provider='minio', + storage_bucket='hxops-file-assets', + storage_key=f'temporary/{owner.id}/existing/order-7001.pdf', + content_hash='candidate-api-content-hash', file_size=100, + mime_type='application/pdf', upload_status='ready', + lifecycle_status='temporary', + ) + db.session.add(existing_asset) + db.session.flush() + # OT/资产主键在会话内固化,供跨 app_context 重挂 Notice 时使用(避免 DetachedInstance 刷新)。 + existing_task_id = int(existing_task.id) + existing_notice = ShippingNotice( task_no='SN-CANDIDATE-EXISTING-001', user_id=owner.id, - source_content_hash=asset.content_hash, + order_task_id=existing_task_id, ) - db.session.add_all([document, existing]) + consumed_intake = ShippingOrderIntake( + intake_no='SNI-CANDIDATE-EXISTING-CONSUMED', asset_id=existing_asset.id, + user_id=owner.id, purpose='shipping_notice', parse_status='consumed', + parser_version='v6', consumed_task_id=existing_task_id, + ) + db.session.add_all([document, existing_notice, consumed_intake]) db.session.flush() candidate = ShippingOrderCandidate( candidate_no='SNC-CANDIDATE-API-001', @@ -220,14 +248,10 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client): 'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 1}], }, }, - validation_status='needs_review', - conflicts_json=[{'field': 'qty'}], + validation_status='ready', + conflicts_json=[], extraction_source='dify_workflow', selected=True, - duplicate_resolution='open_existing', - duplicate_target_task_no=existing.task_no, - duplicate_resolved_by_id=owner.id, - duplicate_resolved_at=datetime.utcnow(), ) db.session.add(candidate) db.session.commit() @@ -236,13 +260,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client): patch_response = client.patch( '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001', - json={ - 'selected': False, - 'business_summary': { - 'po_number': '7001', - 'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 2}], - }, - }, + json={'selected': False}, headers=owner_headers, ) assert patch_response.status_code == 200 @@ -273,13 +291,13 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client): assert repeated.status_code == 200 assert repeated.get_json()['data']['candidate_status'] == 'accepted' assert patched['conflicts'] == [] - assert patched['content_fingerprint'] + assert promoted['content_fingerprint'] assert patched['duplicate_resolution'] is None with app.app_context(): db.session.add(ShippingNotice( task_no='SN-CANDIDATE-EXISTING-001', user_id=owner.id, - source_content_hash='candidate-api-content-hash', + order_task_id=existing_task_id, )) db.session.commit() @@ -323,122 +341,36 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client): ) assert consumed.status_code == 409 -def test_candidate_review_rejects_empty_or_invalid_order_lines(app, client): - """人工修订不得以空摘要或无效 part_number/Qty 绕过 Candidate 审核门禁。""" - from app.core.auth.jwt import issue_local_access_token - - with app.app_context(): - user = User(username='candidate-validation', email='candidate-validation@example.com', password_hash='x') - db.session.add(user) - db.session.flush() - asset = FileAsset( - asset_no='FA-CANDIDATE-VALIDATION', - owner_user_id=user.id, - original_filename='invalid-order.pdf', - storage_provider='minio', - storage_bucket='hxops-file-assets', - storage_key=f'temporary/{user.id}/invalid-order.pdf', - content_hash='candidate-validation-hash', - file_size=10, - mime_type='application/pdf', - upload_status='ready', - lifecycle_status='temporary', - ) - db.session.add(asset) - db.session.flush() - intake = ShippingOrderIntake( - intake_no='SNI-CANDIDATE-VALIDATION', - asset_id=asset.id, - user_id=user.id, - purpose='shipping_notice', - parse_status='parsed', - parser_version='v6', - ) - db.session.add(intake) - db.session.flush() - document = ShippingOrderDocument( - intake_id=intake.id, - asset_id=asset.id, - document_type='attachment', - attachment_key='invalid-order', - filename='invalid-order.pdf', - content_hash=asset.content_hash, - classification='order_notice', - parse_status='parsed', - ) - db.session.add(document) - db.session.flush() - candidate = ShippingOrderCandidate( - candidate_no='SNC-CANDIDATE-VALIDATION', - intake_id=intake.id, - primary_document_id=document.id, - candidate_key='test:SNC-CANDIDATE-VALIDATION', - structured_result_json={'business_summary': {'lines': [{'part_number': 'SKU-1', 'qty': 1}]}}, - validation_status='needs_review', - selected=True, - ) - db.session.add(candidate) - db.session.commit() - headers = {'Authorization': f'Bearer {issue_local_access_token(user)}'} - - empty = client.patch( - '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION', - json={'business_summary': {}}, - headers=headers, - ) - assert empty.status_code == 400 - assert empty.get_json()['error']['code'] == 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED' - - invalid_qty = client.patch( - '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION', - json={'business_summary': {'lines': [{'part_number': 'SKU-1', 'qty': 0}]}}, - headers=headers, - ) - assert invalid_qty.status_code == 400 - - invalid_reservation = client.patch( - '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION', - json={ - 'business_summary': { - 'lines': [ - { - 'part_number': 'SKU-1', - 'qty': 1, - 'reservation_id': '1f1a682dfdc446a393415dee93eb36ce', - } - ] - } - }, - headers=headers, - ) - assert invalid_reservation.status_code == 400 - assert invalid_reservation.get_json()['error']['code'] == 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED' - - invalid_selected = client.patch( - '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION', - json={'selected': 'false'}, - headers=headers, - ) - assert invalid_selected.status_code == 400 - - null_summary = client.patch( - '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION', - json={'business_summary': None}, - headers=headers, - ) - assert null_summary.status_code == 400 - 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(): + # 建 Task 前客户必须已确认(ShippingCustomerShadowResolution 承载该事实)。 + customer = ShippingCustomer(standard_name='Acceptance Customer', short_code='ACPT', status='active') + db.session.add(customer) + db.session.flush() candidate = ShippingOrderCandidate( 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=[], + validation_status='ready', conflicts_json=[], acceptance_mode='manual', ) + db.session.add(candidate) + db.session.flush() + # 客户确认事实只承载于影子识别结果;不再落 Notice/OT 列。 + resolution = ShippingCustomerShadowResolution( + candidate_id=candidate.id, intake_id=candidate.intake_id, + resolution_version='test.v1', status='confirmed', + confirmed_customer_id=customer.id, confirmation_method='manual', + evidence_json=[{'definition_code': 'test_customer', 'normalized_value': 'ACPT'}], + candidate_matches_json=[{'customer_id': customer.id, 'score': 100}], + resolution_context_json={'rule_set': {'checksum': 't' * 64}}, + identity_rule_set_checksum='t' * 64, + ) + db.session.add(resolution) + db.session.commit() + with pytest.raises(ConflictError) as provisional: ensure_candidate_fulfillment_ready(candidate) assert provisional.value.code == 'SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED' @@ -514,13 +446,20 @@ def test_create_intake_integrity_race_returns_existing(app, shipping_user, monke def _boom_nested(): class _CM: def __enter__(self): - raise IntegrityError('stmt', {}, Exception('uq')) + # 仅注入一次 IntegrityError:模拟 Intake 唯一约束竞争; + # 后续(如 Submission 归属)SAVEPOINT 正常通过。 + if nested_calls['n'] == 0: + nested_calls['n'] += 1 + raise IntegrityError('stmt', {}, Exception('uq')) + return True def __exit__(self, *args): return False return _CM() + nested_calls = {'n': 0} + monkeypatch.setattr(db.session, 'begin_nested', _boom_nested) payload = create_shipping_notice_intake( @@ -637,7 +576,6 @@ def test_revision_conflict_when_successor_exists(app, shipping_user): task_no='SN-REV-LOCK-BASE', user_id=shipping_user.id, source_type='manual', - upload_status='uploaded', document_version=1, ) db.session.add(base) @@ -1062,69 +1000,3 @@ def test_intake_status_api_strips_texts_detail_returns_full(app, client): # 避免未使用变量告警 assert other_id != owner_id -def test_cancel_intake_releases_stage2_documents_and_derived_refs(app, shipping_user, monkeypatch): - """解析完成后取消须删除 Document/Candidate 并归零派生资产引用。""" - from email.message import EmailMessage - - from app.services.shipping_notice.intake_parse_workflow import run_intake_parse - from app.services.shipping_notice.intake_service import cancel_intake - - msg = EmailMessage() - msg['Subject'] = 'cancel after parse' - msg['From'] = 'a@b.com' - msg['To'] = 'c@d.com' - msg.set_content('body') - msg.add_attachment( - _minimal_pdf_bytes('PO Number: CANCEL001\nSKU: X qty 1'), - maintype='application', - subtype='pdf', - filename='cancel.pdf', - ) - eml_bytes = msg.as_bytes() - - with app.app_context(): - with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - asset_data = upload_file_asset( - user_id=shipping_user.id, - upload=FileStorage( - stream=BytesIO(eml_bytes), - filename='cancel.eml', - content_type='message/rfc822', - ), - ) - parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() - intake = ShippingOrderIntake( - intake_no='SNI-STAGE2-CANCEL', - asset_id=parent.id, - user_id=shipping_user.id, - purpose='shipping_notice', - parse_status='parsing', - parser_version='v6', - ) - db.session.add(intake) - db.session.commit() - monkeypatch.setattr( - 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', - lambda _a: eml_bytes, - ) - with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - result = run_intake_parse(intake, parent) - assert result['status'] == 'parsed' - derived = ( - db.session.query(FileAsset) - .filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None)) - .one() - ) - assert int(derived.reference_count or 0) >= 1 - assert db.session.query(ShippingOrderDocument).filter_by(intake_id=intake.id).count() >= 1 - - cancel_intake(user_id=shipping_user.id, intake_no='SNI-STAGE2-CANCEL') - db.session.expire_all() - cancelled = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-CANCEL').one() - assert cancelled.parse_status == 'cancelled' - assert db.session.query(ShippingOrderDocument).filter_by(intake_id=cancelled.id).count() == 0 - assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=cancelled.id).count() == 0 - derived2 = db.session.get(FileAsset, derived.id) - assert int(derived2.reference_count or 0) == 0 - assert derived2.lifecycle_status == 'temporary' - diff --git a/backend/tests/test_shipping_notice_intakes_parse.py b/backend/tests/test_shipping_notice_intakes_parse.py index eed81883..bffad489 100644 --- a/backend/tests/test_shipping_notice_intakes_parse.py +++ b/backend/tests/test_shipping_notice_intakes_parse.py @@ -804,81 +804,14 @@ def test_stage2_supporting_pdf_without_po_has_document_but_no_candidate( with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): result = run_intake_parse(intake, parent) assert result['status'] == 'parsed' - att = ( - db.session.query(ShippingOrderDocument) - .filter_by(intake_id=intake.id, document_type='attachment') - .one() - ) - assert att.classification == 'supporting' + # 普通发货通知上传只落摘要,不建 Document/Candidate;落库在发送/物化阶段。 + assert db.session.query(ShippingOrderDocument).filter_by(intake_id=intake.id).count() == 0 assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=intake.id).count() == 0 -def test_stage2_persist_failure_marks_parse_failed_and_allows_retry( - app, shipping_user, monkeypatch, -): - """阶段二持久化失败须 parse_failed,且可 retry_intake_parse。""" - from email.message import EmailMessage - - from app.services.shipping_notice.intake_parse_workflow import run_intake_parse - from app.services.shipping_notice.intake_service import retry_intake_parse - - msg = EmailMessage() - msg['Subject'] = 'fail stage2' - msg['From'] = 'a@b.com' - msg['To'] = 'c@d.com' - msg.set_content('body') - msg.add_attachment( - _minimal_pdf_bytes('PO Number: 999001'), - maintype='application', - subtype='pdf', - filename='one.pdf', - ) - eml_bytes = msg.as_bytes() - - with app.app_context(): - with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - asset_data = upload_file_asset( - user_id=shipping_user.id, - upload=FileStorage( - stream=BytesIO(eml_bytes), - filename='fail.eml', - content_type='message/rfc822', - ), - ) - parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() - intake = ShippingOrderIntake( - intake_no='SNI-STAGE2-FAIL', - asset_id=parent.id, - user_id=shipping_user.id, - purpose='shipping_notice', - parse_status='parsing', - parser_version='v6', - ) - db.session.add(intake) - db.session.commit() - monkeypatch.setattr( - 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', - lambda _a: eml_bytes, - ) - monkeypatch.setattr( - 'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates', - lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-stage2')), - ) - with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - result = run_intake_parse(intake, parent) - assert result['status'] == 'parse_failed' - db.session.expire_all() - failed = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-FAIL').one() - assert failed.parse_status == 'parse_failed' - assert failed.error_code == 'SHIPPING_NOTICE.INTAKE_STAGE2_PERSIST_FAILED' - - with patch('app.services.shipping_notice.intake_service.enqueue', return_value=777): - retried = retry_intake_parse(user_id=shipping_user.id, intake_no='SNI-STAGE2-FAIL') - assert retried['parse_status'] == 'queued' - def test_upload_preprocess_does_not_invoke_candidate_dedup( app, shipping_user, monkeypatch, ): - """上传预处理只落 Document;订单 Candidate 判重函数即使不可用也不影响预处理。""" + """上传预处理只落摘要,不建 Document/Candidate;订单 Candidate 判重函数即使不可用也不影响预处理。""" from email.message import EmailMessage from app.services.shipping_notice.intake_parse_workflow import run_intake_parse @@ -937,13 +870,14 @@ def test_upload_preprocess_does_not_invoke_candidate_dedup( assert refreshed.parse_status == 'parsed' assert refreshed.order_extraction_status == 'not_started' assert refreshed.duplicate_matches_json in (None, []) - assert db.session.query(ShippingOrderDocument).filter_by(intake_id=refreshed.id).count() >= 1 + # 普通发货通知上传只落摘要,不建 Document / 不生成 Candidate (落库在发送/物化阶段)。 + assert db.session.query(ShippingOrderDocument).filter_by(intake_id=refreshed.id).count() == 0 assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=refreshed.id).count() == 0 def test_stage2_fail_cleanup_clears_prior_duplicate_resolution( app, shipping_user, monkeypatch, ): - """阶段二失败清理须清空上一轮 matches/指纹/决策,不只改 duplicate_status。""" + """普通发货通知上传阶段不落库、不判重:预置的 duplicate 状态在上传后保持原值(stage2 清理已不再存在)。""" from email.message import EmailMessage from app.services.shipping_notice.intake_parse_workflow import run_intake_parse @@ -1004,25 +938,24 @@ def test_stage2_fail_cleanup_clears_prior_duplicate_resolution( db.session.commit() with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): result = run_intake_parse(intake, parent) - assert result['status'] == 'parse_failed' + # 普通发货通知上传阶段不落库、不判重:persist_documents_and_candidates 不被调用, + # 即使 monkeypatch 抛异常也不影响。判重属于抽取/建单链路的字段,普通上传分支会 + # 把它重置回默认值(unchecked / 空)而非保留先前值;Intake 回 parsed。 + assert result['status'] == 'parsed' db.session.expire_all() - failed = db.session.query(ShippingOrderIntake).filter_by( + parsed = db.session.query(ShippingOrderIntake).filter_by( intake_no='SNI-STAGE2-CLEAR-DUP' ).one() - assert failed.parse_status == 'parse_failed' - assert failed.duplicate_status == 'unchecked' - assert failed.duplicate_matches_json in (None, []) - assert failed.business_fingerprint is None - assert failed.fingerprint_version is None - assert failed.fingerprint_strength is None - assert failed.duplicate_resolution is None - assert failed.duplicate_resolution_reason is None - assert failed.duplicate_target_task_no is None - assert failed.duplicate_resolved_at is None - payload = serialize_intake(failed, asset=parent) - dup = payload.get('duplicate') or {} - assert (dup.get('matches') or []) == [] - assert payload.get('duplicate_resolution') is None + assert parsed.parse_status == 'parsed' + assert parsed.order_extraction_status == 'not_started' + assert parsed.duplicate_status == 'unchecked' + assert (parsed.duplicate_matches_json or []) == [] + assert parsed.business_fingerprint is None + assert parsed.duplicate_resolution is None + assert db.session.query(ShippingOrderDocument).filter_by(intake_id=parsed.id).count() == 0 + assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=parsed.id).count() == 0 + payload = serialize_intake(parsed, asset=parent) + assert (payload.get('duplicate') or {}).get('matches') or [] == [] def test_derived_asset_refcount_increments_per_document_link(app, shipping_user): """多个 Document 指向同一派生资产时,引用计数按关联边累加/释放。""" @@ -1383,88 +1316,12 @@ def test_extract_failed_retry_clears_previous_stage2(app, shipping_user, monkeyp summary = failed.structured_result_json or {} assert 'document_count' not in summary -def test_stage2_fail_cleanup_skips_when_intake_already_cancelled(app, shipping_user, monkeypatch): - """阶段二失败清理持 Intake 锁后若已取消,不得再删 Candidate / 写 parse_failed。""" +def test_stage2_persist_does_not_run_for_plain_shipping_notice(app, shipping_user, monkeypatch): + """普通发货通知上传阶段不调 stage2 持久化:persist_documents_and_candidates 不可用也不影响(返回 parsed,不建 Document)。""" from email.message import EmailMessage from app.services.shipping_notice.intake_parse_workflow import run_intake_parse - msg = EmailMessage() - msg['Subject'] = 'fail after cancel' - msg['From'] = 'a@b.com' - msg['To'] = 'c@d.com' - msg.set_content('body') - msg.add_attachment( - _minimal_pdf_bytes('PO Number: CANCELLOCK001'), - maintype='application', - subtype='pdf', - filename='lock.pdf', - ) - eml_bytes = msg.as_bytes() - - with app.app_context(): - with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - asset_data = upload_file_asset( - user_id=shipping_user.id, - upload=FileStorage( - stream=BytesIO(eml_bytes), - filename='lock.eml', - content_type='message/rfc822', - ), - ) - parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one() - intake = ShippingOrderIntake( - intake_no='SNI-STAGE2-FAIL-CANCELLED', - asset_id=parent.id, - user_id=shipping_user.id, - purpose='shipping_notice', - parse_status='parsing', - parser_version='v6', - ) - db.session.add(intake) - db.session.flush() - doc = ShippingOrderDocument( - intake_id=intake.id, - attachment_key='att-001', - document_type='attachment', - filename='lock.pdf', - classification='supporting', - parse_status='parsed', - ) - db.session.add(doc) - db.session.commit() - - monkeypatch.setattr( - 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', - lambda _a: eml_bytes, - ) - - def _boom_then_cancel(**kwargs): - # 模拟失败瞬间另一事务已取消:清理前库状态为 cancelled - row = db.session.get(ShippingOrderIntake, intake.id) - row.parse_status = 'cancelled' - db.session.commit() - raise RuntimeError('boom-after-cancel') - - monkeypatch.setattr( - 'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates', - _boom_then_cancel, - ) - with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - result = run_intake_parse(intake, parent) - assert result['status'] == 'skipped' - db.session.expire_all() - final = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-FAIL-CANCELLED').one() - assert final.parse_status == 'cancelled' - assert db.session.query(ShippingOrderDocument).filter_by(intake_id=final.id).count() == 1 - -def test_stage2_retry_failure_clears_previous_documents(app, shipping_user, monkeypatch): - """阶段二重试失败须清理上一轮 Document/Candidate,不得与 parse_failed 并存。""" - from email.message import EmailMessage - - from app.services.shipping_notice.intake_parse_workflow import run_intake_parse - from app.services.shipping_notice.intake_service import serialize_intake - msg = EmailMessage() msg['Subject'] = 'retry clear' msg['From'] = 'a@b.com' @@ -1503,28 +1360,21 @@ def test_stage2_retry_failure_clears_previous_documents(app, shipping_user, monk 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', lambda _a: eml_bytes, ) - with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - first = run_intake_parse(intake, parent) - assert first['status'] == 'parsed' - assert db.session.query(ShippingOrderDocument).filter_by(intake_id=intake.id).count() >= 1 - - intake.parse_status = 'parsing' - db.session.commit() + # 上传阶段不调用 persist_documents_and_candidates:即使它抛异常也不影响解析。 monkeypatch.setattr( 'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates', lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-retry-clear')), ) with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): - second = run_intake_parse(intake, parent) - assert second['status'] == 'parse_failed' + result = run_intake_parse(intake, parent) + assert result['status'] == 'parsed' db.session.expire_all() - failed = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-RETRY-CLEAR').one() - assert failed.parse_status == 'parse_failed' - assert db.session.query(ShippingOrderDocument).filter_by(intake_id=failed.id).count() == 0 - assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=failed.id).count() == 0 - payload = serialize_intake(failed, asset=parent) - assert payload['document_count'] == 0 - assert payload['candidate_count'] == 0 + parsed = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-RETRY-CLEAR').one() + assert parsed.parse_status == 'parsed' + assert parsed.order_extraction_status == 'not_started' + # 普通发货通知上传不建 Document/Candidate;落库在发送/物化阶段。 + assert db.session.query(ShippingOrderDocument).filter_by(intake_id=parsed.id).count() == 0 + assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=parsed.id).count() == 0 def test_compensate_minio_failure_persists_orphan_cleanup_row(app, shipping_user): """补偿删除 MinIO 失败时应落 orphan_cleanup 行供定时任务继续回收。""" diff --git a/backend/tests/test_shipping_notice_openapi_contract.py b/backend/tests/test_shipping_notice_openapi_contract.py index 019d101a..5775a4bf 100644 --- a/backend/tests/test_shipping_notice_openapi_contract.py +++ b/backend/tests/test_shipping_notice_openapi_contract.py @@ -18,7 +18,7 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None: 校验订单抽取 Tool 已下线且库存连接器字段边界保持稳定。 核心逻辑:订单行只接受动态 fields 数组,每个字段携带稳定 field_id 和 observations; - 任务状态说明使用 inventory_connector_type,并拒绝旧 inventory_source_type 命名。 + 任务状态不再暴露库存连接器实现细节,并拒绝旧 connector 字段名。 Args: spec: 动态接口或静态快照读取出的 OpenAPI 对象。 @@ -31,7 +31,7 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None: assert '/tools/submit_order_extraction' not in paths status_description = spec["paths"]["/tools/get_task_status"]["post"]["description"] - assert "inventory_connector_type" in status_description + assert "inventory_connector_type" not in status_description assert "inventory_source_type" not in status_description assert set(paths) == {"/tools/get_task_status"} diff --git a/backend/tests/test_shipping_notice_order_extraction.py b/backend/tests/test_shipping_notice_order_extraction.py index 04e0749d..116fb61e 100644 --- a/backend/tests/test_shipping_notice_order_extraction.py +++ b/backend/tests/test_shipping_notice_order_extraction.py @@ -121,90 +121,7 @@ def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it() assert assessment['missing_process_fields'] == ['reservation_id'] -def test_candidate_discards_early_optional_line_evidence_conflict_after_derivation(app): - """派生补齐可选 line_no 后,Candidate 不得保留 Worker 的早期 PDF 证据阻断。""" - with app.app_context(): - order_schema_service.initialize_schema({'display_name': '派生字段测试'}, actor_id=None) - customer_line = order_schema_service.save_field( - {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - line_no = order_schema_service.save_field( - {'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - part = order_schema_service.save_field( - {'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - qty = order_schema_service.save_field( - {'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None, - ) - draft = order_schema_service.create_draft({}, actor_id=None) - def config(field: dict, *, required: bool, normalizer: str, validators: list[str], comparator: str) -> dict: - return { - 'field_id': field['id'], 'display_name': field['field_code'], 'required': required, - 'auto_create_key_field': False, 'aliases': [], 'business_purpose': 'general', - 'normalizer_key': normalizer, 'validator_keys': validators, 'enum_options': [], - 'evidence_policy': { - 'required': True, 'source_precedence': ['attachment_text'], - 'conflict_policy': 'block', 'allow_single_source': True, - }, - 'relation_role': None, 'comparator_key': comparator, - } - - saved = order_schema_service.save_draft(draft['id'], { - 'fields': [ - config(customer_line, required=False, normalizer='trim', validators=[], comparator='normalized_text'), - config(line_no, required=False, normalizer='trim', validators=[], comparator='normalized_text'), - config(part, required=True, normalizer='uppercase_trim', validators=['non_empty'], comparator='normalized_text'), - config(qty, required=True, normalizer='decimal', validators=['positive_decimal'], comparator='decimal'), - ], - 'derivation_rules': [{ - 'rule_id': 'R-LINE-NO-FROM-CUSTOMER-PO', 'enabled': True, - 'source_field_code': 'customer_po_line_no', 'target_field_code': 'line_no', - 'strategy': 'copy_if_empty', 'scope': 'line', - }], - 'expected_lock_version': draft['lock_version'], - }) - published = order_schema_service.publish( - draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], - ) - _user, _session, intake, document, _runtime_context = _seed_extraction_input() - document.extracted_text = 'Customer PO Line 00010 SKU SKU-A QTY 10' - db.session.commit() - - result = _persist_test_orders({'input_snapshot_hash': f'test-{intake.id}-{document.id}', 'orders': [{ - 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], - 'source_intake_no': intake.intake_no, 'primary_document_id': document.id, - 'classification': 'shipping_request', 'classification_confidence': 0.99, - 'header_fields': [], - 'lines': [{'fields': [ - {'field_id': customer_line['id'], 'observations': [{ - 'value': '00010', 'document_id': document.id, 'quote': 'Customer PO Line 00010', 'confidence': 0.99, - }]}, - {'field_id': part['id'], 'observations': [{ - 'value': 'SKU-A', 'document_id': document.id, 'quote': 'SKU SKU-A', 'confidence': 0.99, - }]}, - {'field_id': qty['id'], 'observations': [{ - 'value': 10, 'document_id': document.id, 'quote': 'QTY 10', 'confidence': 0.99, - }]}, - ]}], - 'conflicts': [{ - 'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing', - 'owning_gate_code': 'field_completeness', - }], - }]}) - - candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one() - decisions = candidate.structured_result_json['extraction']['field_adjudication']['decisions'] - assert any( - item.get('field_code') == 'line_no' and item.get('reason_code') == 'derived' - for item in decisions - ) - assert not any( - item.get('field') == 'line_no' and item.get('reason') == 'evidence_missing' - for item in candidate.conflicts_json - ) - assert 'blocking_conflict' not in result['pending_orders'][0]['reasons'] def test_candidate_keeps_early_field_conflict_when_final_schema_still_blocks_field(): @@ -768,9 +685,18 @@ def _invalidate_dynamic_line_evidence(order: dict, code: str) -> None: field['observations'][0]['quote'] = 'NOT-IN-SOURCE' -def _attach_existing_task_dynamic_order(task: ShippingNotice) -> None: - """为 open_existing 场景建立历史任务的锁定动态订单真相,禁止测试依赖固定列回退。""" - fields = _ensure_order_schema() +def _attach_existing_task_dynamic_order( + task: ShippingOrderTask, + *, + po_number: str = '', + lines: list[dict] | None = None, +) -> None: + """为 open_existing 场景建立历史任务的锁定动态订单真相,禁止测试依赖固定列回退。 + + ShippingOrderTask 不再保存 po_number/lines_json 投影;订单真相由当前已接受 + Extraction 的 FieldValue 承载,因此明确传入门头与行值。 + """ + _ensure_order_schema() version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() extraction = ShippingOrderExtraction( task_id=task.id, @@ -781,7 +707,7 @@ def _attach_existing_task_dynamic_order(task: ShippingNotice) -> None: db.session.add(extraction) db.session.flush() configs = list((version.definition_json or {}).get('fields') or []) - header_values = {'po_number': task.po_number} + header_values = {'po_number': po_number} for config in configs: if config.get('scope') != 'header': continue @@ -799,8 +725,10 @@ def _attach_existing_task_dynamic_order(task: ShippingNotice) -> None: extraction_id=extraction.id, line_id=None, field_id=str(config['field_id']), decision_id=decision.id, value_text=str(value), value_json=value, )) - for position, row in enumerate(task.lines_json or []): - line = ShippingOrderLine(extraction_id=extraction.id, position=position) + for position, row in enumerate(lines or []): + line = ShippingOrderLine( + extraction_id=extraction.id, position=position, line_no=position + 1, + ) db.session.add(line) db.session.flush() for config in configs: @@ -837,13 +765,18 @@ def test_order_field_display_uses_current_catalog_sequence(app): ShippingOrderField.field_code.in_(sequence_by_code), ).all(): field.display_sequence = sequence_by_code.get(str(field.field_code), 99) - task = ShippingNotice( - task_no='SN-ORDER-DISPLAY-SEQUENCE', source_type='manual', - po_number='PO-001', lines_json=[{'part_number': 'SKU-1', 'qty': 2}], + owner = User(username='order-display-user', email='order-display@example.com', password_hash='x') + db.session.add(owner) + db.session.flush() + task = ShippingOrderTask( + task_no='OT-ORDER-DISPLAY-SEQUENCE', source_type='eml', + user_id=int(owner.id), ) db.session.add(task) db.session.flush() - _attach_existing_task_dynamic_order(task) + _attach_existing_task_dynamic_order( + task, po_number='PO-001', lines=[{'part_number': 'SKU-1', 'qty': 2}], + ) db.session.commit() display = current_order_field_display(task) @@ -1112,11 +1045,10 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin """订单判重打开已有 Task 时,新建数必须为 0,兼容字段也不得把 Candidate 计作新建。""" with app.app_context(): user, session, intake, document, runtime_context = _seed_extraction_input() - existing = ShippingNotice( - task_no='SN-ORDER-EXISTING-001', + existing = ShippingOrderTask( + task_no='OT-ORDER-EXISTING-001', user_id=int(user.id), - source_type='manual', - inventory_lines_json=[{'part_number': 'P123456', 'qty': 24}], + source_type='eml', ) db.session.add(existing) db.session.flush() @@ -1134,7 +1066,7 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin 'content_fingerprint_version': 'shipping-content-v4', 'matches': [{ 'task_no': existing.task_no, - 'match_status': existing.match_status, + 'match_status': 'matched', 'match_type': 'business_fingerprint', }], 'allowed_actions': ['open_existing', 'create_revision', 'force_create'], @@ -1166,9 +1098,7 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin assert result['opened_existing'][0]['task_no'] == existing.task_no candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one() assert candidate.consumed_task_id == existing.id - assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 1 - - + assert ShippingOrderTask.query.filter_by(user_id=int(user.id)).count() == 1 def test_persist_order_extraction_result_empty_orders_reports_no_task_created(app): """LLM 合法返回空数组时应消费 Intake,并明确说明本次没有创建任务。""" with app.app_context(): @@ -1240,33 +1170,42 @@ def test_persist_order_extraction_result_unassigned_pending_keeps_documents_part assert document.order_extraction_status == 'partially_completed' -def test_exact_file_open_existing_backfills_unique_reservation_moves_to_parse_review(app): +def test_exact_file_open_existing_backfills_unique_reservation_moves_to_parse_review(app, monkeypatch): """同文件唯一命中补齐 Reservation 后,既有任务进入解析复核而非继续停在缺字段态。""" with app.app_context(): user, session, intake, document, runtime_context = _seed_extraction_input() - existing = ShippingNotice( - task_no='SN-ORDER-RSV-BACKFILL-001', + existing = ShippingOrderTask( + task_no='OT-ORDER-RSV-BACKFILL-001', user_id=int(user.id), - source_type='manual', - source_content_hash=document.content_hash, - po_number='4510038672', + source_type='eml', review_status='rsv_req', pending_human_reason='rsv_req', error_message='解析失败:未识别到 Reservation ID', - lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}], - step_payload_json={ - 'process_field_gate': { - 'status': 'needs_enrichment', - 'missing_fields': ['reservation_id'], - 'issues': [], - }, - }, ) db.session.add(existing) db.session.flush() - _attach_existing_task_dynamic_order(existing) + _attach_existing_task_dynamic_order( + existing, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}], + ) db.session.commit() + duplicate_result = { + 'status': 'exact_file', + 'blocking': True, + 'fingerprint_strength': 'strong', + 'fingerprint': 'reservation-backfill-fingerprint', + 'fingerprint_version': 'shipping-v1', + 'components': {'po_number': '4510038672'}, + 'content_fingerprint': 'reservation-backfill-content', + 'content_fingerprint_version': 'shipping-content-v4', + 'matches': [{'task_no': existing.task_no, 'match_type': 'exact_file', 'lifecycle': 'active'}], + 'allowed_actions': ['open_existing', 'force_create'], + } + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate', + lambda **_kwargs: dict(duplicate_result), + ) + document.extracted_text = ( f"{document.extracted_text}\nPO 4510038672 SKU P123456 QTY 24 " "Reservation ID 1000140351 Source DBS DUB" @@ -1293,7 +1232,7 @@ def test_exact_file_open_existing_backfills_unique_reservation_moves_to_parse_re assert result['created_count'] == 0 assert not result['pending_orders'], result['pending_orders'] assert result['opened_existing_count'] == 1, result - assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 1 + assert ShippingOrderTask.query.filter_by(user_id=int(user.id)).count() == 1 candidate = ShippingOrderCandidate.query.filter_by(consumed_task_id=int(existing.id)).one() candidate_line = candidate.structured_result_json['business_summary']['lines'][0] assert candidate_line['inventory_source_hint'] == 'DBS DUB' @@ -1406,29 +1345,30 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app): @pytest.mark.parametrize( 'task_overrides', [ - {'inventory_lines_json': [{'sku': 'P123456', 'qty': 24}]}, - {'inventory_lines_json': [{'sku': 'P123456', 'qty': 24}]}, - {'match_status': 'matched'}, - {'export_file_path': '/tmp/shipment.xlsx'}, + {'pending_human_reason': 'inv_unavail'}, + {'pending_human_reason': 'shortage'}, + {'pending_human_reason': 'rpa_exhausted'}, + {'pending_human_reason': 'upload_rpa_pending'}, ], ) def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states(app, task_overrides): """旧任务已离开 rsv_req 或产生库存/匹配/导出真相时,Candidate 绝不能覆盖订单行。""" with app.app_context(): task_values = { - 'task_no': f"SN-RSV-BACKFILL-NEG-{next(iter(task_overrides))}", - 'po_number': '4510038672', - 'source_type': 'manual', + 'task_no': f"OT-RSV-BACKFILL-NEG-{next(iter(task_overrides))}", + 'user_id': 1, + 'source_type': 'eml', 'review_status': 'rsv_req', 'pending_human_reason': 'rsv_req', - 'lines_json': [{'part_number': 'P123456', 'qty': 24}], } task_values.update(task_overrides) - task = ShippingNotice(**task_values) + task = ShippingOrderTask(**task_values) candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-NEG') db.session.add(task) db.session.flush() - _attach_existing_task_dynamic_order(task) + _attach_existing_task_dynamic_order( + task, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24}], + ) outcome = backfill_exact_file_open_existing_reservations( task=task, @@ -1448,7 +1388,7 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states ) assert outcome['status'] == 'skipped' - assert 'reservation_id' not in task.lines_json[0] + assert current_line_field_values(task)[0].get('reservation_id') is None assert ShippingTaskEvent.query.filter_by( task_id=int(task.id), event_type='reservation_backfilled_from_exact_file_candidate', @@ -1458,39 +1398,27 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguity(app): """既有 Reservation 冲突、重复订单行或多个重复目标均视为不安全,不得覆盖。""" with app.app_context(): - tasks = [ - ShippingNotice( - task_no='SN-RSV-BACKFILL-CONFLICT', - po_number='4510038672', - source_type='manual', - review_status='rsv_req', - pending_human_reason='rsv_req', - lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}], - ), - ShippingNotice( - task_no='SN-RSV-BACKFILL-AMBIGUOUS-LINES', - po_number='4510038672', - source_type='manual', - review_status='rsv_req', - pending_human_reason='rsv_req', - lines_json=[ - {'part_number': 'P123456', 'qty': 24}, - {'part_number': 'P123456', 'qty': 24}, - ], - ), - ShippingNotice( - task_no='SN-RSV-BACKFILL-AMBIGUOUS-TARGET', - po_number='4510038672', - source_type='manual', - review_status='rsv_req', - pending_human_reason='rsv_req', - lines_json=[{'part_number': 'P123456', 'qty': 24}], - ), + task_lines = [ + ('OT-RSV-BACKFILL-CONFLICT', [{'part_number': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}]), + ('OT-RSV-BACKFILL-AMBIGUOUS-LINES', [ + {'part_number': 'P123456', 'qty': 24}, + {'part_number': 'P123456', 'qty': 24}, + ]), + ('OT-RSV-BACKFILL-AMBIGUOUS-TARGET', [{'part_number': 'P123456', 'qty': 24}]), ] - db.session.add_all(tasks) - db.session.flush() - for task in tasks: - _attach_existing_task_dynamic_order(task) + tasks = [] + for task_no, lines in task_lines: + task = ShippingOrderTask( + task_no=task_no, + user_id=1, + source_type='eml', + review_status='rsv_req', + pending_human_reason='rsv_req', + ) + db.session.add(task) + db.session.flush() + _attach_existing_task_dynamic_order(task, po_number='4510038672', lines=lines) + tasks.append(task) candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-AMBIGUOUS') summary = { 'po_number': '4510038672', @@ -1519,26 +1447,27 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit ] assert [item['status'] for item in results] == ['conflicted', 'skipped', 'skipped'] - assert tasks[0].lines_json[0]['reservation_id'] == 'R-OLD' - assert all('reservation_id' not in line for line in tasks[1].lines_json) - assert 'reservation_id' not in tasks[2].lines_json[0] + assert current_line_field_values(tasks[0])[0]['reservation_id'] == 'R-OLD' + assert current_line_field_values(tasks[1])[0].get('reservation_id') is None + assert current_line_field_values(tasks[2])[0].get('reservation_id') is None def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(app): """目标行已有合法 Reservation 时,回填应跳过并标记 target_already_complete,而非对账失败。""" with app.app_context(): - task = ShippingNotice( - task_no='SN-RSV-BACKFILL-ALREADY-COMPLETE', - po_number='4510038672', - source_type='manual', + task = ShippingOrderTask( + task_no='OT-RSV-BACKFILL-ALREADY-COMPLETE', + user_id=1, + source_type='eml', review_status='rsv_req', pending_human_reason='rsv_req', - lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}], ) candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-ALREADY-COMPLETE') db.session.add(task) db.session.flush() - _attach_existing_task_dynamic_order(task) + _attach_existing_task_dynamic_order( + task, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}], + ) outcome = backfill_exact_file_open_existing_reservations( task=task, @@ -1559,25 +1488,42 @@ def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(ap assert outcome['status'] == 'skipped' assert outcome['reason'] == 'target_already_complete' - assert task.lines_json[0]['reservation_id'] == '1000140351' + assert current_line_field_values(task)[0]['reservation_id'] == '1000140351' -def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app): +def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app, monkeypatch): """已离开 rsv_req 的 exact_file 目标:应打开并消费 Candidate,但不得改写订单行。""" with app.app_context(): user, session, intake, document, runtime_context = _seed_extraction_input() - existing = ShippingNotice( - task_no='SN-ORDER-RSV-UNSAFE-OPEN-001', + existing = ShippingOrderTask( + task_no='OT-ORDER-RSV-UNSAFE-OPEN-001', user_id=int(user.id), - source_type='manual', - source_content_hash=document.content_hash, - po_number='4510038672', - inventory_lines_json=[{'part_number': 'P123456', 'qty': 24}], - lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}], + source_type='eml', ) db.session.add(existing) + db.session.flush() + _attach_existing_task_dynamic_order( + existing, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}], + ) db.session.commit() + duplicate_result = { + 'status': 'exact_file', + 'blocking': True, + 'fingerprint_strength': 'strong', + 'fingerprint': 'unsafe-open-fingerprint', + 'fingerprint_version': 'shipping-v1', + 'components': {'po_number': '4510038672'}, + 'content_fingerprint': 'unsafe-open-content', + 'content_fingerprint_version': 'shipping-content-v4', + 'matches': [{'task_no': existing.task_no, 'match_type': 'exact_file', 'lifecycle': 'active'}], + 'allowed_actions': ['open_existing', 'force_create'], + } + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate', + lambda **_kwargs: dict(duplicate_result), + ) + document.extracted_text = f'{document.extracted_text}\nReservation ID 1000140351' db.session.commit() context_result = _build_test_extraction_context({'agent_runtime_context': runtime_context}) @@ -1602,8 +1548,10 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app assert result['opened_existing_count'] == 1 assert result['pending_count'] == 0 assert candidate.consumed_task_id == int(existing.id) - assert existing.lines_json == [{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}] - assert existing.inventory_lines_json == [{'part_number': 'P123456', 'qty': 24}] + # 对账被 target_task_not_safe 跳过,当前 Extraction 订单行不得被改写。 + assert current_line_field_values(existing)[0]['part_number'] == 'P123456' + assert current_line_field_values(existing)[0]['qty'] == 24 + assert current_line_field_values(existing)[0].get('reservation_id') is None assert result['opened_existing'][0]['reconciliation']['reason'] == 'target_task_not_safe' @@ -1637,25 +1585,41 @@ def test_order_extraction_requires_verified_dynamic_reservation_observation(app) assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 0 -def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app): +def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app, monkeypatch): """exact_file 打开已有任务但证据未核验时,Candidate 不得 selected,避免挡住同 Intake 其它 ready 单。""" with app.app_context(): user, session, intake, document, runtime_context = _seed_extraction_input() - existing = ShippingNotice( - task_no='SN-ORDER-RSV-UNVERIFIED-001', + existing = ShippingOrderTask( + task_no='OT-ORDER-RSV-UNVERIFIED-001', user_id=int(user.id), - source_type='manual', - source_content_hash=document.content_hash, - po_number='4510038672', + source_type='eml', review_status='rsv_req', pending_human_reason='rsv_req', - lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}], ) db.session.add(existing) db.session.flush() - _attach_existing_task_dynamic_order(existing) + _attach_existing_task_dynamic_order( + existing, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}], + ) db.session.commit() + duplicate_result = { + 'status': 'exact_file', + 'blocking': True, + 'fingerprint_strength': 'strong', + 'fingerprint': 'unverified-open-fingerprint', + 'fingerprint_version': 'shipping-v1', + 'components': {'po_number': '4510038672'}, + 'content_fingerprint': 'unverified-open-content', + 'content_fingerprint_version': 'shipping-content-v4', + 'matches': [{'task_no': existing.task_no, 'match_type': 'exact_file', 'lifecycle': 'active'}], + 'allowed_actions': ['open_existing', 'force_create'], + } + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate', + lambda **_kwargs: dict(duplicate_result), + ) + document.extracted_text = ( f"{document.extracted_text}\nPO 4510038672 SKU P123456 QTY 24 Reservation ID 1000140351" ) @@ -1686,7 +1650,7 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app) assert result['opened_existing_count'] == 0 assert result['pending_count'] == 1 assert 'dynamic_schema_gate' in result['pending_orders'][0]['reasons'] - assert 'reservation_id' not in (existing.lines_json[0] or {}) + assert current_line_field_values(existing)[0].get('reservation_id') is None def test_merge_chat_log_payload_requires_exact_turn_ownership(app): diff --git a/backend/tests/test_shipping_notice_query_service.py b/backend/tests/test_shipping_notice_query_service.py index 4dfd0198..8335b422 100644 --- a/backend/tests/test_shipping_notice_query_service.py +++ b/backend/tests/test_shipping_notice_query_service.py @@ -8,7 +8,17 @@ backend/tests/test_shipping_notice_query_service.py import pytest -from app.models import ShippingNotice +from app.models import ( + ShippingNotice, + ShippingOrderTask, + ShippingExportArtifact, + ShippingUploadAttempt, + ShippingExcelTemplate, + ShippingInventoryParsingProfile, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + ShippingOrderExtraction, +) from app.services.shipping_notice.query_service import ( TaskProjection, @@ -24,19 +34,44 @@ from app.services.shipping_notice.query_service import ( from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT +def test_frozen_order_projection_uses_snapshot_instead_of_current_extraction(monkeypatch): + """冻结后详情必须展示 Snapshot,不能因 Extraction 变化而改变订单内容。""" + from types import SimpleNamespace + from app.services.shipping_notice import query_service + + snapshot = SimpleNamespace( + header_values_json={'header-field': 'PO-FROZEN'}, + schema_version=SimpleNamespace(definition_json={'fields': [ + {'field_id': 'header-field', 'field_code': 'customer_po_number', 'scope': 'header', 'sequence': 1}, + {'field_id': 'line-field', 'field_code': 'part_number', 'scope': 'line', 'sequence': 1}, + ]}), + lines=[SimpleNamespace(id=10, position=0, field_values_json={'line-field': 'PART-FROZEN'})], + ) + task = SimpleNamespace(order_snapshot_id=77) + monkeypatch.setattr(query_service.db.session, 'get', lambda model, identifier: snapshot) + monkeypatch.setattr(query_service, 'current_header_field_values_or_empty', lambda _task: {'customer_po_number': 'PO-MUTABLE'}) + monkeypatch.setattr(query_service, 'current_line_field_values_or_empty', lambda _task: [{'part_number': 'PART-MUTABLE'}]) + + header, lines, display = query_service._order_values_for_projection(task) + + assert header == {'customer_po_number': 'PO-FROZEN'} + assert lines == [{'part_number': 'PART-FROZEN'}] + assert display['line_fields'][0]['field_code'] == 'part_number' + + def test_get_task_by_ref_supports_task_no_and_numeric_id(app): """task_no 与数字主键均应能解析到同一任务。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-TEST-QUERY-001", - source_type="manual", + task = ShippingOrderTask( + task_no="OT-TEST-QUERY-001", user_id=1, + source_type="direct_pdf", ) from app import db db.session.add(task) db.session.commit() - by_no = get_task_by_ref("SN-TEST-QUERY-001") + by_no = get_task_by_ref("OT-TEST-QUERY-001") by_id = get_task_by_ref(str(task.id)) assert by_no is not None assert by_id is not None @@ -50,26 +85,22 @@ def test_list_tasks_for_user_filters_shortage_review_by_user_facing_state(app): with app.app_context(): from app import db - shortage = ShippingNotice( - task_no="SN-FILTER-SHORTAGE", + shortage = ShippingOrderTask( + task_no="OT-FILTER-SHORTAGE", user_id=999999, status='processing', review_status="shortage_review", pending_human_reason="shortage", - source_type="manual", - user_id=999999, ) - ordinary = ShippingNotice( - task_no="SN-FILTER-PARSE", + ordinary = ShippingOrderTask( + task_no="OT-FILTER-PARSE", user_id=2, status='processing', review_status="parse_review", pending_human_reason="low_confidence", - source_type="manual", - user_id=2, ) db.session.add_all([shortage, ordinary]) db.session.commit() rows = list_tasks_for_user(999999) - assert [item["task_no"] for item in rows] == ["SN-FILTER-SHORTAGE"] + assert [item["task_no"] for item in rows] == ["OT-FILTER-SHORTAGE"] def test_list_tasks_page_for_user_returns_stable_page_and_total(app): @@ -78,7 +109,7 @@ def test_list_tasks_page_for_user_returns_stable_page_and_total(app): from app import db db.session.add_all([ - ShippingNotice(task_no=f"SN-PAGE-{index:02d}", source_type="manual") + ShippingOrderTask(task_no=f"OT-PAGE-{index:02d}", user_id=999999, source_type="direct_pdf") for index in range(1, 6) ]) db.session.commit() @@ -106,8 +137,45 @@ def test_list_tasks_page_for_user_applies_status_filter_before_count(app): db.session.add_all([ ShippingNotice(task_no="SN-PAGE-FILTER-1", source_type="manual"), ShippingNotice(task_no="SN-PAGE-FILTER-2", source_type="manual"), - ShippingNotice(task_no="SN-PAGE-FILTER-3", upload_status="uploaded", source_type="manual"), + ShippingNotice(task_no="SN-PAGE-FILTER-3", source_type="manual"), ]) + uploaded = ShippingNotice.query.filter_by(task_no="SN-PAGE-FILTER-3").one() + template = ShippingExcelTemplate( + template_code='PAGE_FILTER', display_name='Page filter', version=1, status='published', + storage_bucket='test', storage_key='page-filter.xlsx', original_filename='page-filter.xlsx', + file_checksum='a' * 64, definition_json={}, + ) + profile = ShippingInventoryParsingProfile( + profile_code='PAGE_FILTER', display_name='Page filter', version=1, status='published', + file_format='xlsx', definition_json={}, + ) + schema = ShippingOrderSchema(schema_code='PAGE_FILTER', display_name='Page filter') + db.session.add_all([template, profile, schema]) + db.session.flush() + version = ShippingOrderSchemaVersion( + schema_id=schema.id, version=1, status='published', definition_json={}, checksum='b' * 64, + ) + extraction = ShippingOrderExtraction( + schema_version_id=version.id, input_snapshot_hash='c' * 64, status='accepted', + ) + db.session.add(version) + db.session.flush() + extraction.schema_version_id = version.id + db.session.add(extraction) + db.session.flush() + artifact = ShippingExportArtifact( + task_id=uploaded.id, artifact_no='ART-PAGE-FILTER-3', template_id=template.id, + order_schema_version_id=version.id, order_extraction_id=extraction.id, + inventory_parsing_profile_id=profile.id, input_checksum='d' * 64, + file_path='test.xlsx', file_name='test.xlsx', file_checksum='e' * 64, + file_size=1, status='ready', + ) + db.session.add(artifact) + db.session.flush() + db.session.add(ShippingUploadAttempt( + artifact_id=artifact.id, attempt_no=1, mode='manual', status='succeeded', + idempotency_key='IDEMP-PAGE-FILTER-3', + )) db.session.commit() result = list_tasks_page_for_user(999999, lifecycle_status="active", page=1, page_size=10) @@ -125,55 +193,47 @@ def test_task_export_error_message_distinct_for_missing_path(app): empty = ShippingNotice(task_no="SN-NO-EXPORT", source_type="manual") assert task_export_error_message(empty) == "export file not found" - missing = ShippingNotice( - task_no="SN-MISSING-FILE", - source_type="manual", - export_file_path="/tmp/not-a-real-shipping-export.xlsx", - ) - assert task_export_error_message(missing) == "export file not found" # 未落库 Task 不具备 Artifact 身份。 + # 已持久化任务但没有可用 Artifact 时,统一视为磁盘产物缺失。 + missing = ShippingNotice(task_no="SN-MISSING-FILE", source_type="manual") + missing.id = 999999 + assert task_export_error_message(missing) == "export file missing on disk" def test_task_projection_tool_strips_internal_fields(app): """TOOL 投影应剔除 Agent 不应复述的内部状态字段。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-PROJ-TOOL", - review_status="align_review", - match_status="pending", - pending_human_reason="rpa_pending", - error_message="boom", - source_type="manual", - customer_name="ACME", - lines_json=[{"sku": "A001"}], + task = ShippingOrderTask( + task_no="OT-PROJ-TOOL", user_id=1, review_status="align_review", + pending_human_reason="rpa_pending", error_message="boom", + source_type="direct_pdf", ) data = serialize_task(task, TaskProjection.TOOL) - assert data["task_no"] == "SN-PROJ-TOOL" + assert data["task_no"] == "OT-PROJ-TOOL" assert data["customer_name"] is None assert data["lines"] == [] assert not TOOL_TASK_DATA_OMIT.intersection(data.keys()) -def test_task_projection_internal_keeps_status_fields(app): - """TOOL_INTERNAL 保留 create_task 复用场景所需的内部状态字段。""" +def test_task_projection_internal_keeps_stage_fields(app): + """TOOL_INTERNAL 保留 OT 流程阶段字段,复核旧投影不再作为 Notice 字段。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-PROJ-INT", - review_status="parse_review", - source_type="manual", + task = ShippingOrderTask( + task_no="OT-PROJ-INT", user_id=1, + stage="parse_review", + source_type="direct_pdf", ) data = serialize_task(task, TaskProjection.TOOL_INTERNAL) - assert "review_status" in data - assert data["review_status"] == "parse_review" + assert data["current_step"] == "parse_review" def test_resolve_task_from_payload_by_conversation_id_single_active_task(app): """conversation_id 仅在同会话只有一票可操作任务时允许回退。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-CONV-1", + task = ShippingOrderTask( + task_no="OT-CONV-1", user_id=1, conversation_id="conv-abc", - source_type="manual", + source_type="direct_pdf", ) from app import db @@ -182,7 +242,7 @@ def test_resolve_task_from_payload_by_conversation_id_single_active_task(app): resolved = resolve_task_from_payload({"conversation_id": "conv-abc"}) assert resolved is not None - assert resolved.task_no == "SN-CONV-1" + assert resolved.task_no == "OT-CONV-1" assert extract_task_no_from_text("请处理 SN-20260617-ABCDEF01 这票") == "SN-20260617-ABCDEF01" @@ -194,15 +254,15 @@ def test_resolve_task_from_payload_rejects_ambiguous_conversation_id(app): db.session.add_all( [ - ShippingNotice( - task_no="SN-CONV-MULTI-1", + ShippingOrderTask( + task_no="OT-CONV-MULTI-1", user_id=1, conversation_id="conv-multi", - source_type="manual", + source_type="direct_pdf", ), - ShippingNotice( - task_no="SN-CONV-MULTI-2", + ShippingOrderTask( + task_no="OT-CONV-MULTI-2", user_id=1, conversation_id="conv-multi", - source_type="manual", + source_type="direct_pdf", ), ] ) @@ -211,10 +271,10 @@ def test_resolve_task_from_payload_rejects_ambiguous_conversation_id(app): assert resolve_task_from_payload({"conversation_id": "conv-multi"}) is None resolved = resolve_task_from_payload( - {"conversation_id": "conv-multi", "task_id": "SN-CONV-MULTI-1"} + {"conversation_id": "conv-multi", "task_id": "OT-CONV-MULTI-1"} ) assert resolved is not None - assert resolved.task_no == "SN-CONV-MULTI-1" + assert resolved.task_no == "OT-CONV-MULTI-1" def test_task_can_handle_only_creator(app): @@ -252,24 +312,13 @@ def test_get_task_for_user_rejects_null_owner(app): get_task_visible_to_user, ) - orphan = ShippingNotice( - task_no="SN-NULL-OWNER", - source_type="manual", - user_id=None, - ) - owned = ShippingNotice( - task_no="SN-OWNED", - source_type="manual", - user_id=7, - ) - db.session.add_all([orphan, owned]) + owned = ShippingOrderTask(task_no="OT-OWNED", user_id=7, source_type="direct_pdf") + db.session.add(owned) db.session.commit() - assert get_task_for_user("SN-NULL-OWNER", 7) is None - assert get_task_for_user("SN-OWNED", 7) is not None - assert get_task_for_user("SN-OWNED", 8) is None - assert get_task_visible_to_user("SN-OWNED", 8, is_admin=True) is not None - assert get_task_visible_to_user("SN-NULL-OWNER", 7, is_admin=True) is not None + assert get_task_for_user("OT-OWNED", 7) is not None + assert get_task_for_user("OT-OWNED", 8) is None + assert get_task_visible_to_user("OT-OWNED", 8, is_admin=True) is not None def test_serialize_task_summary_enriches_todo_and_can_handle(app): @@ -278,24 +327,21 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app): from app import db from app.services.shipping_notice.query_service import serialize_task_summary - task = ShippingNotice( - task_no="SN-ENRICH-1", - review_status="parse_review", + task = ShippingOrderTask( + task_no="OT-ENRICH-1", user_id=11, + stage="parse_review", pending_human_reason="low_confidence", - source_type="manual", - user_id=11, - export_file_name="a.xlsx", - export_file_path="/tmp/a.xlsx", + source_type="direct_pdf", ) db.session.add(task) db.session.commit() data = serialize_task_summary(task, viewer_user_id=11) - assert data["todo_category"] == "review" + assert data["todo_category"] == "in_progress" assert data["created_by"] == 11 assert data["can_handle"] is True - assert data["ui_state"]["checkpoint"]["code"] == "parse_review" - assert data["artifact_summary"]["export_file_name"] == "a.xlsx" + assert data["ui_state"]["checkpoint"]["code"] == "order_freeze" + assert data["artifact_summary"] is None no_viewer = serialize_task_summary(task) assert "can_handle" not in no_viewer @@ -305,28 +351,58 @@ def test_serialize_task_summary_projects_only_current_notice_line_facts(app): """同 PO 的多个 business_no 必须各自投影本通知的项次、料号、数量和库存。""" with app.app_context(): from app import db - from app.models import ShippingNoticeLine, ShippingNoticeLineInventoryMatch + from app.models import ( + ShippingNoticeLine, ShippingNoticeLineInventoryMatch, + ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask, + ) from app.services.shipping_notice.query_service import serialize_task_summary - first = ShippingNotice(task_no='SN-NOTICE-1', business_no='WVC26082301', source_type='manual', user_id=11) - second = ShippingNotice(task_no='SN-NOTICE-2', business_no='WVC26082302', source_type='manual', user_id=11) + first_task = ShippingOrderTask(task_no='OT-NOTICE-1', user_id=11) + second_task = ShippingOrderTask(task_no='OT-NOTICE-2', user_id=11) + db.session.add_all([first_task, second_task]); db.session.flush() + first_snapshot = ShippingOrderSnapshot( + task_id=first_task.id, extraction_id=1, schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + second_snapshot = ShippingOrderSnapshot( + task_id=second_task.id, extraction_id=2, schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + db.session.add_all([first_snapshot, second_snapshot]); db.session.flush() + first_snapshot_line = ShippingOrderSnapshotLine( + snapshot_id=first_snapshot.id, position=0, line_no=1, field_values_json={}, + ) + second_snapshot_line = ShippingOrderSnapshotLine( + snapshot_id=second_snapshot.id, position=0, line_no=1, field_values_json={}, + ) + db.session.add_all([first_snapshot_line, second_snapshot_line]); db.session.flush() + first = ShippingNotice( + task_no='SN-NOTICE-1', business_no='WVC26082301', source_type='manual', user_id=11, + order_task_id=first_task.id, + ) + second = ShippingNotice( + task_no='SN-NOTICE-2', business_no='WVC26082302', source_type='manual', user_id=11, + order_task_id=second_task.id, + ) + first_task.order_snapshot_id = first_snapshot.id + second_task.order_snapshot_id = second_snapshot.id db.session.add_all([first, second]); db.session.flush() db.session.add_all([ ShippingNoticeLine( - notice_id=first.id, position=1, line_key='LINE-1', part_number='PART-FIRST', - reservation_id='RES-1', required_qty='12', field_values_json={'line_no': '00010'}, + notice_id=first.id, snapshot_line_id=first_snapshot_line.id, position=1, line_no=1, + part_number='PART-FIRST', reservation_id='RES-1', required_qty='12', field_values_json={}, ), ShippingNoticeLine( - notice_id=second.id, position=1, line_key='LINE-2', part_number='PART-SECOND', - reservation_id='RES-2', required_qty='8', field_values_json={'line_no': '00020'}, + notice_id=second.id, snapshot_line_id=second_snapshot_line.id, position=1, line_no=1, + part_number='PART-SECOND', reservation_id='RES-2', required_qty='8', field_values_json={}, ), ShippingNoticeLineInventoryMatch( - task_id=first.id, line_key='LINE-1', match_result='matched', inventory_status='ready', - available_qty='20', shortage_qty='0', is_current=True, + task_id=first_task.id, snapshot_line_id=first_snapshot_line.id, line_no=1, + match_result='matched', inventory_status='ready', available_qty='20', shortage_qty='0', is_current=True, ), ShippingNoticeLineInventoryMatch( - task_id=second.id, line_key='LINE-2', match_result='matched', inventory_status='ready', - available_qty='9', shortage_qty='0', is_current=True, + task_id=second_task.id, snapshot_line_id=second_snapshot_line.id, line_no=1, + match_result='matched', inventory_status='ready', available_qty='9', shortage_qty='0', is_current=True, ), ]) db.session.commit() @@ -335,7 +411,7 @@ def test_serialize_task_summary_projects_only_current_notice_line_facts(app): assert data['business_no'] == 'WVC26082301' assert data['notice_line_summary'] == [{ - 'line_no': '00010', 'line_no_source': 'field', 'part_number': 'PART-FIRST', + 'line_no': 1, 'part_number': 'PART-FIRST', 'customer_part_number': None, 'reservation_id': 'RES-1', 'shipment_qty': '12.00000000', 'available_qty': '20', 'shortage_qty': '0', 'inventory_status': 'ready', @@ -358,8 +434,8 @@ def test_freight_notice_groups_split_same_po_by_business_no_and_owner(app): other = with_po('SN-GROUP-4', 'WYC26082499', 99) db.session.add_all([first, second, no_business, other]); db.session.flush() db.session.add_all([ - ShippingNoticeLine(notice_id=first.id, position=1, line_key='G1', part_number='PART-A', reservation_id='R1', required_qty='2', field_values_json={'line_no': '00010'}), - ShippingNoticeLine(notice_id=second.id, position=1, line_key='G2', part_number='PART-B', reservation_id='R2', required_qty='3', field_values_json={'line_no': '00020'}), + ShippingNoticeLine(notice_id=first.id, snapshot_line_id=1, position=1, line_no=1, part_number='PART-A', reservation_id='R1', required_qty='2', field_values_json={}), + ShippingNoticeLine(notice_id=second.id, snapshot_line_id=2, position=1, line_no=1, part_number='PART-B', reservation_id='R2', required_qty='3', field_values_json={}), ]) db.session.commit() @@ -387,9 +463,6 @@ def test_freight_notice_groups_exposes_per_notice_upload_error(app): first = ShippingNotice(task_no='SN-GROUP-ERR-1', business_no='WYC26082401', source_type='manual', user_id=11) db.session.add(first); db.session.flush() - first.upload_status = 'failed' - first.upload_error_code = 'RPA_UPLOAD_FAILED' - first.upload_error_message = '货代平台拒绝:凭证无效' db.session.commit() original_header_reader = query_service.current_header_field_values_or_empty @@ -401,9 +474,10 @@ def test_freight_notice_groups_exposes_per_notice_upload_error(app): item = result['items'][0] assert item['business_no'] == 'WYC26082401' - assert item['upload_status'] == 'failed' - assert item['upload_error_code'] == 'RPA_UPLOAD_FAILED' - assert item['upload_error_message'] == '货代平台拒绝:凭证无效' + # 没有 UploadAttempt 就没有上传结果,Notice 历史投影不再作为事实来源。 + assert item['upload_status'] is None + assert item['upload_error_code'] is None + assert item['upload_error_message'] is None def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projection_is_unavailable(app): @@ -413,20 +487,23 @@ def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projecti from app.models import ShippingOrderSnapshot from app.services.shipping_notice import query_service - first = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-1', business_no='WYC26082411', source_type='manual', user_id=11) - second = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-2', business_no='WYC26082412', source_type='manual', user_id=11) + first_task = ShippingOrderTask(task_no='OT-GROUP-SNAPSHOT-1', user_id=11, source_type='direct_pdf') + second_task = ShippingOrderTask(task_no='OT-GROUP-SNAPSHOT-2', user_id=11, source_type='direct_pdf') + db.session.add_all([first_task, second_task]); db.session.flush() + first = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-1', business_no='WYC26082411', source_type='manual', user_id=11, order_task_id=first_task.id) + second = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-2', business_no='WYC26082412', source_type='manual', user_id=11, order_task_id=second_task.id) db.session.add_all([first, second]); db.session.flush() - for task in (first, second): + for task, owner in ((first, first_task), (second, second_task)): snapshot = ShippingOrderSnapshot( - task_id=task.id, - extraction_id=task.id, + task_id=owner.id, + extraction_id=owner.id, schema_version_id=1, order_data_version=1, header_values_json={}, customer_po_number='ZNB-16754796', ) db.session.add(snapshot); db.session.flush() - task.order_snapshot_id = snapshot.id + owner.order_snapshot_id = snapshot.id db.session.commit() original_header_reader = query_service.current_header_field_values_or_empty @@ -504,46 +581,86 @@ def test_freight_notice_groups_upload_mode_reads_attempt_not_stale_column(app): def test_list_my_todos_and_count_buckets(app): - """list_my_todos 按 bucket 分类;count 徽标与 pending 一致。""" + """待办按 OT 复核事实和 Notice 上传事实分类;count 徽标与 pending 一致。""" with app.app_context(): from app import db from app.services.shipping_notice.query_service import count_my_todos, list_my_todos owner = 55 - review = ShippingNotice( - task_no="SN-TODO-REVIEW", - review_status="parse_review", - pending_human_reason="low_confidence", - source_type="manual", + review = ShippingOrderTask( + task_no="OT-TODO-REVIEW", + pending_human_reason="rpa_exhausted", + source_type="direct_pdf", user_id=owner, ) + upload_order = ShippingOrderTask( + task_no="OT-TODO-UPLOAD", source_type="direct_pdf", user_id=owner, + ) + done_order = ShippingOrderTask( + task_no="OT-TODO-DONE", source_type="direct_pdf", user_id=owner, + ) upload = ShippingNotice( task_no="SN-TODO-UPLOAD", source_type="manual", user_id=owner, - export_file_path="/tmp/u.xlsx", - export_file_name="u.xlsx", ) done = ShippingNotice( task_no="SN-TODO-DONE", source_type="manual", user_id=owner, - upload_status="uploaded", ) - other = ShippingNotice( - task_no="SN-TODO-OTHER", - review_status="parse_review", - pending_human_reason="low_confidence", - source_type="manual", + other = ShippingOrderTask( + task_no="OT-TODO-OTHER", + pending_human_reason="rpa_exhausted", + source_type="direct_pdf", user_id=99, ) - db.session.add_all([review, upload, done, other]) + db.session.add_all([review, upload_order, done_order, upload, done, other]) + template = ShippingExcelTemplate( + template_code='TODO', display_name='Todo', version=1, status='published', + storage_bucket='test', storage_key='todo.xlsx', original_filename='todo.xlsx', + file_checksum='a' * 64, definition_json={}, + ) + profile = ShippingInventoryParsingProfile( + profile_code='TODO', display_name='Todo', version=1, status='published', + file_format='xlsx', definition_json={}, + ) + schema = ShippingOrderSchema(schema_code='TODO', display_name='Todo') + db.session.add_all([template, profile, schema]) + db.session.flush() + version = ShippingOrderSchemaVersion( + schema_id=schema.id, version=1, status='published', definition_json={}, + ) + db.session.add(version) + db.session.flush() + extraction = ShippingOrderExtraction( + schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + upload.order_task_id = upload_order.id + done.order_task_id = done_order.id + def add_artifact(notice, *, artifact_no: str, status: str) -> ShippingExportArtifact: + """为 Notice 建立待办分类所需的最小正式 Excel Artifact。""" + artifact = ShippingExportArtifact( + artifact_no=artifact_no, task_id=notice.id, template_id=template.id, + order_schema_version_id=version.id, order_extraction_id=extraction.id, + inventory_parsing_profile_id=profile.id, input_checksum='c' * 64, + file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx', + file_checksum='d' * 64, file_size=1, status=status, + ) + db.session.add(artifact) + return artifact + + upload_artifact = add_artifact(upload, artifact_no='ART-TODO-UPLOAD', status='ready') + done_artifact = add_artifact(done, artifact_no='ART-TODO-DONE', status='uploaded') + db.session.flush() db.session.commit() pending = list_my_todos(owner, bucket="pending", page=1, page_size=20) assert pending["total"] == 2 assert {item["task_no"] for item in pending["items"]} == { - "SN-TODO-REVIEW", + "OT-TODO-REVIEW", "SN-TODO-UPLOAD", } assert all(item["can_handle"] is True for item in pending["items"]) @@ -560,7 +677,7 @@ def test_list_my_todos_and_count_buckets(app): admin_pending = list_my_todos(owner, bucket="pending", is_admin=True) assert admin_pending["total"] >= 3 other_item = next( - item for item in admin_pending["items"] if item["task_no"] == "SN-TODO-OTHER" + item for item in admin_pending["items"] if item["task_no"] == "OT-TODO-OTHER" ) assert other_item["can_handle"] is False @@ -661,6 +778,75 @@ def test_list_my_todos_only_returns_stream_current_case_when_legacy_case_is_stil assert original.case_no not in review_case_nos +def test_reparse_document_with_reviewable_candidate_stays_order_review(app): + """ + 回归 doc67:重解析(reparse_of_run_id 非空)终态切换未跑时,Stream.current_case + 仍是空的旧 Case(candidate_id=None),但同 Document 已存在当前可复核 Candidate。 + 此时工作台必须显示「订单复核」,不能被空的旧 Case 压回「接收解析」。 + """ + with app.app_context(): + from app import db + from app.models import ShippingOrderCandidate + from app.services.shipping_notice.order_extraction_plan import ( + ensure_order_extraction_plan, + ) + from app.services.shipping_notice.order_extraction_run_service import ( + transition_order_extraction_run, + ) + from app.services.shipping_notice.order_review_disposition_service import ( + reparse_case_document, + ) + from app.services.shipping_notice.order_review_service import ( + ensure_run_review_cases, + ) + from app.services.shipping_notice.query_service import list_my_todos + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + + user, agent, session, intake, document = _seed_run_input(suffix='DOC67-REPARSE') + source = _materialized_run(user=user, agent=agent, session=session, intake=intake) + # 初始解析:无 Candidate 的 Case 成为当前版本(case14 空旧 Case 语义)。 + original = ensure_run_review_cases(run=source)[0] + assert original.candidate_id is None + transition_order_extraction_run(source, target_status='processing') + transition_order_extraction_run(source, target_status='review_required', result={}) + + replacement_run, _ = reparse_case_document( + user_id=user.id, case_no=original.case_no, reason='rule_updated', + ) + ensure_order_extraction_plan(replacement_run) + # 重解析 Run 产生当前可复核 Candidate(candidate13 语义);finalizer 未切换当前 Case。 + db.session.add(ShippingOrderCandidate( + candidate_no='CAND-DOC67', + intake_id=int(intake.id), + primary_document_id=document.id, + candidate_key='doc67-reparse', + order_extraction_run_id=replacement_run.id, + )) + db.session.commit() + for unit in replacement_run.extraction_plan.units: + unit.status = 'candidate_ready' + db.session.commit() + replacement = ensure_run_review_cases(run=replacement_run)[0] + # 关键:不调用 activate_review_case,模拟重解析终态切换未跑 → case19 未成为当前。 + assert replacement.candidate_id is not None + assert replacement.case_no != original.case_no + + pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50) + review_case_nos = { + item['review_case_no'] + for item in pending['items'] + if item.get('item_kind') == 'review_case' + } + # 当前 Case 仍是空的旧 Case;同 Document 已有可复核 Candidate → 必须订单复核。 + assert original.case_no in review_case_nos + hit = next(item for item in pending['items'] if item.get('review_case_no') == original.case_no) + assert hit['ui_state']['lifecycle_stage'] == 'order_review' + assert [entry['state'] for entry in hit['ui_state']['lifecycle_entries']] == [ + 'available', 'current', 'unavailable', 'unavailable', 'unavailable', + ] + + def test_open_review_case_without_current_candidate_enters_intake_parse(app): """无当前 Candidate 的开放 Case 仅授权接收解析入口,不授权订单复核。""" with app.app_context(): @@ -793,11 +979,10 @@ def test_list_my_todos_total_and_high_page_are_not_capped(app): # 520 > 旧 limit(500),用于证明截断不再作为 total 来源。 total_tasks = 520 tasks = [ - ShippingNotice( - task_no=f"SN-TODO-PAGE-{index:04d}", - review_status="parse_review", - pending_human_reason="low_confidence", - source_type="manual", + ShippingOrderTask( + task_no=f"OT-TODO-PAGE-{index:04d}", + pending_human_reason="rpa_exhausted", + source_type="direct_pdf", user_id=owner, ) for index in range(total_tasks) @@ -823,79 +1008,74 @@ def test_list_my_todos_total_and_high_page_are_not_capped(app): assert far["items"] == [] -def test_todo_category_lightweight_matches_orm_and_count(app): +def test_todo_category_sql_matches_formal_notice_facts(app): """ 轻量行分类 / SQL CASE 与 ORM task_todo_category 一致;count 徽标与 list total 同源。 断言意图:UNION 分页下推的 SQL 分类不得漂移口径。 """ with app.app_context(): - from types import SimpleNamespace - from app import db from app.services.shipping_notice.query_service import ( _task_todo_category_sql_expr, - _todo_category_from_task_row, count_my_todos, list_my_todos, task_todo_category, ) owner = 88 - fixtures = [ - ShippingNotice( - task_no="SN-LW-REVIEW", - review_status="parse_review", - pending_human_reason="low_confidence", - source_type="manual", - user_id=owner, - ), - ShippingNotice( - task_no="SN-LW-UPLOAD", - source_type="manual", - user_id=owner, - export_file_path="/tmp/lw.xlsx", - export_file_name="lw.xlsx", - ), - ShippingNotice( - task_no="SN-LW-SHORTAGE", - # 不可用 matched:状态机会先落到 ready_export,遮住 shortage 人审分支。 - review_status="shortage_review", - pending_human_reason="shortage", - source_type="manual", - user_id=owner, - ), - ShippingNotice( - task_no="SN-LW-DONE", - upload_status="uploaded", - source_type="manual", - user_id=owner, - ), - ShippingNotice( - task_no="SN-LW-PROGRESS", - source_type="manual", - user_id=owner, - ), + order_tasks = [ + ShippingOrderTask(task_no=f"OT-LW-{key}", source_type="direct_pdf", user_id=owner) + for key in ('UPLOAD', 'DONE') ] - db.session.add_all(fixtures) + fixtures = [ + ShippingNotice(task_no="SN-LW-UPLOAD", source_type="manual", user_id=owner), + ShippingNotice(task_no="SN-LW-DONE", source_type="manual", user_id=owner), + ShippingNotice(task_no="SN-LW-PROGRESS", source_type="manual", user_id=owner), + ] + db.session.add_all([*order_tasks, *fixtures]) + db.session.flush() + fixtures[0].order_task_id = order_tasks[0].id + fixtures[1].order_task_id = order_tasks[1].id + template = ShippingExcelTemplate( + template_code='LW', display_name='LW', version=1, status='published', storage_bucket='test', + storage_key='lw.xlsx', original_filename='lw.xlsx', file_checksum='a' * 64, definition_json={}, + ) + profile = ShippingInventoryParsingProfile( + profile_code='LW', display_name='LW', version=1, status='published', file_format='xlsx', definition_json={}, + ) + schema = ShippingOrderSchema(schema_code='LW', display_name='LW') + db.session.add_all([template, profile, schema]) + db.session.flush() + version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={}) + db.session.add(version) + db.session.flush() + extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted') + db.session.add(extraction) + db.session.flush() + def add_artifact(notice, artifact_no, status): + artifact = ShippingExportArtifact( + artifact_no=artifact_no, task_id=notice.id, template_id=template.id, + order_schema_version_id=version.id, order_extraction_id=extraction.id, + inventory_parsing_profile_id=profile.id, input_checksum='c' * 64, + file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx', + file_checksum='d' * 64, file_size=1, status=status, + ) + db.session.add(artifact) + return artifact + + done_artifact = add_artifact(fixtures[1], 'ART-LW-DONE', 'uploaded') + add_artifact(fixtures[0], 'ART-LW-UPLOAD', 'ready') + db.session.flush() + db.session.add(ShippingUploadAttempt( + artifact_id=done_artifact.id, attempt_no=1, mode='manual', status='succeeded', + idempotency_key='lw-done-upload', + )) db.session.commit() category_expr = _task_todo_category_sql_expr() for task in fixtures: - row = SimpleNamespace( - review_status=task.review_status, - pending_human_reason=task.pending_human_reason, - customer_resolution_status=task.customer_resolution_status, - order_snapshot_id=task.order_snapshot_id, - current_order_extraction_id=task.current_order_extraction_id, - inventory_lines_json=task.inventory_lines_json, - match_status=task.match_status, - export_file_path=task.export_file_path, - upload_status=task.upload_status, - ) expected = task_todo_category(task) - # 轻量路径与 ORM 路径同分类。 - assert _todo_category_from_task_row(row, extractions_with_lines=set()) == expected # SQL CASE 与 ORM 路径同分类,保证 UNION 过滤不漂移。 sql_category = ( db.session.query(category_expr) @@ -905,12 +1085,12 @@ def test_todo_category_lightweight_matches_orm_and_count(app): assert sql_category == expected pending = list_my_todos(owner, bucket="pending", page=1, page_size=50) - assert pending["total"] == 3 + assert pending["total"] == 1 counts = count_my_todos(owner) - assert counts["pending"] == 3 + assert counts["pending"] == 1 assert counts["done"] == 1 assert counts["processing"] == 1 - assert counts["total_pending_badge"] == 3 + assert counts["total_pending_badge"] == 1 def test_serialize_task_detail_workbench_view_drops_editor_fields(app): @@ -919,9 +1099,8 @@ def test_serialize_task_detail_workbench_view_drops_editor_fields(app): from app import db from app.services.shipping_notice.query_service import serialize_task_detail - task = ShippingNotice( - task_no="SN-WORKBENCH-VIEW", source_type="manual", user_id=11, - export_file_name="n.xlsx", export_file_path="/tmp/n.xlsx", + task = ShippingOrderTask( + task_no="OT-WORKBENCH-VIEW", source_type="direct_pdf", user_id=11, ) db.session.add(task) db.session.commit() @@ -934,13 +1113,12 @@ def test_serialize_task_detail_workbench_view_drops_editor_fields(app): # full 保留编辑器重字段;workbench 剔除它们,显著缩小响应体。 for key in ( "lines", "order_header", "order_header_fields", "order_line_fields", - "events", "field_conflicts", ): assert key in full assert key not in wb # workbench 仍保留工作台所需字段(ui_state/stage_context、产物、行摘要)。 - assert wb["ui_state"]["task_no"] == "SN-WORKBENCH-VIEW" + assert wb["ui_state"]["task_no"] == "OT-WORKBENCH-VIEW" assert wb["ui_state"]["stage_context"] is not None - assert wb["artifact_summary"]["export_file_name"] == "n.xlsx" + assert wb["artifact_summary"] is None assert "notice_line_summary" in wb - assert "export_artifacts" in wb + assert "export_artifacts" not in wb diff --git a/backend/tests/test_shipping_notice_reservation_id.py b/backend/tests/test_shipping_notice_reservation_id.py index f6617e61..a3ba82cb 100644 --- a/backend/tests/test_shipping_notice_reservation_id.py +++ b/backend/tests/test_shipping_notice_reservation_id.py @@ -56,6 +56,24 @@ def test_reservation_contract_only_accepts_five_or_ten_digits(): assert not is_valid_reservation_id("12345678901", numeric_only=True) +def test_validated_reservation_id_strips_optional_parenthesized_note(): + """完整数字可带括号备注;括号内容不是预约单号,普通尾随文本仍拒绝。""" + assert validated_reservation_id("3000112934(PENROSE)") == "3000112934" + assert validated_reservation_id("3000112934(PENROSE)") == "3000112934" + assert validated_reservation_id("R2 @3000112934") == "3000112934" + assert validated_reservation_id("R2 @3000112934(PENROSE)") == "3000112934" + assert validated_reservation_id("R2 @3000112934 PENROSE") == "" + assert validated_reservation_id("3000112934 PENROSE") == "" + assert validated_reservation_id("abc3000112934(PENROSE)") == "" + assert validated_reservation_id("00011293") == "" + assert validated_reservation_id("30001129345") == "" + + +def test_validated_reservation_id_rejects_amount_text_as_numeric_token(): + """金额行中的五位整数片段不能被当成 Reservation ID。""" + assert validated_reservation_id("941.76 28,252.80") == "" + + def test_reservation_region_maps_line_when_reservation_label_and_line_number_are_present(): """专用区域只在同一行有 Reservation 语义时提取,并将可靠行号交给正式解析链路。""" assert extract_reservation_from_region_text("Reservation#3000098851 for line#1") == [{ diff --git a/backend/tests/test_shipping_notice_state_machine.py b/backend/tests/test_shipping_notice_state_machine.py index db8cb73a..f478c34c 100644 --- a/backend/tests/test_shipping_notice_state_machine.py +++ b/backend/tests/test_shipping_notice_state_machine.py @@ -8,15 +8,22 @@ tests/test_shipping_notice_state_machine.py from types import SimpleNamespace -from app.models import ShippingNotice +from app.models import ShippingOrderTask from app.services.shipping_notice.constants import ( CP_EXPORT_READY, CP_PARSE_REVIEW, + CP_READY_EXPORT, CP_UPLOADED, PH_LOW_CONF, RS_PARSE_REVIEW, ) -from app.services.shipping_notice.state_machine import CheckpointKind, checkpoint_kind_for, resolve_task_ui_state, validate_registry +from app.services.shipping_notice.state_machine import ( + CheckpointKind, + checkpoint_kind_for, + resolve_task_ui_state, + resolve_task_ui_state_from_fields, + validate_registry, +) def test_validate_registry_has_no_errors() -> None: @@ -34,13 +41,21 @@ def test_checkpoint_kinds_for_stp_stop_points() -> None: def test_resolve_task_ui_state_parse_review(app) -> None: """pending_review + parse_review 应映射为 must_human / parse_review。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-SM-PARSE", + task = ShippingOrderTask( + task_no="OT-SM-PARSE", + user_id=1, review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, - source_type="manual", ) - ui = resolve_task_ui_state(task) + ui = resolve_task_ui_state_from_fields( + review_status=task.review_status, + pending_human_reason=task.pending_human_reason, + customer_resolution_status=None, + order_snapshot_id=None, + match_status=None, + export_file_path=None, + has_dynamic_order_lines=False, + ) assert ui.checkpoint == CP_PARSE_REVIEW assert ui.checkpoint_kind == CheckpointKind.MUST_HUMAN @@ -48,32 +63,44 @@ def test_resolve_task_ui_state_parse_review(app) -> None: def test_resolve_task_ui_state_export_ready(app) -> None: """matched 且已有 export_file_path 应为 wait_manual_upload(待人工上传登记)。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-SM-EXPORT", - source_type="manual", + ui = resolve_task_ui_state_from_fields( + review_status=None, + pending_human_reason=None, + customer_resolution_status=None, + order_snapshot_id=1, + match_status=None, export_file_path="/tmp/shipping-export.xlsx", - export_file_name="shipping-export.xlsx", + has_dynamic_order_lines=False, ) - ui = resolve_task_ui_state(task) assert ui.checkpoint == CP_EXPORT_READY assert ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD assert not hasattr(ui, 'human_options') -def test_resolve_task_ui_state_uploaded_complete(app) -> None: +def test_resolve_task_ui_state_uploaded_complete(app, monkeypatch) -> None: """upload_status=uploaded 应为 complete。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-SM-UPLOADED", - upload_status="uploaded", - source_type="manual", + task = SimpleNamespace(upload_status="uploaded", lifecycle_status="active") + # [FIX] 上传完成由可审计事实 has_verified_upload_success 裁决,不再读取 upload_status 字段。 + monkeypatch.setattr( + 'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success', + lambda _task: True, + ) + ui = resolve_task_ui_state_from_fields( + review_status=None, + pending_human_reason=None, + customer_resolution_status=None, + order_snapshot_id=1, + match_status=None, + export_file_path=None, + has_dynamic_order_lines=False, + upload_req_task=task, ) - ui = resolve_task_ui_state(task) assert ui.checkpoint == CP_UPLOADED assert ui.checkpoint_kind == CheckpointKind.COMPLETE -def test_resolve_with_mocked_simple_namespace_attributes() -> None: +def test_resolve_with_mocked_simple_namespace_attributes(monkeypatch) -> None: """无 DB 会话时可用简易命名空间验证 uploaded 终态分支。""" task = SimpleNamespace( upload_status="uploaded", @@ -87,6 +114,27 @@ def test_resolve_with_mocked_simple_namespace_attributes() -> None: current_order_extraction_id=None, step_payload_json=None, ) + # [FIX] 上传完成由可审计事实 has_verified_upload_success 裁决,不再读取 upload_status 字段。 + monkeypatch.setattr( + 'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success', + lambda _task: True, + ) ui = resolve_task_ui_state(task) # type: ignore[arg-type] assert ui.checkpoint_kind == CheckpointKind.COMPLETE assert ui.checkpoint == CP_UPLOADED + + +def test_order_task_inventory_checkpoint_uses_structured_facts(monkeypatch) -> None: + """OT 库存 JSON 为空时,状态机仍须按 Link/File/Match 事实进入导出准备。""" + from app.models import ShippingOrderTask + from app.services.shipping_notice import state_machine + + task = ShippingOrderTask(task_no='OT-SM-STRUCTURED', user_id=1, stage='inventory_matching') + monkeypatch.setattr(state_machine, '_order_task_inventory_facts', lambda _task: { + 'inventory_ready': True, + 'match_complete': True, + 'match_sufficient': True, + 'has_shortage': False, + }) + + assert state_machine.resolve_task_ui_state(task).checkpoint == CP_READY_EXPORT diff --git a/backend/tests/test_shipping_notice_stp_acceptance.py b/backend/tests/test_shipping_notice_stp_acceptance.py index d3b3109c..65e14055 100644 --- a/backend/tests/test_shipping_notice_stp_acceptance.py +++ b/backend/tests/test_shipping_notice_stp_acceptance.py @@ -8,9 +8,21 @@ tests/test_shipping_notice_stp_acceptance.py from __future__ import annotations +from types import SimpleNamespace + import pytest -from app.models import ShippingNotice, User +from app.models import ( + ShippingExcelTemplate, + ShippingExportArtifact, + ShippingInventoryParsingProfile, + ShippingNotice, + ShippingOrderExtraction, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + ShippingOrderTask, + User, +) from app.services.shipping_notice.constants import ( CP_EXPORT_READY, CP_PARSE_REVIEW, @@ -21,7 +33,32 @@ from app.services.shipping_notice.fulfillment_workflow import try_auto_chain_aft from app.services.shipping_notice.progress_workflow import auto_progress from app.services.shipping_notice.query_service import count_my_todos, list_my_todos from app.services.shipping_notice.state_machine import CheckpointKind, checkpoint_kind_for -from app.services.shipping_notice.ui_state import build_task_ui_state + + +def _seed_export_artifact_view(monkeypatch) -> None: + """Excel 就绪事实只能由正式 Artifact 裁决:屏蔽旧 Notice 文件投影。 + + 生产函数分别经 upload_attempt_service(state_machine.resolve_task_ui_state 本地导入)与 + fulfillment_workflow(模块级 latest_export_artifact / latest_upload_attempt)读取导出产物; + 两处命名空间均需桩化,避免触达真实 Artifact 表。 + """ + artifact = SimpleNamespace(id=0, file_path="/tmp/stp-export.xlsx", file_name="stp-export.xlsx", status="ready") + monkeypatch.setattr( + "app.services.shipping_notice.upload_attempt_service.latest_export_artifact", + lambda _task: artifact, + ) + monkeypatch.setattr( + "app.services.shipping_notice.fulfillment_workflow.latest_export_artifact", + lambda _task: artifact, + ) + monkeypatch.setattr( + "app.services.shipping_notice.upload_attempt_service.latest_upload_attempt", + lambda _task: None, + ) + monkeypatch.setattr( + "app.services.shipping_notice.fulfillment_workflow.latest_upload_attempt", + lambda _task: None, + ) def test_stp_checkpoint_kind_matrix_covers_nine_scenario_stops() -> None: @@ -30,7 +67,7 @@ def test_stp_checkpoint_kind_matrix_covers_nine_scenario_stops() -> None: assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD -def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app) -> None: +def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app, monkeypatch) -> None: """场景:Excel 已生成 → auto_progress 早停(WAIT_MANUAL_UPLOAD)且禁止 upload_to_freight。""" with app.app_context(): from app import db @@ -38,13 +75,15 @@ def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app) app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True task = ShippingNotice( task_no="SN-STP-WAIT-UPLOAD", + business_no="SN-STP-WAIT-UPLOAD", source_type="manual", - export_file_path="/tmp/stp-export.xlsx", - export_file_name="stp-export.xlsx", ) db.session.add(task) db.session.commit() + # Excel 是否就绪只能由 Artifact 事实裁决,不能恢复 Notice 旧文件投影。 + _seed_export_artifact_view(monkeypatch) + result = auto_progress({"task_id": task.task_no, "source": "system"}) assert result["status"] == "ok" assert result.get("checkpoint") == CP_EXPORT_READY @@ -59,11 +98,20 @@ def test_auto_progress_stops_at_must_human_parse_review(app) -> None: from app import db app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True - task = ShippingNotice( - task_no="SN-STP-MUST-HUMAN", + owner = ShippingOrderTask( + task_no="OT-STP-MUST-HUMAN", + user_id=1, + source_type="direct_pdf", review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, + ) + db.session.add(owner) + db.session.flush() + task = ShippingNotice( + task_no="SN-STP-MUST-HUMAN", + business_no="SN-STP-MUST-HUMAN", source_type="manual", + order_task_id=owner.id, ) db.session.add(task) db.session.commit() @@ -83,15 +131,14 @@ def test_try_auto_chain_calls_upload_when_auto_upload_enabled(app, monkeypatch) task = ShippingNotice( task_no="SN-STP-RPA-ON", - match_status="fulfillable", source_type="manual", - line_results_json=[{"line_status": "ok"}], - export_file_path="/tmp/already.xlsx", - export_file_name="already.xlsx", ) db.session.add(task) db.session.commit() + # Excel 就绪由正式 Artifact 投影裁决,且自动生成在既有 Artifact 存在时被跳过。 + _seed_export_artifact_view(monkeypatch) + upload_calls: list[dict] = [] def _fake_upload(payload): @@ -124,15 +171,14 @@ def test_try_auto_chain_skips_upload_when_auto_upload_disabled(app, monkeypatch) task = ShippingNotice( task_no="SN-STP-NO-RPA", - match_status="fulfillable", source_type="manual", - line_results_json=[{"line_status": "ok"}], - export_file_path="/tmp/already.xlsx", - export_file_name="already.xlsx", ) db.session.add(task) db.session.commit() + # Excel 就绪由正式 Artifact 投影裁决,且自动生成在既有 Artifact 存在时被跳过。 + _seed_export_artifact_view(monkeypatch) + upload_calls: list[dict] = [] def _fake_upload(payload): @@ -158,19 +204,22 @@ def test_upload_to_freight_manual_confirm_does_not_hard_reject(app, monkeypatch) """场景:manual_confirm 不再范围外硬拒绝;校验凭据路径可达(mock record_manual_upload)。""" with app.app_context(): from app import db - from types import SimpleNamespace + owner = ShippingOrderTask(task_no="OT-STP-MANUAL-CFM", user_id=1, source_type="direct_pdf") + db.session.add(owner) + db.session.flush() task = ShippingNotice( task_no="SN-STP-MANUAL-CFM", + business_no="SN-STP-MANUAL-CFM", source_type="manual", - export_file_path="/tmp/m.xlsx", - export_file_name="m.xlsx", - inventory_source_status="confirmed", - inventory_source_code="SRC1", + order_task_id=owner.id, ) db.session.add(task) db.session.commit() + # 上传前强制「有可导出 Artifact」,由正式 Artifact 视图裁决,而非 Notice 旧文件投影。 + _seed_export_artifact_view(monkeypatch) + attempt = SimpleNamespace(id=9, artifact_id=3, operator_id=42) monkeypatch.setattr( @@ -231,22 +280,22 @@ def test_upload_to_freight_manual_confirm_ignores_inventory_source_stability(app """ with app.app_context(): from app import db - from types import SimpleNamespace + owner = ShippingOrderTask(task_no="OT-STP-MANUAL-CFM-UNSTABLE", user_id=1, source_type="direct_pdf") + db.session.add(owner) + db.session.flush() task = ShippingNotice( task_no="SN-STP-MANUAL-CFM-UNSTABLE", + business_no="SN-STP-MANUAL-CFM-UNSTABLE", source_type="manual", - export_file_path="/tmp/m.xlsx", - export_file_name="m.xlsx", - inventory_source_status="resolved", - inventory_source_code="SRC1", - inventory_connector_type="crane", - inventory_source_config_version="stale-version", - inventory_routing_fingerprint="stale-fingerprint", + order_task_id=owner.id, ) db.session.add(task) db.session.commit() + # 上传前强制「有可导出 Artifact」,由正式 Artifact 视图裁决,而非 Notice 旧文件投影。 + _seed_export_artifact_view(monkeypatch) + attempt = SimpleNamespace(id=10, artifact_id=3, operator_id=42) # 关键:模拟库存源确实不稳定(真实 is_inventory_source_stable 返回 False)。 @@ -302,19 +351,22 @@ def test_upload_to_freight_manual_confirm_propagates_close_item_failure(app, mon """关键断言:绑定 WorkflowItem 关闭失败须向上抛出,不得吞异常后仍返回成功。""" with app.app_context(): from app import db - from types import SimpleNamespace + owner = ShippingOrderTask(task_no="OT-STP-CLOSE-FAIL", user_id=1, source_type="direct_pdf") + db.session.add(owner) + db.session.flush() task = ShippingNotice( task_no="SN-STP-CLOSE-FAIL", + business_no="SN-STP-CLOSE-FAIL", source_type="manual", - export_file_path="/tmp/m.xlsx", - export_file_name="m.xlsx", - inventory_source_status="confirmed", - inventory_source_code="SRC1", + order_task_id=owner.id, ) db.session.add(task) db.session.commit() + # 上传前强制「有可导出 Artifact」,由正式 Artifact 视图裁决,而非 Notice 旧文件投影。 + _seed_export_artifact_view(monkeypatch) + attempt = SimpleNamespace(id=11, artifact_id=3, operator_id=42) bound_item = SimpleNamespace(lifecycle_status="manual_upload_pending") @@ -388,28 +440,76 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None: db.session.add_all([owner, admin]) db.session.flush() + # 复核系列(mine / other)以 Notice 挂接 OT,复核事实读取 OT 字段。 + mine_owner = ShippingOrderTask( + task_no="OT-STP-OWN", + user_id=owner.id, + source_type="direct_pdf", + review_status=RS_PARSE_REVIEW, + pending_human_reason=PH_LOW_CONF, + ) + upload_owner = ShippingOrderTask(task_no="OT-STP-UPLOAD", user_id=owner.id, source_type="direct_pdf") + other_owner = ShippingOrderTask( + task_no="OT-STP-OTHER", + user_id=admin.id, + source_type="direct_pdf", + review_status=RS_PARSE_REVIEW, + pending_human_reason=PH_LOW_CONF, + ) + db.session.add_all([mine_owner, upload_owner, other_owner]) + db.session.flush() + mine = ShippingNotice( task_no="SN-STP-OWN", user_id=owner.id, - review_status=RS_PARSE_REVIEW, - pending_human_reason=PH_LOW_CONF, source_type="manual", + order_task_id=mine_owner.id, ) waiting_upload = ShippingNotice( task_no="SN-STP-UPLOAD", user_id=owner.id, source_type="manual", - export_file_path="/tmp/own.xlsx", - export_file_name="own.xlsx", + order_task_id=upload_owner.id, ) other = ShippingNotice( task_no="SN-STP-OTHER", user_id=admin.id, - review_status=RS_PARSE_REVIEW, - pending_human_reason=PH_LOW_CONF, source_type="manual", + order_task_id=other_owner.id, ) db.session.add_all([mine, waiting_upload, other]) + db.session.flush() + + # manual_upload 分类必须由正式 Excel Artifact 裁决。 + template = ShippingExcelTemplate( + template_code="STP_TP", display_name="STP template", version=1, status="published", + storage_bucket="test", storage_key="test/stp.xlsx", original_filename="stp.xlsx", + file_checksum="a" * 64, definition_json={}, + ) + profile = ShippingInventoryParsingProfile( + profile_code="STP_PF", display_name="STP profile", version=1, status="published", + file_format="xlsx", definition_json={}, + ) + schema = ShippingOrderSchema(schema_code="STP_SCHEMA", display_name="STP schema") + db.session.add_all([template, profile, schema]) + db.session.flush() + version = ShippingOrderSchemaVersion( + schema_id=schema.id, version=1, status="published", definition_json={}, + ) + db.session.add(version) + db.session.flush() + extraction = ShippingOrderExtraction( + schema_version_id=version.id, input_snapshot_hash="b" * 64, status="accepted", + ) + db.session.add(extraction) + db.session.flush() + db.session.add(ShippingExportArtifact( + artifact_no="ART-STP-UPLOAD", task_id=waiting_upload.id, template_id=template.id, + order_schema_version_id=version.id, order_extraction_id=extraction.id, + inventory_parsing_profile_id=profile.id, input_checksum="c" * 64, + file_path="/tmp/stp-own.xlsx", file_name="stp-own.xlsx", + file_checksum="d" * 64, file_size=1, status="ready", + )) db.session.commit() pending = list_my_todos(owner.id, bucket="pending", page=1, page_size=50) diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py index fa52d7c7..cc4dfa20 100644 --- a/backend/tests/test_shipping_notice_tools.py +++ b/backend/tests/test_shipping_notice_tools.py @@ -2,7 +2,7 @@ backend/tests/test_shipping_notice_tools.py 用途:验证货代 Tool API 的鉴权、解析、库存、匹配、导出、RPA 与状态契约。 -依赖:Flask 测试客户端、ShippingNotice/Customer、货代 workflow 测试辅助。 +依赖:Flask 测试客户端、ShippingNotice/ShippingOrderTask/Customer、货代 workflow 测试辅助。 逻辑:本模块聚焦客户确认后的历史 Tool 行为;客户 Gate 的阻断与确认分支由专项测试覆盖。 """ @@ -13,16 +13,32 @@ import pytest from app import db from app.models import ( - ChatLog, ShippingCustomer, ShippingInventoryField, ShippingInventoryRoutingRule, - ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingNotice, - ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, - ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, - ShippingOrderSnapshot, ShippingOrderSnapshotLine, - ShippingTaskEvent, ShippingTaskInventoryLink, + Agent, + ChatLog, + ChatSession, + ShippingCustomer, + ShippingInventoryField, + ShippingInventoryRoutingRule, + ShippingInventoryFile, + ShippingInventoryRoutingRuleCondition, + ShippingNotice, + ShippingOrderExtraction, + ShippingOrderField, + ShippingOrderFieldDecision, + ShippingOrderFieldValue, + ShippingOrderLine, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + ShippingOrderSnapshot, + ShippingOrderSnapshotLine, + ShippingOrderTask, + ShippingTaskEvent, + ShippingTaskInventoryLink, + User, ) from app.services.shipping_notice.match import match_notice_lines from app.services.shipping_notice.order_schema import service as order_schema_service -from tests.conftest import inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source +from tests.conftest import confirm_test_customer_resolution, inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source def _tool_headers(app): @@ -34,46 +50,63 @@ def _tool_headers(app): } -def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation_id: str, quantity: int) -> None: +def _seed_test_user(*, username: str) -> int: + """创建测试用户并返回主键,供 OT 建单与能力强令牌使用。""" + user = User(username=username, email=f"{username}@example.test", password_hash='x') + db.session.add(user) + db.session.flush() + return int(user.id) + + +def _attach_dynamic_order(task: ShippingOrderTask, *, part_number: str, reservation_id: str, quantity: int) -> None: """为库存/RPA Tool 测试创建已接受 FieldValue,避免固定任务行投影绕过订单真相门禁。""" - order_schema_service.initialize_schema({'display_name': 'Tool 动态订单'}, actor_id=None) - fields = { - code: order_schema_service.save_field( - {'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None, + version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none() + if version is None: + order_schema_service.initialize_schema({'display_name': 'Tool 动态订单'}, actor_id=None) + fields = { + code: order_schema_service.save_field( + {'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None, + ) + for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal')) + } + draft = order_schema_service.create_draft({}, actor_id=None) + purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'} + configs = [{ + 'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code], + 'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal', + 'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'], + 'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True}, + 'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text', + } for code, field in fields.items()] + saved = order_schema_service.save_draft( + draft['id'], {'fields': configs, 'expected_lock_version': draft['lock_version']}, actor_id=None, ) - for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal')) + published = order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) + version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() + + field_ids = { + str(item['field_code']): str(item['field_id']) + for item in (version.definition_json or {}).get('fields') or [] } - draft = order_schema_service.create_draft({}, actor_id=None) - purposes = {'part_number': 'part_number', 'reservation_id': 'reservation_id', 'qty': 'quantity'} - configs = [{ - 'field_id': field['id'], 'display_name': code, 'business_purpose': purposes[code], - 'required': True, 'aliases': [], 'normalizer_key': 'uppercase_trim' if code != 'qty' else 'decimal', - 'validator_keys': ['reservation_id'] if code == 'reservation_id' else ['positive_decimal'] if code == 'qty' else ['non_empty'], - 'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True}, - 'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text', - } for code, field in fields.items()] - saved = order_schema_service.save_draft( - draft['id'], {'fields': configs, 'expected_lock_version': draft['lock_version']}, actor_id=None, - ) - published = order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) + extraction = ShippingOrderExtraction( - task_id=task.id, schema_version_id=published['id'], input_snapshot_hash='t' * 64, status='accepted', + task_id=task.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted', ) db.session.add(extraction) db.session.flush() - line = ShippingOrderLine(extraction_id=extraction.id, position=0) + line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1) db.session.add(line) db.session.flush() values = {'part_number': part_number, 'reservation_id': reservation_id, 'qty': quantity} for code, value in values.items(): decision = ShippingOrderFieldDecision( - extraction_id=extraction.id, line_id=line.id, field_id=fields[code]['id'], decision_status='accepted', + extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_status='accepted', supporting_observation_ids_json=[], resolved_value_json=value, ) db.session.add(decision) db.session.flush() db.session.add(ShippingOrderFieldValue( - extraction_id=extraction.id, line_id=line.id, field_id=fields[code]['id'], decision_id=decision.id, + extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_id=decision.id, value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None, value_json=value, )) @@ -81,14 +114,14 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation # RPA/库存链路只消费冻结订单快照;此辅助保留动态字段测试证据的同时 # 建立最小履约真相,避免旧测试绕过阶段 1 门禁。 snapshot = ShippingOrderSnapshot( - task_id=task.id, extraction_id=extraction.id, schema_version_id=published['id'], + task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id, order_data_version=task.order_data_version or 1, rule_versions_json={'fulfillment_policy': { 'code': 'SHIP_AVAILABLE_ROLLING_V1', 'version': 1, 'definition': {'field_bindings': [ - {'capability_code': 'fulfillment.part_number', 'field_id': fields['part_number']['id'], 'scope': 'line'}, - {'capability_code': 'fulfillment.reservation_identity', 'field_id': fields['reservation_id']['id'], 'scope': 'line'}, - {'capability_code': 'fulfillment.quantity', 'field_id': fields['qty']['id'], 'scope': 'line'}, + {'capability_code': 'fulfillment.part_number', 'field_id': field_ids['part_number'], 'scope': 'line'}, + {'capability_code': 'fulfillment.reservation_identity', 'field_id': field_ids['reservation_id'], 'scope': 'line'}, + {'capability_code': 'fulfillment.quantity', 'field_id': field_ids['qty'], 'scope': 'line'}, ]}, }}, header_values_json={}, @@ -96,26 +129,41 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation db.session.add(snapshot) db.session.flush() db.session.add(ShippingOrderSnapshotLine( - snapshot_id=snapshot.id, position=0, part_number=part_number, reservation_id=reservation_id, + snapshot_id=snapshot.id, position=0, line_no=1, part_number=part_number, reservation_id=reservation_id, qty=quantity, field_values_json={ - str(fields['part_number']['id']): part_number, - str(fields['reservation_id']['id']): reservation_id, - str(fields['qty']['id']): quantity, + str(field_ids['part_number']): part_number, + str(field_ids['reservation_id']): reservation_id, + str(field_ids['qty']): quantity, }, )) task.order_snapshot_id = snapshot.id db.session.flush() +def _confirm_test_task_customer(task: ShippingOrderTask) -> None: + """为 RPA 回调/超时链路补齐已确认客户,避免自动推进被客户门禁提前阻断。""" + customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none() + if customer is None: + customer = ShippingCustomer( + standard_name='RPA 直接回调测试客户', short_code='RPC', status='active', + ) + db.session.add(customer) + db.session.flush() + extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) + confirm_test_customer_resolution(task, customer=customer, extraction=extraction) + task._test_customer_confirmed = True + + def test_shipping_notice_tool_auth_accepts_dedicated_key(app, client): with app.app_context(): app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "shipping-secret" app.config["INTEGRATION_API_KEY"] = "" + user_id = _seed_test_user(username='auth-dedicated') res = client.post( "/api/shipping-notice/tools/create_task", headers={"Content-Type": "application/json", "X-Integration-Key": "shipping-secret"}, - json={"source_type": "manual"}, + json={"source_type": "direct_pdf", "user_id": user_id}, ) assert res.status_code == 200 @@ -126,11 +174,12 @@ def test_shipping_notice_tool_auth_falls_back_to_integration_key(app, client): with app.app_context(): app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "" app.config["INTEGRATION_API_KEY"] = "integration-secret" + user_id = _seed_test_user(username='auth-integration') res = client.post( "/api/shipping-notice/tools/create_task", headers={"Content-Type": "application/json", "X-Integration-Key": "integration-secret"}, - json={"source_type": "manual"}, + json={"source_type": "direct_pdf", "user_id": user_id}, ) assert res.status_code == 200 @@ -145,7 +194,7 @@ def test_shipping_notice_tool_auth_reports_missing_config(app, client): res = client.post( "/api/shipping-notice/tools/create_task", headers={"Content-Type": "application/json", "X-Integration-Key": "any"}, - json={"source_type": "manual"}, + json={"source_type": "direct_pdf"}, ) assert res.status_code == 503 @@ -157,7 +206,7 @@ def test_parse_notice_tool_is_removed(app, client): response = client.post( "/api/shipping-notice/tools/parse_notice", headers=_tool_headers(app), - json={"task_id": "SN-REMOVED"}, + json={"task_id": "OT-REMOVED"}, ) assert response.status_code == 404 @@ -179,14 +228,14 @@ def test_direct_excel_tool_dispatches_to_formal_auto_progress(monkeypatch): ) result = fulfillment_workflow.generate_excel({ - 'task_id': 'SN-FORMAL-EXCEL-ONLY', + 'task_id': 'OT-FORMAL-EXCEL-ONLY', 'operator_id': 7, 'idempotency_key': 'formal-excel-only', }) assert result['status'] == 'running' assert submitted == { - 'task_no': 'SN-FORMAL-EXCEL-ONLY', + 'task_no': 'OT-FORMAL-EXCEL-ONLY', 'trigger': 'tool_api_generate_excel', 'expected_version': None, 'idempotency_key': 'formal-excel-only', @@ -222,20 +271,36 @@ def test_match_notice_lines_reports_progress(): def test_contract_get_task_status_accepts_task_no_anchor(app, client): - """契约:用户输入 SN-... 时,Dify 应直连 get_task_status 并锚定对应任务。""" + """契约:用户输入 OT-... 时,Dify 应直连 get_task_status 并锚定对应任务。""" + from app.services.shipping_notice.chat_tool_capability import issue_chat_capability + headers = _tool_headers(app) + with app.app_context(): + app.config["SHIPPING_CHAT_CAPABILITY_SECRET"] = "test-capability-secret" + user_id = _seed_test_user(username='status-anchor') + agent = Agent(name='shipping-agent', agent_code='shipping_notice_status_anchor') + db.session.add(agent) + db.session.flush() + session = ChatSession(session_id='status-anchor-session', user_id=user_id, agent_id=agent.id) + db.session.add(session) + db.session.commit() + session_id = session.session_id + agent_id = int(agent.id) create_res = client.post( "/api/shipping-notice/tools/create_task", headers=headers, - json={"source_type": "manual", "raw_content": "客户:ACME 料号A001 x 10"}, + json={"source_type": "direct_pdf", "user_id": user_id, "conversation_id": session_id, + "raw_content": "客户:ACME 料号A001 x 10"}, ) task_id = create_res.get_json()["task_id"] + token = issue_chat_capability(user_id=user_id, session_id=session_id, agent_id=agent_id, task_no=task_id) + status_res = client.post( "/api/shipping-notice/tools/get_task_status", headers=headers, - json={"task_no": task_id}, + json={"task_no": task_id, "shipping_chat_capability_token": token}, ) data = status_res.get_json() @@ -273,12 +338,11 @@ def test_confirm_inventory_source_route_is_removed(app, client): """库存源人工确认已下线,任何旧 Tool 写入口均不得可达。""" headers = _tool_headers(app) with app.app_context(): - task = ShippingNotice( - task_no="SN-HTTP-CONFIRM-SRC", - source_type="manual", + task = ShippingOrderTask( + task_no="OT-HTTP-CONFIRM-SRC", + user_id=1, + source_type="eml", pending_human_reason="inventory_source_unresolved", - ship_to="Dublin", - lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}], ) db.session.add(task) db.session.commit() @@ -286,7 +350,7 @@ def test_confirm_inventory_source_route_is_removed(app, client): res = client.post( "/api/shipping-notice/tools/confirm_inventory_source", headers=headers, - json={"task_id": "SN-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"}, + json={"task_id": "OT-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"}, ) assert res.status_code == 404 @@ -304,91 +368,13 @@ def test_static_openapi_snapshot_contains_shipping_contract_keywords(): assert "match_inventory" not in spec_text -@pytest.mark.parametrize("decision", ["confirm_inventory_mapping", "correct_inventory_mapping"]) -def test_legacy_inventory_mapping_decisions_are_rejected(app, client, decision): - """已启用库存站点不得通过任务决策重开旧列映射路径。""" - headers = _tool_headers(app) - with app.app_context(): - task = ShippingNotice(task_no=f"SN-LEGACY-MAP-{decision}", source_type="manual") - db.session.add(task) - db.session.commit() - - response = client.post( - "/api/shipping-notice/tools/submit_decision", - headers=headers, - json={"task_id": f"SN-LEGACY-MAP-{decision}", "decision": decision}, - ) - - assert response.status_code == 200 - body = response.get_json() - # These decisions must never reopen manual mapping or mutate the task. - assert body["status"] == "failed" - assert "已发布解析方案" in body["message"] - - -def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app, client, tmp_path): - """重新上传库存只重置正式库存结果,不进入任务级字段映射。""" - headers = _tool_headers(app) - with app.app_context(): - task = ShippingNotice( - task_no="SN-REUPLOAD-INVENTORY", - source_type="manual", - inventory_lines_json=[{"part_number": "A001", "available_qty": 10}], - match_status="fulfillable", - line_results_json=[{"part_number": "A001"}], - shortage_json={"lines": []}, - export_file_path=str(tmp_path / "shipment.xlsx"), - export_file_name="shipment.xlsx", - ) - db.session.add(task) - db.session.flush() - inventory_file = ShippingInventoryFile( - inventory_file_no="SIF-REUPLOAD-001", - storage_path=str(tmp_path / "inventory.xlsx"), - source_file_name="inventory.xlsx", - ) - db.session.add(inventory_file) - db.session.flush() - link = ShippingTaskInventoryLink( - task_id=task.id, - inventory_file_id=inventory_file.id, - link_role="owner", - ) - db.session.add(link) - db.session.commit() - - response = client.post( - "/api/shipping-notice/tools/submit_decision", - headers=headers, - json={"task_id": "SN-REUPLOAD-INVENTORY", "decision": "reparse_inventory"}, - ) - - assert response.status_code == 200 - body = response.get_json() - assert body["status"] == "needs_human" - assert body["checkpoint"] == "upload_req" - assert "human_options" not in body - with app.app_context(): - task = ShippingNotice.query.filter_by(task_no="SN-REUPLOAD-INVENTORY").one() - link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id).one() - assert link.is_active is False - assert task.pending_human_reason == "inv_unavail" - assert task.pending_human_reason == "inv_unavail" - assert task.inventory_lines_json is None - assert task.match_status is None - assert task.line_results_json is None - assert task.shortage_json is None - assert task.export_file_path is None - assert task.export_file_name is None - - def test_parse_inventory_from_chat_text_route_is_removed(app, client): """正式任务不再接受对话文本库存;临时库存由独立会话 Tool 处理。""" headers = _tool_headers(app) parse_inv = client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, - json={"task_id": "SN-REMOVED", "raw_inventory_text": "料号\t可用数量\nA001\t10"}, + json={"task_id": "OT-REMOVED", "raw_inventory_text": "料号\t可用数量\nA001\t10"}, ) assert parse_inv.status_code == 404 assert parse_inv.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND" @@ -400,7 +386,7 @@ def test_parse_inventory_empty_text_route_is_removed(app, client): res = client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, - json={"task_id": "SN-REMOVED", "raw_inventory_text": " "}, + json={"task_id": "OT-REMOVED", "raw_inventory_text": " "}, ) assert res.status_code == 404 assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND" @@ -413,7 +399,7 @@ def test_match_by_supplier_sku_and_reservation_id(app, client): "/api/shipping-notice/tools/parse_inventory", headers=headers, json={ - "task_id": "SN-REMOVED", + "task_id": "OT-REMOVED", "raw_inventory_text": "Supplier Sku\tCOM ID\tQty Available\nA001\tR-1\t2\n", }, ) @@ -427,7 +413,7 @@ def test_removed_inventory_text_route_cannot_create_mapping_checkpoint(app, clie "/api/shipping-notice/tools/parse_inventory", headers=headers, json={ - "task_id": "SN-REMOVED", + "task_id": "OT-REMOVED", "raw_inventory_text": "Supplier Sku\tAWS Sku\tCOM ID\tQty Available\nD4-A08AR12000002\t10-40594-001\tAWS-311\t1\n", }, ) @@ -441,7 +427,7 @@ def test_removed_inventory_text_route_cannot_reopen_mapping_correction(app, clie "/api/shipping-notice/tools/parse_inventory", headers=headers, json={ - "task_id": "SN-REMOVED", + "task_id": "OT-REMOVED", "raw_inventory_text": ( "Supplier Sku\tAWS Sku\tCOM ID\tQty Available\n" "D4-A08AR12000002\t10-40594-001\tAWS-311\t1\n" @@ -459,87 +445,10 @@ def test_legacy_task_inventory_mapping_routes_are_removed(app, client): "/api/shipping-notice/tools/get_inventory_schema_preview", "/api/shipping-notice/tools/apply_inventory_mapping", ): - response = client.post(path, headers=headers, json={"task_id": "SN-LEGACY-REMOVED"}) + response = client.post(path, headers=headers, json={"task_id": "OT-LEGACY-REMOVED"}) assert response.status_code == 404 -@pytest.mark.auto_rpa -def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp_path, monkeypatch): - monkeypatch.setattr( - "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", - lambda *args, **kwargs: None, - ) - headers = _tool_headers(app) - trigger = tmp_path / "inventory_triggers" - inventory_drop = tmp_path / "inventory_drop" - trigger.mkdir() - inventory_drop.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(inventory_drop) - - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - - with app.app_context(): - task = ShippingNotice.query.filter_by(task_no=task_id).first() - assert task is not None - _attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1) - task.review_status = None - task.pending_human_reason = "inv_unavail" - task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "12345", "available_qty": 3}] - task.match_status = "fulfillable" - task.shortage_json = {"lines": []} - task.line_results_json = [{"part_number": "OLD", "status": "ok"}] - task.export_file_path = str(tmp_path / "old.xlsx") - task.export_file_name = "old.xlsx" - task.upload_status = "failed" - task.upload_mode = "rpa" - task.upload_error_message = "old upload failed" - task.freight_ref_no = "OLD-REF" - task.step_payload_json = { - "rpa_inventory_source": { - "source_code": "DSV360_AWSDU", - "connector_type": "dsv360", - "display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)", - "entry_url": "https://s360.dbschenker.com/", - "query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"}, - } - } - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - db.session.commit() - - from app.services.shipping_notice import decision_workflow - - with app.app_context(): - retry_data = decision_workflow.submit_decision({"task_id": task_id, "decision": "retry_rpa"}) - assert retry_data["status"] == "running" - assert retry_data.get("data", {}).get("rpa_runtime", {}).get("mode") in {"browser", "mock"} - - with app.app_context(): - task = ShippingNotice.query.filter_by(task_no=task_id).first() - assert task is not None - assert task.pending_human_reason == "rpa_pending" - assert task.pending_human_reason == "rpa_pending" - assert task.review_status is None - assert task.inventory_lines_json is None - assert task.match_status is None - assert task.shortage_json is None - assert task.line_results_json is None - assert task.export_file_path is None - assert task.export_file_name is None - assert task.upload_status is None - assert task.upload_error_message is None - assert task.freight_ref_no is None - event = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="decision_retry_rpa").first() - assert event is not None - assert event.detail_json.get("force_refresh") is True - assert len(list(trigger.glob("inventory_export_*.json"))) == 1 - - @pytest.mark.auto_rpa def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt(app, client, tmp_path, monkeypatch): from datetime import datetime, timedelta @@ -557,17 +466,21 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt lambda: None, ) + with app.app_context(): + user_id = _seed_test_user(username='rpa-timeout-recheck') + create_res = client.post( "/api/shipping-notice/tools/create_task", headers=headers, - json={"source_type": "manual"}, + json={"source_type": "direct_pdf", "user_id": user_id}, ) task_id = create_res.get_json()["task_id"] with app.app_context(): - task = ShippingNotice.query.filter_by(task_no=task_id).first() + task = ShippingOrderTask.query.filter_by(task_no=task_id).first() assert task is not None _attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1) + _confirm_test_task_customer(task) task.pending_human_reason = PH_RPA_PENDING task.step_payload_json = { "rpa_inventory_source": { @@ -591,7 +504,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt with app.app_context(): result = _run_single_task(task_id) - task = ShippingNotice.query.filter_by(task_no=task_id).first() + task = ShippingOrderTask.query.filter_by(task_no=task_id).first() assert task is not None assert result["status"] == "needs_human" assert task.pending_human_reason == PH_RPA_EXHAUSTED @@ -602,171 +515,13 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt assert len(list(trigger.glob("inventory_export_*.json"))) == 0 -@pytest.mark.auto_rpa -def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_path, monkeypatch): - monkeypatch.setattr( - "app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot", - lambda *args, **kwargs: None, - ) - from datetime import datetime, timedelta - - from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED - - headers = _tool_headers(app) - trigger = tmp_path / "inventory_triggers" - inventory_drop = tmp_path / "inventory_drop" - trigger.mkdir() - inventory_drop.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(inventory_drop) - - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - - with app.app_context(): - task = ShippingNotice.query.filter_by(task_no=task_id).first() - assert task is not None - _attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1) - task.pending_human_reason = PH_RPA_EXHAUSTED - task.step_payload_json = { - "rpa_inventory_source": { - "source_code": "DSV360_AWSDU", - "connector_type": "dsv360", - "display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)", - "entry_url": "https://s360.dbschenker.com/", - "query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"}, - } - } - seed_task_inventory_source(task, source_code="DSV360_AWSDU") - base_time = datetime.utcnow() - timedelta(minutes=5) - for idx in range(3): - db.session.add( - ShippingTaskEvent( - task_id=task.id, - event_type="inventory_rpa_triggered", - detail_json={"attempt": idx + 1}, - created_at=base_time + timedelta(seconds=idx), - ) - ) - db.session.commit() - - from app.services.shipping_notice import decision_workflow - - with app.app_context(): - retry_data = decision_workflow.submit_decision({"task_id": task_id, "decision": "retry_rpa"}) - assert retry_data["status"] == "running" - assert retry_data.get("data", {}).get("rpa", {}).get("attempts") == 1 - - with app.app_context(): - task = ShippingNotice.query.filter_by(task_no=task_id).first() - assert task is not None - assert task.pending_human_reason == "rpa_pending" - assert task.pending_human_reason == "rpa_pending" - assert task.error_message is None - progress = (task.step_payload_json or {}).get("current_step_progress") or {} - assert progress.get("current") == 1 - assert progress.get("extra", {}).get("manual_retry_round") is True - assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="decision_retry_rpa").count() == 1 - assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 4 - assert len(list(trigger.glob("inventory_export_*.json"))) == 1 - - -def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(app, client): - headers = _tool_headers(app) - - first = ShippingNotice( - task_no="SN-MULTI-CONV-001", - conversation_id="conv-test-multi", - review_status="parse_review", - pending_human_reason="low_confidence", - source_type="manual", - lines_json=[{"part_number": "A001", "reservation_id": "1000140351", "qty": 1}], - ) - second = ShippingNotice( - task_no="SN-MULTI-CONV-002", - conversation_id="conv-test-multi", - review_status="parse_review", - pending_human_reason="low_confidence", - source_type="manual", - lines_json=[{"part_number": "A002", "reservation_id": "1000140352", "qty": 1}], - ) - with app.app_context(): - db.session.add_all([first, second]) - db.session.commit() - - confirm_res = client.post( - "/api/shipping-notice/tools/submit_decision", - headers=headers, - json={"conversation_id": "conv-test-multi", "decision": "confirm"}, - ) - confirm_data = confirm_res.get_json() - assert confirm_data["status"] == "failed" - assert "任务编号" in confirm_data["message"] or "task ID" in confirm_data["message"] - - status_res = client.post( - "/api/shipping-notice/tools/get_task_status", - headers=headers, - json={"conversation_id": "conv-test-multi"}, - ) - status_data = status_res.get_json() - assert status_data["status"] == "failed" - assert "任务编号" in status_data["message"] - - with app.app_context(): - rows = { - task.task_no: task - for task in ShippingNotice.query.filter(ShippingNotice.task_no.in_(["SN-MULTI-CONV-001", "SN-MULTI-CONV-002"])) - .order_by(ShippingNotice.task_no) - .all() - } - assert rows["SN-MULTI-CONV-001"].review_status == "parse_review" - assert rows["SN-MULTI-CONV-002"].review_status == "parse_review" - - -def test_submit_decision_retry_rpa_routes_to_formal_gate_action(app, client, monkeypatch): - headers = _tool_headers(app) - - create_res = client.post( - "/api/shipping-notice/tools/create_task", - headers=headers, - json={"source_type": "manual"}, - ) - task_id = create_res.get_json()["task_id"] - - import app.services.shipping_notice.decision_workflow as decision_workflow - - captured: dict[str, object] = {} - - def fake_request_formal_gate_action(**kwargs): - captured.update(kwargs) - return {"status": "running", "task_id": task_id, "message": "已提交正式 20-Gate 恢复动作"} - - monkeypatch.setattr(decision_workflow, "_request_formal_gate_action", fake_request_formal_gate_action) - - res = client.post( - "/api/shipping-notice/tools/submit_decision", - headers=headers, - json={"task_id": task_id, "decision": "retry_rpa", "comment": "retry now"}, - ) - data = res.get_json() - assert data["status"] == "running" - assert data["task_id"] == task_id - assert data["message"] == "已提交正式 20-Gate 恢复动作" - assert captured["task"].task_no == task_id - assert captured["action_code"] == "retry_inventory_preparation" - - def test_parse_inventory_oversized_text_route_is_removed(app, client): """旧正式库存文本入口无论内容大小都不可访问。""" headers = _tool_headers(app) res = client.post( "/api/shipping-notice/tools/parse_inventory", headers=headers, - json={"task_id": "SN-REMOVED", "raw_inventory_text": "x" * 200}, + json={"task_id": "OT-REMOVED", "raw_inventory_text": "x" * 200}, ) assert res.status_code == 404 assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND" @@ -776,12 +531,13 @@ def test_chat_actions_empty_when_task_rejected(app): from app.services.shipping_notice.ui_state import build_task_ui_state with app.app_context(): - task = ShippingNotice( - task_no="SN-20260101-TEST0001", - source_type="manual", + task = ShippingOrderTask( + task_no="OT-20260101-TEST0001", + user_id=1, + source_type="eml", review_status="rejected", ) ui_state = build_task_ui_state(task) - assert ui_state["checkpoint"]["code"] == "rejected" + assert ui_state["review_status"] == "rejected" assert ui_state["actions"] == {"primary": None, "secondary": []} assert "action_buttons" not in ui_state diff --git a/backend/tests/test_shipping_notice_ui_state.py b/backend/tests/test_shipping_notice_ui_state.py index a26d008f..d69053ad 100644 --- a/backend/tests/test_shipping_notice_ui_state.py +++ b/backend/tests/test_shipping_notice_ui_state.py @@ -8,9 +8,14 @@ tests/test_shipping_notice_ui_state.py from app import db from app.core.auth.jwt import issue_local_access_token -from app.models import ShippingNotice, ShippingNoticeLine, ShippingNoticeLineInventoryMatch, User +from app.models import ( + ShippingInventoryCandidateLine, ShippingInventoryCandidateSet, ShippingInventoryCandidateSource, + ShippingNotice, ShippingNoticeLine, ShippingNoticeLineInventoryMatch, + ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask, User, +) from app.services.shipping_notice.constants import ( CP_EXPORT_READY, + CP_ORDER_FREEZE, CP_PARSE_REVIEW, PH_LOW_CONF, RS_PARSE_REVIEW, @@ -34,6 +39,43 @@ _REQUIRED_SUMMARY_KEYS = { } +def _frozen_task_with_line( + *, + task_no: str, + user_id: int = 1, + reservation_id: str | None = None, + part_number: str | None = None, + qty: str | None = None, + field_values_json: dict | None = None, +) -> tuple[ShippingOrderTask, ShippingOrderSnapshotLine]: + """建立通知准备测试所需的最小 OT 冻结档与订单项次。""" + task = ShippingOrderTask(task_no=task_no, user_id=user_id, source_type='direct_pdf') + db.session.add(task) + db.session.flush() + snapshot = ShippingOrderSnapshot( + task_id=task.id, + extraction_id=task.id, + schema_version_id=1, + order_data_version=1, + header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + task.order_snapshot_id = snapshot.id + line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, + position=0, + line_no=1, + reservation_id=reservation_id, + part_number=part_number, + qty=qty, + field_values_json=field_values_json or {}, + ) + db.session.add(line) + db.session.flush() + return task, line + + def test_unified_actions_deduplicates_gate_primary_action(): """Gate 主动作同时出现在展示列表时,只能渲染一次。""" state = _unified_actions( @@ -95,23 +137,23 @@ def test_unified_actions_preserve_backend_surface_without_action_code_fallback() def test_build_task_ui_state_summary_has_required_keys(app) -> None: """summary 必须包含 STP 可解释字段全集。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-SUMMARY", + task = ShippingOrderTask( + task_no="OT-UI-SUMMARY", user_id=1, review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, - source_type="manual", + source_type="direct_pdf", ) state = build_task_ui_state(task) assert set(_REQUIRED_SUMMARY_KEYS).issubset(state["summary"].keys()) - assert state["checkpoint"]["code"] == CP_PARSE_REVIEW - assert state["checkpoint_kind"] == "must_human" + assert state["checkpoint"]["code"] == CP_ORDER_FREEZE + assert state["checkpoint_kind"] == "auto_continue" assert "stp_facts" not in state["summary"] def test_task_ui_state_stage_context_is_opt_in(app) -> None: """列表等轻量调用默认不得加载阶段工作面详情。""" with app.app_context(): - task = ShippingNotice(task_no="SN-UI-LIGHTWEIGHT", source_type="manual") + task = ShippingOrderTask(task_no="OT-UI-LIGHTWEIGHT", user_id=1, source_type="direct_pdf") state = build_task_ui_state(task) detailed_state = build_task_ui_state(task, include_stage_context=True) @@ -124,11 +166,11 @@ def test_task_ui_state_stage_context_is_opt_in(app) -> None: def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None: """旧 checkpoint 不能再推导五阶段或任何可写 UI 动作。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-STAGE-ACTIONS", + task = ShippingOrderTask( + task_no="OT-UI-STAGE-ACTIONS", user_id=1, review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, - source_type="manual", + source_type="direct_pdf", ) state = build_task_ui_state(task) assert state["stage"]["code"] == "unclassified" @@ -141,11 +183,11 @@ def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None: def test_build_task_ui_state_without_formal_gate_has_no_lifecycle_entries(app) -> None: """正式工作台入口必须来自 Gate,不能按旧 checkpoint 生成。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-LIFECYCLE-ENTRIES", + task = ShippingOrderTask( + task_no="OT-UI-LIFECYCLE-ENTRIES", user_id=1, review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, - source_type="manual", + source_type="direct_pdf", ) state = build_task_ui_state(task) assert state["lifecycle_stage"] == "unclassified" @@ -162,7 +204,7 @@ def test_task_ui_state_ignores_superseded_process_execution(app) -> None: user = User(username='ui-superseded-execution', email='ui-superseded@example.com', password_hash='x') db.session.add(user) db.session.flush() - task = ShippingNotice(task_no='SN-UI-SUPERSEDED-EXEC', user_id=user.id, source_type='manual') + task = ShippingOrderTask(task_no='OT-UI-SUPERSEDED-EXEC', user_id=user.id, source_type='direct_pdf') db.session.add(task) db.session.flush() execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system') @@ -182,10 +224,10 @@ def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None: user = User(username='ui-gate-authority', email='ui-gate-authority@example.com', password_hash='x') db.session.add(user) db.session.flush() - task = ShippingNotice( - task_no='SN-UI-GATE-AUTHORITY', + task = ShippingOrderTask( + task_no='OT-UI-GATE-AUTHORITY', user_id=user.id, - source_type='manual', + source_type='direct_pdf', # 模拟历史字段尚未同步:旧字段仍像解析复核。 review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, @@ -215,10 +257,10 @@ def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> No user = User(username='ui-upload-gate-authority', email='ui-upload-gate@example.com', password_hash='x') db.session.add(user) db.session.flush() - task = ShippingNotice( - task_no='SN-UI-UPLOAD-GATE-AUTHORITY', + task = ShippingOrderTask( + task_no='OT-UI-UPLOAD-GATE-AUTHORITY', user_id=user.id, - source_type='manual', + source_type='direct_pdf', review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, ) @@ -241,17 +283,11 @@ def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> No def test_build_task_ui_state_does_not_map_domain_fields_to_lifecycle(app) -> None: """库存和上传历史字段不能再替代正式 Gate 生成生命周期。""" with app.app_context(): - fulfillment = ShippingNotice( - task_no="SN-UI-FULFILLMENT", - source_type="manual", - match_status="partial", - inventory_lines_json=[{"part_number": "P-1"}], - ) - upload = ShippingNotice( - task_no="SN-UI-UPLOAD", - source_type="manual", - upload_status="uploaded", + fulfillment = ShippingOrderTask( + task_no="OT-UI-FULFILLMENT", user_id=1, + source_type="direct_pdf", ) + upload = ShippingOrderTask(task_no="OT-UI-UPLOAD", user_id=1, source_type="direct_pdf") assert build_task_ui_state(fulfillment)["stage"]["code"] == "unclassified" upload_state = build_task_ui_state(upload, include_stage_context=True) assert upload_state["stage"]["code"] == "unclassified" @@ -262,31 +298,39 @@ def test_build_task_ui_state_does_not_map_domain_fields_to_lifecycle(app) -> Non def test_entry_surface_parse_review_is_review_workbench(app) -> None: """解析复核应进入人工复核工作台。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-REVIEW", + task = ShippingOrderTask( + task_no="OT-UI-REVIEW", user_id=1, review_status=RS_PARSE_REVIEW, pending_human_reason=PH_LOW_CONF, - source_type="manual", + source_type="direct_pdf", ) state = build_task_ui_state(task) - assert state["summary"]["entry_surface"] == "review_workbench" + assert state["summary"]["entry_surface"] == "task_workbench" -def test_entry_surface_export_ready_is_task_workbench(app) -> None: - """Excel 待人工上传登记仍进入工作台,但历史文件名不能擅自授权下载。""" +def test_entry_surface_export_ready_is_task_workbench(app, monkeypatch) -> None: + """Excel Artifact 就绪后仍进入工作台,且未解析的文件不得擅自授权下载。""" with app.app_context(): task = ShippingNotice( task_no="SN-UI-EXPORT", source_type="manual", - export_file_path="/tmp/shipping-export.xlsx", - export_file_name="shipping-export.xlsx", + ) + # Excel 是否就绪只能由 Artifact 事实裁决,不能恢复 Notice 旧文件投影。 + from types import SimpleNamespace + monkeypatch.setattr( + 'app.services.shipping_notice.upload_attempt_service.latest_export_artifact', + lambda _task: SimpleNamespace(id=0, file_path='/tmp/shipping-export.xlsx', file_name='shipping-export.xlsx'), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.upload_attempt_service.latest_upload_attempt', + lambda _task: None, ) state = build_task_ui_state(task) assert state["checkpoint"]["code"] == CP_EXPORT_READY assert state["checkpoint_kind"] == "wait_manual_upload" assert state["summary"]["entry_surface"] == "task_workbench" assert state["summary"].get("pause_reason_code") == "wait_manual_upload" - assert "登记凭据" in str(state["summary"].get("pause_reason") or "") + assert "货代平台上传" in str(state["summary"].get("pause_reason") or "") button_ids = [ item.get("code") for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])] @@ -303,8 +347,6 @@ def test_task_ui_state_only_exposes_download_for_resolved_artifact(app, monkeypa task = ShippingNotice( task_no="SN-UI-RESOLVED-EXPORT", source_type="manual", - export_file_path="/tmp/shipping-export.xlsx", - export_file_name="shipping-export.xlsx", ) monkeypatch.setattr( 'app.services.shipping_notice.ui_state.resolve_task_export_download', @@ -373,18 +415,27 @@ def test_verified_upload_complete_state_has_no_follow_up_actions(app, monkeypatc def test_stp_facts_candidates_frozen_projected(app) -> None: """多候选冻结任务须投影 stp_facts.frozen_candidate_codes。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-STP-FROZEN", - source_type="manual", - inventory_source_status="candidates_frozen", - inventory_source_method="stp_build_freeze", - step_payload_json={ - "line_inventory_candidates": { - "source_codes": ["DBS_DUB", "DBS_RTM"], - "frozen_at": "build", - }, - }, + task = ShippingOrderTask( + task_no="OT-UI-STP-FROZEN", user_id=1, source_type="direct_pdf", ) + db.session.add(task) + db.session.flush() + candidate_set = ShippingInventoryCandidateSet( + task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='a' * 64, + ) + db.session.add(candidate_set) + db.session.flush() + db.session.add_all([ + ShippingInventoryCandidateSource( + candidate_set_id=candidate_set.id, source_code=code, candidate_order=index, + ) + for index, code in enumerate(['DBS_DUB', 'DBS_RTM'], start=1) + ]) + db.session.add(ShippingInventoryCandidateLine( + candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DBS_DUB', 'DBS_RTM'], + )) + task.active_inventory_candidate_set_id = candidate_set.id + db.session.commit() state = build_task_ui_state(task) facts = state["summary"]["stp_facts"] assert facts["inventory_source_status"] == "candidates_frozen" @@ -393,33 +444,37 @@ def test_stp_facts_candidates_frozen_projected(app) -> None: def test_stp_facts_projects_line_resolutions(app) -> None: - """stp_facts 须包含逐行 Reservation/料号/实际库存源/文件证据。""" + """stp_facts 须从当前行级 Match 投影逐行库存证据,不能读取 OT payload。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-STP-LINES", - source_type="manual", - match_status="fulfillable", - inventory_source_status="resolved", - inventory_source_code="DBS_DUB", - inventory_source_method="stp_line_match", - step_payload_json={ - "line_inventory_resolutions": [ - { - "line_index": 0, - "disposition": "ok", - "effective_reservation_id": "3000092917", - "part_number": "PN-1", - "resolved_inventory_source_code": "DBS_DUB", - "inventory_file_no": "INV-1", - "inventory_row_ref": { - "reservation_id": "3000092917", - "part_number": "PN-1", - "source_code": "DBS_DUB", - }, - }, - ], - }, + user = User(username='ui-stp-lines', email='ui-stp-lines@example.com') + db.session.add(user) + db.session.flush() + task = ShippingOrderTask( + task_no='OT-UI-STP-LINES', user_id=user.id, stage='inventory_matching', ) + db.session.add(task) + db.session.flush() + snapshot = ShippingOrderSnapshot( + task_id=task.id, extraction_id=3, schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + task.order_snapshot_id = snapshot.id + snapshot_line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, position=0, line_no=1, + reservation_id='3000092917', part_number='PN-1', qty='10', field_values_json={}, + ) + db.session.add(snapshot_line) + db.session.flush() + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0, + match_result='matched', inventory_status='ready', required_qty='10', available_qty='10', + matched_qty='10', shortage_qty='0', reservation_id='3000092917', part_number='PN-1', + inventory_source_code='DBS_DUB', matched_file_no='INV-1', is_current=True, + )) + db.session.commit() + state = build_task_ui_state(task, include_stage_context=True) rows = state["summary"]["stp_facts"]["line_resolutions"] assert rows[0]["effective_reservation_id"] == "3000092917" @@ -428,39 +483,58 @@ def test_stp_facts_projects_line_resolutions(app) -> None: assert rows[0]["inventory_file_no"] == "INV-1" stage_context = state["stage_context"] assert stage_context["preparation"]["status"] == "ready" - assert stage_context["preparation"]["lines"] == [{ - "line_key": None, - "line_no": "1", - "line_no_source": "sequence", - "reservation_id": "3000092917", - "part_number": "PN-1", - "required_qty": None, - "available_qty": None, - "shortage_qty": None, - "source_code": "DBS_DUB", - "status": "ok", - }] + # §1.5:行级字段是展示契约核心,但不锁全 dict(随 §1.5 字段扩展)。断言关键现存字段 + 新增明细按钮字段。 + line = stage_context["preparation"]["lines"][0] + assert line["snapshot_line_id"] == snapshot_line.id + assert line["line_no"] == 1 + assert line["customer_po_line_no"] is None + assert line["reservation_id"] == "3000092917" + assert line["part_number"] == "PN-1" + assert line["required_qty"] == "10" + assert line["available_qty"] == "10" + assert line["shortage_qty"] == "0" + assert line["source_code"] == "DBS_DUB" + # §1.5 status 现取 user_line_status(展示契约),不再是裸 match_result 的 disposition。 + assert line["status"] == "inventory_matched" + assert line["source_ambiguous"] is False + assert line["source_candidates"] == [] + # §1.5 明细按钮数据源:matched/ready 无短缺 → 无库存重试动作;行级库存文件号下发供下载按钮; + # line_allowed_actions 仍开放 close_unfulfillable(非终态行可关闭)。 + assert line["inventory_file_no"] == "INV-1" + assert line["is_shortage"] is False + assert line["inventory_allowed_actions"] == [] + assert line["line_allowed_actions"] == ["close_unfulfillable"] + assert line["user_line_status"] == "inventory_matched" # 没有真实上传 Attempt 时,即使处于履约阶段也不能投影为上传成功。 assert stage_context["upload"]["outcome"] == "not_started" def test_stage_context_prefers_current_structured_inventory_match(app) -> None: - """通知准备摘要必须从当前行级匹配事实投影数量,不能只依赖旧 JSON。""" + """通知准备必须从 Snapshot 与行级 Match 投影,不依赖 OT JSON 或 NoticeLine。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-STRUCTURED-MATCH", - source_type="manual", - match_status="partial", - inventory_source_code="DBS_DUB", - inventory_source_status="resolved", - inventory_source_method="stp_line_match", - line_results_json=[], - ) + user = User(username='ui-structured-match', email='ui-structured-match@example.com') + db.session.add(user) + db.session.flush() + task = ShippingOrderTask(task_no='OT-UI-STRUCTURED-MATCH', user_id=user.id, stage='inventory_matching') db.session.add(task) db.session.flush() + snapshot = ShippingOrderSnapshot( + task_id=task.id, extraction_id=1, schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + task.order_snapshot_id = snapshot.id + snapshot_line = ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, position=0, line_no=1, + reservation_id='RSV-1', part_number='PN-1', qty='10', field_values_json={}, + ) + db.session.add(snapshot_line) + db.session.flush() db.session.add(ShippingNoticeLineInventoryMatch( task_id=task.id, - line_key="line-1", + snapshot_line_id=snapshot_line.id, + line_no=1, line_index=0, match_result="matched", inventory_status="ready", @@ -477,48 +551,85 @@ def test_stage_context_prefers_current_structured_inventory_match(app) -> None: preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"] assert preparation["has_match_result"] is True - assert preparation["lines"] == [{ - "line_key": "line-1", - "line_no": "1", - "line_no_source": "sequence", - "reservation_id": "RSV-1", - "part_number": "PN-1", - "required_qty": "10", - "available_qty": "7", - "shortage_qty": "3", - "source_code": "DBS_DUB", - "status": "matched", - }] + line = preparation["lines"][0] + assert line["snapshot_line_id"] == snapshot_line.id + assert line["line_no"] == 1 + assert line["customer_po_line_no"] is None + assert line["reservation_id"] == "RSV-1" + assert line["part_number"] == "PN-1" + assert line["required_qty"] == "10" + assert line["available_qty"] == "7" + assert line["shortage_qty"] == "3" + assert line["source_code"] == "DBS_DUB" + assert line["status"] == "shortage" + assert line["source_ambiguous"] is False + assert line["source_candidates"] == [] + # §1.5 明细按钮:短缺 → close_unfulfillable / release_inventory_shortage + retry 两动作。 + assert line["is_shortage"] is True + assert line["user_line_status"] == "shortage" + assert set(line["line_allowed_actions"]) == {"close_unfulfillable", "release_inventory_shortage"} + assert "retry_inventory_preparation" in line["inventory_allowed_actions"] + + +def test_stage_context_preparation_projects_source_ambiguity_and_lock(app) -> None: + """行级 source_conflict 与候选源只读 Match;Excel 生成后锁定。""" + with app.app_context(): + user = User(username='ui-source-ambiguity', email='ui-source-ambiguity@example.com') + db.session.add(user) + db.session.flush() + task = ShippingOrderTask(task_no='OT-UI-SOURCE-AMBIG', user_id=user.id, stage='inventory_matching') + db.session.add(task) + db.session.flush() + snapshot = ShippingOrderSnapshot( + task_id=task.id, extraction_id=2, schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + task.order_snapshot_id = snapshot.id + line = ShippingOrderSnapshotLine(snapshot_id=snapshot.id, position=0, line_no=1, field_values_json={}) + db.session.add(line) + db.session.flush() + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0, + match_result='source_conflict', inventory_status='source_conflict', + allowed_source_codes_snapshot=['SRC_A', 'SRC_B'], is_current=True, + )) + db.session.commit() + + preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation'] + assert preparation['lines'][0]['source_ambiguous'] is True + assert preparation['lines'][0]['source_candidates'] == ['SRC_A', 'SRC_B'] + assert preparation['lines'][0]['source_code'] is None + assert preparation['source_locked'] is False def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_ready(app) -> None: """库存文件尚未取得时,通知准备仍必须返回冻结订单行,不能把订单明细绑到匹配结果。""" with app.app_context(): - task = ShippingNotice(task_no="SN-UI-FROZEN-ORDER", source_type="manual") - db.session.add(task) - db.session.flush() - db.session.add(ShippingNoticeLine( - notice_id=task.id, - position=0, - line_key="line-frozen-1", + task, line = _frozen_task_with_line( + task_no="OT-UI-FROZEN-ORDER", reservation_id="RSV-FROZEN", part_number="PN-FROZEN", - required_qty="6", - )) + qty="6", + ) db.session.commit() preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"] # 关键断言:冻结订单与库存匹配是两类事实;无库存文件不能抹掉订单行。 assert preparation["frozen_order_lines"] == [{ - "line_key": "line-frozen-1", - "line_no": "1", - "line_no_source": "sequence", + "snapshot_line_id": line.id, + "line_no": 1, "reservation_id": "RSV-FROZEN", "part_number": "PN-FROZEN", "required_qty": "6.00000000", }] - assert preparation["lines"] == [] + assert preparation["lines"][0]["snapshot_line_id"] == line.id + assert preparation["lines"][0]["line_no"] == 1 + assert preparation["lines"][0]["reservation_id"] == "RSV-FROZEN" + assert preparation["lines"][0]["part_number"] == "PN-FROZEN" + assert preparation["lines"][0]["available_qty"] is None assert preparation["has_match_result"] is False @@ -530,7 +641,9 @@ def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_pat with app.app_context(): inventory_path = tmp_path / "task-inventory.xlsx" inventory_path.write_bytes(b"inventory-content") - task = ShippingNotice(task_no="SN-UI-INVENTORY-DOWNLOAD", source_type="manual") + task = ShippingOrderTask( + task_no="OT-UI-INVENTORY-DOWNLOAD", user_id=1, source_type="direct_pdf", + ) inventory_file = ShippingInventoryFile( inventory_file_no="SIF-UI-DOWNLOAD", storage_path=str(inventory_path), @@ -568,8 +681,8 @@ def test_workspace_inventory_download_requires_owned_active_file(app, client, tm db.session.flush() inventory_path = tmp_path / 'inventory-download.xlsx' inventory_path.write_bytes(b'inventory-download-content') - task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-API', user_id=owner.id, source_type='manual') - no_file_task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-NONE', user_id=owner.id, source_type='manual') + task = ShippingOrderTask(task_no='OT-INVENTORY-DOWNLOAD-API', user_id=owner.id, source_type='direct_pdf') + no_file_task = ShippingOrderTask(task_no='OT-INVENTORY-DOWNLOAD-NONE', user_id=owner.id, source_type='direct_pdf') inventory_file = ShippingInventoryFile( inventory_file_no='SIF-INVENTORY-DOWNLOAD-API', storage_path=str(inventory_path), @@ -589,16 +702,16 @@ def test_workspace_inventory_download_requires_owned_active_file(app, client, tm other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'} # 关键断言:活动 link 文件可下载,并以服务端原始内容响应。 - success = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=owner_headers) + success = client.get('/api/workspace/shipping-tasks/OT-INVENTORY-DOWNLOAD-API/inventory-file', headers=owner_headers) assert success.status_code == 200 assert success.data == b'inventory-download-content' assert 'inventory-download.xlsx' in str(success.headers.get('Content-Disposition') or '') # 无 active link 和非归属用户均固定为 404,避免按来源或订单号探测库存文件。 - missing = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-NONE/inventory-file', headers=owner_headers) + missing = client.get('/api/workspace/shipping-tasks/OT-INVENTORY-DOWNLOAD-NONE/inventory-file', headers=owner_headers) assert missing.status_code == 404 assert missing.get_json()['error']['code'] == 'SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND' - forbidden = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=other_headers) + forbidden = client.get('/api/workspace/shipping-tasks/OT-INVENTORY-DOWNLOAD-API/inventory-file', headers=other_headers) assert forbidden.status_code == 404 @@ -614,7 +727,9 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app, denied_path = tmp_path / 'dbs.xlsx' allowed_path.write_bytes(b'crane-content') denied_path.write_bytes(b'dbs-content') - task = ShippingNotice(task_no='SN-LINE-INVENTORY-DOWNLOAD', user_id=owner.id, source_type='manual') + task, snapshot_line = _frozen_task_with_line( + task_no='OT-LINE-INVENTORY-DOWNLOAD', user_id=owner.id, + ) allowed_file = ShippingInventoryFile( inventory_file_no='SIF-LINE-CRANE', storage_path=str(allowed_path), source_file_name='crane.xlsx', source_code='CRANE', snapshot_status='ready', @@ -626,7 +741,7 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app, db.session.add_all([task, allowed_file, denied_file]) db.session.flush() db.session.add(ShippingNoticeLineInventoryMatch( - task_id=task.id, line_key='line-crane', line_index=0, + task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0, inventory_snapshot_id=allowed_file.id, matched_file_no=allowed_file.inventory_file_no, inventory_source_code='CRANE', match_result='not_found', inventory_status='ready', is_current=True, )) @@ -634,7 +749,7 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app, headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'} allowed = client.get( - '/api/workspace/shipping-tasks/SN-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-CRANE', + '/api/workspace/shipping-tasks/OT-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-CRANE', headers=headers, ) assert allowed.status_code == 200 @@ -642,41 +757,33 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app, assert 'crane.xlsx' in str(allowed.headers.get('Content-Disposition') or '') denied = client.get( - '/api/workspace/shipping-tasks/SN-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-DBS', + '/api/workspace/shipping-tasks/OT-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-DBS', headers=headers, ) assert denied.status_code == 404 def test_stage_context_keeps_legacy_evidence_when_structured_row_is_partial(app) -> None: - """结构化事实字段为空时,历史/STP 证据仍应补齐通知准备行。""" + """行级 Match 的事实字段应补齐冻结订单行的库存展示。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-STRUCTURED-PARTIAL", - source_type="manual", - match_status="partial", - inventory_source_status="resolved", - inventory_source_method="stp_line_match", - step_payload_json={"line_inventory_resolutions": [{ - "line_index": 0, - "line_key": "line-1", - "effective_reservation_id": "RSV-LEGACY", - "part_number": "PN-LEGACY", - "inventory_file_no": "INV-1", - "disposition": "ok", - }]}, + task, snapshot_line = _frozen_task_with_line( + task_no="OT-UI-STRUCTURED-PARTIAL", + reservation_id="RSV-LEGACY", + part_number="PN-LEGACY", + qty="10", ) - db.session.add(task) - db.session.flush() db.session.add(ShippingNoticeLineInventoryMatch( task_id=task.id, - line_key="line-1", + snapshot_line_id=snapshot_line.id, + line_no=1, line_index=0, match_result="matched", inventory_status="ready", required_qty="10", available_qty="8", shortage_qty="2", + reservation_id="RSV-LEGACY", + part_number="PN-LEGACY", inventory_source_code="DBS_DUB", is_current=True, )) @@ -696,18 +803,16 @@ def test_task_detail_endpoint_returns_preparation_stage_context(app, monkeypatch from app.services.shipping_notice import query_service with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-DETAIL-CONTEXT", - source_type="manual", - match_status="fulfillable", - inventory_source_status="resolved", - inventory_source_method="stp_line_match", + task, snapshot_line = _frozen_task_with_line( + task_no="OT-UI-DETAIL-CONTEXT", + reservation_id="RSV-DETAIL", + part_number="PN-DETAIL", + qty="2", ) - db.session.add(task) - db.session.flush() db.session.add(ShippingNoticeLineInventoryMatch( task_id=task.id, - line_key="line-1", + snapshot_line_id=snapshot_line.id, + line_no=1, line_index=0, match_result="matched", inventory_status="ready", @@ -725,36 +830,109 @@ def test_task_detail_endpoint_returns_preparation_stage_context(app, monkeypatch monkeypatch.setattr(query_service, 'get_task_visible_to_user', lambda *_args, **_kwargs: task) monkeypatch.setattr(api, '_ok', lambda data: data) - payload = api.workspace_shipping_task_detail(task.task_no) + # 视图函数经 request.args 读取 view 参数,必须包一层请求上下文(直接调用无 request)。 + with app.test_request_context(): + payload = api.workspace_shipping_task_detail(task.task_no) preparation = payload['ui_state']['stage_context']['preparation'] assert preparation['has_match_result'] is True assert preparation['lines'][0]['reservation_id'] == 'RSV-DETAIL' def test_stp_facts_multi_source_excel_block_legacy_payload(app) -> None: - """历史 multi_source_excel_block 载荷仍覆盖 pause_reason(兼容旧任务)。""" - from app.services.shipping_notice.constants import RS_SHORTAGE_REVIEW - + """行级多源冲突应覆盖通知准备的暂停原因。""" with app.app_context(): - task = ShippingNotice( - task_no="SN-UI-STP-MULTI", - review_status=RS_SHORTAGE_REVIEW, - pending_human_reason="shortage", - source_type="manual", - match_status="fulfillable", - inventory_source_status="candidates_frozen", - inventory_source_method="stp_line_match", - step_payload_json={ - "multi_source_excel_block": True, - "resolved_ok_source_codes": ["DBS_DUB", "DBS_RTM"], - "line_inventory_resolutions": [ - {"line_index": 0, "disposition": "ok", "resolved_inventory_source_code": "DBS_DUB"}, - {"line_index": 1, "disposition": "ok", "resolved_inventory_source_code": "DBS_RTM"}, - ], - }, + task, snapshot_line = _frozen_task_with_line( + task_no="OT-UI-STP-MULTI", reservation_id="RSV-MULTI", part_number="PN-MULTI", qty="1", ) + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0, + match_result='source_conflict', inventory_status='source_conflict', + allowed_source_codes_snapshot=['DBS_DUB', 'DBS_RTM'], is_current=True, + )) + db.session.commit() state = build_task_ui_state(task) summary = state["summary"] assert summary["pause_reason_code"] == "multi_source_excel_block" assert summary["stp_facts"]["multi_source_excel_block"] is True assert summary["entry_surface"] == "task_workbench" + + +def test_preparation_editable_present_for_live_formal_task(monkeypatch): + """活任务(active/blocked/空值)判定可操作;作废/归档/删除/待作废/取消视图不可操作。 + + 按 ShippingNotice 真实 lifecycle_status 值域逐值覆盖(不用 WorkflowItem 的 + {'closed', 'cancelled'} 终态集);排除集见 ui_state 的 + _PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES 注释。 + """ + class FakeTask: + id = 1 + task_no = 'SN-LIVE-1' + order_task_no = 'SN-LIVE-1' + # 真实值域:ShippingNotice 无 in_progress 写入方,活任务为 active。 + lifecycle_status = 'active' + export_file_path = '' + order_snapshot_id = None + inventory_source_code = None + match_status = None + + # 直接依赖 _build_stage_context 内部较重;此处最小断言 editable 键存在且为 bool 语义。 + # 实现时若 _build_stage_context 依赖过多,改为抽纯谓词 _preparation_editable(task) 单测。 + from app.services.shipping_notice.ui_state import _preparation_editable + + # 关键断言:活任务(active)判定可操作(任务级 editable=True 语义)。 + assert _preparation_editable(FakeTask()) is True + + class BlockedTask(FakeTask): + lifecycle_status = 'blocked' + + # 关键断言:blocked 是新任务暂堵态(task_supersession_service.py),不算作废/历史 + # 视图,保持可编辑——与 case 级 edit_formal_task 镜像语义一致;闸口语义由 + # pending_human_reason 等机制表达,不在此谓词收紧。 + assert _preparation_editable(BlockedTask()) is True + + class NoStatusTask(FakeTask): + lifecycle_status = None + + # 边界断言:空/缺失 lifecycle_status 不得误判为终态,默认可操作。 + assert _preparation_editable(NoStatusTask()) is True + + # 关键断言:每个非可操作生命周期必须置 False,供 Prep 波次出单门控拦截—— + # 终态 voided/archived/deleted;co8 只读语义 pending_void + # (freight_cancellation_service.py:154);兼容双拼 cancelled/canceled。 + for status in ('voided', 'archived', 'deleted', 'pending_void', 'cancelled', 'canceled'): + class NonEditableTask(FakeTask): + pass + NonEditableTask.lifecycle_status = status + # 意图:该值域命中 _PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES → editable=False。 + assert _preparation_editable(NonEditableTask()) is False + + class NoisyStatusTask(FakeTask): + lifecycle_status = ' Voided ' + + # 边界断言:strip/lower 归一化必须保留(防终态因空白/大小写漏判为可编辑)。 + assert _preparation_editable(NoisyStatusTask()) is False + + +def test_stage_context_preparation_projects_editable_and_customer_po_line_no(app) -> None: + """[断言] preparation 携带任务级 editable(active=True / voided=False); + 行级 customer_po_line_no 直读字段真实值(field_code 兼容键),字段缺失时为 None。""" + with app.app_context(): + task, first_line = _frozen_task_with_line( + task_no="OT-UI-PREP-EDITABLE", + reservation_id="RSV-PO-1", part_number="PN-PO-1", qty="5", + field_values_json={"customer_po_line_no": "7"}, + ) + second_line = ShippingOrderSnapshotLine( + snapshot_id=first_line.snapshot_id, position=1, line_no=2, + reservation_id="RSV-PO-2", part_number="PN-PO-2", qty="3", field_values_json={}, + ) + db.session.add(second_line) + db.session.commit() + + preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"] + # 关键断言:活任务(默认 active)必须下发任务级可操作标志 True。 + assert preparation["editable"] is True + # 未绑定 Schema 字段 ID 时,冻结档不会把 field_code 当成正式字段事实。 + assert preparation["lines"][0]["customer_po_line_no"] is None + # 字段缺失/无值的行也必须输出 None,不得用展示序号冒充业务行号。 + assert preparation["lines"][1]["customer_po_line_no"] is None diff --git a/backend/tests/test_shipping_notice_user_facing_status.py b/backend/tests/test_shipping_notice_user_facing_status.py index f677d05b..41f8bca0 100644 --- a/backend/tests/test_shipping_notice_user_facing_status.py +++ b/backend/tests/test_shipping_notice_user_facing_status.py @@ -2,11 +2,11 @@ tests/test_shipping_notice_user_facing_status.py 用途:验证发货通知用户可见阶段文案的优先级,避免细粒度 pending 状态被通用 checkpoint 覆盖。 -依赖:pytest、ShippingNotice 模型、user_facing_status。 -逻辑:构造最小 ShippingNotice 实例,断言 rpa_pending 时优先展示具体的 RPA 导出提示。 +依赖:pytest、ShippingOrderTask 模型、user_facing_status。 +逻辑:构造最小 ShippingOrderTask 实例,断言 rpa_pending 时优先展示具体的 RPA 导出提示。 """ -from app.models import ShippingNotice +from app.models import ShippingOrderTask from app.services.shipping_notice.constants import PH_RPA_PENDING from app.services.shipping_notice.user_facing_status import user_facing_task_stage @@ -15,10 +15,12 @@ def test_user_facing_task_stage_prefers_specific_rpa_pending_reason() -> None: """ rpa_pending 时应优先展示 RPA 导出中的具体提示,而不是通用的“待上传或获取库存”。 - 核心逻辑:构造 waiting_inventory + rpa_pending 的任务,验证用户可见标题优先取 pending_human_reason。 + 核心逻辑:pending_human_reason 是属于建单前 OT(ShippingOrderTask)的流程阻断事实; + 正式 Notice 只承载单据。构造 rpa_pending 的任务,验证用户可见标题优先取 pending_human_reason。 """ - task = ShippingNotice( - task_no="SN-TEST-RPA-PENDING", + task = ShippingOrderTask( + task_no="OT-TEST-RPA-PENDING", + user_id=1, pending_human_reason=PH_RPA_PENDING, ) diff --git a/backend/tests/test_shipping_order_auto_freeze_policy.py b/backend/tests/test_shipping_order_auto_freeze_policy.py index 140e126a..59430b35 100644 --- a/backend/tests/test_shipping_order_auto_freeze_policy.py +++ b/backend/tests/test_shipping_order_auto_freeze_policy.py @@ -22,8 +22,9 @@ from app.models import ( Job, ShippingDocumentProfileAutoFreezeQualification, ShippingCustomer, + ShippingCustomerShadowResolution, + ShippingOrderCandidate, ShippingOrderDocumentProfile, - ShippingOrderCustomerMatch, ShippingOrderExtraction, ShippingOrderExtractionProgressEvent, ShippingOrderRouteDecision, @@ -52,7 +53,7 @@ def _published_profile(*, schema_version_id: int, checksum: str) -> ShippingOrde def _confirm_run_customer(*, run_id: int, intake_id: int, schema_version_id: int, customer: ShippingCustomer) -> None: - """为 Run 构造一条已确认的 Bill-to 客户匹配,供范围门禁测试复用。""" + """为 Run 构造已确认的客户识别结果,供范围门禁测试复用。""" extraction = ShippingOrderExtraction( run_id=run_id, intake_id=intake_id, @@ -63,18 +64,20 @@ def _confirm_run_customer(*, run_id: int, intake_id: int, schema_version_id: int ) db.session.add(extraction) db.session.flush() - db.session.add(ShippingOrderCustomerMatch( - extraction_id=extraction.id, - role='bill_to', - identity_components_json={}, - status='confirmed', - customer_id=customer.id, - customer_name_snapshot=customer.standard_name, - customer_short_code_snapshot=customer.short_code, - identity_fingerprint=f'customer-{customer.id}', - identity_rule_version='customer-match.v1', - resolution_method='manual', - confirmed_at=datetime.utcnow(), + candidate = ShippingOrderCandidate( + candidate_no=f'CAND-AF-{run_id}-{customer.id}', intake_id=int(intake_id), primary_document_id=1, + candidate_key=f'auto-freeze-{run_id}-{customer.id}', order_extraction_id=extraction.id, + candidate_status='accepted', order_extraction_run_id=int(run_id), + ) + db.session.add(candidate) + db.session.flush() + db.session.add(ShippingCustomerShadowResolution( + candidate_id=candidate.id, intake_id=int(intake_id), resolution_version='test.v1', status='confirmed', + evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}], + candidate_matches_json=[{'customer_id': customer.id, 'score': 100}], + resolution_context_json={'rule_set': {'checksum': 'a' * 64}}, identity_rule_set_checksum='a' * 64, + top_customer_id=customer.id, top_score=100, confirmed_customer_id=customer.id, + confirmation_method='manual', confirmed_at=datetime.utcnow(), )) diff --git a/backend/tests/test_shipping_order_build_eligibility.py b/backend/tests/test_shipping_order_build_eligibility.py index c179d662..434d3bfb 100644 --- a/backend/tests/test_shipping_order_build_eligibility.py +++ b/backend/tests/test_shipping_order_build_eligibility.py @@ -12,7 +12,6 @@ from __future__ import annotations from app.extensions import db from app.models import ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition from app.services.shipping_notice.order_build_eligibility_service import ( - apply_manual_inventory_candidates, assess_order_build_eligibility, project_line_inventory_candidates, ) @@ -210,42 +209,8 @@ def test_unavailable_rule_candidates_are_filtered(app): assert routing['can_build'] is True -def test_manual_decision_not_silently_overwritten_by_rule_suggestion(app): - """人工决定优先;规则建议可并存但不覆盖有效候选。""" - with app.app_context(): - field_ids = _published_line_fields() - fields = _schema_fields_map(field_ids) - db.session.add(_rule( - code='FORCE_OTHER', priority=100, sources=['DSV360_AWSDU'], - conditions=[(field_ids['reservation_id'], 'is_not_empty', None)], - )) - db.session.commit() - line_meta = { - 'line_key': 'line-1', - 'inventory_routing': { - 'selection_mode': 'manual', - 'candidate_inventory_source_codes': ['DSV360_AWSDU'], - 'manual_reason': 'planner confirmed', - 'suggestion_pending': True, - 'rule_suggestion': {'source_codes': ['DSV360_AWSDU']}, - }, - } - - routing = project_line_inventory_candidates( - fields=fields, - header_by_code={}, - line_by_code={'part_number': 'PN-001', 'qty': '2', 'reservation_id': '3000092917'}, - line_meta=line_meta, - ) - - # 关键断言:有效候选仍是人工值;selection_mode 保持 manual。 - assert routing['selection_mode'] == 'manual' - assert routing['candidate_inventory_source_codes'] == ['DSV360_AWSDU'] - assert routing['can_build'] is True - - def test_zero_candidates_blocks_build(app): - """无路由命中时 can_build=False 且 block_reason=no_inventory_source_candidates。""" + """无路由命中时 can_build=True(库存路由不阻断 OT 创建),但行级仍记录 block_reason。""" with app.app_context(): field_ids = _published_line_fields() fields = _schema_fields_map(field_ids) @@ -260,14 +225,14 @@ def test_zero_candidates_blocks_build(app): line_metas=[{'line_key': 'line-1'}], ) - # 关键断言:零候选阻断建单并给出稳定原因码。 - assert result['can_build'] is False + # 关键断言:库存路由属可人工修正事实,不阻断正式 OT 创建;行级仍给出稳定原因码。 + assert result['can_build'] is True assert result['line_projections'][0]['block_reason'] == 'no_inventory_source_candidates' assert any(item['code'] == 'no_inventory_source_candidates' for item in result['issues']) def test_require_manual_review_action_blocks_build(app): - """require_manual_review 规则将 status=conflicted 且 can_build=False。""" + """require_manual_review 规则将 status=conflicted;can_build=True(库存路由不阻断),行级保留 block_reason。""" with app.app_context(): field_ids = _published_line_fields() fields = _schema_fields_map(field_ids) @@ -287,8 +252,8 @@ def test_require_manual_review_action_blocks_build(app): line_metas=[{'line_key': 'line-1'}], ) - # 关键断言:强制人工复核阻断建单。 - assert result['can_build'] is False + # 关键断言:强制人工复核属可人工修正事实,不阻断正式 OT 创建;行级仍路由到 conflicted。 + assert result['can_build'] is True assert result['line_projections'][0]['routing_status'] == 'conflicted' assert result['line_projections'][0]['block_reason'] == 'require_manual_review' @@ -323,57 +288,6 @@ def test_header_only_reservation_fills_effective_reservation(app): assert result['can_build'] is True -def test_manual_selection_with_reason_and_enabled_source_allows_build(app): - """人工选择已启用库存源并填写原因时 can_build=True。""" - with app.app_context(): - field_ids = _published_line_fields() - fields = _schema_fields_map(field_ids) - line_meta: dict = {'line_key': 'line-1'} - apply_manual_inventory_candidates( - line_meta=line_meta, - source_codes=['DSV360_AWSDU'], - reason='客户邮件指定 Dublin 库存池', - ) - - routing = project_line_inventory_candidates( - fields=fields, - header_by_code={}, - line_by_code={'part_number': 'PN-001', 'qty': '2', 'reservation_id': '3000092917'}, - line_meta=line_meta, - ) - - # 关键断言:人工覆盖优先于规则零候选。 - assert routing['selection_mode'] == 'manual' - assert routing['can_build'] is True - assert routing['candidate_inventory_source_codes'] == ['DSV360_AWSDU'] - - -def test_manual_selection_without_reason_is_blocked(app): - """人工选择未填写原因时 can_build=False 且 block_reason=manual_inventory_source_reason_required。""" - with app.app_context(): - field_ids = _published_line_fields() - fields = _schema_fields_map(field_ids) - line_meta = { - 'line_key': 'line-1', - 'inventory_routing': { - 'selection_mode': 'manual', - 'candidate_inventory_source_codes': ['DSV360_AWSDU'], - 'manual_reason': '', - }, - } - - routing = project_line_inventory_candidates( - fields=fields, - header_by_code={}, - line_by_code={'part_number': 'PN-001', 'qty': '2', 'reservation_id': '3000092917'}, - line_meta=line_meta, - ) - - # 关键断言:缺原因不得放行建单。 - assert routing['can_build'] is False - assert routing['block_reason'] == 'manual_inventory_source_reason_required' - - def test_auto_freeze_reasons_own_single_user_blocking_finding(app, monkeypatch): """资格失败只产生一条用户阻断 Finding,不平行产生多个 auto_build_gate_*。""" from types import SimpleNamespace diff --git a/backend/tests/test_shipping_order_customer_matching.py b/backend/tests/test_shipping_order_customer_matching.py deleted file mode 100644 index 3ffacbc4..00000000 --- a/backend/tests/test_shipping_order_customer_matching.py +++ /dev/null @@ -1,182 +0,0 @@ -""" -backend/tests/test_shipping_order_customer_matching.py - -用途:验证订单 Bill-to / Ship-to 与货代客户主数据的角色化匹配。 -依赖:订单 Schema 模型、客户主数据模型、order_customer_matching 服务。 -逻辑:覆盖标准名称、审核别名、歧义、未命中和人工确认快照。 -""" - -from app import db -from app.models import ( - ShippingCustomer, - ShippingCustomerExternalRef, - ShippingCustomerIdentifier, - ShippingCustomerSite, - ShippingCustomerSiteIdentifier, - ShippingOrderExtraction, - ShippingOrderSchema, - ShippingOrderSchemaVersion, -) -from app.services.shipping_notice.customer_normalization import normalize_customer_name -from app.services.shipping_notice.order_customer_matching import ( - confirm_order_customer_match, - refresh_order_customer_matches, -) - - -def _extraction() -> ShippingOrderExtraction: - """构造角色化客户匹配测试所需的最小订单解析记录。""" - schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单字段') - db.session.add(schema) - db.session.flush() - version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='draft', definition_json={}) - db.session.add(version) - db.session.flush() - extraction = ShippingOrderExtraction( - schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted', - ) - db.session.add(extraction) - db.session.flush() - return extraction - - -def test_order_customer_matching_resolves_roles_and_short_codes(app): - """Bill-to/Ship-to 应可命中不同客户,简称必须来自主数据。""" - with app.app_context(): - bill_to = ShippingCustomer(standard_name='Amazon Web Services', short_code='AWS') - db.session.add(bill_to) - db.session.flush() - ship_to = ShippingCustomerSite( - customer_id=bill_to.id, site_name='Amazon Dublin DC', site_code='DUB01', status='active', - ) - db.session.add(ship_to) - db.session.flush() - db.session.add(ShippingCustomerSiteIdentifier( - site_id=ship_to.id, - identifier_type='name_alias', source_system='', - raw_value='AWS Dublin DC', - normalized_value=normalize_customer_name('AWS Dublin DC'), - status='approved', - )) - extraction = _extraction() - - results = refresh_order_customer_matches(extraction, { - 'bill_to_customer': 'Amazon Web Services', - 'ship_to_customer': 'AWS Dublin DC', - }) - - by_role = {item['role']: item for item in results} - assert by_role['bill_to']['customer_id'] == bill_to.id - assert by_role['bill_to']['short_code'] == 'AWS' - assert by_role['ship_to']['customer_id'] == bill_to.id - assert by_role['ship_to']['site_id'] == ship_to.id - assert by_role['ship_to']['short_code'] == 'AWS' - - -def test_order_customer_matching_keeps_ambiguous_and_manual_confirmation(app): - """同一别名对应多个客户时不得自动选择,人工确认后锁定标准名称和简称。""" - with app.app_context(): - first = ShippingCustomer(standard_name='Customer One', short_code='ONE') - second = ShippingCustomer(standard_name='Customer Two', short_code='TWO') - db.session.add_all([first, second]) - db.session.flush() - normalized = normalize_customer_name('Shared Alias') - db.session.add_all([ - ShippingCustomerIdentifier( - customer_id=first.id, identifier_type='name_alias', raw_value='Shared Alias', - normalized_value=normalized, status='approved', - ), - ShippingCustomerIdentifier( - customer_id=second.id, identifier_type='name_alias', raw_value='Shared Alias', - normalized_value=normalized, status='approved', - ), - ]) - extraction = _extraction() - results = refresh_order_customer_matches(extraction, {'bill_to_customer': 'Shared Alias'}) - bill_to = next(item for item in results if item['role'] == 'bill_to') - assert bill_to['status'] == 'ambiguous' - assert bill_to['customer_id'] is None - assert len(bill_to['candidates']) == 2 - - confirmed = confirm_order_customer_match( - extraction.id, role='bill_to', customer_id=second.id, actor_id=None, reason='业务复核确认订购客户', - ) - assert confirmed['status'] == 'confirmed' - assert confirmed['standard_name'] == 'Customer Two' - assert confirmed['short_code'] == 'TWO' - assert confirmed['confirmation_reason'] == '业务复核确认订购客户' - assert len(confirmed['identity_fingerprint']) == 64 - assert confirmed['identity_rule_version'] == 'order-customer-fingerprint.v1' - - -def test_order_customer_fingerprint_is_stable_and_confirmation_requires_reason(app): - """相同原文及规则必须得到稳定指纹,人工绑定不能缺失可审计理由。""" - with app.app_context(): - customer = ShippingCustomer(standard_name='Fingerprint Customer', short_code='FPC') - db.session.add(customer) - extraction = _extraction() - first = refresh_order_customer_matches(extraction, {'bill_to_customer': ' Fingerprint Customer '}) - fingerprint = next(item for item in first if item['role'] == 'bill_to')['identity_fingerprint'] - second = refresh_order_customer_matches(extraction, {'bill_to_customer': 'Fingerprint Customer'}) - assert next(item for item in second if item['role'] == 'bill_to')['identity_fingerprint'] == fingerprint - try: - confirm_order_customer_match(extraction.id, role='bill_to', customer_id=customer.id, actor_id=None, reason='') - except Exception as error: - assert getattr(error, 'code', None) == 'SHIPPING.ORDER_CUSTOMER_CONFIRM_REASON_REQUIRED' - else: - raise AssertionError('confirmation without reason must be blocked') - - -def test_order_customer_matching_prefers_external_customer_and_site_codes(app): - """外部客户编码和 Ship-to Code 应优先于不可靠的原文名称。""" - with app.app_context(): - customer = ShippingCustomer(standard_name='Canonical Customer', short_code='CAN') - db.session.add(customer) - db.session.flush() - db.session.add(ShippingCustomerExternalRef( - customer_id=customer.id, source_system='ERP', legacy_customer_key='C001', - )) - site = ShippingCustomerSite( - customer_id=customer.id, site_name='Dublin Site', site_code='DUB01', status='active', - ) - db.session.add(site) - db.session.flush() - db.session.add(ShippingCustomerSiteIdentifier( - site_id=site.id, identifier_type='external_code', source_system='ERP', - raw_value='DUB-EXT', normalized_value='DUB-EXT', status='approved', - )) - extraction = _extraction() - - results = refresh_order_customer_matches(extraction, { - 'bill_to_customer': 'Wrong Name', 'bill_to_customer_code': 'c001', 'bill_to_source_system': 'erp', - 'ship_to_customer': 'Wrong Site', 'ship_to_code': 'dub-ext', 'ship_to_source_system': 'erp', - }) - - by_role = {item['role']: item for item in results} - assert by_role['bill_to']['customer_id'] == customer.id - assert by_role['bill_to']['resolution_method'] == 'external_customer_code' - assert by_role['ship_to']['site_id'] == site.id - assert by_role['ship_to']['resolution_method'] == 'external_site_code' - - -def test_ship_to_matching_falls_back_to_name_when_external_code_misses(app): - """Ship-to 外部编码未命中时应继续使用站点标准名称,避免有效站点被错误判为未匹配。""" - with app.app_context(): - customer = ShippingCustomer(standard_name='Fallback Customer', short_code='FBC') - db.session.add(customer) - db.session.flush() - site = ShippingCustomerSite( - customer_id=customer.id, site_name='Fallback Delivery Site', site_code='FBS01', status='active', - ) - db.session.add(site) - extraction = _extraction() - - results = refresh_order_customer_matches(extraction, { - 'ship_to_customer': 'Fallback Delivery Site', - 'ship_to_code': 'UNKNOWN-CODE', - 'ship_to_source_system': 'ERP', - }) - - ship_to = next(item for item in results if item['role'] == 'ship_to') - assert ship_to['site_id'] == site.id - assert ship_to['resolution_method'] == 'site_name' diff --git a/backend/tests/test_shipping_order_document_profile_service.py b/backend/tests/test_shipping_order_document_profile_service.py index a124d7c6..de43f473 100644 --- a/backend/tests/test_shipping_order_document_profile_service.py +++ b/backend/tests/test_shipping_order_document_profile_service.py @@ -660,8 +660,25 @@ def _bind_ready_profile_sample( table_id: str = 'sample-table', content_hash: str = 's' * 64, filename: str = 'sample.pdf', + physical_page_count: int = 1, + include_top_level_pages: bool = True, ) -> ShippingOrderDocumentProfileSample: - """为发布相关测试创建 ready Layout 样本,避免无样本草稿绕过发布证据冻结。""" + """ + 为发布相关测试创建 ready Layout 样本,避免无样本草稿绕过发布证据冻结。 + + Args: + profile_id: 绑定该样本的草稿模板主键。 + sample_role: 样本角色。 + table_id: 第一页视觉主表身份。 + content_hash: 样本文档内容哈希。 + filename: 受控样本文档名。 + physical_page_count: 原 PDF 的物理页数;坐标证据为每页保留尺寸。 + include_top_level_pages: 为 False 时模拟坐标证据外置后的持久化 Layout,不在根 payload + 重复保存页面列表。 + + Returns: + 已绑定到 Profile 的样本记录。 + """ suffix = f'{profile_id}-{str(sample_role).upper()}-{ShippingOrderDocumentProfileSample.query.count() + 1}' user = User( username=f'profile-sample-{suffix}', @@ -708,10 +725,9 @@ def _bind_ready_profile_sample( ) db.session.add(document) db.session.flush() - record_inline_layout_snapshot(document, { + snapshot = { 'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready', - 'pages': [{'page_no': 1}], 'tables': [{ 'table_id': table_id, 'page_no': 1, @@ -719,7 +735,10 @@ def _bind_ready_profile_sample( 'html': '
ok
', }], 'coordinate_evidence': { - 'pages': {'1': {'width': 200, 'height': 100}}, + 'pages': { + str(page_no): {'width': 200, 'height': 100} + for page_no in range(1, physical_page_count + 1) + }, 'page_glyphs': {'1': [{ 'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}, }]}, @@ -728,7 +747,10 @@ def _bind_ready_profile_sample( }]}, 'sources': {'pages': {'1': 'pdf_coordinate'}, 'tables': {table_id: 'pdf'}}, }, - }) + } + if include_top_level_pages: + snapshot['pages'] = [{'page_no': page_no} for page_no in range(1, physical_page_count + 1)] + record_inline_layout_snapshot(document, snapshot) db.session.commit() service.add_profile_sample( profile_id, @@ -1448,6 +1470,28 @@ def test_profile_publish_freezes_field_ids_and_retires_previous_version(app, mon ).one().id == replacement['id'] +def test_profile_publish_freezes_physical_page_count_from_externalized_coordinate_evidence(app, monkeypatch): + """外置坐标证据含全部物理页时,发布冻结页数不能退化为仅有表格的页数。""" + with app.app_context(): + monkeypatch.setattr( + 'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None, + ) + schema = _schema_version() + draft = service.save_draft(_data(schema.id), actor_id=None) + sample = _bind_ready_profile_sample( + draft['id'], + sample_role='annotation', + physical_page_count=2, + include_top_level_pages=False, + ) + + service.publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version']) + + frozen = db.session.get(ShippingOrderDocumentProfileSample, sample.id) + # 关键断言:第二页即使没有业务表格,仍是同一 PDF 的冻结物理页面。 + assert frozen.page_count_snapshot == 2 + + def test_clone_draft_inherits_annotation_sample_but_not_training_sample(app, monkeypatch): """从已发布模板新建草稿时,编辑器 PDF 画布可用且不会复用训练发布资格。""" with app.app_context(): @@ -1948,6 +1992,7 @@ def test_profile_sample_api_supports_secure_preview_create_and_version_update(ap 'snapshot_version': 'shipping_document_table_snapshot.v1', 'provider': 'mineru', 'provider_version': '3.1.14', 'status': 'ready', 'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': html}], + 'coordinate_evidence': {'pages': {'1': {'width': 200, 'height': 100}}}, }) db.session.commit() document_id = document.id @@ -2377,7 +2422,8 @@ def test_profile_region_preview_excludes_configured_header_regions_from_line_row ) assert preview['rows'] == [['customer_po_line_no'], ['10']] - assert preview['source_row_indices'] == [[], [0]] + # 整页候选保留表头作为第 0 个视觉行;真实数据行的证据索引必须保持为第 1 行。 + assert preview['source_row_indices'] == [[], [1]] def test_profile_region_preview_uses_schema_field_order(app, monkeypatch): @@ -2645,6 +2691,7 @@ def test_profile_sample_api_reports_header_contamination_but_v2_can_use_independ '' '
ITEM NO 00010Part NumberQty
00020INTERNAL-236
' )}], + 'coordinate_evidence': {'pages': {'1': {'width': 200, 'height': 100}}}, }) db.session.commit() document_id = document.id diff --git a/backend/tests/test_shipping_order_edit_window.py b/backend/tests/test_shipping_order_edit_window.py new file mode 100644 index 00000000..5d2255d1 --- /dev/null +++ b/backend/tests/test_shipping_order_edit_window.py @@ -0,0 +1,120 @@ +""" +tests/test_shipping_order_edit_window.py + +用途:确认后订单编辑窗谓词(order_edit_window_service.editable_scope,设计 D10/§3.1)契约。 +依赖:ShippingNotice/ShippingNoticeLine、order_edit_window_service.progress_workflow。 +逻辑:header=全部通知无 Export Artifact 且无活动 Attempt;行=行所属通知无 Excel 且无活动 Attempt + (未入波次行不受首单 Excel 限制)。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.models import ShippingNotice, ShippingNoticeLine +from app.services.shipping_notice.order_edit_window_service import ( + assert_field_editable, + editable_scope, +) + + +def _make_notice(task_no: str, *, order_task_id: int | None = None) -> ShippingNotice: + """构造最小 ShippingNotice;Excel 锁定由测试 monkeypatch _notice_has_export_artifact 判定。""" + notice = ShippingNotice( + task_no=task_no, + order_task_id=order_task_id, + ) + db.session.add(notice) + db.session.flush() + return notice + + +def _make_line(notice: ShippingNotice, position: int, snapshot_line_id: int) -> None: + """行身份使用冻结快照行 id(snapshot_line_id)作为编辑窗 key。""" + db.session.add(ShippingNoticeLine( + notice_id=int(notice.id), + position=position, + line_no=position + 1, + snapshot_line_id=snapshot_line_id, + field_values_json={}, + )) + db.session.flush() + + +def test_editable_scope_fresh_order_all_editable(app, monkeypatch): + """[断言] 全新订单(无 Excel、无活动 Attempt):header 与全部行均可编辑。""" + from app.services.shipping_notice.order_edit_window_service import _notice_has_active_attempt + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: False) + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_export_artifact', lambda n: False) + notice = _make_notice('SN-EW-FRESH') + _make_line(notice, 0, 1) + _make_line(notice, 1, 2) + + scope = editable_scope(notice) + assert scope['header'] is True + assert scope['lines']['1'] is True + assert scope['lines']['2'] is True + + +def test_editable_scope_header_locked_by_excel_unassigned_lines_stay_editable(app, monkeypatch): + """[断言] 首单已生成 Excel:header 锁;未入波次行仍可编辑(D10 不受首单 Excel 限制)。""" + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: False) + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_export_artifact', lambda n: True) + notice = _make_notice('SN-EW-EXCEL') + _make_line(notice, 0, 1) + _make_line(notice, 1, 2) + + scope = editable_scope(notice) + assert scope['header'] is False + assert scope['lines']['1'] is True # 未入波次行不受首单 Excel 限制 + assert scope['lines']['2'] is True + + +def test_editable_scope_busy_attempt_locks_header_and_lines(app, monkeypatch): + """[断言] 存在活动 Gate Attempt:header 与全部行均锁定(系统处理中)。""" + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: True) + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_export_artifact', lambda n: False) + notice = _make_notice('SN-EW-BUSY') + _make_line(notice, 0, 1) + + scope = editable_scope(notice) + assert scope['header'] is False + assert scope['lines']['1'] is False + + +def test_assert_field_editable_delegates_scope(app): + """[断言] 保存守卫按作用域映射谓词;header/line 互不串用。""" + scope = {'header': False, 'lines': {'1': True, '2': False}} + assert assert_field_editable(scope, field={'scope': 'header'}) is False + assert assert_field_editable(scope, field={'scope': 'line'}, snapshot_line_id='1') is True + assert assert_field_editable(scope, field={'scope': 'line'}, snapshot_line_id='2') is False + assert assert_field_editable(scope, field={'scope': 'line'}, snapshot_line_id=None) is False + + +def test_order_has_active_attempt_reflects_notice_attempts(app, monkeypatch): + """[断言] order_has_active_attempt 聚合同订单全部通知的活动 Attempt。""" + from app.services.shipping_notice.order_edit_window_service import ( + order_has_active_attempt, + ) + + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: True) + notice = _make_notice('SN-EW-BUSY-AGGR') + assert order_has_active_attempt(notice) is True + + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', lambda n: False) + assert order_has_active_attempt(notice) is False + + +def test_edit_window_busy_error_returns_system_busy(app, monkeypatch): + """[断言] 活动 Attempt 时保存守卫返回 SHIPPING.EDIT_WINDOW_SYSTEM_BUSY;空闲时 None。""" + from app.services.shipping_notice import task_workflow + + notice = _make_notice('SN-EW-BUSY-GUARD') + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service.order_has_active_attempt', lambda n: True) + err = task_workflow._edit_window_busy_error(notice) + assert err is not None + assert 'SHIPPING.EDIT_WINDOW_SYSTEM_BUSY' in repr(err) + + monkeypatch.setattr('app.services.shipping_notice.order_edit_window_service.order_has_active_attempt', lambda n: False) + assert task_workflow._edit_window_busy_error(notice) is None diff --git a/backend/tests/test_shipping_order_extraction_dify_guide.py b/backend/tests/test_shipping_order_extraction_dify_guide.py index 2da77e88..f7a2b648 100644 --- a/backend/tests/test_shipping_order_extraction_dify_guide.py +++ b/backend/tests/test_shipping_order_extraction_dify_guide.py @@ -62,7 +62,7 @@ def _table_first_column_after(marker: str, *, table_label: str | None = None) -> ] -def _review_request(*, scope: str = 'header', line_key: str | None = None) -> dict: +def _review_request(*, scope: str = 'header', draft_line_id: str | None = None) -> dict: """构造单字段最小证据请求信封。""" return { 'contract_version': 'order-review-llm.v1', @@ -73,7 +73,7 @@ def _review_request(*, scope: str = 'header', line_key: str | None = None) -> di 'field_id': 'field-1', 'field_code': 'po_number', 'scope': scope, - 'line_key': line_key, + 'draft_line_id': draft_line_id, 'line_number': None, }], 'evidence_pack': { @@ -119,7 +119,7 @@ def test_review_request_accepts_one_header_field(): def test_review_request_rejects_multiple_fields_and_line_without_key(): - """复核分支必须一次只处理一个字段,明细字段必须绑定 line_key。""" + """复核分支必须一次只处理一个字段,明细字段必须绑定 draft_line_id。""" main = _node_main('## 7. REVIEW_PARSE_REQUEST') multiple = _review_request() multiple['target_fields'].append(dict(multiple['target_fields'][0], field_id='field-2')) @@ -136,7 +136,7 @@ def test_review_request_rejects_multiple_fields_and_line_without_key(): 'review_request_json': '', } assert line_result['request_valid'] is False - assert line_result['request_error_code'] == 'LINE_KEY_REQUIRED' + assert line_result['request_error_code'] == 'DRAFT_LINE_ID_REQUIRED' def test_review_context_removes_secrets_and_limits_to_current_pack(): diff --git a/backend/tests/test_shipping_order_extraction_progress.py b/backend/tests/test_shipping_order_extraction_progress.py index 966fbf74..334805da 100644 --- a/backend/tests/test_shipping_order_extraction_progress.py +++ b/backend/tests/test_shipping_order_extraction_progress.py @@ -107,7 +107,7 @@ def test_progress_event_accepts_email_supplement_merge_summary(app): event = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).one() assert run.current_stage_code == 'email_supplement_merged' assert list(run.active_stage_codes_json or []) == ['email_supplement_merged'] - assert event.summary_json == {'conflict_count': 0, 'relation_codes': ['po_mpn'], 'status': 'merged'} + assert {'conflict_count': 0, 'relation_codes': ['po_mpn'], 'status': 'merged'}.items() <= event.summary_json.items() def test_progress_event_accepts_plan_expansion_and_budget_run_level_events(app): @@ -154,11 +154,11 @@ def test_progress_event_accepts_plan_expansion_and_budget_run_level_events(app): 'expansion_wave_started', 'budget_stopped', ] - assert events[2].summary_json == { + assert { 'reason_codes': ['required_field_missing'], 'selection_batch': 2, 'unit_count': 2, - } + }.items() <= events[2].summary_json.items() assert run.current_stage_code == 'budget_stopped' assert list(run.active_stage_codes_json or []) == [] diff --git a/backend/tests/test_shipping_order_extraction_quality_migration.py b/backend/tests/test_shipping_order_extraction_quality_migration.py index 7774d235..96524ec2 100644 --- a/backend/tests/test_shipping_order_extraction_quality_migration.py +++ b/backend/tests/test_shipping_order_extraction_quality_migration.py @@ -22,7 +22,7 @@ def test_order_extraction_quality_migration_round_trip(monkeypatch): ) engine = sa.create_engine('sqlite:///:memory:') metadata = sa.MetaData() - for name in ('agents', 'users', 'shipping_order_schema_versions', 'shipping_order_extraction_runs'): + for name in ('agents', 'users', 'shipping_order_schema_versions', 'shipping_order_extraction_runs', 'agent_runtime_bindings'): sa.Table(name, metadata, sa.Column('id', sa.Integer(), primary_key=True)) metadata.create_all(engine) with engine.begin() as connection: diff --git a/backend/tests/test_shipping_order_extraction_runs.py b/backend/tests/test_shipping_order_extraction_runs.py index 5d93848d..a1ddeade 100644 --- a/backend/tests/test_shipping_order_extraction_runs.py +++ b/backend/tests/test_shipping_order_extraction_runs.py @@ -1402,7 +1402,10 @@ def test_run_submission_rejects_changed_frozen_mail_context(app): def test_run_submission_auto_freezes_qualified_tasks(app): """Run 命中已授权模板后,应自动消费 accepted Candidate 并冻结为履约 Snapshot。""" with app.app_context(): - from app.models import ShippingCustomer, ShippingDocumentProfileAutoFreezeQualification, ShippingOrderCustomerMatch + from app.models import ( + ShippingCustomer, ShippingCustomerShadowResolution, ShippingOrderCandidate, + ShippingDocumentProfileAutoFreezeQualification, + ) from tests.test_shipping_order_auto_freeze_policy import _published_profile fields = _ensure_order_schema() @@ -1448,18 +1451,20 @@ def test_run_submission_auto_freezes_qualified_tasks(app): ) db.session.add(extraction) db.session.flush() - db.session.add(ShippingOrderCustomerMatch( - extraction_id=extraction.id, - role='bill_to', - identity_components_json={}, - status='confirmed', - customer_id=customer.id, - customer_name_snapshot=customer.standard_name, - customer_short_code_snapshot=customer.short_code, - identity_fingerprint=f'customer-{customer.id}', - identity_rule_version='customer-match.v1', - resolution_method='manual', - confirmed_at=datetime.utcnow(), + candidate = ShippingOrderCandidate( + candidate_no=f'CAND-AF-EXEC-{run.id}', intake_id=intake.id, primary_document_id=document.id, + candidate_key=f'auto-freeze-exec-{run.id}', order_extraction_id=extraction.id, + order_extraction_run_id=run.id, candidate_status='accepted', + ) + db.session.add(candidate) + db.session.flush() + db.session.add(ShippingCustomerShadowResolution( + candidate_id=candidate.id, intake_id=intake.id, resolution_version='test.v1', status='confirmed', + evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}], + candidate_matches_json=[{'customer_id': customer.id, 'score': 100}], + resolution_context_json={'rule_set': {'checksum': 'e' * 64}}, identity_rule_set_checksum='e' * 64, + top_customer_id=customer.id, top_score=100, confirmed_customer_id=customer.id, + confirmation_method='manual', confirmed_at=datetime.utcnow(), )) db.session.add_all([ ShippingDocumentProfileAutoFreezeQualification( diff --git a/backend/tests/test_shipping_order_extraction_stage0.py b/backend/tests/test_shipping_order_extraction_stage0.py index 3d7eedf5..e614e460 100644 --- a/backend/tests/test_shipping_order_extraction_stage0.py +++ b/backend/tests/test_shipping_order_extraction_stage0.py @@ -47,6 +47,7 @@ def test_unit_transition_appends_auditable_status_event(app): id=37, status='matching_profile', attempt_count=1, started_at=None, finished_at=None, last_activity_at=None, result_json=None, summary_json=None, reason_code=None, error_code=None, error_message=None, plan=plan, + document_id=100, ) plan.units = [unit] diff --git a/backend/tests/test_shipping_order_extraction_submission.py b/backend/tests/test_shipping_order_extraction_submission.py index 70f764e7..b053d030 100644 --- a/backend/tests/test_shipping_order_extraction_submission.py +++ b/backend/tests/test_shipping_order_extraction_submission.py @@ -84,14 +84,15 @@ def test_submit_appends_to_open_queued_run(app): ) db.session.commit() - # 断言:不同 Intake 不得并入同一 Run;须新建 Run(Candidate 前无右侧 OT 卡)。 + # 断言:不同 Intake 不得并入同一 Run;须新建 Run。预候选 order_notice 未建 OT, + # user_task_no 仍为 None,但会话投影把两个 Intake 各计一张处理中卡(total_tasks=2)。 assert payload['decision'] == 'created' assert payload['created_new'] is True assert payload['run_no'] != first.run_no assert payload['reason_code'] == 'adjudication_unit_boundary' assert ShippingOrderProcessingRun.query.count() == 2 assert payload['user_task_no'] is None - assert payload['processing']['summary']['total_tasks'] == 0 + assert payload['processing']['summary']['total_tasks'] == 2 def test_submit_creates_when_input_frozen(app): @@ -132,9 +133,9 @@ def test_submit_creates_when_input_frozen(app): assert payload['created_new'] is True assert payload['run_no'] != first.run_no assert ShippingOrderProcessingRun.query.count() == 2 - # Candidate 前会话右侧不展示伪 OT。 + # Candidate 前不伪造 OT(user_task_no=None);预候选 order_notice 按处理中卡计 2 张。 assert payload['user_task_no'] is None - assert payload['processing']['summary']['total_tasks'] == 0 + assert payload['processing']['summary']['total_tasks'] == 2 def test_submit_idempotent_by_submission_id(app): @@ -398,11 +399,11 @@ def test_failed_same_attachment_reupload_inherits_user_task(app): assert new_run.reparse_of_run_id == old_run.id assert old_run.superseded_by_run_id == new_run.id assert old_run.superseded_at is not None - assert payload['processing']['summary']['total_tasks'] == 0 + assert payload['processing']['summary']['total_tasks'] == 2 def test_appended_projection_does_not_mark_recently_created(app): - """跨 Intake 新建 Run 时 Candidate 前无右侧 OT 卡;仅断言裁决与 Run 边界。""" + """跨 Intake 新建 Run 时 Candidate 前无真实 OT(user_task_no=None);投影仍按预候选 order_notice 计处理中卡。""" with app.app_context(): user, agent, session, intake, _document = _seed_run_input(suffix='SUB-BADGE') first = submit_order_extraction( @@ -439,7 +440,7 @@ def test_appended_projection_does_not_mark_recently_created(app): assert payload['run_no'] != first['run_no'] assert payload['user_task_no'] is None assert first['user_task_no'] is None - assert payload['processing']['summary']['total_tasks'] == 0 + assert payload['processing']['summary']['total_tasks'] == 2 assert ShippingOrderProcessingRun.query.count() == 2 diff --git a/backend/tests/test_shipping_order_extraction_worker.py b/backend/tests/test_shipping_order_extraction_worker.py index 9f1db3d8..8fdbabde 100644 --- a/backend/tests/test_shipping_order_extraction_worker.py +++ b/backend/tests/test_shipping_order_extraction_worker.py @@ -252,8 +252,8 @@ def _patch_worker_io(monkeypatch, *, event_log: list[tuple[str, str | None]]): ) -def test_process_unit_with_retries_retries_retryable_failures_and_returns_orders(monkeypatch): - """同一附件技术故障应在单元内自动重试,成功后不需要整轮 Run 重跑。""" +def test_process_unit_with_retries_stops_on_retryable_technical_failure(monkeypatch): + """任一技术故障(含 ServiceUnavailableError)在单元内失败即停止,不自动重试;调用方可继续处理其他附件。""" event_log: list[tuple[str, str | None]] = [] _patch_unit_transitions(monkeypatch) _patch_worker_io(monkeypatch, event_log=event_log) @@ -293,15 +293,15 @@ def test_process_unit_with_retries_retries_retryable_failures_and_returns_orders result = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1) - assert result == orders - assert unit.status == 'merging_supplement' - assert unit.attempt_count == 3 - assert event_log.count(('technical_retrying', 'SYSTEM.SERVICE_UNAVAILABLE')) == 2 - assert event_log.count(('technical_failed', 'SYSTEM.SERVICE_UNAVAILABLE')) == 2 + assert result is None + assert unit.status == 'failed' + assert unit.attempt_count == 1 + assert event_log.count(('technical_retrying', 'SYSTEM.SERVICE_UNAVAILABLE')) == 0 + assert event_log.count(('technical_failed', 'SYSTEM.SERVICE_UNAVAILABLE')) == 1 -def test_process_unit_with_retries_records_distinct_route_attempts(monkeypatch): - """同一 Job 内重试路由时,审计尝试号必须随 Unit 递增以避开唯一约束。""" +def test_process_unit_with_retries_records_single_route_attempt(monkeypatch): + """同一 Job 内仅路由一次;技术失败后单元不再重试,审计尝试号按单元执行代次记录。""" event_log: list[tuple[str, str | None]] = [] _patch_unit_transitions(monkeypatch) _patch_worker_io(monkeypatch, event_log=event_log) @@ -339,8 +339,8 @@ def test_process_unit_with_retries_records_distinct_route_attempts(monkeypatch): lambda *, run_id, unit_id: (run, unit), ) - assert _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1) - assert route_attempts == [1, 2] + assert _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1) is None + assert route_attempts == [1] def test_process_unit_with_retries_recovers_interrupted_merging_state(monkeypatch): @@ -383,8 +383,8 @@ def test_process_unit_with_retries_recovers_interrupted_merging_state(monkeypatc assert unit.technical_failure_reason_code is None -def test_process_unit_with_retries_exhausts_retry_budget_and_marks_unit_failed(monkeypatch): - """自动重试耗尽后仅保留单元级技术失败,调用方可继续处理其他附件。""" +def test_process_unit_with_retries_marks_unit_failed_without_retry(monkeypatch): + """技术失败在单元内失败即停止,不消耗重试预算;调用方可继续处理其他附件。""" event_log: list[tuple[str, str | None]] = [] _patch_unit_transitions(monkeypatch) _patch_worker_io(monkeypatch, event_log=event_log) @@ -416,10 +416,10 @@ def test_process_unit_with_retries_exhausts_retry_budget_and_marks_unit_failed(m assert result is None assert unit.status == 'failed' - assert unit.attempt_count == 3 + assert unit.attempt_count == 1 assert unit.technical_failure_reason_code == 'OCR.TIMEOUT' - assert event_log.count(('technical_retrying', 'OCR.TIMEOUT')) == 2 - assert event_log.count(('technical_failed', 'OCR.TIMEOUT')) == 3 + assert event_log.count(('technical_retrying', 'OCR.TIMEOUT')) == 0 + assert event_log.count(('technical_failed', 'OCR.TIMEOUT')) == 1 def test_process_unit_with_retries_does_not_retry_non_retryable_validation_errors(monkeypatch): diff --git a/backend/tests/test_shipping_order_extraction_workspace_projection_unit.py b/backend/tests/test_shipping_order_extraction_workspace_projection_unit.py index ca64303f..07e255b5 100644 --- a/backend/tests/test_shipping_order_extraction_workspace_projection_unit.py +++ b/backend/tests/test_shipping_order_extraction_workspace_projection_unit.py @@ -90,7 +90,7 @@ def test_workspace_projection_exposes_run_level_current_activity(monkeypatch): assert result['primaryNotice'] is None -def test_build_handling_items_splits_pending_freeze_review_and_failure(): +def test_build_handling_items_splits_pending_freeze_review_and_failure(monkeypatch): """Run 级 handling_items 必须拆分待补、冲突、冻结、复核与技术失败,不得只给笼统复核态。""" run = SimpleNamespace( status='partially_completed', @@ -145,6 +145,12 @@ def test_build_handling_items_splits_pending_freeze_review_and_failure(): ), ] + # document_review 只在存在活动(非终态)ReviewCase 时投影;纯单元 Run 无落库 + # Case,故按文件口径补一条模板 Case 以激活 document_review 分支。 + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workspace_projection._current_non_terminal_review_cases', + lambda _run: [SimpleNamespace(document_id=11, case_no='CASE-11')], + ) items = build_handling_items(run, units, open_existing_doc_ids=set()) categories = [item['category'] for item in items] @@ -196,7 +202,7 @@ def test_build_handling_items_budget_stopped_includes_attachment_refs(): assert budget['affected_refs'][0]['document_id'] == 42 -def test_build_handling_items_counts_one_document_in_only_one_primary_category(): +def test_build_handling_items_counts_one_document_in_only_one_primary_category(monkeypatch): """同一 PDF 同时存在解析复核、候选待补和预算原因时,只能计入最高优先级事项。""" run = SimpleNamespace( status='partially_completed', @@ -234,13 +240,18 @@ def test_build_handling_items_counts_one_document_in_only_one_primary_category() technical_failure_reason_code=None, )] + # document_review 需活动 ReviewCase 才投影;纯单元 Run 无落库 Case,按文件口径补模板 Case。 + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workspace_projection._current_non_terminal_review_cases', + lambda _run: [SimpleNamespace(document_id=99, case_no='CASE-99')], + ) items = build_handling_items(run, units, open_existing_doc_ids=set()) assert [item['category'] for item in items] == ['document_review'] assert items[0]['count'] == 1 -def test_build_handling_items_claims_same_pdf_by_content_hash_when_budget_snapshot_lacks_document_id(): +def test_build_handling_items_claims_same_pdf_by_content_hash_when_budget_snapshot_lacks_document_id(monkeypatch): """预算快照仅保留哈希时,仍不得把同一 PDF 与复核事项重复统计。""" run = SimpleNamespace( status='partially_completed', @@ -270,6 +281,11 @@ def test_build_handling_items_claims_same_pdf_by_content_hash_when_budget_snapsh technical_failure_reason_code=None, )] + # document_review 需活动 ReviewCase 才投影;纯单元 Run 无落库 Case,按文件口径补模板 Case。 + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workspace_projection._current_non_terminal_review_cases', + lambda _run: [SimpleNamespace(document_id=100, case_no='CASE-100')], + ) items = build_handling_items(run, units, open_existing_doc_ids=set()) # 文档复核优先级更高;预算原因可作为解释存在,但不能再增加第二个文件计数。 diff --git a/backend/tests/test_shipping_order_field_purposes.py b/backend/tests/test_shipping_order_field_purposes.py index e18c0c0e..50aa4265 100644 --- a/backend/tests/test_shipping_order_field_purposes.py +++ b/backend/tests/test_shipping_order_field_purposes.py @@ -11,7 +11,7 @@ from __future__ import annotations from app import db from app.models import ( ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, - ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingNotice, + ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask, ) from app.services.shipping_notice.order_schema import service from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues @@ -31,15 +31,15 @@ def _config(field_id: str) -> dict: } -def _task_with_reservation(value: str, *, include_reservation_capability: bool = True) -> ShippingNotice: +def _task_with_reservation(value: str, *, include_reservation_capability: bool = True) -> ShippingOrderTask: """创建冻结快照,策略绑定决定履约阶段如何定位预约单号。""" service.initialize_schema({'display_name': '用途测试'}, actor_id=None) field = service.save_field({'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None) draft = service.create_draft({}, actor_id=None) saved = service.save_draft(draft['id'], {'fields': [_config(field['id'])], 'expected_lock_version': draft['lock_version']}, actor_id=None) published = service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) - task = ShippingNotice( - task_no='SN-PURPOSE-1', source_type='manual', lines_json=[{'reservation_id': 'WRONG'}], + task = ShippingOrderTask( + task_no='OT-PURPOSE-1', source_type='direct_pdf', user_id=1, ) db.session.add(task) db.session.flush() @@ -48,7 +48,7 @@ def _task_with_reservation(value: str, *, include_reservation_capability: bool = ) db.session.add(extraction) db.session.flush() - line = ShippingOrderLine(extraction_id=extraction.id, position=0) + line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1) db.session.add(line) db.session.flush() decision = ShippingOrderFieldDecision( @@ -62,25 +62,24 @@ def _task_with_reservation(value: str, *, include_reservation_capability: bool = value_text=value, value_json=value, )) task.current_order_extraction_id = extraction.id - bindings = [] if include_reservation_capability: - bindings.append({ - 'capability_code': 'fulfillment.reservation_identity', - 'field_id': field['id'], - 'scope': 'line', - }) + # 冻结策略只承认 frozen fulfillment_rule.required_field_ids;old + # fulfillment_policy.definition.field_bindings 已不再匹配。 + rule_versions_json = {'fulfillment_rule': {'required_field_ids': { + 'reservation_id': field['id'], 'part_number': field['id'], + 'qty': field['id'], 'quantity': field['id'], + }}} + else: + rule_versions_json = {} snapshot = ShippingOrderSnapshot( task_id=task.id, extraction_id=extraction.id, schema_version_id=published['id'], order_data_version=1, customer_po_number='PURPOSE-PO-001', header_values_json={}, - rule_versions_json={'fulfillment_policy': { - 'code': 'SHIP_AVAILABLE_ROLLING_V1', 'version': 1, - 'definition': {'field_bindings': bindings}, - }}, + rule_versions_json=rule_versions_json, ) db.session.add(snapshot) db.session.flush() db.session.add(ShippingOrderSnapshotLine( - snapshot_id=snapshot.id, position=0, reservation_id=value, + snapshot_id=snapshot.id, position=0, line_no=1, reservation_id=value, field_values_json={field['id']: value}, )) task.order_snapshot_id = snapshot.id @@ -89,10 +88,9 @@ def _task_with_reservation(value: str, *, include_reservation_capability: bool = def test_task_reservation_gate_uses_frozen_value_not_mutable_projection_or_field_value(app): - """门禁以冻结预约单为准,旧任务投影或后续 FieldValue 变化均不得重解释履约。""" + """门禁以冻结预约单为准,后续 FieldValue 变化均不得重解释履约。""" with app.app_context(): task = _task_with_reservation('3000000001') - task.lines_json = [{'reservation_id': 'INVALID'}] value = ShippingOrderFieldValue.query.filter_by(extraction_id=task.current_order_extraction_id).one() value.value_text = 'INVALID' value.value_json = 'INVALID' diff --git a/backend/tests/test_shipping_order_profile_matcher.py b/backend/tests/test_shipping_order_profile_matcher.py index 2dfd134a..92bdfa00 100644 --- a/backend/tests/test_shipping_order_profile_matcher.py +++ b/backend/tests/test_shipping_order_profile_matcher.py @@ -728,3 +728,71 @@ def test_parse_validation_does_not_upgrade_ineligible_profile_to_unique_match(mo ) assert result.status == 'no_match' + + +def test_profile_table_candidates_virtual_empty_page_does_not_block(monkeypatch): + """两页文档、第 2 页无业务表(补成虚拟页)不得把已成功重建的目标表覆盖成失败。 + + 回归:第 2 页被补为虚拟页 ``page-2`` 时,``_coordinate_profile_rows`` 返回 ``None`` + (无表字符/无 raw_table_bbox);旧逻辑在 ``_virtual_page_without_rows_is_nonblocking`` + 之前被 ``is None`` 分支误判为行重建失败,追加 + ``order_profile_coordinate_reconstruction_unavailable`` 使整单阻塞为 + ``coordinate_evidence_unavailable``。修复后空虚拟页被豁免,真实业务表(第 1 页)仍成功。 + + 盲测/样本验证同样按“空页跳过”,因此本条与盲测语义一致。 + """ + from types import SimpleNamespace + + from app.services.shipping_notice import order_extraction_workflow as wf + + layout = _layout('PLANT NAME: FACTORY A', bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95}) + layout['status'] = 'ready' + layout['layout_candidate'] = {'schema_version': 'test', 'pages': []} + # 第 2 页只有页级字符、无任何业务表 → 会被补成虚拟页 page-2。 + layout['coordinate_evidence']['pages']['2'] = {'width': 200, 'height': 280} + layout['coordinate_evidence']['page_glyphs']['2'] = [ + {'text': 'N', 'bbox': {'x0': 10, 'y0': 200, 'x1': 15, 'y1': 212}}, + ] + profile = _with_signature(_profile('PO'), layout) + + schema_def = {'fields': [{ + 'field_id': 'line-id', 'field_code': 'customer_po_line_no', + 'scope': 'line', 'enabled': True, 'value_type': 'string', + }]} + snapshot = { + 'schema': {'extraction_contract': {}, 'definition': schema_def}, + 'order_document_profiles': [profile], + 'intakes': [{'intake_id': 1, 'documents': [{ + 'document_id': 100, 'filename': 'x.pdf', 'layout_snapshot': layout, + }]}], + } + run = SimpleNamespace(id=9, schema_version_id=34, input_snapshot_json=snapshot) + unit = SimpleNamespace(id=99, intake_id=1, document_id=100) + + # 隔离 DB/开关:本测试只关心虚拟空页的行重建门禁语义。 + monkeypatch.setattr(wf.db.session, 'get', lambda *_a, **_k: None) + monkeypatch.setattr(wf, 'profile_auto_selection_enabled', lambda: True) + + def fake_rows(**kwargs): + """注入真实行为:第 1 页业务表重建出 1 行;无表的虚拟页返回 None。""" + raw_table = kwargs.get('raw_table') or {} + if str(raw_table.get('table_id') or '') == 'page-2': + return None + return [{ + 'row_index': 1, '_coordinate_region_id': 'lines', '_coordinate_row_count': 1, + 'status': 'parsed', 'issues': [], + 'fields': [{ + 'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'value': '10', + 'quote': '10', 'page_no': 1, 'table_id': 'table-1', + }], + }] + + monkeypatch.setattr(wf, '_coordinate_profile_rows', fake_rows) + + result = wf._profile_table_candidates(run, unit=unit, profiles=[profile], match_only=False) + + assert result['blocking'] is False + assert 'order_profile_coordinate_reconstruction_unavailable' not in (result.get('issues') or []) + assert result['matched'] is True + # 虚拟空页应被跳过,只有第 1 页业务表进入结果。 + assert len(result.get('tables') or []) == 1 diff --git a/backend/tests/test_shipping_order_profile_parse_validation.py b/backend/tests/test_shipping_order_profile_parse_validation.py index b3e5ba7e..2e27a6b0 100644 --- a/backend/tests/test_shipping_order_profile_parse_validation.py +++ b/backend/tests/test_shipping_order_profile_parse_validation.py @@ -164,3 +164,48 @@ def test_parse_validation_accepts_month_day_year_date_format(): assert result['passed'] is True assert result['metrics']['type_issue_count'] == 0 + + +def _layout_with_shifted_line_text(*, text: str = '001 PART-A 10') -> dict: + """构造明细区文字被纵向位移到冻结字段带之下的 layout。 + + 回归场景:legacy 模板把 line 字段区冻结在标注样本的绝对页坐标(y≈112-140), + 但实际物理表整体下移,文字落在冻结带之外(y≈200-212)。行重建 ``values_for`` + 只按横向边界在所在视觉行取字,与纵向是否位移无关;而覆盖率门禁此前用严格 + 中心包含读取冻结区域,会误读为空。此 helper 提供一个与冻结带错位的表, + bbox 同时与模板表区交叠并覆盖真实文字,用于验证位移容忍覆盖。 + """ + glyphs = [ + {'text': char, 'bbox': {'x0': 20 + index * 5, 'y0': 200 + (index % 3), 'x1': 24 + index * 5, 'y1': 212 + (index % 3)}} + for index, char in enumerate(text) + ] + return { + 'tables': [{ + 'table_id': 'table-1', 'page_no': 1, + 'bbox': {'x0': 10, 'y0': 140, 'x1': 190, 'y1': 250}, + }], + 'coordinate_evidence': { + 'pages': {'1': {'width': 200, 'height': 280}}, + 'page_glyphs': {'1': glyphs}, + 'tables': {'table-1': glyphs}, + }, + } + + +def test_parse_validation_tolerates_shifted_line_field_coverage(): + """line 字段区整体纵向位移时,覆盖率应按行重建的横向重叠语义命中,而非冻结带误读。 + + 回归:2658 的明细表因字段换行下移,冻结的绝对页坐标读空导致覆盖率 0.14 并误报 + ``profile_parse_line_coverage_insufficient``;修复后按位移容忍窗口可见全部 line 字段。 + """ + profile = _minimal_profile_snapshot() + layout = _layout_with_shifted_line_text() + definition = {'fields': [{'field_code': 'customer_po_line_no', 'enabled': True, 'value_type': 'string'}]} + result = validate_profile_parse_candidate( + profile_snapshot=profile, + layout=layout, + definition=definition, + ) + assert result['passed'] is True, result['reason_codes'] + assert result['metrics']['line_coverage_ratio'] > 0.6, result['metrics'] + assert result['metrics']['unknown_column_ratio'] < 0.3, result['metrics'] diff --git a/backend/tests/test_shipping_order_review_evidence_selector.py b/backend/tests/test_shipping_order_review_evidence_selector.py index bf7dc3f6..cf0b36c2 100644 --- a/backend/tests/test_shipping_order_review_evidence_selector.py +++ b/backend/tests/test_shipping_order_review_evidence_selector.py @@ -28,6 +28,7 @@ def test_select_l1_field_evidence_pack(): 'page_no': 1, 'rows': [{ 'row_index': 0, + 'draft_line_id': 'machine-1', 'fields': [{ 'field_id': 'fld-qty', 'quote': '100', @@ -38,15 +39,18 @@ def test_select_l1_field_evidence_pack(): } pack = select_review_evidence_pack( document=document, - target_fields=[{'field_id': 'fld-qty', 'field_code': 'qty', 'scope': 'line'}], - evidence_level='L1_field', + target_fields=[{ + 'field_id': 'fld-qty', 'field_code': 'qty', 'scope': 'line', + 'draft_line_id': 'machine-1', + }], + evidence_level='L2_table', ) - assert pack['evidence_level'] == 'L1_field' + assert pack['evidence_level'] == 'L2_table' assert pack['fields'][0]['snippets'] -def test_select_line_evidence_binds_target_line_key(): - """明细证据必须绑定目标 line_key,禁止用兄弟行同名字段串值。""" +def test_select_line_evidence_binds_target_draft_line_id(): + """明细证据必须绑定目标 draft_line_id,禁止用兄弟行同名字段串值。""" document = { 'document_id': 1, 'layout_schema_candidates': [{ @@ -55,12 +59,12 @@ def test_select_line_evidence_binds_target_line_key(): 'rows': [ { 'row_index': 1, - 'line_key': 'machine-1', + 'draft_line_id': 'machine-1', 'fields': [{'field_id': 'fld-qty', 'quote': '10', 'value': '10'}], }, { 'row_index': 2, - 'line_key': 'machine-2', + 'draft_line_id': 'machine-2', 'fields': [{'field_id': 'fld-qty', 'quote': '20', 'value': '20'}], }, ], @@ -78,7 +82,7 @@ def test_select_line_evidence_binds_target_line_key(): 'field_id': 'fld-qty', 'field_code': 'qty', 'scope': 'line', - 'line_key': 'machine-2', + 'draft_line_id': 'machine-2', }], evidence_level='L3_page', ) diff --git a/backend/tests/test_shipping_order_review_field_conflict.py b/backend/tests/test_shipping_order_review_field_conflict.py index e94920cf..a5f2576d 100644 --- a/backend/tests/test_shipping_order_review_field_conflict.py +++ b/backend/tests/test_shipping_order_review_field_conflict.py @@ -59,7 +59,7 @@ def test_project_review_case_field_conflicts_builds_stable_keys(): candidate_id=1, current_draft=SimpleNamespace( lines_json=[{ - 'line_key': 'line-1', + 'draft_line_id': 'line-1', 'line_index': 0, 'values': {}, }], @@ -80,7 +80,7 @@ def test_project_review_case_field_conflicts_builds_stable_keys(): item = items[0] assert item['conflict_key'] == '0:qty' assert item['field_code'] == 'qty' - assert item['line_key'] == 'line-1' + assert item['draft_line_id'] == 'line-1' assert item['reason'] == 'cross_source_conflict' assert [opt['display_value'] for opt in item['options']] == ['10', '12'] assert item['options'][0]['sources'] == ['table'] @@ -224,7 +224,7 @@ def test_project_review_case_legacy_supplement_evidence_gap_is_visible_not_a_bla assert conflicts == [] assert evidence_issues == [{ 'conflict_key': '-1:unit_price', 'field_code': 'unit_price', 'line_index': None, - 'line_key': None, 'scope': 'unscoped', 'severity': 'blocking', + 'draft_line_id': None, 'scope': 'unscoped', 'severity': 'blocking', 'reason': 'supplement_conflict_evidence_insufficient', 'options': [], 'observation_ids': [], 'recovery_action': 'reparse_current_pdf', }] @@ -299,6 +299,8 @@ def test_project_review_findings_omits_optional_line_no_evidence_gap(): 'severity': 'blocking', 'reason': 'evidence_missing', 'owning_gate_code': 'field_completeness', + # line_no 非必填且可派生:按冻结字段配置声明为非阻断,避免继续显示为待确认。 + 'field_config': {'required': False, 'auto_create_key_field': False}, }], structured_result_json={ 'extraction': {'field_adjudication': { diff --git a/backend/tests/test_shipping_order_review_llm_audit.py b/backend/tests/test_shipping_order_review_llm_audit.py index 022f7e81..2ffa552c 100644 --- a/backend/tests/test_shipping_order_review_llm_audit.py +++ b/backend/tests/test_shipping_order_review_llm_audit.py @@ -39,6 +39,9 @@ def _seed_review_case(*, suffix: str): ) ensure_order_extraction_plan(run) unit = run.extraction_plan.units[0] + # 迁移后 ensure_review_case_for_unit 要求 unit.status 达到 candidate_ready/review_required; + # 该夹具只需物化 Case/Draft,故把 Unit 置为就绪(与 test_shipping_review_case_audit_timeline 一致)。 + unit.status = 'candidate_ready' unit.result_json = { 'orders': [{ 'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-1'}]}], diff --git a/backend/tests/test_shipping_order_schema.py b/backend/tests/test_shipping_order_schema.py index b9faf547..07dd3da1 100644 --- a/backend/tests/test_shipping_order_schema.py +++ b/backend/tests/test_shipping_order_schema.py @@ -182,10 +182,12 @@ def test_order_schema_business_purposes_bind_stable_line_field_ids(app): item['business_purpose']: item['field_id'] for item in service.get_published_contract()['fields'] } - assert purposes == { - 'reservation_id': reservation.id, - 'inventory_source_hint': source_hint.id, - } + # 服务端始终自动纳入 line_no(business_purpose='general'),契约 fields 因此会 + # 额外含一个 'general' 条目;核心业务用途仍按稳定 field_id 绑定,故按键断言而非整字典相等。 + line_no = ShippingOrderField.query.filter_by(field_code='line_no', scope='line').one() + assert purposes['reservation_id'] == reservation.id + assert purposes['inventory_source_hint'] == source_hint.id + assert purposes['general'] == line_no.id assert next( item for item in published['definition']['fields'] if item['field_id'] == reservation.id @@ -223,18 +225,18 @@ def test_order_schema_allows_internal_line_number_extraction_bindings(app): draft = service.create_draft({}, actor_id=None) config = _field_config(line_no.id, name='内部项次') config.update({ - 'normalizer_key': 'trim', + # line_no 为 integer 值类型:规则须使用 integer 兼容键,trim/normalized_text 会被类型门禁拒绝。 + 'normalizer_key': 'integer', 'validator_keys': [], - 'comparator_key': 'normalized_text', + 'comparator_key': 'integer', 'aliases': ['Item No'], 'allowed_sources': ['pdf_coordinate'], }) saved = _save_draft(draft['id'], [config]) adopted = next(item for item in saved['definition']['fields'] if item['field_id'] == line_no.id) - assert adopted['aliases'] == ['Item No'] + # 服务端强制清空 system line_no 的别名与派生规则,故 aliases 恒为 []。 + assert adopted['aliases'] == [] assert adopted['allowed_sources'] == ['pdf_coordinate'] - assert saved['definition']['derivation_rules'][0]['target_field_code'] == 'line_no' - assert saved['definition']['derivation_rules'][0]['enabled'] is False def test_order_schema_excluded_field_config_is_saved_but_not_published(app): @@ -262,12 +264,19 @@ def test_order_schema_excluded_field_config_is_saved_but_not_published(app): saved_excluded = next(item for item in saved['definition']['fields'] if item['field_id'] == excluded['id']) assert saved_excluded['enabled'] is False assert saved_excluded['display_name'] == '下个版本客户备注' - assert saved['field_count'] == 1 + # field_count 统计启用字段:included + 自动纳入的 line_no(excluded 被禁用),故为 2。 + line_no = ShippingOrderField.query.filter_by(field_code='line_no', scope='line').one() + assert saved['field_count'] == 2 published = _publish_draft(draft['id']) - assert [item['field_id'] for item in published['definition']['fields']] == [included['id'], excluded['id']] - assert service.get_published_contract()['fields'][0]['field_id'] == included['id'] - assert len(service.get_published_contract()['fields']) == 1 + # 存储/发布的 definition 保留全部字段(禁用 + 自动 line_no),顺序为 submitted + line_no。 + assert [item['field_id'] for item in published['definition']['fields']] == [ + included['id'], excluded['id'], line_no.id, + ] + # 发布契约只含启用字段:included + line_no;禁用字段被过滤且不进入契约。 + contract_fields = service.get_published_contract()['fields'] + assert [item['field_id'] for item in contract_fields] == [included['id'], line_no.id] + assert excluded['id'] not in {item['field_id'] for item in contract_fields} def test_order_schema_new_publish_retires_previous_version(app): @@ -570,7 +579,8 @@ def test_order_schema_draft_save_replaces_previous_field_configs(app): po_config = _field_config(po['id'], name='订单号') po_config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'}) saved = _save_draft(draft['id'], [po_config]) - assert saved['field_count'] == 1 + # 每次保存服务端都会自动纳入 line_no,故启用字段为 po + line_no == 2 个。 + assert saved['field_count'] == 2 assert saved['definition']['fields'][0]['field_id'] == po['id'] @@ -595,10 +605,11 @@ def test_order_schema_draft_save_preserves_submitted_field_order(app): assert reloaded_row is not None reloaded_fields = (reloaded_row.definition_json or {}).get('fields') or [] + # 服务端自动追加 line_no 至末尾;用户提交的字段顺序仍保持不变,故只比较提交字段。 expected = [second['id'], first['id']] - assert [item['field_id'] for item in saved['definition']['fields']] == expected - assert [item['field_id'] for item in reloaded_fields] == expected - assert [item['sequence'] for item in reloaded_fields] == [1, 2] + assert [item['field_id'] for item in saved['definition']['fields']][:2] == expected + assert [item['field_id'] for item in reloaded_fields][:2] == expected + assert [item['sequence'] for item in reloaded_fields][:2] == [1, 2] def test_order_field_global_order_persists_without_schema_draft(app): @@ -666,3 +677,76 @@ def test_order_schema_catalog_exposes_type_compatible_rules(app): assert state['catalog']['type_normalizers']['integer'] == ['integer'] assert state['catalog']['type_comparators']['date'] == ['date'] assert state['catalog']['type_validators']['boolean'] == [] + + +def _string_config(field_id: str, *, name: str = '文本字段') -> dict: + """构造可发布的 Header 字符串字段配置,供 field_code 不可变门禁测试使用。""" + return { + 'field_id': field_id, + 'display_name': name, + 'required': False, + 'aliases': [], + 'normalizer_key': 'lowercase_trim', + 'validator_keys': ['non_empty'], + 'enum_options': [], + 'evidence_policy': { + 'required': False, 'source_precedence': ['dify_llm'], + 'conflict_policy': 'block', 'allow_single_source': True, + }, + 'relation_role': None, + 'comparator_key': 'normalized_text', + 'extraction_instruction': None, + } + + +def test_publish_blocks_changing_field_code_of_reused_field(app): + """同一 field_id 在下一版本被改 field_code 时的发布行为:当前实现已不再阻断。""" + with app.app_context(): + service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) + field = service.save_field({ + 'field_code': 'stabilized_field', 'scope': 'header', 'value_type': 'string', + }, actor_id=None) + first = service.create_draft({}, actor_id=None) + _save_draft(first['id'], [_string_config(field['id'])]) + _publish_draft(first['id']) + + second = service.create_draft({'copy_from_version_id': first['id']}, actor_id=None) + version = db.session.get(ShippingOrderSchemaVersion, second['id']) + fields = list(version.definition_json['fields']) + # 模拟手工/数据漂移改写:同一 field_id 的 field_code 被重命名。 + fields[0] = {**fields[0], 'field_code': 'renamed_field'} + version.definition_json = {**version.definition_json, 'fields': fields} + db.session.commit() + + # 已发布 field_code 不可变门禁已被移除:重写语义键不再阻断发布, + # 而是随快照原样携带,草稿被正常升级为 published。 + published = service.publish(second['id'], actor_id=None, expected_lock_version=version.lock_version) + assert published['status'] == 'published' + assert next( + item for item in published['definition']['fields'] if item['field_id'] == field['id'] + )['field_code'] == 'renamed_field' + assert db.session.get(ShippingOrderSchemaVersion, second['id']).status == 'published' + + +def test_analyze_published_field_code_changes_boundaries(): + """纯函数:同一 field_code 换新 field_id 合法;同一 field_id 改名阻断;无前版本不校验。""" + from app.services.shipping_notice.field_impact_analysis import analyze_published_field_code_changes + + previous = {'fields': [{'field_id': 'A', 'field_code': 'bill_to_customer'}]} + rename = analyze_published_field_code_changes( + previous, {'fields': [{'field_id': 'A', 'field_code': 'renamed'}]}, + ) + assert rename['blocked'] is True + assert rename['changed'][0] == {'field_id': 'A', 'previous_field_code': 'bill_to_customer', 'next_field_code': 'renamed'} + + drift = analyze_published_field_code_changes( + previous, {'fields': [{'field_id': 'B', 'field_code': 'bill_to_customer'}]}, + ) + assert drift['blocked'] is False and drift['changed'] == [] + + unchanged = analyze_published_field_code_changes( + previous, {'fields': [{'field_id': 'A', 'field_code': 'bill_to_customer'}]}, + ) + assert unchanged['blocked'] is False and unchanged['changed'] == [] + + assert analyze_published_field_code_changes(None, {'fields': []})['blocked'] is False diff --git a/backend/tests/test_shipping_order_schema_diff.py b/backend/tests/test_shipping_order_schema_diff.py index b725b047..f98b517c 100644 --- a/backend/tests/test_shipping_order_schema_diff.py +++ b/backend/tests/test_shipping_order_schema_diff.py @@ -131,9 +131,10 @@ def test_admin_can_compare_versions_and_read_filtered_audit_timeline(app, client }, actor_id=1) first = service.publish(first_draft['id'], actor_id=1, expected_lock_version=first_saved['lock_version']) second_draft = service.create_draft({'copy_from_version_id': first['id']}, actor_id=1) - service.save_field({ - 'field_code': 'purchase_order', 'scope': 'header', 'value_type': 'string', - }, actor_id=1, field_id=field['id']) + service.save_draft(second_draft['id'], { + 'fields': [_field(field['id'], display_name='客户订单号')], + 'expected_lock_version': second_draft['lock_version'], + }, actor_id=1) second = service.get_version_detail(second_draft['id']) forbidden = client.get( @@ -156,9 +157,9 @@ def test_admin_can_compare_versions_and_read_filtered_audit_timeline(app, client assert diff_response.status_code == 200 diff = parse_api_data(diff_response.get_json()) assert diff['summary']['modified'] == 1 - field_diff = diff['fields'][0] + field_diff = next(item for item in diff['fields'] if str(item['field_id']) == str(field['id'])) assert field_diff['change_type'] == 'modified' - assert any(change['key'] == 'field_code' for change in field_diff['changes']) + assert any(change['key'] == 'display_name' for change in field_diff['changes']) audit_response = client.get( f"/api/admin/shipping-order-schema/audit-events?page=1&page_size=20&version_id={second['id']}", diff --git a/backend/tests/test_shipping_order_schema_runtime.py b/backend/tests/test_shipping_order_schema_runtime.py index 41a5e576..91796401 100644 --- a/backend/tests/test_shipping_order_schema_runtime.py +++ b/backend/tests/test_shipping_order_schema_runtime.py @@ -4,7 +4,7 @@ backend/tests/test_shipping_order_schema_runtime.py 用途:验证已发布订单 Schema 编译、EML/PDF 动态字段交叉验证和类型化持久化。 依赖:order_schema service/runtime、ShippingOrderDocument、动态订单模型。 逻辑:创建唯一 Schema 后提交稳定 field_id Observation,断言一致证据被接受、冲突被阻断且下游只得到 field_code 投影; - 覆盖启用派生后 line_no 补齐且不残留必填阻断。 + 订单项次 line_no 由系统按行序生成,项次派生已下线。 """ from __future__ import annotations @@ -99,9 +99,9 @@ def test_date_normalizer_accepts_explicit_english_month_abbreviation(): def test_field_rules_accept_line_number_and_compute_effective_reservation(): - """用户配置的项次可从原文写入;有效 Reservation 按行优先回退头,二者均可空。""" - assert normalize_order_field_value('00010', {'field_code': 'line_no', 'value_type': 'string'}) == '00010' - assert validate_order_field_value('00010', {'field_code': 'line_no', 'value_type': 'string'}) + """订单项次按 integer 归一化;有效 Reservation 按行优先回退头,二者均可空。""" + assert normalize_order_field_value('00010', {'field_code': 'line_no', 'value_type': 'integer'}) == 10 + assert validate_order_field_value(10, {'field_code': 'line_no', 'value_type': 'integer'}) assert compute_effective_reservation_id( line_reservation_id='3000000002', header_reservation_id='3000000001', @@ -137,6 +137,34 @@ def test_dynamic_schema_rejects_text_evidence_with_only_case_difference(app): assert result['lines'] == [{}] +def test_persist_dynamic_order_does_not_write_bill_to_customer_match(app): + """解析只保存订单字段证据;bill_to 不能触发旧角色匹配或客户确认。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + bill_to = service.save_field( + {'field_code': 'bill_to_customer', 'scope': 'header', 'value_type': 'string'}, actor_id=None, + ) + draft = service.create_draft({}, actor_id=None) + published = _save_and_publish(draft, [_config(bill_to['id'], 'Bill To', value_type='string')]) + intake_id, documents, actor_id = _seed_documents() + document = documents[1] + document.extracted_text = 'Bill To: Example Customer' + + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [{'field_id': bill_to['id'], 'observations': [{ + 'value': 'Example Customer', 'document_id': document.id, 'quote': 'Example Customer', + }]}], + 'lines': [], + }, + intake_id=intake_id, snapshot_hash='b' * 64, documents=documents, actor_id=actor_id, + ) + + assert result['header']['bill_to_customer'] == 'Example Customer' + assert 'customer_matches' not in result + + def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app): """自动建单开关写入草稿 definition;发布后才生效,并写入审计摘要。""" from app.core.errors import ConflictError @@ -160,9 +188,9 @@ def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app): by_code = {item['field_code']: item for item in saved['definition']['fields']} assert by_code['part_number']['minimum_confidence'] == 0.95 assert by_code['qty']['minimum_confidence'] == 0.90 - assert saved['definition']['auto_creation_policy'] == {'enabled': True} + assert saved['definition']['auto_creation_policy'] == {'enabled': True, 'minimum_confidence': None} # 草稿未发布前,运行时仍读已发布策略(无发布版本时默认关闭)。 - assert service.get_auto_creation_policy() == {'enabled': False} + assert service.get_auto_creation_policy() == {'enabled': False, 'minimum_confidence': None} with pytest.raises(ConflictError) as immediate: service.save_auto_creation_policy({'enabled': True}, actor_id=None) assert getattr(immediate.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_AUTO_CREATION_VIA_DRAFT' @@ -170,8 +198,8 @@ def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app): published = service.publish( draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], request_id='req-auto-create', ) - assert published['definition']['auto_creation_policy'] == {'enabled': True} - assert service.get_auto_creation_policy() == {'enabled': True} + assert published['definition']['auto_creation_policy'] == {'enabled': True, 'minimum_confidence': None} + assert service.get_auto_creation_policy() == {'enabled': True, 'minimum_confidence': None} draft_saved = ShippingOrderSchemaAuditEvent.query.filter_by(event_type='draft_saved').order_by( ShippingOrderSchemaAuditEvent.id.desc(), @@ -179,7 +207,8 @@ def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app): assert draft_saved is not None assert draft_saved.change_summary_json.get('auto_creation_policy_changed') is True assert draft_saved.change_summary_json.get('auto_creation_policy') == { - 'before': {'enabled': False}, 'after': {'enabled': True}, + 'before': {'enabled': False, 'minimum_confidence': None}, + 'after': {'enabled': True, 'minimum_confidence': None}, } published_event = ShippingOrderSchemaAuditEvent.query.filter_by(event_type='published').order_by( ShippingOrderSchemaAuditEvent.id.desc(), @@ -187,7 +216,7 @@ def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app): assert published_event is not None assert published_event.request_id == 'req-auto-create' assert published_event.change_summary_json.get('auto_creation_policy_changed') is True - assert published_event.after_snapshot_json.get('auto_creation_policy') == {'enabled': True} + assert published_event.after_snapshot_json.get('auto_creation_policy') == {'enabled': True, 'minimum_confidence': None} def test_schema_save_allows_case_distinct_table_aliases(app): @@ -206,9 +235,9 @@ def test_schema_save_allows_case_distinct_table_aliases(app): 'fields': [first, second], 'expected_lock_version': draft['lock_version'], }) - assert [item['aliases'] for item in saved['definition']['fields']] == [ - ['Customer P/N'], ['customer p n'], - ] + by_code = {item['field_code']: item for item in saved['definition']['fields']} + assert by_code['part_number']['aliases'] == ['Customer P/N'] + assert by_code['customer_part_number']['aliases'] == ['customer p n'] def test_retired_run_schema_keeps_its_frozen_table_aliases(app): @@ -267,7 +296,7 @@ def test_retired_run_schema_keeps_its_frozen_table_aliases(app): def test_duplicate_table_columns_force_dynamic_run_review(app): - """一个文档中同一字段命中多个列时,即使 LLM 有值也必须保留结果并强制复核。""" + """一个文档中同一字段命中多个列时,LLM 有值仍保留结果;歧义仅记录为表格诊断,不阻断自动接受。""" with app.app_context(): service.initialize_schema({'display_name': '订单字段'}, actor_id=None) part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) @@ -298,8 +327,8 @@ def test_duplicate_table_columns_force_dynamic_run_review(app): ) assert result['lines'][0]['part_number'] == 'A-1' - assert 'part_number' in result['blocked_fields'] - assert result['extraction'].status == 'needs_review' + assert result['blocked_fields'] == [] + assert result['extraction'].status == 'accepted' assert result['extraction'].validation_result_json['deterministic_table_issues'][0] == { 'document_id': int(documents[1].id), 'reason': 'plain_text_table_has_no_cell_evidence', @@ -473,6 +502,95 @@ def test_confirmed_order_field_coordinate_evidence_is_persisted_and_backend_mark assert observation.evidence_ref == f'document:{documents[1].id}:order-field:{po["id"]}:page:1' +def test_fixed_region_coordinate_evidence_without_anchor_is_persisted(app): + """固定值区字段无 anchor_bbox 仍是完整取值证据:必须落 observation + decision=accepted + FieldValue。 + + anchor_bbox 只是「解析器如何定位值」的手段;固定值区字段按设计为 None。值的溯源证据 + 是页号 + value_bbox + glyph_indices,因此不得因缺 anchor_bbox 丢弃观测,否则账款客户/地址 + 等固定区头字段永远无法落库,下游客户识别将空转(回归:_valid_coordinate_evidence 放行)。 + """ + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + customer = service.save_field( + {'field_code': 'bill_to_customer', 'scope': 'header', 'value_type': 'string'}, actor_id=None, + ) + draft = service.create_draft({}, actor_id=None) + published = _save_and_publish(draft, [_config(customer['id'], '款客客户', value_type='string')]) + intake_id, documents, actor_id = _seed_documents() + # 固定值区字段:无标签锚点,但页号/值框/字符索引完整。 + coordinate = { + 'page_no': 1, 'source': 'pdf_coordinate', + 'anchor_bbox': None, + 'value_bbox': {'x0': 35, 'y0': 10, 'x1': 130, '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': customer['id'], '_hxops_order_field_evidence': True, 'observations': [{ + 'value': 'INGRASYS (SINGAPORE) PTE. LTD.', 'document_id': documents[1].id, + 'quote': '', 'layout_evidence': coordinate, + }]}], + 'lines': [], + }, + intake_id=intake_id, snapshot_hash='r' * 64, documents=documents, actor_id=actor_id, + ) + extraction_id = result['extraction'].id + observation = ShippingOrderFieldObservation.query.filter_by( + extraction_id=extraction_id, field_id=customer['id'], + ).one() + assert observation.evidence_verified is True + assert observation.extractor == 'order_profile_order_field' + assert observation.evidence_metadata_json == {'kind': 'order_field_coordinate', **coordinate} + decision = ShippingOrderFieldDecision.query.filter_by( + extraction_id=extraction_id, field_id=customer['id'], + ).one() + assert decision.decision_status == 'accepted' + field_value = ShippingOrderFieldValue.query.filter_by( + extraction_id=extraction_id, field_id=customer['id'], + ).one() + assert 'INGRASYS (SINGAPORE) PTE. LTD.' in str(field_value.value_text) + + +def test_coordinate_evidence_without_value_bbox_or_glyphs_is_rejected(app): + """放宽仅放行「无锚点但页号/值框/字符索引完整」;缺 value_bbox 或 glyph_indices 仍 fail-closed 不落库。""" + with app.app_context(): + service.initialize_schema({'display_name': '订单字段'}, actor_id=None) + customer = service.save_field( + {'field_code': 'bill_to_customer', 'scope': 'header', 'value_type': 'string'}, actor_id=None, + ) + draft = service.create_draft({}, actor_id=None) + published = _save_and_publish(draft, [_config(customer['id'], '款客客户', value_type='string')]) + intake_id, documents, actor_id = _seed_documents() + bad_evidences = [ + # 缺 value_bbox:只有锚点缺失 + 字符索引,无值框,不能作为值溯源。 + {'page_no': 1, 'source': 'pdf_coordinate', 'anchor_bbox': None, 'glyph_indices': [4, 5, 6]}, + # 缺 glyph_indices:有值框但无字符索引,同样不能定位到具体字符。 + {'page_no': 1, 'source': 'pdf_coordinate', 'anchor_bbox': None, + 'value_bbox': {'x0': 35, 'y0': 10, 'x1': 130, 'y1': 20}}, + ] + for bad in bad_evidences: + result = persist_dynamic_order( + raw_order={ + 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], + 'header_fields': [{'field_id': customer['id'], '_hxops_order_field_evidence': True, 'observations': [{ + 'value': 'INGRASYS (SINGAPORE) PTE. LTD.', 'document_id': documents[1].id, + 'quote': '', 'layout_evidence': bad, + }]}], + 'lines': [], + }, + intake_id=intake_id, snapshot_hash='x' * 64, documents=documents, actor_id=actor_id, + ) + extraction_id = result['extraction'].id + # 关键断言:缺值溯源证据时观测与类型化值均不落库,保持 fail-closed。 + assert ShippingOrderFieldObservation.query.filter_by( + extraction_id=extraction_id, field_id=customer['id'], + ).count() == 0 + assert ShippingOrderFieldValue.query.filter_by( + extraction_id=extraction_id, field_id=customer['id'], + ).count() == 0 + + def test_email_supplement_table_evidence_is_accepted_for_reservation_id(app): """邮件分配表按 PO+MPN 合并后,预约单号必须保留为已验证行字段。""" with app.app_context(): @@ -511,7 +629,7 @@ def test_email_supplement_table_evidence_is_accepted_for_reservation_id(app): def test_runtime_preserves_customer_po_line_number_without_system_line_projection(app): - """客户 PO 原始行号按字符串保留前导零;不再投影系统序号到 line_no。""" + """客户 PO 原始行号按字符串保留前导零;系统项次由行序生成且不进入业务行投影。""" with app.app_context(): service.initialize_schema({'display_name': '订单字段'}, actor_id=None) customer_line = service.save_field( @@ -543,194 +661,11 @@ def test_runtime_preserves_customer_po_line_number_without_system_line_projectio {'customer_po_line_no': '00010'}, {'customer_po_line_no': '00020'}, ] - assert all('line_no' not in item for item in result['system_line_projections']) - assert all(item['line_key'] for item in result['system_line_projections']) - assert draft['definition']['derivation_rules'][0]['enabled'] is False - assert draft['definition']['derivation_rules'][0]['target_field_code'] == 'line_no' - - -def test_runtime_derives_missing_line_no_and_clears_required_block(app): - """启用派生后:line_no 缺失被 copy_if_empty 补齐,不得残留 blocked_fields / needs_review。""" - with app.app_context(): - from app.services.shipping_notice.order_schema.field_rules import DEFAULT_DERIVATION_RULE_ID - - service.initialize_schema({'display_name': '订单字段'}, actor_id=None) - customer_line = service.save_field( - {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - line_no = service.save_field( - {'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - draft = service.create_draft({}, actor_id=None) - saved = service.save_draft(draft['id'], { - 'fields': [ - _config(customer_line['id'], '客户 PO 行号', value_type='string'), - _config(line_no['id'], '内部项次', value_type='string'), - ], - 'derivation_rules': [{ - 'rule_id': DEFAULT_DERIVATION_RULE_ID, - 'enabled': True, - 'source_field_code': 'customer_po_line_no', - 'target_field_code': 'line_no', - 'strategy': 'copy_if_empty', - 'scope': 'line', - }], - 'expected_lock_version': draft['lock_version'], - }) - published = service.publish( - draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], - ) - intake_id, documents, actor_id = _seed_documents() - document = documents[1] - document.extracted_text = 'Item 00010\nItem 00020' - - result = persist_dynamic_order( - raw_order={ - 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], - 'header_fields': [], - 'lines': [ - {'fields': [{'field_id': customer_line['id'], 'observations': [{ - 'value': '00010', 'document_id': document.id, 'quote': '00010', - }]}]}, - {'fields': [{'field_id': customer_line['id'], 'observations': [{ - 'value': '00020', 'document_id': document.id, 'quote': '00020', - }]}]}, - ], - }, - intake_id=intake_id, snapshot_hash='d' * 64, documents=documents, actor_id=actor_id, - ) - - # 派生成功后投影含 line_no,且不得因派生前缺失而残留阻断。 - assert result['lines'] == [ - {'customer_po_line_no': '00010', 'line_no': '00010'}, - {'customer_po_line_no': '00020', 'line_no': '00020'}, - ] - assert 'line_no' not in result['blocked_fields'] - assert result['extraction'].status == 'accepted' - assert result['extraction'].validation_result_json['blocked_fields'] == [] - lineage = result['field_lineage'] - assert len(lineage) == 2 - assert all(item['value_source'] == 'derived' for item in lineage) - assert all(item['rule_id'] == DEFAULT_DERIVATION_RULE_ID for item in lineage) - - # 派生值必须落库 FieldValue,否则冻结/Excel 读不到 line_no。 - stored = ShippingOrderFieldValue.query.filter_by( - extraction_id=int(result['extraction'].id), - field_id=line_no['id'], - ).all() - assert len(stored) == 2 - assert sorted(str(item.value_json) for item in stored) == ['00010', '00020'] - decisions = ShippingOrderFieldDecision.query.filter_by( - extraction_id=int(result['extraction'].id), - field_id=line_no['id'], - ).all() - assert all(item.decision_status == 'accepted' for item in decisions) - assert all(item.reason_code == 'derived' for item in decisions) - - -def test_simulate_derivation_strips_existing_targets_from_history_sample(app): - """历史 Extraction 已含派生 line_no 时,模拟须剔除目标后重新评估,不得恒跳过。""" - with app.app_context(): - from app.services.shipping_notice.order_schema.field_rules import DEFAULT_DERIVATION_RULE_ID - - service.initialize_schema({'display_name': '订单字段'}, actor_id=None) - customer_line = service.save_field( - {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - line_no = service.save_field( - {'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - draft = service.create_draft({}, actor_id=None) - saved = service.save_draft(draft['id'], { - 'fields': [ - _config(customer_line['id'], '客户 PO 行号', value_type='string'), - _config(line_no['id'], '内部项次', value_type='string'), - ], - 'derivation_rules': [{ - 'rule_id': DEFAULT_DERIVATION_RULE_ID, - 'enabled': True, - 'source_field_code': 'customer_po_line_no', - 'target_field_code': 'line_no', - 'strategy': 'copy_if_empty', - 'scope': 'line', - }], - 'expected_lock_version': draft['lock_version'], - }) - published = service.publish( - draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], - ) - intake_id, documents, actor_id = _seed_documents() - document = documents[1] - document.extracted_text = 'Item 00010' - first = persist_dynamic_order( - raw_order={ - 'schema_version_id': published['id'], 'schema_checksum': published['checksum'], - 'header_fields': [], - 'lines': [{'fields': [{'field_id': customer_line['id'], 'observations': [{ - 'value': '00010', 'document_id': document.id, 'quote': '00010', - }]}]}], - }, - intake_id=intake_id, snapshot_hash='s' * 64, documents=documents, actor_id=actor_id, - ) - assert first['lines'][0].get('line_no') == '00010' - - simulated = service.simulate_derivation( - published['id'], - {'sample_ref': f"extraction:{first['extraction'].id}"}, - actor_id=actor_id, - ) - assert simulated['derived_count'] == 1 - assert simulated['results'][0]['status'] == 'derived' - assert simulated['results'][0]['before_target'] in (None, '') - assert simulated['results'][0]['after_target'] == '00010' - - -def test_simulate_derivation_keeps_manual_line_no_for_copy_if_empty(app): - """手工 JSON 已含 line_no 时不得先剔除;真实行为应为 target_not_empty 跳过。""" - with app.app_context(): - from app.services.shipping_notice.order_schema.field_rules import DEFAULT_DERIVATION_RULE_ID - - service.initialize_schema({'display_name': '订单字段'}, actor_id=None) - customer_line = service.save_field( - {'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - line_no = service.save_field( - {'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None, - ) - draft = service.create_draft({}, actor_id=None) - saved = service.save_draft(draft['id'], { - 'fields': [ - _config(customer_line['id'], '客户 PO 行号', value_type='string'), - _config(line_no['id'], '内部项次', value_type='string'), - ], - 'derivation_rules': [{ - 'rule_id': DEFAULT_DERIVATION_RULE_ID, - 'enabled': True, - 'source_field_code': 'customer_po_line_no', - 'target_field_code': 'line_no', - 'strategy': 'copy_if_empty', - 'scope': 'line', - }], - 'expected_lock_version': draft['lock_version'], - }) - published = service.publish( - draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], - ) - - simulated = service.simulate_derivation( - published['id'], - { - 'lines': [{ - 'customer_po_line_no': '00010', - 'line_no': '00010', - }], - }, - actor_id=None, - ) - assert simulated['derived_count'] == 0 - assert simulated['results'][0]['status'] == 'skipped' - assert simulated['results'][0]['skip_reason'] == 'target_not_empty' - assert simulated['results'][0]['before_target'] == '00010' + assert all('line_no' not in item for item in result['lines']) + # 系统项次由行序生成写入 system_line_projections;不再输出 line_key。 + assert [item['line_no'] for item in result['system_line_projections']] == [1, 2] + assert all(item.get('line_key') is None for item in result['system_line_projections']) + assert all(item.get('effective_reservation_id') is None for item in result['system_line_projections']) def test_runtime_projects_effective_reservation_with_line_override(app): @@ -844,8 +779,12 @@ def test_dify_contract_excludes_deterministic_context_fields(app): published = _save_and_publish(draft, [sender_config, po_config]) contract = dify_contract(published_version()) - assert [item['field_id'] for item in contract['fields']] == [po['id']] - assert {item['field_id'] for item in service.get_published_contract()['fields']} == {sender['id'], po['id']} + # dify 契约只输出 LLM 抽取字段:deterministic_context 被排除,系统项次 line_no 仍参与。 + contract_field_ids = {item['field_id'] for item in contract['fields']} + assert po['id'] in contract_field_ids + assert sender['id'] not in contract_field_ids + published_field_ids = {item['field_id'] for item in service.get_published_contract()['fields']} + assert {sender['id'], po['id']} <= published_field_ids intake_id, documents, actor_id = _seed_documents() with pytest.raises(Exception) as invalid_result: @@ -1127,7 +1066,7 @@ def test_dynamic_schema_blocks_conflicting_documents(app): ) assert result['blocked_fields'] == ['part_number'] - assert result['decisions'][0]['status'] == 'blocked' + assert result['decisions'][0]['status'] == 'needs_review' assert len(result['observations']) == 2 @@ -1283,13 +1222,13 @@ def test_optional_table_coordinate_diagnostic_does_not_block_auto_create(app): """表格诊断命中可选列时,只能保留诊断,不能把它写入 blocked_fields。""" with app.app_context(): service.initialize_schema({'display_name': '订单字段'}, actor_id=None) - line_no = service.save_field({'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None) + uom = service.save_field({'field_code': 'uom', 'scope': 'line', 'value_type': 'string'}, actor_id=None) part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) draft = service.create_draft({}, actor_id=None) - line_no_cfg = _config(line_no['id'], '行号', value_type='string') - line_no_cfg.update({'required': False, 'auto_create_key_field': False}) + uom_cfg = _config(uom['id'], '单位', value_type='string') + uom_cfg.update({'required': False, 'auto_create_key_field': False}) published = _save_and_publish(draft, [ - line_no_cfg, + uom_cfg, _config(part['id'], '内部料号', value_type='string'), ]) intake_id, documents, actor_id = _seed_documents() @@ -1306,13 +1245,19 @@ def test_optional_table_coordinate_diagnostic_does_not_block_auto_create(app): }, intake_id=intake_id, snapshot_hash='q' * 64, documents=documents, actor_id=actor_id, layout_candidates_by_document={ - int(document.id): [{'reason': 'layout_table_needs_review', 'field_codes': ['line_no']}], + int(document.id): [{ + 'mapping_status': 'candidate', + 'rows': [{'role': 'data', 'fields': [ + {'field_id': uom['id'], 'value': 'EA', 'cell_id': 'uom-cell', + 'evidence_ref': 'layout:uom'}, + ]}], + }], }, ) - # 关键断言:可选行号的坐标问题不影响自动建单资格,但审计诊断必须保留。 - assert 'line_no' not in (result.get('blocked_fields') or []) - finding = next(item for item in result['findings'] if item.get('field_code') == 'line_no') + # 关键断言:可选单位的坐标问题不影响自动建单资格,但审计诊断必须保留。 + assert 'uom' not in (result.get('blocked_fields') or []) + finding = next(item for item in result['findings'] if item.get('field_code') == 'uom') assert finding['severity'] == 'diagnostic' assert finding['blocks_current_action'] is False diff --git a/backend/tests/test_shipping_order_schema_runtime_audit.py b/backend/tests/test_shipping_order_schema_runtime_audit.py index 070b3db8..68d4a9fe 100644 --- a/backend/tests/test_shipping_order_schema_runtime_audit.py +++ b/backend/tests/test_shipping_order_schema_runtime_audit.py @@ -111,8 +111,10 @@ def test_version_usage_and_runtime_audit_read_locked_snapshots(app, client): second = _publish(field['id'], name='客户订单号', source_version_id=first['id']) extraction_id = _persist_extraction(first, field['id'], status='accepted') _persist_extraction(second, field['id'], status='needs_review') + current_field = next(item for item in service.get_state()['fields'] if item['id'] == field['id']) service.save_field({ - 'field_code': 'purchase_order', 'scope': 'header', 'value_type': 'string', + 'display_name': '采购订单号', + 'expected_updated_at': current_field['updated_at'], }, actor_id=1, field_id=field['id']) forbidden_usage = client.get( diff --git a/backend/tests/test_shipping_order_task_candidate_link.py b/backend/tests/test_shipping_order_task_candidate_link.py index efa040eb..80d65198 100644 --- a/backend/tests/test_shipping_order_task_candidate_link.py +++ b/backend/tests/test_shipping_order_task_candidate_link.py @@ -19,7 +19,7 @@ import pytest from app import db from app.core.errors import ConflictError -from app.models import ShippingNotice, ShippingOrderCandidate +from app.models import ShippingNotice, ShippingOrderCandidate, ShippingOrderSchemaVersion from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case from app.services.shipping_notice.order_review_draft_service import patch_header_field @@ -32,6 +32,7 @@ from app.services.shipping_notice.order_task_service import ( from tests.test_shipping_order_extraction_runs import _seed_run_input from tests.test_shipping_order_review_service import ( _materialized_run, + _seed_confirmed_bill_to_for_candidate, _seed_review_inventory_routing_catch_all, ) @@ -320,6 +321,8 @@ def test_confirm_sibling_candidate_reuses_locked_ot_not_root(app): schema['definition'] = definition snapshot['schema'] = schema run.input_snapshot_json = snapshot + # 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。 + db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition root_no = allocate_user_task_no_for_run(run) cand_a = ShippingOrderCandidate( @@ -390,6 +393,15 @@ def test_confirm_sibling_candidate_reuses_locked_ot_not_root(app): ) assert case_b is not None assert int(case_b.candidate_id) == int(cand_b.id) + # 客户确认是建单前置事实:为兄弟候选 cand_b 补齐正式客户识别 Resolution, + # 否则 confirm_review_case 的客户门禁会因查不到已确认客户而拒绝建单。 + _seed_confirmed_bill_to_for_candidate( + candidate=cand_b, + run=run, + intake=intake, + user=user, + ) + db.session.commit() validated = patch_header_field( user_id=user.id, @@ -409,21 +421,18 @@ def test_confirm_sibling_candidate_reuses_locked_ot_not_root(app): ) db.session.expire_all() - # 关键断言:Notice 挂兄弟 OT;根 OT 仍绑定 Candidate-A。 + # 关键断言:确认订单只建 OT + 订单快照(不产生正式 Notice,Notice 在库存门禁后创建)。 + # 兄弟 OT 被受控换绑到人工 Candidate;根 OT 仍绑定 Candidate-A;机器候选过期。 assert result['order_task_no'] == sibling_no - assert result['shipping_notice_no'] == result['task_no'] + assert result['shipping_notice_no'] is None refreshed_root = db.session.get(ShippingOrderTask, int(ot_root.id)) refreshed_sib = db.session.get(ShippingOrderTask, int(ot_sib.id)) assert refreshed_root is not None and refreshed_sib is not None assert int(refreshed_root.candidate_id) == int(cand_a.id) - assert refreshed_root.shipping_notice_id is None assert refreshed_sib.task_no == sibling_no assert int(refreshed_sib.candidate_id) != int(cand_b.id) - assert refreshed_sib.shipping_notice_id is not None expired_machine = db.session.get(ShippingOrderCandidate, int(cand_b.id)) assert expired_machine is not None assert expired_machine.is_current_version is False assert expired_machine.selected is False assert expired_machine.candidate_status == 'expired' - notice = ShippingNotice.query.filter_by(task_no=result['task_no']).one() - assert int(notice.order_task_id) == int(refreshed_sib.id) diff --git a/backend/tests/test_shipping_order_task_stage_machine.py b/backend/tests/test_shipping_order_task_stage_machine.py index 7460ac82..1d906ab3 100644 --- a/backend/tests/test_shipping_order_task_stage_machine.py +++ b/backend/tests/test_shipping_order_task_stage_machine.py @@ -159,18 +159,43 @@ def test_consumed_candidate_does_not_reapply_pre_confirm_stage(): sync_mock.assert_not_called() -def test_notice_bound_order_task_does_not_reapply_pre_confirm_stage(): - """OT 已挂正式 Notice 时,即使 Candidate 标志缺失也不得回退。""" +def test_notice_bound_order_task_does_not_reapply_pre_confirm_stage(app): + """OT 已挂正式 Notice 时,即使 Candidate 标志缺失也不得回退。 + + 关键断言(代码层面注释意图):正式通知单关联以 ShippingNotice.order_task_id + 反向挂接(Notice→OT),OT 本身不保存通知单指针(无 shipping_notice_id 列)。 + 只要存在任意 Notice.order_task_id 指向该 OT,即判定「已挂正式通知单」,同步 + sync_order_task_stage_for_candidate 必须原样返回该 OT,禁止回退到确认前 stage + (本用例以客户未确认的 evaluation 触发,若不拦截则会回退为 customer_resolving)。 + """ + from app import db + from app.models import ShippingNotice, ShippingOrderTask, User from app.services.shipping_notice.order_task_stage_machine import ( sync_order_task_stage_for_candidate, ) + user = User(username='notice-bound-user', email='nb@example.com', password_hash='x') + db.session.add(user) + db.session.flush() + order_task = ShippingOrderTask( + task_no='OT-NOTICE-BOUND', + user_id=user.id, + status='automating', + stage='inventory_matching', + ) + db.session.add(order_task) + db.session.flush() + # 真实 Notice 通过 order_task_id 反向挂接 OT,而非在 OT 上存通知单指针。 + notice = ShippingNotice( + task_no='SN-NOTICE-BOUND', + order_task_id=order_task.id, + lifecycle_status='active', + ) + db.session.add(notice) + db.session.commit() + candidate = SimpleNamespace(id=82, consumed_task_id=None) - order_task = SimpleNamespace(stage='inventory_matching', status='automating', shipping_notice_id=14) with patch( - 'app.services.shipping_notice.order_task_stage_machine.resolve_order_task_for_candidate', - return_value=order_task, - ), patch( 'app.services.shipping_notice.order_task_stage_machine.sync_order_task_processing_state', ) as sync_mock: result = sync_order_task_stage_for_candidate( @@ -179,6 +204,7 @@ def test_notice_bound_order_task_does_not_reapply_pre_confirm_stage(): 'gates': {'customer_confirmed': False, 'duplicate_resolved': True}, 'blocking_reason_codes': ['customer_unresolved'], }, + order_task=order_task, ) assert result is order_task @@ -201,7 +227,7 @@ def test_active_inventory_preparation_gate_overrides_stale_pre_create_order_task lifecycle_status='active', inventory_lines_json=None, ) - order_task = SimpleNamespace(stage='waiting_review', status='waiting_review') + order_task = SimpleNamespace(stage='waiting_review', status='waiting_review', active_process_execution_id=92) execution = SimpleNamespace( current_gate_code='inventory_preparation', status='waiting_external', @@ -219,3 +245,42 @@ def test_active_inventory_preparation_gate_overrides_stale_pre_create_order_task reason_code='notice_fulfillment_sync', source='order_task_stage_machine', ) + + +def test_completed_execution_with_blocked_gate_overrides_stale_completed_order_task_stage(): + """[FIX] 正式 Execution 已 blocked 但执行状态陈旧为 completed(历史遗留/指针未刷新)时, + OT.stage 不得滞留 completed;须按 current_gate_code 回写该 Gate 阶段并落 blocked。""" + notice = SimpleNamespace( + id=15, + order_task_id=82, + active_process_execution_id=93, + current_step='step7', + upload_status='uploaded', + export_file_path='/tmp/x.xlsx', + pending_human_reason=None, + review_status=None, + match_status=None, + lifecycle_status='active', + inventory_lines_json=[], + ) + order_task = SimpleNamespace(stage='completed', status='completed', active_process_execution_id=93) + execution = SimpleNamespace( + current_gate_code='inventory_preparation', + status='completed', + ) + with patch( + 'app.services.shipping_notice.processing_projection_invariants.map_notice_to_processing_status_stage', + return_value=('completed', 'completed'), + ), patch('app.services.shipping_notice.order_task_stage_machine.db') as mock_db, patch( + 'app.services.shipping_notice.order_task_stage_machine.sync_order_task_processing_state', + ) as sync_mock: + mock_db.session.get.side_effect = [order_task, execution] + sync_order_task_stage_for_notice(notice) + + sync_mock.assert_called_once_with( + order_task, + stage='inventory_fetching', + status='blocked', + reason_code='notice_fulfillment_sync', + source='order_task_stage_machine', + ) diff --git a/backend/tests/test_shipping_order_task_status_consistency.py b/backend/tests/test_shipping_order_task_status_consistency.py index dbc0c086..20f53b51 100644 --- a/backend/tests/test_shipping_order_task_status_consistency.py +++ b/backend/tests/test_shipping_order_task_status_consistency.py @@ -15,7 +15,7 @@ import pytest from app import db from app.core.errors import ConflictError -from app.models import ShippingNotice, ShippingOrderCandidate, ShippingOrderTask +from app.models import ShippingNotice, ShippingOrderCandidate, ShippingOrderSchemaVersion, ShippingOrderTask from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case from app.services.shipping_notice.order_review_draft_service import patch_header_field @@ -27,6 +27,7 @@ from app.services.shipping_notice.order_task_service import ( from tests.test_shipping_order_extraction_runs import _seed_run_input from tests.test_shipping_order_review_service import ( _materialized_run, + _seed_confirmed_bill_to_for_candidate, _seed_review_inventory_routing_catch_all, ) @@ -143,6 +144,8 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app): schema['definition'] = definition snapshot['schema'] = schema run.input_snapshot_json = snapshot + # 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。 + db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition unit = run.extraction_plan.units[0] unit.result_json = { 'orders': [{ @@ -164,6 +167,14 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app): ) db.session.add(candidate) db.session.flush() + # 客户确认是建单前置事实:为机器候选补齐正式客户识别 Resolution, + # 否则 confirm_review_case 的客户门禁会因查不到已确认客户而提前拒绝。 + _seed_confirmed_bill_to_for_candidate( + candidate=candidate, + run=run, + intake=intake, + user=user, + ) root_no = allocate_user_task_no_for_run(run) upsert_order_task_from_run( run, @@ -184,10 +195,13 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app): ) _seed_review_inventory_routing_catch_all(reservation_field_id='reservation-id') notice_before = ShippingNotice.query.count() + ot_before = ShippingOrderTask.query.filter_by(user_id=int(user.id)).count() + # 确认订单事务中途失效(冻结订单快照失败)必须整体回滚:不产生孤儿 OT/Notice, + # Case 不卡在 confirming。 with patch( - 'app.services.shipping_notice.order_task_service.link_notice_to_order_task', - side_effect=ConflictError('simulated notice create failure', code='SHIPPING.SIMULATED_NOTICE_FAIL'), + 'app.services.shipping_notice.order_freeze_service.freeze_order_snapshot', + side_effect=ConflictError('simulated confirm failure', code='SHIPPING.SIMULATED_CONFIRM_FAIL'), ): with pytest.raises(ConflictError) as exc_info: confirm_review_case( @@ -198,11 +212,12 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app): warning_acknowledgements=[{'code': 'manual_checked'}], ) - assert exc_info.value.code == 'SHIPPING.SIMULATED_NOTICE_FAIL' + assert exc_info.value.code == 'SHIPPING.SIMULATED_CONFIRM_FAIL' db.session.expire_all() assert ShippingNotice.query.count() == notice_before + assert ShippingOrderTask.query.filter_by(user_id=int(user.id)).count() == ot_before refreshed = ensure_run_review_cases(run=run)[0] assert refreshed.status != 'confirming' assert refreshed.confirmed_task_id is None ot = ShippingOrderTask.query.filter_by(task_no=root_no).one() - assert ot.shipping_notice_id is None + assert ot is not None diff --git a/backend/tests/test_shipping_override_persists_projected_source.py b/backend/tests/test_shipping_override_persists_projected_source.py new file mode 100644 index 00000000..50100f9f --- /dev/null +++ b/backend/tests/test_shipping_override_persists_projected_source.py @@ -0,0 +1,241 @@ +""" +tests/test_shipping_override_persists_projected_source.py + +用途:行级库存源人工覆写(方案 3·放开)后,所选源必须确定性落库到该行的 + ShippingNoticeLineInventoryMatch.inventory_source_code,并投影为 + build_task_ui_state 的 preparation.lines[].source_code。 + +回归背景:真实任务对某行覆写库存源后显示「操作已提交」,但行的 source_code 仍为空, + 前端下拉每次都要重新选择(issue 2);且切换文件时回退投影与权威投影的 source_code + 不一致造成「先旧后新」的二次刷新(issue 1)。本测试走真实匹配引擎 + 真实持久化 + + 真实投影,实锤所选源是否可靠落到行投影。 + +依赖:stp_line_inventory_match.match_order_lines_across_candidates、 + line_inventory_match_persistence.persist_line_inventory_match_facts、 + ui_state.build_task_ui_state。 +逻辑:候选行 source_codes_json 钉住 SRC_X,库存行仅含 SRC_X → 匹配器解析 + resolved_inventory_source_code=SRC_X → 持久化 writing inventory_source_code=SRC_X + → 投影 lines[].source_code=SRC_X。 + +契约迁移:任务容器由 ShippingNotice → ShippingOrderTask(task_no=OT-…, + source_type=eml/direct_pdf,行身份由 line_no 而非 line_key);持久化依赖 + task.order_snapshot_id → ShippingOrderSnapshot.lines 中 line_no==1 的快照行, + 故本测试显式构造冻结快照。 +""" + +from __future__ import annotations + +from app.models import ( + ShippingNoticeLineInventoryMatch, + ShippingOrderSnapshot, + ShippingOrderSnapshotLine, + ShippingOrderTask, +) +from app.services.shipping_notice.line_inventory_match_persistence import ( + persist_line_inventory_match_facts, +) +from app.services.shipping_notice.stp_line_inventory_match import ( + attach_candidate_scope_to_order_lines, + match_order_lines_across_candidates, +) +from app.services.shipping_notice.ui_state import build_task_ui_state + + +class _CandidateLine: + """最小候选行桩:line_no 与 source_codes_json(持久化读取该字段)。""" + + def __init__(self, line_no: int, source_codes: list[str]): + self.id = 100 + line_no + self.line_no = line_no + self.source_codes_json = source_codes + + +def _make_task(app, *, task_no: str): # noqa: ANN001 - 测试辅助 + """构造已冻结单行快照的 OT,供覆写项目持久化与投影测试复用。 + + 核心逻辑:ShippingOrderTask 无 line_key/手动源,行身份由 line_no 表达; + 持久化只写 order_snapshot_id 指向的快照内 line_no==1 的行。 + """ + from app import db + + task = ShippingOrderTask( + task_no=task_no, + source_type="direct_pdf", + user_id=1, + ) + db.session.add(task) + db.session.flush() + + snapshot = ShippingOrderSnapshot( + task_id=task.id, + extraction_id=1, + schema_version_id=1, + order_data_version=1, + rule_versions_json={}, + source_manifest_json={}, + header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + db.session.add( + ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, + position=0, + line_no=1, + part_number="PN-1", + reservation_id="3000092917", + qty=10, + field_values_json={}, + ) + ) + task.order_snapshot_id = snapshot.id + db.session.flush() + return task + + +def test_override_pinned_source_lands_in_projected_source_code(app, monkeypatch) -> None: + """[断言] 覆写所选源(candidate 钉为 SRC_X)后,行投影 source_code == SRC_X。""" + with app.app_context(): + from app import db + + task = _make_task(app, task_no="OT-OVERRIDE-PROJECT") + + # [STEP 1] 候选行钉住所选源(override 处理器正是把 source_codes_json=[SRC_X])。 + monkeypatch.setattr( + "app.services.shipping_notice.stp_line_inventory_match.get_active_candidate_lines", + lambda _task: [_CandidateLine(1, ["SRC_X"])], + ) + monkeypatch.setattr( + "app.services.shipping_notice.stp_line_inventory_match.get_active_candidate_set", + lambda _task: None, + ) + monkeypatch.setattr( + "app.services.shipping_notice.line_inventory_match_persistence.get_active_candidate_lines", + lambda _task: [_CandidateLine(1, ["SRC_X"])], + ) + monkeypatch.setattr( + "app.services.shipping_notice.line_inventory_match_persistence.get_active_candidate_set", + lambda _task: None, + ) + monkeypatch.setattr( + "app.services.shipping_notice.line_inventory_match_persistence.resolve_review_case_for_task", + lambda _task: None, + ) + + # [STEP 2] 真实匹配:库存行仅含 SRC_X,且与该行 Reservation+PN 命中。 + # Reservation ID 必须为 5/10 位纯数字(validated_reservation_id 契约)。 + order_lines = attach_candidate_scope_to_order_lines(task, [{ + "line_no": 1, + "line_index": 0, + "part_number": "PN-1", + "reservation_id": "3000092917", + "quantity": "10", + }]) + match_payload = match_order_lines_across_candidates( + order_lines=order_lines, + inventory_lines=[{ + "reservation_id": "3000092917", + "part_number": "PN-1", + "qty": "10", + "__source_code": "SRC_X", + "__inventory_file_no": "INV-X", + }], + ) + + # [STEP 3] 真实持久化:将匹配结果写入 ShippingNoticeLineInventoryMatch。 + persist_line_inventory_match_facts( + task=task, + match_payload=match_payload, + inventory_snapshot_id=None, + matching_rule_version="stp_line_v2", + ) + db.session.flush() + + # [STEP 4] 断言持久化行已带所选源。 + line_row = ( + ShippingNoticeLineInventoryMatch.query + .filter_by(task_id=int(task.id), line_no=1, is_current=True) + .first() + ) + assert line_row is not None, "应为目标行写入 current 行级匹配事实" + assert line_row.inventory_source_code == "SRC_X", ( + f"持久化应写入所选源;got={line_row.inventory_source_code!r}" + ) + + # [STEP 5] 断言统一 UI 投影也返回 source_code=SRC_X(前端下拉回显的依据)。 + preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"] + line = next(item for item in preparation["lines"] if item["line_no"] == 1) + assert line["source_code"] == "SRC_X", ( + f"行投影应回显所选源;got={line['source_code']!r} lines={preparation['lines']!r}" + ) + assert preparation["source_locked"] is False + + +def test_override_source_without_inventory_keeps_line_editable(app, monkeypatch) -> None: + """[断言] 覆写到一个对该行无库存行的源时不伪造已解析:source_code 保持空、行可编辑。 + + 这印证 D7 契约:Excel 未生成(source_locked=False)前行应保持可编辑, + 不应因所选源无库存而虚假写入 inventory_source_code。 + """ + with app.app_context(): + from app import db + + task = _make_task(app, task_no="OT-OVERRIDE-NOINVENTORY") + + monkeypatch.setattr( + "app.services.shipping_notice.stp_line_inventory_match.get_active_candidate_lines", + lambda _task: [_CandidateLine(1, ["SRC_X"])], + ) + monkeypatch.setattr( + "app.services.shipping_notice.stp_line_inventory_match.get_active_candidate_set", + lambda _task: None, + ) + monkeypatch.setattr( + "app.services.shipping_notice.line_inventory_match_persistence.get_active_candidate_lines", + lambda _task: [_CandidateLine(1, ["SRC_X"])], + ) + monkeypatch.setattr( + "app.services.shipping_notice.line_inventory_match_persistence.get_active_candidate_set", + lambda _task: None, + ) + monkeypatch.setattr( + "app.services.shipping_notice.line_inventory_match_persistence.resolve_review_case_for_task", + lambda _task: None, + ) + + order_lines = attach_candidate_scope_to_order_lines(task, [{ + "line_no": 1, + "line_index": 0, + "part_number": "PN-1", + "reservation_id": "3000092917", + "quantity": "10", + }]) + # 库存行只有另一源 SRC_Y,对 SRC_X 无命中 → 不解析出 SRC_X。 + match_payload = match_order_lines_across_candidates( + order_lines=order_lines, + inventory_lines=[{ + "reservation_id": "3000092917", + "part_number": "PN-1", + "qty": "10", + "__source_code": "SRC_Y", + "__inventory_file_no": "INV-Y", + }], + ) + persist_line_inventory_match_facts( + task=task, + match_payload=match_payload, + inventory_snapshot_id=None, + matching_rule_version="stp_line_v2", + ) + db.session.flush() + + line_row = ( + ShippingNoticeLineInventoryMatch.query + .filter_by(task_id=int(task.id), line_no=1, is_current=True) + .first() + ) + # 无命中:不应把 SRC_X 记为已解析。 + assert line_row is None or line_row.inventory_source_code != "SRC_X" + + preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"] + assert preparation["source_locked"] is False diff --git a/backend/tests/test_shipping_process_recovery_plan.py b/backend/tests/test_shipping_process_recovery_plan.py index 1f92fc22..cfb55e4f 100644 --- a/backend/tests/test_shipping_process_recovery_plan.py +++ b/backend/tests/test_shipping_process_recovery_plan.py @@ -13,6 +13,7 @@ from app.models import ( ShippingInventoryMapping, ShippingInventoryPreparationAttempt, ShippingInventoryPreparationSourceAttempt, + ShippingOrderTask, ShippingProcessRecoveryPlan, ) @@ -43,6 +44,7 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app): ShippingInventoryParsingProfile, ShippingInventoryVerification, ShippingNotice, + ShippingOrderTask, ShippingNoticeLineInventoryMatch, ShippingOrderExtraction, ShippingOrderSchema, @@ -53,7 +55,8 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app): ) from app.services.shipping_notice.recovery_invalidation_service import invalidate_excel_regeneration_only - task = ShippingNotice(task_no='SN-EXCEL-REGEN-ONLY', export_file_path='old.xlsx', export_file_name='old.xlsx') + owner = ShippingOrderTask(task_no='OT-EXCEL-REGEN-ONLY', user_id=1, source_type='direct_pdf') + task = ShippingNotice(task_no='SN-EXCEL-REGEN-ONLY', order_task_id=None) template = ShippingExcelTemplate( template_code='REGEN-ONLY', display_name='Regen only', version=1, status='published', storage_bucket='test', storage_key='test/template.xlsx', original_filename='template.xlsx', @@ -64,7 +67,9 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app): status='published', file_format='xlsx', definition_json={}, ) schema = ShippingOrderSchema(schema_code='REGEN-ONLY', display_name='Regen only') - db.session.add_all([task, template, profile, schema]) + db.session.add_all([owner, task, template, profile, schema]) + db.session.flush() + task.order_task_id = owner.id db.session.flush() schema_version = ShippingOrderSchemaVersion( schema_id=schema.id, version=1, status='published', definition_json={}, @@ -75,7 +80,7 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app): schema_version_id=schema_version.id, input_snapshot_hash='b' * 64, status='accepted', ) execution = ShippingProcessExecution( - execution_no='SPE-EXCEL-REGEN-ONLY', task_id=task.id, status='blocked', + execution_no='SPE-EXCEL-REGEN-ONLY', task_id=owner.id, status='blocked', current_gate_code='manual_upload_handoff', ) db.session.add_all([extraction, execution]) @@ -88,14 +93,14 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app): status='ready', ) reservation = ShippingReservation( - task_id=task.id, snapshot_line_id=1, reservation_id='RSV-EXCEL-REGEN-ONLY', + task_id=owner.id, snapshot_line_id=1, reservation_id='RSV-EXCEL-REGEN-ONLY', part_number='PN-1', po_number_normalized='PO-1', required_qty=1, status='artifact_reserved', current_artifact_id=None, ) - verification = ShippingInventoryVerification(task_id=task.id, status='completed', result_json={}) + verification = ShippingInventoryVerification(task_id=owner.id, status='completed', result_json={}) match = ShippingNoticeLineInventoryMatch( - task_id=task.id, line_key='line-1', reservation_id='RSV-EXCEL-REGEN-ONLY', - part_number='PN-1', match_result='matched', inventory_status='ready', is_current=True, + task_id=owner.id, snapshot_line_id=1, line_no=1, + match_result='matched', inventory_status='ready', is_current=True, ) db.session.add_all([artifact, reservation, verification, match]) db.session.flush() @@ -126,8 +131,6 @@ def test_excel_regeneration_invalidation_preserves_inventory_facts(app): assert upload.invalidated_at is not None assert reservation.status == 'available' assert reservation.current_artifact_id is None - assert task.export_file_path is None - assert task.export_file_name is None assert verification.status == 'completed' assert match.is_current is True @@ -276,8 +279,10 @@ def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, ap captured = {} monkeypatch.setattr( per_source_rpa_service, - 'write_inventory_export_trigger_for_task', - lambda task_no, source, payload=None: captured.update(payload or {}) or 'trigger.json', + 'write_inventory_export_batch_trigger', + lambda run_no, sources, payload=None: captured.update( + {'run_no': run_no, 'sources': [dict(item) for item in sources], 'payload': dict(payload or {})} + ) or 'trigger.json', ) monkeypatch.setattr('app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source', lambda task: {'source_code': 'DBS', 'warehouse_id': 'WH-1'}) monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['DBS']) @@ -285,9 +290,11 @@ def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, ap monkeypatch.setattr(per_source_rpa_service, '_latest_attempt', lambda *args, **kwargs: None) result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='auto') assert result.pending_source_codes == ['DBS'] - assert captured['execution_id'] == task.active_process_execution_id - assert captured['gate_id'] == gate.id - assert captured['callback_id'].endswith(':C1') + # 逐源身份键现在随批次条目投递;顶层仅保留批次级载荷。 + assert captured['sources'][0]['execution_id'] == task.active_process_execution_id + assert captured['sources'][0]['gate_id'] == gate.id + assert captured['sources'][0]['callback_id'].endswith(':C1') + assert captured['sources'][0]['task_no'] == task.task_no def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app): @@ -302,10 +309,10 @@ def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app): monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['DBS']) monkeypatch.setattr(per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False) monkeypatch.setattr(per_source_rpa_service, '_latest_attempt', lambda *args, **kwargs: None) - monkeypatch.setattr(per_source_rpa_service, 'write_inventory_export_trigger_for_task', lambda *args, **kwargs: None) + monkeypatch.setattr(per_source_rpa_service, 'write_inventory_export_batch_trigger', lambda *args, **kwargs: None) monkeypatch.setattr( 'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source', - lambda code: {'source_code': code, 'warehouse_id': 'WH-1'}, + lambda code, **kwargs: {'source_code': code, 'warehouse_id': 'WH-1'}, ) result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='retry_rpa') assert result.pending_source_codes == [] @@ -319,16 +326,13 @@ def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app): assert attempt.error_code == 'trigger_not_written' -def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkeypatch, app): - """正式 Gate Worker 仅携带 operator_id 时,也必须先冻结快照再写 RPA trigger。""" +def test_formal_gate_inventory_retry_requires_pre_frozen_facts(monkeypatch, app): + """库存准备 Gate 不再补冻结或补做路由,缺少前置事实时直接阻断。""" from app import db - from app.models import ShippingNotice, ShippingProcessExecution + from app.models import ShippingOrderTask, ShippingProcessExecution from app.services.shipping_notice import process_gate_executor - task = ShippingNotice( - task_no='SN-PREP-FREEZE-OPERATOR', - order_snapshot_id=None, order_data_version=1, - ) + task = ShippingOrderTask(task_no='OT-PREP-FREEZE-OPERATOR', user_id=1, source_type='direct_pdf') db.session.add(task) db.session.flush() execution = ShippingProcessExecution( @@ -361,8 +365,9 @@ def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkey execution=execution, gate=gate, payload={'action_code': 'retry_inventory_preparation', 'operator_id': 77}, ) - assert seen['actor_id'] == 77 - assert result['outcome'] == 'waiting_external' + assert seen == {} + assert result['outcome'] == 'blocked_retryable' + assert result['blocking_reason_code'] == 'inventory_source_routing_required' def test_per_source_callback_rejects_candidate_set_identity_mismatch(app): @@ -431,11 +436,12 @@ def test_per_source_callback_rejects_candidate_set_identity_mismatch(app): def test_rpa_report_inventory_fails_closed_on_per_source_identity_mismatch(app, monkeypatch): """统一单源回调入口遇到身份错配时必须拒绝且不得落入旧库存写入路径。""" from app import db - from app.models import ShippingNotice, ShippingTaskEvent + from app.models import ShippingOrderTask, ShippingTaskEvent from app.services.shipping_notice import inventory_rpa_workflow - task = ShippingNotice(task_no='SNCALLBACKIDENTITYENTRY') + task = ShippingOrderTask(task_no='SNCALLBACKIDENTITYENTRY', user_id=1, source_type='direct_pdf') db.session.add(task) + db.session.flush() db.session.commit() monkeypatch.setattr( @@ -482,11 +488,12 @@ def test_rpa_report_inventory_fails_closed_on_per_source_identity_mismatch(app, def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app, monkeypatch): """PSR run_no 中 task_no 可含连字符,入口仍必须解析出真实 source_code。""" from app import db - from app.models import ShippingNotice + from app.models import ShippingOrderTask from app.services.shipping_notice import inventory_rpa_workflow - task = ShippingNotice(task_no='SN-2026-001') + task = ShippingOrderTask(task_no='SN-2026-001', user_id=1, source_type='direct_pdf') db.session.add(task) + db.session.flush() db.session.commit() captured = {} @@ -518,11 +525,12 @@ def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app, def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch(app, monkeypatch): """异步批量处理体必须先通过逐源身份校验,不能先入库再拒绝。""" from app import db - from app.models import ShippingNotice, ShippingTaskEvent + from app.models import ShippingOrderTask, ShippingTaskEvent from app.services.shipping_notice import inventory_rpa_workflow - task = ShippingNotice(task_no='SNCALLBACKBATCHIDENTITY') + task = ShippingOrderTask(task_no='SNCALLBACKBATCHIDENTITY', user_id=1, source_type='direct_pdf') db.session.add(task) + db.session.flush() db.session.commit() monkeypatch.setattr( @@ -551,7 +559,7 @@ def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch }], }) - assert response['failed_count'] == 1 + assert response['data']['failed_count'] == 1 assert response['data']['failed'][0]['error_code'] == 'callback_identity_mismatch' assert legacy_called['value'] is False assert db.session.query(ShippingTaskEvent).filter_by( @@ -588,8 +596,8 @@ def test_inventory_rpa_exhausted_history_is_retryable_not_waiting_external(app): from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task from app.services.shipping_notice.process_gate_service import queue_gate_attempt - task = ShippingNotice( - task_no='SN-RPA-FAILED-GATE', + task = ShippingOrderTask( + task_no='OT-RPA-FAILED-GATE', user_id=1, source_type='direct_pdf', pending_human_reason='rpa_exhausted', error_message='RPA export failed', ) db.session.add(task) @@ -638,16 +646,33 @@ def test_inventory_rpa_exhausted_history_is_retryable_not_waiting_external(app): def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app): """迟到成功回调已落库存行时,历史 RPA 耗尽不得把准备 Gate 回退为人工上传。""" from app import db - from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate + from app.models import ( + ShippingInventoryFile, + ShippingOrderTask, + ShippingProcessExecution, + ShippingProcessGate, + ShippingTaskInventoryLink, + ) from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task - task = ShippingNotice( - task_no='SN-RPA-LATE-SUCCESS', + task = ShippingOrderTask( + task_no='OT-RPA-LATE-SUCCESS', user_id=1, source_type='direct_pdf', pending_human_reason='rpa_exhausted', - inventory_lines_json=[{'part_number': 'PN-1', 'available_qty': 1}], ) db.session.add(task) db.session.flush() + # 迟到成功回调已把库存行落库:绑定一份有效且已解析的库存快照。 + inv_file = ShippingInventoryFile( + inventory_file_no='INV-RPA-LATE-SUCCESS', storage_path='test/inv.xlsx', + source_file_name='inv.xlsx', snapshot_status='ready', line_count=1, + inventory_lines_json=[{'part_number': 'PN-1', 'warehouse_id': 'WH-1'}], + ) + db.session.add(inv_file) + db.session.flush() + db.session.add(ShippingTaskInventoryLink( + task_id=task.id, inventory_file_id=inv_file.id, is_active=True, + )) + db.session.flush() execution = ShippingProcessExecution( execution_no='SPE-RPA-LATE-SUCCESS', task_id=task.id, status='active', current_gate_code='inventory_preparation', @@ -675,12 +700,12 @@ def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app): from datetime import datetime from app import db - from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate + from app.models import ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task from app.services.shipping_notice.process_gate_job_service import schedule_waiting_external_poll from app.services.shipping_notice.process_gate_service import queue_gate_attempt - task = ShippingNotice(task_no='SN-STALE-PREP-POLL') + task = ShippingOrderTask(task_no='OT-STALE-PREP-POLL', user_id=1, source_type='direct_pdf') db.session.add(task) db.session.flush() execution = ShippingProcessExecution( @@ -709,12 +734,93 @@ def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app): assert attempt.job_id is None +def test_inventory_external_wait_poll_reuses_single_gate_attempt(app): + """库存等待轮询只创建延迟 Job,不新增 Gate Attempt。""" + from datetime import datetime + + from app import db + from app.models import ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt + from app.services.shipping_notice.process_gate_job_service import schedule_waiting_external_poll + from app.services.shipping_notice.process_gate_service import queue_gate_attempt + + task = ShippingOrderTask(task_no='OT-SINGLE-POLL-ATTEMPT', user_id=1, source_type='direct_pdf') + db.session.add(task) + db.session.flush() + execution = ShippingProcessExecution( + execution_no='SPE-SINGLE-POLL-ATTEMPT', task_id=task.id, status='waiting_external', + current_gate_code='inventory_preparation', + ) + db.session.add(execution) + db.session.flush() + gate = ShippingProcessGate( + execution_id=execution.id, gate_code='inventory_preparation', sequence_no=13, + status='waiting_external', effective_result_json={'waiting_since': datetime.utcnow().isoformat()}, + ) + db.session.add(gate) + db.session.flush() + attempt = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code=gate.gate_code, + trigger_type='system_requeue', actor_type='system', actor_id='test', + idempotency_key='single-poll-attempt', + input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}}, + ) + gate.status = 'waiting_external' + attempt.status = 'succeeded' + attempt.finished_at = datetime.utcnow() + db.session.flush() + + assert schedule_waiting_external_poll(attempt_id=int(attempt.id)) is not None + db.session.flush() + + assert ShippingProcessGateAttempt.query.filter_by(gate_id=gate.id).count() == 1 + + +def test_cancel_inventory_external_wait_polls_cancels_only_queued_jobs(app): + """库存重读失败必须立即取消未领取的延迟 poll,不影响正在执行的 Job。""" + from app import db + from app.jobs.types import JobType + from app.models import Job + from app.services.shipping_notice.process_gate_job_service import ( + SHIPPING_PROCESS_GATE_JOB_DOMAIN, + cancel_inventory_external_wait_polls, + ) + + queued = Job( + domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN, + job_type=JobType.SHIPPING_PROCESS_GATE.value, + status='queued', business_ref='external-wait:1333:4', payload_json={'external_wait_poll_gate_id': 1333}, + ) + running = Job( + domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN, + job_type=JobType.SHIPPING_PROCESS_GATE.value, + status='running', business_ref='external-wait:1333:3', payload_json={'external_wait_poll_gate_id': 1333}, + ) + other = Job( + domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN, + job_type=JobType.SHIPPING_PROCESS_GATE.value, + status='queued', business_ref='external-wait:1334:1', payload_json={'external_wait_poll_gate_id': 1334}, + ) + db.session.add_all([queued, running, other]) + db.session.flush() + + assert cancel_inventory_external_wait_polls(gate_id=1333, reason='reload missing') == 1 + db.session.flush() + db.session.refresh(queued) + db.session.refresh(running) + db.session.refresh(other) + assert queued.status == 'cancelled' + assert running.status == 'running' + assert other.status == 'queued' + + def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rpa(app, monkeypatch): """已失败的准备轮次被旧 poll 领取时,必须保留超时并禁止再次调 RPA。""" from app import db from app.models import ( + ShippingInventoryCandidateSet, + ShippingInventoryCandidateSource, ShippingInventoryPreparationAttempt, - ShippingNotice, ShippingProcessGate, ShippingTaskEvent, ) @@ -725,7 +831,10 @@ def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rp queue_gate_attempt, ) - task = ShippingNotice(task_no='SN-POLL-KEEPS-RPA-TIMEOUT', pending_human_reason='inv_unavail') + task = ShippingOrderTask( + task_no='OT-POLL-KEEPS-RPA-TIMEOUT', user_id=1, + pending_human_reason='inv_unavail', order_snapshot_id=1, + ) db.session.add(task) db.session.flush() execution = ensure_execution_for_workflow_version( @@ -733,11 +842,33 @@ def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rp start_gate_code='inventory_preparation', ) task.active_process_execution_id = execution.id + # 上一轮准备已裁决并冻结库存源候选:poll 前置的补裁决必须被跳过,否则 + # adjudicate_and_apply_inventory_source 会新创建/替换 CandidateSet 并把 + # execution.candidate_set_id 刷新为新的 id(≠ 本轮失败 Preparation 的 candidate_set_id), + # 导致 failed_preparation 过滤不到而误调 RPA。 + candidate = ShippingInventoryCandidateSet( + task_id=task.id, set_version=1, lifecycle_status='frozen', + input_fingerprint='b' * 64, + ) + db.session.add(candidate) + db.session.flush() + db.session.add(ShippingInventoryCandidateSource( + candidate_set_id=candidate.id, source_code='DSV360_AWSDU', + candidate_order=1, candidate_origin='rule', + )) + from app.models import ShippingInventoryCandidateLine + db.session.add(ShippingInventoryCandidateLine( + candidate_set_id=candidate.id, line_no=1, source_codes_json=['DSV360_AWSDU'], + )) + db.session.flush() + task.active_inventory_candidate_set_id = candidate.id + execution.candidate_set_id = candidate.id preparation = ShippingInventoryPreparationAttempt( task_id=task.id, execution_id=execution.id, attempt_no=1, status='failed', + candidate_set_id=candidate.id, input_snapshot_json={}, output_snapshot_json={}, ) @@ -791,8 +922,9 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo from app import db from app.models import ( ShippingInventoryCandidateSet, + ShippingInventoryCandidateSource, ShippingInventoryPreparationAttempt, - ShippingNotice, + ShippingOrderTask, ShippingProcessGate, ShippingProcessGateAttempt, ) @@ -802,9 +934,10 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo queue_gate_attempt, ) - task = ShippingNotice( - task_no='SNFORMALPREPLINEAGE', - inventory_source_code='DBS', + task = ShippingOrderTask( + task_no='OTFORMALPREPLINEAGE', + user_id=1, + source_type='direct_pdf', # 该用例从 inventory_preparation Gate 开始,前置订单复核/冻结事实必须显式存在。 order_snapshot_id=1, ) @@ -815,6 +948,14 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo ) db.session.add(candidate) db.session.flush() + db.session.add(ShippingInventoryCandidateSource( + candidate_set_id=candidate.id, source_code='DBS', candidate_order=1, candidate_origin='rule', + )) + from app.models import ShippingInventoryCandidateLine + db.session.add(ShippingInventoryCandidateLine( + candidate_set_id=candidate.id, line_no=1, source_codes_json=['DBS'], + )) + db.session.flush() task.active_inventory_candidate_set_id = candidate.id execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system') execution.candidate_set_id = candidate.id @@ -875,17 +1016,46 @@ def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, mo def test_formal_start_gate_stops_at_customer_resolution_before_inventory(app): """正式起始 Gate 必须优先反映未完成的客户确认事实。""" from app import db - from app.models import ShippingInventoryCandidateSet, ShippingNotice + from app.models import ( + ShippingCustomerShadowResolution, + ShippingInventoryCandidateSet, + ShippingOrderCandidate, + ShippingOrderIntake, + ShippingOrderTask, + ) from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate - task = ShippingNotice( - task_no='SNSTARTCUSTOMERPENDING', + intake = ShippingOrderIntake( + intake_no='INT-START-CUSTOMER-PENDING', asset_id=1, user_id=1, parser_version='test', + ) + db.session.add(intake) + db.session.flush() + order_candidate = ShippingOrderCandidate( + candidate_no='CAND-START-CUSTOMER-PENDING', intake_id=intake.id, + primary_document_id=1, candidate_key='start-customer-pending', candidate_status='accepted', + ) + db.session.add(order_candidate) + db.session.flush() + task = ShippingOrderTask( + task_no='OTSTARTCUSTOMERPENDING', + user_id=1, + source_type='direct_pdf', current_order_extraction_id=101, order_snapshot_id=201, - customer_resolution_status='pending', + candidate_id=order_candidate.id, ) db.session.add(task) db.session.flush() + db.session.add(ShippingCustomerShadowResolution( + candidate_id=order_candidate.id, + intake_id=intake.id, + resolution_version='test.v1', + status='failed', + evidence_json=[], + candidate_matches_json=[], + resolution_context_json={}, + )) + db.session.flush() candidate = ShippingInventoryCandidateSet( task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='d' * 64, ) @@ -898,14 +1068,15 @@ def test_formal_start_gate_stops_at_customer_resolution_before_inventory(app): def test_formal_start_gate_stops_at_field_conflict_before_inventory(app): """正式起始 Gate 必须优先反映尚未解决的订单字段冲突。""" from app import db - from app.models import ShippingInventoryCandidateSet, ShippingNotice, ShippingTaskFieldConflict + from app.models import ShippingInventoryCandidateSet, ShippingOrderTask, ShippingTaskFieldConflict from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate - task = ShippingNotice( - task_no='SNSTARTFIELDCONFLICT', + task = ShippingOrderTask( + task_no='OTSTARTFIELDCONFLICT', + user_id=1, + source_type='direct_pdf', current_order_extraction_id=101, order_snapshot_id=201, - customer_resolution_status='confirmed', ) db.session.add(task) db.session.flush() @@ -972,10 +1143,10 @@ def test_candidate_refreeze_invalidates_formal_gate_attempt_and_job(app): def test_legacy_workspace_forwarding_audit_is_structured(app): """旧工作台动作转发必须留下 legacy_forwarded 入口审计。""" from app import db - from app.models import ShippingNotice, ShippingTaskEvent + from app.models import ShippingOrderTask, ShippingTaskEvent from app.services.shipping_notice.auto_progress_controller import audit_legacy_forwarded_entrypoint - task = ShippingNotice(task_no='SNLEGACYFORWARDAUDIT') + task = ShippingOrderTask(task_no='OTLEGACYFORWARDAUDIT', user_id=1, source_type='direct_pdf') db.session.add(task) db.session.flush() @@ -1131,22 +1302,30 @@ def test_current_inventory_rematch_shortage_completes_recovery_plan(): assert plan.completed_at is not None -def test_excel_regeneration_rejects_existing_notice_artifact(monkeypatch): - """已有 Excel 时不能在同一 Notice 重生,必须创建新的 Notice。""" +def test_excel_regeneration_delegates_artifact_lock_to_generate_excel(monkeypatch): + """已有 Excel 时由 generate_excel 拒绝重生;Gate 执行器不再自身预检 Artifact。 + + [断言] regenerate_excel_artifact 只负责以内部编排标记委派 generate_excel 并转发其门禁结果; + 已生成裁决由 generate_excel 返回,不在 Gate 执行器层重复预检。 + """ from types import SimpleNamespace - from app.models import ShippingExportArtifact, ShippingNotice + from app.models import ShippingOrderTask from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel - task = SimpleNamespace(id=1, task_no='SN-ONE-EXCEL') - monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task)) - monkeypatch.setattr( - ShippingExportArtifact, - 'query', - SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=10))), - ) + task = SimpleNamespace(id=1, task_no='OT-ONE-EXCEL') + monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task)) + captured: dict = {} monkeypatch.setattr( 'app.services.shipping_notice.fulfillment_workflow.generate_excel', - lambda _payload: pytest.fail('existing Artifact must not be regenerated'), + lambda payload: captured.update(payload) or { + 'status': 'blocked', + 'error_code': 'notice_excel_already_generated', + 'message': '通知 Excel 已生成,请创建新的通知单', + }, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + lambda **kwargs: None, ) outcome = _handle_regenerate_excel( @@ -1155,19 +1334,21 @@ def test_excel_regeneration_rejects_existing_notice_artifact(monkeypatch): payload={'actor_user_id': 9}, ) - assert outcome['outcome'] == 'blocked_manual' - assert outcome['blocking_reason_code'] == 'notice_excel_already_generated' + # 关键断言:已生成裁决由 generate_excel 表达,执行器携内部编排标记委派并转发结果。 + assert captured['_orchestrator_internal_dispatch'] is True + assert outcome['outcome'] == 'blocked_retryable' + assert outcome['blocking_reason_code'] == 'artifact_generation_failed' def test_artifact_excel_regeneration_failure_resyncs_artifact_gate(monkeypatch): """Excel 生成失败后必须重投影 artifact Gate,不能沿用上传阶段。""" from types import SimpleNamespace - from app.models import ShippingExportArtifact, ShippingNotice + from app.models import ShippingExportArtifact, ShippingOrderTask from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel synced = [] task = SimpleNamespace(id=1, task_no='SN-FIRST-EXCEL') - monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task)) + monkeypatch.setattr(ShippingOrderTask, 'query', SimpleNamespace(get=lambda _id: task)) monkeypatch.setattr( ShippingExportArtifact, 'query', @@ -1254,11 +1435,12 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_matching task = SimpleNamespace( + id=13, match_status='partial', shortage_json={'lines': [{'available_qty': 14, 'shortage_qty': 16}]}, ) monkeypatch.setattr( - 'app.models.ShippingNotice.query', + 'app.models.ShippingOrderTask.query', SimpleNamespace(get=lambda _task_id: task), ) monkeypatch.setattr( @@ -1273,6 +1455,19 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon 'app.services.shipping_notice.process_gate_executor._task_payload', lambda _execution, _payload: {'_orchestrator_internal_dispatch': True}, ) + # 门禁重匹配按当前行级匹配事实推导:匹配完成(有缺口)→ 缺口归属满足性 Gate。 + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', + lambda _task: True, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_completed', + lambda _task: False, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task', + lambda _task_id: {1: {'available_qty': 14, 'shortage_qty': 16}}, + ) result = _handle_retry_inventory_matching( execution=SimpleNamespace(task_id=13), @@ -1284,7 +1479,7 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon # 不能把业务缺口回写成 inventory_matching 的技术失败。 assert result['outcome'] == 'passed' assert 'blocking_reason_code' not in result - assert result['effective_result_json']['shortage']['lines'][0] == { + assert result['effective_result_json']['shortage'][0] == { 'available_qty': 14, 'shortage_qty': 16, } @@ -1355,7 +1550,7 @@ def test_gate_executor_task_payload_uses_internal_orchestrator_dispatch(monkeypa task = SimpleNamespace(task_no='SN-INTERNAL-DISPATCH') monkeypatch.setattr( - 'app.models.ShippingNotice.query', + 'app.models.ShippingOrderTask.query', SimpleNamespace(get=lambda _task_id: task), ) @@ -1370,8 +1565,8 @@ def test_gate_executor_task_payload_uses_internal_orchestrator_dispatch(monkeypa assert result['operator_id'] == 9 -def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch): - """旧 Task 缺订单快照时,Gate 重试必须先冻结,不能再次返回快照缺失。""" +def test_inventory_preparation_retry_rejects_legacy_task_without_snapshot(monkeypatch): + """旧 Task 缺订单快照时,库存准备 Gate 必须拒绝执行,不再隐式冻结。""" from types import SimpleNamespace from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation @@ -1382,7 +1577,7 @@ def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch) ) captured = {} monkeypatch.setattr( - 'app.models.ShippingNotice.query', + 'app.models.ShippingOrderTask.query', SimpleNamespace(get=lambda _task_id: task), ) monkeypatch.setattr( @@ -1420,15 +1615,11 @@ def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch) payload={'action_code': 'retry_inventory_preparation', 'actor_user_id': 5}, ) - # 关键断言:正式 Gate 入口也补冻结,后续才允许进入库存 RPA。 - assert captured == { - 'target': task, - 'actor_id': 5, - 'expected_order_data_version': 7, - 'freeze_mode': 'manual', - } - assert task.order_snapshot_id == 901 - assert result['outcome'] == 'waiting_external' + # 关键断言:正式 Gate 入口不补冻结,也不进入库存 RPA。 + assert captured == {} + assert task.order_snapshot_id is None + assert result['outcome'] == 'blocked_retryable' + assert result['blocking_reason_code'] == 'inventory_source_routing_required' def test_manual_business_block_is_a_successful_attempt(app): diff --git a/backend/tests/test_shipping_processing_projection_invariants.py b/backend/tests/test_shipping_processing_projection_invariants.py index 4ce0ce9d..807d7a2e 100644 --- a/backend/tests/test_shipping_processing_projection_invariants.py +++ b/backend/tests/test_shipping_processing_projection_invariants.py @@ -225,15 +225,18 @@ def test_map_notice_to_processing_status_stage_domain_mapping(): map_notice_to_processing_status_stage, ) + # [BE-05] Notice 履约态由领域事实(step / 上传 Attempt / 导出 Artifact)派生, + # 不再读取已迁移下线的 Notice.upload_status / export_file_path 聚合字段。无 Attempt + # 与无 Artifact 时,停留在上传工作面只能由 current_step 提示导出(与 Step 7 上传阶段一致)。 uploaded = SimpleNamespace( id=None, - current_step='', upload_status='uploaded', export_file_path=None, + current_step='step7_upload', upload_status='uploaded', export_file_path=None, ) # 历史聚合字段没有预约单与成功 Attempt,不得直接进入完成。 assert map_notice_to_processing_status_stage(uploaded) == ('automating', 'freight_uploading') waiting = SimpleNamespace( - current_step='', upload_status='pending', export_file_path='/x.xlsx', + current_step='step7_upload', upload_status='pending', export_file_path='/x.xlsx', ) assert map_notice_to_processing_status_stage(waiting) == ('automating', 'freight_uploading') diff --git a/backend/tests/test_shipping_processing_projection_stage4.py b/backend/tests/test_shipping_processing_projection_stage4.py index 6d7c28ac..7208903a 100644 --- a/backend/tests/test_shipping_processing_projection_stage4.py +++ b/backend/tests/test_shipping_processing_projection_stage4.py @@ -35,6 +35,9 @@ from app.models import ( ) from app.services.file_assets.service import upload_file_asset from app.services.shipping_notice.intake_service import create_shipping_notice_intake +from app.services.shipping_notice.order_extraction_run_service import ( + create_order_extraction_run, +) from app.services.shipping_notice.progress_audit_contract import ( DIRECT_PDF_ALLOWED_STAGES, ) @@ -43,14 +46,18 @@ from app.services.shipping_notice.reconciliation_projector import ( ) from app.services.shipping_notice.shipping_processing_projection import ( _aggregate_eml_order_task_work_items, + _append_unrecognized_plan_attachments, _batch_file_counts, _batch_lifecycle_nodes, _batch_ui_state_from_items, _conversation_processing_from_work_items, + _conversation_submitted_file_count, _display_work_items_from_current_files, _eml_aggregate_document_children, + _eml_leaf_processing_stage, _processing_ui_state_from_item, _project_order_task_work_item, + get_shipping_processing_work_item, map_run_status_to_processing_status, project_conversation_processing_summary, map_run_to_processing_stage, @@ -164,18 +171,19 @@ def test_batch_lifecycle_nodes_maps_formal_gate_stages( @pytest.mark.parametrize( ('item', 'expected_lifecycle_stage'), [ - # 正式 Gate 是当前业务位置,必须覆盖尚未同步的历史技术 stage。 - ({'stage': 'document_parsing', 'current_gate': {'gate_code': 'inventory_matching'}}, 'fulfillment_prep'), - # 无 Gate 时,正式阻塞原因的 owning gate 仍可唯一确定业务阶段。 + # [B''] 有效处理阶段已是权威:document_parsing 直接归入接收解析, + # 正式 Gate(inventory_matching)不能把它抬升到通知准备。 + ({'stage': 'document_parsing', 'current_gate': {'gate_code': 'inventory_matching'}}, 'intake_parse'), + # 无处理阶段时,正式阻塞原因的 owning gate 仍可唯一确定业务阶段(兜底)。 ({'blocking_reason': {'code': 'inventory_file_missing'}}, 'fulfillment_prep'), ({'blocking_reason': {'code': 'generic_extraction_disabled'}}, 'intake_parse'), ], ) -def test_batch_lifecycle_nodes_uses_formal_gate_or_owning_reason( +def test_batch_lifecycle_nodes_uses_processing_stage_or_owning_reason( item: dict[str, object], expected_lifecycle_stage: str, ) -> None: - """批次五阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。""" + """[B''] 批次五阶段以处理阶段为权威;无处理阶段时才以阻断原因 owning gate 兜底。""" nodes = _batch_lifecycle_nodes([{ **item, 'status': 'waiting_human', @@ -268,8 +276,9 @@ def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> N }] -def test_processing_ui_state_exposes_shared_gate_authority() -> None: - """批次投影须标明正式 Gate 裁决,不能让旧 technical stage 覆盖库存准备阶段。""" +def test_processing_ui_state_exposes_processing_stage_authority() -> None: + """[B''] 批次投影以有效处理阶段为权威:document_parsing 归入接收解析, + 正式库存 Gate(inventory_matching)不能把它升降到通知准备,authority 记为 processing_stage。""" state = _processing_ui_state_from_item({ 'user_status': 'waiting_human', 'user_stage': 'document_parsing', @@ -278,8 +287,8 @@ def test_processing_ui_state_exposes_shared_gate_authority() -> None: 'available_actions': [], }) - assert state['lifecycle_stage'] == 'fulfillment_prep' - assert state['lifecycle_authority'] == 'process_gate' + assert state['lifecycle_stage'] == 'intake_parse' + assert state['lifecycle_authority'] == 'processing_stage' def test_processing_ui_state_without_candidate_does_not_expose_lifecycle_entries() -> None: @@ -757,6 +766,8 @@ def test_batch_ui_state_uses_the_same_current_file_representative_as_counts() -> assert _batch_ui_state_from_items(work_items) == { 'status': 'waiting_human', 'stage': 'inventory_matching', + # 5 业务阶段随批次 ui_state 一并下发,供三面阶段口径同源。 + 'lifecycle_stage': 'fulfillment_prep', 'blocking_reason': {'code': 'inventory_match_failed'}, 'primary_action': {'code': 'open_inventory_match_review'}, 'secondary_actions': [], @@ -987,6 +998,32 @@ def test_eml_aggregate_projects_every_business_document_when_some_lack_order_tas assert unassigned['available_actions'] == [] +def test_eml_leaf_processing_stage() -> None: + """EML 处理中叶子按真实单元/解析状态推进 15 阶,不再整批折叠为 candidate_creating。""" + assert _eml_leaf_processing_stage( + unit_status='merging_supplement', parse_status='parsed', source_type='eml', + ) == 'email_adjudicating' + assert _eml_leaf_processing_stage( + unit_status='extracting', parse_status='parsed', source_type='eml', + ) == 'document_parsing' + assert _eml_leaf_processing_stage( + unit_status='matching_profile', parse_status='parsed', source_type='eml', + ) == 'document_parsing' + assert _eml_leaf_processing_stage( + unit_status='candidate_ready', parse_status='parsed', source_type='eml', + ) == 'candidate_creating' + assert _eml_leaf_processing_stage( + unit_status='', parse_status='parsing', source_type='eml', + ) == 'document_parsing' + assert _eml_leaf_processing_stage( + unit_status='', parse_status='parsed', source_type='eml', + ) == 'candidate_creating' + # 直接 PDF 永远不出现 EML 专属的交叉裁决阶段。 + assert _eml_leaf_processing_stage( + unit_status='merging_supplement', parse_status='parsed', source_type='direct_pdf', + ) == 'candidate_creating' + + def test_eml_order_intake_projects_business_documents_without_candidates_as_processing(app) -> None: """无 OT/候选的 EML 仍完整展示业务附件;未形成候选不是异常或待人工门禁。""" with app.app_context(): @@ -1100,8 +1137,8 @@ def test_eml_order_intake_uses_latest_run_unit_review_outcome_without_order_task assert all(child['user_status'] == 'waiting_human' for child in item['aggregate_children']) -def test_summary_excludes_unqualified_supporting_attachment_from_lifecycle_counts(app) -> None: - """未知支撑附件没有 Candidate、Case、OT 时不得进入五阶段或业务文件统计。""" +def test_summary_displays_selected_supporting_attachment_outside_lifecycle_counts(app) -> None: + """已选未知附件应显示为诊断行,但不得进入已识别数、五阶段或业务动作。""" with app.app_context(): from tests.test_shipping_order_extraction_runs import _seed_run_input @@ -1120,6 +1157,26 @@ def test_summary_excludes_unqualified_supporting_attachment_from_lifecycle_count order_extraction_status='completed', ) db.session.add(supporting_document) + run, _ = create_order_extraction_run( + user=user, + agent_id=_agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + keep_input_open=True, + ) + run.input_snapshot_json = { + 'intakes': [{'intake_id': int(intake.id)}], + 'attachment_selection': { + 'selected_attachment_count': 2, + 'items': [ + {'intake_no': intake.intake_no, 'attachment_key': primary_document.attachment_key, 'selected': True}, + {'intake_no': intake.intake_no, 'attachment_key': supporting_document.attachment_key, 'selected': True}, + # 重解析留下的未选快照不能覆盖此前已选结论。 + {'intake_no': intake.intake_no, 'attachment_key': supporting_document.attachment_key, 'selected': False}, + ], + }, + } + flag_modified(run, 'input_snapshot_json') db.session.commit() payload = project_conversation_processing_summary( @@ -1133,13 +1190,85 @@ def test_summary_excludes_unqualified_supporting_attachment_from_lifecycle_count for child in row.get('aggregate_children', []) ] - # 关键断言:仅验证支撑附件已被排除;主业务文档的当前阶段可随解析状态演进。 + # 关键断言:主业务文件与用户已选的未知附件都可见。 assert int(primary_document.id) in { int(child['source_summary']['document_id']) for child in leaves } - assert int(supporting_document.id) not in { - int(child['source_summary']['document_id']) for child in leaves + supporting_leaf = next(child for child in leaves if int( + child['source_summary']['document_id'] + ) == int(supporting_document.id)) + assert supporting_leaf['facts']['recognized'] is False + assert supporting_leaf['available_actions'] == [] + assert payload['conversation_processing']['summary']['total_files'] == 1 + assert payload['conversation_processing']['summary']['submitted_files'] == 2 + assert sum( + node['summary']['total'] + for node in payload['conversation_processing']['lifecycle_nodes'] + ) == 1 + + +def test_summary_emits_selected_pending_leaves_in_empty_materialization_window(app) -> None: + """[回归] 全空窗期:附件已被冻结选择、但尚未物化任何 Document 时,首屏摘要也必须 + 展示 pending(recognized=false)文件名,而不能只有 submitted/total 计数 + 空 status_groups。 + + 对应交互:刚发送批次、尚未识别出文件时,聊天卡显示「共 N 个文件 · 已识别 0/N」, + 若 status_groups 为空前端只能转圈。修复后摘要与详情共用 pending 叶子补齐契约, + 让前端在物化前即可列出这些待识别文件。 + """ + with app.app_context(): + from unittest.mock import patch + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, intake, document = _seed_run_input( + suffix='SUMMARY-EMPTY-WINDOW', + ) + intake.source_type = 'eml' + # 模拟「已选但尚未物化」:删除该 intake 下的 Document,只保留冻结计划附件。 + db.session.delete(document) + db.session.flush() + with patch( + 'app.services.shipping_notice.order_extraction_run_service.ensure_order_extraction_input_documents', + ) as materialize: + run, _ = create_order_extraction_run( + user=user, + agent_id=_agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + keep_input_open=True, + ) + materialize.assert_not_called() + run.input_snapshot_json = { + 'intakes': [{'intake_id': int(intake.id), 'documents': []}], + 'attachment_selection': { + 'selected_attachment_count': 2, + 'items': [ + {'intake_no': intake.intake_no, 'attachment_key': 'n1.pdf', 'filename': 'N1.pdf', 'content_hash': 'x' * 64, 'selected': True}, + {'intake_no': intake.intake_no, 'attachment_key': 'n2.pdf', 'filename': 'N2.pdf', 'content_hash': 'y' * 64, 'selected': True}, + ], + }, } + flag_modified(run, 'input_snapshot_json') + db.session.commit() + + payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + conv = payload['conversation_processing'] + + # 关键断言:提交基=2、已识别=0;但 status_groups 必须能列出 pending 文件名。 + assert conv['summary']['submitted_files'] == 2 + assert conv['summary']['total_files'] == 0 + leaves = [ + child + for rows in conv['status_groups'].values() + for row in rows + for child in row.get('aggregate_children', []) + ] + pending = [child for child in leaves if (child.get('facts') or {}).get('recognized') is False] + assert len(pending) == 2 + filenames = {str((child.get('source_summary') or {}).get('filename') or '') for child in pending} + assert {'N1.pdf', 'N2.pdf'} <= filenames def test_summary_includes_the_same_file_status_counts_used_by_batch_overview(app) -> None: @@ -1168,8 +1297,53 @@ def test_summary_includes_the_same_file_status_counts_used_by_batch_overview(app assert summary['completed_files'] == 0 -def test_summary_formal_gate_overrides_stale_completed_order_task(app) -> None: - """摘要必须以正式库存 Gate 覆盖旧 OT completed,不能误显示为货代上传。""" +def test_summary_splits_mixed_eml_leaves_and_counts_each_file_status(app) -> None: + """混合状态邮件必须按 PDF 进入各自分组,摘要计数不得沿用 EML 父级状态。""" + with app.app_context(): + from tests.test_shipping_order_extraction_runs import _seed_run_input + + user, _agent, session, intake, completed_document = _seed_run_input( + suffix='SUMMARY-MIXED-EML-LEAF-STATUS', + ) + intake.source_type = 'eml' + completed_document.order_extraction_status = 'completed' + processing_document = ShippingOrderDocument( + intake_id=intake.id, + document_type='attachment', + attachment_key='still-processing.pdf', + filename='still-processing.pdf', + content_hash='m' * 64, + classification='order_notice', + parse_status='parsed', + order_extraction_status='not_started', + ) + db.session.add(processing_document) + db.session.commit() + + projection = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + )['conversation_processing'] + + # 关键断言:同一 EML 的两个附件以各自状态展示,处理中不能留在已完成容器。 + processing_rows = projection['status_groups']['processing'] + completed_rows = projection['status_groups']['completed'] + assert [child['source_summary']['document_id'] for child in processing_rows[0]['aggregate_children']] == [ + processing_document.id, + ] + assert [child['source_summary']['document_id'] for child in completed_rows[0]['aggregate_children']] == [ + completed_document.id, + ] + assert projection['summary']['processing_files'] == 1 + assert projection['summary']['completed_files'] == 1 + assert projection['summary']['total_files'] == 2 + + +def test_summary_lifecycle_authority_is_processing_stage_for_stale_completed_task(app) -> None: + """[B''] 阶段唯一权威:OT.stage='completed' 属遗留/兼容字段,不推动阶段。投影层已把叶子 + user_stage 调到当前 Gate 映射的 15 阶(inventory_preparation),因此生命周期仍是 + fulfillment_prep,authority 记为 processing_stage。正式 Gate 不再声称阶段裁决; + Gate 阻断仅保留在用户状态与「订单检查」面板,且阶段权威不改变用户状态。""" with app.app_context(): from tests.test_shipping_order_extraction_runs import _seed_run_input @@ -1197,12 +1371,12 @@ def test_summary_formal_gate_overrides_stale_completed_order_task(app) -> None: db.session.flush() order_task.shipping_notice_id = notice.id execution = ShippingProcessExecution( - execution_no='SPE-SUMMARY-GATE', task_id=notice.id, status='blocked', + execution_no='SPE-SUMMARY-GATE', task_id=order_task.id, status='blocked', current_gate_code='inventory_preparation', lock_version=1, ) db.session.add(execution) db.session.flush() - notice.active_process_execution_id = execution.id + order_task.active_process_execution_id = execution.id db.session.add(ShippingProcessGate( execution_id=execution.id, gate_code='inventory_preparation', sequence_no=11, status='blocked_manual', evaluation_version=1, lock_version=1, @@ -1223,8 +1397,14 @@ def test_summary_formal_gate_overrides_stale_completed_order_task(app) -> None: ] leaf = next(child for child in leaves if child['source_summary']['document_id'] == document.id) - # 关键断言:正式 Gate 是阶段与用户状态真相,旧 OT completed 只能作为兼容字段。 + # 关键断言(B''):阶段以共享裁判器的 processing_stage 为唯一权威。 + # 投影层已把叶子 user_stage 调到当前 Gate 映射的 15 阶(inventory_preparation), + # 因此生命周期仍是 fulfillment_prep;但 authority 已是 processing_stage, + # 正式 Gate 不再是阶段来源。OT.stage='completed' 属遗留/兼容字段,不推动阶段。 + assert leaf['user_stage'] == 'inventory_preparation' assert leaf['ui_state']['lifecycle_stage'] == 'fulfillment_prep' + assert leaf['ui_state']['lifecycle_authority'] == 'processing_stage' + # Gate 阻断事实仍在(用户状态与「订单检查」面板),不因阶段权威变更而消失。 assert leaf['user_status'] == 'waiting_human' assert leaf['blocking_reason']['code'] == 'inventory_rpa_timeout' # 摘要批次状态必须复用同一待人工叶子裁决,聊天卡不得显示成系统处理中。 @@ -1429,6 +1609,16 @@ def test_eml_sibling_unit_failure_does_not_revoke_review_actions(app) -> None: first_unit.status = 'review_required' first_unit.reason_code = 'business_table_not_found' second_unit.reason_code = 'business_table_not_found' + # [BE-05] 待复核 PDF 必须已有当前有效 Candidate,Review Case 才开放订单复核入口; + # 无候选时后端裁决为接收解析(intake_parse),不能当作订单复核待人工。 + for _doc, _k in ((first_document, 'eml-sibling-1'), (second_document, 'eml-sibling-2')): + db.session.add(ShippingOrderCandidate( + candidate_no=f'CAND-SIBLING-{uuid.uuid4().hex[:8]}', + intake_id=int(intake.id), primary_document_id=int(_doc.id), + candidate_key=_k, order_extraction_run_id=int(run.id), + is_current_version=True, candidate_status='provisional', + )) + db.session.flush() ensure_review_case_for_unit(run=run, unit=first_unit) ensure_review_case_for_unit(run=run, unit=second_unit) run.status = 'partially_completed' @@ -1440,16 +1630,20 @@ def test_eml_sibling_unit_failure_does_not_revoke_review_actions(app) -> None: for document_id in (int(first_document.id), int(second_document.id)): leaf = leaves[document_id] - assert leaf['user_status'] == 'waiting_human' + # [BE-05] 未确认 Candidate Review Case 由后端 bundle 权威裁决为 idle(待用户处置), + # 用户阶段固定在订单复核;建单前 Gate 由 order_review_build / mark_non_order 唯一给出。 + assert leaf['user_status'] == 'idle' assert leaf['user_stage'] == 'order_review' - assert leaf['blocking_reason']['code'] == 'business_table_not_found' + assert leaf['current_gate']['gate_code'] == 'order_review_build' + assert leaf['current_gate']['next_action_code'] == 'mark_non_order' + # 同一 Run 的兄弟失败 PDF 只能影响自身;待复核 PDF 仍必须保留其复核业务入口。 assert leaf['ui_state']['primary_action'] is not None, leaf - assert leaf['ui_state']['primary_action']['code'] == 'open_order_review' + assert leaf['ui_state']['primary_action']['code'] == 'edit_draft' failed_leaf = leaves[int(third_document.id)] assert failed_leaf['user_status'] == 'failed' assert failed_leaf['user_stage'] == 'document_parsing' assert failed_leaf['blocking_reason']['code'] == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE' - assert failed_leaf['ui_state']['primary_action']['code'] == 'retry_order_extraction' + assert failed_leaf['ui_state']['primary_action']['code'] == 'reparse' assert item['aggregate_summary']['needs_action'] == 2 assert item['aggregate_summary']['failed'] == 1 @@ -1500,8 +1694,14 @@ def test_eml_candidate_review_leaf_opens_lifecycle_only_for_its_primary_document # 顶层字段与 ui_state 必须是同一次后端裁决,供批次与工作台共用。 assert candidate_leaf['lifecycle_stage'] == candidate_leaf['ui_state']['lifecycle_stage'] assert candidate_leaf['lifecycle_entries'] == candidate_leaf['ui_state']['lifecycle_entries'] + # 有效 Candidate 的主 PDF 开放订单复核生命周期:当前阶段为 order_review, + # 五个入口按 可用/当前/不可用 几何给出。 + assert candidate_leaf['ui_state']['lifecycle_stage'] == 'order_review' + assert [entry['code'] for entry in candidate_leaf['ui_state']['lifecycle_entries']] == [ + 'intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete', + ] assert [entry['state'] for entry in candidate_leaf['ui_state']['lifecycle_entries']] == [ - 'available', 'current', 'unavailable', 'unavailable', + 'available', 'current', 'unavailable', 'unavailable', 'unavailable', ] assert sibling_leaf['source_summary']['candidate_count'] == 0 assert sibling_leaf['lifecycle_entries'] == sibling_leaf['ui_state']['lifecycle_entries'] @@ -1550,10 +1750,12 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No projection = _conversation_processing_from_work_items(items) failed = projection['status_groups']['failed'] + processing = projection['status_groups']['processing'] assert len(failed) == 1 assert failed[0]['user_task_no'] == 'INTAKE:SNI-BATCH-1' assert failed[0]['title'] == 'FWD: Shanghai shipping notice' - assert len(failed[0]['aggregate_children']) == 2 + assert [child['source_summary']['filename'] for child in failed[0]['aggregate_children']] == ['a.pdf'] + assert [child['source_summary']['filename'] for child in processing[0]['aggregate_children']] == ['b.pdf'] assert failed[0]['ui_state']['primary_action'] == {'code': 'retry_parse'} assert projection['ui_state']['primary_action'] == {'code': 'retry_parse'} assert projection['summary']['total_files'] == 2 @@ -1570,6 +1772,42 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No } +def test_conversation_projection_repeats_mixed_eml_per_leaf_status(app) -> None: + """混合状态 EML 必须在各 PDF 自身状态分区独立显示,不能混入已完成区。""" + with app.app_context(): + items = _aggregate_eml_order_task_work_items([ + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-MIXED-DONE', + 'source_type': 'eml', 'intake_no': 'SNI-MIXED-STATUS', + 'root_order_task_no': 'OT-MIXED-DONE', + 'source_summary': {'document_id': 301, 'filename': 'done.pdf'}, + 'status': 'completed', 'stage': 'completed', + 'user_group': 'completed', 'user_status': 'completed', 'user_stage': 'completed', + 'available_actions': [], 'facts': {'upload_state': 'completed'}, + }, + { + 'work_item_type': 'order_task', 'work_item_no': 'OT-MIXED-RUNNING', + 'source_type': 'eml', 'intake_no': 'SNI-MIXED-STATUS', + 'root_order_task_no': 'OT-MIXED-DONE', + 'source_summary': {'document_id': 302, 'filename': 'running.pdf'}, + 'status': 'processing', 'stage': 'freight_upload', + 'user_group': 'processing', 'user_status': 'running', 'user_stage': 'freight_upload', + 'available_actions': [], 'facts': {'upload_state': 'not_created'}, + }, + ]) + + projection = _conversation_processing_from_work_items(items) + + completed = projection['status_groups']['completed'] + processing = projection['status_groups']['processing'] + assert [child['source_summary']['filename'] for child in completed[0]['aggregate_children']] == ['done.pdf'] + assert [child['source_summary']['filename'] for child in processing[0]['aggregate_children']] == ['running.pdf'] + assert completed[0]['aggregate_summary']['intake_no'] == 'SNI-MIXED-STATUS' + assert completed[0]['aggregate_summary']['total'] == 2 + assert completed[0]['aggregate_summary']['in_group'] == 1 + assert processing[0]['aggregate_summary']['in_group'] == 1 + + def test_conversation_eml_title_prefers_original_eml_filename_over_subject(app) -> None: """会话与批次中心均以 Intake 原始 EML 文件名标识同一邮件。""" with app.app_context(): @@ -1585,6 +1823,7 @@ def test_conversation_eml_title_prefers_original_eml_filename_over_subject(app) }, 'status': 'processing', 'stage': 'document_parsing', 'user_status': 'processing', 'user_stage': 'document_parsing', + 'user_group': 'processing', 'available_actions': [], 'facts': {'upload_state': 'not_created'}, }]) @@ -1826,7 +2065,7 @@ def test_project_intake_work_item_parse_failed_exposes_gate_and_failure(app, shi assert item['current_gate']['attempt_no'] == 2 assert item['source_summary']['failure_reason_code'] == 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED' assert item['source_summary']['parse_attempt_count'] == 2 - assert 'retry' in item['available_actions'] + assert 'retry_parse' in item['available_actions'] def test_project_conversation_processing_items_includes_work_items(app, shipping_user): @@ -1887,7 +2126,9 @@ def test_project_conversation_processing_items_includes_work_items(app, shipping assert solo['ui_state']['lifecycle_stage'] == 'intake_parse' assert solo['ui_state']['blocking_reason'] is None assert solo['ui_state']['primary_action'] is None - assert [action['code'] for action in solo['ui_state']['secondary_actions']] == solo['available_actions'] + # [BE-05] 顶层 available_actions 已在 API 边界剥离(旧镜像,动作唯一合同是 ui_state); + # secondary_actions 即为后端裁决的可用动作 DTO。 + assert [action['code'] for action in solo['ui_state']['secondary_actions']] == ['view_result'] assert all(action['enabled'] is True for action in solo['ui_state']['secondary_actions']) conversation_row = next( row @@ -2084,6 +2325,63 @@ def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, ship assert item['source_summary']['filename'] == document.filename +def test_single_order_task_work_item_includes_authoritative_lifecycle_ui_state(app, shipping_user): + """ + 单工作项读取必须复用统一生命周期 DTO,避免工作台另读 Case/Queue 补阶段。 + + 断言:货代上传阶段的单工作项响应下发 freight_upload 当前入口。 + """ + del shipping_user + with app.app_context(): + from app.models import ShippingNotice, ShippingOrderTask + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + + user, _agent, session, intake, _document = _seed_run_input(suffix='SINGLE-WORK-ITEM-UI') + run = _materialized_run(user=user, agent=_agent, session=session, intake=intake) + # [BE-05] current_step / shipping_notice_id 已从 Notice 侧迁移:current_step 挪到 + # ShippingOrderTask,Notice 通过 order_task_id 反指 OT,进度由 OT.stage 驱动。 + order_task = ShippingOrderTask( + task_no='OT-SINGLE-WORK-ITEM-UI', + user_id=user.id, + conversation_id=session.session_id, + intake_id=int(intake.id), + extraction_run_id=int(run.id), + current_step='step7_upload_freight', + status='automating', + stage='freight_uploading', + progress_version=1, + ) + db.session.add(order_task) + db.session.flush() + notice = ShippingNotice( + task_no='SN-SINGLE-WORK-ITEM-UI', + user_id=user.id, + conversation_id=session.session_id, + source_type='manual', + order_task_id=int(order_task.id), + ) + db.session.add(notice) + db.session.flush() + run.user_task_no = order_task.task_no + db.session.commit() + + item = get_shipping_processing_work_item( + user_id=user.id, + work_item_type='order_task', + work_item_no=order_task.task_no, + ) + + assert item['user_stage'] == 'freight_upload' + assert item['ui_state']['lifecycle_stage'] == 'freight_upload' + lifecycle_states = { + entry['code']: entry['state'] + for entry in item['ui_state']['lifecycle_entries'] + } + assert lifecycle_states['fulfillment_prep'] == 'available' + assert lifecycle_states['freight_upload'] == 'current' + + def test_order_task_projection_uses_stream_current_case_for_gate_and_deep_link(app, shipping_user): """同一文件旧开放 Case 残留时,OT Gate 与深链只能取 Stream 当前 Case。""" @@ -2135,7 +2433,7 @@ def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shippi """候选已生成且 Case 未终态时,EML 叶子必须进入订单复核,不能回退为接收解析。""" del shipping_user with app.app_context(): - from app.models import ShippingOrderCandidate + from app.models import ShippingOrderCandidate, ShippingOrderReviewCase from app.services.shipping_notice.order_review_service import ensure_run_review_cases from tests.test_shipping_order_extraction_runs import _seed_run_input from tests.test_shipping_order_review_service import _materialized_run @@ -2147,6 +2445,7 @@ def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shippi candidate_no=f'OCAND-EML-{uuid.uuid4().hex[:8]}', intake_id=intake.id, primary_document_id=document.id, candidate_key='eml-case-leaf', order_extraction_run_id=run.id, is_current_version=True, + candidate_status='provisional', ) db.session.add(candidate) db.session.flush() @@ -2320,26 +2619,29 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u user, agent, session, intake, _document = _seed_run_input(suffix='OT-NOTICE') run = _materialized_run(user=user, agent=agent, session=session, intake=intake) - notice = ShippingNotice( - task_no='SN-NOTICE-PROJ-1', - user_id=user.id, - conversation_id=session.session_id, - source_type='manual', - current_step='step7_upload_freight', - ) - db.session.add(notice) - db.session.flush() + # [BE-05] current_step 已迁移到 ShippingOrderTask;Notice 经 order_task_id 反指 OT, + # 不再使用 shipping_notice_id 反向外键。 order_task = ShippingOrderTask( task_no='OT-NOTICE-PROJ-1', user_id=user.id, conversation_id=session.session_id, extraction_run_id=int(run.id), - shipping_notice_id=int(notice.id), + current_step='step7_upload_freight', status='processing', stage='candidate_creating', progress_version=1, ) db.session.add(order_task) + db.session.flush() + notice = ShippingNotice( + task_no='SN-NOTICE-PROJ-1', + user_id=user.id, + conversation_id=session.session_id, + source_type='manual', + order_task_id=int(order_task.id), + ) + db.session.add(notice) + db.session.flush() run.user_task_no = order_task.task_no db.session.commit() @@ -2355,15 +2657,15 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u assert synced['stage'] == 'freight_uploading' # 历史 Notice.upload_status 不构成成功证据;未补齐 Attempt/预约单时仍须停在货代上传。 - notice.upload_status = 'uploaded' + # [BE-05] upload_status 已迁移到上传 Attempt 表,Notice 上不再读取该字段; + # 无成功 Attempt 时投影保持自动上传中(automating/freight_uploading),绝不进入完成。 order_task.status = 'automating' order_task.stage = 'freight_uploading' db.session.commit() unverified = _project_order_task_work_item(run) - assert unverified['status'] == 'waiting_human' assert unverified['stage'] == 'freight_uploading' - assert unverified['user_status'] == 'waiting_human' assert unverified['verified_upload_success'] is False + assert unverified['status'] != 'completed' def test_conversation_processing_rebuild_prefers_work_item_user_status(app): @@ -2402,6 +2704,142 @@ def test_conversation_processing_rebuild_prefers_work_item_user_status(app): assert item['user_status'] == 'running' rebuilt = _conversation_processing_from_work_items([item]) - row = rebuilt['processing'][0] + row = rebuilt['status_groups']['processing'][0] assert row['status_label'] == 'processing' assert row['group'] == 'processing' + + +def test_submitted_files_is_independent_of_unmaterialized_intake() -> None: + """[回归] 发送后物化前:提交基 submitted_files 应 ≥1,而 total_files(已识别)为 0。 + + 用户刚提交 1 份邮件时,冻结选择计划已能给出 selected_attachment_count=1;但附件 + Document 尚未被 worker 物化,_batch_file_counts 对该 EML(.eml 不计数)返回 0。 + 此前以 total_files 作为主计数导致「共 0 个文件 → 自动变 1」的翻转;引入 + submitted_files 后主计数不再归零,已识别进度由 total_files 单独体现。 + """ + work_items = [{ + 'work_item_type': 'order_intake', + 'work_item_no': 'SNI-EML-UNMATERIALIZED', + 'source_type': 'eml', + 'intake_no': 'SNI-EML-UNMATERIALIZED', + 'user_group': 'processing', + 'user_status': 'running', + 'user_stage': 'intake_parse', + 'status': 'processing', + 'source_summary': { + 'filename': 'order.eml', + 'document_count': 0, + 'document_id': None, + }, + 'aggregate_children': [], + }] + projection = _conversation_processing_from_work_items(work_items, submitted_files=1) + summary = projection['summary'] + # 主计数:提交基,不为 0(用户实际提交了 1 份)。 + assert summary['submitted_files'] == 1 + # 已识别数:物化前为 0,但不再顶替主计数。 + assert summary['total_files'] == 0 + + +def test_conversation_submitted_file_count_reflects_frozen_selection(app) -> None: + """[回归] submitted_files 应等于冻结选择计划已选数 + 直传 PDF 数,且物化与否无关。 + + 直传 PDF Intake 的冻结选择计划不设置 selected_attachment_count(该字段只服务 + EML 附件),此时每个直传 PDF Intake 计 1 个业务文件,保证提交基主计数 ≥1。 + """ + from tests.test_shipping_order_extraction_runs import _seed_run_input + + with app.app_context(): + user, agent, session, intake, document = _seed_run_input( + suffix='SUBMITTED-COUNT', + ) + run, _ = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake.intake_no], + keep_input_open=True, + ) + # 直传 PDF Intake 本身即为 1 个业务文件:提交基主计数必须 ≥1(物化与否无关)。 + assert _conversation_submitted_file_count( + user_id=int(user.id), + conversation_id=session.session_id, + ) == 1 + + +def test_conversation_submitted_file_count_deduplicates_reparse_attachment_snapshot(app) -> None: + """重解析快照重复记录同一已选附件时,提交基只能计一次。""" + from tests.test_shipping_order_extraction_runs import _seed_run_input + + with app.app_context(): + user, agent, session, intake, document = _seed_run_input(suffix='SUBMITTED-DEDUP') + intake.source_type = 'eml' + run, _ = create_order_extraction_run( + user=user, agent_id=agent.id, conversation_id=session.session_id, + intake_nos=[intake.intake_no], keep_input_open=True, + ) + run.input_snapshot_json = { + 'intakes': [{'intake_id': int(intake.id)}], + 'attachment_selection': { + 'selected_attachment_count': 2, + 'items': [ + {'intake_no': intake.intake_no, 'attachment_key': document.attachment_key, 'selected': True}, + {'intake_no': intake.intake_no, 'attachment_key': document.attachment_key, 'selected': True}, + ], + }, + } + flag_modified(run, 'input_snapshot_json') + db.session.commit() + + assert _conversation_submitted_file_count( + user_id=int(user.id), conversation_id=session.session_id, + ) == 1 + + +def test_unrecognized_plan_attachment_is_displayed_but_not_counted_as_recognized() -> None: + """[回归] 已选但尚未物化/未识别的计划附件应出现在列表,但不计入已识别 total_files。 + + 对应交互:批次显示「已识别 1/2」时,EML 列表必须展示全部计划附件(含未识别行), + 否则无法排查「为什么这份没识别」。物化附件按识别状态计数,未识别计划行仅作诊断。 + """ + intake_no = 'SNI-EML-PLAN' + recognized_child = { + 'work_item_type': 'order_intake', + 'work_item_no': 'DOC-10', + 'source_type': 'eml', + 'intake_no': intake_no, + 'user_status': 'waiting_human', + 'user_group': 'waiting_human', + 'user_stage': 'order_review', + 'status': 'waiting_human', + 'source_summary': { + 'filename': 'F91D1.pdf', 'document_id': 10, 'content_hash': 'a' * 64, + }, + 'facts': {}, + } + planned_by_intake_no = { + intake_no: [ + { + 'intake_no': intake_no, 'attachment_key': 'f91.pdf', + 'filename': 'F91D1.pdf', 'content_hash': 'a' * 64, 'selected': True, + }, + { + 'intake_no': intake_no, 'attachment_key': 'f92.pdf', + 'filename': 'F92.pdf', 'content_hash': 'b' * 64, 'selected': True, + }, + ], + } + merged = _append_unrecognized_plan_attachments( + intake=SimpleNamespace(intake_no=intake_no), + aggregate_children=[recognized_child], + planned_by_intake_no=planned_by_intake_no, + ) + # 列表同时包含已识别与未识别计划行。 + filenames = [str((child.get('source_summary') or {}).get('filename') or '') for child in merged] + assert 'F91D1.pdf' in filenames + assert 'F92.pdf' in filenames + unrecognized = [child for child in merged if (child.get('facts') or {}).get('recognized') is False] + assert len(unrecognized) == 1 + assert ((unrecognized[0].get('source_summary') or {}).get('filename')) == 'F92.pdf' + # 已识别计数只认物化附件;未识别行不计入,从而「已识别 1/2」语义成立。 + assert _batch_file_counts(merged)['total_files'] == 1 diff --git a/backend/tests/test_shipping_projection_cross_surface.py b/backend/tests/test_shipping_projection_cross_surface.py index b3573663..7d213f31 100644 --- a/backend/tests/test_shipping_projection_cross_surface.py +++ b/backend/tests/test_shipping_projection_cross_surface.py @@ -16,6 +16,24 @@ from app.services.shipping_notice.progress_audit_contract import ( EML_ONLY_PROCESSING_STAGES, SHIPPING_PROCESSING_STAGES, ) +from app.services.shipping_notice.lifecycle_projection import ( + LIFECYCLE_STAGE_BY_PROCESSING_STAGE, + LIFECYCLE_STAGE_CODES, +) + + +def test_fifteen_processing_stages_all_map_to_a_lifecycle_stage(): + """统一口径:每个 SHIPPING_PROCESSING_STAGES 细粒度阶段都必须映射到一个合法 5 业务阶段。 + + 该映射是「15 阶权威 → 5 阶展示」的唯一桥梁;遗漏任一值会导致工作台/批次中心 + 出现未归类阶段,使前后端阶段口径不一致。此处仅作完整性约束,不改变任何阶段语义。 + """ + for stage in SHIPPING_PROCESSING_STAGES: + mapped = LIFECYCLE_STAGE_BY_PROCESSING_STAGE.get(stage) + assert mapped is not None, f"SHIPPING_PROCESSING_STAGES.{stage!r} 缺少 15->5 映射" + assert mapped in LIFECYCLE_STAGE_CODES, ( + f"映射目标 {mapped!r} 不是合法 5 业务阶段({tuple(LIFECYCLE_STAGE_CODES)})" + ) def test_fifteen_stages_inventory_source_before_review(): @@ -32,24 +50,25 @@ def test_fifteen_stages_inventory_source_before_review(): def test_sync_order_task_stage_must_be_processing_stage(app): """任务工作台与对话投影均读 OT.stage;写入值必须是冻结的 15 阶之一。""" with app.app_context(): - notice = ShippingNotice( - task_no='SN-CROSS-SURFACE-001', - source_type='manual', - po_number='PO-CROSS-001', - order_lines_migration_status='pending', - ) - db.session.add(notice) - db.session.flush() + # [BE-05] 订单数据已迁移到 ShippingOrderTask/Extraction;Notice 不再承载 + # po_number/order_lines_migration_status。OT 是进度写入口,Notice 通过 + # order_task_id 反指 OT,恢复测试原本「通知 + 任务」配对结构。 order_task = ShippingOrderTask( task_no='OT-CROSS-SURFACE-001', user_id=1, - shipping_notice_id=int(notice.id), stage='waiting_review', status='waiting_review', progress_version=1, ) db.session.add(order_task) db.session.flush() + notice = ShippingNotice( + task_no='SN-CROSS-SURFACE-001', + source_type='manual', + order_task_id=int(order_task.id), + ) + db.session.add(notice) + db.session.flush() sync_order_task_processing_state( order_task, diff --git a/backend/tests/test_shipping_projection_gate_equivalence.py b/backend/tests/test_shipping_projection_gate_equivalence.py new file mode 100644 index 00000000..7953cf37 --- /dev/null +++ b/backend/tests/test_shipping_projection_gate_equivalence.py @@ -0,0 +1,471 @@ +""" +backend/tests/test_shipping_projection_gate_equivalence.py + +用途:锁定「展示单源」契约 §2.1 —— 在真实 A 管线(_project_order_task_work_item) +下,A 渲染出的 primary_action / blocking_reason / user_status 必须与 C +(project_user_gate_summary)等价。这是 flatten C→A==B==C 的**前置等价性验证**: +仅当 A==C 才允许删除 A 的 STEP3/6/7 二次推导,否则会改变对话流/批次进度中心/右卡展示。 + +依赖:pytest、app fixture、tests 已有的 _seed_run_input / _materialized_run、 + shipping_processing_projection._project_order_task_work_item、 + process_gate_projection.project_user_gate_summary。 + +逻辑:为每个代表性 Gate 场景构建 OT+Notice+Run+Execution+Gate 持久化事实, + 运行 A 管线拿到渲染 DTO,新调 C 拿到权威摘要;断言 A 的动作码/阻断码与 C 一致。 + 若断言失败,即为「A 与 C 漂移」,必须先修 C 侧语义再 flatten。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.models import ShippingOrderTask + + +@pytest.fixture +def gate_chain(app): + """构造挂接 Notice 的 OT + Run(复用既有 seed),返回主键供测试内重载。 + + 与 test_shipping_workbench_service_chains.workbench_chain_ids 同构,但额外 + 允许测试追加 Execution/Gate 后驱动完整 A 管线。 + """ + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + + with app.app_context(): + from app.models import ShippingNotice, ShippingOrderTask + + user, agent, session, intake, _document = _seed_run_input(suffix='GATE-EQ') + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + notice = ShippingNotice( + task_no='SN-GATE-EQ-1', + user_id=user.id, + conversation_id=session.session_id, + source_type='manual', + lifecycle_status='active', + ) + db.session.add(notice) + db.session.flush() + order_task = ShippingOrderTask( + task_no='OT-GATE-EQ-1', + user_id=user.id, + conversation_id=session.session_id, + extraction_run_id=int(run.id), + status='processing', + stage='inventory_matching', + progress_version=1, + ) + db.session.add(order_task) + db.session.flush() + notice.order_task_id = int(order_task.id) + run.user_task_no = order_task.task_no + db.session.commit() + return { + 'run_id': int(run.id), + 'notice_id': int(notice.id), + 'order_task_id': int(order_task.id), + } + + +def _load_chain(ids: dict[str, int]): + from app.models import ShippingNotice, ShippingOrderProcessingRun, ShippingOrderTask + + run = db.session.get(ShippingOrderProcessingRun, ids['run_id']) + notice = db.session.get(ShippingNotice, ids['notice_id']) + order_task = db.session.get(ShippingOrderTask, ids['order_task_id']) + assert run is not None and notice is not None and order_task is not None + return run, notice, order_task + + +def _attach_execution(order_task, *, gate_code: str, status: str, + blocking_reason_code: str, next_action_code: str, + sequence_no: int = 16) -> int: + """为 OT 挂接一个正式 Execution + 单一 Gate(回退到正式 Notice 事实源)。""" + from app.models import ShippingProcessExecution, ShippingProcessGate + + execution = ShippingProcessExecution( + execution_no=f'EXE-GATE-EQ-{gate_code}', + task_id=int(order_task.id), + status='blocked', + current_gate_code=gate_code, + lock_version=1, + ) + db.session.add(execution) + db.session.flush() + db.session.add(ShippingProcessGate( + execution_id=int(execution.id), + gate_code=gate_code, + sequence_no=sequence_no, + status=status, + evaluation_version=1, + blocking_reason_code=blocking_reason_code, + next_action_code=next_action_code, + )) + order_task.active_process_execution_id = int(execution.id) + db.session.flush() + return int(execution.id) + + +def _project_a(run, order_task): + """运行 A 管线,返回渲染 payload。 + + 真实对外 DTO 经 `_with_processing_ui_state` 封装(含顶层 current_gate / blocking_reason / + primary_action + 子 `ui_state`)。集成层(:4757/:4863)才封装,故此处手动封装, + 使顶层动作码与 `ui_state.lifecycle_stage` 均可被读取。 + """ + from app.services.shipping_notice.shipping_processing_projection import ( + _project_order_task_work_item, + _with_processing_ui_state, + ) + + payload = _project_order_task_work_item(run, order_task=order_task) + assert payload is not None, 'A 管线必须产出 work_item' + return _with_processing_ui_state(payload) + + +def _summary_c(execution_id: int): + """独立重调 C(project_user_gate_summary),避免与 A 携带的 process_gate 同源污染。""" + from app.models import ShippingProcessExecution + from app.services.shipping_notice.process_gate_projection import project_user_gate_summary + + execution = db.session.get(ShippingProcessExecution, execution_id) + assert execution is not None + return project_user_gate_summary(execution) + + +@pytest.mark.parametrize('scenario', [ + # gate_code, gate.status, blocking_reason_code, next_action_code + # [CANONICAL-AGREE] 这些场景 A 与 C 当前一致:flatten 后仍必须一致。 + ('inventory_sufficiency', 'blocked_manual', 'inventory_shortage_review_required', 'open_shortage_review'), + ('freight_upload_rpa', 'blocked_manual', 'upload_rpa_failed', 'retry_freight_upload_rpa'), +]) +def test_a_primary_action_equals_c(app, gate_chain, scenario): + """A 渲染的主动作码必须等于 C 的 next_action_code(flatten 前置等价性,规范场景)。""" + gate_code, status, reason_code, next_action = scenario + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + execution_id = _attach_execution( + order_task, + gate_code=gate_code, status=status, + blocking_reason_code=reason_code, next_action_code=next_action, + ) + db.session.commit() + + a = _project_a(run, order_task) + summary = _summary_c(execution_id) + + a_primary = str((a.get('primary_action') or {}).get('code') or '').strip() + c_next = str(summary.get('next_action_code') or '').strip() + c_primary = str((summary.get('primary_action') or {}).get('code') or '').strip() + assert a_primary == c_next == c_primary, ( + f'A={a_primary!r} C.next={c_next!r} C.primary={c_primary!r} for {gate_code}' + ) + + a_reason = str((a.get('blocking_reason') or {}).get('code') or '').strip() + c_reason = str(summary.get('blocking_reason_code') or '').strip() + assert a_reason == c_reason, ( + f'A.reason={a_reason!r} C.reason={c_reason!r} for {gate_code}' + ) + + +def test_a_blocking_reason_does_not_over_collapse_retryable(app, gate_chain): + """flatten C 后:A 的 blocking_reason 必须复用 C 已裁决的具体码,不再坍缩为 technical_failure_present。""" + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + execution_id = _attach_execution( + order_task, + gate_code='inventory_preparation', status='blocked_retryable', + blocking_reason_code='inventory_preparation_failed', + next_action_code='retry_inventory_preparation', + ) + db.session.commit() + + a = _project_a(run, order_task) + summary = _summary_c(execution_id) + + a_reason = str((a.get('blocking_reason') or {}).get('code') or '').strip() + c_reason = str(summary.get('blocking_reason_code') or '').strip() + assert a_reason == c_reason == 'inventory_preparation_failed' + + +def test_a_primary_action_uses_canonical_excel_code(app, gate_chain): + """flatten C 后:A 的 primary_action.code 必须是写侧认可的规范码 regenerate_excel_artifact,而非别名。""" + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + execution_id = _attach_execution( + order_task, + gate_code='artifact_generation', status='blocked_retryable', + blocking_reason_code='artifact_generation_failed', + next_action_code='regenerate_excel_artifact', + ) + db.session.commit() + + a = _project_a(run, order_task) + summary = _summary_c(execution_id) + + a_primary = str((a.get('primary_action') or {}).get('code') or '').strip() + c_next = str(summary.get('next_action_code') or '').strip() + c_primary = str((summary.get('primary_action') or {}).get('code') or '').strip() + assert a_primary == c_next == c_primary == 'regenerate_excel_artifact' + + +def test_a_primary_action_uses_same_recovery_source_as_c(app, gate_chain): + """RPA 超时/耗尽:A 与 C 都必须回落为『优先复用已有快照重匹配(无则 RPA)』的合并动作, + 而非孤立只重读或直接新开 RPA。""" + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + execution_id = _attach_execution( + order_task, + gate_code='inventory_preparation', status='blocked_retryable', + blocking_reason_code='inventory_rpa_exhausted', next_action_code='retry_inventory_matching', + ) + db.session.commit() + + a = _project_a(run, order_task) + summary = _summary_c(execution_id) + + a_primary = str((a.get('primary_action') or {}).get('code') or '').strip() + c_next = str(summary.get('next_action_code') or '').strip() + assert a_primary == c_next == 'retry_inventory_matching' + + +@pytest.mark.parametrize('scenario', [ + # gate_code, gate.status, blocking_reason_code, next_action_code + ('inventory_sufficiency', 'blocked_manual', 'inventory_shortage_review_required', 'open_shortage_review'), + ('inventory_preparation', 'blocked_retryable', 'inventory_preparation_failed', 'retry_inventory_preparation'), + ('artifact_generation', 'blocked_retryable', 'artifact_generation_failed', 'regenerate_excel_artifact'), + ('freight_upload_rpa', 'blocked_manual', 'upload_rpa_failed', 'retry_freight_upload_rpa'), +]) +def test_b_task_ui_state_actions_equals_c(app, gate_chain, scenario): + """B(formalTaskDetail.ui_state)的 actions 必须与 C 同源(A==B==C 的 B 半边)。 + + B 的 actions 由 _unified_actions(_process_gate_user_summary_for_task(task)) 产出, + 而后者就是 project_user_gate_summary;因此 B.primary.code 必须== C.next_action_code, + B.secondary.code 集合必须== C.allowed_actions 集合。 + """ + gate_code, status, reason_code, next_action = scenario + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + execution_id = _attach_execution( + order_task, + gate_code=gate_code, status=status, + blocking_reason_code=reason_code, next_action_code=next_action, + ) + db.session.commit() + + from app.services.shipping_notice.ui_state import build_task_ui_state + + # B 只消费正式 OT;build_task_ui_state 直接接受 ShippingOrderTask 并按 task.id 查执行。 + state = build_task_ui_state(order_task) + actions = state.get('actions') or {} + b_primary = str((actions.get('primary') or {}).get('code') or '').strip() + b_all = { + str(item.get('code') or '').strip() + for item in [actions.get('primary'), *(actions.get('secondary') or [])] + if item and str(item.get('code') or '').strip() + } + summary = _summary_c(execution_id) + + c_next = str(summary.get('next_action_code') or '').strip() + c_allowed = { + str(code or '').strip() + for code in summary.get('allowed_actions') or [] + if str(code or '').strip() + } + assert b_primary == c_next, ( + f'B.primary={b_primary!r} C.next={c_next!r} for {gate_code}' + ) + # B 把 C.allowed_actions 拆成 primary+secondary;二者并集必须等于 allowed_actions。 + # 不能再要求 secondary==allowed:主动作被 C 列为 allowed 但在 B 里归到 primary。 + assert b_all == c_allowed, ( + f'B.all={sorted(b_all)} C.allowed={sorted(c_allowed)} for {gate_code}' + ) + + +def test_preparation_line_emits_decisional_allowed_actions(app, gate_chain): + """§1.5 明细按钮修复:preparation.lines[] 必须带 line_allowed_actions / + inventory_allowed_actions / inventory_file_no,否则前端 formalPreparationLineAllows 恒 false、 + 明细行按钮不渲染。用正式 OT + 一行 not_found 断言短缺行按钮被正确授权。""" + from app.models import ( + ShippingNoticeLineInventoryMatch, + ShippingOrderSnapshot, + ShippingOrderSnapshotLine, + ) + from app.services.shipping_notice.ui_state import build_task_ui_state + + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + # 冻结快照行 → 行级匹配(not_found,短缺)。 + snapshot = ShippingOrderSnapshot( + task_id=int(order_task.id), extraction_id=1, schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + order_task.order_snapshot_id = int(snapshot.id) + line = ShippingOrderSnapshotLine( + snapshot_id=int(snapshot.id), position=0, line_no=1, + reservation_id='RSV-EQ', part_number='PN-EQ', qty='8', field_values_json={}, + ) + db.session.add(line) + db.session.flush() + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=int(order_task.id), snapshot_line_id=int(line.id), line_no=1, line_index=0, + match_result='not_found', inventory_status='ready', required_qty='8', + available_qty='0', matched_qty='0', shortage_qty='8', + reservation_id='RSV-EQ', part_number='PN-EQ', + inventory_source_code='DBS_DUB', matched_file_no='INV-EQ', is_current=True, + )) + db.session.commit() + + preparation = build_task_ui_state(order_task, include_stage_context=True)['stage_context']['preparation'] + assert preparation['lines'], '必须有至少一行' + line_row = preparation['lines'][0] + # 短缺行:close + release_inventory_shortage(line);retry_inventory_preparation(inventory)。 + assert set(line_row['line_allowed_actions']) == { + 'close_unfulfillable', 'release_inventory_shortage', + } + assert 'retry_inventory_preparation' in line_row['inventory_allowed_actions'] + # 下载库存按钮依赖 inventory_file_no。 + assert line_row['inventory_file_no'] == 'INV-EQ' + assert line_row['user_line_status'] == 'shortage' + + +def test_preparation_line_allowed_actions_are_zero_n_plus_one(app, gate_chain): + """§5.1 N+1 守门:行级 action 字段由内存事实投影发,GET 详情 SQL 数恒定且不随行数线性放大。 + + 行级 fact 字典只读已加载的 match_row 列 + detail_json(触库的是 `_build_stage_context` + 自身的批量预取),每行并不追加查询;6 行仍须落在固定数量级。若逐行 SQL/重序列化, + SQL 数会近似=6×行查询而被本上限拦下。 + """ + from sqlalchemy import event + + from app.models import ( + ShippingNoticeLineInventoryMatch, + ShippingOrderSnapshot, + ShippingOrderSnapshotLine, + ) + from app.services.shipping_notice.ui_state import build_task_ui_state + from tests.test_shipping_order_review_service import _capture_sql_statements + + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + snapshot = ShippingOrderSnapshot( + task_id=int(order_task.id), extraction_id=1, schema_version_id=1, + order_data_version=1, header_values_json={}, + ) + db.session.add(snapshot) + db.session.flush() + order_task.order_snapshot_id = int(snapshot.id) + line_count = 6 + for i in range(line_count): + line = ShippingOrderSnapshotLine( + snapshot_id=int(snapshot.id), position=i, line_no=i + 1, + reservation_id=f'RSV-{i}', part_number=f'PN-{i}', qty='8', field_values_json={}, + ) + db.session.add(line) + db.session.flush() + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=int(order_task.id), snapshot_line_id=int(line.id), line_no=i + 1, line_index=i, + match_result='matched', inventory_status='ready', required_qty='8', + available_qty='8', matched_qty='8', shortage_qty='0', + reservation_id=f'RSV-{i}', part_number=f'PN-{i}', + inventory_source_code='DBS_DUB', matched_file_no=f'INV-{i}', is_current=True, + )) + db.session.commit() + + task_id = int(order_task.id) + db.session.remove() + with app.test_request_context(): + ot = db.session.get(ShippingOrderTask, task_id) + statements: list[str] = [] + listener = _capture_sql_statements(statements) + event.listen(db.engine, 'before_cursor_execute', listener) + try: + preparation = build_task_ui_state(ot, include_stage_context=True)['stage_context']['preparation'] + finally: + event.remove(db.engine, 'before_cursor_execute', listener) + assert len(preparation['lines']) == line_count + # 关键断言:6 行仍落在固定数量级;若逐行重查会显著超出(约 6×行查询)而触发。 + assert len(statements) <= 40, ( + f'SQL 数随行数放大: 6 行仍应固定数量级,实测 {len(statements)}' + ) + + +@pytest.mark.parametrize('scenario', [ + # gate_code, expected lifecycle stage(契约:正式 Gate 映射到五阶段业务码唯一表) + ('inventory_matching', 'fulfillment_prep'), + ('inventory_sufficiency', 'fulfillment_prep'), + ('artifact_generation', 'fulfillment_prep'), + ('freight_upload_rpa', 'freight_upload'), + ('manual_upload_handoff', 'freight_upload'), +]) +def test_gate_maps_to_lifecycle_stage_b(app, gate_chain, scenario): + """五阶段门禁→生命周期 唯一映射必须正确(B 侧,真实 Notice 路径)。 + + `LIFECYCLE_STAGE_BY_GATE`(lifecycle_projection.py:30)是正式 Gate→五阶段业务码的唯一表。 + B(build_task_ui_state on Notice,processing_stage=None)经 project_lifecycle 走 Gate 兜底, + 必须按该表落到正确业务码。**freight_upload_rpa / manual_upload_handoff 必须属于 freight_upload** + —— 这是用户确认的契约(方案 A)。 + """ + gate_code, expected_stage = scenario + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + execution_id = _attach_execution( + order_task, + gate_code=gate_code, status='blocked_manual', + blocking_reason_code='inventory_preparation_failed', next_action_code='retry_inventory_preparation', + ) + # 让 notice 路径(_process_gate_user_summary_for_task 按 task.id=notice.id 查 execution) + # 命中同一 execution:B 在生产中把 Notice 传给 build_task_ui_state。 + from app.models import ShippingProcessExecution + execution = db.session.get(ShippingProcessExecution, execution_id) + execution.task_id = int(notice.id) + db.session.commit() + + from app.services.shipping_notice.ui_state import build_task_ui_state + b = build_task_ui_state(notice) + b_stage = str((b.get('stage') or {}).get('code') or '').strip() + b_lifecycle = str(b.get('lifecycle_stage') or '').strip() + + # B(Notice 路径)必须按 LIFECYCLE_STAGE_BY_GATE 落到五阶段码。 + assert b_stage == b_lifecycle == expected_stage, ( + f'B.stage={b_stage!r} B.lifecycle={b_lifecycle!r} expected={expected_stage!r} for {gate_code}' + ) + + +def test_a_secondary_actions_carry_mark_manual_uploaded(app, gate_chain): + """A(shippingProcessingProjection.ui_state.secondary_actions)必须透传原始 Gate 码 mark_manual_uploaded。 + + 契约 §2.5 差异①:A 的 secondary_actions 用别名 open_manual_upload,B/C 用 mark_manual_uploaded。 + frontend manualUploadRegistrationAuthorized 读 A 时须能匹配到 mark_manual_uploaded(否则按钮失效)。 + 本守卫在归一化前应 RED(记录 bug),归一化后应 GREEN。 + """ + with app.app_context(): + run, notice, order_task = _load_chain(gate_chain) + # freight_upload_rpa blocked_manual:C 的 gate_side_recovery_actions / 显式 append 授权手动上传。 + execution_id = _attach_execution( + order_task, + gate_code='freight_upload_rpa', status='blocked_manual', + blocking_reason_code='upload_rpa_failed', next_action_code='retry_freight_upload_rpa', + ) + db.session.commit() + + a = _project_a(run, order_task) + ui_state = a.get('ui_state') or {} + secondary_codes = { + str(item.get('code') or '').strip() + for item in ui_state.get('secondary_actions') or [] + if item + } + primary_code = str((ui_state.get('primary_action') or {}).get('code') or '').strip() + # C 是唯一授权来源:allowed_actions 必含 mark_manual_uploaded(手动上传入口)。 + summary = _summary_c(execution_id) + c_allowed = {str(c or '').strip() for c in summary.get('allowed_actions') or []} + assert 'mark_manual_uploaded' in c_allowed, f'C.allowed={sorted(c_allowed)}' + # [§2.5 归一守卫] A 的 secondary_actions 必须透传原始码 mark_manual_uploaded(而非 open_manual_upload 别名), + # 且与 C.allowed_actions 同集(允许与主动作并存)。 + assert 'mark_manual_uploaded' in secondary_codes or primary_code == 'mark_manual_uploaded', ( + f'A.secondary={sorted(secondary_codes)} A.primary={primary_code!r} C.allowed={sorted(c_allowed)}' + ) diff --git a/backend/tests/test_shipping_review_case_audit_timeline.py b/backend/tests/test_shipping_review_case_audit_timeline.py index 1cb254c1..cc96d7cc 100644 --- a/backend/tests/test_shipping_review_case_audit_timeline.py +++ b/backend/tests/test_shipping_review_case_audit_timeline.py @@ -40,6 +40,9 @@ def test_review_case_audit_timeline_owner_reads_snapshots_and_stranger_denied(ap user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-AUDIT-TL') run = _materialized_run(user=user, agent=agent, session=session, intake=intake) unit = run.extraction_plan.units[0] + # 迁移后 ensure_review_case_for_unit 要求 unit.status 达到 candidate_ready/review_required; + # 测试仅需审计时间线可见性,故把 Unit 置为就绪以初始化 Case/Draft。 + unit.status = 'candidate_ready' unit.result_json = {'orders': [{'header_fields': [], 'lines': []}]} db.session.commit() case = ensure_run_review_cases(run=run)[0] diff --git a/backend/tests/test_shipping_review_confirm_auto_progress.py b/backend/tests/test_shipping_review_confirm_auto_progress.py index baf98cf8..022a4f65 100644 --- a/backend/tests/test_shipping_review_confirm_auto_progress.py +++ b/backend/tests/test_shipping_review_confirm_auto_progress.py @@ -14,7 +14,7 @@ import pytest from app import db from app.jobs.types import JobType -from app.models import Job, ShippingNotice +from app.models import Job, ShippingOrderTask from app.services.shipping_notice.order_review_confirmation_service import ( _task_needs_post_confirm_auto_progress, schedule_auto_progress_after_review_confirm, @@ -81,13 +81,28 @@ def test_project_post_confirm_auto_progress_marks_stuck_task_for_retry(app, monk assert summary['reason_code'] == 'auto_progress_job_succeeded_but_task_not_advanced' -def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extraction(): - """created/parsed 且已挂 Extraction 的任务需要确认后补推。""" +def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extraction(monkeypatch): + """created/parsed 且已挂 Extraction 的任务需要确认后补推;已进入导出/上传事实则跳过。""" + from types import SimpleNamespace as NS + + from app.services.shipping_notice import upload_attempt_service + + # [断言] 是否已推进以真实履约事实(Artifact/Attempt)判定,不再读 OT 冗余字段。 + def fake_upload_attempt(task): + if getattr(task, 'upload_status', None) is not None: + return NS(status='pending') + return None + + monkeypatch.setattr(upload_attempt_service, 'latest_upload_attempt', fake_upload_attempt) + monkeypatch.setattr(upload_attempt_service, 'latest_export_artifact', lambda task: None) + stuck = MagicMock( current_order_extraction_id=12, + upload_status=None, ) parsed = MagicMock( current_order_extraction_id=12, + upload_status=None, ) progressed = MagicMock( upload_status='pending', @@ -95,6 +110,7 @@ def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extrac ) shell = MagicMock( current_order_extraction_id=None, + upload_status=None, ) assert _task_needs_post_confirm_auto_progress(stuck) is True assert _task_needs_post_confirm_auto_progress(parsed) is True @@ -106,8 +122,8 @@ def test_task_needs_post_confirm_auto_progress_requires_early_status_with_extrac def test_schedule_auto_progress_enqueues_job_without_commit(app, monkeypatch): """commit=False 时写入 Job 但不提交,供与确认事务同提交。""" with app.app_context(): - task = ShippingNotice( - task_no='SN-CONFIRM-AP-1', + task = ShippingOrderTask( + task_no='OT-CONFIRM-AP-1', user_id=1, current_order_extraction_id=99, ) @@ -143,8 +159,8 @@ def test_schedule_auto_progress_enqueues_job_without_commit(app, monkeypatch): def test_schedule_auto_progress_enqueues_for_parsed_after_confirm(app, monkeypatch): """确认后已有解析结果仍须入队(CONFIRM_PARSE 后常见态)。""" with app.app_context(): - task = ShippingNotice( - task_no='SN-CONFIRM-AP-PARSED', + task = ShippingOrderTask( + task_no='OT-CONFIRM-AP-PARSED', user_id=1, current_order_extraction_id=99, ) @@ -178,8 +194,8 @@ def test_schedule_auto_progress_enqueues_for_parsed_after_confirm(app, monkeypat def test_schedule_auto_progress_idempotent_replay_reseeds_when_stuck(app, monkeypatch): """幂等回放在任务仍悬挂于 created 时必须补推,不能无条件跳过。""" with app.app_context(): - task = ShippingNotice( - task_no='SN-CONFIRM-AP-2', + task = ShippingOrderTask( + task_no='OT-CONFIRM-AP-2', user_id=1, current_order_extraction_id=88, ) @@ -219,15 +235,22 @@ def test_schedule_auto_progress_idempotent_replay_reseeds_when_stuck(app, monkey def test_schedule_auto_progress_skips_when_already_progressed(app, monkeypatch): - """任务已离开 created 时幂等回放不再入队。""" + """任务已进入行级库存匹配事实(可履约)时幂等回放不再入队。""" + from app.models import ShippingNoticeLineInventoryMatch + with app.app_context(): - task = ShippingNotice( - task_no='SN-CONFIRM-AP-3', + task = ShippingOrderTask( + task_no='OT-CONFIRM-AP-3', user_id=1, - upload_status='pending', current_order_extraction_id=77, ) db.session.add(task) + db.session.flush() + # 已履约事实:可当前库匹配使 _task_needs_post_confirm_auto_progress 判 False。 + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=task.id, snapshot_line_id=1, line_no=1, + match_result='matched', inventory_status='ready', is_current=True, + )) db.session.commit() monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker') schedule = schedule_auto_progress_after_review_confirm( @@ -285,11 +308,10 @@ def test_run_single_task_auto_progresses_created_task_with_extraction(app, monke from app.services.shipping_notice import batch_orchestrator with app.app_context(): - # ShippingBatch 已物理下线;仅用 ShippingNotice 表达确认建单后的悬挂态。 - task = ShippingNotice( - task_no='SN-CONFIRM-AP-4', + # ShippingBatch 已物理下线;仅用 ShippingOrderTask 表达确认建单后的悬挂态。 + task = ShippingOrderTask( + task_no='OT-CONFIRM-AP-4', user_id=1, - source_type='review_confirmation', current_order_extraction_id=66, ) db.session.add(task) diff --git a/backend/tests/test_shipping_review_formal_task_edit.py b/backend/tests/test_shipping_review_formal_task_edit.py index 2235c1a7..d61f7eb1 100644 --- a/backend/tests/test_shipping_review_formal_task_edit.py +++ b/backend/tests/test_shipping_review_formal_task_edit.py @@ -4,7 +4,8 @@ backend/tests/test_shipping_review_formal_task_edit.py 用途:验收正式任务字段写路径(Schema 策略 + order_data_version)与 change_effect 下游失效。 依赖:task_workflow、schema_edit_policy、order_schema_service、ShippingOrderTask。 逻辑:默认 reservation_id 不可写;Schema editable=True 可写并递增版本; - rerun_inventory_matching / regenerate_excel 分别失效匹配或导出并同步 OT stage。 + rerun_inventory_matching / regenerate_excel 分别失效匹配或导出并置 invalidated_from_stage; + 正式字段编辑以 Excel ready 为硬冻结,不再用 order_snapshot_id 阻断。 """ from __future__ import annotations @@ -12,15 +13,14 @@ from __future__ import annotations from app import db from app.models import ( ShippingExportArtifact, + ShippingNotice, ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderTask, - ShippingNotice, ) from app.services.shipping_notice.order_schema import service as order_schema_service -from app.services.shipping_notice.order_task_service import sync_order_task_processing_state from app.services.shipping_notice.task_workflow import update_notice_fields, update_notice_line @@ -36,12 +36,14 @@ def _review_payload(*, version: int = 1) -> dict[str, object]: def _attach_extraction( - task: ShippingNotice, + task: ShippingOrderTask, rows: list[dict], *, field_policies: dict[str, dict] | None = None, + header_values: dict[str, object] | None = None, ) -> dict[str, str]: """建立带 task_edit_policy 的动态 Extraction,供 formal edit 测试使用。""" + header_values = dict(header_values or {'po_number': 'PO-FORMAL-001'}) order_schema_service.initialize_schema({'display_name': 'Formal Edit Schema'}, actor_id=None) existing_fields = { item['field_code']: item @@ -97,7 +99,7 @@ def _attach_extraction( db.session.add(extraction) db.session.flush() header_field = fields['po_number'] - header_value = task.po_number + header_value = header_values.get('po_number') header_decision = ShippingOrderFieldDecision( extraction_id=extraction.id, line_id=None, @@ -118,7 +120,9 @@ def _attach_extraction( value_json=header_value, )) for position, row in enumerate(rows): - line = ShippingOrderLine(extraction_id=extraction.id, position=position) + line = ShippingOrderLine( + extraction_id=extraction.id, position=position, line_no=position + 1, + ) db.session.add(line) db.session.flush() for code, field in fields.items(): @@ -150,17 +154,45 @@ def _attach_extraction( return {code: field['id'] for code, field in fields.items()} -def _task(**kwargs) -> ShippingNotice: - task = ShippingNotice( - task_no=kwargs.pop('task_no', 'SN-FORMAL-EDIT-001'), - source_type='manual', - po_number=kwargs.pop('po_number', 'PO-FORMAL-001'), - match_status=kwargs.pop('match_status', 'matched'), - line_results_json=kwargs.pop('line_results_json', [{'part_number': 'A001'}]), - export_file_path=kwargs.pop('export_file_path', None), - export_file_name=kwargs.pop('export_file_name', None), +def _freeze_formal_task_snapshot(task: ShippingOrderTask) -> None: + """补齐正式编辑前置:客户确认 + 冻结订单快照,使 order_field_id_values(order_field_purposes) 可读。 + + 正式编辑路径会对 task 跑 task_reservation_gate_issues → order_field_id_values, + 后者要求 task.order_snapshot_id 非空;缺快照会抛 order_schema_unavailable 并抢先置 RSV_REQUIRED/OT waiting_review。 + """ + from app.models import ShippingCustomer, ShippingOrderExtraction + from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot + + customer = ShippingCustomer(standard_name='正式编辑测试客户', short_code='FORMAL', status='active') + db.session.add(customer) + db.session.flush() + from tests.conftest import confirm_test_customer_resolution + extraction = db.session.get(ShippingOrderExtraction, int(task.current_order_extraction_id)) + if extraction is None: + raise ValueError('formal edit test task must have an accepted extraction') + confirm_test_customer_resolution(task, customer=customer, extraction=extraction) + freeze_order_snapshot( + task, actor_id=None, expected_order_data_version=int(task.order_data_version or 1), + freeze_mode='auto', + auto_freeze_policy={ + 'test_fixture': True, 'enabled': True, 'mode': 'qualified', + 'qualification_status': 'qualified', 'customer_scope_status': 'allowed', + 'blocking_reason_codes': [], + }, + ) + db.session.flush() + + +def _task(**kwargs) -> ShippingOrderTask: + """构造正式订单任务(OT)作为 formal edit 的目标容器。""" + task = ShippingOrderTask( + task_no=kwargs.pop('task_no', 'OT-FORMAL-EDIT-001'), + user_id=1, + source_type=kwargs.pop('source_type', 'direct_pdf'), + status=kwargs.pop('status', 'processing'), + stage=kwargs.pop('stage', 'inventory_matching'), order_data_version=kwargs.pop('order_data_version', 1), - order_lines_migration_status='pending', + step_payload_json=dict(kwargs.pop('step_payload_json', None) or {}), **kwargs, ) db.session.add(task) @@ -168,24 +200,15 @@ def _task(**kwargs) -> ShippingNotice: return task -def _link_order_task(task: ShippingNotice, *, stage: str = 'inventory_matching') -> ShippingOrderTask: - """挂接 OT 供 change_effect stage 同步断言。""" - order_task = ShippingOrderTask( - task_no=f'OT-{task.task_no}', - user_id=1, - candidate_id=None, - shipping_notice_id=int(task.id), - stage=stage, - status='processing', - progress_version=1, - ) - db.session.add(order_task) +def _link_order_task(task: ShippingOrderTask, *, stage: str = 'inventory_matching') -> ShippingOrderTask: + """挂接任务当前 stage 供 change_effect 用例表达 OT 进度;正式编辑任务本身即 OT。""" + task.stage = stage db.session.flush() - return order_task + return task -def _seed_ready_export_artifact(task: ShippingNotice, *, path: str | None = None) -> ShippingExportArtifact: - """为 Excel 冻结测试植入 status=ready 的 Artifact(BE-09)。""" +def _seed_ready_export_artifact(task: ShippingOrderTask, *, path: str | None = None) -> ShippingExportArtifact: + """为 Excel 冻结测试植入 status=ready 的 Artifact(BE-09),并挂接正式 Notice 供导出事实读取。""" from app.models import ( ShippingExcelTemplate, ShippingInventoryParsingProfile, @@ -193,7 +216,17 @@ def _seed_ready_export_artifact(task: ShippingNotice, *, path: str | None = None ShippingOrderSchemaVersion, ) - file_path = str(path or task.export_file_path or '/tmp/formal.xlsx') + notice = ShippingNotice( + task_no=f'SN-{task.task_no}', + business_no=f'BN-{task.task_no}', + user_id=task.user_id, + order_task_id=int(task.id), + source_type='direct_pdf', + ) + db.session.add(notice) + db.session.flush() + + file_path = str(path or '/tmp/formal.xlsx') template = ShippingExcelTemplate( template_code=f'TPL-{task.task_no}', display_name='Formal Edit', @@ -234,14 +267,14 @@ def _seed_ready_export_artifact(task: ShippingNotice, *, path: str | None = None extraction_id = extraction.id artifact = ShippingExportArtifact( artifact_no=f'ART-{task.task_no}', - task_id=int(task.id), + task_id=int(notice.id), template_id=int(template.id), order_schema_version_id=int(version.id), order_extraction_id=int(extraction_id), inventory_parsing_profile_id=int(profile.id), input_checksum='b' * 64, file_path=file_path, - file_name=str(task.export_file_name or 'formal.xlsx'), + file_name='formal.xlsx', file_checksum='c' * 64, file_size=10, status='ready', @@ -277,7 +310,7 @@ def test_formal_edit_rejects_default_readonly_field(app): def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app): """Schema editable=True 时允许写入并递增 order_data_version。""" with app.app_context(): - task = _task(export_file_path='/tmp/formal.xlsx', export_file_name='formal.xlsx') + task = _task() _attach_extraction( task, [{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}], @@ -288,7 +321,7 @@ def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app): }, }, ) - _seed_ready_export_artifact(task) + artifact = _seed_ready_export_artifact(task) db.session.commit() # Excel ready(ready Artifact)时即使 Schema editable 也必须冻结。 @@ -302,8 +335,7 @@ def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app): assert frozen['data']['error_code'] == 'SHIPPING.ORDER_EXCEL_FROZEN' # 清除导出后允许 Schema 放行字段写入。 - task.export_file_path = None - task.export_file_name = None + artifact.status = 'superseded' db.session.commit() response = update_notice_line({ @@ -313,16 +345,14 @@ def test_formal_edit_accepts_schema_allowed_field_and_bumps_version(app): **_review_payload(version=1), }) assert response['status'] == 'ok' - refreshed = db.session.get(ShippingNotice, task.id) + refreshed = db.session.get(ShippingOrderTask, task.id) assert int(refreshed.order_data_version) == 2 - # change_effect=none 时不应清空已有匹配结果。 - assert refreshed.match_status == 'matched' def test_change_effect_rerun_inventory_matching_invalidates_match_and_syncs_ot(app): - """rerun_inventory_matching 清空匹配并同步 OT inventory_matching stage。""" + """rerun_inventory_matching 清空匹配/导出并置 invalidated_from_stage。""" with app.app_context(): - task = _task(export_file_path='/tmp/formal.xlsx', export_file_name='formal.xlsx') + task = _task() _attach_extraction( task, [{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}], @@ -333,10 +363,8 @@ def test_change_effect_rerun_inventory_matching_invalidates_match_and_syncs_ot(a }, }, ) - order_task = _link_order_task(task, stage='excel_generating') - # 测试编辑路径:先去掉 Excel 冻结。 - task.export_file_path = None - task.export_file_name = None + _freeze_formal_task_snapshot(task) + _link_order_task(task, stage='excel_generating') db.session.commit() response = update_notice_line({ @@ -346,19 +374,16 @@ def test_change_effect_rerun_inventory_matching_invalidates_match_and_syncs_ot(a **_review_payload(version=1), }) assert response['status'] == 'ok' - refreshed = db.session.get(ShippingNotice, task.id) - assert refreshed.match_status is None - assert refreshed.line_results_json is None - assert refreshed.export_file_path is None - ot = db.session.get(ShippingOrderTask, order_task.id) - assert ot.stage == 'inventory_matching' - assert int(ot.progress_version) == 2 + refreshed = db.session.get(ShippingOrderTask, task.id) + assert int(refreshed.order_data_version) == 2 + assert refreshed.step_payload_json['invalidated_from_stage'] == 'inventory_matching' + assert 'export_meta' not in refreshed.step_payload_json def test_change_effect_regenerate_excel_only_clears_export(app): - """regenerate_excel 仅清空导出并同步 OT excel_generating。""" + """regenerate_excel 仅清空导出并置 invalidated_from_stage。""" with app.app_context(): - task = _task() + task = _task(stage='inventory_matching') _attach_extraction( task, [{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}], @@ -369,10 +394,8 @@ def test_change_effect_regenerate_excel_only_clears_export(app): }, }, ) - order_task = _link_order_task(task, stage='inventory_matching') - # 版本不匹配的导出视为 stale,不触发 Excel 冻结,便于测 regenerate_excel。 - task.export_file_path = '/tmp/stale.xlsx' - task.export_file_name = 'stale.xlsx' + _freeze_formal_task_snapshot(task) + _link_order_task(task, stage='inventory_matching') task.step_payload_json = { **dict(task.step_payload_json or {}), 'export_meta': {'order_data_version': 999}, @@ -385,19 +408,16 @@ def test_change_effect_regenerate_excel_only_clears_export(app): **_review_payload(), }) assert response['status'] == 'ok' - refreshed = db.session.get(ShippingNotice, task.id) - assert refreshed.match_status == 'matched' - assert refreshed.line_results_json == [{'part_number': 'A001'}] - assert refreshed.export_file_path is None - ot = db.session.get(ShippingOrderTask, order_task.id) - assert ot.stage == 'excel_generating' - assert int(ot.progress_version) == 2 + refreshed = db.session.get(ShippingOrderTask, task.id) + assert int(refreshed.order_data_version) == 2 + assert refreshed.step_payload_json['invalidated_from_stage'] == 'excel_generating' + assert 'export_meta' not in refreshed.step_payload_json def test_formal_edit_allowed_with_order_snapshot_when_excel_not_ready(app): """有 order_snapshot_id 但 Excel 未 ready 时,Schema editable 字段仍可写。""" with app.app_context(): - task = _task(order_snapshot_id=12345) + task = _task() _attach_extraction( task, [{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}], @@ -408,6 +428,7 @@ def test_formal_edit_allowed_with_order_snapshot_when_excel_not_ready(app): }, }, ) + _freeze_formal_task_snapshot(task) db.session.commit() response = update_notice_line({ @@ -417,6 +438,6 @@ def test_formal_edit_allowed_with_order_snapshot_when_excel_not_ready(app): **_review_payload(version=1), }) assert response['status'] == 'ok' - refreshed = db.session.get(ShippingNotice, task.id) + refreshed = db.session.get(ShippingOrderTask, task.id) assert int(refreshed.order_data_version) == 2 - assert int(refreshed.order_snapshot_id) == 12345 + assert int(refreshed.order_snapshot_id) == int(task.order_snapshot_id) diff --git a/backend/tests/test_shipping_review_wave_line_concurrency.py b/backend/tests/test_shipping_review_wave_line_concurrency.py index 4d0dc002..4105c01c 100644 --- a/backend/tests/test_shipping_review_wave_line_concurrency.py +++ b/backend/tests/test_shipping_review_wave_line_concurrency.py @@ -3,7 +3,7 @@ tests/test_shipping_review_wave_line_concurrency.py 用途:同行并发入波次的唯一约束与错误码证据。 依赖:pytest、threading、ShippingOrderReviewWaveLine、app fixture。 -逻辑:两线程同时插入同一 (case, line_key);只允许一条成功;失败映射稳定错误码。 +逻辑:两线程同时插入同一 (case, snapshot_line_id);只允许一条成功;失败映射稳定错误码。 若环境变量 HXOPS_PG_CONCURRENCY_URL 指向 PostgreSQL,则在真实 PG 上再跑一轮。 """ @@ -20,7 +20,7 @@ from sqlalchemy.exc import IntegrityError from app import db from app.core.errors import ConflictError -from app.models import ShippingOrderReviewWaveLine, ShippingNotice +from app.models import ShippingOrderReviewWaveLine, ShippingOrderTask from app.services.shipping_notice.order_review_confirmation_service import _persist_wave_lines_for_task @@ -36,7 +36,6 @@ def test_wave_line_unique_constraint_blocks_second_insert(app): from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan from app.services.shipping_notice.order_review_service import ensure_run_review_cases - from app.services.shipping_notice.tool_common import generate_task_no user, agent, session, intake, document = _seed_run_input(suffix='WAVE-CONC-UQ') run, _ = create_order_extraction_run( @@ -51,32 +50,30 @@ def test_wave_line_unique_constraint_blocks_second_insert(app): case = ensure_run_review_cases(run=run)[0] db.session.commit() - task1 = ShippingNotice( - task_no=generate_task_no(), - user_id=int(user.id), source_type='review_confirmation', - source_file_name=document.filename, source_content_hash=document.content_hash, + task1 = ShippingOrderTask( + task_no='OT-WAVE-UQ-1', + user_id=int(user.id), source_type='eml', ) - task2 = ShippingNotice( - task_no=generate_task_no(), - user_id=int(user.id), source_type='review_confirmation', - source_file_name=document.filename, source_content_hash=document.content_hash, + task2 = ShippingOrderTask( + task_no='OT-WAVE-UQ-2', + user_id=int(user.id), source_type='eml', ) db.session.add_all([task1, task2]) db.session.flush() _persist_wave_lines_for_task( - case=case, task=task1, line_keys=['L-CONC'], wave_no=1, revision_id=None, + case=case, task=task1, snapshot_line_ids=[1], wave_no=1, revision_id=None, ) db.session.commit() with pytest.raises(ConflictError) as exc: _persist_wave_lines_for_task( - case=case, task=task2, line_keys=['L-CONC'], wave_no=2, revision_id=None, + case=case, task=task2, snapshot_line_ids=[1], wave_no=2, revision_id=None, ) assert exc.value.code == 'SHIPPING.REVIEW_LINE_ALREADY_IN_TASK' db.session.rollback() assert ShippingOrderReviewWaveLine.query.filter_by( - review_case_id=int(case.id), line_key='L-CONC', + review_case_id=int(case.id), snapshot_line_id=1, ).count() == 1 @@ -92,7 +89,6 @@ def test_wave_line_concurrent_inserts_only_one_wins(app): from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan from app.services.shipping_notice.order_review_service import ensure_run_review_cases - from app.services.shipping_notice.tool_common import generate_task_no user, agent, session, intake, document = _seed_run_input(suffix='WAVE-CONC-RACE') run, _ = create_order_extraction_run( @@ -109,11 +105,10 @@ def test_wave_line_concurrent_inserts_only_one_wins(app): case_id = int(case.id) tasks = [] - for _ in range(2): - task = ShippingNotice( - task_no=generate_task_no(), - user_id=int(user.id), source_type='review_confirmation', - source_file_name=document.filename, source_content_hash=document.content_hash, + for index in range(2): + task = ShippingOrderTask( + task_no=f'OT-WAVE-RACE-{index + 1}', + user_id=int(user.id), source_type='eml', ) db.session.add(task) tasks.append(task) @@ -128,7 +123,7 @@ def test_wave_line_concurrent_inserts_only_one_wins(app): barrier.wait(timeout=10) row = ShippingOrderReviewWaveLine( review_case_id=case_id, - line_key='L-RACE', + snapshot_line_id=1, task_id=task_id, wave_no=wave_no, created_at=datetime.utcnow(), @@ -153,7 +148,7 @@ def test_wave_line_concurrent_inserts_only_one_wins(app): assert results.count('conflict') == 1 with app.app_context(): assert ShippingOrderReviewWaveLine.query.filter_by( - review_case_id=case_id, line_key='L-RACE', + review_case_id=case_id, snapshot_line_id=1, ).count() == 1 @@ -163,7 +158,7 @@ def test_wave_line_concurrent_inserts_only_one_wins(app): ) def test_wave_line_concurrent_inserts_on_postgres(): """ - 真实 PostgreSQL 上验证 (review_case_id, line_key) 唯一约束并发行为。 + 真实 PostgreSQL 上验证 (review_case_id, snapshot_line_id) 唯一约束并发行为。 需预先存在空库并可建临时表;通过环境变量注入连接串。 """ @@ -182,10 +177,10 @@ def test_wave_line_concurrent_inserts_on_postgres(): 'tmp_wave_lines', metadata, sa.Column('id', sa.Integer(), primary_key=True, autoincrement=True), sa.Column('review_case_id', sa.Integer(), sa.ForeignKey('tmp_review_cases.id'), nullable=False), - sa.Column('line_key', sa.String(64), nullable=False), + sa.Column('snapshot_line_id', sa.Integer(), nullable=False), sa.Column('task_id', sa.Integer(), sa.ForeignKey('tmp_shipping_tasks.id'), nullable=False), sa.Column('wave_no', sa.Integer(), nullable=False), - sa.UniqueConstraint('review_case_id', 'line_key', name='uq_tmp_wave_case_line'), + sa.UniqueConstraint('review_case_id', 'snapshot_line_id', name='uq_tmp_wave_case_line'), ) metadata.drop_all(engine) metadata.create_all(engine) @@ -202,7 +197,7 @@ def test_wave_line_concurrent_inserts_on_postgres(): with engine.begin() as conn: try: conn.execute(wave.insert().values( - review_case_id=1, line_key='L1', task_id=task_id, wave_no=wave_no, + review_case_id=1, snapshot_line_id=101, task_id=task_id, wave_no=wave_no, )) return 'ok' except IntegrityError: diff --git a/backend/tests/test_shipping_review_workbench_stage_layering.py b/backend/tests/test_shipping_review_workbench_stage_layering.py index 90607427..fa500f51 100644 --- a/backend/tests/test_shipping_review_workbench_stage_layering.py +++ b/backend/tests/test_shipping_review_workbench_stage_layering.py @@ -267,8 +267,18 @@ def test_project_stage_for_task_without_domain_facts_is_order_creating(): assert stage['source'] == 'domain_facts' -def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload(): - """历史 Notice.upload_status 无成功 Attempt 时不得绕过货代上传核对。""" +def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload(monkeypatch): + """无成功 Attempt(仅上传尝试已发生但未核对)时仍停留货代上传工作面。""" + from types import SimpleNamespace + + from app.services.shipping_notice import upload_attempt_service as upload_mod + + # 迁移后上传态以「最近上传尝试」为准,不再读取 Notice 上的历史聚合字段 upload_status。 + monkeypatch.setattr( + upload_mod, + 'latest_upload_attempt', + lambda _task: SimpleNamespace(status='uploaded'), + ) task = SimpleNamespace( id=1, order_task_id=9, diff --git a/backend/tests/test_shipping_review_workbench_state_isolation.py b/backend/tests/test_shipping_review_workbench_state_isolation.py index 9e18b487..24e55dc7 100644 --- a/backend/tests/test_shipping_review_workbench_state_isolation.py +++ b/backend/tests/test_shipping_review_workbench_state_isolation.py @@ -13,11 +13,32 @@ from types import SimpleNamespace from unittest.mock import patch from app.services.shipping_notice.order_review_projection import ( + _inventory_rpa_is_running, _project_case_automation_status, ) from app.services.shipping_notice.process_gate_projection import project_user_gate_summary +def test_inventory_running_is_not_inferred_from_stage_automation_job(): + """阶段推进 Job 运行中但未创建库存 Attempt 时,明细不得显示获取库存中。""" + task = SimpleNamespace(task_no='OT-TEST-1') + with patch( + 'app.services.shipping_notice.order_review_projection.ShippingTaskInventoryRpaAttempt.query', + ) as query: + query.filter.return_value.first.return_value = None + assert _inventory_rpa_is_running(task) is False + + +def test_inventory_running_requires_queued_or_running_attempt(): + """只有库存 RPA Attempt queued/running 才能投影 acquiring_inventory。""" + task = SimpleNamespace(task_no='OT-TEST-2') + with patch( + 'app.services.shipping_notice.order_review_projection.ShippingTaskInventoryRpaAttempt.query', + ) as query: + query.filter.return_value.first.return_value = SimpleNamespace(status='queued') + assert _inventory_rpa_is_running(task) is True + + def test_automation_waiting_to_start_when_eligible_but_not_queued(): """资格达标且未建单时只能是 waiting_to_start,不得伪装 running。""" case = SimpleNamespace( @@ -151,10 +172,12 @@ def test_unexpected_stp_error_has_stable_user_message(): category_hint='temporary_storage_error', ) - assert retryable is False + assert retryable is True assert result['message'] == '自动建单失败,已停止,等待用户选择下一步动作' assert 'psycopg2' not in result['message'] assert 'invalid input syntax' not in result['message'] + assert result['next_action'] == 'retry_stp_auto_create' + assert result['decision_trace']['matched_rule'] == 'temporary_storage_error' def test_automation_failed_stops_when_post_confirm_needs_user_action(): @@ -456,7 +479,8 @@ def test_project_user_gate_summary_exposes_retry_for_confirmed_inventory_pending assert summary['current_blocking_gate']['status'] == 'blocked_retryable' assert summary['next_action_code'] == 'retry_inventory_matching' - assert summary['allowed_actions'] == ['retry_inventory_matching'] + # 迁移后行级库存源在 Excel 未生成时持续可编辑,选源/覆写动作与阻断态解耦。 + assert summary['allowed_actions'] == ['retry_inventory_matching', 'override_line_inventory_source'] def test_project_user_gate_summary_keeps_pending_match_system_owned_without_inventory(monkeypatch): diff --git a/backend/tests/test_shipping_schema_edit_policy.py b/backend/tests/test_shipping_schema_edit_policy.py index 7297e1b2..7b14d073 100644 --- a/backend/tests/test_shipping_schema_edit_policy.py +++ b/backend/tests/test_shipping_schema_edit_policy.py @@ -63,7 +63,7 @@ def test_sanitize_audit_field_value_truncates_long_text() -> None: def test_excel_ready_requires_ready_artifact(app) -> None: - """仅有 export_file_path、无 ready Artifact 时不得冻结(BE-09)。""" + """无 ready Artifact 时不得冻结;只有 Artifact 进入 ready 才冻结。""" from app import db from app.models import ( ShippingExcelTemplate, @@ -76,14 +76,7 @@ def test_excel_ready_requires_ready_artifact(app) -> None: ) with app.app_context(): - task = ShippingNotice( - task_no='SN-EXCEL-READY-BE09', - source_type='manual', - export_file_path='/tmp/be09.xlsx', - export_file_name='be09.xlsx', - order_data_version=1, - order_lines_migration_status='pending', - ) + task = ShippingNotice(task_no='SN-EXCEL-READY-BE09', source_type='manual') db.session.add(task) db.session.flush() assert is_excel_ready_for_task(task) is False diff --git a/backend/tests/test_shipping_stage_capability.py b/backend/tests/test_shipping_stage_capability.py new file mode 100644 index 00000000..44f34644 --- /dev/null +++ b/backend/tests/test_shipping_stage_capability.py @@ -0,0 +1,655 @@ +# backend/tests/test_shipping_stage_capability.py +import pytest + +from app.services.shipping_notice.process_gate_contract import ( + STAGE_CAPABILITY_DEFINITIONS, + stage_capability, + is_stage_capability, + capability_stage, +) + + +def test_stage_capability_definitions_exist(): + assert 'retry_inventory_preparation' in STAGE_CAPABILITY_DEFINITIONS + assert 'override_line_inventory_source' in STAGE_CAPABILITY_DEFINITIONS + assert 'reload_inventory_result' in STAGE_CAPABILITY_DEFINITIONS + + +def test_stage_capability_returns_definition(): + cap = stage_capability('retry_inventory_preparation') + assert cap is not None + assert cap['stage'] == 'fulfillment_prep' + assert cap['scope'] == 'task' + assert cap['reset_to'] == 'inventory_preparation' + assert 'inventory_matching' in cap['invalidate'] + + +def test_stage_capability_unknown_returns_none(): + assert stage_capability('retry_freight_upload_rpa') is None + + +def test_is_stage_capability(): + assert is_stage_capability('retry_inventory_preparation') is True + assert is_stage_capability('retry_freight_upload_rpa') is False + assert is_stage_capability(None) is False + + +def test_capability_stage(): + assert capability_stage('retry_inventory_preparation') == 'fulfillment_prep' + assert capability_stage('unknown') is None + + +# 追加到 test_shipping_stage_capability.py +def test_build_task_ui_state_exposes_capabilities(monkeypatch): + # 构造一个确认任务(轻量,不依赖 DB);此处用真正的 ui_state 冒烟,最小断言字段存在 + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + # 直接测纯辅助,避免重 DB 依赖 + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={'source_options': [{'source_code': 'CRANE'}], 'source_locked': False, 'lines': []}, + source_locked=False, + ) + codes = [c['code'] for c in caps] + assert 'retry_inventory_preparation' in codes + assert 'reload_inventory_result' in codes + assert 'override_line_inventory_source' in codes + + +def test_capabilities_disabled_when_excel_locked(): + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={'source_options': [{'source_code': 'CRANE'}], 'source_locked': True, 'lines': []}, + source_locked=True, + ) + assert all(c['enabled'] is False for c in caps) + assert all(c['disabled_reason'] for c in caps) + + +# 预条件语义(Task 2 变更):能力可用性由数据谓词决定,而非仅代码在场。 +# 断言关键分支:重抓(有候选源/Excel未锁定);重抓(无候选源但有失败源);重读(已有抓取结果)。 +def test_retry_inventory_preparation_enabled_with_candidates(): + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={'source_options': [{'source_code': 'CRANE'}], 'source_locked': False, 'lines': []}, + source_locked=False, + ) + by_code = {c['code']: c for c in caps} + # 预条件:source_options 非空(候选源) + Excel 未锁定 → 重抓可用。 + assert by_code['retry_inventory_preparation']['enabled'] is True + assert by_code['retry_inventory_preparation']['disabled_reason'] is None + + +def test_retry_inventory_preparation_enabled_with_failed_source(): + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={ + 'source_options': [], 'source_locked': False, 'lines': [], + 'failed_source_codes': ['CRANE'], + }, + source_locked=False, + ) + by_code = {c['code']: c for c in caps} + # 预条件:无候选源但存在失败源(有抓取失败的源可重试) → 重抓仍可用 + # (docstring:重抓→有候选源或失败源)。这是一期实现遗漏的分支,此处锁定。 + assert by_code['retry_inventory_preparation']['enabled'] is True + assert by_code['retry_inventory_preparation']['disabled_reason'] is None + + +def test_reload_inventory_result_enabled_with_resolved_source(): + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={ + 'source_options': [], 'source_locked': False, 'lines': [], + 'resolved_source_codes': ['CRANE'], + }, + source_locked=False, + ) + by_code = {c['code']: c for c in caps} + # 预条件:已有抓取结果(resolved_source_codes 非空) → 重读可用。 + assert by_code['reload_inventory_result']['enabled'] is True + assert by_code['reload_inventory_result']['disabled_reason'] is None + + +# Task 3 —— 编排器 execute_stage_capability(作废下游 + 重置 + 幂等重跑) +# 断言意图:invalidate_downstream_gates 的返回被透传为 invalidated_gates;重走后 +# run_task_auto_progress 会执行(reran=True);capability['reset_to'] 使 current_gate_code 复位。 +from app.services.shipping_notice.process_gate_service import execute_stage_capability + + +def test_execute_stage_capability_invalidates_downstream(monkeypatch): + class FakeGate: + gate_code = 'inventory_preparation' + status = 'passed' + + class FakeExecution: + current_gate_code = 'inventory_field_mapping' + id = 1 + + calls = {} + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.invalidate_downstream_gates', + lambda **kw: calls.update(kw) or ['inventory_field_mapping', 'inventory_matching'], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.run_task_auto_progress', + lambda *a, **k: calls.update(run=True, run_kwargs=k), + ) + cap = stage_capability('retry_inventory_preparation') + result = execute_stage_capability( + execution=FakeExecution(), gate=FakeGate(), capability=cap, + actor_type='user', actor_id=1, idempotency_key='k1', + ) + assert 'inventory_field_mapping' in result['invalidated_gates'] + assert calls.get('run') is True + # 断言失效链只作废准备 Gate 的下游,不能把准备 Gate 自身置 invalidated。 + assert calls['change_type'] == 'inventory_source_changed' + assert calls['exclude_gate_codes'] == {'inventory_preparation'} + # 断言幂等键被真正透传给 run_task_auto_progress(findings:曾经接收但不转发)。 + assert calls['run_kwargs']['idempotency_key'] == 'k1' + # 用户点击重抓库存必须保留定向恢复语义,不能退化成失败后的自动重试。 + assert calls['run_kwargs']['resume_gate_code'] == 'inventory_preparation' + assert calls['run_kwargs']['inventory_mode'] == 'retry_rpa' + + +def test_execute_stage_capability_forwards_line_scope_for_line_rpa_retry(monkeypatch): + class FakeGate: + gate_code = 'inventory_preparation' + status = 'blocked_retryable' + + class FakeExecution: + current_gate_code = 'inventory_matching' + id = 1 + + calls = {} + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.invalidate_downstream_gates', + lambda **kw: [], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.run_task_auto_progress', + lambda *a, **k: calls.update(run_kwargs=k), + ) + result = execute_stage_capability( + execution=FakeExecution(), gate=FakeGate(), capability=stage_capability('retry_inventory_preparation'), + actor_type='user', actor_id=1, idempotency_key='line-rpa', line_scope_key=42, + ) + assert result['reran'] is True + assert calls['run_kwargs']['line_scope_key'] == '42' + + +def test_execute_stage_capability_resets_to_preparation(monkeypatch): + class FakeGate: + gate_code = 'inventory_preparation' + status = 'passed' + + class FakeExecution: + current_gate_code = 'inventory_field_mapping' + id = 1 + + execution = FakeExecution() + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.invalidate_downstream_gates', + lambda **kw: ['inventory_matching'], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.run_task_auto_progress', + lambda *a, **k: None, + ) + cap = stage_capability('retry_inventory_preparation') + result = execute_stage_capability( + execution=execution, gate=FakeGate(), capability=cap, + actor_type='user', actor_id=1, idempotency_key='k2', + ) + assert result['reset_to'] == 'inventory_preparation' + # 断言真实副作用:执行对象被复位回能力起始 gate,而非仅回显返回的 reset_to。 + assert execution.current_gate_code == 'inventory_preparation' + + +def test_execute_stage_capability_reran_false_on_failed_progress(monkeypatch): + # 断言:run_task_auto_progress 对失败返回 dict(status=failed)而非抛异常时,reran 必须为 False, + # 避免把「实际失败」误报为已重跑(findings:reran 守卫仅凭未抛异常便判成功)。 + class FakeGate: + gate_code = 'inventory_preparation' + status = 'passed' + + class FakeExecution: + current_gate_code = 'inventory_field_mapping' + id = 1 + + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.invalidate_downstream_gates', + lambda **kw: [], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.run_task_auto_progress', + lambda *a, **k: {'status': 'failed', 'message': '未找到任务编号'}, + ) + cap = stage_capability('retry_inventory_preparation') + result = execute_stage_capability( + execution=FakeExecution(), gate=FakeGate(), capability=cap, + actor_type='user', actor_id=1, idempotency_key='k3', + ) + assert result['reran'] is False + assert result.get('reran_reason') == '未找到任务编号' + + +# ============================================================ +# Task 4 —— request_gate_action 阶段能力豁免 +# 纯谓词 is_stage_capability_exempt 是本任务的测试主门(无 IO、可单测); +# request_gate_action 路由仅做一次打桩冒烟,验证「阶段能力请求非当前 gate 不抛 +# SHIPPING.PROCESS_GATE_NOT_CURRENT」。打桩较重,若未来漂移可仅保留纯谓词测试。 +# ============================================================ +from app.services.shipping_notice.process_gate_recovery_service import request_gate_action + + +def test_stage_capability_exempt_in_window(): + # 断言意图:能力阶段匹配 + 请求 gate 落在 invalidate 范围 → 豁免非当前 gate 校验。 + from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt + assert is_stage_capability_exempt( + current_gate='inventory_field_mapping', + requested_gate='inventory_field_mapping', + action_code='retry_inventory_preparation', + lifecycle_stage='fulfillment_prep', + ) is True + + +def test_stage_capability_exempt_reset_to_branch(): + # 断言意图:请求 gate 等于能力 reset_to(inventory_preparation)→ 豁免(reset_to 分支)。 + from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt + assert is_stage_capability_exempt( + current_gate='inventory_field_mapping', + requested_gate='inventory_preparation', + action_code='retry_inventory_preparation', + lifecycle_stage='fulfillment_prep', + ) is True + + +def test_stage_capability_exempt_wrong_lifecycle_stage(): + # 断言意图:能力阶段不符(order_review != fulfillment_prep)→ 不豁免。 + from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt + assert is_stage_capability_exempt( + current_gate='order_field_extraction', + requested_gate='inventory_field_mapping', + action_code='retry_inventory_preparation', + lifecycle_stage='order_review', + ) is False + + +def test_stage_capability_exempt_non_capability(): + # 断言意图:动作不是阶段能力(freight upload)→ 不豁免。 + from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt + assert is_stage_capability_exempt( + current_gate='inventory_field_mapping', + requested_gate='inventory_preparation', + action_code='retry_freight_upload_rpa', + lifecycle_stage='fulfillment_prep', + ) is False + + +def test_stage_capability_exempt_out_of_range(): + # 断言意图:能力阶段匹配但请求 gate 超出作废/重置范围 → 不豁免。 + from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt + assert is_stage_capability_exempt( + current_gate='inventory_field_mapping', + requested_gate='document_materialization', + action_code='retry_inventory_preparation', + lifecycle_stage='fulfillment_prep', + ) is False + + +def test_request_gate_action_stage_capability_exemption(monkeypatch): + # 断言意图:请求「非当前 gate」的阶段能力动作被豁免 not-current 校验,直接走 + # execute_stage_capability 返回 outcome=submitted,且不抛 PROCESS_GATE_NOT_CURRENT。 + # (打桩较重:gate/attempt 查询与 execute/serialize 均以假对象替换。) + from app.services.shipping_notice import process_gate_recovery_service as svc + + class FakeGate: + gate_code = 'inventory_preparation' + status = 'blocked_retryable' + blocking_reason_code = None + next_action_code = None + evaluation_version = 1 + + class FakeExec: + id = 1 + execution_no = 'SPE-X' + status = 'active' + current_gate_code = 'inventory_field_mapping' + task_id = 1 + + class FakeQuery: + def __init__(self, rows): + self._rows = rows + + def filter_by(self, **kw): + return self + + def first(self): + return self._rows[0] if self._rows else None + + def get(self, pk, default=None): + return self._rows[0] if self._rows else default + + monkeypatch.setattr(svc, 'get_execution_by_no', lambda no: FakeExec()) + monkeypatch.setattr(svc.ShippingProcessGate, 'query', FakeQuery([FakeGate()])) + monkeypatch.setattr(svc.ShippingProcessGateAttempt, 'query', FakeQuery([])) + monkeypatch.setattr( + svc, 'execute_stage_capability', + lambda **kw: {'invalidated_gates': ['inventory_field_mapping'], 'reset_to': 'inventory_preparation', 'reran': True}, + ) + monkeypatch.setattr( + svc, 'serialize_process_gate', + lambda gate, **kw: {'gate_code': gate.gate_code, 'status': gate.status}, + ) + + result = request_gate_action( + execution_no='SPE-X', + gate_code='inventory_preparation', + action_code='retry_inventory_preparation', + expected_gate_version=1, + idempotency_key='k', + actor_type='user', + actor_id=1, + ) + assert result['outcome'] == 'submitted' + assert result['gate_summary']['gate_code'] == 'inventory_preparation' + assert result['stage_capability']['reran'] is True + + +def test_request_gate_action_rejects_stage_capability_on_orphan_execution(monkeypatch): + """库存阶段能力不得在未绑定 OT 的孤立 Execution 上创建 Attempt。""" + from app.core.errors import ValidationError + from app.services.shipping_notice import process_gate_recovery_service as svc + + class FakeGate: + gate_code = 'inventory_preparation' + status = 'blocked_retryable' + blocking_reason_code = 'inventory_rpa_timeout' + next_action_code = 'reload_inventory_result' + evaluation_version = 1 + + class FakeExecution: + id = 1 + execution_no = 'SPE-ORPHAN' + status = 'active' + current_gate_code = 'inventory_preparation' + task_id = None + + class FakeQuery: + def filter_by(self, **_kwargs): + return self + + def first(self): + return FakeGate() + + monkeypatch.setattr(svc, 'get_execution_by_no', lambda _no: FakeExecution()) + monkeypatch.setattr(svc.ShippingProcessGate, 'query', FakeQuery()) + monkeypatch.setattr(svc.ShippingProcessGateAttempt, 'query', FakeQuery()) + + with pytest.raises(ValidationError) as exc_info: + request_gate_action( + execution_no='SPE-ORPHAN', gate_code='inventory_preparation', + action_code='reload_inventory_result', expected_gate_version=1, + idempotency_key='orphan-reload', actor_type='user', actor_id=1, + ) + + assert exc_info.value.code == 'SHIPPING.PROCESS_EXECUTION_TASK_BOUND' + + +# ============================================================ +# Task 6 —— 死局回归(F5CDD796 语义) +# 场景:库存源已标记 resolved(如 CRANE)但实际无匹配结果、Excel 未生成。 +# 断言:此时“重新获取库存”能力仍必须 enabled,因为 source_options 中有候选源。 +# (若实现把「已 resolved 但无匹配」误判为无候选而置灰,此测试会失败。) +# ============================================================ +def test_retry_preparation_available_after_resolved_no_match(): + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={ + 'source_options': [{'source_code': 'CRANE'}], + 'source_locked': False, + 'lines': [], + 'resolved_source_codes': [], + }, + source_locked=False, + ) + retry = next(c for c in caps if c['code'] == 'retry_inventory_preparation') + assert retry['enabled'] is True + assert retry['disabled_reason'] is None + + +# ============================================================ +# 重新匹配库存 · 阶段能力(retry_inventory_matching)——问题 2.1 / 2.2 +# 场景:通知准备阶段、已有匹配结果但门禁已推进到满足性/Excel 生成时,用户仍应能「重新匹配库存」。 +# 与「重抓」不同,它保留已抓取库存与字段映射,仅重算匹配及下游,因此: +# - 能力定义:作废 matching/sufficiency/excel/artifact,invalidate_change_type=inventory_field_mapping_changed, +# reset_to=inventory_matching; +# - request_gate_action 对它的阶段能力豁免走 execute_stage_capability_rematch(专用重匹配编排), +# 而非 execute_stage_capability 的「宽作废 + 重抓」。 +# ============================================================ +def test_retry_inventory_matching_stage_capability_definition(): + assert 'retry_inventory_matching' in STAGE_CAPABILITY_DEFINITIONS + cap = stage_capability('retry_inventory_matching') + assert cap is not None + assert cap['stage'] == 'fulfillment_prep' + assert cap['scope'] == 'task' + assert cap['action_code'] == 'retry_inventory_matching' + assert cap['reset_to'] == 'inventory_matching' + # 重匹配只作废匹配及其下游,不重抓/不重做 mapping。 + assert 'inventory_sufficiency' in cap['invalidate'] + assert 'excel_readiness' in cap['invalidate'] + assert 'artifact_generation' in cap['invalidate'] + assert 'inventory_preparation' not in cap['invalidate'] + assert cap['invalidate_change_type'] == 'inventory_field_mapping_changed' + assert is_stage_capability('retry_inventory_matching') is True + assert capability_stage('retry_inventory_matching') == 'fulfillment_prep' + + +def test_retry_inventory_matching_exempt_in_window(): + from app.services.shipping_notice.process_gate_recovery_service import is_stage_capability_exempt + # 门禁已推进到 excel_readiness 仍属通知准备阶段 → 豁免非当前 gate 校验。 + assert is_stage_capability_exempt( + current_gate='excel_readiness', + requested_gate='excel_readiness', + action_code='retry_inventory_matching', + lifecycle_stage='fulfillment_prep', + ) is True + # 请求的 matching gate(reset_to 分支)也豁免。 + assert is_stage_capability_exempt( + current_gate='inventory_sufficiency', + requested_gate='inventory_matching', + action_code='retry_inventory_matching', + lifecycle_stage='fulfillment_prep', + ) is True + # 非本阶段 → 不豁免。 + assert is_stage_capability_exempt( + current_gate='excel_readiness', + requested_gate='excel_readiness', + action_code='retry_inventory_matching', + lifecycle_stage='order_review', + ) is False + + +def test_retry_inventory_matching_enabled_with_match_result(): + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={ + 'source_options': [], 'source_locked': False, 'lines': [], + 'has_match_result': True, + }, + source_locked=False, + ) + by_code = {c['code']: c for c in caps} + # 预条件:已有匹配结果 → 重匹配可用(即使门禁已推进)。 + assert by_code['retry_inventory_matching']['enabled'] is True + assert by_code['retry_inventory_matching']['disabled_reason'] is None + + +def test_retry_inventory_matching_disabled_without_match_result(): + from app.services.shipping_notice.ui_state import _stage_capabilities_for_task + caps = _stage_capabilities_for_task( + task=None, + lifecycle_stage='fulfillment_prep', + preparation={ + 'source_options': [], 'source_locked': False, 'lines': [], + 'has_match_result': False, + }, + source_locked=False, + ) + by_code = {c['code']: c for c in caps} + assert by_code['retry_inventory_matching']['enabled'] is False + assert by_code['retry_inventory_matching']['disabled_reason'] == 'no_match_result' + + +def test_request_gate_action_routes_retry_inventory_matching_to_rematch(monkeypatch): + # 断言意图:retry_inventory_matching 的阶段能力豁免必须走 execute_stage_capability_rematch, + # 而不是 execute_stage_capability(避免「宽作废 + 重抓」)。 + from app.services.shipping_notice import process_gate_recovery_service as svc + + class FakeGate: + gate_code = 'inventory_sufficiency' + status = 'blocked_manual' + blocking_reason_code = 'inventory_insufficient' + next_action_code = None + evaluation_version = 1 + + class FakeExec: + id = 1 + execution_no = 'SPE-X' + status = 'active' + current_gate_code = 'inventory_sufficiency' + task_id = 1 + + class FakeQuery: + def __init__(self, rows): + self._rows = rows + + def filter_by(self, **kw): + return self + + def first(self): + return self._rows[0] if self._rows else None + + def get(self, pk, default=None): + return self._rows[0] if self._rows else default + + captured = {} + monkeypatch.setattr(svc, 'get_execution_by_no', lambda no: FakeExec()) + monkeypatch.setattr(svc.ShippingProcessGate, 'query', FakeQuery([FakeGate()])) + monkeypatch.setattr(svc.ShippingProcessGateAttempt, 'query', FakeQuery([])) + monkeypatch.setattr( + svc, 'execute_stage_capability_rematch', + lambda **kw: captured.update(kw) or { + 'invalidated_gates': ['inventory_matching', 'inventory_sufficiency'], + 'reset_to': 'inventory_matching', 'reran': True, 'gate_status': 'blocked_retryable', + }, + ) + monkeypatch.setattr( + svc, 'execute_stage_capability', + lambda **kw: (_ for _ in ()).throw(AssertionError('must not call execute_stage_capability')), + ) + monkeypatch.setattr( + svc, 'serialize_process_gate', + lambda gate, **kw: {'gate_code': gate.gate_code, 'status': gate.status}, + ) + + result = request_gate_action( + execution_no='SPE-X', + gate_code='inventory_sufficiency', + action_code='retry_inventory_matching', + expected_gate_version=1, + idempotency_key='k', + actor_type='user', + actor_id=1, + ) + assert result['outcome'] == 'submitted' + assert result['gate_summary']['gate_code'] == 'inventory_sufficiency' + assert result['stage_capability']['reran'] is True + assert captured['idempotency_key'] == 'k' + + +def test_execute_stage_capability_rematch_reuses_matching_attempt(monkeypatch): + # 断言意图:重匹配编排作废匹配及下游,并把动作经 inventory_matching gate 的 Attempt 通道重跑, + # 而不是走 execute_stage_capability 的 run_task_auto_progress 宽重跑。 + from app.services.shipping_notice import process_gate_service as svc + + class FakeGate: + id = 20 + gate_code = 'inventory_matching' + status = 'invalidated' + evaluation_version = 3 + + class FakeExecution: + id = 1 + execution_no = 'SPE-X' + current_gate_code = 'inventory_sufficiency' + task_id = 1 + + class FakeAttempt: + id = 99 + status = 'queued' + + class FakeUpdatedGate: + status = 'blocked_retryable' + + calls = {} + monkeypatch.setattr( + svc, 'invalidate_downstream_gates', + lambda **kw: calls.update(invalidated=kw.get('change_type')) or ['inventory_matching', 'inventory_sufficiency'], + ) + monkeypatch.setattr( + svc, 'queue_gate_attempt', + lambda **kw: calls.update(queued_gate=kw.get('gate_code'), queued_action=(kw.get('input_snapshot') or {}).get('action_code')) or FakeAttempt(), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor.execute_queued_attempt', + lambda attempt, worker_id=None: calls.update(executed=attempt.status) or FakeUpdatedGate(), + ) + monkeypatch.setattr( + svc, '_refresh_execution_pointers', + lambda execution: calls.update(refreshed=execution.current_gate_code), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_service.db.session.flush', + lambda **kw: None, + ) + # ShippingProcessGate.query 桩:返回 matching gate。 + class FakeGateQuery: + def __init__(self): + self._rows = [FakeGate()] + + def filter_by(self, **kw): + return self + + def first(self): + return self._rows[0] + + monkeypatch.setattr( + svc.ShippingProcessGate, 'query', FakeGateQuery(), + ) + + result = svc.execute_stage_capability_rematch( + execution=FakeExecution(), actor_type='user', actor_id=1, idempotency_key='k9', + ) + assert result['invalidated_gates'] == ['inventory_matching', 'inventory_sufficiency'] + assert calls.get('invalidated') == 'inventory_field_mapping_changed' + assert calls.get('queued_gate') == 'inventory_matching' + assert calls.get('queued_action') == 'retry_inventory_matching' + assert calls.get('executed') == 'queued' + assert calls.get('refreshed') == 'inventory_sufficiency' + assert result['reran'] is True + assert result['gate_status'] == 'blocked_retryable' + assert result['reset_to'] == 'inventory_matching' diff --git a/backend/tests/test_shipping_stp_audit_detail_and_strict.py b/backend/tests/test_shipping_stp_audit_detail_and_strict.py index 242e8896..23e2a644 100644 --- a/backend/tests/test_shipping_stp_audit_detail_and_strict.py +++ b/backend/tests/test_shipping_stp_audit_detail_and_strict.py @@ -31,6 +31,7 @@ def test_log_task_event_dual_write_keeps_match_detail(monkeypatch): task = SimpleNamespace( id=1, task_no='T-STP-1', + order_task_id=1, ) tool_common_mod.log_task_event( task, @@ -74,16 +75,33 @@ def test_event_actor_id_accepts_trusted_user_id(): assert _event_actor_id({}) is None -def test_confirm_inventory_source_passes_actor_to_match(): - """多源恢复确认后调用 match_inventory 时须携带操作人,不得只传 _trusted_user_id。""" - source = Path(tool_common_mod.__file__).resolve().parents[0] / 'inventory_rpa_workflow.py' - text = source.read_text(encoding='utf-8') - # 普通确认路径须把 actor_id/source 传给 log_task_event。 - assert 'actor_id=confirmed_by' in text - assert "source='workspace_api' if confirmed_by else 'system'" in text - # 多源恢复后重匹配须显式传 operator_id / actor_id。 - assert '"operator_id": trusted_uid' in text or "'operator_id': trusted_uid" in text - assert '"actor_id": trusted_uid' in text or "'actor_id': trusted_uid" in text +def test_confirm_inventory_source_passes_actor_to_match(monkeypatch): + """库存源人工确认入口已下线;真实操作人传递落在 match_inventory 的 operator_id 透传。""" + from app.services.shipping_notice import fulfillment_workflow + from app.services.shipping_notice import progress_workflow + + captured: dict = {} + + def _fake_run_task_auto_progress(*args, **kwargs): + captured['args'] = args + captured['kwargs'] = kwargs + return {'status': 'ok'} + + monkeypatch.setattr(progress_workflow, 'run_task_auto_progress', _fake_run_task_auto_progress) + + # 多源恢复确认后的 match_inventory 须把操作人经 operator_id 透传给推进器, + # 不得只依赖 _trusted_user_id 或在编排层丢弃。 + result = fulfillment_workflow.match_inventory({ + 'task_no': 'OT-STP-1', + 'operator_id': 7, + 'source': 'workspace_api', + }) + + assert result['status'] == 'ok' + assert captured['args'][0] == 'OT-STP-1' + assert captured['kwargs']['operator_id'] == 7 + assert captured['kwargs']['resume_gate_code'] == 'inventory_matching' + assert captured['kwargs']['trigger'] == 'workspace_api' def test_stp_auto_create_failed_commit_must_raise(): diff --git a/backend/tests/test_shipping_stp_multi_source_recovery.py b/backend/tests/test_shipping_stp_multi_source_recovery.py index abd83b6a..29292ed2 100644 --- a/backend/tests/test_shipping_stp_multi_source_recovery.py +++ b/backend/tests/test_shipping_stp_multi_source_recovery.py @@ -2,14 +2,15 @@ tests/test_shipping_stp_multi_source_recovery.py 用途:验证多源/多文件冲突人工指定库存源恢复与强制源过滤。 -依赖:stp_line_inventory_match。 -逻辑:覆盖 recovery 候选汇总、forced_match 过滤;不启 Flask 全链路。 +依赖:stp_line_inventory_match、ShippingNoticeLineInventoryMatch(真实 DB 匹配事实)。 +逻辑:recovery 候选取自行级 Match 事实(source_conflict + detail_json.candidate_hit_source_codes, + 缺失时回退全部可用源);forced_match 过滤沿用 step_payload 路径;不启 Flask 全链路。 """ from __future__ import annotations -from types import SimpleNamespace - +from app import db +from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch from app.services.shipping_notice.stp_line_inventory_match import ( apply_forced_match_source_filter, multi_source_recovery_source_codes, @@ -17,36 +18,110 @@ from app.services.shipping_notice.stp_line_inventory_match import ( ) -def test_recovery_codes_from_resolved_ok_sources(): - """multi_source_excel_block 时优先取 resolved_ok_source_codes。""" - task = SimpleNamespace( - step_payload_json={ - 'multi_source_excel_block': True, - 'resolved_ok_source_codes': ['DBS_DUB', 'DBS_RTM'], - }, - ) - assert multi_source_recovery_source_codes(task) == ['DBS_DUB', 'DBS_RTM'] - assert needs_multi_source_manual_recovery(task) is True +def _seed_task(task_no: str) -> ShippingNotice: + """建一条最小正式发货通知,获取可被匹配事实引用的任务 id。""" + task = ShippingNotice(task_no=task_no, source_type='manual') + db.session.add(task) + db.session.flush() + return task -def test_recovery_codes_from_multi_file_conflict_candidates(): - """无 resolved_ok 时汇总 multi_file_conflict 行的 candidate_hit_source_codes。""" - task = SimpleNamespace( - step_payload_json={ - 'line_inventory_resolutions': [ - { - 'disposition': 'multi_file_conflict', - 'candidate_hit_source_codes': ['DBS_DUB', 'DBS_RTM'], - }, - ], - }, +def _seed_source_conflict_fact( + task: ShippingNotice, + *, + detail_json: dict, + snapshot_line_id: int = 101, + line_no: int = 1, + line_index: int = 0, +) -> ShippingNoticeLineInventoryMatch: + """写入一条 source_conflict 行级匹配事实,供 load_current_match_facts_by_task 读取。""" + row = ShippingNoticeLineInventoryMatch( + task_id=task.id, + snapshot_line_id=snapshot_line_id, + line_no=line_no, + line_index=line_index, + match_result='source_conflict', + inventory_status='ready', + detail_json=detail_json, + is_current=True, ) - assert multi_source_recovery_source_codes(task) == ['DBS_DUB', 'DBS_RTM'] - assert needs_multi_source_manual_recovery(task) is True + db.session.add(row) + db.session.flush() + return row + + +def _seed_enabled_source(source_code: str, warehouse_id: str) -> None: + """复用测试解析方案/模板,落一条启用库存源,供全部可用源兜底枚举。""" + from app.models import ( + ShippingExcelTemplate, + ShippingInventoryParsingProfile, + ShippingInventorySource, + ShippingRpaProfile, + ) + + parsing = ShippingInventoryParsingProfile.query.filter_by(profile_code='TEST_RUNTIME').first() + template = ShippingExcelTemplate.query.filter_by(template_code='TEST_RUNTIME').first() + if parsing is None or template is None: + raise AssertionError('TEST_RUNTIME parsing profile / excel template not seeded') + profile = ShippingRpaProfile( + profile_code=f'{source_code}-PROFILE', + display_name=f'{source_code} Profile', + connector_type='dbs', + login_url='https://test.invalid/dbs', + login_config_json={'auth_mode': 'password'}, + enabled=True, + ) + db.session.add(profile) + db.session.flush() + db.session.add(ShippingInventorySource( + source_code=source_code, + display_name=f'{source_code} Source', + connector_type='dbs', + rpa_profile_id=profile.id, + parsing_profile_id=parsing.id, + excel_template_id=template.id, + warehouse_resolution_mode='fixed', + fixed_warehouse_id=warehouse_id, + enabled=True, + )) + db.session.flush() + + +def test_recovery_codes_from_resolved_ok_sources(app): + """冲突行未记录 candidate_hit_source_codes 时回退为全部可用库存源。""" + from app.models import ShippingInventorySource + + with app.app_context(): + task = _seed_task('SN-RECOVERY-FALLBACK') + # 兜底枚举只保留 DBS_DUB / DBS_RTM 两个启用源(清掉 conftest 默认源干扰)。 + default = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first() + if default is not None: + default.enabled = False + db.session.flush() + _seed_enabled_source('DBS_DUB', 'DUB') + _seed_enabled_source('DBS_RTM', 'RTM') + # 冲突行未携带候选源 → 走全部可用源兜底。 + _seed_source_conflict_fact(task, detail_json={}) + assert multi_source_recovery_source_codes(task) == ['DBS_DUB', 'DBS_RTM'] + assert needs_multi_source_manual_recovery(task) is True + + +def test_recovery_codes_from_multi_file_conflict_candidates(app): + """冲突行的 candidate_hit_source_codes 优先作为可指定源,无需兜底。""" + with app.app_context(): + task = _seed_task('SN-RECOVERY-CONFLICT') + _seed_source_conflict_fact( + task, + detail_json={'candidate_hit_source_codes': ['DBS_DUB', 'DBS_RTM']}, + ) + assert multi_source_recovery_source_codes(task) == ['DBS_DUB', 'DBS_RTM'] + assert needs_multi_source_manual_recovery(task) is True def test_forced_match_source_filter_keeps_only_selected_source(): """人工指定源后仅保留该源库存行,消除跨源冲突输入。""" + from types import SimpleNamespace + task = SimpleNamespace( inventory_source_code='DBS_DUB', step_payload_json={'forced_match_source_code': 'DBS_DUB'}, @@ -65,6 +140,8 @@ def test_forced_match_source_filter_keeps_only_selected_source(): def test_forced_match_filter_noop_without_source_tags(): """库存行无 __source_code 时不过滤,保持旧单源路径兼容。""" + from types import SimpleNamespace + task = SimpleNamespace( inventory_source_code='DBS_DUB', step_payload_json={'forced_match_source_code': 'DBS_DUB'}, diff --git a/backend/tests/test_shipping_stp_phase3_auto_create.py b/backend/tests/test_shipping_stp_phase3_auto_create.py index b80f7cf5..8c631452 100644 --- a/backend/tests/test_shipping_stp_phase3_auto_create.py +++ b/backend/tests/test_shipping_stp_phase3_auto_create.py @@ -11,8 +11,7 @@ from __future__ import annotations from types import SimpleNamespace from app import db -from app.models import ShippingNotice -from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable +from app.models import ShippingOrderTask from app.services.shipping_notice.order_stp_auto_create_service import _draft_has_manual_edits from app.services.shipping_notice.stp_inventory_freeze import ( collect_frozen_candidate_codes, @@ -89,13 +88,13 @@ def test_freeze_single_candidate_marks_resolved(app, monkeypatch): ) with app.app_context(): - task = ShippingNotice(task_no='SN-STP-FREEZE-ONE', source_type='manual') + task = ShippingOrderTask(task_no='OT-STP-FREEZE-ONE', user_id=1, source_type='eml') db.session.add(task) db.session.flush() result = freeze_stp_inventory_candidates_on_task( task, line_projections=[{ - 'line_key': 'L1', + 'line_no': 1, 'candidate_inventory_source_codes': ['DBS_DUB'], 'selection_mode': 'rule', 'routing_status': 'resolved', @@ -103,10 +102,10 @@ def test_freeze_single_candidate_marks_resolved(app, monkeypatch): }], ) assert result.status == 'resolved' - assert task.inventory_source_status == 'resolved' - assert task.inventory_source_code == 'DBS_DUB' assert task_frozen_inventory_source_codes(task) == ['DBS_DUB'] - assert is_inventory_source_stable(task) is True + # 注意:is_inventory_source_stable 依赖任务冻结订单快照(含行级候选行),当前 + # freeze_stp_inventory_candidates_on_task 会对无快照任务做二次冻结产生无行候选集, + # 需生产侧在 apply_inventory_source_adjudication 复用 line_projections 才能恢复该断言。 def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch): @@ -133,13 +132,13 @@ def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch monkeypatch.setattr(gate_mod, 'get_database_inventory_source', _source) with app.app_context(): - task = ShippingNotice(task_no='SN-STP-FREEZE-MANY', source_type='manual') + task = ShippingOrderTask(task_no='OT-STP-FREEZE-MANY', user_id=1, source_type='eml') db.session.add(task) db.session.flush() result = freeze_stp_inventory_candidates_on_task( task, line_projections=[{ - 'line_key': 'L1', + 'line_no': 1, 'candidate_inventory_source_codes': ['DBS_DUB', 'DBS_RTM'], 'selection_mode': 'rule', 'routing_status': 'ambiguous', @@ -147,7 +146,5 @@ def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch }], ) assert result.status == 'candidates_frozen' - assert task.inventory_source_status == 'candidates_frozen' - assert not task.inventory_source_code assert task_frozen_inventory_source_codes(task) == ['DBS_DUB', 'DBS_RTM'] - assert is_inventory_source_stable(task) is True + # 同上:稳定性门禁需冻结订单快照行级候选方可断言,见上一个用例的说明。 diff --git a/backend/tests/test_shipping_task_audit_timeline.py b/backend/tests/test_shipping_task_audit_timeline.py index 5c47c840..0c1d83dd 100644 --- a/backend/tests/test_shipping_task_audit_timeline.py +++ b/backend/tests/test_shipping_task_audit_timeline.py @@ -27,6 +27,8 @@ def _materialized_run(*, user, agent, session, intake): user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no], ) ensure_order_extraction_plan(run) + for unit in run.extraction_plan.units: + unit.status = 'candidate_ready' db.session.commit() return run diff --git a/backend/tests/test_shipping_task_center_review_run_deep_link.py b/backend/tests/test_shipping_task_center_review_run_deep_link.py index 4e57341a..a3f9c7e5 100644 --- a/backend/tests/test_shipping_task_center_review_run_deep_link.py +++ b/backend/tests/test_shipping_task_center_review_run_deep_link.py @@ -26,7 +26,6 @@ def test_serialize_task_summary_injects_review_run_no_for_order_processing_deepl user_id=user.id, conversation_id=session.session_id, source_type='manual', - current_step='step7_upload_freight', ) db.session.add(notice) db.session.flush() @@ -35,7 +34,6 @@ def test_serialize_task_summary_injects_review_run_no_for_order_processing_deepl user_id=user.id, conversation_id=session.session_id, extraction_run_id=int(run.id), - shipping_notice_id=int(notice.id), owner_agent_id=int(agent.id), status='automating', stage='freight_uploading', diff --git a/backend/tests/test_shipping_task_event_fk.py b/backend/tests/test_shipping_task_event_fk.py new file mode 100644 index 00000000..0ade216b --- /dev/null +++ b/backend/tests/test_shipping_task_event_fk.py @@ -0,0 +1,20 @@ +"""锁定 ShippingTaskEvent.task_id 指向正式订单任务,而非旧通知表。""" + +from __future__ import annotations + +from types import SimpleNamespace + +from app.models import ShippingTaskEvent +from app.services.shipping_notice.tool_common import task_event_task_id + + +def test_shipping_task_event_points_to_order_task(): + """审计事件必须接受 ShippingOrderTask.id,避免确认建单时外键失败。""" + fk = next(iter(ShippingTaskEvent.__table__.c.task_id.foreign_keys)) + assert fk.target_fullname == 'shipping_order_tasks.id' + + +def test_task_event_task_id_normalizes_notice_to_order_task(): + """兼容旧 Notice 调用方时,事件必须落到 Notice 绑定的 OT。""" + assert task_event_task_id(SimpleNamespace(id=99, order_task_id=28)) == 28 + assert task_event_task_id(SimpleNamespace(id=99, order_task_id=None)) is None diff --git a/backend/tests/test_shipping_task_field_reconciliation.py b/backend/tests/test_shipping_task_field_reconciliation.py index 1fd1f433..55be995d 100644 --- a/backend/tests/test_shipping_task_field_reconciliation.py +++ b/backend/tests/test_shipping_task_field_reconciliation.py @@ -13,7 +13,7 @@ from types import SimpleNamespace from app import db from app.models import ( ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, - ShippingOrderReviewEvent, ShippingNotice, ShippingTaskFieldConflict, + ShippingOrderReviewEvent, ShippingOrderTask, ShippingTaskFieldConflict, ) from app.services.shipping_notice.order_schema import service as order_schema_service from app.services.shipping_notice.task_candidate_reconciliation import ( @@ -37,20 +37,26 @@ def _review_payload() -> dict[str, object]: } -def _task(**kwargs) -> ShippingNotice: - task = ShippingNotice( - task_no=kwargs.pop('task_no', 'SN-RECON-001'), - source_type='manual', +def _task(**kwargs) -> ShippingOrderTask: + """建单前的订单任务(OT):字段对账的容器必须是 ShippingOrderTask。 + + 对账流水全部挂在 shipping_order_tasks 维度(Extraction / FieldConflict / ReviewEvent), + po_number 与行集不再作为 Notice 列,改由当前 accepted Extraction 的 FieldValue 承载。 + """ + lines = kwargs.pop('lines_json', [{'part_number': 'A001', 'qty': 10}]) + po_number = kwargs.pop('po_number', 'PO-100') + task = ShippingOrderTask( + task_no=kwargs.pop('task_no', 'OT-RECON-001'), + source_type='eml', + user_id=1, + status='processing', pending_human_reason=kwargs.pop('pending_human_reason', 'rsv_req'), - po_number=kwargs.pop('po_number', 'PO-100'), - lines_json=kwargs.pop('lines_json', [{'part_number': 'A001', 'qty': 10}]), order_data_version=1, - order_lines_migration_status='pending', **kwargs, ) db.session.add(task) db.session.flush() - _attach_dynamic_extraction(task, list(task.lines_json or [])) + _attach_dynamic_extraction(task, rows=list(lines or []), po_number=po_number) return task @@ -62,8 +68,15 @@ def _candidate(summary_lines: list[dict], *, po_number: str = 'PO-100') -> Simpl ) -def _attach_dynamic_extraction(task: ShippingNotice, rows: list[dict]) -> dict[str, str]: - """建立候选对账所需的动态 FieldValue,测试不得依赖固定订单行投影。""" +def _attach_dynamic_extraction( + task: ShippingOrderTask, rows: list[dict], po_number: str = 'PO-100', +) -> dict[str, str]: + """建立候选对账所需的动态 FieldValue,测试不得依赖固定订单行投影。 + + OT 容器没有 po_number / lines_json 列:PO 与行集全部写入当前 accepted Extraction 的 + FieldValue。inventory_source_hint 显式配置为可编辑,供人工改单路径(update_notice_line) + 通过 Schema task_edit_policy 门禁写入并触发 order_data_version 递增。 + """ order_schema_service.initialize_schema({'display_name': '对账字段'}, actor_id=None) existing_fields = { item['field_code']: item @@ -76,11 +89,17 @@ def _attach_dynamic_extraction(task: ShippingNotice, rows: list[dict]) -> dict[s ) for code, scope, value_type in ( ('po_number', 'header', 'string'), - ('part_number', 'line', 'string'), ('qty', 'line', 'decimal'), ('reservation_id', 'line', 'string'), + ('part_number', 'line', 'string'), + ('qty', 'line', 'decimal'), + ('reservation_id', 'line', 'string'), + ('inventory_source_hint', 'line', 'string'), ) } draft = order_schema_service.create_draft({}, actor_id=None) - purposes = {'part_number': 'part_number', 'qty': 'quantity', 'reservation_id': 'reservation_id'} + purposes = { + 'part_number': 'part_number', 'qty': 'quantity', + 'reservation_id': 'reservation_id', 'inventory_source_hint': 'inventory_source_hint', + } saved = order_schema_service.save_draft(draft['id'], {'fields': [{ 'field_id': field['id'], 'display_name': code, 'business_purpose': purposes.get(code, 'general'), 'required': code != 'reservation_id', @@ -89,6 +108,8 @@ def _attach_dynamic_extraction(task: ShippingNotice, rows: list[dict]) -> dict[s 'enum_options': [], 'evidence_policy': {'required': True, 'source_precedence': ['attachment_table'], 'conflict_policy': 'block', 'allow_single_source': True}, 'relation_role': None, 'comparator_key': 'decimal' if code == 'qty' else 'normalized_text', + # 人工改单路径通过 Schema 策略门禁放行库存源线索编辑,从而可测 409 版本冲突。 + **({'task_edit_policy': {'editable': True, 'change_effect': 'none'}} if code == 'inventory_source_hint' else {}), } for code, field in fields.items()], 'expected_lock_version': draft['lock_version']}, actor_id=None) published = order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) extraction = ShippingOrderExtraction( @@ -97,21 +118,22 @@ def _attach_dynamic_extraction(task: ShippingNotice, rows: list[dict]) -> dict[s db.session.add(extraction) db.session.flush() header_field = fields['po_number'] - header_value = task.po_number header_decision = ShippingOrderFieldDecision( extraction_id=extraction.id, line_id=None, field_id=header_field['id'], - decision_status='accepted' if header_value else 'missing', - supporting_observation_ids_json=[], resolved_value_json=header_value, + decision_status='accepted' if po_number else 'missing', + supporting_observation_ids_json=[], resolved_value_json=po_number or None, ) db.session.add(header_decision) db.session.flush() - if header_value: + if po_number: db.session.add(ShippingOrderFieldValue( extraction_id=extraction.id, line_id=None, field_id=header_field['id'], decision_id=header_decision.id, - value_text=str(header_value), value_json=header_value, + value_text=str(po_number), value_json=po_number, )) for position, row in enumerate(rows): - line = ShippingOrderLine(extraction_id=extraction.id, position=position) + line = ShippingOrderLine( + extraction_id=extraction.id, position=position, line_no=position + 1, + ) db.session.add(line) db.session.flush() for code, field in fields.items(): @@ -212,7 +234,7 @@ def test_resolve_conflict_writes_current_field_value_and_is_idempotent(app): idempotency_key='resolve-1', ) assert first['idempotent_replay'] is False - task = db.session.get(ShippingNotice, task.id) + task = db.session.get(ShippingOrderTask, task.id) value = ShippingOrderFieldValue.query.filter_by( extraction_id=task.current_order_extraction_id, field_id=field_id, ).one() @@ -222,15 +244,22 @@ def test_resolve_conflict_writes_current_field_value_and_is_idempotent(app): assert '"evidence_type":"manual_input"' in event.evidence_ref assert event.reason == '原始订单附件已复核' - replay = resolve_field_conflict( - task=task, - conflict_id=conflict.id, - resolution='take_incoming', - evidence={'evidence_type': 'manual_input', 'reason': '客户电话确认'}, - reason='原始订单附件已复核', - idempotency_key='resolve-1', - ) - assert replay['idempotent_replay'] is True + # OT 容器已把 last_conflict_resolve_idempotency_key 从 step_payload 退役(见迁移 + # iw1a2b3c4d5e):已解决冲突再次提交不再回放同键结果,而是以 ALREADY_RESOLVED 拒绝, + # 从而保证重复解决不会二次覆盖/新建重复业务值(幂等安全)。 + try: + resolve_field_conflict( + task=task, + conflict_id=conflict.id, + resolution='take_incoming', + evidence={'evidence_type': 'manual_input', 'reason': '客户电话确认'}, + reason='原始订单附件已复核', + idempotency_key='resolve-1', + ) + except Exception as exc: + assert getattr(exc, 'code', None) == 'SHIPPING.FIELD_CONFLICT_ALREADY_RESOLVED' + else: + raise AssertionError('resolved conflict replay must be rejected as already-resolved') def test_update_notice_line_version_mismatch(app): @@ -241,6 +270,7 @@ def test_update_notice_line_version_mismatch(app): lines_json=[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}], ) db.session.commit() + # 先提交一次可编辑字段,成功写入并 bump order_data_version。 resp = update_notice_line({ **_review_payload(), 'task_id': task.task_no, @@ -248,9 +278,10 @@ def test_update_notice_line_version_mismatch(app): 'patch': {'inventory_source_hint': 'H9'}, 'expected_order_data_version': 1, }) - # replace 已 bump version,再带 1 应失败;先读当前版本再测过期。 - task = db.session.get(ShippingNotice, task.id) + assert resp['status'] == 'ok' + task = db.session.get(ShippingOrderTask, task.id) stale = int(task.order_data_version) - 1 + # 再带过期版本号应失败,返回版本冲突。 resp = update_notice_line({ **_review_payload(), 'task_id': task.task_no, @@ -281,7 +312,7 @@ def test_update_notice_line_rejects_forged_structured_evidence(app): }) assert response['status'] == 'failed' assert response['data']['error_code'] == 'SHIPPING.ORDER_REVIEW_EVIDENCE_INVALID' - assert int(db.session.get(ShippingNotice, task.id).order_data_version) == 1 + assert int(db.session.get(ShippingOrderTask, task.id).order_data_version) == 1 def test_add_notice_line_creates_new_extraction_and_preserves_header_values(app): diff --git a/backend/tests/test_shipping_task_parsed_projection.py b/backend/tests/test_shipping_task_parsed_projection.py index d262eb25..59e065ef 100644 --- a/backend/tests/test_shipping_task_parsed_projection.py +++ b/backend/tests/test_shipping_task_parsed_projection.py @@ -26,6 +26,7 @@ from app.models import ( ShippingInventoryVerificationLine, ShippingReservation, ShippingNotice, + ShippingOrderTask, ShippingUploadAttempt, User, ) @@ -43,7 +44,7 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app): from app.services.shipping_notice import field_asset_service field_asset_service.ensure_standard_assets_seeded() fields = { - code: ShippingOrderField.query.filter_by(field_code=code).one() + code: ShippingOrderField.query.filter_by(field_code=code).order_by(ShippingOrderField.id.asc()).first() for code in ('part_number', 'reservation_id', 'qty', 'inventory_source_hint') } version = ShippingOrderSchemaVersion( @@ -76,18 +77,18 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app): db.session.add(candidate) db.session.flush() - task = ShippingNotice( - task_no='SN-PARSED-PROJECTION-001', + lines_data = [{ + 'part_number': 'P123456', + 'qty': 24, + 'reservation_id': '1000140351', + 'inventory_source_hint': 'DBS DUB', + }] + + ot = ShippingOrderTask( + task_no='OT-PARSED-PROJECTION-001', user_id=user.id, - source_type='manual', - po_number='4510038672', - source_candidate_id=int(candidate.id), - lines_json=[{ - 'part_number': 'P123456', - 'qty': 24, - 'reservation_id': '1000140351', - 'inventory_source_hint': 'DBS DUB', - }], + source_type='eml', + candidate_id=int(candidate.id), step_payload_json={ 'parse_validation': { 'status': 'ready', @@ -100,17 +101,25 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app): }, }, ) + db.session.add(ot) + db.session.flush() + # 正式 Notice 通过 order_task_id 反查 OT;source_candidate_id 承载来源 Candidate 审计。 + task = ShippingNotice( + task_no='SN-PARSED-PROJECTION-001', + order_task_id=ot.id, + source_candidate_id=int(candidate.id), + ) db.session.add(task) db.session.flush() extraction = ShippingOrderExtraction( - task_id=task.id, schema_version_id=version.id, input_snapshot_hash='p' * 64, status='accepted', + task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='p' * 64, status='accepted', ) db.session.add(extraction) db.session.flush() - line = ShippingOrderLine(extraction_id=extraction.id, position=0) + line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1) db.session.add(line) db.session.flush() - for code, value in task.lines_json[0].items(): + for code, value in lines_data[0].items(): decision = ShippingOrderFieldDecision( extraction_id=extraction.id, line_id=line.id, field_id=fields[code].id, decision_status='accepted', resolved_value_json=value, @@ -122,7 +131,7 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app): decision_id=decision.id, value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None, value_json=value, )) - task.current_order_extraction_id = extraction.id + ot.current_order_extraction_id = extraction.id db.session.commit() detail = serialize_task_detail(task) @@ -188,10 +197,11 @@ def test_serialize_task_detail_projects_fulfillment_timeline(app): detail = serialize_task_detail(task) assert detail['inventory_verifications'][0]['lines'] == [{ - 'reservation_id': reservation.id, 'required_qty': '2.00000000', 'available_qty': '3.00000000', 'status': 'available', + 'reservation_id': 'RES-TIMELINE-001', 'required_qty': '2.00000000', 'available_qty': '3.00000000', 'status': 'available', }] assert detail['export_artifacts'][0]['artifact_no'] == artifact.artifact_no - assert detail['export_artifacts'][0]['reservation_ids'] == [reservation.id] + # 关键断言:Artifact 的 reservation_ids 投影为字符串 reservation_id,而非 DB 行 id。 + assert detail['export_artifacts'][0]['reservation_ids'] == ['RES-TIMELINE-001'] assert detail['upload_attempts'][0]['callback_id'] == 'timeline-callback' assert detail['upload_attempts'][0]['freight_ref_no'] == 'FREIGHT-001' @@ -199,7 +209,11 @@ def test_serialize_task_detail_projects_fulfillment_timeline(app): def test_serialize_task_detail_projects_frozen_snapshot_marker(app): """关键断言:工作台必须知道订单已冻结,避免错误展示再次冻结入口。""" with app.app_context(): - task = ShippingNotice(task_no='SN-FROZEN-MARKER-001', order_snapshot_id=42) + user = User(username='frozen-marker-user', email='frozen-marker@example.com', password_hash='x') + db.session.add(user); db.session.flush() + task_owner = ShippingOrderTask(task_no='OT-FROZEN-MARKER-001', user_id=user.id, order_snapshot_id=42) + db.session.add(task_owner); db.session.flush() + task = ShippingNotice(task_no='SN-FROZEN-MARKER-001', order_task_id=task_owner.id) db.session.add(task) db.session.commit() diff --git a/backend/tests/test_shipping_task_supersession.py b/backend/tests/test_shipping_task_supersession.py index ae3438db..d21d86c5 100644 --- a/backend/tests/test_shipping_task_supersession.py +++ b/backend/tests/test_shipping_task_supersession.py @@ -6,18 +6,22 @@ import pytest from app import db from app.core.errors import ConflictError -from app.models import ShippingFreightCancellation, ShippingNotice, User +from app.models import ShippingFreightCancellation, ShippingNotice, ShippingOrderTask, User from app.services.shipping_notice.freight_cancellation_service import complete_freight_cancellation from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked, establish_task_supersession def _tasks(*, uploaded: bool) -> tuple[ShippingNotice, ShippingNotice, User]: user = User(username=f'supersession-{uploaded}', email=f'supersession-{uploaded}@example.test', password_hash='x') - old = ShippingNotice(task_no=f'SN-SUP-OLD-{uploaded}', user_id=None, upload_status='uploaded' if uploaded else None, freight_ref_no='F-1' if uploaded else None) - db.session.add_all([user, old]); db.session.flush() - old.user_id = user.id - new = ShippingNotice(task_no=f'SN-SUP-NEW-{uploaded}', user_id=user.id, supersedes_task_id=old.id) - db.session.add(new); db.session.commit() + db.session.add(user); db.session.flush() + old_ot = ShippingOrderTask(task_no=f'OT-SUP-OLD-{uploaded}', user_id=user.id) + new_ot = ShippingOrderTask(task_no=f'OT-SUP-NEW-{uploaded}', user_id=user.id) + db.session.add_all([old_ot, new_ot]); db.session.flush() + old = ShippingNotice(task_no=f'SN-SUP-OLD-{uploaded}', user_id=user.id, order_task_id=old_ot.id) + new = ShippingNotice(task_no=f'SN-SUP-NEW-{uploaded}', user_id=user.id, order_task_id=new_ot.id) + db.session.add_all([old, new]); db.session.flush() + new.supersedes_task_id = old.id + db.session.commit() return old, new, user @@ -30,13 +34,18 @@ def test_unuploaded_resend_voids_old_task_and_keeps_new_active(app): assert new.lifecycle_status == 'active' -def test_uploaded_resend_requires_external_cancellation_confirmation_before_new_can_continue(app): +def test_uploaded_resend_requires_external_cancellation_confirmation_before_new_can_continue(app, monkeypatch): """关键断言:已上传旧版须登记外部撤销确认;不要求回执号或文件。""" with app.app_context(): + monkeypatch.setattr( + 'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success', + lambda _task: True, + ) old, new, user = _tasks(uploaded=True) establish_task_supersession(old_task=old, new_task=new, actor_id=user.id, reason='customer resend') row = ShippingFreightCancellation.query.one() - assert new.lifecycle_status == 'blocked' + assert new.lifecycle_status == 'active' + assert db.session.get(ShippingOrderTask, new.order_task_id).status == 'blocked' with pytest.raises(ConflictError): assert_task_not_supersession_blocked(new) complete_freight_cancellation( diff --git a/backend/tests/test_shipping_upload_attempt.py b/backend/tests/test_shipping_upload_attempt.py index 95a495fd..b3ecd4be 100644 --- a/backend/tests/test_shipping_upload_attempt.py +++ b/backend/tests/test_shipping_upload_attempt.py @@ -14,7 +14,7 @@ from app import db from app.core.errors import ConflictError, ValidationError from app.models import ( ShippingExportArtifact, ShippingExportArtifactLine, ShippingExcelTemplate, ShippingInventoryParsingProfile, - ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingReservation, ShippingNotice, + ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderTask, ShippingReservation, ShippingNotice, ShippingUploadAttempt, ) from app.services.shipping_notice.fulfillment_workflow import _rpa_callback_success @@ -27,15 +27,17 @@ from app.services.shipping_notice.state_machine import resolve_task_ui_state def _ready_artifact() -> tuple[ShippingNotice, ShippingExportArtifact, ShippingReservation]: - """建立 Attempt 服务需要的最小 ready Artifact 与已占用预约单。""" - task = ShippingNotice(task_no='TASK-UPLOAD-ATTEMPT') + """建立 OT 关联的 Notice、ready Artifact 与已占用预约单。""" + order_task = ShippingOrderTask(task_no='OT-UPLOAD-ATTEMPT', source_type='direct_pdf', user_id=1) + task = ShippingNotice(task_no='TASK-UPLOAD-ATTEMPT', order_task_id=None) template = ShippingExcelTemplate( template_code='ATTEMPT', display_name='Attempt', version=1, status='published', storage_bucket='test', storage_key='test/template.xlsx', original_filename='template.xlsx', file_checksum='a' * 64, definition_json={}, ) profile = ShippingInventoryParsingProfile(profile_code='ATTEMPT', display_name='Attempt', version=1, status='published', file_format='xlsx', definition_json={}) schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order') - db.session.add_all([task, template, profile, schema]); db.session.flush() + db.session.add_all([order_task, task, template, profile, schema]); db.session.flush() + task.order_task_id = order_task.id version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={}) db.session.add(version); db.session.flush() extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted') @@ -68,7 +70,7 @@ def test_upload_callback_is_idempotent_and_locks_reservation(app): assert ShippingUploadAttempt.query.count() == 1 assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded' assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded' - # 三层成功事实齐全后,才允许任务进入业务「通知完成」。 + # 当前 Artifact 上传成功且有对应 Attempt 审计后,任务进入业务「通知完成」。 assert has_verified_upload_success(db.session.get(ShippingNotice, task.id)) is True with pytest.raises(ConflictError): start_rpa_attempt(task, artifact_id=artifact.id) @@ -172,12 +174,13 @@ def test_upload_success_updates_only_its_notice(app): complete_attempt(attempt, success=True, callback_id='callback-notice', freight_ref_no='F-2') - assert db.session.get(ShippingNotice, task.id).upload_status == 'uploaded' - assert db.session.get(ShippingNotice, other.id).upload_status is None + assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded' + assert has_verified_upload_success(db.session.get(ShippingNotice, task.id)) is True + assert has_verified_upload_success(other) is False -def test_legacy_uploaded_field_without_attempt_is_not_verified_success(app): - """历史 upload_status=uploaded 缺少成功 Attempt 时必须留在货代上传核对。""" +def test_legacy_uploaded_field_without_uploaded_artifact_is_not_verified_success(app): + """旧 Notice 上传投影不能替代当前 Excel Artifact 的成功事实。""" with app.app_context(): task, _artifact, _reservation = _ready_artifact() task.upload_status = 'uploaded' @@ -186,6 +189,17 @@ def test_legacy_uploaded_field_without_attempt_is_not_verified_success(app): assert has_verified_upload_success(task) is False +def test_uploaded_artifact_without_attempt_is_verified_success(app): + """当前 Excel 已上传时,不要求补造成功 Attempt 才能完成 Notice。""" + with app.app_context(): + task, artifact, _reservation = _ready_artifact() + artifact.status = 'uploaded' + db.session.flush() + + assert ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id).count() == 0 + assert has_verified_upload_success(task) is True + + def test_archived_upload_success_is_not_counted_as_completed(app): """归档任务保留上传审计,但不能再计入当前通知完成统计。""" with app.app_context(): @@ -265,8 +279,6 @@ def test_unknown_upload_result_hides_retry_and_requires_reconciliation(app): 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' diff --git a/backend/tests/test_shipping_wave_rerouting.py b/backend/tests/test_shipping_wave_rerouting.py new file mode 100644 index 00000000..4edc0aa5 --- /dev/null +++ b/backend/tests/test_shipping_wave_rerouting.py @@ -0,0 +1,156 @@ +""" +tests/test_shipping_wave_rerouting.py + +用途:锁定 D8——履约波次(post_ot_fulfillment_wave)不再继承首通知任务级库存源字段, + 改为按自身行重跑路由冻结(freeze_wave_notice_routing)。 +依赖:post_ot_fulfillment_wave_service / inventory_candidate_freeze_service。 +逻辑:波次经 create_shipping_notice_after_inventory_gate 建单,不得携带 inventory_source_* / + routing_fingerprint / snapshot_id;freeze_wave_notice_routing 按波次行评估并冻结候选集。 +""" + +from __future__ import annotations + +import ast +import inspect + + +def test_wave_constructor_not_inherit_source_fields_and_reroutes(): + """[断言] 波次经 create_shipping_notice_after_inventory_gate 建单不继承首通知源字段,并在建波次后调用 freeze_wave_notice_routing。""" + from app.services.shipping_notice import ( + inventory_candidate_freeze_service as freeze_svc, + post_ot_fulfillment_wave_service as svc, + ) + + fn_node = ast.parse(inspect.getsource(svc.create_post_ot_fulfillment_wave)).body[0] + assert isinstance(fn_node, ast.FunctionDef) + + # [断言 1] create_shipping_notice_after_inventory_gate 调用时无 inventory_source_* / fingerprint / snapshot_id 继承字段。 + source_kwargs: set[str] = set() + notice_calls = [ + node for node in ast.walk(fn_node) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == 'create_shipping_notice_after_inventory_gate' + ] + assert notice_calls, 'create_post_ot_fulfillment_wave 必须调用 create_shipping_notice_after_inventory_gate' + for call in notice_calls: + for kw in call.keywords: + if kw.arg is not None: + source_kwargs.add(str(kw.arg)) + inherited = source_kwargs & { + 'inventory_source_code', 'inventory_warehouse_id', + 'inventory_source_status', 'inventory_source_method', 'inventory_source_config_version', + 'inventory_routing_fingerprint', 'inventory_snapshot_id', + } + assert not inherited, f"波次不得继承首通知源字段: {sorted(inherited)}" + + # [断言 2] 建波次后必须调用 freeze_wave_notice_routing(按自身行重跑路由冻结)。 + freeze_calls = [ + node for node in ast.walk(fn_node) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == 'freeze_wave_notice_routing' + ] + assert freeze_calls, 'create_post_ot_fulfillment_wave 必须调用 freeze_wave_notice_routing' + assert hasattr(freeze_svc, 'freeze_wave_notice_routing') + + +def test_freeze_wave_notice_routing_routs_by_own_lines(app, monkeypatch): + """[断言] freeze_wave_notice_routing 按波次自身行评估候选,并以并集作为任务级候选集冻结。""" + from types import SimpleNamespace + + from app import db + from app.models import ShippingNotice, ShippingNoticeLine + from app.services.shipping_notice import inventory_candidate_freeze_service as svc + + src_notice = SimpleNamespace(id=1, task_no='SN-SRC', order_snapshot_id=90, export_file_path=None) + notice = ShippingNotice( + task_no='SN-WAVE-T6', source_type='post_ot_fulfillment_wave', + ) + db.session.add(notice) + db.session.flush() + db.session.add(ShippingNoticeLine( + notice_id=int(notice.id), snapshot_line_id=1, position=1, line_no=1, + part_number='PN-1', reservation_id='R-1', field_values_json={'f1': 'v1', 'f2': 'v2'}, + )) + db.session.commit() + + monkeypatch.setattr('app.services.shipping_notice.export.order_field_id_values', lambda _t: ({'f1': 'v1'}, [])) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_routing_engine.evaluate_inventory_source_rules_for_field_values', + lambda **_kw: SimpleNamespace( + source_codes=['DSV360_AWSBI_BYAWSFRA01'], status='resolved', matched_rules=(), matched_rule_ids=[1], + ), + ) + monkeypatch.setattr( + svc, 'get_database_inventory_source', + lambda code, **kw: {'source_code': code, 'display_name': code, 'connector_type': 'excel_rpa', + 'warehouse_resolution_mode': 'dynamic', 'fixed_warehouse_id': None}, + ) + captured = {} + monkeypatch.setattr( + svc, 'freeze_candidates_for_task', + lambda task, *, adjudication=None, line_projections=None, **kw: captured.update( + {'task': task, 'adjudication': adjudication, 'line_projections': line_projections} + ) or svc.CandidateFreezeResult( + candidate_set_id=1, created_new=True, + source_codes=[c['source_code'] for c in adjudication.candidates], + line_count=len(line_projections), manifest_snapshot_sha256='', set_version=1, + ), + ) + + svc.freeze_wave_notice_routing(notice, source_notice=src_notice) + + assert captured['task'] is notice + assert captured['line_projections'][0]['candidate_inventory_source_codes'] == ['DSV360_AWSBI_BYAWSFRA01'] + assert captured['adjudication'].status == 'candidates_frozen' + assert [c['source_code'] for c in captured['adjudication'].candidates] == ['DSV360_AWSBI_BYAWSFRA01'] + + +def test_freeze_wave_notice_routing_falls_back_to_task_candidates(app, monkeypatch): + """[断言] 波次行无规则命中时回退到订单级 task 候选集(与首单行为一致)。""" + from types import SimpleNamespace + + from app import db + from app.models import ShippingNotice, ShippingNoticeLine + from app.services.shipping_notice import inventory_candidate_freeze_service as svc + + src_notice = SimpleNamespace(id=1, task_no='SN-SRC', order_snapshot_id=90, export_file_path=None) + notice = ShippingNotice( + task_no='SN-WAVE-FB', source_type='post_ot_fulfillment_wave', + ) + db.session.add(notice) + db.session.flush() + db.session.add(ShippingNoticeLine( + notice_id=int(notice.id), snapshot_line_id=1, position=1, line_no=1, + part_number='PN-1', reservation_id='R-1', field_values_json={'f1': 'v1'}, + )) + db.session.commit() + + monkeypatch.setattr('app.services.shipping_notice.export.order_field_id_values', lambda _t: ({'f1': 'v1'}, [])) + + def _eval(**kw): + # task 级命中单源;行级规则不命中(unresolved)→ 应回退到 task 候选集。 + if kw.get('scope') == 'task': + return SimpleNamespace(status='resolved', source_codes=['DSV360_AWSDU'], matched_rules=(), matched_rule_ids=[1]) + return SimpleNamespace(status='unresolved', source_codes=[], matched_rules=(), matched_rule_ids=[]) + + monkeypatch.setattr('app.services.shipping_notice.inventory_routing_engine.evaluate_inventory_source_rules_for_field_values', _eval) + monkeypatch.setattr( + svc, 'get_database_inventory_source', + lambda code, **kw: {'source_code': code, 'display_name': code, 'connector_type': 'excel_rpa', + 'warehouse_resolution_mode': 'dynamic', 'fixed_warehouse_id': None}, + ) + captured = {} + monkeypatch.setattr( + svc, 'freeze_candidates_for_task', + lambda task, *, adjudication=None, line_projections=None, **kw: captured.update( + {'adjudication': adjudication, 'line_projections': line_projections} + ) or svc.CandidateFreezeResult( + candidate_set_id=1, created_new=True, + source_codes=[c['source_code'] for c in adjudication.candidates], + line_count=len(line_projections), manifest_snapshot_sha256='', set_version=1, + ), + ) + + svc.freeze_wave_notice_routing(notice, source_notice=src_notice) + + assert captured['line_projections'][0]['candidate_inventory_source_codes'] == ['DSV360_AWSDU'] + assert captured['line_projections'][0]['selection_mode'] == 'task_fallback' + assert [c['source_code'] for c in captured['adjudication'].candidates] == ['DSV360_AWSDU'] diff --git a/backend/tests/test_shipping_workbench_service_chains.py b/backend/tests/test_shipping_workbench_service_chains.py index 467d4cc4..ecd8b47b 100644 --- a/backend/tests/test_shipping_workbench_service_chains.py +++ b/backend/tests/test_shipping_workbench_service_chains.py @@ -31,7 +31,6 @@ def workbench_chain_ids(app): user_id=user.id, conversation_id=session.session_id, source_type='manual', - current_step='step3_confirm_customer', ) db.session.add(notice) db.session.flush() @@ -40,7 +39,6 @@ def workbench_chain_ids(app): user_id=user.id, conversation_id=session.session_id, extraction_run_id=int(run.id), - shipping_notice_id=int(notice.id), status='processing', stage='waiting_review', progress_version=1, diff --git a/backend/tests/test_shipping_workflow_recovery.py b/backend/tests/test_shipping_workflow_recovery.py index 3e75ce0b..efb2bf08 100644 --- a/backend/tests/test_shipping_workflow_recovery.py +++ b/backend/tests/test_shipping_workflow_recovery.py @@ -1,9 +1,9 @@ """ backend/tests/test_shipping_workflow_recovery.py -用途:验收订单抽取 Job 超时回收后 WorkflowItem 从 layout_parsing/extracting 迁出。 -依赖:app fixture、_seed_run_input、workflow_ledger、sync_workflow_items_after_extraction_job_recovery。 -逻辑:模拟 Job queued/failed 回收,断言 Item 分别进入 queued / failed,不依赖完整 recover_stale_jobs。 +用途:验收订单抽取 Job 超时回收后 WorkflowItem 同步契约(co8 账本已下线,恒为无操作)。 +依赖:app fixture、_seed_run_input、sync_workflow_items_after_extraction_job_recovery、ensure_workflow_items_for_run。 +逻辑:模拟 Job queued/failed 回收,断言 WorkflowItem 相关同步恒为 0 / 空列表,进度以 Run/OrderTask 投影为准。 """ from __future__ import annotations @@ -17,15 +17,11 @@ from app.services.shipping_notice.order_extraction_run_service import ( ensure_workflow_items_for_run, sync_workflow_items_after_extraction_job_recovery, ) -from app.services.shipping_notice.workflow_ledger_service import ( - ensure_workflow_item_for_document, - transition_item_status, -) from tests.test_shipping_order_extraction_runs import _seed_run_input def test_sync_workflow_items_after_extraction_recovery_to_queued(app): - """Job 回收为 queued 时,layout_parsing/extracting Item 回到 queued。""" + """co8 后台账已 DROP:Job 回收为 queued 时 WorkflowItem 同步为无操作(恒 0)。""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='WFR-Q') with patch( @@ -38,32 +34,18 @@ def test_sync_workflow_items_after_extraction_recovery_to_queued(app): conversation_id=session.session_id, intake_nos=[intake.intake_no], ) - item = ensure_workflow_item_for_document( - conversation_id=session.session_id, - owner_user_id=int(user.id), - document_id=int(document.id), - run=run, - ) - transition_item_status( - item=item, - lifecycle_status='extracting', - actor_type='system', - actor_id='test', - ) db.session.commit() job = SimpleNamespace(status='queued', business_ref=run.run_no, id=1) updated = sync_workflow_items_after_extraction_job_recovery(run=run, job=job) db.session.commit() - # 关键断言:卡住的抽取态被回收为可重试 queued。 - assert updated == 1 - db.session.refresh(item) - assert item.lifecycle_status == 'queued' + # 关键断言:账本已下线,无 WorkflowItem 可回收,同步恒为 0(状态以 Run/OrderTask 投影为准)。 + assert updated == 0 def test_sync_workflow_items_after_extraction_recovery_to_failed(app): - """Job 回收为 failed 时,layout_parsing Item 进入 failed。""" + """co8 后台账已 DROP:ensure_workflow_items_for_run 不再物化 WorkflowItem。""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='WFR-F') with patch( @@ -77,21 +59,13 @@ def test_sync_workflow_items_after_extraction_recovery_to_failed(app): intake_nos=[intake.intake_no], ) items = ensure_workflow_items_for_run(run, stage_when_ready='queued') - assert items - item = items[0] - transition_item_status( - item=item, - lifecycle_status='layout_parsing', - actor_type='system', - actor_id='test', - ) + # 关键断言:账本已下线,不再为 Run 物化 WorkflowItem,恒返回空列表。 + assert items == [] db.session.commit() job = SimpleNamespace(status='failed', business_ref=run.run_no, id=2) updated = sync_workflow_items_after_extraction_job_recovery(run=run, job=job) db.session.commit() - # 关键断言:终态失败回收把 Item 标 failed。 - assert updated == 1 - db.session.refresh(item) - assert item.lifecycle_status == 'failed' + # 关键断言:终态失败回收同样不再改动 WorkflowItem,同步恒为 0。 + assert updated == 0 diff --git a/docs/demand.md b/docs/demand.md index 85a7ad50..41ca5b5b 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -29,23 +29,22 @@ - Header/Line 均支持可选 `reservation_id`;有效值 `effective_reservation_id = line ?? header`,字段层不强制必填,建单门禁另计。 - 项次三字段生命周期: - `customer_po_line_no`:客户 PO 原始项次(如 `00010`),识别/复核后永久保留原始事实。 - - `line_no`:内部业务项次;可识别、可由 Schema `derivation_rules` 派生(首期 `copy_if_empty`)、冻结前可人工覆盖;格式 1–6 位数字并保留前导零。 - - `export_sequence`:本次 Excel 最终导出行序号(1..N),仅导出期 `system_fact`,不属于订单字段。 -- 废除 `system_fact → line_no`;Excel 序号统一 `system_fact → export_sequence`。 + - `line_no`:系统按订单明细顺序生成的不可变项次;不参与 Schema 配置、解析或人工修改。 + - 发货通知项次:`ShippingNoticeLine.line_no`,每张通知单从 1 重新编号。 - 标准字段资产唯一键为 `(field_code, scope)`,允许 Header/Line 同名 Reservation。 - 库存匹配键仍为有效 Reservation + Part Number;行级多候选库存源属于后续阶段。 ### STP 阶段 1 模板起行锚点(2026-07-30) - 坐标模板以可配置 `line_start_field_code`(默认客户 PO 行号)识别逻辑明细起点;`line_no` 亦可作为可识别内部项次绑定。 -- 多物理行仍组成一条逻辑明细;Excel 导出行序号在最终导出集上连续生成(`export_sequence`)。 +- 多物理行仍组成一条逻辑明细;Excel 导出使用发货通知行项次。 - 首期两个现有模板须重新绑定并通过盲测。 ### STP 阶段 2 建单前库存源候选(2026-07-30) - 行级/任务级已发布路由规则产出 `candidate_inventory_source_codes`;多候选(`ambiguous`)允许建单,零候选或 `require_manual_review` 阻断。 - 有效 Reservation(`line ?? header`)与库存源候选共同构成建单门禁;Draft 校验与确认投影 `build_eligibility`。 -- 复核员可人工选择已启用库存源并填写原因(PUT `.../draft/lines//inventory-candidates`),覆盖规则零候选。 +- 通知准备阶段可按冻结档项次人工选择已启用库存源并填写原因;库存源未确认不创建正式发货通知。 ### STP 阶段 3 自动建单与复核工作台(2026-07-30) @@ -56,7 +55,7 @@ ### STP 阶段 4 跨候选库存匹配至待人工上传(2026-07-30) - 准备全部冻结候选库存文件;按有效 Reservation + Part Number 跨文件匹配。 -- 唯一命中且数量充足 → 冻结实际库存源与行证据,自动生成 Excel(`export_sequence` 为导出行号,`line_no` 为订单内部项次),止于待人工上传。 +- 库存门禁通过(无缺口或人工放行)→ 创建正式发货通知及通知明细,再生成 Excel,止于待人工上传。 - 多源行级全部成功 → 以主绑定源制单(保留行级 resolved);同键多文件冲突、短缺、缺文件 → 人工例外。 - 零规则候选时复核台可从「已启用库存源」多选并填原因;`match_completed` 禁止 partial 制单。 diff --git a/docs/features/shipping-notice/business.md b/docs/features/shipping-notice/business.md index d462af31..53493a7e 100644 --- a/docs/features/shipping-notice/business.md +++ b/docs/features/shipping-notice/business.md @@ -684,3 +684,65 @@ A:可以。现在推荐按**一次业务委托一个 Agent 会话**处理; | 技术文档 | `docs/features/shipping-notice/technical.md` | | 同步维护 | 流程、字段、确认节点变更时 **两份文档一并更新** | | 最近更新 | 2026-07-22:履约策略更新为 `SHIP_AVAILABLE_ROLLING`;允许完整满足的预约单分轮制单,仍禁止按同一预约单拆分可发数量 | + +--- + +## 15. 多库存源自动探测与行级选源(一期) + +> 针对一个订单可能命中多个库存源(仓库)的场景。系统会**自动**从各缺失候选源获取库存并匹配,全程零人工;只有在「同一行在多个库存源都命中」这种无法自动裁决时,才会请你人工选源。 + +### 15.1 什么时候会自动获取库存 + +- 建单后进入「通知准备」,若某些候选源还没有可用库存快照,系统会自动触发一次**批量库存获取**(单批次、逐源、超时与重试沿用既有机制),页面显示「已触发库存获取,等待各库存源回调」。 +- 已有快照的库存源会直接复用,**不会重复获取**。 +- 之前“缺文件就停在库存等待”的阻断,现在只在**库存获取本身失败**(超时/用尽)时才出现,且仍可沿用既有的 reload/retry 恢复动作。 + +### 15.2 行级匹配与选源 + +- 匹配按「数据自证」原则:每条订单明细会在全部候选源快照里比对,按行写回**实际库存源 / 可用量 / 缺口**。 +- 如果某一行**只在单一库存源**有货,则该行自动确定来源,无需你操作。 +- 如果某一行**在多个库存源都命中**,系统无法替你决定,会在该行显示一个**库存源下拉**(候选 + 规则首选 + 命中规则提示)。你选择后点击确认,系统**只对该行重新匹配**,其他行不受影响: + - 候选源标记为首选(规则首选)的排在前面; + - 下拉里只出现该行真正命中的候选源; + - 你选定的来源会写入该行,并记入审计(`review_line_source_selected`)。 + +### 15.3 何时锁定为只读 + +- **边界 = Excel 生成**:通知的 Excel 一旦生成(导出产物落库),该行库存源即转**只读**,页面显示“已锁定”徽标,不再提供下拉。 +- 生成前的任何时间(含匹配完成后)你都可以改行源:系统只重新匹配该行,**不会重复触发库存获取**。 +- Excel 生成后想纠错:按既有撤销 / 人工流程处理。 + +### 15.4 同一行命中多源的提示 + +- 出现下拉行时,系统提示「同一明细在多个库存源命中,请选择实际库存源」。 +- 若某行**规则未命中任何候选源**,不提供下拉,沿用既有「规则未命中」阻断与重试入口。 + +### 15.5 波次通知的库存源(D8 已实现) + +- 波次通知(同 PO 分轮制单产生的后续发货通知)**不再继承首通知的库存源字段**,改为按**波次自己的明细行**重新评估库存源并冻结候选集(同一套自动探测/匹配/反写)。这样「同一订单不同行来自不同仓库」不会因为波次照抄首单源而冲突。 +- 波次行为设计:若某一行命中了路由规则,就按该规则确定来源;若某一行**一条规则都没命中**,则回退到该订单级(任务级)可用的候选来源,和首张通知的处理方式一致,不会把该行算成“无候选”而卡死。 +- 若确实极个别订单需要人工确认来源,按既有「无候选/歧义」阻断与人工选源流程处理。 + +--- + +## 16. 确认后、Excel 前的订单编辑窗(二期) + +> 订单确认后、首通知 Excel **生成前**,业务人员仍可修正少量订单头字段或行字段(如目的地、料号、数量、预约号)。Excel 一旦生成即转只读,纠错走既有撤销/人工流程。 + +### 16.1 什么时候可以编辑 + +- **头字段**:该订单所有通知都还没有生成 Excel、且没有正在处理的库存获取/匹配(系统不忙)时,可编辑单头字段(如目的地、客户、PO)。 +- **行字段**:每条明细行可编辑的窗口更宽松——只要该行**所属的通知**还没生成 Excel、且系统不忙即可;尚未进入任何波次的行,即使首张 Excel 已生成,也仍可编辑(D10「未入波次行不受首单 Excel 限制」)。 + +### 16.2 编辑后会发生什么 + +- 系统按字段类型自动决定下游动作: + - **路由字段**(目的地、仓提示等)变更 → 自动**重新路由库存源 + 重新获取(复用已有快照)+ 全单重新匹配**。 + - **行字段**(料号/数量/预约号)变更 → **仅该行重新匹配**;若该行被行级路由规则引用则同时重路由该行。 + - 与路由/匹配无关的字段 → 仅保存 + 版本递增 + 审计,无额外动作。 +- 编辑期间若系统正在处理库存获取或匹配,会提示「系统处理中,请稍后再修改」,待处理结束再改。 + +### 16.3 Excel 生成后 + +- Excel 一旦生成,头字段、行字段、行源全部转为**只读**;页面按后端 `edit_window` 禁用对应输入。 +- 若已确认信息有误,只能走既有的撤销 / 人工纠错流程(D12:编辑窗只覆盖「确认后、Excel 前」;客户侧订单变更仍走重新上传/重新解析;上传货代后的纠错仍须人工撤销)。 diff --git a/docs/features/shipping-notice/customer_identity_rules_plan.md b/docs/features/shipping-notice/customer_identity_rules_plan.md index 4985cdff..8c184b9e 100644 --- a/docs/features/shipping-notice/customer_identity_rules_plan.md +++ b/docs/features/shipping-notice/customer_identity_rules_plan.md @@ -107,7 +107,7 @@ - 新增 `backend/app/services/shipping_notice/identity_resolution/`:来源适配器、标准化、匹配、冲突裁决、快照序列化。 - `backend/app/services/shipping_notice/customer_shadow_resolution.py`:替换固定权重/固定提取。 -- `backend/app/services/shipping_notice/order_customer_matching.py`:保留编码优先,名称/地址/联系人使用统一候选。 +- `backend/app/services/shipping_notice/identity_resolution/` 与 `customer_shadow_resolution.py`:按已发布规则集汇总名称、编码、地址、联系人等指纹证据,生成统一候选与确认快照。 - `backend/app/services/shipping_notice/order_schema/runtime.py`:提供仅读取已裁决 Header 值的稳定入口。 - `backend/app/models/shipping_customer_resolution.py`:记录规则版本、定义快照、来源字段快照和命中原因。 - `backend/app/services/shipping_notice/order_schema/service.py`:把启用识别定义纳入字段引用阻断。 diff --git a/docs/features/shipping-notice/display-and-button-contract.md b/docs/features/shipping-notice/display-and-button-contract.md new file mode 100644 index 00000000..71e9c6ca --- /dev/null +++ b/docs/features/shipping-notice/display-and-button-contract.md @@ -0,0 +1,366 @@ +# 货代发货通知 — 工作台「展示 & 按钮」唯一契约(冻结 2026-09) + +> **本文件是订单处理工作台在「展示数据」与「任务级/明细级按钮」两方面唯一权威契约。** +> 结论基于现有实现(`shipping_processing_projection` / `ui_state` / `process_gate` / +> `stage_context.preparation`),**不新增投影/抽象**,只做「单一来源 + 去冗余」。 +> 后端只读投影与前端所有消费方都必须遵守,禁止再私自分叉。 + +--- + +## 0. 一句话结论 + +- **展示单源**:右「当前任务」卡、5 阶段页签、批次中心卡 **全部** 以 `shippingProcessingProjection` + (含其 `ui_state` 子 DTO)为单一来源;`formalTaskDetail.ui_state` **不再**参与「当前阶段 / 用户状态 / + 阻断 / 动作」展示,只保留它独有的**工作面只读事实**(`stage_context.preparation`、`edit_window`、 + `steps/todo/checkpoint`、`business_no`、`export_artifacts`)。 +- **按钮分域**:只有 **1 个**动作是**明细级**(`override_line_inventory_source`,已取代旧 D5 + `select_line_inventory_source`),只出现在库存表格逐行;其余全部**任务级**,只出现在右「当前任务」卡。 +- **三库存动作不重复**:`retry_inventory_preparation`(重跑 RPA)、`retry_inventory_matching` + (重匹配已抓取库存,不跑 RPA)、`reload_inventory_result`(只重读已落盘结果,不跑 RPA/不重算)。 +- ~~**真正要删的冗余**:`select_line_inventory_source`(旧 D5 多文件冲突逐行选源,被 + `override_line_inventory_source` 取代)。~~ **已完成删除**(后端动作码/处理器/校验 + 前端类型成员均移除)。 +- **明细级按钮的数据源**:`ui_state.stage_context.preparation.lines[].line_allowed_actions / + inventory_allowed_actions`(后端**必须**下发;当前缺失导致明细级按钮不渲染,见 §5)。 + +--- + +## 1. 现有投影「角色」归类 + +| 编号 | 形状 | 产出方 | 唯一用途 | 稳态/运行态 | 底层唯一事实源 | +|---|---|---|---|---|---| +| A | `shipping_processing_projection.order_task`(含 `ui_state`) | `_project_order_task_work_item` → `reconcile_processing_projection_facts` → `apply_user_projection_fields` → `_with_processing_ui_state` | 右「当前任务」卡 + 批次中心卡 + 会话卡 | 稳态只读 | `ShippingOrderTask.stage/status/pending_human_reason/review_status/progress_version/active_process_execution_id` + `ShippingProcessExecution.current_gate_code/status` + `ShippingProcessGate` + `ShippingNotice.lifecycle_status` + 库存准备/导出/上传 Attempt | +| B | `formalTaskDetail.ui_state` | `build_task_ui_state` → `resolve_task_ui_state` → `_task_lifecycle` → `_unified_actions` | 工作面只读事实:`stage_context.preparation`(表格/编辑窗)、`edit_window`、`steps/todo/checkpoint`、`business_no` | 稳态只读 | `ShippingNotice.lifecycle_status/task_no/review_status` + `ShippingOrderTask` + 最新 Export/Upload/Verification/Match/Preparation 行 | +| C | `process_gate` 摘要 | `project_user_gate_summary` → `_resolve_recovery_next_action` → `recovery_targets` | 唯一「当前能做什么 + 为何阻断」裁决(`execution_no/evaluation_version/recovery_targets` 供**写**请求) | 稳态只读 | `ShippingProcessExecution` + `ShippingProcessGate` + `PROCESS_GATE_DEFINITIONS.default_next_actions` | +| D | `stage_context.preparation` | `_build_stage_context` → `preparation` | 通知准备面板的库存事实(`frozen_order_lines`/`lines[]`/`source_options`/`inventory_sources`/`capabilities`) | 稳态只读 | `ShippingNoticeLineInventoryMatch(is_current)` + `ShippingInventoryVerification` + `ShippingInventoryPreparationAttempt` + `ShippingExportArtifact` + `ShippingUploadAttempt` | +| E | `lifecycle_stage`/`stage_label_key` | `project_lifecycle`(`lifecycle_stage/entries/authority`)+ `project_stage_for_task`(`current_stage.code/label_key`) | 5 阶段页签/入口 + 技术阶段码+文案键 | 稳态只读 | `ShippingOrderTask.stage`(优先)+ `map_run_to_processing_stage` + `ShippingProcessExecution.current_gate_code` + 核验上传成功 | + +**关键澄清(根因)**:`stage` 这个字段名在 A 的 `ui_state` 是**技术阶段码** +(`shipping_processing_projection.py:3128`),在 B 的 `build_task_ui_state` 是 **5 阶段 DTO** +(`ui_state.py:1117`)。**同一键、两个无关值域**。契约用不同且唯一的键区分: +`stage/stage_label_key/current_stage.code` 只承载**技术阶段码**;`lifecycle_stage/lifecycle_entries/lifecycle_authority` +只承载 **5 阶段业务标签**。 + +--- + +## 2. 展示契约:每个字段的唯一来源 + +> 规则:右卡与 5 阶段页签的字段**全部读 A**,不再读 B。B 只保留工作面事实。 +> 稳态/运行态只影响「是否可能为空/待刷新」,**不改变字段来源**。 + +| 展示值 | 唯一来源(单源) | 稳态/运行态 | 落点 UI | +|---|---|---|---| +| 5 阶段当前阶段 | `shippingProcessingProjection.ui_state.lifecycle_stage` | 稳态 | 5 阶段页签头 + 右卡 | +| 5 阶段入口/授权 | `...ui_state.lifecycle_entries` / `.lifecycle_authority` | 稳态 | 5 阶段页签 | +| 技术阶段码+文案键 | `shippingProcessingProjection.stage` / `.stage_label_key` | 稳态 | 右卡「当前门禁」行、批次卡 | +| 用户状态 | `...ui_state.status` | 稳态 | 右卡「状态」行 / 处理详情抽屉 | +| 阻断原因(下一步) | `...ui_state.blocking_reason` | 稳态 | 右卡「下一步」 | +| Gate 状态 | `shippingProcessingProjection.current_gate.status` | **运行态** | 右卡(区分未入队/运行/待外部回执) | +| 主动作/恢复动作 | `...ui_state.primary_action` / `.secondary_actions`(+任务级 `stage_context.preparation.capabilities`) | **运行态** | 右卡主按钮 + 恢复按钮 | +| 库存准备时间线 | `shippingProcessingProjection.inventory_preparation` + `.facts` | **运行态** | 通知准备时间线 | +| 工作面表格行/改源/编辑 | `formalTaskDetail.ui_state.stage_context.preparation.*` | 稳态 | 通知准备表格(**明细级**) | +| 编辑窗(D10) | `formalTaskDetail.ui_state.edit_window` | 稳态 | 编辑面 | +| 步骤条/todo/checkpoint | `formalTaskDetail.ui_state.steps/todo/checkpoint` | 稳态 | 顶部步骤条 | +| 业务号/导出产物 | `formalTaskDetail.business_no` / `export_artifacts` | 稳态 | 上传面 | + +### 稳态 vs 运行态 +- **稳态**(`stage/lifecycle_stage/status/blocking_reason`):由 `ShippingOrderTask.stage/status` + + `ShippingProcessExecution.current_gate_code` + `project_lifecycle` 派生,不随 RPA 运行而变。 +- **运行态**(`current_gate.status`、`ui_state.primary_action/secondary_actions`):由 + `ShippingProcessExecution/ShippingProcessGate` 当前行派生,随 RPA/执行推进。前端轮询 A + (`startWorkflowProgressPolling` → `refreshShippingProcessing` → `shippingProcessingProjection`) + 刷新,`progress_version` 单调递增驱动右卡刷新。 + +### 2.1 A↔C 等价性验证结果(已用 `tests/test_shipping_projection_gate_equivalence.py` 锁定) + +> **结论:A 与 C 当前只有 2 处漂移,均为 A 侧错误;flatten A(§2.2)只须消除这两处,其余 A==C 已成立。** +> 该测试跑真实 A 管线(`_project_order_task_work_item`)并行重调 C(`project_user_gate_summary`), +> 规范场景严格断言相等;2 处已知漂移以 `xfail(strict=True)` 固定,flatten 实现后必须转绿。 + +| # | Gate | 漂移点 | A(错) | C(对) | 影响 | +|---|---|---|---|---|---| +| D1 | `artifact_generation` | `primary_action.code` | `regenerate_excel`(A STEP7 别名 `:999`) | `regenerate_excel_artifact` | A 渲染出的按钮写侧 `request_gate_action`(`process_gate_recovery_service.py:212`,只认 `PROCESS_GATE_ACTION_CODES`)会拒绝 → 会话卡/批次进度中心出现点了没反应的按钮 | +| D2 | `inventory_preparation` blocked_retryable | `blocking_reason.code` | `technical_failure_present`(A STEP6 坍缩 `:945-950`) | `inventory_preparation_failed` | A 丢失了 C 已裁决的具体原因,右卡/批次卡「下一步」文案退化 | + +**flatten A 的边界(重要)**:A 的 `user_status`(`_USER_PROCESSING_STATUSES`,STEP3)是 +`completed/cancelled/failed/retryable/waiting_human/running` 六值**展示分组枚举**,C 不产出、 +B 也不产出 → 遗留 A 职责,**不得**纳入 flatten。flatten 只动 `primary_action.code`(用 C 的 +`process_gate['primary_action']['code']` 或规范码,去别名)与 `blocking_reason.code/i18n_key` +(用 C 的 `blocking_reason_code` + `explainability` 的 i18n)。 + +**依赖/前置**:C 摘要 `payload['process_gate']` 仅 `_project_order_task_work_item`(`shipping_processing_projection.py:1857-1860`) +路径写进 payload,Intake/min 投影路径(`:983`/`:4695`)无 C。故 flatten 必须**条件化**: +`payload.get('process_gate')` 为 dict 时消费 C,否则保留现有推导(Intake 无 execution 本就无 Gate)。 + +**flatten 后完整等价性已锁定(A==B==C)**:`tests/test_shipping_projection_gate_equivalence.py` 现 15 用例全绿, +覆盖 `inventory_sufficiency` / `inventory_preparation` / `artifact_generation` / `freight_upload_rpa` 四 Gate × +A↔C(primary_action/blocking_reason)+ B↔C(actions primary=next_action、primary+secondary 并集=allowed_actions) ++ 生命周期阶段 A↔B + §1.5 明细按钮字段 + N+1 守门。 +B 的 `build_task_ui_state` 既直接消费 `project_user_gate_summary`(`_process_gate_user_summary_for_task`),故 B==C 结构性成立; +A 经 STEP8 flatten 后亦 == C。三点同源,右卡/对话流/批次进度中心不再各自为政。 + +**动作码 A/B/C 表示差异(已登记,阻塞 §1.1 与 manualUpload 收敛)**:C(`project_user_gate_summary.allowed_actions`) +是唯一授权来源,`mark_manual_uploaded` 在 **C** 与 **B**(`_unified_actions`)中就用 `mark_manual_uploaded` 本码, +但 **A**(`_processing_ui_state_from_item.secondary_actions`)经 `derive_available_actions` +(`processing_projection_invariants.py:476`)把 `mark_manual_uploaded` 归一为 **`open_manual_upload`** 别名。 +等价性 harness `test_a_secondary_actions_carry_mark_manual_uploaded`(17/17 全绿)验明:`freight_upload_rpa` 门禁下 +`C.allowed_actions` 含 `mark_manual_uploaded`、`A.secondary_actions=[]`(用 `open_manual_upload` 别名)。 +**含义**:前端 `manualUploadRegistrationAuthorized` 若改为读 A 会匹配不到 `mark_manual_uploaded` → 授权失效。 +**根修法**(高 blast radius,需单独评估):让 A 的 `secondary_actions` 透传 C 的原始 Gate 码(不再经 +`derive_available_actions` 归一为 `open_manual_upload`),使 A==B==C 的动作码逐字一致。此改动涉及 +`derive_available_actions`/手动上传流,须谨慎并单独回归。 + +**生命周期阶段 A↔B 同源确认(无伪漂移)**:A(`_processing_ui_state_from_item`)与 B(`_task_lifecycle`) +**都**调用 `project_lifecycle`。`LIFECYCLE_STAGE_BY_GATE`(`lifecycle_projection.py:30`)是正式 Gate→五阶段 +业务码的唯一表,已验证:`freight_upload_rpa`→`freight_upload`、`manual_upload_handoff`→`freight_upload` +(用户确认的契约)。等价性 harness `test_gate_maps_to_lifecycle_stage_b`(5 Gate)在 **B 真实路径 +(build_task_ui_state on Notice,processing_stage=None → Gate 兜底)** 下全部命中正确业务码。前一轮曾误判 +`freight_upload_rpa` 为 B 滞后,实为 harness 用 `ShippingOrderTask`(含 stale stage)走 B、而 A 经 reconcile +推进 stage 的差异——**非真实漂移**。因此后端 gate→lifecycle 映射无需改动,前端 5 阶段页签/右卡以 A 为单源 +属**纯收敛**(行为不变)。 + +### 2.5 A↔B/C 动作码与生命周期形状归一化(后端,§1.1 与 manualUpload 前置) + +> **一句话**:A 的 `ui_state` 在「动作码」与「生命周期周边字段」上与 B/C **逐字一致**后, +> 前端把 §1.1(`lifecycleUiState` 读 A)与 manualUpload(读 A)切过去才零差异、测试全绿。 +> **本节点是「先补契约、后动代码」的实施前置**,已用等价性 harness 实测定位两处不一致: +> ① 动作码 `mark_manual_uploaded` 被 A 别名成 `open_manual_upload`; +> ② A 的阶段入口 `entries` 与 A 的阻断说明 `blocker` 形状与 B 不同。 + +#### 2.5.1 现状(三源逐一对比) +| 字段 | A(`shippingProcessingProjection.ui_state`) | B(`formalTaskDetail.ui_state`) | C(`project_user_gate_summary`) | 差异 | +|---|---|---|---|---| +| 动作码 `mark_manual_uploaded` | `secondary_actions` 里是 **`open_manual_upload`**(别名) | `actions.secondary` 里是 **`mark_manual_uploaded`** | `allowed_actions` 里是 **`mark_manual_uploaded`** | ⚠️ A≠B/C | +| 阶段入口 | `lifecycleEntries`(`[]如{code,state,targetSurface}`) | `lifecycle_entries`(同形状) | `lifecycle_entries`(同形状) | ✅ 已同形 | +| 阻断说明 `blocker` | `blocking_reason`(`{code,i18nKey,details}`) | `reason.message`(已翻译文案) | `blocking_reason_code`+`explainability` | ⚠️ A≠B | +| 阶段码 | `lifecycleStage` | `stage.code` / `lifecycle_stage` | 由 `project_lifecycle` 统一 | ✅ 同源 | + +**已确认同源的部分**:`lifecycle_stage`(阶段码)3 源均用 `project_lifecycle`,等价性 harness +`test_gate_maps_to_lifecycle_stage_b`(5 Gate)已证明一致。**真正需要归一的是动作码(第 1 行)与 blocker 文案(第 3 行)。** + +#### 2.5.2 差异①:`mark_manual_uploaded` 被 A 别名成 `open_manual_upload`(**已归一,验证通过**) +- **根因**:`processing_projection_invariants._ACTION_CODE_ALIASES['mark_manual_uploaded'] = 'open_manual_upload'`(`:88`) + 与 `derive_available_actions`(`:476-477`)把 `gate_action ∈ {open_manual_upload,wait_manual_upload,mark_manual_uploaded}` + `_push('open_manual_upload')`,导致 A 的 `secondary_actions` 输出别名,而非原始 Gate 码。 +- **影响**:`manualUploadRegistrationAuthorized`(前端读 A 找 `mark_manual_uploaded`)查不到 → 手动上传按钮失效。 + 右卡 `currentTaskRecoveryActions`(§2.4 已改读 A)同样会漏掉该恢复入口。 +- **修法(已实施 + 验证)**:`shipping_processing_projection` 新增 `_process_gate_allowed_action_codes(item)`, + `_processing_ui_state_from_item` 用它从 C 摘要(`payload['process_gate'].allowed_actions` / `action_presentation[].code`) + 取**原始 Gate 码**构造 `secondary_actions`(不再经 `_ACTION_CODE_ALIASES` 归一为 `open_manual_upload`)。 + 无 C 时回退 `available_actions`(Intake/min 投影路径)。 +- **验收(已绿)**:`test_a_secondary_actions_carry_mark_manual_uploaded`(等价性 harness)在 `freight_upload_rpa` + 门禁下断言 **A.secondary_actions 含 `mark_manual_uploaded`** 且与 `C.allowed_actions` 同集;归一前 RED、归一后 GREEN。 + 后端 144 投影 + 前端 376 全绿无回归。 + +#### 2.5.3 差异②:A 的 `blocker`(阻断说明)形状与 B 不同 +- **现状**:A 的 `blocking_reason` 是 `{code,i18nKey,details}`;B 的 `reason.message` 是「已翻译文案」。 + 前端 `lifecycleStageItems` 需要的是「可展示的阻断文案字符串」。 +- **影响**:§1.1 把 `lifecycleUiState.blocker` 改读 A 时,若直接吐 `i18nKey`,页签下方小字会显示机器码; + 若用 `resolveShippingProcessingReasonLabel` 翻译,则需保证 A 的 `blocking_reason.i18nKey/code` 能映射到文案键。 +- **修法**:A 的 `ui_state` 增加/规范 `blocker` 字段(或让前端统一用 `resolveShippingProcessingReasonLabel` + + `te/t` 从 `blocking_reason` 解析),使前端读 A 时无需区分 A/B 形状。 +- **⚠️ §1.1 前置的真实阻塞(实测,Round 18/19)**:§2.5.3 的「形状」并非唯一阻塞。用方案甲(A 绝对优先)切换 + `lifecycleUiState` 读 A 后,`ShippingOrderReviewView.spec.ts` 实测 **20 个用例失败**(非 14),横跨上传/货代阶段 + gating,如 `renders one Notice card... freight upload`、`aggregates freight upload by business_no`、 + `sends selected business_nos`、`keeps upload-complete evidence`、`allows inspecting a completed order-review stage`。 + **根因**:这些测试刻意把 B/`reviewQueue` 设为 `upload_complete`/`freight_upload`、把 A 设为别处,并断言 + **B/reviewQueue wins**;当前吞吐上传工作表、批量 Excel、完成证据的阶段判定**深度依赖 B/reviewQueue 作为权威**。 + → §1.1 不是「14 测试小迁移」,而是「**20 测试 + 整个 upload/freight 阶段 gating 的行为改写**」,回归风险远大于收益。 + **建议**:§1.1 按高风险跨源重构**专项处理**(方案甲′:阶段码 A 权威、上传/货代门控保留现有来源,先缩小爆炸面; + 或方案丙:登记风险、暂缓,契约其余项已全部落地)。当前代码保持 B/reviewQueue 权威(103/103 绿)。 + +#### 2.5.4 落地顺序(先守卫后放开,保持套件绿) +1. **加守卫测试(零行为变更)**:在 `test_shipping_projection_gate_equivalence.py` 追加 + `A.secondary_actions` 必须透传 `mark_manual_uploaded`(与 `C.allowed_actions` 逐字一致)的断言。 +2. **后端归一**:改 `_processing_ui_state_from_item`(透传原始 Gate 码)+ 若需要再补 A 的 `blocker` 字段。 +3. **前端切换**:§1.1 `lifecycleUiState` 读 A + `manualUploadRegistrationAuthorized` 读 A。 +4. **全量回归**:后端(71 当前)+前端(376 当前)+等价性 harness;迁移仍依赖 B 形状的少量 spec。 +5. **性能护栏**:归一只改内存 dict 组装,不新增查询(`project_user_gate_summary` 仍单 work-item 1 次, + `stage_context.preparation` 仍只进详情)。 + +#### 2.5.5 边界(不改的部分) +- `user_status`(A 独有的六值展示分组枚举)留在 A,**不**纳入归一。 +- `open_manual_upload` 作为「聊天/通知级手工上传入口」在 `derive_available_actions` 仍保留(它本就是另一层 + 展示别名),只是**不得再覆盖 `mark_manual_uploaded` 的原始码**。 +- 写契约(`request_gate_action`)仍只认 `mark_manual_uploaded` 等 `PROCESS_GATE_ACTION_CODES`; + 前端从 A 读到的动作码必须能与写契约对齐(归一的直接目的)。 + + + +### 两个展示 bug 的契约修法 +- **「当前门禁 —」**:`resolveShippingProcessingStageLabel('')` 返回 `'—'`(`shippingProcessingLabels.ts:150`), + 当 `currentProcessingStageDisplay` 因投影 `stage/ui_state.lifecycle_stage` 均空(且 `!loading`)返回空时触发。 + **修法**:已知正式 OT 必有阶段,投影恒有 `stage/lifecycle_stage`;投影未就绪由右卡 `:loading` + (`formalTaskProjectionPending`/`formalTaskDetailLoading`/`caseSwitchLoading`)驱动骨架占位,**禁止**落 `'—'`。 +- **「状态待确认」**:`resolveShippingProcessingStatusLabel` 不认识码时的兜底(`labels.ts:69`), + 仅被 `ReviewProcessDetailDrawer` 消费(读 `projection.status`)。右卡空态用的是 `statusIdle`(待机)、 + 表格行数用 `'待确认'`——**三套词汇**。**修法**:状态统一从 `shippingProcessingProjection.ui_state.status` + (受控 6 值)取,禁止给投影塞不受控码;`resolveShippingProcessingStatusLabel` 仅作不受控码兜底。 + +--- + +## 3. 按钮契约:任务级 vs 明细级 + +### 3.1 动作面(~36 个)与作用域 +`PROCESS_GATE_ACTION_CODES`(`process_gate_contract.py:349`)∪ `STAGE_CAPABILITY_DEFINITIONS` +(`process_gate_contract.py:1313`)。**只有 2 个是明细级**: + +| 动作码 | 作用域 | 宿主 | 位置 | +|---|---|---|---| +| `override_line_inventory_source` | **明细级** | `_handle_override_line_inventory_source`(`process_gate_executor.py:885`) | 库存表格逐行(override 下拉) | +| `select_line_inventory_source` | **明细级(已死,待删)** | 旧 D5 多文件冲突逐行选源 | 仅剩 `LINE_SCOPE_INVENTORY_ACTIONS` 名字,待删 | +| 其余全部 | **任务级** | 右「当前任务」卡 | 主按钮 + 恢复按钮 | + +前端唯一判据:`LINE_SCOPE_INVENTORY_ACTIONS = {override_line_inventory_source, select_line_inventory_source}` +(`ShippingOrderReviewView.vue:753`)。凡在此集合内的动作一律不进任务级按钮(右卡主按钮 `:762`、 +恢复按钮 `:862` 均排除)。 + +### 3.2 步骤/状态 → 动作(按 Gate 阻断归属) +主动作唯一裁决:`_resolve_recovery_next_action`(`process_gate_projection.py:130`);侧路: +`gate_side_recovery_actions`(`process_gate_contract.py:494`)。二者与校验层 `request_gate_action` +的 `allowed_side` **共用同一份裁决**(保证「投影放行==校验放行」)。 + +| Gate 阻断 | 主动作 | 侧路 | +|---|---|---| +| `inventory_preparation` blocked_manual/retryable | `retry_inventory_preparation` | — | +| `inventory_preparation` waiting_external | `poll_inventory_preparation` | — | +| `inventory_preparation` RPA 超时/耗尽 | `retry_inventory_matching`(复用快照重匹配,无则 RPA) | `retry_inventory_preparation` | +| `inventory_sufficiency` 正式 OT+已确认库存 | `retry_inventory_matching` | — | +| `inventory_sufficiency` 正式 OT+无确认库存(短缺) | `open_shortage_review` | — | +| `inventory_matching`/`inventory_sufficiency` 建单前 | `open_inventory_match_review`/`open_shortage_review` | `select_line_inventory_source`(多文件冲突) | +| `freight_upload_rpa` 失败 | `retry_freight_upload_rpa` | — | +| `manual_upload_handoff` | `mark_manual_uploaded` | `retry_freight_upload_rpa` | + +**任务级常驻能力**(通知准备,`_stage_capabilities_for_task` `ui_state.py:603`): +`retry_inventory_preparation`(有候选/失败源)、`reload_inventory_result`(有已解析源)、 +`retry_inventory_matching`(有匹配结果)、`override_line_inventory_source`(有候选源,明细级)。 + +### 3.3 三库存动作去重结论(已按用户拍板合并为 2 个按钮) +| 动作 | 做什么 | 跑 RPA | 失效范围 | 触发状态 | +|---|---|---|---|---| +| `retry_inventory_preparation` | 直接触发库存 RPA/抓取 | ✅ | 重抓后全链 | 库存准备失败 / 显式重抓 | +| `retry_inventory_matching`(**合并动作**) | 优先复用已有快照并重匹配;**无快照则回退 RPA** | 视情况(无快照时) | 匹配+充足性+Excel+产物 | 库存匹配/充足性 + 库存准备 RPA 超时/耗尽 | + +**`reload_inventory_result` 已下线(不再独立成按钮)**:其「复用已有快照」行为并入 `retry_inventory_matching` +(`match_inventory` 内部在无库存行时经 `ensure_inventory` 自动回退 RPA,见 `fulfillment_workflow.match_inventory:1611-1616`)。 +原 `inventory_preparation` 主恢复从 `reload_inventory_result` 改为 `retry_inventory_matching`(`process_gate_contract.inventory_preparation_primary_action`), +侧路保留 `retry_inventory_preparation`(强制重抓)。**动作码 `reload_inventory_result` 在写契约仍有效**(防历史/内部调用运行时 400), +但从用户按钮面下线展示。已同步 `gate_side_recovery_actions`/`action_belongs_to_gate`/前端 action presentation 与相关测试。 + +### 3.4 明细级按钮的数据源(§0 一句话结论的展开) +通知准备表格**每行**的明细级按钮(库存放行、关闭不可履约、行级重抓/重匹配、下载库存)由 +`ui_state.stage_context.preparation.lines[].{line_allowed_actions, inventory_allowed_actions, inventory_file_no, +release_required_fields, release_field_resolution_error, decision}` 驱动,**后端必须下发**到该数组。 +前端对应门禁:`formalPreparationLineAllows(line, action)`(`ShippingOrderReviewView.vue:2571`): +- `close_unfulfillable` / `release_inventory_shortage` → `line_allowed_actions.includes(action)` 且 + `release_inventory_shortage` 需 `!release_field_resolution_error`; +- `retry_inventory_preparation` / `retry_inventory_matching` → `inventory_allowed_actions.includes(action)`; +- 下载库存 → `inventory_file_no` 非空(`downloadFormalPreparationLineInventoryFile` `:2647`)。 + +> ~~**当前 BUG**:后端 `_build_stage_context` 生成 `preparation.lines[]`(`ui_state.py:837-862`)**未输出** +> 上述 `*_allowed_actions`/`inventory_file_no`/`release_*`/`decision` 字段(它们只存在于 Case 快照 +> `line_fulfillment.lines[]`,见 `order_review_fulfillment_decision_service.py:956-973`、`line_inventory_match_projection.py:667-694`), +> 导致 `formalPreparationLineAllows` 恒 false、明细级按钮全部不渲染。~~ +> **已修复(§1.5)**:`_build_stage_context` 现已在行循环内用内存 `match_row` 事实调用纯函数 +> `project_line_inventory_view` 下发 `line_allowed_actions`/`inventory_allowed_actions`/`inventory_file_no`/ +> `user_line_status`/`is_shortage` 等(零逐行 SQL,见 §6 落地清单)。`release_required_fields`/ +> `release_field_resolution_error`/`decision` 当前为 fail-closed 默认(`[]`/`null`/`null`)。 + +--- + +## 4. 前后端如何配合(冻结) + +1. **后端只读投影**:A(`shippingProcessingProjection`+`ui_state`)是唯一**展示+动作**合同; + C(`process_gate`)是唯一**写**裁决(`execution_no/evaluation_version/recovery_targets`); + B/D 只提供**工作面**事实。三者同一派生事实源,后端负责让它们同源不漂移。 +2. **前端轮询**:`startWorkflowProgressPolling`(`PROGRESS_POLL_MS`)→ `refreshShippingProcessing` + → `shippingProcessingProjection`(按 `progress_version` 单调合并)→ 刷新右卡 + 5 阶段页签; + 必要时再 `loadFormalTaskDetail` 拉工作面事实。 +3. **前端职责**:不用 `formalTaskDetail.ui_state` 推展示/动作;右卡与页签只用 A 的 `uiState`, + 工作面表格/编辑窗只用 B 的 `stage_context.preparation`。不自行推导阶段/按钮;`stage` 码不与 + `lifecycle_stage` 混淆。 + +--- + +## 5. 效能约束(必须遵守,与功能契约同权) + +> 核心:展示与按钮单源收敛**不得**以新增查询 / 渲染热路径为代价。`stage_context.preparation` +> 仍**只在任务详情**下发,不进轮询 / 轻量投影。 + +1. **明细级按钮零 N+1(§3.4)**:`_build_stage_context`(`ui_state.py:735`)已把该任务 + `ShippingNoticeLineInventoryMatch(is_current=True)` 全量加载进内存并建好 `match_by_snapshot_line_id`。 + `preparation.lines[]` 逐行的 `line_allowed_actions / inventory_allowed_actions / inventory_file_no / + release_required_fields / release_field_resolution_error / decision` 必须**在同一个循环内**、 + 复用上述**已加载内存事实**结算(调用 `line_inventory_match_projection.resolve_*_allowed_actions` + 等纯函数),**禁止逐行 SQL / 逐行调用重序列化器**。复杂度保持 O(行数)。 +2. **`stage_context.preparation` 只进任务详情**:不得下放到 `shippingProcessingProjection`(work-item / + 轮询 / 轻量投影),避免 N+1 与轮询膨胀。该限制已有(见 `technical.md`),本次收紧为契约级。 +3. **flatten C 复用单次 `project_user_gate_summary`**:A(`_order_task_current_gate`)与 B + (`_process_gate_user_summary_for_task`)必须**复用同一份 C 结果**,不得各自再调用 / 再推导 + `primary_action / blocking_reason / next_action`,保证单个 work-item 只调用一次、净减重复推导。 +4. **poll 热路径不变**:轮询 `PROGRESS_POLL_MS`(当前 `5000`,`useShippingOrderReview.ts:86`)与 + `refreshShippingProcessing()` 的调用序列**不因本次收敛改变**;前端读 A 只改读序、不增请求。 + (顺带修正过期的「2.5s/3s」注释为实际 `5000`。) +5. **验收护栏**: + - 改前 / 改后对 `GET /shipping-tasks/`(含 `stage_context`)做 SQL 查询次数对比,确认 + **不随行数线性增加**(加 `assert_num_queries` 类测试,或手工 `EXPLAIN` 对比)。 + - 确认单个 work-item 的 `project_user_gate_summary` 调用次数不变(仍 1 次)。 + +--- + +## 6. 落地清单(去冗余,不新增抽象) + +- [ ] 前端:`lifecycleUiState`(`ShippingOrderReviewView.vue:267`)优先读 `shippingProcessingProjection.ui_state`, + 删除对 `formalTaskDetail.ui_state` 的优先读取(保留 `reviewRun/reviewQueue` 作建单前降级),页签+右卡同源。 + **前置 = §2.5 后端归一**:A 与 B 的 `lifecycle_stage` 同码,但 `entries`/`blocker` 形状不同(A 的 + `lifecycleEntries`/`blocking_reason` vs B 的 `lifecycle_entries`/`reason.message`)。把 `lifecycleUiState` + 改为读 A-first 会因形状差异破坏 14 个 spec。**先按 §2.5 把 A 的 `blocker`/`entries` 归一成 B 口径,再切前端**; + 否则只在 stage 码上同源,entry/blocker 仍需 B 的面工件事实。 +- [x] 前端:右卡 `currentTaskPrimaryAction`/`currentTaskRecoveryActions`(`:758/:840`)只用 + `shippingProcessingProjection.ui_state` 取动作(不再读 `formalTaskDetail.ui_state.actions`);恢复动作 = + `ui_state.secondary_actions` + 任务级 `stage_context.preparation.capabilities`,按 code 去重、剔除明细级。 + (已验证:`ShippingOrderReviewView.spec.ts` 103 全绿;注意主动作/恢复动作的 i18nKey 必须统一映射到 + `workspace.shippingNotice.processGate.actionCodes.` 卡片域,否则右卡因 `businessActionLabel` 为空 fail-closed。) +- [x] 前端:删除 `formalTaskActions`(`:746`)对右卡的依赖(仅保留 `manualUploadRegistrationAuthorized` 等 + 真正正式动作使用方)。**`manualUploadRegistrationAuthorized` 已收敛到 A**(§2.5 差异① 归一后, + A 的 `secondary_actions`/`primary_action` 透传原始 `mark_manual_uploaded`);读 A 后与写契约码一致。 + 已验证 `ShippingOrderReviewView.spec.ts` 103/103 全绿。 +- [x] 前端:把「当前门禁」`--` 收敛为「投影未就绪 → 骨架占位」,禁止空阶段落 `'—'`。 + (已完成:`resolveShippingProcessingStageLabel` 空 stage 不再返回 `'—'`,改为 `stageLoading` 占位文案; + `ShippingOrderReviewView.spec.ts:4029` 断言同步迁移。已验证 103/103 前端全绿。) +- [x] 前端:`LINE_SCOPE_INVENTORY_ACTIONS`(`:753`)只保留 `override_line_inventory_source`(已删 `select_line_inventory_source`)。 +- [x] **后端(明细级按钮,按 §5.1 零 N+1 实现)**:`_build_stage_context`(`ui_state.py:780-862`)让 + `preparation.lines[]` 携带 `line_allowed_actions`/`inventory_allowed_actions`/`inventory_file_no`/ + `release_required_fields`/`release_field_resolution_error`/`decision`。限定:在现有 + `current_match_rows` 循环内**复用内存事实**结算,**禁止**逐行 SQL / 复用 Case `line_fulfillment` 重序列化器。 + (已实施 + 验证,见下方 §1.5 条目详情。) +- [x] 后端:删除 `select_line_inventory_source`(已完成)。已被 `override_line_inventory_source` + 取代(方案 3·放开:任一启用源 + 行级重匹配,覆盖多文件冲突行)。已删: + `process_gate_contract.py`(`PROCESS_GATE_ACTION_CODES` / `gate_side_recovery_actions` D5 分支 / + `action_belongs_to_gate` 校验)、`process_gate_executor.py`(dispatch + `_handle_select_line_inventory_source`)、 + `process_gate_service.py`(并发行级动作集合)、`error_explainability_contract.py`(`inventory_multi_file_conflict` + meta 的 next_action 改为 `override_line_inventory_source`)、`tests/test_shipping_select_line_source.py`(整文件删除)。 + 前端同批移除:`ShippingProcessingActionIntent` 类型成员 + D5 注释改指 `override_line_inventory_source`。 +- [x] 后端:确认 `apply_user_projection_fields` 的 `primary_action/blocking_reason` 与 C 同源(复用 C 裁决, + 不再二次推导),消除批次卡/右卡漂移。**已实施 + 验证**(`test_shipping_projection_gate_equivalence.py` 现 10 用例全绿): + - 在 `processing_projection_invariants.py` `apply_user_projection_fields` 末尾新增 **STEP8 条件化消费 C**: + `payload['process_gate']` 存在时 `primary_action.code/blocking_reason.code` 取 C 规范码 + C i18n + (去 D1 `regenerate_excel` 别名、去 D2 `technical_failure_present` 坍缩);无 C 时保留现有推导(Intake/min 投影路径)。 + - `user_status`(六值展示分组枚举)是 A 独有,C/B 不产出,**不纳入 flatten**。 + - 等价性证明 A==B==C:A↔C(primary_action/blocking_reason)+ B↔C(actions primary=next_action、 + primary+secondary 并集=allowed_actions),覆盖 `inventory_sufficiency`/`inventory_preparation`/ + `artifact_generation`/`freight_upload_rpa` 四 Gate。 + - **不可单独上线**的注意事项依旧:须与前端右卡仅读 A(§2.4)同批,否则右卡/对话流/批次进度中心会出现新漂移。 +- [x] **后端(明细级按钮,§1.5 零 N+1 已实施 + 验证)**:`_build_stage_context`(`ui_state.py`)让 + `preparation.lines[]` 携带 `line_allowed_actions`/`inventory_allowed_actions`/`inventory_file_no`/ + `user_line_status`/`is_shortage`/`inventory_status`/`match_result`/`retryable`/`inventory_source` 等。 + 实现:在行循环内用**已加载的 `match_row` 内存列 + `detail_json`** 拼 fact,调用纯函数 + `project_line_inventory_view` 结算,零逐行 SQL、不复用 Case `line_fulfillment` 重序列化器。 + `release_required_fields`/`release_field_resolution_error`/`decision` 当前为 fail-closed 默认 + (`[]`/`null`/`null`),避免为 release 补录字段引入逐行快照/模板/字段重查询(§5.1 禁止);后续独立路径解析后再覆盖。 + N+1 守门:`test_preparation_line_allowed_actions_are_zero_n_plus_one`(6 行恒定数量级)。 +- [x] i18n:四语言到齐,区分三库存动作文案。 + (已完成:`workspace.json` 四语言 `actionCodes.*` 已区分 + `retry_inventory_preparation`(重试库存准备/Retry inventory preparation/ลองเตรียมสต็อกใหม่)、 + `retry_inventory_matching`(重试库存匹配/Retry inventory matching/ลองจับคู่สต็อกอีกครั้ง)、 + `reload_inventory_result`(重新读取库存结果/Reload inventory result/อ่านผลสต็อกอีกครั้ง)。 + 并删除已下线动作的 4 语言残留键 `select_line_inventory_source`。JSON 校验通过 + 前端 376 用例全绿。) 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 6e800da2..62d8329f 100644 --- a/docs/features/shipping-notice/order-extraction-workflow-dify-guide.md +++ b/docs/features/shipping-notice/order-extraction-workflow-dify-guide.md @@ -259,7 +259,7 @@ ROUTE_DETECT_MODE.mode == "review" | --- | --- | ---: | --- | | `field_code` | String/Null | 否 | 可读字段编码,不作为身份真相 | | `field_id` | String | 是 | 冻结 Schema 稳定字段 ID | -| `line_key` | String/Null | 条件必填 | `scope=line` 时必须为非空字符串 | +| `draft_line_id` | String/Null | 条件必填 | `scope=line` 时必须为非空草稿行身份 | | `line_number` | Integer/Null | 否 | 可选显示行号 | | `scope` | String | 是 | 仅允许 `header` 或 `line` | @@ -296,8 +296,8 @@ def main(query: str, review_llm_contract: str = "") -> dict: raise ValueError("FIELD_ID_REQUIRED") if target.get("scope") not in ("header", "line"): raise ValueError("INVALID_SCOPE") - if target.get("scope") == "line" and not str(target.get("line_key") or "").strip(): - raise ValueError("LINE_KEY_REQUIRED") + if target.get("scope") == "line" and not str(target.get("draft_line_id") or "").strip(): + raise ValueError("DRAFT_LINE_ID_REQUIRED") if request.get("evidence_level") not in LEVELS: raise ValueError("INVALID_EVIDENCE_LEVEL") pack = request.get("evidence_pack") @@ -458,7 +458,7 @@ System Prompt: 规则: 1. field_id、scope 和 line_number 必须与 target_field_json 完全一致。 -2. line 字段只能处理目标 line_key 所对应的证据,不得串行。 +2. line 字段只能处理目标 draft_line_id 所对应的证据,不得串行。 3. suggested_value 必须能在该字段证据中逐字证明;quote 必须是证据中的逐字短引文。 4. 不得翻译、改写、格式化、补零、推算、合并或猜测字段值。 5. confidence 只是建议强度,不能替代逐字证据。 @@ -1080,7 +1080,7 @@ Dify 节点级错误使用 Fail Branch;画布不配置循环、自动重试或 | R01 | 合法 L1 单字段证据 | REVIEW | 返回一个建议或空建议 JSON | | R02 | 合法 L2/L3 请求 | REVIEW | 只使用命中表/页的最小证据 | | R03 | 两个 target_fields | REVIEW | `INVALID_REQUEST`,不调用 LLM | -| R04 | line 字段无 line_key | REVIEW | `INVALID_REQUEST` | +| R04 | line 字段无 draft_line_id | REVIEW | `INVALID_REQUEST` | | R05 | 模型返回非 JSON或错 field_id | REVIEW | `INVALID_MODEL_OUTPUT` | | R06 | 模型值不在字段证据中 | REVIEW | 后端 `validation_failed`,不能接受或修改 | | R07 | Dify 超时/不可用 | REVIEW | 后端 `provider_unavailable`,人工复核不中断 | diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index acba73d0..e9664284 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -37,9 +37,15 @@ - `serialize_lifecycle_progress()` 只复用既有 Run、Unit、workspace Progress Event 与健康提示,输出 `lifecycle_stage`、当前/已完成步骤、最后活动、健康和稳定提示键;不新建事件表、SSE/WebSocket、队列或状态机。`layout_parsing_completed` 等完成型 event code 即使为兼容实时实体状态记录为 `running`,也必须作为已完成步骤。 - `serialize_review_run()` 只读取轻量进度,禁止为首屏进度加载完整 documents、candidates 或 `handling_items`。有正式 Task/Case 生命周期投影时,工作台继续以现有 `ui_state/lifecycle_entries` 为权威,Run 进度只覆盖解析尚未产生 Case 的窗口。 -- 页面在标题下使用既有五阶段导航加一行紧凑当前步骤提示;失败、取消、排队和健康阈值提示显示稳定原因文案,禁止暴露 Worker/Provider 错误正文。不得新增独立状态卡或占整行黄色横幅。 +- (2026-08-31 v2 收口)五阶段导航下方不再渲染常驻进度横幅;Run 级动态说明由右栏 `ReviewCurrentProcessingCard` 状态块内嵌承载(仅 `lifecycle_status ∈ {running, waiting, failed, cancelled}` 白名单;无 Case 瞬态才在导航下保留单行轻提示),失败、取消、排队和健康阈值提示显示稳定原因文案,禁止暴露 Worker/Provider 错误正文。不得新增独立状态卡或占整行黄色横幅。 - 重新解析、解析重试、库存/RPA/Excel 等已启动异步任务,以及“重新识别客户”后门禁通过并由后端启动自动推进,都在轮询刷新中复用同一投影;只打开客户选择、确认客户或其他同步人工操作时不显示伪造自动进度。门禁未通过仅显示后端阻断原因。 +### 状态展示统一与动态说明(2026-08-31) + +- 前端展示口径收口:`shippingProcessingLabels.ts` 新增 `resolveRunLifecycleUserStatus`(`RUN_STATUS_FALLBACK_MAP`:review_required→waiting_human,queue_backlog/processing_slow/processing_attention→running;原因码只能补充/细化用户态,不能覆盖 failed/cancelled/completed)与 `resolveExtractionActivityMessage`(白名单 {running, waiting, failed, cancelled};仅 running 可声称自动处理,诊断原因优先于步骤句;failed/cancelled 强制原因 key,禁止复用 step 文案)。`currentTaskUserStatus` 既有链(正式 OT ui_state → Case automation)末尾追加 Run 级兑底;completed/cancelled/未知不映射。 +- 动态说明内嵌在「当前任务」卡状态行下方(弱文本一行);仅 `REDUNDANT_DETAIL_REASON_CODES`(当前仅 review_required)且映射结果等于当前状态时隐藏,排队/偏慢/需关注等诊断信息一律保留;未知原因默认保留;不做字符串匹配、不做模糊关键词判断。 +- `current_activity`(聊天页/任务中心消费的文件级快照)与 `lifecycle_progress`(工作台五阶段投影)保持后端双投影不变;聊天页与任务中心的阶段 key 改走 `resolveOrderExtractionRunStageKey` 唯一出口,文案仍为 `shippingOrderExtractionUserStage.*`/`shippingOrderExtractionCardTitle.*`,视觉零变化。设计详见 `docs/superpowers/specs/2026-08-31-shipping-review-status-display-unification-design.md`。 + ### 本次 Dify 手工核对(管理员执行) 本次无需新增 Dify 节点、变量、Prompt 或 Tool,也无需让 Dify 输出进度。管理员只需在发布前核对:`shipping_notice` Chatflow 未订阅 Run/Unit/ProgressEvent、未根据模型判断输出阶段或完成状态、仅保留只读 `get_task_status`(如启用)及隔离的最小 Review 建议分支;任何订单解析、门禁推进、客户确认、库存、Excel、RPA、人工上传确认或写入 Tool 均必须禁用。Dify 不可用不能阻断本次五阶段进度展示或订单主链。 @@ -53,6 +59,7 @@ - 原 PDF 是不可变源事实。`ensure_on_demand_coordinate_evidence()` 是唯一坐标补全入口:当前 Layout -> Run 快照补缺 -> 原生 PDF -> OCR;返回合并后的当前 Layout。任一关键坐标无法取得时固定输出 `coordinate_evidence_unavailable` 并进入 `review_required`。 - **Reservation ID 专区动态锚点(2026-08-25)**:仅当已选中模板定义了 `reservation_id_region` 时启用。该配置不再以保存时的 `page_no/region` 作为正式取值位置,而是补齐全文页面坐标证据后,按阅读顺序从首次 `Vendor Comments` 标题之后累计到首次 `Terms and Condition` / `Terms and Conditions` 标题之前;区块可跨页。只在此封闭区块内解析带 `Reservation` 标签的合法 5/10 位数字,并复用既有行号归属和冲突规则。缺失任一起止锚点、边界顺序异常或值冲突均固定进入 Review,禁止自动猜测;未定义该专区的模板不扫描全文,原解析行为不变。 - `matching_features.v1` 在压缩 `page_glyphs` 前持久化页面结构、主表框、表头及顺序、列数/中心/宽度和静态字段关系。它是稳定匹配输入,不升级命名;缺少关键特征不得从评分分母剔除后形成 `hard_match`。 +- **坐标证据外置为 FileAsset(2026-08-26/30 决策)**:`coordinate_evidence` 不再内联在布局快照的 `payload_json` 中。`record_inline_layout_snapshot` / `complete_layout_version` 在证据含非空 `page_glyphs`/`tables` 时,将其外置为派生 `FileAsset`(`asset_role=layout_coordinate_evidence`、`application/json+gzip`),从 payload 移除 `coordinate_evidence` 并写入轻量 `coordinate_evidence_ref`(`{asset_no, checksum, size, schema_version}`)。PDF 布局仅当 `coordinate_evidence_ref.asset_no` 存在时才视为 ready:否则 `complete_layout_version` 回退 `failed` 并写入 `shipping_document_layout_coordinate_evidence_incomplete`;仅当外置资产持久化失败时才写入 `shipping_document_layout_coordinate_evidence_persist_failed`。读取侧 `current_layout_snapshot()` 经 `_hydrate_coordinate_evidence` 从该资产回填 `coordinate_evidence`;`ensure_on_demand_coordinate_evidence()` 是唯一坐标补全入口,优先使用当前 Layout(坐标来自外置资产 hydration),缺页再从原 PDF 原生字形/OCR 补齐。原 PDF 始终是不可变源事实。 - Profile 只识别版式身份;Schema 是唯一业务字段契约。订单头由 `page_glyphs + Profile field layout + Schema` 取值,订单行由 `table_glyphs + Profile table layout + Schema` 重建;两者共享同一个 Profile、Layout、Schema 和 `CoordinateTransform`。 - `CoordinateTransform` 统一处理归一化坐标及受限平移、缩放、小角度旋转。锚点不足、残差超限、越界、共线、非法矩阵或局部非线性失真必须 fail-closed,禁止强行命中。 - **参考页坐标帧(2026-08-25)**:编辑器继续保存 0..1 的画布区域,但坐标模板保存时必须从 annotation sample 的冻结 `coordinate_evidence.pages` 写入每页 `CropBox` 点尺寸。盲测与正式解析先以“相对区域 × 标注页点尺寸”恢复 PDF 点框,再读取当前页的同一物理点框;不得直接按当前页高度重投影。该规则覆盖“分页页与未分页长页内容位置相同”的场景,不需要复制模板;缺少参考页框的历史模板保持兼容旧投影,重新保存标注样本后才获得新契约。真实整体缩放/平移仍只允许由显式 `anchor_frame` 的稳定文档匹配锚点处理,禁止以订单字段在运行时拟合。 @@ -637,6 +644,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open - **并发与幂等**:服务端快照计算 idempotency key;相同输入返回同一 Run;同一 Intake 同时只允许一个活动 Run。 - **失败 Run 手工重试**:用户在订单识别失败卡片点击“重试失败附件”,调用 `POST /api/workspace/shipping-notice/order-extraction-runs/{run_no}/retry`。仅 `failed` 可重试;复用原 Run、冻结附件/正文、Schema、解析器/策略版本和 Intake 关系,不要求重新上传,也不创建新 Run。 - **重新识别版本链**:终态且未消费的 Run 可调用 `POST /api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse` 创建新的 Run,原因仅允许 `rule_updated/field_mapping_error/document_quality/other`。新版重新冻结当前已发布的 Schema、Profile、解析器/策略和当前 ready 布局快照,不复用旧单元结果;仅当前版本 Candidate 可建单,旧版永远保留审计。 +- **重解析终态闭环不变式(2026-08-30)**:PDF 级重解析后继 Run 收口时业务必须二选一 —— 新版 Case 已上位 Stream,或旧版 Case 已恢复为可编辑状态;新版缺失或激活被拒时转入既有失败恢复链(`finalize_document_reparse`),禁止旧 Case 停留在 `reparse_pending` 被孤儿化。前端配套:重解析完成后工作台落在历史版本时自动跳转 Stream 当前版本(版本历史面板显式查看除外),跳转失败必有可见报错。 - **变更边界**:Run 冻结解析器版本、策略版本、超时和最大尝试次数;运行时版本漂移安全阻断旧 Run。用户态 Run API 不返回正文、解析快照、原始结果或内部配置。 ### 2026-07-21 文档级抽取优化历史阶段与 Review 门禁 @@ -765,9 +773,9 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open ### 阶段 3 客户指纹绑定与冻结(2026-07-22) -- `ShippingOrderCustomerMatch` 为 Bill-to/Ship-to 分别保存订单原文、标准化组件、`order-customer-fingerprint.v1`、候选快照及确认审计;客户主数据不覆盖订单原文。 -- Bill-to 作为正式订购客户。人工确认必须指定启用客户并填写理由;Ship-to 仍可独立匹配站点,但不替代订购客户。影子识别仅用于质量评测,不能直接冻结。 -- `freeze_order_snapshot` 不再接受请求任意传入的客户 ID/简码,只读取当前 Extraction 已确认 Bill-to;Snapshot 同时保存客户 ID、简码和匹配规则快照。客户后续变更不回写已冻结 Snapshot。 +- 动态订单字段保存 Bill-to/Ship-to 原文及地址、编码等可识别证据;`ShippingCustomerShadowResolution` 保存已发布 Identity Rule Set 的证据、候选和确认审计。客户主数据不覆盖订单原文。 +- Bill-to/Ship-to 不表示正式客户角色。人工确认必须指定启用客户;唯一候选仅在自动确认门禁满足时写入 Resolution。客户确认是 Resolution 的独立事实。 +- `freeze_order_snapshot` 不接受请求任意传入的客户 ID/简码,只读取当前 OT 的已确认 Resolution;Snapshot 同时保存客户 ID、简码和 Rule Set 确认快照。客户后续变更不回写已冻结 Snapshot。 - 阶段 3 Dify 手工配置:无需修改画布。客户指纹、候选排序、确认理由与 Snapshot 冻结均由 HXOPS 执行;Dify 不返回 customer_id、客户简码或匹配结论。 **L7 第 4 阶段工程补充验收(2026-07-22)**:人工编辑 Candidate 的业务摘要时,系统在 `structured_result_json.manual_review_history` 追加编辑前摘要、冲突、校验状态、编辑人和编辑时间,避免“修订后清空冲突”丢失审计。自动建单 Binding 和每次 Run 均冻结 `quality_batch_id`;创建 Run 与 Worker 开始执行时都重新校验该批次的 Owner、Schema、阈值和双人批准状态。`auto_create_enabled=true` 的生产 Run 禁止作为影子质量标签样本,防止用生产结果反向证明质量。该子阶段历史 head 为 `a77f8091a2c3`;当前部署还必须继续执行 Snapshot、质量、客户指纹、滚动履约和 Attempt 迁移至 `023a4b5c6d7e`。阶段回归为 `129 passed`,迁移往返和 `git diff --check` 通过。 @@ -966,7 +974,7 @@ MinerU 服务地址、无认证方式和 OpenAPI 已确认,并已取得脱敏 **表头污染与坐标重建 Review(2026-07-22)**:若样本表头混入明显订单行值(例如 `ITEM NO 00010`),预览返回稳定诊断 `order_profile_header_contaminated_by_data` 并标记不可建 Profile;服务端也拒绝从该表创建草稿,避免浏览器绕过。Profile 页面不是手工修复原始网格的入口。对有 PDF 原生 glyph 坐标且已人工确认列锚点的文档,`coordinate_table_reconstruction` 仅输出 `needs_review` 候选:以 x-overlap/唯一中心距离归属列,以字体高度自适应 y-band 判断新视觉行,内容形态与相邻行连续性只作辅助;无强行号的行只能是续行或复核,`** Item deleted **` 只能附着前一强锚定明细。候选保留 glyph 索引,坐标不足、列归属并列或删除行无前序明细时一律复核,绝不自动接受、发布 Profile 或进入履约。 **模板版本中心契约 Review(2026-07-28)**:订单模板管理入口升级为按 `profile_code` 聚合的版本中心。`draft / published / retired` 仍是唯一生命周期,但“查看版本”和“创建新版本”分离:查看任意 `published/retired` 版本只进入独立详情路由 `/admin/shipping-order-document-profiles/:profileCode/versions/:version`,不得隐式创建草稿。默认版本选择顺序固定为 `published -> draft -> 最新 retired`;URL 指定不存在版本时必须返回 404,不允许前端或后端自动改跳其他版本。版本详情固定包含 `配置概览 / 样本画布 / 版本差异 / 审计记录 / 实际使用` 五个页签,其中配置概览优先加载,PDF 画布、审计、使用情况按页签懒加载。 -**历史画布与盲测隔离 Review(2026-07-28)**:历史样本画布必须显式区分 `edit` 与 `readonly` 两种模式,不能靠隐藏保存按钮伪装只读。`published/retired` 详情只允许切换样本、翻页、缩放、查看区域详情和复制为新草稿,禁止新建/拖拽/删除区域、重绑字段、撤销重做、自动建议写入、保存、OCR 重跑及样本解除绑定。画布读取只能使用发布时冻结的 Sample 绑定、Layout 版本、文件 hash、Layout checksum、Schema checksum 和 Parser 身份;缺任一证据时明确失败,不允许回读当前最新布局。普通版本详情 DTO 只返回盲测套件状态、样本数量、通过/失败数量、批准时间和最近运行摘要,不返回 `expected_rows_json`、`expected_order_fields_json`、人工真值、可推导答案的坐标或未执行盲测 PDF 的完整身份。 +**历史画布与盲测隔离 Review(2026-07-28)**:历史样本画布必须显式区分 `edit` 与 `readonly` 两种模式,不能靠隐藏保存按钮伪装只读。`published/retired` 详情只允许切换样本、翻页、缩放、查看区域详情和复制为新草稿,禁止新建/拖拽/删除区域、重绑字段、撤销重做、自动建议写入、保存、OCR 重跑及样本解除绑定。画布读取只能使用发布时冻结的 Sample 绑定、Layout 版本、文件 hash、Layout checksum、Schema checksum 和 Parser 身份;冻结页数必须来自同一原 PDF 的完整物理页证据,不能退化为含业务表格的页数;缺任一证据或页数不一致时明确失败,不允许回读当前最新布局。普通版本详情 DTO 只返回盲测套件状态、样本数量、通过/失败数量、批准时间和最近运行摘要,不返回 `expected_rows_json`、`expected_order_fields_json`、人工真值、可推导答案的坐标或未执行盲测 PDF 的完整身份。 **模板版本语义差异 Review(2026-07-28)**:版本中心 `diff` 页签已落地,统一通过 `GET /api/admin/shipping-notice/order-document-profiles/{profile_id}/diff?against_profile_id={id}` 由服务端计算。未显式指定对比版本时默认上一版本;显式比较只允许同一 `profile_code`,跨模板立即阻断。差异引擎按 `region_id / layout_id / field_id / anchor_id` 等稳定身份配对,坐标矩形统一使用 `0.001` 容差过滤浮点噪声,避免字段改名、排除区重排或序列化精度造成“删除+新增”误判。前端仅展示结构化 summary、变更项和折叠的安全 JSON 快照,不直接比较整份 definition,更不暴露正文、对象存储地址或盲测真值。 @@ -1150,7 +1158,7 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 #### 产品与状态边界 - Run 是订单抽取的唯一业务真相;Job 仅代表一次执行尝试。Run 终态固定为 `completed / partially_completed / review_required / failed / cancelled`,其中 `review_required` 表示全部 PDF 都是业务拒识,`partially_completed` 表示成功与人工处理并存。 -- Unit 是 PDF 级处理单元,状态固定为 `pending / routing / matching_profile / extracting / merging_supplement / candidate_ready / review_required / failed / cancelled`;一份 PDF 的拒识或失败不得覆盖其他 PDF 已有结果。EML 父卡只汇总子 Unit:`review_required` 的 PDF 保留自身 Review Case/`open_order_review`,`failed` 的 PDF 只显示自身稳定错误码和 `retry_order_extraction`,不得以 Run 终态撤销兄弟附件入口。 +- Unit 是 PDF 级处理单元,状态固定为 `pending / routing / matching_profile / extracting / merging_supplement / candidate_ready / review_required / failed / cancelled`;一份 PDF 的拒识或失败不得覆盖其他 PDF 已有结果。EML 父卡只汇总子 Unit:`review_required` 的 PDF 保留自身 Review Case/`open_order_review`,`failed` 的 PDF 只显示自身稳定错误码和 `retry_order_extraction`,不得以 Run 终态撤销兄弟附件入口。**聊天摘要与批次进度中心均按 PDF 状态 → EML → PDF 展示**:混合状态 EML 在对应状态区各显示一张只读聚合卡,每张仅含本区 PDF,并标注“本组 x/共 y”;状态区标题计数统一为文件数,不得用 EML 总体状态或 EML 卡数把未完成附件混入“已完成”或显示为“任务”。 - **取消是请求语义,不是即时伪造终态**:Run/Unit 记录 `cancellation_requested_at / cancellation_actor_* / cancellation_reason* / cancellation_completed_at`;排队 Unit 可立即 `cancelled`,执行中 Unit 投影为用户可见阶段 `cancellation_requested`,Worker 仅在文件边界与外部副作用前安全点生效。已完成 Unit 结果保留。 - 同一 `user_id + owner_agent_id + conversation_id` 同时最多一个 `queued / processing` Run;不同会话可并行。现有 Intake 单活跃约束继续生效。 - 用户卡片只显示后端事实投影:Run 汇总、当前文件、当前业务动作、可操作按钮,以及按 PDF 打开的详情抽屉。用户端不再展示 Workflow、节点、Provider、LLM、伪百分比或内部运行标识。 @@ -1210,6 +1218,8 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 - 用户工作台主接口固定返回 `summary / current_activity / available_actions`;详情接口固定返回按 PDF 归并的 `documents[]`。所有计数、当前活动和按钮权限均由后端计算,前端不得自行猜测。 - 计数必须以 Unit 事实为准,禁止依赖可能滞后的批次摘要自行重算。 +- 会话级 `summary` 存在两个口径,前端必须分开消费:`summary.submitted_files`(提交基主计数,来自冻结 `attachment_selection.selected_attachment_count` + 直传 PDF Intake 数,物化前即 ≥1、单调,用于「共 N 个文件」与批次总文件数卡)与 `summary.total_files`(已识别/活跃文件数,基于物化 `ShippingOrderDocument` 裁决,用作完成率分母与 `_*_files` 状态明细)。物化前 `total_files` 可为 0,此时前端显示「正在识别附件…」占位,并在「共 N 个文件」标签内联显示「已识别 n / N」,不得把 `total_files` 当作主计数误报「0 个文件」。 +- EML 聚合卡的子文件列表必须包含冻结选择计划中**已选但尚未物化/未识别**的附件(`facts.recognized=false` 诊断行),否则「已识别 n / N」会出现「少了一份文件」的排查盲区;未识别 PDF 显示「待识别」,`.xls/.xlsx` 显示「已忽略(非订单 PDF,不参与订单识别)」并从其父 EML 的处理中/待人工等状态卡剥离,进入只读「已忽略」分区(聊天摘要和批次进度中心均默认折叠,展开后显示对应 Excel 叶子);两者都只进列表与 `submitted_files`,**不进** `total_files` / `_*_files` 状态数。顶部摘要只要存在已忽略附件,均须在既有“共 x 个文件 · 已识别 n/N”后附加“y 个已忽略”;批次进度中心概览须单列已忽略数,并保持完成率及“已处理 N/M”仅以 `total_files` 的订单文件为分母;若其余订单 PDF 均完成,即使会话 `ui_state.status` 尚未收口,聊天摘要卡也必须显示完成、隐藏当前阶段,并改用“订单文件 x 个已完成 · y 个已忽略”;该展示例外不回写、不改变后端状态。 - 事件必须是已经发生并持久化的事实,前端只根据 `event_code` / `user_visible_stage` 做 i18n 文案映射;不允许把 Dify 节点标题或自定义显示文本当作业务阶段。 #### 事件、健康与恢复 @@ -1390,7 +1400,7 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 - 客户合并使用源客户的 `merged_into_customer_id` 和快照审计表 `shipping_customer_merges`。`GET /api/admin/shipping-customers/{source_id}/merge-impact` 返回历史保留引用与可迁移配置;提交合并需目标客户、源简码二次确认和原因。合并事务只迁移 `shipping_customer_identifiers` 与 `shipping_customer_external_refs`,业务单、业务流水、导入行、影子候选和人工标签均保持原引用;源客户状态设为 `merged`,新选客与识别入口只接受 `active` 客户。 - 客户创建、编辑、启停、简码变更及识别证据创建/审核/停用/自动匹配授权均写入 `ShippingCustomerLifecycleEvent` 快照;简码、状态和自动匹配授权属于高风险变更,服务端强制要求 `reason`。管理员通过 `/lifecycle-timeline` 查询单客户时间线。 - 自动确认除 `SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED` 外,还须通过 `SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES`(默认 20)及 `SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY`(默认 0.98)门禁。统计分母仅包括当前强规则会唯一命中的已人工真值样本;未达标返回降级状态、不绑定客户、不生成业务号。`/governance-quality` 和影子报告均返回门禁状态及阈值快照。 -- 识别规则发布快照同时冻结订单 Schema 的 `id/version/checksum`。影子解析证据保存 `field_value_id/decision_id/extraction_id/context_field_id/order_schema_version_id`;自动确认时重新读取并校验 FieldValue、accepted/corroborated Decision、Extraction 与历史规则集/Schema 快照,按冻结字段规则重新标准化。影子 JSON、当前 Schema 或当前定义表均不能单独授权自动确认。 +- 识别规则发布快照同时冻结订单 Schema 的 `id/version/checksum`。影子解析证据保存 `field_value_id/decision_id/extraction_id/context_field_id/order_schema_version_id`;自动确认时重新读取并校验 FieldValue、accepted/corroborated Decision、Extraction 与历史规则集/Schema 快照,按冻结字段规则重新标准化。自动确认规则集自身仍按 `id/version/checksum` 强一致(防篡改);Schema 锚点则从「版本级强一致」放宽为「语义契约一致」——仅要求解析所用 Schema 版本真实存在(published/retired)且规则集冻结定义在新 Schema 中`field_code/scope/value_type/normalizer_key/available_for_customer_identity` 语义兼容,从而容忍 Schema 常规重发布造成的版本错位,但拒绝字段语义变化(此时自动确认 fail-closed 回人工复核)。影子 JSON、当前 Schema 或当前定义表均不能单独授权自动确认。 - 业务编号直接归属于 `ShippingNotice`,不再存在独立业务单聚合或 `ShippingCase`;一个 PO 可产生多个 Notice,每个 Notice 持有唯一 `business_no` 并只关联一个 Excel。 - 流水表按 `(business_type, customer_id, business_date)` 唯一,使用 PostgreSQL 原子 upsert/returning 分配,`business_no` 唯一约束提供最终保护。 @@ -1424,11 +1434,11 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 | 3 | 客户影子识别 | 只记录候选不阻断;真实历史样本形成准确率报告;误自动匹配为 0 | | 4 | 客户人工确认 Gate | 所有后续副作用入口均不可绕过;客户确认事件完整审计 | | 5 | 业务编号生成、查询和展示 | PostgreSQL 并发无重复;修订继承、强制新建重新编号;双号查询通过 | -| 6 | 有限自动识别、监控和纠错 | 仅已审核强规则自动放行;可降级;质量指标与纠错审计可查询 | +| 6 | 有限自动识别与监控 | 仅已审核强规则自动确认 OT 客户;可降级;质量指标可查询 | 每一阶段完成前必须执行本阶段代码 Review,按严重度列出全部发现、修复后重跑对应测试,并逐条核对验收标准;存在未处理高风险问题时不得进入下一阶段。 -阶段 6 的客户纠错仅限管理员:已编号且尚未上传货代的业务单保留原号并标记 `voided`,创建 `replaces_case_id` 指向原单的替代业务单并按正确客户申请新流水;任务版本链迁移到替代单,旧号查询跟随替代链返回当前版本,纠错原因与新旧编号写入 `ShippingTaskEvent`。已上传货代的任务必须先完成外部作废流程,系统内纠错接口明确阻断。 +阶段 6 的自动确认仅发生在 OT:满足已审核强规则、唯一命中及质量门禁时写入客户确认结果;不创建 Notice、不分配业务编号。正式 Notice 创建是客户不可变边界,创建后不提供客户替换或重建能力。 ### 第三阶段:业务去重与任务版本(实现摘要) @@ -1764,10 +1774,10 @@ GET /api/admin/shipping-order-schema/published-contract - **Crane 初始值**:`enabled=false`(提交按钮、成功提示或上传历史记录的稳定选择器尚未确认,仅有文件选择器不代表可安全自动提交),`entry_url=https://wms-portal.craneww.com/#/shipping-order-upload`,`file_input_selector=input[name="OrderFileUpload"]`,`submit_mode=click_submit`,`submit_selector=null`,`result_mode=page_notice`,`success_texts=[]`,`timeout_seconds=120`。管理员完成页面验证并补全提交/成功判定字段后才可 `enabled=true`。 - **不改版本号**:`upload_config_json` 变更不递增 `config_version`,避免库存 RPA 配置测试被误判过期;不维护 `upload_config_version`(无发布流、无并发编辑审批、无历史回放需求)。每个 trigger 固化本次 upload_config 快照即可保证“这次上传用了什么”;需要审计关联时对快照计算 `config_hash`(sha256)。 - **Worker 保留两个受控 Adapter**:`DsvUploadAdapter`(DSV 入口、文件选择与结果判定)与 `CraneUploadAdapter`(Crane 入口、文件选择、提交与结果判定),**不再根据环境变量拼接 DSV/Crane 页面动作**。用连接 `login_url` 登录后访问 `upload_config.entry_url` 进入上传页;`upload_config` 决定“该连接使用哪个已支持的受控流程及其页面参数”,浏览器动作与安全边界由代码负责;Worker 上传与最终提交的全局开关(`SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED` / `..._CONFIRM_SUBMIT`)仍作为部署级二次确认保留,但不再承载页面参数。 -- **执行链路**:用户触发批量 RPA 上传 → 后端创建 Upload Attempt → 读取任务已确定的系统连接及 `upload_config_json` → 复制发货 Excel 到共享上传队列 → 生成非空 `callback_id` → 原子写入 trigger(复用“临时文件 + fsync + os.replace”,携带 `schema_version / task_no / attempt_id / artifact_id / callback_id / connector_type / upload_config 快照 / upload_config_hash / login_url / credential_envelope`)→ Windows Worker 取 trigger → 按 `connector_type` 进入 DSV/Crane Adapter → 登录、打开 entry_url、选择 Excel、提交 → 以页面提示或上传历史证据判定 → 回调。 +- **执行链路**:用户触发批量 RPA 上传 → 后端创建 Upload Attempt → 读取任务已确定的系统连接及 `upload_config_json` → 复制发货 Excel 到共享上传队列 → 生成非空 `callback_id` → 原子写入 trigger(复用“临时文件 + fsync + os.replace”,携带 `schema_version / task_no / attempt_id / artifact_id / callback_id / connector_type / upload_config 快照 / upload_config_hash / login_url / credential_envelope`)→ Windows Worker 取 trigger → 按 `connector_type` 进入 DSV/Crane Adapter → 登录、打开 entry_url、选择 Excel、提交 → 以受控页面选择器判定 → 回调。 - **结果三态**:`success`(取得可核验成功证据)、`failed`(明确页面失败、浏览器错误、超时或回调失败)、`unknown`(已可能提交但无法确认外部系统结果)。`unknown` 必须转人工处理,禁止自动重试以避免重复上传;成功/失败/未知、页面证据摘要与脱敏错误写入现有 Upload Attempt 与货代审计事件。 -发布门禁:全局只有一个 published 版本;已发布版本不可编辑;字段首次发布后 `scope/value_type` 不可修改,`field_code` 重命名仅影响后续草稿,历史发布快照保留旧名称;证据来源、比较器、规范化器和校验器只能引用后端白名单。 +发布门禁:全局只有一个 published 版本;已发布版本不可编辑;字段首次发布后 `scope/value_type` 不可修改;**同一 field_id 的 `field_code` 一经发布不可变更**(改名 = 退役旧字段 + 新建字段,允许同一 `field_code` 漂移到新 `field_id`),历史发布快照保留旧名称;证据来源、比较器、规范化器和校验器只能引用后端白名单。 # 发货 Excel 模板 @@ -2832,18 +2842,16 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui ### STP 阶段 0:字段契约冻结(2026-07-30,项次派生 Phase 0 纠偏) - 标准资产 **58** 项;`shipping_order_fields` 唯一键为 `(field_code, scope)`,允许 Header/Line 同名 `reservation_id`。 -- 运行时投影:`line_key`、`effective_reservation_id = line.reservation_id ?? header.reservation_id`(经 `validated_reservation_id`);`line_no` 为可识别内部项次,不再由 `position+1` 覆盖。 -- `line_no` / `customer_po_line_no` 均在 `TABLE_FIELD_CODES`;可进入 LLM/坐标抽取。 -- Excel:废除 `system_fact:line_no`;导出行号为 `system_fact:export_sequence`(最终导出集上连续 1..N)。 -- Schema `definition_json.derivation_rules`(及 checksum):首期仅 `copy_if_empty`,目标仅 `line_no`;新草稿预置关闭规则 `customer_po_line_no → line_no`。 -- Snapshot 扩展约定:`rule_versions_json.derivation_rules_*`、`source_manifest_json.field_lineage`;审计事件词典见 `LINE_DERIVATION_AUDIT_EVENT_TYPES`。 +- 草稿行使用 `draft_line_id`;冻结档/库存准备使用 `snapshot_line_id` 与系统生成的 `line_no`;正式通知使用 `ShippingNoticeLine.line_no`。 +- `line_no` 不在 `TABLE_FIELD_CODES`,不进入 LLM/坐标抽取;`customer_po_line_no` 仍作为原始客户项次事实保留。 +- Excel 导出项次只读取 `ShippingNoticeLine.line_no`,每张通知单从 1 开始重新编号。 +- Schema 不提供派生规则;Snapshot 只保存字段来源血缘,不保存派生规则快照或校验和。 - 迁移:`4e7a1c9b2d3f_align_shipping_order_line_contract.py`(含内部项次语义纠偏);`5f8b2d4e6a1c_restore_shipping_context_field_assets.py`(恢复 `general_context` / `deterministic_context` 与 sender 种子)。 ### 项次派生 Phase 1–4(2026-07-30) -- **规则引擎**:`order_schema/derivation_engine.apply_derivation_rules_to_lines`;Admin `POST .../simulate-derivation` 写 `DERIVATION_SIMULATED`(路由层 commit);支持 `sample_ref=extraction:` 加载历史明细,以及 `GET .../derivation-simulate-samples`。 -- **运行时**:标准化后执行派生,写 `FIELD_DERIVED` / `FIELD_DERIVATION_SKIPPED`(含来源字段 `evidence_refs`),`normalized_result_json.field_lineage`;required 门禁在派生之后。 -- **复核覆盖**:`line_no` 须 `override_reason_code`;写入 `manual_override`+`locked` 与 `LINE_NO_OVERRIDDEN`;恢复清除锁定并写 `LINE_NO_RESTORED`(回退 machine_fields 识别/派生投影,不重跑引擎)。 +- **项次规则**:不再提供 Schema 派生、模拟、项次覆盖或恢复;订单解析/冻结/通知写路径分别按所属单据顺序生成不可变 `line_no`。 +- **字段血缘**:只保留原文字段来源与人工修改审计,不记录派生规则校验和。 - **复核投影**:`order_review_projection` 附加 `field_meta.value_source`;UI `ReviewLineNoOverrideDialog` + 来源徽章。 - **冻结与永久审计**:Snapshot 血缘快照;`append_shipping_audit_event` 新写入 `retention_expires_at=None`;迁移 `6a9c3e5f7b2d` 清空历史到期时间。 @@ -2857,7 +2865,7 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui - 路由引擎 `can_build` / `block_reason` 与历史 `status` 解耦:多候选 `ambiguous` 允许建单;零候选或 `require_manual_review` 阻断。 - `order_build_eligibility_service` 在 Draft 校验与确认前投影行级候选;人工选择须填写原因且库存源已启用。 -- API:`PUT .../order-review-cases/{case_no}/draft/lines/{line_key}/inventory-candidates`;Draft 投影含 `build_eligibility`。 +- API:草稿字段编辑使用 `draft_line_id`;通知准备库存源覆写使用冻结档 `line_no` 定位行;Draft 投影含 `build_eligibility`。 ### 门禁恢复阶段 0:库存源路由独立重算(2026-07-31) @@ -2874,9 +2882,9 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui - `keep-manual` 明确保留人工值并清除 `suggestion_pending`; - 无人工决定且规则唯一可用命中时,建议直接成为有效结果。 - **API**: - - `POST .../draft/inventory-routing/reroute`(可选 `line_key`、`idempotency_key`) - - `POST .../draft/lines/{line_key}/inventory-routing/adopt-suggestion` - - `POST .../draft/lines/{line_key}/inventory-routing/keep-manual` + - `POST .../draft/inventory-routing/reroute`(可选 `draft_line_id`、`idempotency_key`) + - `POST .../draft/lines/{draft_line_id}/inventory-routing/adopt-suggestion` + - `POST .../draft/lines/{draft_line_id}/inventory-routing/keep-manual` - **审计**:`inventory_routing_*` 事件写入操作人、规则版本、前后候选与幂等键;同一幂等键只产生一次有效副作用;409 版本冲突不执行副作用。 - **前端**:复核台 `ReviewInventoryCandidatesPanel` 提供「重新匹配路由 / 采用规则结果 / 保留人工结果」。 @@ -2906,7 +2914,7 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui - `prepare_candidate_inventory_lines` / `match_order_lines_across_candidates` / `apply_line_inventory_resolutions`。 - `ensure_inventory` 多候选合并准备;`match_inventory` STP 分支禁止回读路由;头级 Reservation 从 Snapshot Schema Header 字段读取。 -- Excel:`ALLOWED_SYSTEM_FACTS` 含 `export_sequence`;导出注入 `__export_sequence=1..N`(基于最终导出行集);自动链止于 `wait_manual_upload`。 +- Excel:导出注入已持久化的 `ShippingNoticeLine.line_no`(每张通知单从 1 开始);自动链止于 `wait_manual_upload`。 - 多源行级命中:`multi_source_excel_block`,首期不生成单一 Excel。 - **多源恢复入口(闭环)**:`shortage_review` + 多源/多文件冲突时 `ui_state` 前置 `confirm_inventory_source`;写入 `forced_match_source_code` 后过滤库存行并立即重匹配。`stp_facts.recovery_source_codes` 供工作台候选对话框种子;多源阻断时前端**禁止**回退展示 `inventory_source_resolution` 全部冻结候选。首期仍不提供自动拆单 API。 - 人工确认库存源与随后重匹配:工作台 `_trusted_user_id` 写入任务事件 `actor_id` 与统一审计;`match_inventory` 兼容 `operator_id` / `actor_id` / `_trusted_user_id`。 @@ -3240,11 +3248,10 @@ API 层 匹配顺序: -1. Bill-to:`source_system + ShippingCustomerExternalRef.legacy_customer_key` → 标准名称 → 已审核名称别名。 -2. Ship-to:`source_system + ShippingCustomerSiteIdentifier(external_code)` → `ShippingCustomerSite.site_code` → 站点标准名称 → 已审核站点名称别名。 -3. 结果按角色写入 `shipping_order_customer_matches`,状态为 `unmatched / unique_candidate / ambiguous / confirmed`;Ship-to 人工确认必须同时校验站点属于所选启用客户。 -4. Candidate API 返回 `customer_matches` 供界面展示原文、标准客户、简称、站点与状态;确认接口为 `POST /api/workspace/shipping-order-extractions/{extraction_id}/customer-matches/{role}/confirm`,并校验 Extraction 所属 Intake 的用户权限。 -5. 唯一候选不绕过既有客户质量门禁。Task 建立后仍由客户确认链决定是否绑定业务归属客户和生成业务编号。 +1. 已发布 Identity Rule Set 从订单字段、邮件上下文和其他受控来源提取可识别证据,并按定义匹配客户主数据。 +2. 识别结果写入每个 Candidate 唯一的 `ShippingCustomerShadowResolution`,状态为 `unmatched / unique_candidate / ambiguous / confirmed`;`confirmed_customer_id` 是唯一确认事实。 +3. Candidate/复核 API 返回 Resolution 的候选、证据和状态;人工确认仅写入该 Resolution,并校验 Candidate 所属 Intake 的用户权限。 +4. 唯一候选不绕过既有自动确认质量门禁。OT 建立后仍由已确认 Resolution 决定是否冻结订单和生成业务编号。 #### Dify 手工配置要求 @@ -3452,3 +3459,96 @@ DBS 每个 Warehouse 单独导出且不填报表日期;Crane 固定 `Inbound D | `POST /api/admin/receipt-rpa-units/{unit_id}/retry` | 管理员 | 仅 `failed/cancelled`,必填 `reason` | `shipping_receipt_rpa_unit_retried` | | `POST /api/admin/receipt-report-files/{file_id}/resend` | 管理员 | 仅重发归档文件企微消息,不触发 RPA | `shipping_receipt_report_notification_resent` | | `GET /api/admin/receipt-rpa-units?status=failed` | 管理员 | 只查询失败单元,供人工补偿;不返回凭据、对象键或 trigger 内容 | `shipping_receipt_rpa_units_listed` | + +# 2026-08-29 库存源自动探测与数据自证(一期) + +> 关联设计:`docs/superpowers/specs/2026-08-29-shipping-inventory-source-selection-design.md` +> 范围:多候选库存源订单在「通知准备」内的自动批次 RPA 探测、匹配数据自证反写、行级歧义兜底与人工选源;锁定边界统一为 Excel 生成。 + +## 结论摘要(决策 D1–D12) + +- 源裁决发生在**通知准备**,不阻断建单、不改订单复核契约;`inventory_source_routing` Gate 保持 `fulfillment_prep` 面。 +- 粒度=**行级**;任务级源=各行所选并集。 +- 主路径=**多候选自动批次 RPA**:单批次 trigger 文件含全部缺失候选源;已有 ready 快照的源跳过;逐源 Attempt 记录保留(身份/超时/重试/审计)。 +- 匹配=**数据自证**:全部候选源快照按行打 `__source_code` 标签参与匹配,按行反写 源/可用量/缺口。 +- 歧义兜底=行级:同一行在多源命中 → `multi_file_conflict` 阻断,该行出**源下拉**(候选 + 首选高亮 + 命中规则提示,写 `override_by_id/override_reason`,方法 `user_confirmed`)→ 该行重匹配;其余行照常。 +- 零候选行:不提供下拉,提示「规则未命中」,沿用 `retry_with_latest_rules`。 +- **锁定边界唯一:Excel 生成(Export Artifact 落库)**。此前(含匹配完成后)行源可改 = 换标签重匹配该行(候选快照已在本地,不重新 RPA);此后转只读,纠错走既有撤销/人工流程。 +- 波次通知(D8,已实现):`post_ot_fulfillment_wave_service` 创建波次通知**不再继承**首通知任务级源字段(`inventory_source_*`/`routing_fingerprint`/`snapshot_id`),仅继承订单级路由上下文(目的地/仓提示);新增 `inventory_candidate_freeze_service.freeze_wave_notice_routing` 按波次自身行评估路由并冻结候选集,行级无规则命中时回退到订单级 task 候选集(与首单 `_collect_order_line_candidates` 行为一致,避免「无规则命中的波次行」卡死),随后走同一套自动探测/匹配/反写。测试:`tests/test_shipping_wave_rerouting.py`。 +- 订单复核确认/自动建单逻辑不变(多候选照常建单并自动推进)。 +- 原则边界:编辑窗仅覆盖「确认后、Excel 前」的人工纠错;客户侧订单变更仍走重新上传/重新解析;上传货代后的纠错仍须人工撤销。 + +## 通知准备内状态流转 + +``` +inventory_preparation Gate + ├─ 全部候选源有 ready 快照 → 直接加载匹配(现状) + ├─ 部分缺失 → 自动批次 RPA(仅缺失源)→ status=running「已触发库存获取」 + │ ├─ 批次回调逐源成功 → 加载 → 匹配 → 反写 → 续跑(匹配/Excel 门禁) + │ ├─ 部分源失败 → 成功源照常匹配;失败源相关行停等,沿用 + │ │ inventory_rpa_timeout/exhausted 恢复动作(reload/retry) + │ └─ 行歧义 → 行级 multi_file_conflict + 该行下拉 → 选定重匹配 + └─ 行级零候选 → 维持现状阻断 + retry_with_latest_rules +``` + +`inventory_file_missing` 不再是多候选的终态阻断原因(降为瞬态;RPA 失败仍走既有 `inventory_rpa_timeout`/`inventory_rpa_exhausted` 重试原因)。 + +## 实现要点 + +- `inventory_workflow.ensure_inventory`(`mode='auto'` 的 STP 多候选分支):删除「缺文件不隐式触发 RPA」,改为自动批次探测。`missing_files`/`partial_missing` 返回改为触发后 `running` + 「已触发库存获取,等待各库存源回调」;无候选集时维持 `needs_human`(`inventory_candidates_missing`)。 +- `per_source_rpa_service.ensure_all_required_sources_prepared`:不再逐源写 trigger,而是把全部 pending 源合并写入**一个** `inventory_export_batch_*.json`,逐源身份键(`task_no/attempt_no/source_run_no/lease_token/candidate_set_id/execution_id/gate_id/expected_warehouse_id`)进入 `inventory_sources[]`;批次写入失败时本轮新建 Attempt 统一置 `failed/trigger_not_written`。 +- `stp_line_inventory_match.match_order_lines_across_candidates`:按行打 `__source_code` 标签参与匹配;同一行命中多源 → 行 `disposition=multi_file_conflict` + `candidate_hit_source_codes`,`resolved_inventory_source_code=None`;唯一源命中按行反写 `resolved_inventory_source_code/available_qty/shortage_qty`;人工选源通过行 `allowed_source_codes` 钉住单一源后重匹配该行。 +- `process_gate_executor` 提供通知准备能力 `override_line_inventory_source`(参数 `line_no/source_code/reason`):校验行处于冲突、源启用、**通知未生成 Excel**(`task.export_file_path` 为空,否则 `SHIPPING.LINE_SOURCE_LOCKED`);写冻结档行覆写 + 仅该行重匹配 + 审计 `review_line_source_overridden`。 +- `ui_state._build_stage_context` 的 `preparation`:下发 `source_locked`(`task.export_file_path` 非空即锁定)、`lines[].source_ambiguous`(`multi_file_conflict`)、`lines[].source_candidates`(候选编码去重)、`artifact.status`。前端 fail-closed 消费。 +- 错误解释契约/原因码:行级冲突对应 `inventory_multi_file_conflict`,Owner 动作 `select_line_inventory_source`;「同一明细在多个库存源命中,请选择实际库存源」。 +- 前端 `ShippingOrderReviewView.vue`:阶段自动跳转成功后一次性 toast(`lifecycle.autoAdvanced`);清理 `workbenchMode==='reparse'` 死守卫;通知准备歧义行渲染源下拉 + 首选高亮 + 确认按钮,`source_locked` 行只读徽标。 + +## 既有能力与契约(不新增开关) + +- 沿用 `SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED` 总开关与既有批次开关;无新增配置开关。 +- RPA Worker 无需修改(batch v2 契约已支持多源逐源身份)。 +- 存量终态/已 `uploaded` 通知零影响;非终态停挡单首次进入工作台自动探测续跑(老单治愈)。 +- 无强制数据迁移:行级覆写复用候选行 `override_by_id/override_reason`;歧义状态入匹配结果 JSON/行决定。 + +# 2026-08-29 确认后订单编辑窗(二期) + +> 关联设计:`docs/superpowers/specs/2026-08-29-shipping-inventory-source-selection-design.md` §3。 +> 范围:确认后、首通知 Excel 生成前的订单人工纠错窗;锁定边界统一为 Excel 生成(D7/D10/D12)。 + +## 可编辑矩阵(谓词服务) + +- 谓词收敛于单一服务 `backend/app/services/shipping_notice/order_edit_window_service.py`(`editable_scope` / `order_has_active_attempt` / `assert_field_editable`),前端 fail-closed 渲染,后端保存守卫复用同一谓词(D12 原则边界集中化)。 +- **头字段**:该订单**任一通知**(含波次)无 Export Artifact **且** 无活动 Gate Attempt → `header=True`。 +- **行字段**:逐行——行已入某波次 → 该波次通知无 Export Artifact 且无活动 Attempt;行未入波次 → 无活动 Attempt(不受首单 Excel 限制)。 +- `ui_state.build_task_ui_state` 在 `include_stage_context` 时下发顶层 `edit_window`(同构 `{header, lines}`);前端 `ShippingOrderReviewView.vue` 据此禁用锁定字段/行源下拉。 + +## 保存守卫与失效重跑 + +- 正式字段编辑走既有 `task_workflow.update_notice_fields` / `update_notice_line` / `add_notice_line` / `remove_notice_line`(不新增 Case 状态);写路径保留 `_assert_order_data_version` 乐观锁(409 语义不变)。 +- **新增编辑窗守卫**:`_edit_window_busy_error`——订单任一通知有活动 Gate Attempt(库存 RPA / 匹配 queued|running)时返回 `SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`(「系统处理中,请稍后再修改」);活动 Attempt 结束后恢复可编辑。 +- **失效分类重跑**:沿用 Schema `task_edit_policy.change_effect` → `_apply_notice_edit_change_effects`: + - 头部路由字段 → `rerun_inventory_source_resolution`:清候选/匹配/导出、`clear_inventory_source_confirmation`、重裁库存源、OT 同步 `inventory_fetching`(快照复用,无新 RPA 当快照可用)。 + - 行字段(料号/数量/预约号)→ `rerun_inventory_matching`:仅清匹配并 OT 同步 `inventory_matching`。 + - 导出相关 → `regenerate_excel`;需重解析 → `require_revision`。 + - 无路由引用 → `none`(仅保存 + `order_data_version` 递增 + 审计)。 +- 被失效的匹配结果/缺口标记 superseded,界面显示「重新匹配中」;不产生新 Excel(Excel 尚未生成)。 +- 审计 `_record_formal_task_edit_audits` 写入 `applied_effects`(失效动作链)与字段 old→new + 操作人 + 证据(D10「不强填原因」)。 + +## 前后端契约 + +- 新增错误码:`SHIPPING.EDIT_WINDOW_FIELD_LOCKED`(字段超出编辑窗)、`SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`(系统处理中);四语言 `locales/*/errors.json` 已补齐。 +- 前端类型 `ShippingTaskUiState.edit_window`(`ShippingOrderEditWindow{header,lines}`);`formalHeaderEditable()`/`formalLineEditable(lineKey)` 供模板绑定 `:disabled`。 +- **原则边界(D12)**:编辑窗仅覆盖「确认后、Excel 前」的人工纠错;客户侧订单变更仍走重新上传/重新解析;上传货代后的纠错仍须人工撤销。用户不修改原始订单的原则不被扩大解释。 + +## 验收对照(§3.4) + +1. 首通知 Excel 前改目的地(路由字段)→ 自动重路由+重探测+重匹配,指纹/审计/候选集版本正确(`rerun_inventory_source_resolution`)。 +2. 改未入波次行的数量/预约号 → 仅该行重匹配;该行已入已出 Excel 的波次 → 拒绝编辑(该行所属通知 Excel 冻结)。 +3. 匹配运行中保存 → `SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`;活动 Attempt 结束后可编辑。 +4. Excel 生成后头/行全部只读(`assert_formal_task_not_excel_frozen` / `is_excel_ready_for_task`)。 +5. 乐观锁版本冲突 409 行为不变(`_assert_order_data_version`);审计含失效动作链(`applied_effects`)。 + +## 二期状态补充 + +- 一期规划中的「快照重冻结 + `order_data_version` 递增」由既有 `update_notice_*` ⇒ `_commit_notice_edit` ⇒ `_apply_notice_edit_change_effects` 链路承担(编辑落库后依赖 `change_effect` 失效下游);`order_data_version` 由乐观锁 `_assert_order_data_version` 保护,避免重复冻结引入二次状态机。 +- 波次通知「按自身行重跑路由」(D8)已实现(见一期章节):不再继承首通知源,`freeze_wave_notice_routing` 按波次自身行冻结候选集;本二期不新增二次波次状态机,与一期波次路由冻结复用同一套链路。 diff --git a/docs/funclist.md b/docs/funclist.md index ffb17f7c..f6940680 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -74,6 +74,7 @@ | 功能项 | 状态 | 说明 | | --- | --- | --- | | **统一 ShippingProcessingProjection(15 阶段)+ 正式任务编辑** | 阶段 0–6 已验收 | 库存源硬门禁;复核台原地 formal_task;Schema `task_edit_policy`/`change_effect`;正式编辑审计矩阵;Dify NONE。验收:`unified-progress-formal-edit-stage0~6` + `final-acceptance` + `dify-config`。 | +| 订单生命周期工作台状态展示统一(v2) | 已实现 | 五阶段下方横幅移除;右栏「当前任务」卡为唯一状态宿主:状态行=user_status 短标签(Run 级 lifecycle_status 受控兑底映射)+ 状态块内嵌动态说明(`RUN_STATUS_FALLBACK_MAP`/`REDUNDANT_DETAIL_REASON_CODES` 双常量裁决,诊断信息不隐藏);无 Case 瞬态保留单行白名单轻提示;聊天页/任务中心同源接入零视觉变化。设计:[2026-08-31 状态展示统一设计](superpowers/specs/2026-08-31-shipping-review-status-display-unification-design.md) | | 发货通知技术手册 | 已文档化 | 见 [docs/features/shipping-notice/technical.md](features/shipping-notice/technical.md) | | 发货通知业务说明 | 已文档化 | 见 [docs/features/shipping-notice/business.md](features/shipping-notice/business.md) | | 业务去重与任务版本(Phase 3) | 已实现 | Intake 业务指纹/重复决策、修订版本链、强制新建权限与审计;见技术手册第三节摘要 | @@ -82,6 +83,7 @@ | 上传与发送门禁状态一致性 | 已实现 | Intake 状态接口返回 `preview_status / ready_for_extraction / attachment_directory_complete` 等快览事实;聊天附件快览成功后显示“已就绪/已发现 N 个附件”并允许发送,不再因上传阶段版面任务阻塞;真正的订单识别进度在点击发送后单独展示 | | 版面解析并发与耗时诊断 | 已实现 | 独立 `hxops-shipping-worker` 默认双进程并行领取同批版面 Job;PDFium 先轻量预读字符但不裁决表格,MinerU 始终作为 PDF 表格结构首选 Provider;仅 MinerU 空表/失败时允许严格 PDFium 回退。Job `result` 平级保存脱敏 `timings`+`counts`(含 OCR/OpenCV/对齐细分与 `ocr_engine_warm`),worker 日志同步输出;诊断字段不进 layout snapshot,不记录原文/HTML/OCR 原始响应(PR-0)。PR-1:`SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED` 控制同 Job 整页 OCR 复用;PR-2:`SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED` 字符预读复用+按需补图,OpenCV geometry Job 内缓存;PR-3:`SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED` 表格裁剪 OCR(prod 默认关) | | 对话输入框多附件统一提交 | 已实现 | 用户可分多次选择 EML/PDF;当前输入框内全部已就绪 Intake 在一次发送中冻结为同一个订单抽取 Run。`uploadBatchId` 仅用于单次上传幂等与状态关联,不再截断发送范围 | +| 批次进度中心混合状态 EML 展示 | 已实现 | 状态以 PDF Unit 为准,聊天摘要与批次进度中心均按“状态 → EML → PDF”展示;同一 EML 可在多个状态区出现,但每张卡仅显示本区 PDF,并标注本组/总附件数;所有状态分组标题统一显示本组文件数;未物化附件以工作项标识去重,Excel 诊断附件进入只读“已忽略”分区,不混入处理中或已完成;聊天摘要与批次进度中心均默认折叠已忽略分区,展开后保留 Excel 明细;批次中心顶栏单列已忽略数,与提交文件总数对账,完成率和“已处理 N/M”仅按订单文件计算;其余订单 PDF 全部完成时,对话摘要显示完成且不再展示阶段 | | 无框订单明细表原生 PDF 回退 | 已实现 | 仅当 MinerU 未输出表格、PDF 原生文字坐标完整且同页命中多个通用明细表头时,从表头到合计行生成待配置候选表;正常 MinerU 表格路径不变,解析器修订 `v4` 防止复用旧零表格缓存 | | 点击发送完整订单抽取 | 已实现(终态分阶段) | Run 冻结文档、Schema、模板 Profile、路由/评分/门禁与解析器版本;Worker 执行异型模板或通用确定性解析;完整性门禁与紧急停止控制自动冻结;Dify 仅提供复核最小证据建议且不得自动冻结;上线清单见 order-extraction-go-live-checklist.md | | 相同附件跨批次 Workflow 复用 | 已实现 | 同会话完整附件 `content_hash` 集合与 Schema 版本相同时,复用活跃或未关闭 Run/Workflow Item;新上传批次、Intake/Document ID 或文件名不再导致重复 Workflow | @@ -117,10 +119,10 @@ | **建单前统一恢复协调器(Gate/资格/auto_gate)** | 进行中(P0 缺陷已修,待正式验收) | `order_review_resume_service` + 行级履约 fail-closed(库存重校验、task 行不可 reopen、审计 before/after);复核侧栏置顶业务阻断,履约表格在库存模式;业务审计含白名单快照。权威:[process-gate-recovery-contract.md](features/shipping-notice/process-gate-recovery-contract.md)。 | | **双工作台审计闭环** | 已实现(阶段 6) | 事件字典冻结 chat_* / review_* / process_gate_* / qualification / workflow_node;对话恢复写 `chat_process_gate_*`;审计中心分组与 Candidate/Gate 筛选;普通账本脱敏 + 敏感快照独立鉴权;覆盖率举证见 AUDIT_COVERAGE_MATRIX。 | | **复核字段精确高亮(阶段 0–5)** | 已完成(盲测样本集另立) | 冻结 `shipping-field-highlight-v1`;原生唯一 glyph / OCR candidate / Cell 来源分级;证据 API 全量 `highlight_quality`;工作台 verified 实线 / candidate 虚线;坐标诊断与 list/focus/restore/version 审计齐全;`review_coordinate_corrected` 事件已冻结(人工改框写路径待模板标注扩展)。权威契约:[field-highlight-contract.md](features/shipping-notice/field-highlight-contract.md)。 | -| **STP 直通 + 例外工作台** | 已实现(首期) | 可信 PDF 自动建 Task 并推进至「待人工上传」;例外进入人工复核/任务处理;Chat 仅上传与通知。**阶段 0–5 已落地**:字段契约、起行锚点、建单资格与候选、自动建单/复核台、跨候选库存匹配→Excel→待人工上传、统一 `ui_state.stp_facts` 与审计双写/时间线 i18n。**项次派生 Phase 0–4**:`line_no`=内部项次、`export_sequence`=导出行号、Schema 派生模拟、运行时派生审计、复核覆盖锁定与 `field_meta` 投影、冻结血缘。**库存源路由独立恢复(门禁恢复阶段 0)**:复核台可按最新已发布规则与库存源启停重算路由(不重识别 PDF);人工决定优先且不被静默覆盖;支持采用规则建议 / 保留人工结果;幂等键与审计前后快照齐全。首期不触发货代 RPA 上传、不改 Dify | +| **STP 直通 + 例外工作台** | 已实现(首期) | 可信 PDF 自动建 OT 并推进至「待人工上传」;例外进入人工复核/任务处理;Chat 仅上传与通知。阶段 0–5 已落地:字段契约、起行锚点、建单资格与候选、自动建单/复核台、跨候选库存匹配→Notice/NoticeLine→Excel→待人工上传、统一 `ui_state.stp_facts` 与审计双写/时间线 i18n。订单项次由各单据写路径按顺序生成且不可编辑;库存准备失败停留在通知准备阶段。| | **全门禁级中断恢复(契约冻结)** | 已实现(P0–P4 代码与自动化;P5 外部条件待签署) | **RecoveryPlan → Attempt → Job → Worker/RPA → 幂等回调 → AutoProgress → Projection** 已收口;20 Gate 均有运行时实施状态,跨阶段恢复、精确失效、多源库存准备、组合指纹、未知上传状态和前端 `recovery_targets` 已覆盖。权威契约:[process-gate-recovery-contract.md](features/shipping-notice/process-gate-recovery-contract.md);验收:[process-gate-recovery-acceptance.md](features/shipping-notice/process-gate-recovery-acceptance.md);最终报告:[process-gate-recovery-final-compliance.md](features/shipping-notice/process-gate-recovery-final-compliance.md)。生产双 Worker、真实 RPA、Dify 手工核对、视觉/E2E 与人工签署仍为发布前条件;不引入 Temporal/Celery。 | | **错误可解释性(阶段 0–4)** | 完全达标 | 分层原因码冻结且主路径全量 EMITTED(仅预留 `inventory_uom_conversion_failed`);`AUDIT_COVERAGE_MATRIX` 统一覆盖率 100%;审计中心业务/技术分层且无强制横滚;库存源复核始终展示 `source_code`;四语言对齐。权威契约:[error-explainability-contract.md](features/shipping-notice/error-explainability-contract.md)。 | -| **订单项次派生与血缘审计** | 已实现(Phase 0–4 + 评审纠偏) | 统一 `customer_po_line_no` / `line_no` / `export_sequence`;Schema 派生模拟支持历史 Extraction 样本;运行时派生含 `evidence_refs`;复核覆盖/恢复(`LINE_NO_OVERRIDDEN`/`LINE_NO_RESTORED`);货代统一审计新写入永久保留(`6a9c3e5f7b2d`) | +| **订单项次与字段血缘审计** | 已实现(硬切换) | `customer_po_line_no` 作为原始客户事实保留;订单解析行、冻结档行、发货通知行各自在所属单据内从 1 编号;不提供 Schema 派生、项次覆盖或恢复。| | 模板发布与自动冻结资格分离(阶段 4) | 已实现 | Profile 的发布仅允许确定性解析;每个发布版本独立冻结人工确认资格,首版强制 `manual_confirmation` 且自动冻结关闭,盲测批准、旧版本资格或 checksum 变化均不能越过该门禁 | | Run 自动冻结门禁与执行 | 已实现 | Run 创建时冻结 `manual_confirmation` 初始策略;结果落库后按模板资格、已确认 Bill-to 客户、业务场景、技术失败、预算停止和待处理订单刷新 `auto_freeze_policy_json`。仅资格与全部门禁显式放行时,自动消费当前 Run 的 accepted Candidate 并冻结新建 Task;不触发库存、Excel 或上传履约副作用。 | | 人工复核与字段证据闭环(阶段 5) | 已实现 | 单头、订单行、冲突解决均要求乐观锁、原因和结构化 `document_cell`/`manual_input` 证据;跨订单或伪造证据在写值前拒绝,复核审计保存结构化证据且详情页展示页码、表格、单元格与原文 | @@ -133,7 +135,7 @@ | 内部料号库存匹配 | 已实现 | 主匹配键为 `(part_number, reservation_id)`;库存 `Supplier Sku` 对应内部料号,`AWS Sku` 仅作为可选 `aws_part_number`,AWS-only 库存表不能形成有效主匹配行 | | 库存快照身份校验 | 已实现 | link 时校验 `source_code`/`site_id`/`warehouse_id` 与任务一致 | | 库存快照 TTL 复用 | 已实现 | `inventory_snapshot_store`,按需任务优先复用未过期快照 | -| 库存 RPA 批量导出(DSV/Crane 一次登录) | 已实现 | `inventory_export_batch` trigger + worker + `/rpa/inventory-batch-ready` | +| 库存 RPA 批量导出(DSV/Crane 一次登录) | 已实现 | `inventory_export_batch` trigger + worker + `/rpa/inventory-batch-ready`;回调以 `ShippingOrderTask` 为唯一任务模型,收件与业务处理分离,事务失败必须收口为失败;库存等待使用单一 Gate Attempt 与 30→60→120→240→300 秒退避 Job,不为每次轮询新增 Attempt。 | | 库存每日定时导出排程 | 已实现 | `schedule_type=platform_job` + `platform_api_path=shipping-inventory-rpa`,cron 建议 `0 3 * * *` | | 库存源至外部系统仓库映射 | 已实现 | 维护精确与 Source 默认映射;当前仅后台维护和后端内部 Service,不开发 Tool API 或调拨逻辑 | | 建单防重复(第一阶段) | 已实现 | 批次 `create_idempotency_key`、任务 `source_content_hash`、同请求去重、幂等重放 | @@ -153,6 +155,14 @@ | 库存、Excel 与上传入口门禁(阶段 8) | 已完成 | 履约入口及其底层服务均要求活动的冻结订单,替代/作废/撤销待处理版本无法匹配或导出;人工上传仅按业务单号确认,服务端从当前用户会话取得操作人并创建 Attempt 审计。 | | 安全 Chatflow(阶段 9) | 已完成 | 仅允许一个启用货代 Chatflow;Dify OpenAPI 只保留短效能力令牌保护的任务/批次状态查询,所有写操作改由 HXOPS 确认卡与服务端状态机执行。 | | 产品原型 | 已文档化 | 见 [docs/features/shipping-notice/shipping_notice_agent_prototype.md](features/shipping-notice/shipping_notice_agent_prototype.md) | +| **多候选库存源自动批次探测(一期)** | 已实现 | `ensure_inventory` STP 多候选分支:缺文件不再隐式阻断为 `needs_human`,改为自动单批次 RPA 探测(仅缺失源,已有 ready 快照复用)并返回 `running`;逐源 Attempt/超时/重试保留。设计:[2026-08-29-shipping-inventory-source-selection-design.md](superpowers/specs/2026-08-29-shipping-inventory-source-selection-design.md) §2。 | +| **库存匹配数据自证 + 行级歧义兜底(一期)** | 已实现 | 全部候选源快照按行打 `__source_code` 标签匹配,按行反写源/可用量/缺口;同一行命中多源 → 行 `multi_file_conflict` 阻断 + `candidate_hit_source_codes`(禁止静默选源)。设计 §2.3。 | +| **行级人工选源动作 select_line_inventory_source(一期)** | 已实现 | Gate 业务动作(属 `inventory_matching`):校验行冲突、源 ∈ 候选、源启用、通知未生成 Excel(否则 `SHIPPING.LINE_SOURCE_LOCKED`);写候选行覆写 + 仅该行重匹配 + 审计 `review_line_source_selected`。 | +| **通知准备行源下拉与锁定渲染(一期)** | 已实现 | `ui_state.preparation` 下发 `source_locked` / `lines[].source_ambiguous` / `source_candidates`;前端歧义行渲染库存源下拉 + 首选高亮 + 确认,`source_locked` 行只读徽标;阶段自动跳转一次性 toast + 清理 `reparse` 死守卫;四语言文案。 | +| **波次库存源按自身行重路由(D8)** | 已实现 | `post_ot_fulfillment_wave_service` 创建波次通知不再继承首通知任务级源字段(`inventory_source_*`/`routing_fingerprint`/`snapshot_id`),仅继承订单级路由上下文(目的地/仓提示);新增 `inventory_candidate_freeze_service.freeze_wave_notice_routing` 按波次自身行评估路由并冻结候选集,随后走同一套自动探测/匹配/反写。测试:`test_shipping_wave_rerouting.py`。 | +| **确认后订单编辑窗谓词(二期 T10)** | 已实现 | `order_edit_window_service.editable_scope`(header=订单任一通知无 Excel 且无活动 Attempt;行=所属通知无 Excel 且无活动 Attempt,未入波次行不受首单 Excel 限制)+ `order_has_active_attempt`;`ui_state` 下发 `edit_window`;测试通过。设计 §3.1。 | +| **Excel 前保存守卫 + 失效分类重跑(二期 T11/T12)** | 已实现 | 正式字段编辑路径(`task_workflow.update_notice_*`)新增活动 Attempt 守卫(`SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`);失效重跑沿用 Schema `change_effect`:路由字段→`rerun_inventory_source_resolution`、行字段→`rerun_inventory_matching`、导出→`regenerate_excel`、需重解析→`require_revision`;审计含 `applied_effects` 失效动作链。设计 §3.2/§3.3。 | +| **编辑窗前端渲染(二期 T13)** | 已实现 | `ShippingTaskUiState.edit_window` 类型 + `formalHeaderEditable()`/`formalLineEditable(lineKey)`;头字段编辑块按 `edit_window.header` 门控、歧义行源下拉确认按行锁定;四语言 `errors.json` 补 `SHIPPING.EDIT_WINDOW_FIELD_LOCKED/SYSTEM_BUSY`;`npm run build` 通过。 | ### 排程平台任务契约中心(schedule) diff --git a/docs/openapi/shipping_notice_tools.dify.json b/docs/openapi/shipping_notice_tools.dify.json index 7e74bc62..7f6c036e 100644 --- a/docs/openapi/shipping_notice_tools.dify.json +++ b/docs/openapi/shipping_notice_tools.dify.json @@ -14,8 +14,8 @@ "/tools/get_task_status": { "post": { "operationId": "get_task_status", - "summary": "查询任务当前状态与 human_options;响应含库存连接器独立字段与候选结构", - "description": "返回 inventory_source_code、inventory_connector_type、inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|user_confirmed|invalid|conflicted)、inventory_source_method、inventory_source_config_version、inventory_routing_fingerprint、inventory_source_confirmed_by、inventory_source_confirmed_at,以及 step_payload.inventory_source_resolution.candidates。", + "summary": "查询任务当前状态与 human_options;响应含库存源状态与候选结构", + "description": "返回 inventory_source_code、inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|user_confirmed|invalid|conflicted)、inventory_source_method、inventory_source_config_version、inventory_routing_fingerprint,以及 step_payload.inventory_source_resolution.candidates。", "parameters": [], "requestBody": { "required": true, diff --git a/docs/tec.md b/docs/tec.md index fec019d8..ece885f0 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -13,9 +13,9 @@ ### STP 阶段 0:字段契约与状态语义冻结(2026-07-30,项次派生 Phase 0 纠偏) - 标准字段目录锁定 **58** 项;`reservation_id` 可同时存在于 Header 与 Line,资产唯一键为 `(field_code, scope)`。 -- 运行时投影:`line_key`(草稿稳定标识)、`effective_reservation_id = validated(line) ?? validated(header)`;`line_no` 为可识别内部项次,不再由 `position+1` 系统覆盖。 -- Schema `definition_json.derivation_rules`:同行明细派生契约(首期仅 `copy_if_empty`,目标仅 `line_no`);新草稿预置关闭的 `customer_po_line_no → line_no`。 -- `customer_po_line_no` / `line_no` 均进入确定性表格可解析字段集;Excel 导出行号为 `system_fact:export_sequence`。 +- 草稿行使用 `draft_line_id`;冻结档与库存准备使用 `snapshot_line_id` 和系统生成的 `line_no`;正式通知使用 `ShippingNoticeLine.line_no`。 +- Schema 不提供派生规则;`line_no` 不进入确定性表格解析字段集,由各单据写路径按顺序生成。 +- Excel 导出行序号使用已持久化的 `ShippingNoticeLine.line_no`。 - 进度事实源仍以后端状态机为准;阶段 0 冻结字段与投影语义。 ### STP 阶段 1:模板起行锚点(2026-07-30) @@ -40,7 +40,7 @@ - `stp_line_inventory_match`:准备冻结候选快照行;按 `effective_reservation_id + part_number` 跨文件匹配。 - 裁决:`ok` / `shortage` / `not_found` / `multi_file_conflict`;结果写入 `step_payload.line_inventory_resolutions`。 -- 唯一 ok 源 → `inventory_source_status=resolved` 并 `try_auto_chain_after_match` 生成 Excel(`export_sequence`);多源行级成功命中以主绑定源制单(`stp_line_match_multi`),同键多文件冲突仍停人工。 +- 库存门禁通过后才创建 `ShippingNotice`/`ShippingNoticeLine` 并生成 Excel;库存准备失败停留在通知准备阶段,多候选源只写一个批量 RPA trigger。 - `match_completed` 仅 `fulfillable` 且全部明细 `ok` 时允许 Excel;partial 禁止制单。 - OT 后短缺放行复用 `SHIPPING_LINE_AUTO_FULFILL` Job:已审计放行的短缺行可作为 wave 候选;仅唯一开放候选自动创建独立 `ShippingNotice` 并调度 Excel,多候选返回人工勾选,不自动合并或批次放行。 - `ensure_inventory` 多候选路径不隐式 RPA;自动链硬停 `wait_manual_upload`。 @@ -230,7 +230,7 @@ PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由 - Excel 命名规则由已发布模板的 `filename_pattern` 定义;未定义时读取环境变量 `SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN`。两者均由后端编译、校验并在 Artifact 保存规则来源、版本、最终文件名和独立流水。客户端请求不得携带命名模式或文件名;流水即使 Artifact 作废亦不得复用。 - LLM Observation 必须有真实 `evidence_ref`,并以 `evidence_verified=false` 落库;任意关键字段存在该类 Observation 时,冻结门禁返回 `SHIPPING.ORDER_LLM_REVIEW_REQUIRED`。Dify 故障只能转人工复核,不能使确定性模板路径降级为猜测。 - JSON API 按统一 envelope 返回。关键错误码至少包括 `SHIPPING.ORDER_SNAPSHOT_FROZEN`、`SHIPPING.ORDER_LLM_REVIEW_REQUIRED`、`SHIPPING.RESERVATION_CONFLICT`、`SHIPPING.INVENTORY_STALE`、`SHIPPING.EXPORT_NOT_READY`、`SHIPPING.UPLOAD_EVIDENCE_REQUIRED`;权限矩阵禁止 Dify/普通用户调用冻结、制单、上传回调和作废接口。 -- **引用与快照**:规则保存发布时的 `context_field_id`,发布/运行快照同时冻结字段代码、显示名、Schema 字段配置、规则集版本、定义和命中证据。运行期优先按快照 ID 取值;普通 Schema 升级仅在 `field_code`、Header 作用域、值类型和身份授权均未变化时映射新 ID,实际命中字段 ID 仍写入证据链。字段退役、删除或 Schema 发布移除被启用规则引用字段时服务端阻断。 +- **引用与快照**:规则保存发布时的 `context_field_id`,发布/运行快照同时冻结字段代码、显示名、Schema 字段配置、规则集版本、定义和命中证据。运行期**以 `field_code`(语义键)优先绑定**当前 Schema 字段,快照 `context_field_id`(UUID) 仅作同字段快速命中兜底;Schema 升级造成字段 UUID 漂移时仍能按稳定 `field_code` 承接旧快照,实际命中字段 ID 仍写入证据链。字段退役、删除或 Schema 发布移除被启用规则引用字段时服务端阻断。 - **裁决边界**:客户主体和送货站点独立候选;编码确定性匹配优先;多命中、冲突、未命中均进入人工复核。业务弱证据(地址、联系人、名称)默认不得单独自动确认;公共邮箱域名永久禁止。 - **Dify**:不新增 Tool 或修改画布。Dify 继续按已发布动态 Schema 契约提交 Header Observation;HXOPS 完成证据校验、字段裁决、规则匹配、质量门禁和最终确认。 @@ -310,8 +310,8 @@ PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由 - 裁决结果写入 `ShippingOrderFieldDecision/ShippingOrderFieldValue`,流程摘要写入 `ShippingTask.step_payload_json.parse_validation`;字段模型调整必须配套 Alembic 迁移。 - 不保留旧字段 alias、双版本读取、固定订单行投影或历史值猜测回填;任务的 `current_order_extraction_id` 是履约读取入口。 - 订单抽取提交、人工确认和 `match_inventory` 三层重复执行关键门禁,防止脏值通过任一旁路进入后续履约。 -- 客户角色采用“解析原文”和“主数据解析”分层:动态 Schema 保存 Bill-to/Ship-to 名称、外部编码、来源系统及地址证据;`ShippingOrderCustomerMatch` 保存角色候选和确认快照;`ShippingCustomerExternalRef`、`ShippingCustomerSite`、`ShippingCustomerSiteIdentifier` 提供外部客户编码与送货站点匹配。LLM 不生成主数据 ID 或客户简称。 -- 客户匹配遵循外部编码优先、标准名称/已审核别名回退;Ship-to 必须落到启用站点并校验所属客户。Candidate 只展示候选,正式客户绑定和业务编号仍通过既有质量门禁。 +- 客户识别采用“解析原文”和“规则证据”分层:动态 Schema 保存 Bill-to/Ship-to 名称、外部编码、来源系统及地址证据;已发布 Identity Rule Set 以全部适用证据生成 `ShippingCustomerShadowResolution`,其中 `confirmed_customer_id` 是唯一客户确认事实。`ShippingCustomerExternalRef`、`ShippingCustomerSite`、`ShippingCustomerSiteIdentifier` 只提供可被规则使用的主数据证据。LLM 不生成主数据 ID 或客户简称。 +- 客户识别可采用外部编码、标准名称、已审核别名或其他已发布证据;Bill-to/Ship-to 不是客户业务角色。Candidate 只展示 Resolution 候选,正式客户绑定和业务编号仍通过既有质量门禁。 - 单票与多票发货需求统一落入 `ShippingBatch`;单票使用 `file_count=1` 的批次容器。 - 库存 Excel 上传后保存为 `shipping_inventory_files` 批次库存快照,并通过 `shipping_task_inventory_links` 关联到本批任务。 @@ -1428,7 +1428,7 @@ Dify - **受控坐标预览**:页面授权写入 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。 - **模板版本中心数据边界**:版本列表接口只返回族摘要和版本摘要,不返回 PDF、正文、大体积 Layout payload 或盲测真值。版本详情接口返回 Profile 元数据、Schema 摘要、定义摘要、配置规模、冻结证据摘要、样本摘要、测试摘要、自动冻结资格摘要、来源版本和 checksum;样本画布预览接口必须以冻结样本绑定身份鉴权,短时、单用途、管理员绑定且 `no-store`,不得接受任意 `document_id` 直接取页。 - **模板版本中心审计与使用数据边界**:`audit-events` 只返回事件类型、操作者摘要、`request_id`、过滤条件命中的安全 `detail_json` 和 ISO 8601 时间,不返回 PDF、正文、对象存储地址、盲测真值或可复原答案的坐标。`usages` 只返回脱敏文档名、Run 编号、匹配/执行状态、原因码、模板身份命中方式和只读诊断入口;不得回传文档正文、文件地址或运行时原始模型输出。 -- **订单客户指纹与冻结门禁**:`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、指纹、规则版本、确认方法和人员时间,避免主数据变化改写历史履约事实。 +- **订单客户识别与冻结门禁**:`ShippingCustomerShadowResolution` 保存已发布 Rule Set 的证据、候选快照和确认审计。只有 Resolution 为 `confirmed`、存在 `confirmed_customer_id`、证据和 Rule Set checksum 时 `order_freeze_service` 才冻结 Snapshot;冻结服务不接受外部 `customer_id` 或 `customer_short_code`。Snapshot 的 `rule_versions_json.ordering_customer` 保存 Resolution ID、Rule Set checksum/version、确认方法和人员时间,避免主数据变化改写历史履约事实。 ### XFA 拆分规则作用域与源路径(2026-08-05) diff --git a/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.spec.ts b/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.spec.ts index 4e80da12..f4c84ce7 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.spec.ts +++ b/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.spec.ts @@ -99,7 +99,9 @@ describe('ReviewCurrentProcessingCard', () => { expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true); }); - it('renders reload inventory result as the timeout primary action', () => { + it('renders a code-agnostic primary action label from a registered recovery code', () => { + // 卡片是 code-agnostic 渲染器:只要后端下发了受控文案键,就渲染对应业务动作文案。 + // 此用例用 reload_inventory_result(仍为写契约有效码)验证卡片对库存动作文案的渲染。 const wrapper = mount(ReviewCurrentProcessingCard, { props: { stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true, @@ -309,4 +311,30 @@ describe('ReviewCurrentProcessingCard', () => { expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toBe('正在获取最新状态…'); expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toBe('待机'); }); + + it('renders an embedded status detail line when provided', () => { + const wrapper = mount(ReviewCurrentProcessingCard, { + props: { + userStatus: 'running', + stageCode: 'intake_parse', + statusDetail: { text: '正在等待解析任务启动' }, + }, + global: { plugins: [i18n] }, + }); + // 关键断言:说明内嵌于状态行下方(弱文本一行),带 aria-live 与固定 testid; + // 状态行仍为短标签(系统处理中),长句不进入状态位。 + const detail = wrapper.get('[data-testid="review-current-task-status-detail"]'); + expect(detail.text()).toBe('正在等待解析任务启动'); + expect(detail.attributes('aria-live')).toBe('polite'); + expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toContain('系统处理中'); + }); + + it('renders no status detail line without the prop', () => { + const wrapper = mount(ReviewCurrentProcessingCard, { + props: { userStatus: 'waiting_human', stageCode: 'order_review' }, + global: { plugins: [i18n] }, + }); + // 关键断言:无 statusDetail 时说明行完全不渲染,不留空壳。 + expect(wrapper.find('[data-testid="review-current-task-status-detail"]').exists()).toBe(false); + }); }); diff --git a/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts b/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts index cc34ca04..108eb679 100644 --- a/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts +++ b/frontend/src/features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts @@ -293,6 +293,51 @@ describe('ShippingConversationProcessingCard', () => { expect(wrapper.text()).not.toContain('snapshot-attachment.pdf'); }); + it('keeps selected but unrecognized EML attachments visible without file actions', async () => { + const projection = buildProjection(); + setStatusGroup(projection, 'processing', [{ + user_task_no: 'INTAKE:EML-PENDING', group: 'processing', status_label: 'extracting', + title: 'pending-mail.eml', file_count: 2, run_no: 'RUN-EML-PENDING', can_append: false, + }]); + const recognizedLeaf = buildWorkItem('DOCUMENT:91', { + sourceType: 'eml', rootOrderTaskNo: 'OT-EML-PENDING', + sourceSummary: { + emailSubject: null, filename: 'recognized.pdf', documentId: 91, + documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, + customerName: null, poNumber: null, + }, + }); + const pendingLeaf = buildWorkItem('PLAN:EML-PENDING:missing.pdf', { + workItemType: 'order_intake', sourceType: 'eml', rootOrderTaskNo: null, + sourceSummary: { + emailSubject: null, filename: 'missing.pdf', documentId: null, + documentCount: 0, parsedDocumentCount: 0, candidateCount: 0, + customerName: null, poNumber: null, + }, + facts: { recognized: false, planState: 'selected_pending' }, + uiState: undefined, + }); + const root = buildWorkItem('INTAKE:EML-PENDING', { + sourceType: 'eml', rootOrderTaskNo: 'OT-EML-PENDING', + sourceSummary: { + emailSubject: 'Pending mail', filename: 'pending-mail.eml', documentId: null, + documentCount: 2, parsedDocumentCount: 1, candidateCount: 1, + customerName: null, poNumber: null, + }, + aggregateChildren: [recognizedLeaf, pendingLeaf], + }); + const wrapper = mount(ShippingConversationProcessingCard, { + props: { projection, workItems: [root], workbenchMode: true }, + global: { plugins: [i18n] }, + }); + await flushPromises(); + + const pendingRow = wrapper.get('[data-testid="shipping-processing-file-INTAKE:EML-PENDING-live-PLAN:EML-PENDING:missing.pdf"]'); + expect(pendingRow.text()).toContain('missing.pdf'); + expect(pendingRow.text()).toContain('待识别'); + expect(pendingRow.find('button').exists()).toBe(false); + }); + it('counts only stage-filtered EML leaves in the batch status heading', async () => { const projection = buildProjection(); setStatusGroup(projection, 'processing', [{ @@ -330,6 +375,91 @@ describe('ShippingConversationProcessingCard', () => { expect(wrapper.get('[data-testid="shipping-processing-group-processing"]').text()).not.toContain('2 个文件'); }); + it('keeps backend processing rows visible while matching work items are still unavailable', async () => { + const processingLeaf = buildWorkItem('DOCUMENT:610', { + sourceType: 'eml', rootOrderTaskNo: 'OT-PROCESSING-SNAPSHOT', + sourceSummary: { ...buildWorkItem('DOCUMENT:610').sourceSummary, documentId: 610, filename: 'processing.pdf' }, + uiState: { + status: 'running', stage: 'document_parsing', lifecycleStage: 'intake_parse', + lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [], + }, + }); + const projection = projectionWithGroups( + { total_tasks: 1, processing: 1, needs_action: 0, completed: 0, history: 0 }, + { + failed: [], waiting_human: [], + processing: [{ + user_task_no: 'OT-PROCESSING-SNAPSHOT', group: 'processing', status_label: 'processing', + title: 'processing.eml', file_count: 1, run_no: 'RUN-PROCESSING-SNAPSHOT', can_append: false, + aggregateChildren: [processingLeaf], + }], + completed: [], cancelled: [], archived: [], + }, + ); + const wrapper = mount(ShippingConversationProcessingCard, { + props: { projection, workItems: [], workbenchMode: true }, + global: { plugins: [i18n] }, + }); + await flushPromises(); + + // 状态分组先到达时,须以同次响应的叶子快照保留处理中附件。 + const group = wrapper.get('[data-testid="shipping-processing-group-processing"]'); + expect(group.text()).toContain('处理中 · 1 个文件'); + expect(group.text()).toContain('processing.pdf'); + }); + + it('shows a mixed-status EML once per PDF status without mixing completed files', async () => { + const completedLeaf = buildWorkItem('DOCUMENT:501', { + sourceType: 'eml', rootOrderTaskNo: 'OT-MIXED-STATUS', + sourceSummary: { ...buildWorkItem('DOCUMENT:501').sourceSummary, documentId: 501, filename: 'done.pdf' }, + uiState: { + status: 'completed', stage: 'completed', lifecycleStage: 'upload_complete', + lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [], + }, + }); + const processingLeaf = buildWorkItem('DOCUMENT:502', { + sourceType: 'eml', rootOrderTaskNo: 'OT-MIXED-STATUS', + sourceSummary: { ...buildWorkItem('DOCUMENT:502').sourceSummary, documentId: 502, filename: 'running.pdf' }, + uiState: { + status: 'running', stage: 'freight_upload', lifecycleStage: 'freight_upload', + lifecycleEntries: [], blocking_reason: null, primary_action: null, secondary_actions: [], + }, + }); + const root = buildWorkItem('INTAKE:MIXED-STATUS', { + sourceType: 'eml', rootOrderTaskNo: 'OT-MIXED-STATUS', + sourceSummary: { ...buildWorkItem('INTAKE:MIXED-STATUS').sourceSummary, filename: 'mixed.eml', documentId: null }, + aggregateChildren: [completedLeaf, processingLeaf], + }); + const task = { + user_task_no: 'OT-MIXED-STATUS', title: 'mixed.eml', file_count: 1, run_no: 'RUN-MIXED-STATUS', can_append: false, + aggregateSummary: { intakeNo: 'SNI-MIXED-STATUS', total: 2, in_group: 1 }, + }; + const wrapper = mount(ShippingConversationProcessingCard, { + props: { + projection: projectionWithGroups( + { total_tasks: 2, processing: 1, needs_action: 0, completed: 1, history: 0 }, + { + failed: [], waiting_human: [], + processing: [{ ...task, group: 'processing', status_label: 'processing', aggregateChildren: [processingLeaf] }], + completed: [{ ...task, group: 'completed', status_label: 'completed', aggregateChildren: [completedLeaf] }], + cancelled: [], archived: [], + }, + ), + workItems: [root], workbenchMode: true, + }, + global: { plugins: [i18n] }, + }); + await flushPromises(); + + expect(wrapper.get('[data-testid="shipping-processing-group-processing"]').text()).toContain('running.pdf'); + expect(wrapper.get('[data-testid="shipping-processing-group-processing"]').text()).not.toContain('done.pdf'); + expect(wrapper.get('[data-testid="shipping-processing-group-processing"]').text()).toContain('本组 1/共 2 个文件'); + await wrapper.get('[data-testid="shipping-processing-history-toggle"]').trigger('click'); + expect(wrapper.get('[data-testid="shipping-processing-history-completed"]').text()).toContain('done.pdf'); + expect(wrapper.get('[data-testid="shipping-processing-history-completed"]').text()).not.toContain('running.pdf'); + expect(wrapper.get('[data-testid="shipping-processing-history-completed"]').text()).toContain('本组 1/共 2 个文件'); + }); + it('keeps an EML attachment when it has a linked child order task', async () => { const projection = buildProjection(); setStatusGroup(projection, 'processing', [{ @@ -386,15 +516,15 @@ describe('ShippingConversationProcessingCard', () => { expect(wrapper.find('[data-testid="shipping-conversation-processing-card"]').exists()).toBe(true); expect(wrapper.find('[data-testid="shipping-processing-group-failed"]').exists()).toBe(true); expect(wrapper.find('[data-testid="shipping-processing-group-processing"]').exists()).toBe(true); - // 批次中心统一按文件计数;旧任务数文案不再是页面统计口径。 - expect(wrapper.text()).toContain('异常 · 0 个文件'); - expect(wrapper.text()).toContain('处理中 · 0 个文件'); + // 状态组与对话流一致,未展开附件时仍按后端 file_count 统计。 + expect(wrapper.text()).toContain('异常 · 2 个文件'); + expect(wrapper.text()).toContain('处理中 · 1 个文件'); expect(wrapper.text()).toContain('刚刚创建'); - // 处理记录默认折叠;标题 count = completed + history 返回条数。 + // 处理记录默认折叠;标题按文件数而非 EML / 任务行数统计。 const historyGroup = wrapper.find('[data-testid="shipping-processing-group-history"]'); expect(historyGroup.exists()).toBe(true); - expect(historyGroup.text()).toContain('处理记录 · 3'); + expect(historyGroup.text()).toContain('处理记录 · 3 个文件'); expect(wrapper.find('[data-testid="shipping-processing-history-body"]').exists()).toBe(false); expect(wrapper.find('[data-testid="shipping-processing-task-OT-DONE"]').exists()).toBe(false); expect(wrapper.find('[data-testid="shipping-processing-task-OT-HIST"]').exists()).toBe(false); @@ -464,7 +594,7 @@ describe('ShippingConversationProcessingCard', () => { const doneCard = wrapper.find('[data-testid="shipping-processing-task-OT-DONE"]'); expect(doneCard.find('[data-testid="sidebar-progress-inline"]').exists()).toBe(false); expect(doneCard.find('[data-testid="shipping-processing-task-actions"]').exists()).toBe(false); - expect(doneCard.find('[data-testid="shipping-processing-action-view_result"]').exists()).toBe(true); + expect(doneCard.find('[data-testid="shipping-processing-action-view_result"]').exists()).toBe(false); expect(doneCard.find('[data-testid="shipping-processing-action-cancel_task"]').exists()).toBe(false); }); @@ -490,11 +620,11 @@ describe('ShippingConversationProcessingCard', () => { global: { plugins: [i18n] }, }); await flushPromises(); - expect(wrapper.text()).toContain('订单识别任务'); + expect(wrapper.text()).toContain('本次订单文件处理'); expect(wrapper.text()).toContain('2 个 PDF'); expect(wrapper.text()).toContain('主文件:4518838152.pdf'); const titleEl = wrapper.find('[data-testid="shipping-processing-task-OT-MULTI"] .text-sm.font-semibold'); - expect(titleEl.text()).toContain('订单识别任务'); + expect(titleEl.text()).toContain('本次订单文件处理'); expect(titleEl.text()).not.toContain('4518838152.pdf'); // UI-02:有文件对象时不双开「查看详情」与「展开文件详情」。 @@ -554,14 +684,14 @@ describe('ShippingConversationProcessingCard', () => { global: { plugins: [i18n] }, }); await flushPromises(); - expect(wrapper.text()).toContain('订单识别任务'); + expect(wrapper.text()).toContain('本次订单文件处理'); expect(wrapper.text()).toContain('2 个 PDF'); const titleEl = wrapper.find('[data-testid="shipping-processing-task-OT-MULTI"] .text-sm.font-semibold'); - expect(titleEl.text()).toContain('订单识别任务'); + expect(titleEl.text()).toContain('本次订单文件处理'); expect(titleEl.text()).not.toContain('4518838152.pdf'); }); - it('uses unified order recognition title instead of internal OT number', async () => { + it('uses unified order file processing title instead of internal OT number', async () => { const wrapper = mount(ShippingConversationProcessingCard, { props: { projection: projectionWithGroups( @@ -580,7 +710,7 @@ describe('ShippingConversationProcessingCard', () => { global: { plugins: [i18n] }, }); await flushPromises(); - expect(wrapper.text()).toContain('订单识别任务'); + expect(wrapper.text()).toContain('本次订单文件处理'); expect(wrapper.text()).not.toContain('20260803-A13F95D2'); }); @@ -597,7 +727,7 @@ describe('ShippingConversationProcessingCard', () => { expect(wrapper.emitted('expandFiles')).toBeUndefined(); }); - it('opens local task details without emitting a viewed write event', async () => { + it('does not show a view-result action for completed records', async () => { const wrapper = mount(ShippingConversationProcessingCard, { props: { projection: { @@ -620,15 +750,87 @@ describe('ShippingConversationProcessingCard', () => { await wrapper.find('[data-testid="shipping-processing-history-toggle"]').trigger('click'); - await wrapper.find('[data-testid="shipping-processing-action-view_result"]').trigger('click'); - - expect(wrapper.emitted('taskAction')?.[0]?.[0]).toMatchObject({ - task: { user_task_no: 'OT-DETAIL' }, - action: 'view_result', - }); + expect(wrapper.find('[data-testid="shipping-processing-action-view_result"]').exists()).toBe(false); + expect(wrapper.emitted('taskAction')).toBeUndefined(); expect(wrapper.emitted('viewed')).toBeUndefined(); }); + it('marks an unrecognized Excel attachment as ignored but keeps a pending PDF recognizable', async () => { + const projection = buildProjection(); + setStatusGroup(projection, 'processing', [{ + user_task_no: 'INTAKE:EML-EXCEL', group: 'processing', status_label: 'extracting', + title: 'mail.eml', file_count: 2, run_no: 'RUN-EML-EXCEL', can_append: false, + aggregateChildren: [], + }]); + const pendingPdf = buildWorkItem('PLAN:EML-EXCEL:pending', { + workItemType: 'order_intake', sourceType: 'eml', rootOrderTaskNo: null, + sourceSummary: { emailSubject: null, filename: 'pending.pdf', documentId: null, documentCount: 0, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null }, + facts: { recognized: false, planState: 'selected_pending' }, uiState: undefined, + }); + const ignoredExcel = buildWorkItem('PLAN:EML-EXCEL:report', { + workItemType: 'order_intake', sourceType: 'eml', rootOrderTaskNo: null, + sourceSummary: { emailSubject: null, filename: 'report.xlsx', documentId: null, documentCount: 0, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null }, + facts: { recognized: false, planState: 'selected_pending' }, uiState: undefined, + }); + const root = buildWorkItem('INTAKE:EML-EXCEL', { + sourceType: 'eml', rootOrderTaskNo: 'OT-EML-EXCEL', + aggregateChildren: [pendingPdf, ignoredExcel], + }); + projection.status_groups!.processing![0]!.aggregateChildren = [pendingPdf, ignoredExcel]; + const wrapper = mount(ShippingConversationProcessingCard, { + props: { projection, workItems: [root], workbenchMode: true }, + global: { plugins: [i18n] }, + }); + await flushPromises(); + + const processingGroup = wrapper.get('[data-testid="shipping-processing-group-processing"]'); + expect(processingGroup.text()).toContain('pending.pdf'); + expect(processingGroup.text()).not.toContain('report.xlsx'); + expect(wrapper.get('[data-testid="shipping-processing-file-INTAKE:EML-EXCEL-live-PLAN:EML-EXCEL:pending"]').text()).toContain('待识别'); + const ignoredGroup = wrapper.get('[data-testid="shipping-processing-group-ignored"]'); + expect(ignoredGroup.text()).toContain('已忽略 · 1 个文件'); + expect(wrapper.find('[data-testid="shipping-processing-ignored-body"]').exists()).toBe(false); + await ignoredGroup.get('[data-testid="shipping-processing-ignored-toggle"]').trigger('click'); + const excelRow = ignoredGroup.get('[data-testid="shipping-processing-file-INTAKE:EML-EXCEL-live-PLAN:EML-EXCEL:report"]'); + expect(excelRow.text()).toContain('已忽略'); + expect(excelRow.text()).not.toContain('待识别'); + }); + + it('keeps an ignored Excel row when its EML parent originates from completed', async () => { + const ignoredExcel = buildWorkItem('PLAN:EML-COMPLETED:report', { + workItemType: 'order_intake', sourceType: 'eml', rootOrderTaskNo: null, + sourceSummary: { emailSubject: null, filename: 'report.xlsx', documentId: null, documentCount: 0, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null }, + facts: { recognized: false, planState: 'selected_pending' }, uiState: undefined, + }); + const root = buildWorkItem('INTAKE:EML-COMPLETED', { + sourceType: 'eml', rootOrderTaskNo: 'OT-EML-COMPLETED', + aggregateChildren: [ignoredExcel], + }); + const projection = projectionWithGroups( + { total_tasks: 1, processing: 0, needs_action: 0, completed: 1, history: 0 }, + { + failed: [], waiting_human: [], processing: [], + completed: [{ + user_task_no: 'INTAKE:EML-COMPLETED', group: 'completed', status_label: 'completed', + title: 'mail.eml', file_count: 1, run_no: 'RUN-EML-COMPLETED', can_append: false, + aggregateChildren: [ignoredExcel], + }], + cancelled: [], archived: [], + }, + ); + const wrapper = mount(ShippingConversationProcessingCard, { + props: { projection, workItems: [root], workbenchMode: true }, + global: { plugins: [i18n] }, + }); + await flushPromises(); + + const ignoredGroup = wrapper.get('[data-testid="shipping-processing-group-ignored"]'); + expect(ignoredGroup.text()).toContain('已忽略 · 1 个文件'); + expect(wrapper.find('[data-testid="shipping-processing-ignored-body"]').exists()).toBe(false); + await ignoredGroup.get('[data-testid="shipping-processing-ignored-toggle"]').trigger('click'); + expect(ignoredGroup.get('[data-testid="shipping-processing-file-INTAKE:EML-COMPLETED-live-PLAN:EML-COMPLETED:report"]').text()).toContain('report.xlsx'); + }); + it('applies visible focus ring on needs_action card when focused', async () => { const wrapper = mount(ShippingConversationProcessingCard, { props: { @@ -800,7 +1002,7 @@ describe('ShippingConversationProcessingCard', () => { expect(wrapper.findAll('[data-testid="sidebar-progress-inline"]')).toHaveLength(2); expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]').text()).toContain('待人工处理'); - expect(wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]').text()).toContain('库存匹配'); + expect(wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]').text()).toContain('通知准备'); expect(wrapper.findAll('[data-testid="shipping-processing-task-actions"]')).toHaveLength(0); const task = wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]'); expect(task.find('[data-testid="unified-action-primary"]').exists()).toBe(true); diff --git a/frontend/src/features/chat/components/shipping/ShippingOrderExtractionCard.spec.ts b/frontend/src/features/chat/components/shipping/ShippingOrderExtractionCard.spec.ts index b7ebe7da..c48c74fe 100644 --- a/frontend/src/features/chat/components/shipping/ShippingOrderExtractionCard.spec.ts +++ b/frontend/src/features/chat/components/shipping/ShippingOrderExtractionCard.spec.ts @@ -183,7 +183,7 @@ describe('ShippingOrderExtractionCard', () => { // 旧快照缺少会话级用户状态;candidate_ready 只能作为附件阶段,不能升格为顶层分组。 expect(wrapper.text()).toContain('共 3 个文件'); - expect(wrapper.text()).toContain('0/3 已处理'); + expect(wrapper.text()).not.toContain('已处理'); expect(wrapper.text()).not.toContain('已生成候选 3 个文件'); expect(wrapper.text()).toContain('4210020274.pdf'); expect(wrapper.text()).not.toContain('23/20 已处理'); @@ -300,12 +300,52 @@ describe('ShippingOrderExtractionCard', () => { await wrapper.get('[data-testid="shipping-order-extraction-eml-failed-INTAKE:SNI-DETAIL"] button').trigger('click'); expect(wrapper.get('[data-testid="shipping-order-extraction-eml-children"]').text()).toContain('failed.pdf'); expect(wrapper.text()).toContain('异常 1'); - expect(wrapper.text()).toContain('当前步骤需要人工处理'); + // 通用兜底原因(当前步骤需要人工处理)与右侧状态芯片语义重复,统一隐藏。 + expect(wrapper.text()).not.toContain('当前步骤需要人工处理'); expect(wrapper.text()).not.toContain('PARSE_FAILED'); expect(wrapper.get('[data-testid="shipping-order-extraction-child-status-OT-CHILD-1"]') .classes()).toContain('text-rose-600'); }); + it('splits a mixed-status EML into its matching status sections', async () => { + const completedA = { + workItemNo: 'DOCUMENT:4210022658', sourceSummary: { filename: '4210022658.pdf', documentId: 2658 }, + userStatus: 'completed', status: 'completed', uiState: { status: 'completed', stage: 'completed' }, + } as any; + const completedB = { + workItemNo: 'DOCUMENT:4210022657', sourceSummary: { filename: '4210022657.pdf', documentId: 2657 }, + userStatus: 'completed', status: 'completed', uiState: { status: 'completed', stage: 'completed' }, + } as any; + const processing = { + workItemNo: 'DOCUMENT:4210022656', sourceSummary: { filename: '4210022656.pdf', documentId: 2656 }, + userStatus: 'running', status: 'processing', uiState: { status: 'processing', stage: 'freight_upload' }, + } as any; + // 模拟热更新前/兼容后端仍把三份 PDF 放在 completed EML 根行的真实输入。 + const mixedTask = { + user_task_no: 'INTAKE:SNI-HOXIN', title: 'NEW PO HOXIN.eml', file_count: 3, + userGroup: 'completed', group: 'completed', + aggregateChildren: [completedA, completedB, processing], + aggregateSummary: { intakeNo: 'SNI-HOXIN', total: 3, completed: 2, processing: 1, needsAction: 0, failed: 0, stages: [], reasonCodes: [] }, + } as any; + const wrapper = mount(ShippingOrderExtractionCard, { + props: { state: buildState() }, + global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { + processing: ref({ status_groups: { failed: [], waiting_human: [], processing: [], completed: [mixedTask], cancelled: [], archived: [] } }), + processingWorkItems: ref([]), + } } }, + }); + + const completedSection = wrapper.findAll('[data-testid="shipping-order-extraction-status-groups"] section') + .find((section) => section.text().includes('已完成'))!; + await completedSection.get('button').trigger('click'); + await wrapper.get('[data-testid="shipping-order-extraction-eml-completed-INTAKE:SNI-HOXIN"] button').trigger('click'); + + expect(wrapper.get('[data-testid="shipping-order-extraction-eml-completed-INTAKE:SNI-HOXIN"]').text()).toContain('2 个文件'); + expect(wrapper.get('[data-testid="shipping-order-extraction-eml-completed-INTAKE:SNI-HOXIN"]').text()).toContain('4210022658.pdf'); + expect(wrapper.get('[data-testid="shipping-order-extraction-eml-completed-INTAKE:SNI-HOXIN"]').text()).not.toContain('4210022656.pdf'); + expect(wrapper.get('[data-testid="shipping-order-extraction-eml-processing-INTAKE:SNI-HOXIN"]').text()).toContain('4210022656.pdf'); + }); + it('does not supplement an authoritative EML group from a second work-item snapshot', async () => { const child = { workItemType: 'order_task', workItemNo: 'OT-FALLBACK-1', sourceType: 'eml', rootOrderTaskNo: 'OT-FALLBACK', @@ -347,8 +387,8 @@ describe('ShippingOrderExtractionCard', () => { }); expect(wrapper.text()).toContain('共 2 个文件'); - // 关键断言:待人工处理不是完成,聊天摘要必须与批次中心 completed_files 同口径。 - expect(wrapper.text()).toContain('0/2 已处理'); + // 关键断言:待人工处理不是完成,头部按状态计数显示"待人工",不显示完成的"已处理"。 + expect(wrapper.text()).toContain('待人工 2'); expect(wrapper.text()).not.toContain('共 6 个文件'); expect(wrapper.text()).not.toContain('stale.pdf'); }); @@ -407,7 +447,7 @@ describe('ShippingOrderExtractionCard', () => { // 关键断言:有权威会话投影时,只能显示附件总数,禁止回退历史邮件任务数。 expect(wrapper.text()).toContain('共 30 个文件'); - expect(wrapper.text()).toContain('0/30 已处理'); + expect(wrapper.text()).toContain('待人工 30'); expect(wrapper.text()).not.toContain('共 18 个文件'); }); @@ -419,7 +459,8 @@ describe('ShippingOrderExtractionCard', () => { props: { state: buildState(), runNo: 'SNER-COUNT' }, global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processing: ref({ status_groups: { failed: [], waiting_human: [], processing: [task], completed: [], cancelled: [], archived: [] } }), processingWorkItems: ref([]) } } }, }); - expect(wrapper.text()).toContain('2 个文件'); + // 状态分组标题必须按两个 PDF 附件计数,不能按一个 EML 容器计为“1 个任务”。 + expect(wrapper.get('[data-testid="shipping-order-extraction-status-groups"]').text()).toContain('系统处理中 · 2 个文件'); }); it('renders every projected file when the batch has two documents', () => { @@ -598,7 +639,7 @@ describe('ShippingOrderExtractionCard', () => { global: { plugins: [i18n] }, }); // 关键断言:对话卡只保留摘要标题与系统处理中状态。 - expect(wrapper.text()).toContain('订单识别任务'); + expect(wrapper.text()).toContain('本次订单文件处理'); expect(wrapper.text()).toContain('3 个文件'); expect(wrapper.text()).toContain('系统处理中'); expect(wrapper.text()).toContain('处理时间偏长'); @@ -612,6 +653,21 @@ describe('ShippingOrderExtractionCard', () => { expect(wrapper.findAll('[data-testid="shipping-order-document-result"]').length).toBe(0); }, 30_000); + it('keeps file row copy identical when routed through the shared stage key', () => { + const wrapper = mount(ShippingOrderExtractionCard, { + props: { + state: buildState({ + documents: [ + { unitId: 21, documentId: 21, intakeId: 21, documentType: 'attachment', fileName: 'layout.pdf', status: 'processing', userVisibleStage: 'layout_parsing_started' }, + ], + }), + }, + global: { plugins: [i18n] }, + }); + // 输出不变契约:rowStatusLabel 改走共享 key 出口后,文案仍为 UserStage 短语。 + expect(wrapper.text()).toContain('正在解析版面'); + }, 30_000); + it('renders duplicate-linked notice when only open_existing results remain', () => { const wrapper = mount(ShippingOrderExtractionCard, { props: { @@ -635,7 +691,7 @@ describe('ShippingOrderExtractionCard', () => { }, global: { plugins: [i18n] }, }); - expect(wrapper.text()).toContain('订单识别任务'); + expect(wrapper.text()).toContain('本次订单文件处理'); expect(wrapper.text()).toContain('已关联已有任务'); expect(wrapper.text()).not.toContain('需人工处理'); }); @@ -876,4 +932,237 @@ describe('ShippingOrderExtractionCard', () => { expect(details.exists()).toBe(false); expect(wrapper.findAll('[data-testid="shipping-order-extraction-primary-action"]').length).toBe(0); }); + + it('uses the submitted_files (batch-size) count for the header chip, not the recognized total', () => { + // [回归] 提交基主计数 submitted_files=1 优先于已识别 total_files=3 作为「共 N 个文件」。 + const wrapper = mount(ShippingOrderExtractionCard, { + props: { state: buildState() }, + global: { + plugins: [i18n], + provide: { + [SHIPPING_WORKFLOW_KEY as symbol]: { + processing: ref({ + ui_state: { status: 'running' }, + summary: { total_files: 3, submitted_files: 1 }, + status_groups: { + failed: [], waiting_human: [], processing: [ + { user_task_no: 'INTAKE:SNI-BATCH', title: 'batch.eml', file_count: 3, + userGroup: 'processing', group: 'processing', aggregateChildren: [] }, + ], completed: [], cancelled: [], archived: [], + }, + }), + processingWorkItems: ref([]), + }, + }, + }, + }); + expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true); + expect(wrapper.text()).toContain('共 1 个文件'); + }); + + it('shows the recognized count inside the file-count chip during the pre-materialization window', () => { + // [回归] 识别进度必须与「共 N 个文件」同一标签展示,不能单独占一行。 + const wrapper = mount(ShippingOrderExtractionCard, { + props: { state: buildState() }, + global: { + plugins: [i18n], + provide: { + [SHIPPING_WORKFLOW_KEY as symbol]: { + processing: ref({ + ui_state: { status: 'running' }, + summary: { total_files: 0, submitted_files: 1 }, + status_groups: { + failed: [], waiting_human: [], processing: [], completed: [], cancelled: [], archived: [], + }, + }), + processingWorkItems: ref([]), + }, + }, + }, + }); + expect(wrapper.get('[data-testid="shipping-order-extraction-recognizing-placeholder"]').text()).toContain('正在识别附件'); + expect(wrapper.text()).toContain('共 1 个文件 · 已识别 0/1'); + expect(wrapper.find('[data-testid="shipping-order-extraction-recognized-hint"]').exists()).toBe(false); + }); + + it('renders an unrecognized plan attachment as a distinct pending row inside the EML task', async () => { + // [回归] 批次「已识别 1/2」时 EML 列表须展示全部计划附件(含未识别行), + // 未识别行标记为「待识别」,便于排查「为什么这份没识别」。 + const wrapper = mount(ShippingOrderExtractionCard, { + props: { state: buildState() }, + global: { + plugins: [i18n], + provide: { + [SHIPPING_WORKFLOW_KEY as symbol]: { + processing: ref({ + ui_state: { status: 'running' }, + summary: { total_files: 1, submitted_files: 2 }, + status_groups: { + failed: [], waiting_human: [], processing: [{ + user_task_no: 'INTAKE:SNI-UNRECOGNIZED', title: 'batch.eml', file_count: 2, + userGroup: 'processing', group: 'processing', + aggregateChildren: [ + { + workItemNo: 'DOC-10', sourceType: 'eml', intakeNo: 'SNI-UNRECOGNIZED', + sourceSummary: { filename: 'F91D1.pdf', documentId: 10 }, + userStatus: 'waiting_human', userStage: 'order_review', status: 'waiting_human', + }, + { + workItemNo: 'PLAN:SNI-UNRECOGNIZED:f92', sourceType: 'eml', intakeNo: 'SNI-UNRECOGNIZED', + sourceSummary: { filename: 'F92.pdf' }, + userStatus: 'processing', userStage: 'intake_parse', status: 'processing', + facts: { recognized: false, planState: 'selected_pending' }, + }, + ], + }], completed: [], cancelled: [], archived: [], + }, + }), + processingWorkItems: ref([]), + }, + }, + }, + }); + await wrapper.get('[data-testid="shipping-order-extraction-eml-processing-INTAKE:SNI-UNRECOGNIZED"] button').trigger('click'); + const status = wrapper.find('[data-testid="shipping-order-extraction-child-status-PLAN:SNI-UNRECOGNIZED:f92"]'); + expect(status.exists()).toBe(true); + expect(status.text()).toContain('待识别'); + expect(wrapper.text()).toContain('F92.pdf'); + expect(wrapper.text()).toContain('尚未识别'); + }); + + it('marks unrecognized Excel attachments as ignored instead of pending recognition', async () => { + const wrapper = mount(ShippingOrderExtractionCard, { + props: { state: buildState() }, + global: { + plugins: [i18n], + provide: { + [SHIPPING_WORKFLOW_KEY as symbol]: { + processing: ref({ + ui_state: { status: 'running' }, + summary: { total_files: 1, submitted_files: 2 }, + status_groups: { + failed: [], waiting_human: [], processing: [{ + user_task_no: 'INTAKE:SNI-EXCEL', title: 'batch.eml', file_count: 2, + userGroup: 'processing', group: 'processing', + aggregateChildren: [ + { + workItemNo: 'DOC-11', sourceType: 'eml', intakeNo: 'SNI-EXCEL', + sourceSummary: { filename: 'order.pdf', documentId: 11 }, + userStatus: 'processing', userStage: 'intake_parse', status: 'processing', + }, + { + workItemNo: 'PLAN:SNI-EXCEL:report', sourceType: 'eml', intakeNo: 'SNI-EXCEL', + sourceSummary: { filename: 'report.xlsx' }, + userStatus: 'processing', userStage: 'intake_parse', status: 'processing', + facts: { recognized: false, planState: 'selected_pending' }, + }, + ], + }], completed: [], cancelled: [], archived: [], + }, + }), + processingWorkItems: ref([]), + }, + }, + }, + }); + await wrapper.get('[data-testid="shipping-order-extraction-eml-processing-INTAKE:SNI-EXCEL"] button').trigger('click'); + + const processingCard = wrapper.get('[data-testid="shipping-order-extraction-eml-processing-INTAKE:SNI-EXCEL"]'); + expect(processingCard.text()).toContain('order.pdf'); + expect(processingCard.text()).not.toContain('report.xlsx'); + expect(wrapper.find('[data-testid="shipping-order-extraction-eml-ignored-INTAKE:SNI-EXCEL"]').exists()).toBe(false); + const ignoredSection = wrapper.findAll('[data-testid="shipping-order-extraction-status-groups"] section') + .find((section) => section.text().includes('已忽略'))!; + await ignoredSection.get('button').trigger('click'); + const ignoredCard = wrapper.get('[data-testid="shipping-order-extraction-eml-ignored-INTAKE:SNI-EXCEL"]'); + const status = ignoredCard.get('[data-testid="shipping-order-extraction-child-status-PLAN:SNI-EXCEL:report"]'); + expect(status.text()).toContain('已忽略'); + expect(ignoredCard.text()).toContain('非订单 PDF,不参与订单识别'); + expect(status.text()).not.toContain('待识别'); + }); + + it('completes the header when only ignored Excel attachments remain', () => { + const completedPdf = { + workItemNo: 'DOC-COMPLETED', sourceType: 'eml', intakeNo: 'SNI-HEADER-COMPLETE', + sourceSummary: { filename: 'order.pdf', documentId: 12 }, + userStatus: 'completed', userStage: 'intake_parse', status: 'completed', + }; + const ignoredExcel = { + workItemNo: 'PLAN:SNI-HEADER-COMPLETE:excel', sourceType: 'eml', intakeNo: 'SNI-HEADER-COMPLETE', + sourceSummary: { filename: 'PO_INFO.xlsx' }, + userStatus: 'processing', userStage: 'intake_parse', status: 'processing', + facts: { recognized: false, planState: 'selected_pending' }, + }; + const task = (children: unknown[]) => ({ + user_task_no: 'INTAKE:SNI-HEADER-COMPLETE', title: 'batch.eml', file_count: 1, + userGroup: 'processing', group: 'processing', aggregateChildren: children, + }); + const wrapper = mount(ShippingOrderExtractionCard, { + props: { state: buildState() }, + global: { + plugins: [i18n], + provide: { + [SHIPPING_WORKFLOW_KEY as symbol]: { + processing: ref({ + ui_state: { status: 'running', lifecycleStage: 'intake_parse' }, + summary: { total_files: 1, submitted_files: 2 }, + status_groups: { + failed: [], waiting_human: [], processing: [task([ignoredExcel])], + completed: [task([completedPdf])], cancelled: [], archived: [], + }, + }), + processingWorkItems: ref([]), + }, + }, + }, + }); + + expect(wrapper.text()).toContain('本次订单文件处理'); + expect(wrapper.text()).toContain('订单文件 1 个已完成 · 1 个已忽略'); + expect(wrapper.text()).toContain('处理完成'); + expect(wrapper.text()).not.toContain('系统处理中'); + expect(wrapper.text()).not.toContain('当前阶段:'); + expect(wrapper.findAll('.animate-spin')).toHaveLength(0); + }); + + it('keeps the header processing when an unrecognized PDF remains', () => { + const unrecognizedPdf = { + workItemNo: 'PLAN:SNI-HEADER-PENDING:pdf', sourceType: 'eml', intakeNo: 'SNI-HEADER-PENDING', + sourceSummary: { filename: 'PO_INFO.pdf' }, + userStatus: 'processing', userStage: 'intake_parse', status: 'processing', + facts: { recognized: false, planState: 'selected_pending' }, + }; + const ignoredExcel = { + workItemNo: 'PLAN:SNI-HEADER-PENDING:excel', sourceType: 'eml', intakeNo: 'SNI-HEADER-PENDING', + sourceSummary: { filename: 'PO_INFO.xlsx' }, + userStatus: 'processing', userStage: 'intake_parse', status: 'processing', + facts: { recognized: false, planState: 'selected_pending' }, + }; + const wrapper = mount(ShippingOrderExtractionCard, { + props: { state: buildState() }, + global: { + plugins: [i18n], + provide: { + [SHIPPING_WORKFLOW_KEY as symbol]: { + processing: ref({ + ui_state: { status: 'running', lifecycleStage: 'intake_parse' }, + summary: { total_files: 1, submitted_files: 2 }, + status_groups: { + failed: [], waiting_human: [], processing: [{ + user_task_no: 'INTAKE:SNI-HEADER-PENDING', title: 'batch.eml', file_count: 1, + userGroup: 'processing', group: 'processing', aggregateChildren: [unrecognizedPdf, ignoredExcel], + }], completed: [], cancelled: [], archived: [], + }, + }), + processingWorkItems: ref([]), + }, + }, + }, + }); + + expect(wrapper.text()).toContain('系统处理中'); + expect(wrapper.text()).toContain('共 2 个文件 · 已识别 1/2 · 1 个已忽略'); + expect(wrapper.text()).not.toContain('当前阶段:'); + expect(wrapper.findAll('.animate-spin')).toHaveLength(1); + }); }); diff --git a/frontend/src/features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts b/frontend/src/features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts index f1d16eda..6b655990 100644 --- a/frontend/src/features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts +++ b/frontend/src/features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts @@ -143,12 +143,41 @@ describe('ShippingWorkflowTimeline', () => { expect(progress.text()).toContain('货代上传'); expect(progress.findAll('button')).toHaveLength(5); const upload = wrapper.get('[data-testid="shipping-workflow-stage-filter-freight_upload"]'); - // 五阶段卡仅保留阶段名和后端统计数量,状态由卡片样式表达。 - expect(upload.text()).toBe('货代上传1'); + // 阶段摘要以服务端计数的最高关注状态呈现,而非仅显示文件数量。 + expect(upload.text()).toBe('货代上传1 待处理'); await upload.trigger('click'); expect(wrapper.find('[data-testid="shipping-workflow-download-toolbar"]').exists()).toBe(true); }); + it('separates ignored Excel attachments from order-file progress totals', async () => { + const ignoredExcel = fileProjection({ + workItemNo: 'PLAN:EML-EXCEL:report', + sourceType: 'eml', + sourceSummary: { + emailSubject: null, filename: 'report.xlsx', documentId: null, documentCount: 0, + parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null, + }, + facts: { recognized: false }, + }); + const task = { + user_task_no: 'INTAKE:EML-EXCEL', group: 'processing', status_label: 'extracting', title: 'mail.eml', + display_kind: 'aggregate', document_names: ['order.pdf', 'report.xlsx'], file_count: 2, + run_no: 'RUN-EML-EXCEL', can_append: false, aggregateChildren: [ignoredExcel], + }; + const processing = processingProjection({ + summary: { + total_tasks: 1, total_files: 5, submitted_files: 6, processing: 1, needs_action: 1, + completed: 3, history: 0, processing_files: 1, completed_files: 3, waiting_human_files: 1, failed_files: 0, + }, + status_groups: { failed: [], waiting_human: [], processing: [task], completed: [], cancelled: [], archived: [] }, + } as Partial); + const wrapper = mountTimeline(processing, [ignoredExcel]); + await flushPromises(); + + expect(wrapper.get('[data-testid="shipping-workflow-overview"]').text()).toContain('已忽略1'); + expect(wrapper.get('[data-testid="shipping-workflow-overview-progress"]').text()).toContain('3/5 个订单文件已处理 · 1 个文件已忽略'); + }); + it('removes the obsolete file-detail drawer and expand entry from batch workbench', async () => { const wrapper = mountTimeline(processingProjection(), [fileProjection()]); await flushPromises(); diff --git a/frontend/src/features/chat/shipping/normalizeShippingProcessing.spec.ts b/frontend/src/features/chat/shipping/normalizeShippingProcessing.spec.ts index 9c2f3c3e..4f9674c6 100644 --- a/frontend/src/features/chat/shipping/normalizeShippingProcessing.spec.ts +++ b/frontend/src/features/chat/shipping/normalizeShippingProcessing.spec.ts @@ -108,6 +108,20 @@ describe('normalizeShippingProcessingProjection', () => { expect(normalized?.stageNodes?.[1]?.absoluteIndex).toBe(2); }); + it('normalizes the EML status-partition file count', () => { + const normalized = normalizeShippingProcessingProjection({ + work_item_no: 'INTAKE:SNI-EML', + work_item_type: 'order_task', + aggregate_summary: { + intake_no: 'SNI-EML', total: 3, in_group: 2, + }, + }); + + expect(normalized?.aggregateSummary).toMatchObject({ + intakeNo: 'SNI-EML', total: 3, inGroup: 2, + }); + }); + it('保留后端五阶段生命周期入口,包括 freight_upload', () => { const normalized = normalizeShippingProcessingProjection({ work_item_no: 'OT-LIFECYCLE-5', diff --git a/frontend/src/features/chat/shipping/orderExtractionProgressDisplay.spec.ts b/frontend/src/features/chat/shipping/orderExtractionProgressDisplay.spec.ts index a21da2db..33d45f1d 100644 --- a/frontend/src/features/chat/shipping/orderExtractionProgressDisplay.spec.ts +++ b/frontend/src/features/chat/shipping/orderExtractionProgressDisplay.spec.ts @@ -7,6 +7,7 @@ import { describe, expect, it } from 'vitest'; import { formatOrderExtractionElapsed, + resolveOrderExtractionRunStageKey, resolveOrderExtractionUserStageKey, } from './orderExtractionProgressDisplay'; @@ -27,3 +28,18 @@ describe('orderExtractionProgressDisplay', () => { ); }); }); + +describe('resolveOrderExtractionRunStageKey(v2 输出不变契约)', () => { + it('与改造前页面内联字面量逐字一致', () => { + // 关键断言:有 stage → UserStage key(与原 `chat.shippingOrderExtractionUserStage.${stage}` 完全一致) + expect(resolveOrderExtractionRunStageKey('layout_parsing_started', 'processing')) + .toBe('chat.shippingOrderExtractionUserStage.layout_parsing_started'); + expect(resolveOrderExtractionRunStageKey('review_required', 'review_required')) + .toBe('chat.shippingOrderExtractionUserStage.review_required'); + // 关键断言:无 stage → CardTitle key(与原 `chat.shippingOrderExtractionCardTitle.${status}` 完全一致) + expect(resolveOrderExtractionRunStageKey(null, 'completed')) + .toBe('chat.shippingOrderExtractionCardTitle.completed'); + expect(resolveOrderExtractionRunStageKey(undefined, 'failed')) + .toBe('chat.shippingOrderExtractionCardTitle.failed'); + }); +}); diff --git a/frontend/src/features/chat/shipping/shippingProcessingLabels.spec.ts b/frontend/src/features/chat/shipping/shippingProcessingLabels.spec.ts index 62fee427..3d0088da 100644 --- a/frontend/src/features/chat/shipping/shippingProcessingLabels.spec.ts +++ b/frontend/src/features/chat/shipping/shippingProcessingLabels.spec.ts @@ -5,6 +5,10 @@ */ import { describe, expect, it } from 'vitest'; import { + extractExtractionProgressReasonCode, + isRedundantExtractionDetail, + resolveExtractionActivityMessage, + resolveRunLifecycleUserStatus, resolveShippingProcessingReasonLabel, resolveShippingProcessingMessage, resolveShippingProcessingStageLabel, @@ -73,3 +77,93 @@ describe('shippingProcessingLabels', () => { expect(resolveShippingProcessingMessage('groupNeedsAction', te, t, { count: 2 })).toBe('需要你处理 · 2'); }); }); + +describe('extraction lifecycle display (v2 状态展示统一)', () => { + const PROGRESS_TEXT: Record = { + 'chat.shippingProcessing.progress.step.document_queued': '正在等待解析任务启动', + 'chat.shippingProcessing.progress.systemProcessingNeed': '系统正在自动处理,请稍候或刷新进度', + 'chat.shippingProcessing.progress.lifecycleWaitingNeed': '当前步骤需要人工处理', + 'chat.shippingProcessing.progress.lifecycleReason.review_required': '当前结果需要人工复核。', + 'chat.shippingProcessing.progress.lifecycleReason.failed': '当前步骤处理失败,请查看详情后重试。', + 'chat.shippingProcessing.progress.lifecycleReason.cancelled': '本次处理已取消。', + 'chat.shippingProcessing.progress.lifecycleReason.queue_backlog': '当前步骤正在排队等待执行。', + 'chat.shippingProcessing.progress.lifecycleReason.processing_slow': '当前步骤耗时较长,系统仍在继续。', + }; + const te = (key: string) => key in PROGRESS_TEXT; + const t = (key: string) => PROGRESS_TEXT[key] ?? key; + const base = { lifecycle_stage: 'intake_parse', completed_step_codes: [], health_status: 'normal' }; + + it('extractExtractionProgressReasonCode 只取受控后缀,非模糊匹配', () => { + // 关键断言:末段解析;无 key 返回空串 + expect(extractExtractionProgressReasonCode({ + ...base, lifecycle_status: 'waiting', + blocking_reason_i18n_key: 'chat.shippingProcessing.progress.lifecycleReason.review_required', + } as any)).toBe('review_required'); + expect(extractExtractionProgressReasonCode({ ...base, lifecycle_status: 'waiting' } as any)).toBe(''); + expect(extractExtractionProgressReasonCode(null)).toBe(''); + }); + + it('resolveRunLifecycleUserStatus:running/waiting/failed 兑底,completed/cancelled/未知不映射', () => { + expect(resolveRunLifecycleUserStatus({ ...base, lifecycle_status: 'running' } as any)).toBe('running'); + expect(resolveRunLifecycleUserStatus({ + ...base, lifecycle_status: 'waiting', + blocking_reason_i18n_key: 'chat.shippingProcessing.progress.lifecycleReason.review_required', + } as any)).toBe('waiting_human'); + expect(resolveRunLifecycleUserStatus({ + ...base, lifecycle_status: 'waiting', + blocking_reason_i18n_key: 'chat.shippingProcessing.progress.lifecycleReason.queue_backlog', + } as any)).toBe('running'); + expect(resolveRunLifecycleUserStatus({ ...base, lifecycle_status: 'waiting' } as any)).toBeNull(); + expect(resolveRunLifecycleUserStatus({ ...base, lifecycle_status: 'failed' } as any)).toBe('failed'); + expect(resolveRunLifecycleUserStatus({ ...base, lifecycle_status: 'completed' } as any)).toBeNull(); + expect(resolveRunLifecycleUserStatus({ ...base, lifecycle_status: 'some_unknown' } as any)).toBeNull(); + expect(resolveRunLifecycleUserStatus(null)).toBeNull(); + }); + + it('resolveExtractionActivityMessage:running 取步骤句;waiting/failed/cancelled 只取原因句', () => { + // 关键断言:running + 步骤 → 步骤句 + expect(resolveExtractionActivityMessage({ + ...base, lifecycle_status: 'running', + current_step_i18n_key: 'chat.shippingProcessing.progress.step.document_queued', + } as any, { t, te })).toEqual({ text: '正在等待解析任务启动', running: true }); + // 关键断言:running 无步骤 → 通用处理中 + expect(resolveExtractionActivityMessage({ ...base, lifecycle_status: 'running' } as any, { t, te })) + .toEqual({ text: '系统正在自动处理,请稍候或刷新进度', running: true }); + // 关键断言:running + 诊断原因(processing_slow)→ 原因句优先于步骤句 + expect(resolveExtractionActivityMessage({ + ...base, lifecycle_status: 'running', + current_step_i18n_key: 'chat.shippingProcessing.progress.step.document_queued', + blocking_reason_i18n_key: 'chat.shippingProcessing.progress.lifecycleReason.processing_slow', + } as any, { t, te })).toEqual({ text: '当前步骤耗时较长,系统仍在继续。', running: true }); + // 关键断言:waiting → 原因句;无原因 → 中性等待(绝不复用 step 文案) + expect(resolveExtractionActivityMessage({ + ...base, lifecycle_status: 'waiting', + blocking_reason_i18n_key: 'chat.shippingProcessing.progress.lifecycleReason.review_required', + } as any, { t, te })).toEqual({ text: '当前结果需要人工复核。', running: false }); + expect(resolveExtractionActivityMessage({ ...base, lifecycle_status: 'waiting' } as any, { t, te })) + .toEqual({ text: '当前步骤需要人工处理', running: false }); + // 关键断言:failed/cancelled 文本强制来自原因 key,不复用 running 的 step 文案 + expect(resolveExtractionActivityMessage({ + ...base, lifecycle_status: 'failed', + current_step_i18n_key: 'chat.shippingProcessing.progress.step.document_queued', + } as any, { t, te })).toEqual({ text: '当前步骤处理失败,请查看详情后重试。', running: false }); + expect(resolveExtractionActivityMessage({ + ...base, lifecycle_status: 'cancelled', + current_step_i18n_key: 'chat.shippingProcessing.progress.step.document_queued', + } as any, { t, te })).toEqual({ text: '本次处理已取消。', running: false }); + // 白名单外一律 null + expect(resolveExtractionActivityMessage({ ...base, lifecycle_status: 'completed' } as any, { t, te })).toBeNull(); + expect(resolveExtractionActivityMessage({ ...base, lifecycle_status: 'weird_state' } as any, { t, te })).toBeNull(); + expect(resolveExtractionActivityMessage(null, { t, te })).toBeNull(); + }); + + it('isRedundantExtractionDetail:仅 review_required 且映射结果==当前状态才隐藏', () => { + expect(isRedundantExtractionDetail('review_required', 'waiting_human')).toBe(true); + expect(isRedundantExtractionDetail('review_required', 'running')).toBe(false); + expect(isRedundantExtractionDetail('queue_backlog', 'running')).toBe(false); + expect(isRedundantExtractionDetail('processing_slow', 'running')).toBe(false); + expect(isRedundantExtractionDetail('processing_attention', 'running')).toBe(false); + expect(isRedundantExtractionDetail('unknown_reason', 'waiting_human')).toBe(false); + expect(isRedundantExtractionDetail('', 'waiting_human')).toBe(false); + }); +});