diff --git a/.env.shared b/.env.shared index 397de76f..54be5454 100644 --- a/.env.shared +++ b/.env.shared @@ -152,6 +152,8 @@ SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED=true SHIPPING_NOTICE_WORKER_CONCURRENCY=2 # 通用 Job 回收阈值须高于版面 Worker 360 秒上限,避免并发 Worker 误回收正常长任务。 SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS=420 +# 资格达标后 waiting_to_start 且无 STP 入队记录的超时(秒);超时投影 manual_fallback。 +SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS=120 # 门禁 Attempt 租约 / 心跳 / 接管 / 技术重试(与 process_gate_job_service 默认一致)。 SHIPPING_PROCESS_GATE_LEASE_SECONDS=60 SHIPPING_PROCESS_GATE_HEARTBEAT_SECONDS=15 @@ -180,7 +182,12 @@ SHIPPING_NOTICE_PROFILE_AUTO_SELECTION_ENABLED=true SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED=true # XFA 数据路径 Profile(识别到 xfa_hybrid 即正式提取) SHIPPING_NOTICE_XFA_ENABLED=true -# 自动建单走 Schema auto_creation_policy / 统一 CQ;无独立 XFA_AUTO_CREATE 开关。 +# 独立自动建单总闸(阶段 5+);默认关。开启前须合成预览门禁 / CQ / 盲测 / 审计补偿就绪。 +SHIPPING_NOTICE_XFA_AUTO_CREATE_ENABLED=false +# 离线完整 flatten 引擎是否已交付;默认 false(禁 overlay/壳图充当图源)。 +SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY=false +# 自动建单硬前置:审计写失败补偿能力就绪前禁止开自动建单。 +SHIPPING_NOTICE_XFA_AUDIT_COMPENSATION_REQUIRED_FOR_AUTO_CREATE=true # shadow=true:完整解析与资格评估,但阻断真实自动建单(仅记录 would_auto_create) SHIPPING_NOTICE_XFA_SHADOW_MODE=false # 自动建单硬门禁白名单:客户或 Profile checksum 为空 → fail-closed diff --git a/backend/app/api/admin/shipping_order_document_profiles.py b/backend/app/api/admin/shipping_order_document_profiles.py index c5b3a181..5134a53c 100644 --- a/backend/app/api/admin/shipping_order_document_profiles.py +++ b/backend/app/api/admin/shipping_order_document_profiles.py @@ -3,10 +3,12 @@ backend/app/api/admin/shipping_order_document_profiles.py 用途:提供订单文档模板 Profile 的管理员版本治理 API。 依赖:admin blueprint、require_admin、order_document_profile_service、 - order_document_profile_visual_binding_service、order_profile_unified_migration。 -逻辑:路由只转换请求和操作者;版本、Schema、字段、统一迁移与发布门禁全部由服务层执行。 + order_document_profile_preview_service、order_document_profile_xfa_preview_service、 + order_document_profile_xfa_automark_service、order_document_profile_visual_binding_service、 + order_profile_unified_migration。 +逻辑:路由只转换请求和操作者;版本、Schema、字段、XFA 合成预览、OCR 自动标记、 + 统一迁移与发布门禁由服务层执行。 """ - from __future__ import annotations import io @@ -23,6 +25,8 @@ from app.services.shipping_notice import order_document_profile_diff as diff_ser from app.services.shipping_notice import order_document_profile_creation_service as creation_service from app.services.shipping_notice import order_document_profile_lease_service as lease_service from app.services.shipping_notice import order_document_profile_preview_service as preview_service +from app.services.shipping_notice import order_document_profile_xfa_preview_service as xfa_preview_service +from app.services.shipping_notice import order_document_profile_xfa_automark_service as xfa_automark_service from app.services.shipping_notice import order_document_profile_revision_service as revision_service from app.services.shipping_notice import order_document_profile_suggestion_service as suggestion_service from app.services.shipping_notice import order_document_profile_service as service @@ -798,6 +802,62 @@ def preview_order_document_profile_sample_xfa_value(document_id: int): )) +@admin_bp.route( + '/shipping-notice/order-document-profile-samples//xfa/preview', + methods=['POST'], +) +@require_admin +def request_order_document_profile_sample_xfa_synthetic_preview(document_id: int): + """ + 生成或复用绑定冻结 Analysis 的 XFA 合成预览,返回身份与页元数据(不含大图)。 + + 核心逻辑:委托 xfa_preview_service;可选 body.force=true 强制重生成。 + """ + data = request.get_json(silent=True) or {} + return _private_ok(xfa_preview_service.request_xfa_synthetic_preview( + document_id, + actor_id=_actor_id(), + force=bool(data.get('force')), + )) + + +@admin_bp.route( + '/shipping-notice/order-document-profile-samples//xfa/preview/pages', + methods=['GET'], +) +@require_admin +def list_order_document_profile_sample_xfa_synthetic_preview_pages(document_id: int): + """列出冻结 Analysis 绑定的最新 ready 合成预览页并签发短时 token。""" + return _private_ok(xfa_preview_service.list_xfa_synthetic_preview_pages( + document_id, + actor_id=_actor_id(), + )) + + +@admin_bp.route( + '/shipping-notice/order-document-profile-samples//xfa/preview/pages/', + methods=['GET'], +) +@require_admin +def get_order_document_profile_sample_xfa_synthetic_preview_page(document_id: int, page_no: int): + """ + 消费一次性授权并返回合成预览单页 PNG。 + + 核心逻辑:与既有 preview-pages 一致——query preview_token、private no-store。 + """ + image = xfa_preview_service.render_xfa_synthetic_preview_page( + document_id, + page_no=page_no, + token=str(request.args.get('preview_token') or ''), + actor_id=_actor_id(), + ) + response = send_file(io.BytesIO(image), mimetype='image/png', as_attachment=False, max_age=0) + response.headers['Cache-Control'] = 'private, no-store, max-age=0' + response.headers['Pragma'] = 'no-cache' + response.headers['X-Content-Type-Options'] = 'nosniff' + return response + + @admin_bp.route( '/shipping-notice/order-document-profile-samples//xfa/split-rules/preview', methods=['POST'], @@ -948,7 +1008,7 @@ def suggest_order_document_profile_xfa_visual_bindings(profile_id: int): ) @require_admin def confirm_order_document_profile_xfa_visual_binding(profile_id: int, binding_id: str): - """管理员确认视觉绑定;写 before/after 审计。""" + """管理员确认视觉绑定;须携带合成预览 checksum / render_mode;写 before/after 审计。""" data = request.get_json(silent=True) or {} ctx = _write_context(data) visual = data.get('visual_binding') if isinstance(data.get('visual_binding'), dict) else {} @@ -962,6 +1022,8 @@ def confirm_order_document_profile_xfa_visual_binding(profile_id: int, binding_i lease_token=ctx.get('lease_token'), operation_id=ctx.get('operation_id'), request_id=getattr(g, 'request_id', None), + preview_render_checksum=str(data.get('preview_render_checksum') or '').strip() or None, + render_mode=str(data.get('render_mode') or '').strip() or None, )) @@ -986,6 +1048,97 @@ def reject_order_document_profile_xfa_visual_binding(profile_id: int, binding_id )) +@admin_bp.route( + '/shipping-notice/order-document-profiles//xfa/automark', + methods=['POST'], +) +@require_admin +def enqueue_order_document_profile_xfa_ocr_automark(profile_id: int): + """ + 入队 XFA OCR 自动标记异步 Job。 + + 核心逻辑:body.document_id 必填;可选 force 强制重生成合成预览后入队。 + """ + data = request.get_json(silent=True) or {} + document_id = data.get('document_id') + if document_id in (None, ''): + raise ValidationError( + 'document_id is required', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', + ) + page_nos = data.get('page_nos') if isinstance(data.get('page_nos'), list) else None + return _private_ok(xfa_automark_service.enqueue_xfa_ocr_automark( + profile_id, + document_id=int(document_id), + actor_id=_actor_id(), + force=bool(data.get('force')), + page_nos=[int(item) for item in (page_nos or [])], + )) + + +@admin_bp.route( + '/shipping-notice/order-document-profiles//xfa/automark/jobs/', + methods=['GET'], +) +@require_admin +def get_order_document_profile_xfa_ocr_automark_job(profile_id: int, job_id: int): + """轮询 OCR 自动标记 Job 状态与建议列表。""" + return _private_ok(xfa_automark_service.get_xfa_ocr_automark_job( + job_id, + profile_id=profile_id, + )) + + +@admin_bp.route( + '/shipping-notice/order-document-profiles//xfa/automark/suggestions//accept', + methods=['POST'], +) +@require_admin +def accept_order_document_profile_xfa_automark_suggestion(profile_id: int, suggestion_id: str): + """ + 接受 OCR 自动标记建议。 + + 核心逻辑:high→confirmed(须 checksum);medium/low→suggested;mismatch 阻断。 + """ + data = request.get_json(silent=True) or {} + ctx = _write_context(data) + job_id = data.get('job_id') + return _private_ok(xfa_automark_service.accept_xfa_automark_suggestion( + profile_id, + suggestion_id, + actor_id=_actor_id(), + browser_session_id=ctx.get('browser_session_id'), + lease_token=ctx.get('lease_token'), + operation_id=ctx.get('operation_id'), + request_id=getattr(g, 'request_id', None), + job_id=int(job_id) if job_id not in (None, '') else None, + preview_render_checksum=str(data.get('preview_render_checksum') or '').strip() or None, + )) + + +@admin_bp.route( + '/shipping-notice/order-document-profiles//xfa/automark/suggestions//reject', + methods=['POST'], +) +@require_admin +def reject_order_document_profile_xfa_automark_suggestion(profile_id: int, suggestion_id: str): + """驳回 OCR 自动标记建议并减少 unresolved mismatch 计数。""" + data = request.get_json(silent=True) or {} + ctx = _write_context(data) + job_id = data.get('job_id') + return _private_ok(xfa_automark_service.reject_xfa_automark_suggestion( + profile_id, + suggestion_id, + actor_id=_actor_id(), + browser_session_id=ctx.get('browser_session_id'), + lease_token=ctx.get('lease_token'), + operation_id=ctx.get('operation_id'), + request_id=getattr(g, 'request_id', None), + reason_code=str(data.get('reason_code') or '').strip() or None, + job_id=int(job_id) if job_id not in (None, '') else None, + )) + + @admin_bp.route( '/shipping-notice/order-document-profiles//unified-migration/dry-run', methods=['POST'], diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index bd8415d0..f467d493 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -15,7 +15,7 @@ import uuid from io import BytesIO from typing import Any -from flask import Blueprint, g, request, send_file +from flask import Blueprint, current_app, g, request, send_file from app import db from app.core.auth.jwt import get_current_user @@ -28,6 +28,7 @@ from app.services.shipping_notice.constants import ( CP_EXPORT_GENERATED, CP_NOTICE_TEXT_EXTRACTION_FAILED, ) +from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership from app.services.shipping_notice.query_service import ( EXPORT_MIME_TYPE, count_my_todos, @@ -89,6 +90,35 @@ def _ok(payload: Any, *, status: int = 200): return ok(payload, request_id=getattr(g, 'request_id', None), status=status) +def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> None: + """ + 履约写接口:若请求携带期望 OT/Case/Run,校验与正式 Notice 归属一致。 + + 核心逻辑:委托 assert_notice_task_ownership;未携带期望字段时放行(兼容旧客户端)。 + + Args: + task: 已鉴权的 ShippingNotice。 + user_id: 当前用户 id。 + + Raises: + ConflictError: 归属不匹配。 + """ + data = request.get_json(silent=True) or {} + assert_notice_task_ownership( + task, + expected_order_task_no=( + str(data.get('expected_order_task_no') or data.get('order_task_no') or '').strip() or None + ), + expected_review_case_no=( + str(data.get('expected_review_case_no') or data.get('case_no') or '').strip() or None + ), + expected_run_no=( + str(data.get('expected_run_no') or data.get('run_no') or '').strip() or None + ), + actor_id=user_id, + ) + + @workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET']) def workspace_shipping_tasks(): """分页列出当前用户可见的发货任务,可按批次与处理状态过滤。""" @@ -950,6 +980,7 @@ def workspace_match_shipping_inventory(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') + _assert_fulfillment_task_ownership(task, user.id) from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint, human_options_for_checkpoint matched = shipping_tools.match_inventory({ @@ -993,6 +1024,7 @@ def workspace_generate_shipping_excel(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') + _assert_fulfillment_task_ownership(task, user.id) from app.services.shipping_notice import tools as shipping_tools result = shipping_tools.generate_excel({'task_id': task.task_no}) if isinstance(result, dict) and result.get('status') == 'ok': @@ -1015,6 +1047,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') + _assert_fulfillment_task_ownership(task, user.id) from app.services.shipping_notice import tools as shipping_tools data = request.get_json(silent=True) or {} payload = { @@ -1033,8 +1066,16 @@ def workspace_mark_manual_uploaded(task_no: str): @workspace_shipping_notice_bp.route('/shipping-tasks//retry-upload', methods=['POST']) def workspace_retry_shipping_upload(task_no: str): - """首期禁用货代 RPA 重试上传;引导用户改走人工凭据登记。""" - _require_user() + """ + 货代上传重试入口;首期若全局禁用 RPA 则返回明确错误码。 + + 核心逻辑:先做归属校验;若平台禁用 RPA 再抛 ValidationError,避免跳过归属门禁。 + """ + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + _assert_fulfillment_task_ownership(task, user.id) raise ValidationError( '首期不支持货代 RPA 上传重试。请下载 Excel,在货代系统人工上传后提交截图/PDF 凭据。', code='SHIPPING.FREIGHT_RPA_UPLOAD_DISABLED', @@ -1378,7 +1419,11 @@ def workspace_get_shipping_order_review_case(case_no: str): from app.services.shipping_notice.order_review_projection import serialize_review_case from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user - payload = serialize_review_case(get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin)) + # 只读:禁止在 GET 中入队 STP(入队仅抽取收尾 / resume / 显式 retry POST)。 + payload = serialize_review_case( + get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin), + is_admin=is_admin, + ) record_access_audit( action='view_order_review_case', aggregate_type='order_review_case', @@ -1390,6 +1435,26 @@ def workspace_get_shipping_order_review_case(case_no: str): return _ok(payload) +@workspace_shipping_notice_bp.route( + '/shipping-notice/order-review-cases//stp-auto-create/retry', + methods=['POST'], +) +def workspace_retry_shipping_order_stp_auto_create(case_no: str): + """ + 显式重试 STP 自动建单入队(failed / manual_fallback)。 + + 核心逻辑:委托 retry_stp_auto_create_for_case;成功返回 queued/reused+job_id; + 失败抛结构化业务错误,禁止伪装成功。 + """ + user = _require_user() + from app.services.shipping_notice.order_stp_auto_create_service import ( + retry_stp_auto_create_for_case, + ) + + result = retry_stp_auto_create_for_case(user_id=int(user.id), case_no=str(case_no)) + return _ok(result) + + @workspace_shipping_notice_bp.route( '/shipping-notice/order-review-cases//access/version-history', methods=['POST'], diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index dfd0f443..d47eafc6 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -173,6 +173,8 @@ class Config: REDIS_URL = os.getenv('REDIS_URL') # 订单文档模板预览默认要求 Redis;仅开发单进程 run.py 可显式放开进程内一次性令牌兜底。 ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK = False + # 默认禁止进程内 JTI;仅 Development/Testing 显式开启 + XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = False FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true' HR_WORKFLOW_IFRAME_URL = os.getenv('HR_WORKFLOW_IFRAME_URL') HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE') @@ -222,6 +224,10 @@ class Config: SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float( os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420') ) + # 资格达标后 waiting_to_start 且仍无 STP Job 的超时;超时投影为 manual_fallback。 + SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS = int( + os.getenv('SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS', '120') or '120' + ) SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true') SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true' # 订单解析主链开关:通用确定性解析 / 分路径自动冻结 / 模板自动采用 / LLM 辅助复核 / 全局紧急停止。 @@ -240,10 +246,22 @@ class Config: os.getenv('SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED', 'false').lower() == 'true' ) # XFA 数据路径 Profile:识别到 xfa_hybrid 即走 xfa_dataset。 - # 自动建单与坐标路径共用 Schema auto_creation_policy / CQ,无独立 XFA 自动建单开关。 + # 独立自动建单总闸(阶段 5+);默认关。开启前须满足合成预览门禁 / CQ / 盲测 / 审计补偿。 SHIPPING_NOTICE_XFA_ENABLED = ( os.getenv('SHIPPING_NOTICE_XFA_ENABLED', 'true').lower() == 'true' ) + SHIPPING_NOTICE_XFA_AUTO_CREATE_ENABLED = ( + os.getenv('SHIPPING_NOTICE_XFA_AUTO_CREATE_ENABLED', 'false').lower() == 'true' + ) + # 离线完整 flatten 引擎是否已交付并可返回 ready;默认 false(禁 overlay/壳图)。 + SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY = ( + os.getenv('SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY', 'false').lower() == 'true' + ) + # 自动建单硬前置:审计写失败补偿能力就绪前禁止开自动建单(阶段 6)。 + SHIPPING_NOTICE_XFA_AUDIT_COMPENSATION_REQUIRED_FOR_AUTO_CREATE = ( + os.getenv('SHIPPING_NOTICE_XFA_AUDIT_COMPENSATION_REQUIRED_FOR_AUTO_CREATE', 'true').lower() + == 'true' + ) SHIPPING_NOTICE_XFA_SHADOW_MODE = ( os.getenv('SHIPPING_NOTICE_XFA_SHADOW_MODE', 'false').lower() == 'true' ) @@ -612,11 +630,14 @@ class DevelopmentConfig(Config): # 本机常无 Redis:不强制 Redis,允许进程内存兜底心跳(单进程 run.py 可用) SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True + # XFA 拆分确认 JTI:仅单进程 development 允许内存消费;test/prod 多 Worker 必须 Redis + XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True class ProductionConfig(Config): DEBUG = False SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL') + XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = False class TestingConfig(Config): @@ -630,6 +651,8 @@ class TestingConfig(Config): ENV_NAME = 'dev' SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True + # pytest 单进程:允许内存 JTI;生产语义由 ProductionConfig 关闭 + XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True config = { diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py index 5621e3e1..37fc7377 100644 --- a/backend/app/jobs/handlers/__init__.py +++ b/backend/app/jobs/handlers/__init__.py @@ -15,5 +15,7 @@ from app.jobs.handlers import ( # noqa: F401 shipping_notice_run, shipping_order_extraction, shipping_process_gate, + shipping_stp_auto_create, + shipping_xfa_ocr_automark, wecom_directory_sync, ) diff --git a/backend/app/jobs/handlers/shipping_stp_auto_create.py b/backend/app/jobs/handlers/shipping_stp_auto_create.py new file mode 100644 index 00000000..71e50985 --- /dev/null +++ b/backend/app/jobs/handlers/shipping_stp_auto_create.py @@ -0,0 +1,46 @@ +""" +backend/app/jobs/handlers/shipping_stp_auto_create.py + +用途:消费 STP 自动建单 Job,执行 confirm_review_case 与确认后自动推进入队。 +依赖:JobContext、order_stp_auto_create_service.execute_stp_auto_create_job、 + jobs.queue finish/fail。 +逻辑:由 shipping worker 领取;幂等键保证同一 Case/draft 不重复建单; + 失败标记 Job failed,供 Projection 显示 retryable。 +""" + +from __future__ import annotations + +from app.jobs.context import JobContext +from app.jobs.queue import fail_job, finish_job +from app.jobs.registry import register_handler +from app.jobs.types import JobType +from app.services.shipping_notice.order_stp_auto_create_service import ( + execute_stp_auto_create_job, +) + + +@register_handler(JobType.SHIPPING_STP_AUTO_CREATE) +def handle_shipping_stp_auto_create(ctx: JobContext) -> None: + """ + 执行 STP 自动建单 Job。 + + 核心逻辑:委托 execute_stp_auto_create_job;成功 finish,业务拒绝/异常 fail。 + """ + payload = ctx.payload if isinstance(ctx.payload, dict) else {} + try: + result = execute_stp_auto_create_job(payload=payload, job_id=int(ctx.job_id)) + if result.get('ok'): + finish_job(int(ctx.job_id), message=str(result.get('message') or 'STP 自动建单完成')) + return + fail_job( + int(ctx.job_id), + error_code=str(result.get('error_code') or 'STP_AUTO_CREATE_FAILED'), + message=str(result.get('message') or 'STP 自动建单失败'), + ) + except Exception as exc: # noqa: BLE001 + fail_job( + int(ctx.job_id), + error_code='STP_AUTO_CREATE_EXCEPTION', + message=str(exc)[:500], + ) + raise diff --git a/backend/app/jobs/handlers/shipping_xfa_ocr_automark.py b/backend/app/jobs/handlers/shipping_xfa_ocr_automark.py new file mode 100644 index 00000000..3152577f --- /dev/null +++ b/backend/app/jobs/handlers/shipping_xfa_ocr_automark.py @@ -0,0 +1,82 @@ +""" +backend/app/jobs/handlers/shipping_xfa_ocr_automark.py + +用途:异步执行 XFA OCR 自动标记(原生 PDF/PDFium 页图),产出 suggested visual_bindings(不自动 confirmed)。 +依赖:Job queue、order_document_profile_xfa_automark_service(执行体)、JobType。 +逻辑:由 shipping worker 领取;payload 含 profile_id/document_id/preview_render_checksum; + 不再依赖 /xfa/preview synthetic;空白壳返回空建议成功;OCR 不可用时 fail_job。 +""" + +from __future__ import annotations + +from app.extensions import db +from app.jobs.context import JobContext +from app.jobs.queue import fail_job, finish_job +from app.jobs.registry import register_handler +from app.jobs.types import JobType +from app.models import Job + + +@register_handler(JobType.SHIPPING_XFA_OCR_AUTOMARK) +def run_shipping_xfa_ocr_automark(ctx: JobContext, payload: dict) -> None: + """ + 执行 XFA OCR 自动标记 Job。 + + 核心逻辑:读取冻结 Job 载荷 → 委托 automark_service.execute_xfa_ocr_automark_job → + finish/fail。OCR 引擎不可用时不可重试(明确业务码)。 + + Args: + ctx: Worker 上下文(堆栈仅运维可见)。 + payload: 须含 job_id;业务字段在 Job.payload_json。 + + Returns: + None。 + """ + _ = ctx + raw_job_id = payload.get('job_id') + job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None + if job is None: + return + + owned_attempt = int(job.attempts or 0) + frozen = dict(job.payload_json or {}) + frozen.setdefault('job_id', int(job.id)) + + from app.services.shipping_notice import order_document_profile_xfa_automark_service as automark_service + + try: + result = automark_service.execute_xfa_ocr_automark_job(frozen) + except automark_service.XfaOcrAutomarkError as exc: + fail_job( + job.id, + error=str(exc.message or exc)[:500], + result={ + 'status': 'failed', + 'error_code': exc.error_code, + 'preview_render_checksum': frozen.get('preview_render_checksum'), + 'details': dict(exc.details or {}), + }, + retryable=bool(exc.retryable), + owned_attempt=owned_attempt, + ) + return + except Exception as exc: # noqa: BLE001 — 未知异常走可重试失败 + fail_job( + job.id, + error=str(exc)[:500], + result={ + 'status': 'failed', + 'error_code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_AUTOMARK_FAILED', + 'preview_render_checksum': frozen.get('preview_render_checksum'), + }, + retryable=True, + owned_attempt=owned_attempt, + ) + return + + finish_job( + job.id, + result=result, + message='XFA OCR automark completed', + owned_attempt=owned_attempt, + ) diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py index 8d99c7c0..fec9182c 100644 --- a/backend/app/jobs/types.py +++ b/backend/app/jobs/types.py @@ -20,6 +20,10 @@ class JobType(StrEnum): SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction' SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout' SHIPPING_PROCESS_GATE = 'shipping_process_gate' + # XFA 合成预览就绪后的 OCR 自动标记(Job.job_type 为字符串列,无需 DB enum 迁移) + SHIPPING_XFA_OCR_AUTOMARK = 'shipping_xfa_ocr_automark' + # 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm) + SHIPPING_STP_AUTO_CREATE = 'shipping_stp_auto_create' SCHEDULE_RUN = 'schedule_run' FILE_CHECK_RUN = 'file_check_run' WECOM_DIRECTORY_SYNC = 'wecom_directory_sync' @@ -55,7 +59,8 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = { 'kb': frozenset({'clean', 'path_upload', 'sync_dify'}), 'shipping': frozenset({ 'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction', - 'shipping_document_layout', 'shipping_process_gate', + 'shipping_document_layout', 'shipping_process_gate', 'shipping_xfa_ocr_automark', + 'shipping_stp_auto_create', }), } diff --git a/backend/app/models/job.py b/backend/app/models/job.py index dd7b4a60..bab5c5b7 100644 --- a/backend/app/models/job.py +++ b/backend/app/models/job.py @@ -29,6 +29,7 @@ class Job(Base): Index('ix_jobs_type_status_created', 'job_type', 'status', 'created_at'), Index('ix_jobs_business_ref', 'domain', 'job_type', 'business_ref'), Index('ix_jobs_locked_at', 'locked_at'), + Index('ix_jobs_retry_of_job_id', 'retry_of_job_id'), # 仅预解析 Job:同业务锚点同时只允许一条 queued # (不含 running:retry 可在旧 running 残留时另建 queued;RUN 复查也不受限) Index( @@ -82,6 +83,24 @@ class Job(Base): "AND business_ref IS NOT NULL" ), ), + # STP 自动建单:同幂等键同时只允许一条 queued/running(failed 可保留审计并新建重试 Job) + Index( + 'uq_jobs_shipping_stp_auto_create_active_ref', + 'domain', + 'job_type', + 'business_ref', + unique=True, + postgresql_where=text( + "job_type = 'shipping_stp_auto_create' " + "AND status IN ('queued', 'running') " + "AND business_ref IS NOT NULL" + ), + sqlite_where=text( + "job_type = 'shipping_stp_auto_create' " + "AND status IN ('queued', 'running') " + "AND business_ref IS NOT NULL" + ), + ), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -99,6 +118,8 @@ class Job(Base): max_attempts: Mapped[int] = mapped_column(Integer, default=3) locked_by: Mapped[Optional[str]] = mapped_column(String(128)) locked_at: Mapped[Optional[datetime]] = mapped_column(DateTime) + # 重试链:新 Job 指向被替换的 failed/dead Job,保留旧行审计。 + retry_of_job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True) created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id')) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) @@ -106,3 +127,4 @@ class Job(Base): finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime) created_by: Mapped[Optional['User']] = relationship('User', foreign_keys=[created_by_id]) + retry_of_job: Mapped[Optional['Job']] = relationship('Job', remote_side=[id], foreign_keys=[retry_of_job_id]) diff --git a/backend/app/services/shipping_notice/audit_compensation_service.py b/backend/app/services/shipping_notice/audit_compensation_service.py new file mode 100644 index 00000000..651a086a --- /dev/null +++ b/backend/app/services/shipping_notice/audit_compensation_service.py @@ -0,0 +1,210 @@ +""" +services/shipping_notice/audit_compensation_service.py + +用途:发货通知审计写失败补偿骨架(阶段 6)——记录待补偿、列出、重试桩。 +依赖:标准库 logging/threading/time;可选 Redis list(键 shipping:audit:compensation)。 +逻辑:优先进程内队列 + 结构化日志;Redis 可用时双写 list。本阶段不引入 DB 迁移。 + 生产持久化与定时重试属阶段 6 完工项(见模块 docstring TODO)。 + +TODO(stage-6-completion): 生产必须接入持久化(DB 或强依赖 Redis)与告警渠道; + 当前 in-process 在多 Worker / 重启下会丢失,仅供开发与单测骨架。 +""" + +from __future__ import annotations + +import json +import logging +import threading +import time +import uuid +from typing import Any + +_LOGGER = logging.getLogger(__name__) + +REDIS_COMPENSATION_KEY = 'shipping:audit:compensation' +_LOCK = threading.RLock() +# 进程内待补偿队列(测试 / 单进程开发兜底;生产需持久化) +_PENDING: list[dict[str, Any]] = [] + + +def _try_redis_client() -> Any | None: + """尽力获取 Redis;失败返回 None(不 fail-closed,因本骨架允许内存)。""" + try: + from app.services.redis_client import get_redis_client + + return get_redis_client() + except Exception as exc: # noqa: BLE001 + _LOGGER.debug('audit compensation Redis unavailable: %s', exc) + return None + + +def record_audit_write_failure( + *, + event_type: str, + payload: dict[str, Any] | None = None, + error: str | None = None, + profile_id: int | None = None, + document_id: int | None = None, + actor_id: int | None = None, + request_id: str | None = None, +) -> dict[str, Any]: + """ + 记录一次审计写失败,进入待补偿队列。 + + 核心逻辑:构造 compensation 记录 → 结构化日志 → 内存列表;Redis 可用时 LPUSH。 + + Args: + event_type: 失败的审计事件名。 + payload: 可安全重放的摘要(禁止密钥/全文 XML)。 + error: 失败原因短文本。 + profile_id/document_id/actor_id/request_id: 关联上下文。 + + Returns: + 新建的 compensation 记录(含 id / status=pending)。 + """ + record = { + 'id': f'ac-{uuid.uuid4().hex[:16]}', + 'event_type': str(event_type or '').strip() or 'unknown', + 'payload': dict(payload or {}), + 'error': str(error or '')[:500], + 'profile_id': profile_id, + 'document_id': document_id, + 'actor_id': actor_id, + 'request_id': request_id, + 'status': 'pending', + 'retry_count': 0, + 'created_at': time.time(), + 'updated_at': time.time(), + } + _LOGGER.error( + 'shipping_audit_write_failure compensation_id=%s event_type=%s error=%s profile_id=%s', + record['id'], + record['event_type'], + record['error'], + profile_id, + ) + with _LOCK: + _PENDING.append(record) + client = _try_redis_client() + if client is not None: + try: + client.lpush(REDIS_COMPENSATION_KEY, json.dumps(record, ensure_ascii=False, default=str)) + except Exception as exc: # noqa: BLE001 + _LOGGER.warning('audit compensation Redis LPUSH failed: %s', exc) + return dict(record) + + +def list_pending_compensation(*, limit: int = 100) -> list[dict[str, Any]]: + """ + 列出待补偿记录(优先内存;可选合并 Redis 只读快照)。 + + Args: + limit: 最大返回条数。 + + Returns: + status=pending 的记录副本列表(新→旧不保证严格序)。 + """ + safe_limit = max(1, min(int(limit or 100), 1000)) + with _LOCK: + pending = [dict(item) for item in _PENDING if item.get('status') == 'pending'] + # Redis 侧仅作观测补充;权威仍以内存为准(阶段 6 骨架) + client = _try_redis_client() + if client is not None: + try: + raw_items = client.lrange(REDIS_COMPENSATION_KEY, 0, safe_limit - 1) or [] + seen = {item.get('id') for item in pending} + for raw in raw_items: + try: + item = json.loads(raw) + except (TypeError, ValueError, json.JSONDecodeError): + continue + if item.get('status') == 'pending' and item.get('id') not in seen: + pending.append(item) + seen.add(item.get('id')) + except Exception as exc: # noqa: BLE001 + _LOGGER.debug('audit compensation Redis LRANGE failed: %s', exc) + return pending[:safe_limit] + + +def retry_pending(*, limit: int = 20) -> dict[str, Any]: + """ + 重试待补偿记录的骨架实现:仅打日志并标记 retried,不真正重写审计。 + + 核心逻辑:取出 pending → 递增 retry_count → status=retried_stub → 结构化日志。 + 真实审计重放留待阶段 6 完工。 + + Args: + limit: 本轮最多处理条数。 + + Returns: + {retried, remaining, items} 摘要。 + """ + safe_limit = max(1, min(int(limit or 20), 200)) + retried: list[dict[str, Any]] = [] + with _LOCK: + candidates = [item for item in _PENDING if item.get('status') == 'pending'][:safe_limit] + for item in candidates: + item['retry_count'] = int(item.get('retry_count') or 0) + 1 + item['status'] = 'retried_stub' + item['updated_at'] = time.time() + retried.append(dict(item)) + _LOGGER.info( + 'shipping_audit_compensation_retry_stub compensation_id=%s event_type=%s retry_count=%s', + item.get('id'), + item.get('event_type'), + item.get('retry_count'), + ) + remaining = sum(1 for item in _PENDING if item.get('status') == 'pending') + return { + 'retried': len(retried), + 'remaining': remaining, + 'items': retried, + 'note': 'stub_only_no_audit_replay', + } + + +def reset_compensation_store_for_tests() -> None: + """ + 清空进程内补偿队列(仅测试使用)。 + + Returns: + None + """ + with _LOCK: + _PENDING.clear() + + +def is_audit_compensation_healthy() -> bool: + """ + 判断审计补偿通道是否健康(自动建单硬前置)。 + + 核心逻辑(硬冻结): + 1. 存在 pending 补偿记录 → 不健康; + 2. 当前实现仅为内存/观测骨架且 retry 不做真实重放 → 恒判定为不健康 + (生产持久化 + 真实重放完成前不得让 can_auto_create 绕过)。 + + Returns: + True 仅当补偿系统已达生产级且无 pending;现阶段恒 False。 + """ + pending = list_pending_compensation(limit=1) + if pending: + return False + # 骨架未完成真实重放与持久化:fail-closed,禁止资格计算绕过。 + return False + + +def audit_compensation_health_snapshot() -> dict[str, Any]: + """ + 返回审计补偿健康快照(供资格评估写入 evidence)。 + + Returns: + {healthy, pending_count, persistence, replay_capable, note}。 + """ + pending = list_pending_compensation(limit=1000) + return { + 'healthy': is_audit_compensation_healthy(), + 'pending_count': len(pending), + 'persistence': 'in_memory_stub', + 'replay_capable': False, + 'note': 'OPERATIONAL_PENDING_until_persistent_replay', + } \ No newline at end of file diff --git a/backend/app/services/shipping_notice/audit_query_service.py b/backend/app/services/shipping_notice/audit_query_service.py index f2111c03..fe87940b 100644 --- a/backend/app/services/shipping_notice/audit_query_service.py +++ b/backend/app/services/shipping_notice/audit_query_service.py @@ -56,6 +56,9 @@ XFA_VISUAL_BINDING_AUDIT_EVENT_TYPES: frozenset[str] = frozenset({ 'xfa_visual_binding_confirmed', 'xfa_visual_binding_rejected', 'xfa_visual_binding_updated', + 'xfa_ocr_started', + 'xfa_ocr_completed', + 'xfa_ocr_failed', }) XFA_SPLIT_AUDIT_EVENT_TYPES: frozenset[str] = frozenset({ 'xfa_split_rule_suggested', @@ -75,6 +78,9 @@ XFA_UNIFIED_AUDIT_EVENT_TYPES: frozenset[str] = ( 'order_profile_unified_migration_executed', 'xfa_profile_draft_saved', 'xfa_mapping_saved', + 'xfa_structure_analysis_reused', + 'xfa_structure_analysis_reuse_rejected', + 'xfa_structure_analysis_reparse_queued', }) ) diff --git a/backend/app/services/shipping_notice/candidate_qualification_service.py b/backend/app/services/shipping_notice/candidate_qualification_service.py index bd98b7b8..5b808f8e 100644 --- a/backend/app/services/shipping_notice/candidate_qualification_service.py +++ b/backend/app/services/shipping_notice/candidate_qualification_service.py @@ -14,6 +14,7 @@ services/shipping_notice/candidate_qualification_service.py 另要求 evidence 计数与四项 cross-check 齐全且仅为 matched/passed/skipped; PDF 优先关键冲突(conflicts_json.reason=pdf_preferred_critical_conflict) 映射为 review_required,阻断 can_auto_create。 + 硬冻结 2026-08-07:不再叠加 XFA_AUTO_CREATE / flatten / 审计补偿等模板类型特例到 can_auto_create。 """ from __future__ import annotations @@ -46,6 +47,27 @@ from app.services.shipping_notice.tool_common import ( xfa_shadow_mode_enabled, ) + +def _candidate_field(candidate: Any, key: str, default: Any = None) -> Any: + """ + 兼容读取 Candidate 字段(ORM / dict / SimpleNamespace)。 + + 核心逻辑:dict 用 .get;对象用 getattr;禁止对非 dict 调用 .get。 + + Args: + candidate: Candidate 或兼容对象。 + key: 字段名。 + default: 缺省值。 + + Returns: + 字段值或 default。 + """ + if candidate is None: + return default + if isinstance(candidate, dict): + return candidate.get(key, default) + return getattr(candidate, key, default) + _DEFAULT_BUSINESS_SCENARIO = 'shipping_notice_order' # 分类置信度默认下限;仅当 Schema auto_creation_policy 未配置 minimum_confidence 时回退。 @@ -339,7 +361,12 @@ def evaluate_candidate_qualification( 'confidence_policy': confidence_policy, } + # 硬冻结(2026-08-07):can_auto_create 只由全局 Schema/CQ 与统一资格门禁决定; + # 不再叠加 XFA_AUTO_CREATE / flatten / 审计补偿等模板类型特例。 can_auto_create = status == 'eligible' + evidence_snapshot = { + **evidence_snapshot, + } return { 'status': status, 'gates': gates, diff --git a/backend/app/services/shipping_notice/conversation_processing_projection.py b/backend/app/services/shipping_notice/conversation_processing_projection.py index 2e5bcfb8..67f31f7c 100644 --- a/backend/app/services/shipping_notice/conversation_processing_projection.py +++ b/backend/app/services/shipping_notice/conversation_processing_projection.py @@ -7,10 +7,12 @@ services/shipping_notice/conversation_processing_projection.py order_extraction_workspace_projection._run_available_actions。 逻辑:由 GET conversations/{id}/processing 与统一提交响应内嵌;按 needs_action / processing / completed / history 分组;未查看成功结果进 completed,与异常态分离; - 先加载全部当前有效右侧候选 Run(无归并前截断),再加载同 OT 的历史谱系; - 每个 PDF 独立选择最新有效版本,归并后再按任务数截断; - 任务—PDF 两层:单 PDF 用文件名作 title;多 PDF 用 display_kind=multi_document_task, - file_count 按 content_hash/root/document 去重;objects 含当前 PDF 子对象。 + 已查看 completed + cancelled 进 history(右侧处理记录); + 先加载全部当前有效右侧候选 Run(无硬顶行数截断),再加载同 OT 的谱系以折叠 PDF; + 每个 PDF 独立选择最新有效版本;同一 user_task_no 只出一张卡(替代谱系不另开历史卡); + 不按附件指纹跨 OT 归并;不同 user_task_no 即使同指纹也各出一张卡; + 汇总计数在截断前计算;活跃任务与 history 分别截断; + 展示标题由前端统一「订单识别任务」;document_names[0] 作主文件;title 恒为空。 """ from __future__ import annotations @@ -40,7 +42,7 @@ _HISTORY_RUN_STATUSES = frozenset({ 'completed', 'cancelled', }) -# 右侧可能展示的 Run 状态(未替代前提下);completed 还需未查看才输出。 +# 右侧可能展示的 Run 状态(未替代前提下);cancelled / 已查看 completed 进 history。 _RIGHT_PANEL_RUN_STATUSES = frozenset({ 'queued', 'processing', @@ -48,7 +50,10 @@ _RIGHT_PANEL_RUN_STATUSES = frozenset({ 'review_required', 'partially_completed', 'completed', + 'cancelled', }) +_DEFAULT_ACTIVE_TASK_LIMIT = 50 +_DEFAULT_HISTORY_TASK_LIMIT = 20 _NEEDS_ACTION_ITEM_LIFECYCLES = frozenset({ 'pending_review', 'manual_upload_pending', @@ -294,12 +299,13 @@ def _task_title_and_display_kind( documents: list[dict[str, Any]], ) -> tuple[str | None, str, list[str]]: """ - 解析任务标题与展示类型。 + 解析任务展示类型与文件名列表。 - 核心逻辑:仅单 PDF 允许用文件名作 title;多 PDF 返回 title=None + multi_document_task。 + 核心逻辑:展示标题由前端统一「订单识别任务」,本函数恒返回 title=None; + document_names 仍按去重 PDF 文件名收集,供前端 document_names[0] 作主文件副标题。 Returns: - (title, display_kind, document_names) + (title, display_kind, document_names);title 恒为 None。 """ names: list[str] = [] for document in documents: @@ -307,38 +313,24 @@ def _task_title_and_display_kind( if name: names.append(name) if len(documents) == 1: - title = names[0] if names else None - return title, 'single_document_task', names + return None, 'single_document_task', names return None, 'multi_document_task', names -def _attachment_fingerprint_key(run: ShippingOrderProcessingRun) -> tuple[str, ...] | None: - """会话投影用的附件身份键;空指纹返回 None。""" - from app.services.shipping_notice.order_extraction_run_service import ( - _business_attachment_fingerprint, - ) - - snapshot = ( - run.request_snapshot_json - if isinstance(run.request_snapshot_json, dict) - else run.input_snapshot_json - ) - fingerprint = _business_attachment_fingerprint(snapshot if isinstance(snapshot, dict) else None) - return fingerprint or None - - def _resolve_task_group(run: ShippingOrderProcessingRun) -> str: """ 将「当前有效 Run」映射为会话顶层分组。 核心逻辑(版本维度与业务状态分离): - - superseded_by_run_id 非空 → history(已被新版本替代); + - superseded_by_run_id 非空 → 不作为独立任务卡(候选查询已排除); + 替代谱系 PDF 折叠进当前 OT 的 objects,不另开历史卡(BE-03); - needs_action:复核/失败/部分完成(异常或需人工决策); - processing:queued/processing; - completed 且尚未查看 → completed(成功通知,与 needs_action 分离); - - completed 已查看 / cancelled → history(右侧不展示)。 + - completed 已查看 / cancelled → history(右侧处理记录)。 """ if getattr(run, 'superseded_by_run_id', None) is not None: + # 仅防御:候选集本不含 superseded;谱系折叠见 _effective_business_documents。 return 'history' status = str(run.status or '') if status in _NEEDS_ACTION_RUN_STATUSES: @@ -557,6 +549,7 @@ def _resolve_task_actions(run: ShippingOrderProcessingRun) -> tuple[str | None, 聚合任务级权威操作;前端禁止自行按状态推导按钮。 核心逻辑:复用 workspace `_run_available_actions`,再映射会话任务卡常用动作码。 + 主 CTA 优先业务入口;cancel_* / view_details 永不作 primary;无业务入口时兜底 focus_task。 Returns: (primary_action, available_actions) @@ -584,21 +577,24 @@ def _resolve_task_actions(run: ShippingOrderProcessingRun) -> tuple[str | None, actions.append('retry_failed_documents') if 'view_details' not in actions: - actions.insert(0, 'view_details') + actions.append('view_details') + # [BE-01] 业务主入口优先;禁止 cancel / view_details 升为 primary。 primary: str | None = None for candidate in ( 'open_review', 'enter_manual_review', 'retry_failed_documents', 'retry_failed_attachments', - 'cancel_task', - 'cancel_run', - 'view_details', + 'retry_parse', ): if candidate in actions: primary = candidate break + if primary is None: + if 'focus_task' not in actions: + actions.append('focus_task') + primary = 'focus_task' return primary, actions @@ -670,16 +666,22 @@ def project_conversation_processing( recent_task_no: str | None = None, recent_decision: str | None = None, recent_append_count: int | None = None, - limit: int = 50, + limit: int = _DEFAULT_ACTIVE_TASK_LIMIT, + history_limit: int = _DEFAULT_HISTORY_TASK_LIMIT, ) -> dict[str, Any]: """ 投影会话级「本次处理中」用户可见任务。 核心逻辑: 1. 先筛未替代且右侧可见状态的当前 Run,确定需要展示的用户任务; - 2. 加载这些 OT 的全部 Run 谱系,每个 PDF 身份独立选择最新版本; - 3. 同一 user_task_no 只输出一张任务卡,再按附件指纹归并重复任务; - 4. 输出 needs_action / processing / completed,最后按 task_limit 截断。 + 2. 加载这些 OT 的全部 Run 谱系,每个 PDF 身份独立选择最新版本(替代谱系折叠进当前 OT); + 3. 同一 user_task_no 只输出一张任务卡(仅按 OT 去重,不按附件指纹跨 OT 归并); + 4. 输出 needs_action / processing / completed / history; + 5. 汇总计数在截断前基于全量列表;活跃与 history 分别截断。 + + Returns: + 含 summary / 分组任务列表的投影字典;summary.total_files 为当前会话正式任务 + 覆盖的文件总数(含处理记录,不含 order_intake)。 """ normalized = str(conversation_id or '').strip() @@ -687,11 +689,11 @@ def project_conversation_processing( if not focused: focused = _latest_focused_task_no(user_id=int(user_id), conversation_id=normalized) - task_limit = max(1, min(int(limit or 50), 200)) - # [BE-02] 候选集仅含当前有效 + 右侧可见状态;不得在归并前用固定窗口截断。 - # 极端会话硬顶仅防失控读放大,远高于常规用户任务上限。 + task_limit = max(1, min(int(limit or _DEFAULT_ACTIVE_TASK_LIMIT), 200)) + history_task_limit = max(1, min(int(history_limit or _DEFAULT_HISTORY_TASK_LIMIT), 200)) + # [BE-02] 候选集仅含当前有效 + 右侧可见状态;不得在投影前用固定窗口截断。 + # 无行级硬顶:依赖事后 task_limit / history_limit;替代谱系另查。 # [UI-01 / BE-03] Candidate 前 user_task_no 为 NULL:不进右侧「订单任务」卡。 - candidate_hard_cap = 5000 runs = ( ShippingOrderProcessingRun.query.filter( ShippingOrderProcessingRun.user_id == int(user_id), @@ -704,11 +706,10 @@ def project_conversation_processing( ShippingOrderProcessingRun.last_activity_at.desc().nullslast(), ShippingOrderProcessingRun.created_at.desc(), ) - .limit(candidate_hard_cap) .all() ) - # [STEP 1] 同一 OT 只选择一个代表 Run(重识别不产生新用户任务)。 + # [STEP 1] 同一 OT 只选择一个代表 Run(重识别不产生新用户任务;仅按 user_task_no 去重)。 latest_by_task: dict[str, ShippingOrderProcessingRun] = {} for run in runs: task_no = str(getattr(run, 'user_task_no', None) or '').strip() @@ -740,34 +741,11 @@ def project_conversation_processing( if task_no in runs_by_task: runs_by_task[task_no].append(lineage_run) - # [STEP 2][BE-02] 按附件指纹归并任务卡;PDF 集合仍按各 OT 谱系独立汇总。 - latest_by_identity: dict[str, ShippingOrderProcessingRun] = {} - task_nos_by_identity: dict[str, list[str]] = {} - identity_order: list[str] = [] - for run in latest_by_task.values(): - fingerprint = _attachment_fingerprint_key(run) - identity = ( - 'fp:' + '|'.join(fingerprint) - if fingerprint - else f'task:{getattr(run, "user_task_no", None) or run.run_no}' - ) - existing = latest_by_identity.get(identity) - if existing is None: - latest_by_identity[identity] = run - task_nos_by_identity[identity] = [ - str(getattr(run, 'user_task_no', None) or '').strip(), - ] - identity_order.append(identity) - continue - task_no = str(getattr(run, 'user_task_no', None) or '').strip() - if task_no and task_no not in task_nos_by_identity[identity]: - task_nos_by_identity[identity].append(task_no) - if _run_recency_key(run) > _run_recency_key(existing): - latest_by_identity[identity] = run - + # [STEP 2][BE-02] 一 OT 一卡;同 OT 谱系折叠 PDF;禁止按附件指纹跨 OT 归并。 needs_action: list[dict[str, Any]] = [] processing: list[dict[str, Any]] = [] completed: list[dict[str, Any]] = [] + history: list[dict[str, Any]] = [] recent = str(recent_task_no or '').strip() or None decision = str(recent_decision or '').strip().lower() or None append_count = ( @@ -775,15 +753,12 @@ def project_conversation_processing( if recent_append_count is not None else None ) - for identity in identity_order: - run = latest_by_identity[identity] - # 已被替代的版本不进入右侧。 + for task_no, run in latest_by_task.items(): + # 已被替代的版本不进入右侧独立任务卡(谱系只用于 PDF 折叠)。 if not _is_current_effective_run(run): continue - source_runs: list[ShippingOrderProcessingRun] = [] - for task_no in task_nos_by_identity.get(identity, []): - source_runs.extend(runs_by_task.get(task_no) or [latest_by_task[task_no]]) - effective_documents = _effective_business_documents(source_runs or [run]) + source_runs = runs_by_task.get(task_no) or [run] + effective_documents = _effective_business_documents(source_runs) task = _project_user_task( run, focused_task_no=focused, @@ -803,21 +778,29 @@ def project_conversation_processing( processing.append(task) elif group == 'completed': completed.append(task) + elif group == 'history': + history.append(task) - # [STEP 3] 组内按最近活动时间降序;再按任务数截断(非原始 Run 数)。 + # [STEP 3] 组内按最近活动时间降序;汇总用全量,再分别截断活跃 / history。 def _sort_key(item: dict[str, Any]) -> str: return str(item.get('last_activity_at') or item.get('created_at') or '') needs_action.sort(key=_sort_key, reverse=True) processing.sort(key=_sort_key, reverse=True) completed.sort(key=_sort_key, reverse=True) + history.sort(key=_sort_key, reverse=True) - # 优先保留需处理与处理中,再填已完成通知。 + full_needs_action = list(needs_action) + full_processing = list(processing) + full_completed = list(completed) + full_history = list(history) + + # 活跃:优先保留需处理与处理中,再填已完成通知。 kept: list[tuple[str, dict[str, Any]]] = [] for bucket, rows in ( - ('needs_action', needs_action), - ('processing', processing), - ('completed', completed), + ('needs_action', full_needs_action), + ('processing', full_processing), + ('completed', full_completed), ): for row in rows: if len(kept) >= task_limit: @@ -828,24 +811,45 @@ def project_conversation_processing( needs_action = [row for bucket, row in kept if bucket == 'needs_action'] processing = [row for bucket, row in kept if bucket == 'processing'] completed = [row for bucket, row in kept if bucket == 'completed'] + history = full_history[:history_task_limit] - total_files = sum( - int(item.get('file_count') or 0) for item in needs_action + processing + completed + full_active_count = ( + len(full_needs_action) + len(full_processing) + len(full_completed) ) - total = len(needs_action) + len(processing) + len(completed) + returned_active_count = len(needs_action) + len(processing) + len(completed) + # total_files:当前会话正式任务覆盖的文件总数(含处理记录,不含 order_intake)。 + total_files = sum( + int(item.get('file_count') or 0) + for item in full_needs_action + full_processing + full_completed + full_history + ) + # total_tasks:截断前当前有效 OT 卡数量(一 OT 一卡,无指纹折叠)。 + total_tasks = full_active_count + len(full_history) return { 'summary': { - 'total_tasks': total, + 'total_tasks': total_tasks, + # 当前会话正式任务覆盖的文件总数(含处理记录,不含 order_intake)。 'total_files': total_files, - 'processing': len(processing), - 'needs_action': len(needs_action), - 'completed': len(completed), - 'history': 0, + 'processing': len(full_processing), + 'needs_action': len(full_needs_action), + 'completed': len(full_completed), + 'history': len(full_history), + 'truncated': { + 'active': full_active_count > returned_active_count, + 'history': len(full_history) > len(history), + }, + 'returned': { + 'needs_action': len(needs_action), + 'processing': len(processing), + 'completed': len(completed), + 'history': len(history), + }, + 'has_more_active': full_active_count > returned_active_count, + 'has_more_history': len(full_history) > len(history), }, 'focused_task_no': focused, 'recent_task_no': recent, 'needs_action': needs_action, 'processing': processing, 'completed': completed, - 'history': [], + 'history': history, } diff --git a/backend/app/services/shipping_notice/document_layout/lifecycle.py b/backend/app/services/shipping_notice/document_layout/lifecycle.py index 31ea4822..5c323897 100644 --- a/backend/app/services/shipping_notice/document_layout/lifecycle.py +++ b/backend/app/services/shipping_notice/document_layout/lifecycle.py @@ -2,9 +2,9 @@ backend/app/services/shipping_notice/document_layout/lifecycle.py 用途:管理 ShippingOrderDocument 的版面版本、checksum、大小门禁和当前成功快照。 -依赖:ShippingDocumentLayoutVersion、ShippingXfaStructureAnalysis、Flask 配置、SQLAlchemy Session、workflow_ledger_service - (claim/complete/recovery 尽力同步 WorkflowItem,缺 Item 不阻断版面收口)。 -逻辑:相同内容/parser/checksum 幂等复用;XFA 复用时同步本地化结构分析身份; +依赖:ShippingDocumentLayoutVersion、ShippingXfaStructureAnalysis、Flask 配置、SQLAlchemy Session、 + workflow_ledger_service、audit_service(XFA Analysis 复用/拒绝/重排队双写审计)。 +逻辑:相同内容/parser/checksum 幂等复用;XFA 复用时同步本地化结构分析身份并写审计; 失败版本保留审计,只有可用终态更新 Document 当前引用。 """ @@ -294,9 +294,93 @@ def record_inline_layout_snapshot( return version +def _audit_xfa_analysis_reuse_event( + *, + event_type: str, + document: ShippingOrderDocument, + result: str = 'success', + source_document_id: int | None = None, + source_layout_version_id: int | None = None, + source_analysis_id: int | None = None, + target_layout_version_id: int | None = None, + target_analysis_id: int | None = None, + content_hash: str | None = None, + template_packet_checksum: str | None = None, + datasets_packet_checksum: str | None = None, + dataset_structure_fingerprint: str | None = None, + reject_reason: str | None = None, + job_id: int | None = None, + actor_user_id: int | None = None, + request_id: str | None = None, + operation_id: str | None = None, + before: dict[str, Any] | None = None, + after: dict[str, Any] | None = None, +) -> None: + """ + 双写 XFA StructureAnalysis 复用/拒绝/重排队审计(Document 可见流 + 平台账本)。 + + 核心逻辑:actor 固定为 system/worker,并附带触发用户与 Job/request/operation(存在时)。 + + Args: + event_type: xfa_structure_analysis_reused / reuse_rejected / reparse_queued。 + document: 目标 Document。 + result: success / failure / degraded。 + 其余字段:来源/目标身份与 checksum 快照。 + """ + try: + from flask import g, has_request_context + + from app.services.shipping_notice.audit_service import append_shipping_audit_event + + if actor_user_id is None and has_request_context(): + actor_user_id = getattr(g, 'current_user_id', None) or getattr(g, 'user_id', None) + if request_id is None and has_request_context(): + request_id = getattr(g, 'request_id', None) + payload = { + 'source_document_id': source_document_id, + 'source_layout_version_id': source_layout_version_id, + 'source_analysis_id': source_analysis_id, + 'target_document_id': int(document.id), + 'target_layout_version_id': target_layout_version_id, + 'target_analysis_id': target_analysis_id, + 'content_hash': content_hash or str(document.content_hash or '') or None, + 'template_packet_checksum': template_packet_checksum, + 'datasets_packet_checksum': datasets_packet_checksum, + 'dataset_structure_fingerprint': dataset_structure_fingerprint, + 'reject_reason': reject_reason, + 'job_id': job_id, + 'trigger_user_id': int(actor_user_id) if actor_user_id is not None else None, + 'request_id': str(request_id) if request_id else None, + 'operation_id': str(operation_id) if operation_id else None, + 'before': before or {}, + 'after': after or {}, + } + append_shipping_audit_event( + event_type=event_type, + aggregate_type='shipping_order_document', + aggregate_id=str(int(document.id)), + document_id=int(document.id), + actor_type='system', + actor_id=None, + result=result, + action=event_type, + sensitivity_level='internal', + before=before, + after=after or payload, + metadata={ + **{k: v for k, v in payload.items() if k not in {'before', 'after'}}, + 'executor': 'system/worker', + }, + ) + except Exception: # noqa: BLE001 — 审计失败不得阻断布局复用主路径 + _LOGGER.exception('Failed to write XFA analysis reuse audit event=%s', event_type) + + def _clone_reusable_layout_for_document( document: ShippingOrderDocument, reusable: ShippingDocumentLayoutVersion, + *, + created_by_id: int | None = None, ) -> ShippingDocumentLayoutVersion | None: """ 将同一所有者的已完成布局快照本地化到目标 Document。 @@ -304,11 +388,12 @@ def _clone_reusable_layout_for_document( LayoutVersion 的 document_id 是不可跨文档共享的外键语义;相同内容只能复用 已冻结 payload,不能让目标 Document 指向源 Document 的版本记录。XFA 快照还必须 为目标 Document 克隆独立 StructureAnalysis,并重写快照 analysis_id;源证据缺失或 - 身份不一致时返回 None,让调用方重新排队解析。 + 身份不一致时写 reuse_rejected 审计并返回 None,让调用方重新排队解析。 Args: document: 待接收复用结果的目标 Document。 reusable: 同一所有者、同内容且 parser 身份一致的源 LayoutVersion。 + created_by_id: 触发用户(若有)。 Returns: 目标 Document 专属 LayoutVersion;无法安全本地化时返回 None。 @@ -324,6 +409,8 @@ def _clone_reusable_layout_for_document( copied_payload.setdefault('snapshot_version', reusable.contract_version or LAYOUT_CONTRACT_VERSION) target_analysis: ShippingXfaStructureAnalysis | None = None + source_analysis: ShippingXfaStructureAnalysis | None = None + reject_reason: str | None = None if str(copied_payload.get('provider') or '') == 'xfa': capability = ( copied_payload.get('xfa_capability') @@ -336,20 +423,44 @@ def _clone_reusable_layout_for_document( if source_analysis_id not in (None, '') else None ) - if ( - source_analysis is None - or int(source_analysis.document_id) != int(reusable.document_id) - or str(source_analysis.analysis_status or '') != 'ready' - or str(source_analysis.source_content_hash or '').lower() - != str(document.content_hash or '').lower() - or str(source_analysis.template_packet_checksum or '') - != str(capability.get('template_packet_checksum') or '') - or str(source_analysis.dataset_structure_fingerprint or '') - != str(capability.get('dataset_structure_fingerprint') or '') + if source_analysis is None: + reject_reason = 'source_analysis_missing' + elif int(source_analysis.document_id) != int(reusable.document_id): + reject_reason = 'source_analysis_document_mismatch' + elif str(source_analysis.analysis_status or '') != 'ready': + reject_reason = 'source_analysis_not_ready' + elif str(source_analysis.source_content_hash or '').lower() != str(document.content_hash or '').lower(): + reject_reason = 'content_hash_mismatch' + elif str(source_analysis.template_packet_checksum or '') != str(capability.get('template_packet_checksum') or ''): + reject_reason = 'template_checksum_mismatch' + elif str(source_analysis.dataset_structure_fingerprint or '') != str( + capability.get('dataset_structure_fingerprint') or '', ): + reject_reason = 'structure_fingerprint_mismatch' + + if reject_reason is not None: + _audit_xfa_analysis_reuse_event( + event_type='xfa_structure_analysis_reuse_rejected', + document=document, + result='failure', + source_document_id=int(reusable.document_id), + source_layout_version_id=int(reusable.id), + source_analysis_id=int(source_analysis_id) if source_analysis_id not in (None, '') else None, + content_hash=str(document.content_hash or '') or None, + template_packet_checksum=str(capability.get('template_packet_checksum') or '') or None, + dataset_structure_fingerprint=str(capability.get('dataset_structure_fingerprint') or '') or None, + reject_reason=reject_reason, + actor_user_id=created_by_id, + before={ + 'source_layout_version_id': int(reusable.id), + 'source_analysis_id': source_analysis_id, + }, + after={}, + ) return None # [STEP 1] Analysis 是 document-scoped 证据;克隆安全摘要并先取得目标主键。 + assert source_analysis is not None target_analysis = ShippingXfaStructureAnalysis( document_id=int(document.id), layout_version_id=None, @@ -386,8 +497,44 @@ def _clone_reusable_layout_for_document( if target_analysis is not None: if str(localized.status or '') not in CURRENT_LAYOUT_STATUSES: db.session.delete(target_analysis) + _audit_xfa_analysis_reuse_event( + event_type='xfa_structure_analysis_reuse_rejected', + document=document, + result='failure', + source_document_id=int(reusable.document_id), + source_layout_version_id=int(reusable.id), + source_analysis_id=int(source_analysis.id) if source_analysis is not None else None, + target_layout_version_id=int(localized.id), + reject_reason='localized_layout_not_ready', + actor_user_id=created_by_id, + ) return None target_analysis.layout_version_id = int(localized.id) + _audit_xfa_analysis_reuse_event( + event_type='xfa_structure_analysis_reused', + document=document, + result='success', + source_document_id=int(reusable.document_id), + source_layout_version_id=int(reusable.id), + source_analysis_id=int(source_analysis.id) if source_analysis is not None else None, + target_layout_version_id=int(localized.id), + target_analysis_id=int(target_analysis.id), + content_hash=str(document.content_hash or '') or None, + template_packet_checksum=str(target_analysis.template_packet_checksum or '') or None, + datasets_packet_checksum=str(target_analysis.datasets_packet_checksum or '') or None, + dataset_structure_fingerprint=str(target_analysis.dataset_structure_fingerprint or '') or None, + actor_user_id=created_by_id, + before={ + 'source_document_id': int(reusable.document_id), + 'source_layout_version_id': int(reusable.id), + 'source_analysis_id': int(source_analysis.id) if source_analysis is not None else None, + }, + after={ + 'target_document_id': int(document.id), + 'target_layout_version_id': int(localized.id), + 'target_analysis_id': int(target_analysis.id), + }, + ) return localized @@ -435,9 +582,19 @@ def schedule_layout_version( None, ) if reusable_from_owner is not None: - localized = _clone_reusable_layout_for_document(document, reusable_from_owner) + localized = _clone_reusable_layout_for_document( + document, + reusable_from_owner, + created_by_id=created_by_id, + ) if localized is not None: return localized + # 复用被拒绝后继续排队重新解析;下方 enqueue 后写 reparse_queued + reuse_rejected_source = reusable_from_owner + else: + reuse_rejected_source = None + else: + reuse_rejected_source = None active = ShippingDocumentLayoutVersion.query.filter( ShippingDocumentLayoutVersion.document_id == int(document.id), ShippingDocumentLayoutVersion.status.in_({'queued', 'running'}), @@ -479,6 +636,35 @@ def schedule_layout_version( commit=False, ) version.job_id = job_id + # [STEP] 仅在跨文档复用失败后重新 enqueue 时写 reparse_queued(force 重解析不记该事件) + if reuse_rejected_source is not None: + source_cap = ( + reuse_rejected_source.payload_json.get('xfa_capability') + if isinstance(reuse_rejected_source.payload_json, dict) + and isinstance(reuse_rejected_source.payload_json.get('xfa_capability'), dict) + else {} + ) + _audit_xfa_analysis_reuse_event( + event_type='xfa_structure_analysis_reparse_queued', + document=document, + result='degraded', + source_document_id=int(reuse_rejected_source.document_id), + source_layout_version_id=int(reuse_rejected_source.id), + source_analysis_id=( + int(source_cap['structure_analysis_id']) + if source_cap.get('structure_analysis_id') not in (None, '') + else None + ), + target_layout_version_id=int(version.id), + content_hash=source_hash, + job_id=int(job_id) if job_id is not None else None, + actor_user_id=created_by_id, + after={ + 'queued_layout_version_id': int(version.id), + 'job_id': int(job_id) if job_id is not None else None, + 'force': bool(force), + }, + ) return version diff --git a/backend/app/services/shipping_notice/document_layout/xfa_analysis.py b/backend/app/services/shipping_notice/document_layout/xfa_analysis.py index 17d79874..80690b95 100644 --- a/backend/app/services/shipping_notice/document_layout/xfa_analysis.py +++ b/backend/app/services/shipping_notice/document_layout/xfa_analysis.py @@ -1,11 +1,13 @@ """ backend/app/services/shipping_notice/document_layout/xfa_analysis.py -用途:编排 XFA packet 读取、datasets 解析、签名计算与布局快照/持久化。 -依赖:xfa_packets、xfa_dataset、xfa_signature、xfa_acroform、xfa_contract、 - ShippingXfaStructureAnalysis 模型。 -逻辑:由 runtime 与 shipping_document_layout Job 调用;成功时写入结构分析记录并返回 - 不含 XML/PDF 正文的 capability 快照。 +用途:编排 XFA packet 读取、datasets 解析、签名计算与布局快照/持久化; + 并提供 Layout 冻结的 StructureAnalysis 精确解析(禁止回退 document 最新)。 +依赖:ValidationError、ShippingDocumentLayoutVersion、ShippingOrderDocument、 + ShippingXfaStructureAnalysis、xfa_packets、xfa_dataset、xfa_signature、 + xfa_acroform、xfa_contract。 +逻辑:由 runtime / shipping_document_layout Job 写入分析;Profile 读路径经 + resolve_frozen_xfa_structure_analysis 按 Layout.structure_analysis_id 精确读取。 """ from __future__ import annotations @@ -14,8 +16,9 @@ from dataclasses import dataclass, field from datetime import datetime from typing import Any +from app.core.errors import ValidationError from app.extensions import db -from app.models import ShippingXfaStructureAnalysis +from app.models import ShippingDocumentLayoutVersion, ShippingOrderDocument, ShippingXfaStructureAnalysis from app.services.shipping_notice.document_layout.xfa_acroform import ( build_reconciliation_candidates, read_acroform_fields, @@ -396,7 +399,7 @@ def project_field_tree(analysis: ShippingXfaStructureAnalysis, *, include_values def get_latest_analysis_for_document(document_id: int) -> ShippingXfaStructureAnalysis | None: """ - 读取文档最近一次成功的 XFA 结构分析。 + 读取文档最近一次结构分析(兼容诊断;正式路径请用 resolve_frozen_xfa_structure_analysis)。 Args: document_id: ShippingOrderDocument 主键。 @@ -411,6 +414,172 @@ def get_latest_analysis_for_document(document_id: int) -> ShippingXfaStructureAn ) +def resolve_layout_version_for_xfa( + document: ShippingOrderDocument, + *, + layout_version: ShippingDocumentLayoutVersion | None = None, + layout_version_id: int | None = None, +) -> ShippingDocumentLayoutVersion: + """ + 解析文档应绑定的 LayoutVersion(旧 Revision 传入显式版本,禁止回退“最新”)。 + + 核心逻辑:显式 layout_version / layout_version_id 优先;否则使用 Document.current。 + + Args: + document: 样本文档。 + layout_version: 已加载的 LayoutVersion。 + layout_version_id: LayoutVersion 主键。 + + Returns: + LayoutVersion 实体。 + + Raises: + ValidationError: Layout 缺失或不属于该 Document。 + """ + version = layout_version + if version is None and layout_version_id is not None: + version = db.session.get(ShippingDocumentLayoutVersion, int(layout_version_id)) + if version is None: + version = getattr(document, 'current_layout_version', None) + if version is None: + raise ValidationError( + 'XFA layout version is missing for structure analysis binding', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_MISSING', + details={'document_id': int(document.id), 'reason': 'layout_missing'}, + ) + if int(version.document_id) != int(document.id): + raise ValidationError( + 'XFA layout version does not belong to the sample document', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_IDENTITY_MISMATCH', + details={ + 'document_id': int(document.id), + 'layout_version_id': int(version.id), + 'layout_document_id': int(version.document_id), + }, + ) + return version + + +def resolve_frozen_xfa_structure_analysis( + document: ShippingOrderDocument, + *, + layout_version: ShippingDocumentLayoutVersion | None = None, + layout_version_id: int | None = None, + require_ready: bool = True, +) -> tuple[ShippingDocumentLayoutVersion, ShippingXfaStructureAnalysis, dict[str, Any]]: + """ + 按 Layout 冻结的 structure_analysis_id 精确读取 Analysis(禁止 document 最新回退)。 + + 核心逻辑:Layout → xfa_capability.structure_analysis_id → 主键读取 → + 校验 document_id / layout_version_id / content_hash;缺失、身份不一致、陈旧分码 fail-closed。 + + Args: + document: 样本文档。 + layout_version: 可选已解析 LayoutVersion(旧 Revision / 非 current 必传)。 + layout_version_id: 可选 LayoutVersion 主键。 + require_ready: True 时要求 analysis_status=ready。 + + Returns: + (layout_version, analysis, capability_dict)。 + + Raises: + ValidationError: XFA_ANALYSIS_MISSING / IDENTITY_MISMATCH / STALE。 + """ + version = resolve_layout_version_for_xfa( + document, + layout_version=layout_version, + layout_version_id=layout_version_id, + ) + payload = version.payload_json if isinstance(version.payload_json, dict) else {} + capability = payload.get('xfa_capability') if isinstance(payload.get('xfa_capability'), dict) else {} + if not capability and isinstance(payload.get('capability'), dict): + capability = payload.get('capability') or {} + raw_id = capability.get('structure_analysis_id') + if raw_id in (None, ''): + raise ValidationError( + 'Frozen XFA structure_analysis_id is missing on layout snapshot', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_MISSING', + details={ + 'document_id': int(document.id), + 'layout_version_id': int(version.id), + 'reason': 'structure_analysis_id_missing', + }, + ) + try: + analysis_id = int(raw_id) + except (TypeError, ValueError) as exc: + raise ValidationError( + 'Frozen XFA structure_analysis_id is invalid', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_MISSING', + details={ + 'document_id': int(document.id), + 'layout_version_id': int(version.id), + 'structure_analysis_id': raw_id, + }, + ) from exc + + analysis = db.session.get(ShippingXfaStructureAnalysis, analysis_id) + if analysis is None: + raise ValidationError( + 'Frozen XFA structure analysis record is missing', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_MISSING', + details={ + 'document_id': int(document.id), + 'layout_version_id': int(version.id), + 'structure_analysis_id': analysis_id, + }, + ) + if int(analysis.document_id) != int(document.id): + raise ValidationError( + 'XFA structure analysis document identity mismatch', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_IDENTITY_MISMATCH', + details={ + 'document_id': int(document.id), + 'analysis_document_id': int(analysis.document_id), + 'structure_analysis_id': analysis_id, + 'layout_version_id': int(version.id), + }, + ) + analysis_layout_id = getattr(analysis, 'layout_version_id', None) + if analysis_layout_id not in (None, '') and int(analysis_layout_id) != int(version.id): + raise ValidationError( + 'XFA structure analysis layout identity mismatch', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_IDENTITY_MISMATCH', + details={ + 'document_id': int(document.id), + 'layout_version_id': int(version.id), + 'analysis_layout_version_id': int(analysis_layout_id), + 'structure_analysis_id': analysis_id, + }, + ) + doc_hash = str(document.content_hash or '').strip().lower() + analysis_hash = str(analysis.source_content_hash or '').strip().lower() + if doc_hash and analysis_hash and doc_hash != analysis_hash: + raise ValidationError( + 'XFA structure analysis content hash is stale relative to the document', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_STALE', + details={ + 'document_id': int(document.id), + 'layout_version_id': int(version.id), + 'structure_analysis_id': analysis_id, + 'document_content_hash': doc_hash, + 'analysis_content_hash': analysis_hash, + }, + ) + if require_ready and str(analysis.analysis_status or '') != 'ready': + raise ValidationError( + 'XFA structure analysis is not ready', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_MISSING', + details={ + 'document_id': int(document.id), + 'layout_version_id': int(version.id), + 'structure_analysis_id': analysis_id, + 'analysis_status': analysis.analysis_status, + }, + ) + return version, analysis, dict(capability) + + def rebuild_tree_dto_from_analysis( analysis: ShippingXfaStructureAnalysis, pdf_bytes: bytes, diff --git a/backend/app/services/shipping_notice/document_layout/xfa_contract.py b/backend/app/services/shipping_notice/document_layout/xfa_contract.py index 02076fe3..6ef8e63d 100644 --- a/backend/app/services/shipping_notice/document_layout/xfa_contract.py +++ b/backend/app/services/shipping_notice/document_layout/xfa_contract.py @@ -3,9 +3,9 @@ services/shipping_notice/document_layout/xfa_contract.py 用途:冻结 XFA 数据路径 Profile 契约——template_mode、受控路径语法、结构指纹、 统一字段 binding(value_binding + visual_binding)、鉴别联合 definition、 - evidence 与安全投影。 + evidence 与安全投影、合成预览审计事件与错误码注册。 依赖:Pydantic 2、标准库 hashlib/json/re/unicodedata;被 order_extraction_route_contract、 - Profile 校验、拆分契约与后续 xfa_*.py 解析器引用。 + Profile 校验、拆分契约、xfa_preview_* 与后续 xfa_*.py 解析器引用。 逻辑:本模块只定义契约与纯函数校验,不读 PDF/XML、不执行脚本、不接正式流量; 禁止混入 coordinate 表区键,但允许 visual_binding 归一化框作为视觉证据。 header_mappings / line_mapping.fields 仅作**迁移输入**解析(order_profile_unified_migration); @@ -144,6 +144,12 @@ XFA_ERROR_CODES: Final[frozenset[str]] = frozenset({ 'XFA_SPLIT_RULE_INVALID', 'XFA_SPLIT_FIELD_CONFLICT', 'XFA_SPLIT_MIRROR_MISMATCH', + # 合成预览(阶段 1 POC) + 'XFA_PREVIEW_STALE', + 'XFA_PREVIEW_FAILED', + 'XFA_PREVIEW_UNAVAILABLE', + 'XFA_PREVIEW_PAGE_INCONSISTENT', + 'XFA_PREVIEW_VALUE_MISMATCH', }) XFA_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({ @@ -178,6 +184,14 @@ XFA_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({ 'xfa_profile_checksum_mismatch', 'xfa_visual_not_publishable', 'xfa_split_rule_unconfirmed', + # 合成预览发布门禁(阶段 5) + 'xfa_synthetic_preview_not_ready', + 'xfa_preview_render_checksum_missing', + 'xfa_preview_pages_incomplete', + 'xfa_preview_page_box_invalid', + 'xfa_ocr_unresolved_mismatch', + 'xfa_preview_checksum_drift', + 'xfa_preview_renderer_version_mismatch', }) XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({ @@ -189,6 +203,9 @@ XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({ 'xfa_document_kind_detected', 'xfa_packet_parsed', 'xfa_structure_analysis_ready', + 'xfa_structure_analysis_reused', + 'xfa_structure_analysis_reuse_rejected', + 'xfa_structure_analysis_reparse_queued', 'xfa_field_tree_accessed', 'xfa_collections_accessed', 'xfa_sensitive_sample_value_read', @@ -228,6 +245,16 @@ XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({ # 统一 binding 一次性迁移(阶段 7) 'order_profile_unified_migration_dry_run', 'order_profile_unified_migration_executed', + # 合成预览(阶段 1 POC) + 'xfa_preview_requested', + 'xfa_preview_generated', + 'xfa_preview_failed', + 'xfa_preview_viewed', + 'xfa_preview_stale', + # OCR 自动标记建议(阶段 3) + 'xfa_ocr_started', + 'xfa_ocr_completed', + 'xfa_ocr_failed', }) # Profile / Run / 分析 DTO 禁止键(大小写不敏感);完整 XML / PDF bytes / 存储地址不得外泄。 @@ -400,6 +427,16 @@ XfaVisualBindingSource = Literal[ ] XfaVisualBindingStatus = Literal['suggested', 'confirmed', 'rejected', 'unavailable'] XfaBindingScope = Literal['header', 'line'] +# 画布工具 → 统一 region_kind;xfa_visual 为历史兼容别名(等价 field) +XfaVisualRegionKind = Literal['anchor', 'header', 'line', 'exclude', 'field', 'xfa_visual'] +XFA_VISUAL_REGION_KINDS: Final[frozenset[str]] = frozenset({ + 'anchor', + 'header', + 'line', + 'exclude', + 'field', + 'xfa_visual', +}) class XfaNormalizedBBox(XfaContractModel): @@ -448,13 +485,24 @@ class XfaValueBinding(XfaContractModel): class XfaVisualBinding(XfaContractModel): - """视觉绑定:页码 + 归一化框 + 确认状态;正式字段发布前须 confirmed。""" + """视觉绑定:页码 + 归一化框 + 确认状态;正式字段发布前须 confirmed。 + + 合成预览确认证据(阶段 4+):confirmed 时须携带 preview_render_checksum / + render_mode=xfa_dataset_preview / confirmed_on=xfa_dataset_preview。 + """ page_no: int = Field(ge=1, le=500) normalized_bbox: XfaNormalizedBBox source: XfaVisualBindingSource status: XfaVisualBindingStatus confidence: float = Field(default=1.0, ge=0.0, le=1.0) + # 画布区域语义:anchor|header|line|exclude|field(xfa_visual 历史兼容) + region_kind: XfaVisualRegionKind | None = None + # 合成预览确认证据(可选;confirm 门禁写入,publish 门禁读取) + preview_render_checksum: str | None = None + render_mode: str | None = None + confirmed_on: str | None = None + renderer_version: str | None = None class XfaSplitRuleRef(XfaContractModel): @@ -482,21 +530,37 @@ class XfaUnifiedFieldBinding(XfaContractModel): @model_validator(mode='after') def validate_xfa_scope_value_type(self) -> 'XfaUnifiedFieldBinding': - """XFA Profile 内正式绑定必须是 xfa_dataset(由上层 Profile 再强制)。""" + """同模板允许字段级混合数据源;具体约束由 value_binding / 发布门禁执行。""" return self def is_formal_binding_publishable(binding: XfaUnifiedFieldBinding) -> bool: """ - 判断统一绑定是否满足发布门禁的视觉确认要求。 + 判断统一绑定是否满足发布门禁(字段级混合数据源口径)。 + + 核心逻辑: + - xfa_dataset:正式 path 已配置即可发布(视觉框可选); + - pdf_coordinate / ocr_coordinate:必须视觉 confirmed; + - 旧合成预览确认(confirmed_on/render_mode=xfa_dataset_preview)视为未重确认。 Args: binding: 统一字段绑定。 Returns: - 视觉状态为 confirmed 时为 True。 + 满足对应类型发布条件时为 True。 """ - return binding.visual_binding.status == 'confirmed' + value_type = binding.value_binding.type + visual = binding.visual_binding + confirmed_on = str(visual.confirmed_on or '').strip() + render_mode = str(visual.render_mode or '').strip() + # 旧 flatten/synthetic 坐标系确认框须在原生 PDF 画布重确认。 + if visual.status == 'confirmed' and ( + confirmed_on == 'xfa_dataset_preview' or render_mode == 'xfa_dataset_preview' + ): + return False + if value_type == 'xfa_dataset': + return bool(binding.value_binding.path_id and binding.value_binding.data_path) + return visual.status == 'confirmed' def canonical_unified_bindings_payload( @@ -538,6 +602,10 @@ class OrderXfaDatasetProfile(XfaContractModel): bindings: list[XfaUnifiedFieldBinding] = Field(default_factory=list) cross_checks: XfaCrossChecks = Field(default_factory=XfaCrossChecks) split_rules: list[dict[str, Any]] = Field(default_factory=list) + # 合成预览摘要(可选;发布门禁优先读取 status / preview_render_checksum) + xfa_preview: dict[str, Any] | None = None + # OCR 自动标记摘要(可选;未解决 mismatch 计数供发布门禁读取) + xfa_ocr_automark: dict[str, Any] | None = None @model_validator(mode='before') @classmethod @@ -587,8 +655,12 @@ class OrderXfaDatasetProfile(XfaContractModel): binding_ids: list[str] = [] binding_field_keys: list[tuple[str, str]] = [] for binding in self.bindings: - if binding.value_binding.type != 'xfa_dataset': - raise ValueError('OrderXfaDatasetProfile bindings must use value_binding.type=xfa_dataset') + # 硬冻结(2026-08-07):同模板允许 xfa_dataset / pdf_coordinate / ocr_coordinate 混用。 + if binding.value_binding.type not in {'xfa_dataset', 'pdf_coordinate', 'ocr_coordinate'}: + raise ValueError( + 'OrderXfaDatasetProfile bindings must use value_binding.type in ' + 'xfa_dataset|pdf_coordinate|ocr_coordinate', + ) binding_ids.append(binding.binding_id) binding_field_keys.append((binding.scope, binding.field_id)) field_ids.append(binding.field_id) diff --git a/backend/app/services/shipping_notice/document_layout/xfa_preview_cache.py b/backend/app/services/shipping_notice/document_layout/xfa_preview_cache.py new file mode 100644 index 00000000..2dcd7ed6 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/xfa_preview_cache.py @@ -0,0 +1,133 @@ +""" +services/shipping_notice/document_layout/xfa_preview_cache.py + +用途:XFA 合成预览进程内缓存(Phase 1 POC);按身份指纹键存取预览结果。 +依赖:threading、xfa_preview_contract.build_preview_identity_fingerprint。 +逻辑:由预览编排层调用;可选后续替换为 Redis;本模块不做 IO/渲染。 +""" + +from __future__ import annotations + +import threading +import time +from typing import Any + +from app.services.shipping_notice.document_layout.xfa_preview_contract import ( + PreviewIdentityContext, + build_preview_identity_fingerprint, +) + +_LOCK = threading.RLock() +_CACHE: dict[str, tuple[float, dict[str, Any]]] = {} +_DEFAULT_TTL_SECONDS = 30 * 60 + + +def build_preview_cache_key( + *, + structure_analysis_id: int | str | None, + template_packet_checksum: str, + datasets_packet_checksum: str, + dataset_structure_fingerprint: str, + source_content_hash: str, + renderer_version: str, +) -> str: + """ + 构造预览缓存键(analysis_id + checksums + renderer_version)。 + + 核心逻辑:委托 PreviewIdentityContext 指纹,page_count/preview_render_checksum 置空 + 以便在渲染前即可定位缓存槽。 + + Args: + structure_analysis_id: 冻结结构分析 ID。 + template_packet_checksum: template packet 校验和。 + datasets_packet_checksum: datasets packet 校验和。 + dataset_structure_fingerprint: datasets 结构指纹。 + source_content_hash: 源 PDF 内容哈希。 + renderer_version: 合成器版本。 + + Returns: + 稳定十六进制缓存键。 + """ + ctx = PreviewIdentityContext( + document_id=None, + layout_version_id=None, + structure_analysis_id=structure_analysis_id, + source_content_hash=str(source_content_hash or ''), + template_packet_checksum=str(template_packet_checksum or ''), + datasets_packet_checksum=str(datasets_packet_checksum or ''), + dataset_structure_fingerprint=str(dataset_structure_fingerprint or ''), + preview_render_checksum='', + renderer_version=str(renderer_version or ''), + page_count=0, + ) + return build_preview_identity_fingerprint(ctx) + + +def get_preview_cache(key: str) -> dict[str, Any] | None: + """ + 读取预览缓存条目。 + + 核心逻辑:持锁检查 TTL;过期则删除并返回 None。 + + Args: + key: build_preview_cache_key 结果。 + + Returns: + 缓存的预览结果字典;未命中或过期时为 None。 + """ + text = str(key or '').strip() + if not text: + return None + now = time.time() + with _LOCK: + item = _CACHE.get(text) + if item is None: + return None + expires_at, payload = item + if expires_at <= now: + _CACHE.pop(text, None) + return None + return dict(payload) + + +def set_preview_cache( + key: str, + value: dict[str, Any], + *, + ttl_seconds: int = _DEFAULT_TTL_SECONDS, +) -> None: + """ + 写入预览缓存条目。 + + Args: + key: 缓存键。 + value: 可浅拷贝的预览结果字典(调用方勿放入不可序列化巨型对象以外的副作用状态)。 + ttl_seconds: 存活秒数;最小 1。 + """ + text = str(key or '').strip() + if not text or not isinstance(value, dict): + return + expires_at = time.time() + max(1, int(ttl_seconds)) + with _LOCK: + _CACHE[text] = (expires_at, dict(value)) + + +def invalidate_preview_cache(key: str | None = None) -> None: + """ + 使预览缓存失效。 + + 核心逻辑:key 为空时清空全部;否则仅删除指定键。 + + Args: + key: 可选缓存键;None/空串表示清空。 + """ + with _LOCK: + if not key: + _CACHE.clear() + return + _CACHE.pop(str(key), None) + + +def clear_preview_cache() -> None: + """清空全部预览缓存(测试辅助)。""" + invalidate_preview_cache(None) diff --git a/backend/app/services/shipping_notice/document_layout/xfa_preview_contract.py b/backend/app/services/shipping_notice/document_layout/xfa_preview_contract.py new file mode 100644 index 00000000..17491ca7 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/xfa_preview_contract.py @@ -0,0 +1,185 @@ +""" +services/shipping_notice/document_layout/xfa_preview_contract.py + +用途:冻结 XFA 自研静态合成预览(Phase 1 POC)契约——render_mode、预览状态、 + 错误码、身份上下文、审计事件名与确定性指纹辅助。 +依赖:标准库 dataclasses/hashlib/json;被 xfa_preview_renderer / xfa_preview_cache / + 后续预览 API 与审计接线引用。 +逻辑:本模块只定义纯数据与纯函数,不读 PDF、不渲染、不落库;身份字段与 + preview_render_checksum 必须与合成器输出一致,供 stale 判定与发布证据绑定。 +""" + +from __future__ import annotations + +import hashlib +import json +from dataclasses import asdict, dataclass +from typing import Any, Final, Literal + +# --------------------------------------------------------------------------- +# 渲染模式 / 预览状态 +# --------------------------------------------------------------------------- + +RENDER_MODE: Final[str] = 'xfa_dataset_preview' + +XfaPreviewStatus = Literal['ready', 'needs_review', 'failed', 'stale'] +XFA_PREVIEW_STATUSES: Final[frozenset[str]] = frozenset({ + 'ready', + 'needs_review', + 'failed', + 'stale', +}) + +# --------------------------------------------------------------------------- +# 稳定错误码(短码;AppError 层可映射为 SHIPPING.ORDER_DOCUMENT_PROFILE_*) +# --------------------------------------------------------------------------- + +XFA_PREVIEW_STALE: Final[str] = 'XFA_PREVIEW_STALE' +XFA_PREVIEW_FAILED: Final[str] = 'XFA_PREVIEW_FAILED' +XFA_PREVIEW_UNAVAILABLE: Final[str] = 'XFA_PREVIEW_UNAVAILABLE' +XFA_PREVIEW_PAGE_INCONSISTENT: Final[str] = 'XFA_PREVIEW_PAGE_INCONSISTENT' +XFA_PREVIEW_VALUE_MISMATCH: Final[str] = 'XFA_PREVIEW_VALUE_MISMATCH' + +XFA_PREVIEW_ERROR_CODES: Final[frozenset[str]] = frozenset({ + XFA_PREVIEW_STALE, + XFA_PREVIEW_FAILED, + XFA_PREVIEW_UNAVAILABLE, + XFA_PREVIEW_PAGE_INCONSISTENT, + XFA_PREVIEW_VALUE_MISMATCH, +}) + +# AppError / i18n 完整码(与 SHIPPING.ORDER_DOCUMENT_PROFILE_* 风格对齐) +SHIPPING_XFA_PREVIEW_STALE: Final[str] = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_STALE' +SHIPPING_XFA_PREVIEW_FAILED: Final[str] = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_FAILED' +SHIPPING_XFA_PREVIEW_UNAVAILABLE: Final[str] = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_UNAVAILABLE' +SHIPPING_XFA_PREVIEW_PAGE_INCONSISTENT: Final[str] = ( + 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_PAGE_INCONSISTENT' +) +SHIPPING_XFA_PREVIEW_VALUE_MISMATCH: Final[str] = ( + 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_VALUE_MISMATCH' +) + +XFA_PREVIEW_SHIPPING_ERROR_BY_CODE: Final[dict[str, str]] = { + XFA_PREVIEW_STALE: SHIPPING_XFA_PREVIEW_STALE, + XFA_PREVIEW_FAILED: SHIPPING_XFA_PREVIEW_FAILED, + XFA_PREVIEW_UNAVAILABLE: SHIPPING_XFA_PREVIEW_UNAVAILABLE, + XFA_PREVIEW_PAGE_INCONSISTENT: SHIPPING_XFA_PREVIEW_PAGE_INCONSISTENT, + XFA_PREVIEW_VALUE_MISMATCH: SHIPPING_XFA_PREVIEW_VALUE_MISMATCH, +} + +# --------------------------------------------------------------------------- +# 审计事件(预览生命周期) +# --------------------------------------------------------------------------- + +XFA_PREVIEW_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({ + 'xfa_preview_requested', + 'xfa_preview_generated', + 'xfa_preview_failed', + 'xfa_preview_viewed', + 'xfa_preview_stale', +}) + + +@dataclass(frozen=True) +class PreviewIdentityContext: + """ + 合成预览身份上下文:发布视觉证据与 stale 判定的冻结字段集合。 + + 任一关键校验和/指纹变化即视为预览身份漂移,不得继续当作 ready 证据。 + """ + + document_id: int | None + layout_version_id: int | None + structure_analysis_id: int | str | None + source_content_hash: str + template_packet_checksum: str + datasets_packet_checksum: str + dataset_structure_fingerprint: str + preview_render_checksum: str + render_mode: str = RENDER_MODE + renderer_version: str = '' + page_count: int = 0 + + +def shipping_error_code_for_preview(error_code: str | None) -> str | None: + """ + 将预览短错误码映射为 SHIPPING.ORDER_DOCUMENT_PROFILE_* AppError 码。 + + 核心逻辑:查 XFA_PREVIEW_SHIPPING_ERROR_BY_CODE;未知码原样返回。 + + Args: + error_code: 预览短错误码或已是完整 SHIPPING.* 码。 + + Returns: + 完整业务错误码;输入为空时返回 None。 + """ + text = str(error_code or '').strip() + if not text: + return None + if text.startswith('SHIPPING.'): + return text + return XFA_PREVIEW_SHIPPING_ERROR_BY_CODE.get(text, text) + + +def preview_identity_to_dict(ctx: PreviewIdentityContext) -> dict[str, Any]: + """ + 将 PreviewIdentityContext 序列化为可审计/可缓存的普通字典。 + + Args: + ctx: 预览身份上下文。 + + Returns: + 字段字典(不含额外派生键)。 + """ + return asdict(ctx) + + +def build_preview_identity_fingerprint(ctx: PreviewIdentityContext) -> str: + """ + 计算预览身份指纹(不含 preview_render_checksum 本身,避免循环依赖)。 + + 核心逻辑:对 document/layout/analysis/内容哈希/packet/结构指纹/render_mode/ + renderer_version/page_count 做稳定 JSON 序列化后 SHA-256。 + + Args: + ctx: 预览身份上下文。 + + Returns: + 64 位十六进制指纹字符串。 + """ + payload = { + 'document_id': ctx.document_id, + 'layout_version_id': ctx.layout_version_id, + 'structure_analysis_id': ctx.structure_analysis_id, + 'source_content_hash': str(ctx.source_content_hash or ''), + 'template_packet_checksum': str(ctx.template_packet_checksum or ''), + 'datasets_packet_checksum': str(ctx.datasets_packet_checksum or ''), + 'dataset_structure_fingerprint': str(ctx.dataset_structure_fingerprint or ''), + 'render_mode': str(ctx.render_mode or RENDER_MODE), + 'renderer_version': str(ctx.renderer_version or ''), + 'page_count': int(ctx.page_count or 0), + } + raw = json.dumps(payload, sort_keys=True, separators=(',', ':'), ensure_ascii=True) + return hashlib.sha256(raw.encode('utf-8')).hexdigest() + + +def is_preview_identity_stale( + *, + expected: PreviewIdentityContext, + actual: PreviewIdentityContext, +) -> bool: + """ + 判断实际预览身份是否相对期望身份已过期(stale)。 + + 核心逻辑:比较身份指纹与 preview_render_checksum;任一不等即 stale。 + + Args: + expected: 期望/冻结身份(例如绑定证据快照)。 + actual: 当前重新计算的身份。 + + Returns: + True 表示应标记 stale 并重新生成/重确认。 + """ + if build_preview_identity_fingerprint(expected) != build_preview_identity_fingerprint(actual): + return True + return str(expected.preview_render_checksum or '') != str(actual.preview_render_checksum or '') diff --git a/backend/app/services/shipping_notice/document_layout/xfa_preview_renderer.py b/backend/app/services/shipping_notice/document_layout/xfa_preview_renderer.py new file mode 100644 index 00000000..e3996dc0 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/xfa_preview_renderer.py @@ -0,0 +1,200 @@ +""" +services/shipping_notice/document_layout/xfa_preview_renderer.py + +用途:XFA 离线完整 flatten 入口(硬冻结 §0)。当前未接入可复现 flatten 引擎时 + 一律 fail-closed 返回 needs_review;禁止静态 overlay / 壳图充当 ready。 +依赖:xfa_preview_contract;未来真实引擎须离线、禁不受控脚本、输出可复现 checksum。 +逻辑:由预览编排服务调用 compose_xfa_dataset_preview_pages;settings + SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY=true 且引擎实现就绪后才可返回 ready。 +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass, field +from typing import Any + +from app.services.shipping_notice.document_layout.xfa_preview_contract import ( + RENDER_MODE, + XFA_PREVIEW_FAILED, + XFA_PREVIEW_UNAVAILABLE, + XfaPreviewStatus, +) + +# 版本号:v0_pending 表示尚未交付完整 flatten;不得与历史 overlay checksum 混用。 +RENDERER_VERSION = 'hxops.xfa_flatten.v0_pending' + + +@dataclass +class DrawnFieldEcho: + """单页上 flatten 回显痕迹(完整引擎就绪后使用)。""" + + path_id: str + value: str + normalized_bbox: dict[str, float] + page_no: int = 1 + + +@dataclass +class XfaPreviewComposeResult: + """flatten / 预览文档级结果;status!=ready 时 pages 为空。""" + + status: XfaPreviewStatus + error_code: str | None + render_mode: str + renderer_version: str + page_count: int + preview_render_checksum: str | None + pages: list[dict[str, Any]] = field(default_factory=list) + diagnostics: dict[str, Any] = field(default_factory=dict) + + def to_dict(self) -> dict[str, Any]: + """序列化为普通字典。""" + return { + 'status': self.status, + 'error_code': self.error_code, + 'render_mode': self.render_mode, + 'renderer_version': self.renderer_version, + 'page_count': self.page_count, + 'preview_render_checksum': self.preview_render_checksum, + 'pages': self.pages, + 'diagnostics': self.diagnostics, + } + + +def compute_preview_render_checksum( + *, + renderer_version: str, + pages: list[dict[str, Any]], +) -> str: + """ + 计算可复现的预览渲染校验和。 + + 核心逻辑:串联 renderer_version 与各页宽高/回显指纹/图像哈希后 SHA-256。 + + Args: + renderer_version: 合成器版本。 + pages: 含 width/height/drawn_field_echoes/png_bytes 的页列表。 + + Returns: + hex digest 字符串。 + """ + parts: list[str] = [str(renderer_version or '')] + for page in pages: + page_no = int(page.get('page_no') or 0) + width = float(page.get('width') or 0) + height = float(page.get('height') or 0) + echoes = page.get('drawn_field_echoes') if isinstance(page.get('drawn_field_echoes'), list) else [] + echo_fp = '|'.join( + f"{item.get('path_id')}:{item.get('value')}" + for item in echoes + if isinstance(item, dict) + ) + png = page.get('png_bytes') + img_hash = '' + if isinstance(png, (bytes, bytearray)) and png: + img_hash = hashlib.sha256(bytes(png)).hexdigest() + parts.append(f'{page_no}:{width}x{height}:{echo_fp}:{img_hash}') + return hashlib.sha256('\n'.join(parts).encode('utf-8')).hexdigest() + + +def is_xfa_flatten_engine_ready() -> bool: + """ + 完整离线 flatten 引擎是否已启用且可对外返回 ready。 + + 核心逻辑:读取 settings.SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY;默认 false。 + 引擎实现与人眼一致性完成前必须保持关闭。 + + Returns: + True 仅当显式开启(当前仍无真实引擎实现,开启也不会 ready)。 + """ + try: + from app.core.config.settings import Settings + + return bool(getattr(Settings, 'SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY', False)) + except Exception: # noqa: BLE001 + return False + + +def attempt_offline_xfa_flatten( + *, + pdf_bytes: bytes, + analysis_or_nodes: Any, + page_boxes: list[dict[str, Any]] | None = None, + template_bytes: bytes | None = None, +) -> XfaPreviewComposeResult: + """ + 尝试离线完整 XFA flatten(template + datasets → 有效 PDF/PNG)。 + + 核心逻辑:硬冻结要求删除 overlay;真实引擎未交付前一律 needs_review。 + 不得用 PDFium 壳图或黄框叠加冒充 ready。 + + Args: + pdf_bytes: 源 XFA PDF 字节。 + analysis_or_nodes: datasets 分析或叶子映射(预留)。 + page_boxes: 可选期望页框(预留)。 + template_bytes: 可选 template packet(预留)。 + + Returns: + 当前恒为 needs_review / failed;未来引擎就绪后返回 ready + pages。 + """ + del analysis_or_nodes, page_boxes, template_bytes # 真实引擎接入时启用 + if not pdf_bytes: + return XfaPreviewComposeResult( + status='failed', + error_code=XFA_PREVIEW_FAILED, + render_mode=RENDER_MODE, + renderer_version=RENDERER_VERSION, + page_count=0, + preview_render_checksum=None, + pages=[], + diagnostics={'reason': 'empty_pdf_bytes'}, + ) + # [STEP] 完整 flatten 未交付:fail-closed(禁止 overlay ready) + return XfaPreviewComposeResult( + status='needs_review', + error_code=XFA_PREVIEW_UNAVAILABLE, + render_mode=RENDER_MODE, + renderer_version=RENDERER_VERSION, + page_count=0, + preview_render_checksum=None, + pages=[], + diagnostics={ + 'reason': 'flatten_engine_unavailable', + 'message': ( + 'Offline reproducible XFA flatten is not available; ' + 'shell PDF / PDFium shell / overlay must not be used as canvas source' + ), + 'flatten_engine_ready_flag': is_xfa_flatten_engine_ready(), + 'operational_status': 'OPERATIONAL_PENDING', + }, + ) + + +def compose_xfa_dataset_preview_pages( + *, + pdf_bytes: bytes, + analysis_or_nodes: Any, + page_boxes: list[dict[str, Any]] | None = None, + template_bytes: bytes | None = None, +) -> XfaPreviewComposeResult: + """ + XFA 标注图源编排入口(对外保持原函数名以兼容调用方)。 + + 核心逻辑:委托 attempt_offline_xfa_flatten;未完成完整 flatten 前不得返回 ready。 + + Args: + pdf_bytes: 源 PDF 字节。 + analysis_or_nodes: datasets 分析或叶子映射。 + page_boxes: 可选期望页框。 + template_bytes: 可选 template packet。 + + Returns: + XfaPreviewComposeResult;当前预期 status=needs_review。 + """ + return attempt_offline_xfa_flatten( + pdf_bytes=pdf_bytes, + analysis_or_nodes=analysis_or_nodes, + page_boxes=page_boxes, + template_bytes=template_bytes, + ) diff --git a/backend/app/services/shipping_notice/document_layout/xfa_split_preview_token.py b/backend/app/services/shipping_notice/document_layout/xfa_split_preview_token.py index 53df5ec9..5597c07b 100644 --- a/backend/app/services/shipping_notice/document_layout/xfa_split_preview_token.py +++ b/backend/app/services/shipping_notice/document_layout/xfa_split_preview_token.py @@ -2,9 +2,10 @@ services/shipping_notice/document_layout/xfa_split_preview_token.py 用途:签发与校验 XFA 拆分规则预览确认令牌,防止客户端自行声明 confirmed。 -依赖:Flask current_app.SECRET_KEY、hmac、hashlib、time、secrets、redis_client(可选)。 +依赖:Flask current_app.SECRET_KEY、hmac、hashlib、time、secrets、redis_client。 逻辑:由 preview_xfa_split_rules 签发;save_draft / 确认接口经 verify_and_consume 原子消费 jti; - Redis 不可用时回退进程内 set + threading.Lock(单测与单进程开发友好,非多 Worker 生产语义)。 + 生产/预发/多 Worker:Redis 不可用时 fail-closed(STORE_UNAVAILABLE); + 仅 TESTING 或单进程 development(ALLOW_MEMORY_JTI)允许进程内兜底。 """ from __future__ import annotations @@ -12,6 +13,7 @@ from __future__ import annotations import hashlib import hmac import json +import logging import secrets import threading import time @@ -21,6 +23,8 @@ from flask import current_app from app.core.errors import ValidationError +_LOGGER = logging.getLogger(__name__) + # 预览确认令牌默认有效期(秒) DEFAULT_SPLIT_PREVIEW_TOKEN_TTL_SECONDS = 15 * 60 @@ -59,6 +63,40 @@ class _MemoryConsumedJtiStore: _memory_jti_store = _MemoryConsumedJtiStore() +def _allow_memory_jti_fallback() -> bool: + """ + 是否允许进程内 JTI 消费兜底。 + + 核心逻辑:pytest(TESTING)或明确开启 ALLOW_MEMORY_JTI 的单进程 development; + ENV_NAME 为 test/prod/staging 时一律禁止(即使误配开关)。 + + Returns: + True 仅当允许内存兜底。 + """ + if bool(current_app.config.get('TESTING')): + return True + env = str(current_app.config.get('ENV_NAME') or '').strip().lower() + if env in {'test', 'prod', 'production', 'staging', 'pre', 'uat'}: + return False + if env not in {'dev', 'development'}: + return False + return bool(current_app.config.get('XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI')) + + +def _raise_confirm_store_unavailable(*, reason: str) -> None: + """ + Redis 确认存储不可用时 fail-closed。 + + Raises: + ValidationError: SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_CONFIRM_STORE_UNAVAILABLE。 + """ + raise ValidationError( + 'XFA split confirmation store is temporarily unavailable', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_CONFIRM_STORE_UNAVAILABLE', + details={'reason': reason}, + ) + + def _signing_secret() -> bytes: """ 读取应用级签名密钥。 @@ -102,7 +140,8 @@ def _try_consume_jti(*, jti: str, ttl_seconds: int) -> bool: """ 原子消费令牌 jti。 - 核心逻辑:优先 Redis SET NX EX;失败或不可用时回退进程内 set + Lock。 + 核心逻辑:优先 Redis SET NX EX;Redis 不可用时仅在 testing/单进程 development + 回退进程内 store,否则抛 STORE_UNAVAILABLE(禁止多 Worker 不一致消费)。 Args: jti: 令牌唯一标识。 @@ -110,18 +149,31 @@ def _try_consume_jti(*, jti: str, ttl_seconds: int) -> bool: Returns: True 表示首次消费成功;False 表示已被消费。 + + Raises: + ValidationError: Redis 不可用且当前环境禁止内存兜底。 """ key = f'{_JTI_REDIS_KEY_PREFIX}{jti}' ttl = max(1, int(ttl_seconds)) + redis_error: Exception | None = None try: from app.services.redis_client import get_redis_client client = get_redis_client() if client is not None: return bool(client.set(key, '1', nx=True, ex=ttl)) - except Exception: - pass - return _memory_jti_store.try_consume(jti, ttl) + redis_error = RuntimeError('redis_client_unavailable') + except Exception as exc: # noqa: BLE001 — 任意 Redis 故障均需 fail-closed 决策 + redis_error = exc + _LOGGER.warning('XFA split preview token Redis consume failed: %s', exc) + + if _allow_memory_jti_fallback(): + return _memory_jti_store.try_consume(jti, ttl) + + _raise_confirm_store_unavailable( + reason='redis_unavailable' if redis_error is not None else 'redis_client_missing', + ) + return False # pragma: no cover — raise 已终止 def _validate_token_bindings( @@ -386,8 +438,8 @@ def verify_and_consume_split_preview_token( """ 验签并原子消费拆分预览确认令牌。 - 核心逻辑:验签与绑定校验通过后,以 Redis SET NX EX(或进程内兜底)标记 jti 已消费; - 重复消费抛 token_replay。 + 核心逻辑:验签与绑定校验通过后,以 Redis SET NX EX 标记 jti 已消费; + 重复消费抛 token_replay;Redis 不可用且非允许环境抛 STORE_UNAVAILABLE。 Args: token: 预览接口返回的令牌。 @@ -405,7 +457,7 @@ def verify_and_consume_split_preview_token( 已校验且已消费的 payload dict。 Raises: - ValidationError: 令牌无效、绑定不匹配或已被消费(重放)。 + ValidationError: 令牌无效、绑定不匹配、已被消费,或确认存储不可用。 """ payload = _decode_and_verify_signature(token) _validate_token_bindings( diff --git a/backend/app/services/shipping_notice/document_layout/xfa_template_parser.py b/backend/app/services/shipping_notice/document_layout/xfa_template_parser.py new file mode 100644 index 00000000..0436a164 --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/xfa_template_parser.py @@ -0,0 +1,294 @@ +""" +services/shipping_notice/document_layout/xfa_template_parser.py + +用途:防御性解析 XFA template packet,提取 field/draw 节点的 bind 引用与近似几何 + (x/y/w/h 属性),供自研静态合成预览定位回显文本。 +依赖:lxml、xfa_packets.preflight_xml_bytes、xfa_dataset._hardened_parser 模式。 +逻辑:由 xfa_preview_renderer 调用;不执行 JS/FormCalc、不联网;解析失败返回空列表。 +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Any + +from lxml import etree + +from app.services.shipping_notice.document_layout.xfa_packets import XfaPacketError, preflight_xml_bytes + +_DIMENSION_RE = re.compile( + r'^\s*(?P-?\d+(?:\.\d+)?)\s*(?Ppt|mm|in|cm|px)?\s*$', + re.IGNORECASE, +) +# 常见页面参考尺寸(Letter pt),仅用于将绝对单位粗略归一化。 +_DEFAULT_PAGE_WIDTH_PT = 612.0 +_DEFAULT_PAGE_HEIGHT_PT = 792.0 +_FIELD_DRAW_LOCAL_NAMES = frozenset({'field', 'draw'}) + + +@dataclass(frozen=True) +class XfaTemplateFieldGeometry: + """ + template 中可定位的 field/draw 摘要。 + + 坐标为页面相对归一化框(左上原点 0..1);无法可靠归一化时 normalized_bbox 为空。 + """ + + name: str + bind_ref: str + page_no: int + raw_x: float | None + raw_y: float | None + raw_w: float | None + raw_h: float | None + normalized_bbox: dict[str, float] | None + local_name: str + + +def _local_name(tag: str) -> str: + """提取 XML localName,忽略命名空间前缀。""" + return str(tag or '').rsplit('}', 1)[-1].lower() + + +def _hardened_parser() -> etree.XMLParser: + """ + 构造禁用外部实体与 DTD 的 lxml 解析器。 + + Returns: + 与 datasets 解析同策略的安全 XMLParser。 + """ + return etree.XMLParser( + resolve_entities=False, + load_dtd=False, + no_network=True, + huge_tree=False, + ) + + +def _parse_dimension(raw: str | None) -> float | None: + """ + 解析 XFA 尺寸属性(可带 pt/mm/in/cm/px 后缀)为浮点数。 + + 核心逻辑:无单位时原样返回数值;有单位时统一换算为 pt(近似)。 + + Args: + raw: 属性字符串,如 ``36pt``、``10mm``、``0.25``。 + + Returns: + 数值(pt 或无单位原值);无法解析时返回 None。 + """ + text = str(raw or '').strip() + if not text: + return None + match = _DIMENSION_RE.match(text) + if not match: + return None + try: + value = float(match.group('value')) + except (TypeError, ValueError): + return None + unit = (match.group('unit') or '').lower() + if not unit or unit == 'pt' or unit == 'px': + return value + if unit == 'in': + return value * 72.0 + if unit == 'mm': + return value * 72.0 / 25.4 + if unit == 'cm': + return value * 72.0 / 2.54 + return value + + +def _attr(element: etree._Element, *names: str) -> str: + """按候选属性名读取第一个非空值(忽略命名空间前缀)。""" + for name in names: + for key, value in element.attrib.items(): + local = str(key).rsplit('}', 1)[-1] + if local.lower() == name.lower() and str(value or '').strip(): + return str(value).strip() + return '' + + +def _extract_bind_ref(element: etree._Element) -> str: + """ + 从 field/draw 或其 bind 子节点提取 dataRef。 + + 核心逻辑:优先读子节点 ``bind`` 的 ref/dataRef;否则读自身 bind/ref 属性。 + """ + direct = _attr(element, 'bind', 'ref', 'dataRef') + if direct: + return direct + for child in element: + if not isinstance(child.tag, str): + continue + if _local_name(child.tag) != 'bind': + continue + ref = _attr(child, 'ref', 'dataRef', 'match') + if ref and ref.lower() not in {'none', 'dataref', 'once', 'global', 'dataRef'.lower()}: + return ref + # match="dataRef" 时真正路径常在 ref + ref2 = _attr(child, 'ref', 'dataRef') + if ref2: + return ref2 + return '' + + +def _normalize_bbox_from_raw( + *, + x: float | None, + y: float | None, + w: float | None, + h: float | None, + page_width: float, + page_height: float, +) -> dict[str, float] | None: + """ + 将 template 原始 x/y/w/h 粗略归一化为左上原点 0..1 框。 + + 核心逻辑:若数值均落在 0..1 则视为已归一化;否则按 page pt 尺寸换算。 + XFA 模板常以左下为原点,此处按「y 为距底边」尝试翻转;若翻转后越界则按左上解释。 + + Args: + x/y/w/h: 原始尺寸(pt 或相对)。 + page_width/page_height: 参考页尺寸(pt)。 + + Returns: + ``{x0,y0,x1,y1}``;无法构成有效框时返回 None。 + """ + if x is None or y is None or w is None or h is None: + return None + if w <= 0 or h <= 0: + return None + if page_width <= 0 or page_height <= 0: + return None + + # [STEP 1] 已是相对坐标 + if 0.0 <= x <= 1.0 and 0.0 <= y <= 1.0 and 0.0 < w <= 1.0 and 0.0 < h <= 1.0: + x0, y0, x1, y1 = x, y, x + w, y + h + else: + # [STEP 2] 绝对 pt:优先按 PDF 左下原点翻转 + x0 = x / page_width + x1 = (x + w) / page_width + y0_flip = 1.0 - ((y + h) / page_height) + y1_flip = 1.0 - (y / page_height) + y0_top = y / page_height + y1_top = (y + h) / page_height + if 0.0 <= y0_flip <= 1.0 and 0.0 <= y1_flip <= 1.0 and y1_flip > y0_flip: + y0, y1 = y0_flip, y1_flip + else: + y0, y1 = y0_top, y1_top + + x0 = max(0.0, min(1.0, x0)) + x1 = max(0.0, min(1.0, x1)) + y0 = max(0.0, min(1.0, y0)) + y1 = max(0.0, min(1.0, y1)) + if x1 <= x0 or y1 <= y0: + return None + return {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1} + + +def _resolve_page_no(element: etree._Element, default_page: int = 1) -> int: + """从节点或其祖先读取 page/pageNum 属性;非法时回退 default_page。""" + current: etree._Element | None = element + while current is not None: + raw = _attr(current, 'page', 'pageNum', 'page_no') + if raw: + try: + value = int(float(raw)) + if value >= 1: + return value + except (TypeError, ValueError): + pass + parent = current.getparent() + current = parent if isinstance(parent, etree._Element) else None + return max(1, int(default_page)) + + +def parse_xfa_template_field_geometries( + template_bytes: bytes, + *, + page_width: float = _DEFAULT_PAGE_WIDTH_PT, + page_height: float = _DEFAULT_PAGE_HEIGHT_PT, +) -> list[XfaTemplateFieldGeometry]: + """ + 解析 XFA template packet,提取带 bind 与近似位置的 field/draw 节点。 + + 核心逻辑:preflight → hardened lxml 解析 → 遍历 field/draw;读取 name/bind 与 + x/y/w/h;失败或不可解析时返回空列表(不抛给调用方)。 + + Args: + template_bytes: template packet XML 字节。 + page_width: 用于绝对坐标归一化的参考页宽(pt)。 + page_height: 用于绝对坐标归一化的参考页高(pt)。 + + Returns: + 几何摘要列表;不可解析时为空列表。 + """ + if not template_bytes: + return [] + try: + preflight_xml_bytes(template_bytes) + root = etree.fromstring(template_bytes, parser=_hardened_parser()) + except (XfaPacketError, etree.XMLSyntaxError, ValueError, TypeError, OSError): + return [] + except Exception: + return [] + + results: list[XfaTemplateFieldGeometry] = [] + for element in root.iter(): + if not isinstance(element.tag, str): + continue + local = _local_name(element.tag) + if local not in _FIELD_DRAW_LOCAL_NAMES: + continue + name = _attr(element, 'name') or local + bind_ref = _extract_bind_ref(element) + x = _parse_dimension(_attr(element, 'x')) + y = _parse_dimension(_attr(element, 'y')) + w = _parse_dimension(_attr(element, 'w', 'width')) + h = _parse_dimension(_attr(element, 'h', 'height')) + page_no = _resolve_page_no(element) + bbox = _normalize_bbox_from_raw( + x=x, y=y, w=w, h=h, page_width=page_width, page_height=page_height, + ) + results.append(XfaTemplateFieldGeometry( + name=name, + bind_ref=bind_ref, + page_no=page_no, + raw_x=x, + raw_y=y, + raw_w=w, + raw_h=h, + normalized_bbox=bbox, + local_name=local, + )) + return results + + +def serialize_template_field_geometries( + items: list[XfaTemplateFieldGeometry], +) -> list[dict[str, Any]]: + """ + 将 template 几何摘要序列化为普通字典列表(测试/诊断用)。 + + Args: + items: parse_xfa_template_field_geometries 结果。 + + Returns: + 可 JSON 化的字典列表。 + """ + return [ + { + 'name': item.name, + 'bind_ref': item.bind_ref, + 'page_no': item.page_no, + 'raw_x': item.raw_x, + 'raw_y': item.raw_y, + 'raw_w': item.raw_w, + 'raw_h': item.raw_h, + 'normalized_bbox': item.normalized_bbox, + 'local_name': item.local_name, + } + for item in items + ] 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 4a34ede2..3b04deed 100644 --- a/backend/app/services/shipping_notice/document_profile_quality_service.py +++ b/backend/app/services/shipping_notice/document_profile_quality_service.py @@ -690,7 +690,7 @@ def list_independent_samples(*, suite_id: int, actor_id: int) -> dict[str, Any]: # [STEP 1] XFA 草稿只列出文档级结构分析候选,不走 MinerU 表格身份。 if _is_xfa_profile(profile): - from app.models import ShippingXfaStructureAnalysis + from app.models import ShippingXfaStructureAnalysis # noqa: F401 — 保留导入兼容历史引用 for document in documents_by_id.values(): if document.id in excluded: @@ -706,13 +706,16 @@ def list_independent_samples(*, suite_id: int, actor_id: int) -> dict[str, Any]: if candidate_key in candidate_keys: continue candidate_keys.add(candidate_key) - analysis = ( - ShippingXfaStructureAnalysis.query.filter_by( - document_id=int(document.id), analysis_status='ready', + try: + from app.core.errors import ValidationError as _XfaValidationError + from app.services.shipping_notice.document_layout.xfa_analysis import ( + resolve_frozen_xfa_structure_analysis, ) - .order_by(ShippingXfaStructureAnalysis.id.desc()) - .first() - ) + + layout_version, analysis, _capability = resolve_frozen_xfa_structure_analysis(document) + except _XfaValidationError: + analysis = None + layout_version = None if analysis is None: result.append({ 'document_id': document.id, @@ -732,7 +735,7 @@ def list_independent_samples(*, suite_id: int, actor_id: int) -> dict[str, Any]: 'layout_issue_codes': ['xfa_structure_analysis_pending'], }) continue - identity_token = int(analysis.layout_version_id or analysis.id) + identity_token = int(getattr(layout_version, 'id', None) or analysis.layout_version_id or analysis.id) payload_checksum = str( analysis.datasets_packet_checksum or analysis.dataset_structure_fingerprint or '', )[:64] or None @@ -998,21 +1001,22 @@ def add_sample( raise ConflictError('Blind test samples must be independent of modelling samples', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT') if _is_xfa_profile(profile): parser = _xfa_definition_contract(profile) - from app.models import ShippingXfaStructureAnalysis - document = db.session.get(ShippingOrderDocument, int(document_id)) - analysis = ( - ShippingXfaStructureAnalysis.query.filter_by(document_id=int(document_id), analysis_status='ready') - .order_by(ShippingXfaStructureAnalysis.id.desc()) - .first() + from app.services.shipping_notice.document_layout.xfa_analysis import ( + resolve_frozen_xfa_structure_analysis, ) - if document is None or analysis is None: - raise ValidationError('Test sample XFA evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') + document = db.session.get(ShippingOrderDocument, int(document_id)) + if document is None: + raise ValidationError( + 'Test sample XFA evidence is unavailable', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID', + ) + layout_version, analysis, _capability = resolve_frozen_xfa_structure_analysis(document) # 预跑一次确保真值对应的文档可被当前草稿读取。 _candidate_for_xfa_sample(profile=profile, document_id=int(document_id)) resolved_table_id = XFA_DOCUMENT_TABLE_ID sample = ShippingDocumentProfileTestSample( suite_id=suite.id, document_id=int(document_id), table_id=resolved_table_id, - layout_version_id=analysis.layout_version_id, + layout_version_id=int(layout_version.id), layout_payload_checksum=str(analysis.datasets_packet_checksum or analysis.dataset_structure_fingerprint or '')[:64] or None, layout_parser_key=XFA_PARSER_IDENTITY, layout_parser_version=str(analysis.parser_identity or XFA_PARSER_IDENTITY), diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index 8261ee5a..ffa3c7ec 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -805,6 +805,15 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: task = resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang)) + # [STEP] 工作台传入期望 OT/Case/Run 时做归属 fail-closed。 + from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership + assert_notice_task_ownership( + task, + expected_order_task_no=str(payload.get('expected_order_task_no') or '').strip() or None, + expected_review_case_no=str(payload.get('expected_review_case_no') or '').strip() or None, + expected_run_no=str(payload.get('expected_run_no') or '').strip() or None, + actor_id=actor_id, + ) disposition_gate = _task_disposition_gate_response(task) if disposition_gate is not None: return disposition_gate @@ -1111,6 +1120,14 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: task = resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang)) + from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership + assert_notice_task_ownership( + task, + expected_order_task_no=str(payload.get('expected_order_task_no') or '').strip() or None, + expected_review_case_no=str(payload.get('expected_review_case_no') or '').strip() or None, + expected_run_no=str(payload.get('expected_run_no') or '').strip() or None, + actor_id=actor_id, + ) disposition_gate = _task_disposition_gate_response(task) if disposition_gate is not None: return disposition_gate @@ -1305,6 +1322,14 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: task = resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang)) + from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership + assert_notice_task_ownership( + task, + expected_order_task_no=str(payload.get('expected_order_task_no') or '').strip() or None, + expected_review_case_no=str(payload.get('expected_review_case_no') or '').strip() or None, + expected_run_no=str(payload.get('expected_run_no') or '').strip() or None, + actor_id=_event_actor_id(payload), + ) disposition_gate = _task_disposition_gate_response(task) if disposition_gate is not None: return disposition_gate 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 74016632..8d3d2ea8 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 @@ -60,24 +60,29 @@ def _initial_coordinate_definition(main_table_id: str) -> dict[str, Any]: } -def _latest_ready_xfa_analysis(document_id: int) -> ShippingXfaStructureAnalysis | None: +def _frozen_ready_xfa_analysis(document: ShippingOrderDocument) -> ShippingXfaStructureAnalysis | None: """ - 读取文档最新 ready 态 XFA 结构分析。 + 读取文档当前 Layout 冻结的 ready 态 XFA 结构分析。 + + 核心逻辑:委托 resolve_frozen_xfa_structure_analysis;缺失时返回 None(由调用方 fail-closed)。 Args: - document_id: ShippingOrderDocument 主键。 + document: ShippingOrderDocument。 Returns: - ready 分析记录;不存在则 None。 + ready 分析记录;冻结身份不可用则 None。 """ - return ( - ShippingXfaStructureAnalysis.query.filter_by( - document_id=int(document_id), analysis_status='ready', - ) - .order_by(ShippingXfaStructureAnalysis.id.desc()) - .first() + from app.core.errors import ValidationError as _ValidationError + from app.services.shipping_notice.document_layout.xfa_analysis import ( + resolve_frozen_xfa_structure_analysis, ) + try: + _layout, analysis, _capability = resolve_frozen_xfa_structure_analysis(document) + except _ValidationError: + return None + return analysis + def _new_profile_code() -> str: """生成新模板族的服务端系统编码,避免客户端命名参与解析、版本和审计主键。""" @@ -114,13 +119,15 @@ def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str, ) layout = profile_service._document_layout(document) xfa_ready = profile_service._layout_is_xfa_analysis_ready(layout) - analysis = _latest_ready_xfa_analysis(document.id) if xfa_ready else None + analysis = _frozen_ready_xfa_analysis(document) if xfa_ready else None if xfa_ready and analysis is None: - raise ValidationError( - 'XFA structure analysis is unavailable', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_UNAVAILABLE', + from app.services.shipping_notice.document_layout.xfa_analysis import ( + resolve_frozen_xfa_structure_analysis, ) + # 再走一次以抛出精确 MISSING / IDENTITY_MISMATCH / STALE 错误码 + resolve_frozen_xfa_structure_analysis(document) + # [STEP 1] 按样本能力分支:XFA 不要求 table_id;坐标仍校验主表。 sample_table_id: str | None = None if analysis is not None: diff --git a/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py b/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py index e2688ec6..e173cfd3 100644 --- a/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_publish_check_service.py @@ -5,8 +5,9 @@ services/shipping_notice/order_document_profile_publish_check_service.py 依赖:草稿 Revision、验证运行、版面/XFA 结构签名、跨模板重叠验证、语义差异、发布服务、 编辑租约服务、xfa_validation 视觉指标与统一 bindings。 逻辑:报告冻结当前草稿身份与签名/重叠引用;XFA 模式使用结构签名、路径/集合/对账阻断, - 以及视觉绑定完整性与 visual/evidence 100% 阈值;消费时在同一事务再次校验并发布, - 草稿或签名变化只能令报告失效;编辑人不得批准自己的 Revision。 + 以及字段级混合数据源可发布性与跨源 OCR mismatch 清零; + 不再要求 flatten/synthetic ready / renderer_version / preview checksum; + 消费时在同一事务再次校验并发布,草稿或签名变化只能令报告失效;编辑人不得批准自己的 Revision。 """ from __future__ import annotations @@ -167,6 +168,7 @@ def _blocking_xfa_definition( """ blocking: list[dict[str, Any]] = [] definition = dict(profile.definition_json or {}) + # 硬冻结(2026-08-07):flatten 未就绪不再阻断人工模板发布。 source = definition.get('source_contract') if isinstance(definition.get('source_contract'), dict) else {} if not source.get('template_packet_checksum') or not source.get('dataset_structure_fingerprint'): blocking.append({ @@ -366,16 +368,69 @@ def _blocking_xfa_definition( return blocking +def _resolve_xfa_preview_publish_evidence( + definition: dict[str, Any], + bindings_list: list[Any], +) -> tuple[str | None, str | None]: + """ + 从 definition.xfa_preview 或已确认 visual_binding 共识解析发布用合成预览证据。 + + 核心逻辑:优先读 definition.xfa_preview;否则要求每个 confirmed binding 携带相同 + 非空 preview_render_checksum,并据此推断 preview_status=ready。 + + Args: + definition: XFA definition JSON。 + bindings_list: definition.bindings 列表。 + + Returns: + (preview_status, preview_render_checksum);证据不足时 checksum 为 None。 + """ + preview_meta = definition.get('xfa_preview') if isinstance(definition.get('xfa_preview'), dict) else {} + status = str(preview_meta.get('status') or '').strip().lower() or None + checksum = str(preview_meta.get('preview_render_checksum') or '').strip() or None + + confirmed_checksums: set[str] = set() + confirmed_missing = False + for raw in bindings_list: + if not isinstance(raw, dict): + continue + visual = raw.get('visual_binding') if isinstance(raw.get('visual_binding'), dict) else {} + if str(visual.get('status') or '') != 'confirmed': + continue + item_checksum = str(visual.get('preview_render_checksum') or '').strip() + if not item_checksum: + confirmed_missing = True + continue + confirmed_checksums.add(item_checksum) + + if not checksum: + if confirmed_missing or not confirmed_checksums: + return status, None + if len(confirmed_checksums) != 1: + return status, None + checksum = next(iter(confirmed_checksums)) + if not status: + status = 'ready' + elif confirmed_checksums and (checksum not in confirmed_checksums or confirmed_missing): + # 已确认绑定缺少或与 definition 摘要不一致 → 视为缺证据 + return status, None + elif not status and checksum: + status = 'ready' + return status, checksum + + def _blocking_xfa_visual_bindings( *, definition: dict[str, Any], schema_field_ids: set[str], ) -> list[dict[str, Any]]: """ - 校验统一视觉绑定是否满足发布门禁。 + 校验统一绑定是否满足发布门禁(原生 PDF 画布 + 字段级混合数据源)。 核心逻辑:XFA 无 bindings 一律阻断;bindings 与 legacy mappings 共存 → - xfa_dual_binding_source;已有 bindings 时每个正式 Schema 字段须 is_formal_binding_publishable。 + xfa_dual_binding_source;正式字段须 is_formal_binding_publishable + (datasets 视觉可选;坐标/OCR 须 confirmed);未处理跨源 OCR mismatch 必须为 0。 + 不再要求 synthetic preview ready / renderer_version / preview checksum。 """ from app.services.shipping_notice.document_layout.xfa_contract import ( XfaUnifiedFieldBinding, @@ -409,7 +464,7 @@ def _blocking_xfa_visual_bindings( if has_xfa_dataset and not bindings_list: blocking.append({ 'key': 'xfa_visual_bindings_required', - 'message': 'Unified visual bindings are required before publishing an XFA profile.', + 'message': 'Unified field bindings are required before publishing an XFA profile.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', 'reason_code': 'xfa_visual_bindings_required', }) @@ -440,7 +495,10 @@ def _blocking_xfa_visual_bindings( if incomplete: blocking.append({ 'key': 'xfa_visual_binding_incomplete', - 'message': 'Every formal Schema-mapped field must have a confirmed visual binding.', + 'message': ( + 'Every formal Schema-mapped field must have a publishable binding ' + '(datasets path, or confirmed visual for coordinate/OCR).' + ), 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', 'reason_code': 'xfa_visual_binding_incomplete', 'field_ids': incomplete[:20], @@ -449,14 +507,60 @@ def _blocking_xfa_visual_bindings( if coverage < 1.0 and 'xfa_visual_binding_incomplete' not in {item.get('key') for item in blocking}: blocking.append({ 'key': 'xfa_visual_coverage_insufficient', - 'message': 'Visual binding coverage must be 100% before publish.', + 'message': 'Formal field publishable coverage must be 100% before publish.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', 'reason_code': 'xfa_visual_coverage_insufficient', 'visual_coverage_rate': coverage, }) + + # [STEP] 跨源 OCR mismatch 清零(不再要求 synthetic ready / checksum / renderer) + if has_xfa_dataset or str(definition.get('template_mode') or '') == 'xfa_dataset': + mismatch_blocking = _blocking_xfa_unresolved_ocr_mismatch(definition) + existing_keys = {item.get('key') for item in blocking} + for item in mismatch_blocking: + if item.get('key') in existing_keys: + continue + blocking.append(item) + existing_keys.add(item.get('key')) return blocking +def _blocking_xfa_unresolved_ocr_mismatch(definition: dict[str, Any]) -> list[dict[str, Any]]: + """ + 发布前要求未处理跨源 OCR/datasets mismatch 为 0。 + + 核心逻辑:读取 definition.xfa_ocr_automark / xfa_preview 中的 + unresolved_ocr_mismatch_count;缺失视为 0。 + + Args: + definition: XFA definition。 + + Returns: + 阻断项列表(至多一项)。 + """ + preview_meta = definition.get('xfa_preview') if isinstance(definition.get('xfa_preview'), dict) else {} + automark_meta = ( + definition.get('xfa_ocr_automark') + if isinstance(definition.get('xfa_ocr_automark'), dict) + else {} + ) + unresolved = preview_meta.get('unresolved_ocr_mismatch_count') + if unresolved is None: + unresolved = automark_meta.get('unresolved_ocr_mismatch_count', 0) + try: + unresolved_count = int(unresolved or 0) + except (TypeError, ValueError): + unresolved_count = 0 + if unresolved_count <= 0: + return [] + return [{ + 'key': 'xfa_ocr_unresolved_mismatch', + 'message': 'Unresolved OCR/datasets mismatches must be cleared before publish.', + 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_MISMATCH', + 'reason_code': 'xfa_ocr_unresolved_mismatch', + 'unresolved_ocr_mismatch_count': unresolved_count, + }] + def _blocking_xfa_validation_metrics(summary: dict[str, Any]) -> list[dict[str, Any]]: """ 当 current-sample 摘要含统一指标时,要求视觉/证据覆盖率均为 100%。 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 2dfc91a4..4e294185 100644 --- a/backend/app/services/shipping_notice/order_document_profile_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_service.py @@ -378,47 +378,50 @@ def _assert_xfa_analysis_matches_live(*, analysis: Any, outcome: Any) -> None: ) -def resolve_xfa_path_context(document: ShippingOrderDocument) -> dict[str, Any]: +def resolve_xfa_path_context( + document: ShippingOrderDocument, + *, + layout_version_id: int | None = None, +) -> dict[str, Any]: """ - ???? PDF ? path_id ??????????checksum?? + 按当前(或指定)Layout 冻结 Analysis 解析 path_id 映射与样本 checksum。 - ??????? FileAsset ? analyze_xfa_pdf ? ?? path_id/data_path? - ? definition ????????? DTO ??? + 核心逻辑:resolve_frozen_xfa_structure_analysis → FileAsset → analyze_xfa_pdf → + 比对 live fingerprint(STALE)→ 构建 path_map。 Args: - document: ??????? + document: 样本文档。 + layout_version_id: 可选冻结 LayoutVersion(旧 Revision / 非 current)。 Returns: - ? path_map?analysis?dataset_root_path?template/dataset checksum ????? + 含 path_map、analysis、dataset_root_path、template/dataset checksum 等上下文字典。 Raises: - ValidationError: ??????? XFA? + ValidationError: Analysis 缺失/身份不一致/陈旧,或样本不可用。 """ - from app.models import ShippingXfaStructureAnalysis from app.services.file_assets.service import read_asset_bytes - from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf + from app.services.shipping_notice.document_layout.xfa_analysis import ( + analyze_xfa_pdf, + resolve_frozen_xfa_structure_analysis, + ) - analysis = ( - ShippingXfaStructureAnalysis.query.filter_by(document_id=int(document.id), analysis_status='ready') - .order_by(ShippingXfaStructureAnalysis.id.desc()) - .first() + _layout_version, analysis, _capability = resolve_frozen_xfa_structure_analysis( + document, + layout_version_id=layout_version_id, ) - if analysis is None: - raise ValidationError( - 'XFA structure analysis is unavailable', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_UNAVAILABLE', - ) asset = db.session.get(FileAsset, int(document.asset_id or 0)) if document.asset_id else None if asset is None: raise ValidationError( 'XFA sample asset is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_UNAVAILABLE', + details={'document_id': int(document.id), 'reason': 'asset_missing'}, ) outcome = analyze_xfa_pdf(read_asset_bytes(asset)) if outcome.dataset_analysis is None: raise ValidationError( 'XFA datasets are unavailable for path resolution', code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_UNAVAILABLE', + details={'document_id': int(document.id), 'reason': 'datasets_unavailable'}, ) _assert_xfa_analysis_matches_live(analysis=analysis, outcome=outcome) path_map: dict[str, str] = {} @@ -427,6 +430,7 @@ def resolve_xfa_path_context(document: ShippingOrderDocument) -> dict[str, Any]: known_ids = set(path_map.keys()) | set(outcome.dataset_analysis.known_path_ids) return { 'analysis': analysis, + 'layout_version_id': int(_layout_version.id), 'dataset_analysis': outcome.dataset_analysis, 'path_map': path_map, 'known_path_ids': known_ids, @@ -1955,7 +1959,9 @@ def _freeze_xfa_sample_evidence(profile: ShippingOrderDocumentProfile, *, frozen Returns: ????????? """ - from app.models import ShippingXfaStructureAnalysis + from app.services.shipping_notice.document_layout.xfa_analysis import ( + resolve_frozen_xfa_structure_analysis, + ) from app.services.shipping_notice.document_layout.xfa_contract import XFA_PARSER_IDENTITY samples = ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).order_by( @@ -1983,18 +1989,17 @@ def _freeze_xfa_sample_evidence(profile: ShippingOrderDocumentProfile, *, frozen 'Profile sample document is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', ) - analysis = ( - ShippingXfaStructureAnalysis.query.filter_by( - document_id=int(sample.document_id), analysis_status='ready', + try: + layout_version, analysis, _capability = resolve_frozen_xfa_structure_analysis( + document, + layout_version_id=int(sample.layout_version_id) if sample.layout_version_id else None, ) - .order_by(ShippingXfaStructureAnalysis.id.desc()) - .first() - ) - if analysis is None: + except ValidationError as exc: raise ConflictError( - 'XFA structure analysis is unavailable for publish freeze', + exc.message, code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', - ) + details=dict(exc.details or {}), + ) from exc if ( str(analysis.template_packet_checksum or '') != expected_template or str(analysis.dataset_structure_fingerprint or '') != expected_fingerprint @@ -2004,7 +2009,7 @@ def _freeze_xfa_sample_evidence(profile: ShippingOrderDocumentProfile, *, frozen code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', ) content_hash = str(document.content_hash or analysis.source_content_hash or '').strip().lower() - sample.layout_version_id = analysis.layout_version_id + sample.layout_version_id = int(layout_version.id) sample.source_content_hash = content_hash or str(analysis.source_content_hash or '') sample.layout_payload_checksum = str( analysis.datasets_packet_checksum or analysis.dataset_structure_fingerprint or '', @@ -2019,6 +2024,7 @@ def _freeze_xfa_sample_evidence(profile: ShippingOrderDocumentProfile, *, frozen sample.table_identity_snapshot = { 'kind': 'xfa_structure', 'structure_analysis_id': int(analysis.id), + 'layout_version_id': int(layout_version.id), 'template_packet_checksum': analysis.template_packet_checksum, 'datasets_packet_checksum': analysis.datasets_packet_checksum, 'dataset_structure_fingerprint': analysis.dataset_structure_fingerprint, @@ -4256,17 +4262,19 @@ def _require_sample_document(document_id: int) -> ShippingOrderDocument: def get_xfa_field_tree(document_id: int, *, actor_id: int | None) -> dict[str, Any]: """ - ??????? XFA ?????? DTO?? line_count?? + 返回样本冻结 Layout 绑定的 XFA 字段树 DTO。 + + 核心逻辑:resolve_frozen_xfa_structure_analysis → rebuild_tree_dto_from_analysis。 Args: - document_id: ShippingOrderDocument ??? - actor_id: ??? ID????? + document_id: ShippingOrderDocument 主键。 + actor_id: 操作者 ID(必填)。 Returns: - ??? DTO? + 字段树 DTO。 Raises: - NotFoundError: actor ????????? + NotFoundError / ValidationError: 样本或冻结 Analysis 不可用。 """ if actor_id is None: raise NotFoundError( @@ -4274,33 +4282,20 @@ def get_xfa_field_tree(document_id: int, *, actor_id: int | None) -> dict[str, A code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND', ) document = _require_sample_document(document_id) - from app.models import ShippingXfaStructureAnalysis from app.services.file_assets.service import read_asset_bytes - from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot - from app.services.shipping_notice.document_layout.xfa_analysis import rebuild_tree_dto_from_analysis + from app.services.shipping_notice.document_layout.xfa_analysis import ( + rebuild_tree_dto_from_analysis, + resolve_frozen_xfa_structure_analysis, + ) from app.services.shipping_notice.document_layout.xfa_contract import sanitize_xfa_dto - analysis = ( - ShippingXfaStructureAnalysis.query.filter_by(document_id=int(document.id)) - .order_by(ShippingXfaStructureAnalysis.id.desc()) - .first() - ) - layout = current_layout_snapshot(document) or {} - if analysis is None and not _layout_is_xfa_analysis_ready(layout): - raise ValidationError( - 'XFA structure analysis is unavailable', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_UNAVAILABLE', - ) - if analysis is None: - raise ValidationError( - 'XFA structure analysis record is missing', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_UNAVAILABLE', - ) + _layout_version, analysis, _capability = resolve_frozen_xfa_structure_analysis(document) asset = db.session.get(FileAsset, int(document.asset_id or 0)) if document.asset_id else None if asset is None: raise ValidationError( 'XFA sample asset is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_UNAVAILABLE', + details={'document_id': int(document.id), 'reason': 'asset_missing'}, ) pdf_bytes = read_asset_bytes(asset) payload = rebuild_tree_dto_from_analysis(analysis, pdf_bytes, include_values=True) @@ -4309,7 +4304,10 @@ def get_xfa_field_tree(document_id: int, *, actor_id: int | None) -> dict[str, A document_id=document.id, event_type='xfa_field_tree_accessed', actor_id=actor_id, - detail={'analysis_id': analysis.id}, + detail={ + 'analysis_id': analysis.id, + 'layout_version_id': int(_layout_version.id), + }, ) return sanitize_xfa_dto(payload) @@ -4481,17 +4479,19 @@ def _assign_xfa_collection_recommendations(candidates: list[dict[str, Any]]) -> def get_xfa_collections(document_id: int, *, actor_id: int | None) -> dict[str, Any]: """ - ?? XFA ?????????/????? + 返回样本冻结 Layout 绑定的 XFA 集合候选(权威/镜像)。 + + 核心逻辑:resolve_frozen → resolve_xfa_path_context → 候选 DTO。 Args: - document_id: ShippingOrderDocument ??? - actor_id: ??? ID????? + document_id: ShippingOrderDocument 主键。 + actor_id: 操作者 ID(必填)。 Returns: - ???? DTO????? XML?? + 集合候选 DTO。 Raises: - NotFoundError: actor ????????? + NotFoundError / ValidationError: 样本或冻结 Analysis 不可用。 """ if actor_id is None: raise NotFoundError( @@ -4499,20 +4499,13 @@ def get_xfa_collections(document_id: int, *, actor_id: int | None) -> dict[str, code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND', ) document = _require_sample_document(document_id) - from app.models import ShippingXfaStructureAnalysis + from app.services.shipping_notice.document_layout.xfa_analysis import ( + resolve_frozen_xfa_structure_analysis, + ) from app.services.shipping_notice.document_layout.xfa_contract import sanitize_xfa_dto - analysis = ( - ShippingXfaStructureAnalysis.query.filter_by(document_id=int(document.id)) - .order_by(ShippingXfaStructureAnalysis.id.desc()) - .first() - ) - if analysis is None or analysis.analysis_status != 'ready': - raise ValidationError( - 'XFA structure analysis is unavailable', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_UNAVAILABLE', - ) - context = resolve_xfa_path_context(document) + _layout_version, analysis, _capability = resolve_frozen_xfa_structure_analysis(document) + context = resolve_xfa_path_context(document, layout_version_id=int(_layout_version.id)) candidates = _assign_xfa_collection_recommendations([ _xfa_collection_candidate_dto(context['dataset_analysis'], item) for item in context['dataset_analysis'].collection_candidates @@ -4526,6 +4519,7 @@ def get_xfa_collections(document_id: int, *, actor_id: int | None) -> dict[str, actor_id=actor_id, detail={ 'analysis_id': analysis.id, + 'layout_version_id': int(_layout_version.id), 'dataset_structure_fingerprint': analysis.dataset_structure_fingerprint, 'selectable_count': len(selectable), 'excluded_count': len(excluded), @@ -4540,6 +4534,7 @@ def get_xfa_collections(document_id: int, *, actor_id: int | None) -> dict[str, ) return sanitize_xfa_dto({ 'analysis_id': analysis.id, + 'layout_version_id': int(_layout_version.id), 'document_kind': analysis.document_kind, 'dataset_structure_fingerprint': analysis.dataset_structure_fingerprint, 'template_packet_checksum': analysis.template_packet_checksum, @@ -4577,22 +4572,15 @@ def preview_xfa_sample_value( code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND', ) document = _require_sample_document(document_id) - from app.models import ShippingXfaStructureAnalysis from app.services.file_assets.service import read_asset_bytes - from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf + from app.services.shipping_notice.document_layout.xfa_analysis import ( + analyze_xfa_pdf, + resolve_frozen_xfa_structure_analysis, + ) from app.services.shipping_notice.document_layout.xfa_contract import assert_path_id_known, sanitize_xfa_dto from app.services.shipping_notice.document_layout.xfa_dataset import mask_value_for_dto - analysis = ( - ShippingXfaStructureAnalysis.query.filter_by(document_id=int(document.id)) - .order_by(ShippingXfaStructureAnalysis.id.desc()) - .first() - ) - if analysis is None or analysis.analysis_status != 'ready': - raise ValidationError( - 'XFA structure analysis is unavailable', - code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_UNAVAILABLE', - ) + _layout_version, analysis, _capability = resolve_frozen_xfa_structure_analysis(document) summary = analysis.tree_summary_json if isinstance(analysis.tree_summary_json, dict) else {} known_ids = set(summary.get('known_path_ids') or []) assert_path_id_known(str(path_id or ''), known_ids) @@ -4602,6 +4590,7 @@ def preview_xfa_sample_value( raise ValidationError( 'XFA sample asset is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_UNAVAILABLE', + details={'document_id': int(document.id), 'reason': 'asset_missing'}, ) outcome = analyze_xfa_pdf(read_asset_bytes(asset)) _assert_xfa_analysis_matches_live(analysis=analysis, outcome=outcome) @@ -4942,8 +4931,10 @@ def _reject_split_rule_confirmation(exc: ValidationError) -> None: """ 将令牌校验失败映射为显式确认拒绝(禁止静默降级 draft)。 + 核心逻辑:仅 TOKEN_INVALID 映射为 CONFIRM_REJECTED;STORE_UNAVAILABLE 等其它码原样抛出。 + Raises: - ValidationError: SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_CONFIRM_REJECTED 或原 TOKEN_INVALID。 + ValidationError: CONFIRM_REJECTED(令牌类)或原错误码(如 STORE_UNAVAILABLE)。 """ if exc.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID': raise ValidationError( diff --git a/backend/app/services/shipping_notice/order_document_profile_validation_service.py b/backend/app/services/shipping_notice/order_document_profile_validation_service.py index c9f46e68..7a730855 100644 --- a/backend/app/services/shipping_notice/order_document_profile_validation_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_validation_service.py @@ -1,7 +1,9 @@ """ services/shipping_notice/order_document_profile_validation_service.py -用途:执行订单文档 Profile 草稿的不可变即时检查、当前样本试运行、版面/XFA 结构签名与跨模板唯一性验证。 +用途:执行订单文档 Profile 草稿的不可变即时检查、当前样本试运行、版面/XFA 结构签名与跨模板唯一性验证; + 另提供合成预览发布门禁 assert_xfa_synthetic_preview_gate(全页 ready、checksum、 + unresolved OCR mismatch=0、renderer_version 共识;由 publish_check_service 接线)。 依赖:Profile Revision、受控样本、版面签名/匹配服务、XFA 提取与结构签名、解析校验、Profile 保存服务及编辑租约服务。 逻辑:每次运行先冻结草稿和样本证据身份,再只保存安全摘要;XFA current-sample 另附脱敏字段级 Header/Line; 签名成功后更新 Profile 轻量引用;跨模板重叠验证消费已发布快照与统一 matcher; @@ -49,6 +51,206 @@ def _profile(profile_id: int) -> ShippingOrderDocumentProfile: return profile +def assert_xfa_synthetic_preview_gate( + *, + template_mode: str | None, + preview_status: str | None, + preview_render_checksum: str | None, + bindings: list[dict[str, Any]] | None = None, + schema_field_ids: set[str] | None = None, + preview_meta: dict[str, Any] | None = None, + current_renderer_version: str | None = None, +) -> None: + """ + XFA 合成预览发布门禁(fail-closed)。 + + 核心逻辑:仅对 xfa_dataset 模式生效;preview_status 须 ready、须有 + preview_render_checksum,正式 Schema 字段 visual_binding 须全部 confirmed; + 另校验全页 ready、未解决 OCR mismatch=0、confirmed 绑定 renderer_version 一致。 + 普通 coordinate / plain PDF 直接放行。由 publish_check_service 接线消费。 + + Args: + template_mode: Profile template_mode(xfa_dataset 时强制门禁)。 + preview_status: 合成预览状态(须 ready)。 + preview_render_checksum: 合成器校验和。 + bindings: 统一 bindings 列表。 + schema_field_ids: 可选正式 Schema 字段集合;为空时检查全部 bindings。 + preview_meta: definition.xfa_preview 摘要(page_count / unresolved_ocr_mismatch_count)。 + current_renderer_version: 当前合成器版本;用于比对 confirmed 绑定。 + + Returns: + None(通过时)。 + + Raises: + ValidationError: 合成预览未就绪 / 缺 checksum / 视觉绑定未确认 / mismatch 未清。 + """ + mode = str(template_mode or '').strip() + if mode != 'xfa_dataset': + return + + blocking: list[dict[str, Any]] = [] + meta = preview_meta if isinstance(preview_meta, dict) else {} + + # [STEP 1] 合成预览必须 ready + status = str(preview_status or meta.get('status') or '').strip().lower() + if status != 'ready': + blocking.append({ + 'key': 'xfa_synthetic_preview_not_ready', + 'reason_code': 'xfa_synthetic_preview_not_ready', + 'message': 'XFA synthetic preview is not ready for publish', + 'preview_status': status or None, + }) + + # [STEP 2] 发布证据须绑定 preview_render_checksum + checksum = str(preview_render_checksum or meta.get('preview_render_checksum') or '').strip() + if not checksum: + blocking.append({ + 'key': 'xfa_preview_render_checksum_missing', + 'reason_code': 'xfa_preview_render_checksum_missing', + 'message': 'preview_render_checksum is required for XFA publish', + }) + + # [STEP 3] 全页合成就绪:page_count>0 且 pages_ready 齐全(若提供) + page_count = meta.get('page_count') + pages_ready = meta.get('pages_ready') + try: + page_count_int = int(page_count) if page_count not in (None, '') else 0 + except (TypeError, ValueError): + page_count_int = 0 + if page_count is not None and page_count_int <= 0: + blocking.append({ + 'key': 'xfa_preview_pages_incomplete', + 'reason_code': 'xfa_preview_pages_incomplete', + 'message': 'XFA synthetic preview page_count must be positive before publish', + 'page_count': page_count, + }) + elif isinstance(pages_ready, list) and page_count_int > 0: + ready_nos = {int(item) for item in pages_ready if str(item).isdigit() or isinstance(item, int)} + expected = set(range(1, page_count_int + 1)) + if ready_nos != expected: + blocking.append({ + 'key': 'xfa_preview_pages_incomplete', + 'reason_code': 'xfa_preview_pages_incomplete', + 'message': 'All synthetic preview pages must be ready before publish', + 'page_count': page_count_int, + 'pages_ready_count': len(ready_nos), + }) + + # [STEP 4] 未解决 OCR mismatch 必须为 0 + unresolved = meta.get('unresolved_ocr_mismatch_count') + if unresolved is None: + # 回退扫描 suggestions / bindings 上的 needs_review + automark = meta.get('xfa_ocr_automark') if isinstance(meta.get('xfa_ocr_automark'), dict) else None + if automark is None: + unresolved = 0 + else: + try: + unresolved = int(automark.get('unresolved_ocr_mismatch_count') or 0) + except (TypeError, ValueError): + unresolved = 0 + try: + unresolved_count = int(unresolved or 0) + except (TypeError, ValueError): + unresolved_count = 0 + if unresolved_count > 0: + blocking.append({ + 'key': 'xfa_ocr_unresolved_mismatch', + 'reason_code': 'xfa_ocr_unresolved_mismatch', + 'message': 'Unresolved OCR mismatches must be cleared before publish', + 'unresolved_ocr_mismatch_count': unresolved_count, + }) + + # [STEP 3b] 源页与合成页的逐页身份/page box 证据必须完整。 + page_evidence = meta.get('pages') if isinstance(meta.get('pages'), list) else None + source_count = meta.get('source_page_count') + synthetic_count = meta.get('synthetic_page_count') + if page_evidence is None or source_count is None or synthetic_count is None: + blocking.append({ + 'key': 'xfa_preview_page_identity_missing', + 'reason_code': 'xfa_preview_page_identity_missing', + 'message': 'Per-page source/synthetic page identity evidence is required before publish', + }) + else: + try: + source_count_int = int(source_count) + synthetic_count_int = int(synthetic_count) + except (TypeError, ValueError): + source_count_int = synthetic_count_int = 0 + if source_count_int <= 0 or source_count_int != synthetic_count_int or len(page_evidence) != source_count_int: + blocking.append({ + 'key': 'xfa_preview_page_identity_mismatch', + 'reason_code': 'xfa_preview_page_identity_mismatch', + 'message': 'Source and synthetic page counts/evidence must match', + }) + for page in page_evidence: + if not isinstance(page, dict) or not page.get('page_identity_hash') or page.get('source_page_box') != page.get('synthetic_page_box'): + blocking.append({ + 'key': 'xfa_preview_page_identity_mismatch', + 'reason_code': 'xfa_preview_page_identity_mismatch', + 'message': 'Every synthetic page must carry matching page box and identity hash', + }) + break + + # [STEP 5] 正式字段视觉绑定须 confirmed;确认凭据必须完整(含 renderer_version)且匹配当前版本 + required_ids = {str(item) for item in (schema_field_ids or set()) if str(item)} + items = [item for item in (bindings or []) if isinstance(item, dict)] + if required_ids: + items = [item for item in items if str(item.get('field_id') or '') in required_ids] + expected_renderer = str( + current_renderer_version + or meta.get('renderer_version') + or '' + ).strip() + if not items and required_ids: + blocking.append({ + 'key': 'xfa_visual_bindings_required', + 'reason_code': 'xfa_visual_bindings_required', + 'message': 'Unified visual bindings are required before publish', + }) + else: + incomplete = [] + renderer_mismatch = [] + for item in items: + visual = item.get('visual_binding') if isinstance(item.get('visual_binding'), dict) else {} + field_ref = str(item.get('field_id') or item.get('binding_id') or '') + if str(visual.get('status') or '') != 'confirmed': + incomplete.append(field_ref) + continue + item_checksum = str(visual.get('preview_render_checksum') or '').strip() + item_confirmed_on = str(visual.get('confirmed_on') or '').strip() + item_version = str(visual.get('renderer_version') or '').strip() + # BE-4:confirmed 必须携带 checksum + confirmed_on + renderer_version;版本非空时还须与当前一致 + if ( + not item_checksum + or item_confirmed_on != 'xfa_dataset_preview' + or not item_version + or (expected_renderer and item_version != expected_renderer) + ): + renderer_mismatch.append(field_ref) + if incomplete: + blocking.append({ + 'key': 'xfa_visual_binding_incomplete', + 'reason_code': 'xfa_visual_binding_incomplete', + 'message': 'Formal fields are missing confirmed visual bindings', + 'field_ids': incomplete, + }) + if renderer_mismatch: + blocking.append({ + 'key': 'xfa_preview_renderer_version_mismatch', + 'reason_code': 'xfa_preview_renderer_version_mismatch', + 'message': 'Confirmed visual bindings must carry matching renderer_version evidence', + 'field_ids': renderer_mismatch, + 'expected_renderer_version': expected_renderer or None, + }) + + if blocking: + raise ValidationError( + 'XFA synthetic preview publish gate blocked', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SYNTHETIC_PREVIEW_GATE', + details={'blocking': blocking}, + ) + + def _is_xfa_profile(profile: ShippingOrderDocumentProfile) -> bool: """ 判断草稿是否为 xfa_dataset 模式。 @@ -795,7 +997,10 @@ def run_xfa_structure_signature( 运行摘要 DTO(含 signature_checksum / structure fingerprint)。 """ _ = data - from app.models import ShippingXfaStructureAnalysis + from app.models import ShippingOrderDocument + from app.services.shipping_notice.document_layout.xfa_analysis import ( + resolve_frozen_xfa_structure_analysis, + ) from app.services.shipping_notice.document_layout.xfa_signature import build_xfa_structure_signature profile = _profile(profile_id) @@ -828,12 +1033,16 @@ def run_xfa_structure_signature( analysis_ids: list[int] = [] datasets_checksums: list[str] = [] for sample in samples: - analysis = ( - ShippingXfaStructureAnalysis.query.filter_by( - document_id=int(sample.document_id), analysis_status='ready', + document = db.session.get(ShippingOrderDocument, int(sample.document_id)) + if document is None: + raise ValidationError( + 'Profile sample document is unavailable', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_MISSING', + details={'document_id': int(sample.document_id)}, ) - .order_by(ShippingXfaStructureAnalysis.id.desc()) - .first() + _layout, analysis, _capability = resolve_frozen_xfa_structure_analysis( + document, + layout_version_id=int(sample.layout_version_id) if sample.layout_version_id else None, ) if analysis is None: raise ValidationError( diff --git a/backend/app/services/shipping_notice/order_document_profile_visual_binding_service.py b/backend/app/services/shipping_notice/order_document_profile_visual_binding_service.py index 38ad364c..cbad96b0 100644 --- a/backend/app/services/shipping_notice/order_document_profile_visual_binding_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_visual_binding_service.py @@ -2,9 +2,10 @@ backend/app/services/shipping_notice/order_document_profile_visual_binding_service.py 用途:XFA 统一视觉绑定的建议、确认、驳回编排(Lease、definition 更新与审计)。 -依赖:xfa_visual_binding、xfa_analysis、order_document_profile_service、lease_service、 - order_document_profile_audit_service(双写 Profile + 平台快照)。 -逻辑:admin API 调用本模块;建议只读不写 Draft;确认/驳回需租约并写 before/after 审计及加密 full 快照。 +依赖:xfa_visual_binding、xfa_analysis、order_document_profile_service、 + lease_service、order_document_profile_audit_service(双写 Profile + 平台快照)。 +逻辑:admin API 调用本模块;建议只读不写 Draft;确认/驳回需租约并写 before/after 审计; + 确认绑定原生 PDF 画布(confirmed_on=native_pdf);旧 synthetic 确认须重确认。 """ from __future__ import annotations @@ -31,6 +32,10 @@ from app.services.shipping_notice.order_document_profile_audit_service import ( record_visual_binding_audit, ) +# 原生 PDF 画布确认标识(硬冻结 2026-08-07)。 +NATIVE_PDF_CONFIRM_MODE = 'native_pdf' +_CONFIRM_REQUIRES_PAGE = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_CONFIRM_REQUIRES_PAGE' + def _profile(profile_id: int) -> ShippingOrderDocumentProfile: """读取 Profile;不存在时统一 not-found。""" @@ -163,6 +168,54 @@ def _find_binding(definition: dict[str, Any], binding_id: str) -> tuple[int, dic ) +def demote_legacy_synthetic_visual_bindings(definition: dict[str, Any]) -> dict[str, Any]: + """ + 将旧合成预览确认框降级为待重确认(不自动迁移坐标系)。 + + 核心逻辑:confirmed_on/render_mode 为 xfa_dataset_preview 的 confirmed 绑定 + → status=suggested,并清除合成证据字段。 + + Args: + definition: XFA definition(就地修改并返回)。 + + Returns: + 处理后的 definition。 + """ + bindings = definition.get('bindings') + if not isinstance(bindings, list): + return definition + changed = False + next_bindings: list[Any] = [] + for raw in bindings: + if not isinstance(raw, dict): + next_bindings.append(raw) + continue + visual = raw.get('visual_binding') if isinstance(raw.get('visual_binding'), dict) else None + if not visual: + next_bindings.append(raw) + continue + confirmed_on = str(visual.get('confirmed_on') or '').strip() + render_mode = str(visual.get('render_mode') or '').strip() + if visual.get('status') == 'confirmed' and ( + confirmed_on == 'xfa_dataset_preview' or render_mode == 'xfa_dataset_preview' + ): + next_visual = dict(visual) + next_visual['status'] = 'suggested' + next_visual.pop('preview_render_checksum', None) + next_visual.pop('confirmed_on', None) + next_visual.pop('renderer_version', None) + next_visual['render_mode'] = NATIVE_PDF_CONFIRM_MODE + next_raw = dict(raw) + next_raw['visual_binding'] = next_visual + next_bindings.append(next_raw) + changed = True + else: + next_bindings.append(raw) + if changed: + definition['bindings'] = next_bindings + return definition + + def confirm_xfa_visual_binding( profile_id: int, binding_id: str, @@ -174,10 +227,15 @@ def confirm_xfa_visual_binding( lease_token: str | None, operation_id: str | None = None, request_id: str | None = None, + preview_render_checksum: str | None = None, + render_mode: str | None = None, ) -> dict[str, Any]: """ 管理员确认视觉绑定;写 definition 与 before/after 审计。 + 核心逻辑:在原生 PDF 画布上确认——须有 page_no 与 normalized_bbox; + confirmed_on/render_mode 写为 native_pdf。不再要求合成预览 checksum。 + Args: profile_id: 模板 ID。 binding_id: 目标 binding_id。 @@ -188,10 +246,18 @@ def confirm_xfa_visual_binding( lease_token: 编辑租约令牌。 operation_id: 幂等操作 ID。 request_id: HTTP request_id。 + preview_render_checksum: 兼容旧客户端;忽略。 + render_mode: 兼容旧客户端;写入时强制 native_pdf。 Returns: 更新后的 binding 摘要。 + + Raises: + ValidationError: 缺少页码或 bbox。 + ConflictError: 缺少编辑租约。 + NotFoundError: Profile / binding 不存在。 """ + del preview_render_checksum, render_mode # 兼容入参;确认证据改绑原生 PDF if actor_id is None: raise ConflictError('Edit lease is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED') profile = _profile(profile_id) @@ -202,13 +268,37 @@ def confirm_xfa_visual_binding( lease_token=lease_token, ) definition = _require_xfa_draft(profile) + demote_legacy_synthetic_visual_bindings(definition) + + # [STEP 1] 原生 PDF 确认门禁:页码与 bbox 必填 + next_visual = dict(visual_binding or {}) + page_no = next_visual.get('page_no') + bbox = next_visual.get('normalized_bbox') + if not page_no or not isinstance(bbox, dict): + raise ValidationError( + 'Visual binding confirm requires page_no and normalized_bbox on native PDF canvas', + code=_CONFIRM_REQUIRES_PAGE, + details={ + 'page_no_present': bool(page_no), + 'normalized_bbox_present': isinstance(bbox, dict), + 'expected_confirmed_on': NATIVE_PDF_CONFIRM_MODE, + }, + ) + index, binding = _find_binding(definition, binding_id) before = visual_binding_audit_snapshot(binding) - next_visual = dict(visual_binding or {}) + # [STEP 2] 写入确认状态与原生 PDF 证据(保留 region_kind) next_visual['status'] = 'confirmed' next_visual.setdefault('source', 'manual_draw') next_visual.setdefault('confidence', 1.0) + existing_visual = binding.get('visual_binding') if isinstance(binding.get('visual_binding'), dict) else {} + if not next_visual.get('region_kind'): + next_visual['region_kind'] = existing_visual.get('region_kind') or 'field' + next_visual.pop('preview_render_checksum', None) + next_visual.pop('renderer_version', None) + next_visual['render_mode'] = NATIVE_PDF_CONFIRM_MODE + next_visual['confirmed_on'] = NATIVE_PDF_CONFIRM_MODE updated = deepcopy(binding) updated['visual_binding'] = next_visual @@ -220,8 +310,10 @@ def confirm_xfa_visual_binding( code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', ) value = updated.get('value_binding') if isinstance(updated.get('value_binding'), dict) else {} - value.update({'type': 'xfa_dataset', 'path_id': str(path_id), 'data_path': data_path}) - updated['value_binding'] = value + # 仅在调用方提供 path 时更新 datasets 绑定;不强制覆盖已选的坐标/OCR 类型。 + if str(value.get('type') or 'xfa_dataset') == 'xfa_dataset': + value.update({'type': 'xfa_dataset', 'path_id': str(path_id), 'data_path': data_path}) + updated['value_binding'] = value bindings = list(definition.get('bindings') or []) bindings[index] = updated @@ -240,7 +332,12 @@ def confirm_xfa_visual_binding( operation_id=operation_id, before=before, after=after, - detail={'binding_id': binding_id, 'action': 'confirm'}, + detail={ + 'binding_id': binding_id, + 'action': 'confirm', + 'render_mode': NATIVE_PDF_CONFIRM_MODE, + 'confirmed_on': NATIVE_PDF_CONFIRM_MODE, + }, raw_binding_before=binding, raw_binding_after=updated, profile_context=build_profile_audit_context(profile), diff --git a/backend/app/services/shipping_notice/order_document_profile_xfa_automark_service.py b/backend/app/services/shipping_notice/order_document_profile_xfa_automark_service.py new file mode 100644 index 00000000..9fd5b1f4 --- /dev/null +++ b/backend/app/services/shipping_notice/order_document_profile_xfa_automark_service.py @@ -0,0 +1,1143 @@ +""" +services/shipping_notice/order_document_profile_xfa_automark_service.py + +用途:XFA OCR 自动标记入队、Job 执行、建议查询与 accept/reject 编排。 +依赖:jobs.queue、xfa_ocr_adapter、xfa_visual_binding_service、native_pdf(PDFium 页图)、 + visual_binding_service(确认)、lease_service、audit helpers、Job 模型。 +逻辑:Admin API 调用 enqueue/get/accept/reject;Worker Handler 调用 + execute_xfa_ocr_automark_job。编辑图源为原生 PDF 页,不再依赖 /xfa/preview。 + high 且无 mismatch 才可接受为 confirmed;medium/low 仅写 suggested; + mismatch 硬阻断。永不自动 confirmed。空白壳 OCR 无内容 → 空建议成功。 +""" + +from __future__ import annotations + +import hashlib +import io +import secrets +from copy import deepcopy +from typing import Any + +from app.core.errors import ConflictError, NotFoundError, ServiceUnavailableError, ValidationError +from app.extensions import db +from app.jobs.queue import enqueue +from app.jobs.types import JobType +from app.models import Job, ShippingOrderDocument, ShippingOrderDocumentProfile +from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN +from app.services.shipping_notice.xfa_ocr_adapter import OCR_UNAVAILABLE_CODE, recognize_preview_page +from app.services.shipping_notice.xfa_visual_binding_service import merge_visual_binding_suggestions + +AUTOMARK_OCR_UNAVAILABLE = OCR_UNAVAILABLE_CODE +AUTOMARK_MISMATCH_BLOCKED = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_MISMATCH_BLOCKED' +AUTOMARK_SUGGESTION_NOT_FOUND = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_SUGGESTION_NOT_FOUND' +# 兼容旧客户端错误码名;原生确认路径已不再要求 synthetic checksum。 +AUTOMARK_PREVIEW_REQUIRED = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_CONFIRM_REQUIRES_SYNTHETIC_PREVIEW' + +NATIVE_PDF_RENDER_MODE = 'native_pdf' +NATIVE_PDF_RENDERER_VERSION = 'hxops.native_pdf.v1' + + +class XfaOcrAutomarkError(Exception): + """ + Job 执行期受控失败(映射为 fail_job result.error_code)。 + + Attributes: + error_code: 业务错误码。 + message: 人类可读摘要。 + details: 脱敏细节。 + retryable: 是否允许 Job 重试。 + """ + + def __init__( + self, + message: str, + *, + error_code: str, + details: dict[str, Any] | None = None, + retryable: bool = False, + ) -> None: + super().__init__(message) + self.message = message + self.error_code = str(error_code or 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_AUTOMARK_FAILED') + self.details = dict(details or {}) + self.retryable = bool(retryable) + + +def _profile(profile_id: int) -> ShippingOrderDocumentProfile: + """读取 Profile;缺失时 NotFound。""" + row = db.session.get(ShippingOrderDocumentProfile, int(profile_id)) + if row is None: + raise NotFoundError( + 'Order document profile not found', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND', + ) + return row + + +def _require_xfa_draft(profile: ShippingOrderDocumentProfile) -> dict[str, Any]: + """校验 XFA 草稿并返回 definition 副本。""" + if str(profile.status or '') != 'draft': + raise ConflictError( + 'Only draft profiles support XFA OCR automark', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_IMMUTABLE', + ) + mode = str(profile.template_mode or (profile.definition_json or {}).get('template_mode') or '') + if mode != 'xfa_dataset': + raise ValidationError( + 'XFA OCR automark is only available for xfa_dataset profiles', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', + ) + return dict(profile.definition_json or {}) + + +def _suggestion_id(*, page_no: int, field_key: str, bbox: dict[str, Any]) -> str: + """ + 生成稳定 suggestion_id(同页同字段同框可幂等)。 + + Args: + page_no: 页码。 + field_key: path_id / field_key。 + bbox: 归一化框。 + + Returns: + sugg- 前缀十六进制 ID。 + """ + raw = ( + f'{int(page_no)}|{field_key}|' + f'{float(bbox.get("x0") or 0):.4f},{float(bbox.get("y0") or 0):.4f},' + f'{float(bbox.get("x1") or 0):.4f},{float(bbox.get("y1") or 0):.4f}' + ) + return 'sugg-' + hashlib.sha256(raw.encode('utf-8')).hexdigest()[:20] + + +def _audit_automark( + *, + profile_id: int, + document_id: int | None, + event_type: str, + actor_id: int | None, + detail: dict[str, Any] | None = None, + result: str = 'success', + error_code: str | None = None, +) -> None: + """写入 OCR 自动标记审计;失败吞掉以免阻断主流程。""" + try: + from app.services.shipping_notice.audit_service import append_shipping_audit_event + + append_shipping_audit_event( + event_type=event_type, + aggregate_type='order_document_profile', + aggregate_id=str(profile_id), + actor_type='admin' if actor_id is not None else 'system', + actor_id=actor_id, + document_id=document_id, + result=result, + error_code=error_code, + source='shipping_xfa_ocr_automark', + metadata=dict(detail or {}), + ) + except Exception: + pass + + +def _load_native_pdf_pages_for_ocr( + document_id: int, + *, + page_filter: set[int] | None = None, +) -> dict[str, Any]: + """ + 加载原生 PDF/PDFium 页图供 OCR(编辑画布同源)。 + + 核心逻辑:读样本 FileAsset → extract_native_pdf_pages → PNG; + 无页或无可渲染图时返回空 pages(由执行体记为空建议成功,不报 PREVIEW_UNAVAILABLE)。 + + Args: + document_id: 样本文档 ID。 + page_filter: 可选页码子集。 + + Returns: + {pages, page_count, preview_render_checksum, renderer_version, render_mode}。 + + Raises: + XfaOcrAutomarkError: 样本/资产缺失(不可重试)。 + """ + from PIL import Image + + from app.models import FileAsset + from app.services.file_assets.service import read_asset_bytes + from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages + + document = db.session.get(ShippingOrderDocument, int(document_id)) + if document is None or not document.asset_id: + raise XfaOcrAutomarkError( + 'Sample document not found', + error_code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND', + retryable=False, + ) + asset = db.session.get(FileAsset, int(document.asset_id)) + if asset is None: + raise XfaOcrAutomarkError( + 'Sample document asset not found', + error_code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND', + retryable=False, + ) + + try: + pdf_bytes = read_asset_bytes(asset) + except Exception as exc: # noqa: BLE001 + # 读盘失败与「空白壳无可渲染页」区分:后者走空 pages 成功路径。 + raise XfaOcrAutomarkError( + 'Failed to read sample PDF bytes', + error_code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_READ_FAILED', + details={'document_id': int(document_id)}, + retryable=False, + ) from exc + + asset_digest = hashlib.sha256(pdf_bytes or b'').hexdigest() + pages_out: list[dict[str, Any]] = [] + page_digests: list[str] = [] + try: + native_pages = extract_native_pdf_pages(pdf_bytes, render_scale=2.0, render_images=True) + except Exception: + # 空白壳 / 无法渲染:按空页成功路径处理 + return { + 'pages': [], + 'page_count': 0, + 'preview_render_checksum': f'sha256:{asset_digest}', + 'renderer_version': NATIVE_PDF_RENDERER_VERSION, + 'render_mode': NATIVE_PDF_RENDER_MODE, + } + + for page in native_pages: + page_no = int(getattr(page, 'page_no', 0) or 0) + if page_no <= 0: + continue + if page_filter and page_no not in page_filter: + continue + image = getattr(page, 'image', None) + if image is None: + continue + stream = io.BytesIO() + Image.fromarray(image).save(stream, format='PNG', optimize=True) + png = stream.getvalue() + if not png: + continue + page_digests.append(hashlib.sha256(png).hexdigest()) + pages_out.append({ + 'page_no': page_no, + 'png_bytes': png, + 'width': float(getattr(page, 'width', 0) or 0), + 'height': float(getattr(page, 'height', 0) or 0), + }) + + checksum = ( + 'sha256:' + hashlib.sha256('|'.join(page_digests).encode('utf-8')).hexdigest() + if page_digests + else f'sha256:{asset_digest}' + ) + return { + 'pages': pages_out, + 'page_count': len(pages_out), + 'preview_render_checksum': checksum, + 'renderer_version': NATIVE_PDF_RENDERER_VERSION, + 'render_mode': NATIVE_PDF_RENDER_MODE, + } + + +def _dataset_targets_flat(document_id: int) -> list[dict[str, Any]]: + """ + 从 XFA datasets 叶子构建 OCR 匹配目标(不依赖 synthetic drawn_field_echoes)。 + + Args: + document_id: 样本文档 ID。 + + Returns: + [{field_key, value}];分析失败返回空列表。 + """ + try: + from app.models import FileAsset + from app.services.file_assets.service import read_asset_bytes + from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf + from app.services.shipping_notice.document_layout.xfa_dataset import _path_id_for + + document = db.session.get(ShippingOrderDocument, int(document_id)) + if document is None or not document.asset_id: + return [] + asset = db.session.get(FileAsset, int(document.asset_id)) + if asset is None: + return [] + outcome = analyze_xfa_pdf(read_asset_bytes(asset)) + analysis = outcome.dataset_analysis + if analysis is None: + return [] + targets: list[dict[str, Any]] = [] + for data_path, raw in (analysis.leaf_values_by_path or {}).items(): + path_id = str(_path_id_for(str(data_path)) or '').strip() + if not path_id: + continue + targets.append({ + 'field_key': path_id, + 'value': str(raw or ''), + 'data_path': str(data_path), + }) + return targets + except Exception: + return [] + + +def _dataset_targets_from_preview_pages(pages: list[dict[str, Any]]) -> dict[int, list[dict[str, Any]]]: + """ + 兼容旧 synthetic pages 的按页 targets 投影(仅测试/回退;正式路径用 _dataset_targets_flat)。 + + Args: + pages: 含 drawn_field_echoes 的页列表。 + + Returns: + page_no → [{field_key, value, normalized_bbox}] + """ + by_page: dict[int, list[dict[str, Any]]] = {} + for page in pages: + if not isinstance(page, dict): + continue + page_no = int(page.get('page_no') or 0) + if page_no <= 0: + continue + targets: list[dict[str, Any]] = [] + for echo in page.get('drawn_field_echoes') or []: + if not isinstance(echo, dict): + continue + field_key = str(echo.get('path_id') or echo.get('field_key') or '').strip() + if not field_key: + continue + bbox = echo.get('normalized_bbox') if isinstance(echo.get('normalized_bbox'), dict) else {} + targets.append({ + 'field_key': field_key, + 'value': str(echo.get('value') or ''), + 'normalized_bbox': dict(bbox), + }) + by_page[page_no] = targets + return by_page + + +def _widget_candidates_for_page( + *, + document_id: int, + page_no: int, + targets: list[dict[str, Any]], +) -> list[dict[str, Any]]: + """ + 尽力生成 Widget 候选;失败时返回空列表(OCR 仍可补框)。 + + 核心逻辑:读 PDF AcroForm → 对目标框调用 suggest_visual_binding_candidates。 + """ + if not targets: + return [] + try: + from app.models import FileAsset + from app.services.file_assets.service import read_asset_bytes + from app.services.shipping_notice.document_layout.xfa_acroform import read_acroform_widgets + from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf + from app.services.shipping_notice.document_layout.xfa_visual_binding import ( + suggest_visual_binding_candidates, + ) + + document = db.session.get(ShippingOrderDocument, int(document_id)) + if document is None or not document.asset_id: + return [] + asset = db.session.get(FileAsset, int(document.asset_id)) + if asset is None: + return [] + pdf_bytes = read_asset_bytes(asset) + widgets = read_acroform_widgets(pdf_bytes) + outcome = analyze_xfa_pdf(pdf_bytes) + if outcome.dataset_analysis is None: + return [] + # 用整页框作为查询区域以收集该页 Widget 候选 + result = suggest_visual_binding_candidates( + page_no=int(page_no), + normalized_bbox={'x0': 0.0, 'y0': 0.0, 'x1': 1.0, 'y1': 1.0}, + dataset_analysis=outcome.dataset_analysis, + widgets=[w for w in widgets if int(getattr(w, 'page_no', 0) or 0) == int(page_no)], + ) + return list(result.get('candidates') or []) + except Exception: + return [] + + +def _normalize_suggestion(item: dict[str, Any], *, page_no: int) -> dict[str, Any]: + """为合并结果补 suggestion_id / region_kind / match 字段。""" + bbox = item.get('normalized_bbox') if isinstance(item.get('normalized_bbox'), dict) else {} + field_key = str(item.get('field_key') or '') + match_class = str(item.get('match_class') or 'needs_review') + needs_review = bool( + item.get('needs_review') + or match_class == 'needs_review' + or str(item.get('suggestion_status') or '') == 'needs_review' + ) + suggestion_id = _suggestion_id(page_no=page_no, field_key=field_key, bbox=bbox) + return { + 'suggestion_id': suggestion_id, + 'field_key': field_key or None, + 'page_no': int(page_no), + 'normalized_bbox': dict(bbox), + 'source': item.get('source') or 'suggested', + 'status': 'suggested', + 'confidence': float(item.get('confidence') or 0.0), + 'match_class': match_class, + 'suggestion_origin': item.get('suggestion_origin') or 'ocr', + 'ocr_text': item.get('ocr_text'), + 'dataset_value': item.get('dataset_value'), + 'iou': item.get('iou'), + 'auto_confirm_blocked': True, + 'needs_review': needs_review, + 'region_kind': item.get('region_kind') or 'field', + 'preview_render_checksum': item.get('preview_render_checksum'), + 'renderer_version': item.get('renderer_version') or NATIVE_PDF_RENDERER_VERSION, + } + + +def execute_xfa_ocr_automark_job(payload: dict[str, Any]) -> dict[str, Any]: + """ + Worker 执行体:OCR 原生 PDF 页并合并 Widget/OCR 建议。 + + 核心逻辑: + 1. 加载 PDFium 原生页 PNG(与编辑画布同源); + 2. 无页/空白壳 → 空建议成功(不报 XFA_PREVIEW_UNAVAILABLE); + 3. 逐页 recognize_preview_page;无 OCR 行时不生成 datasets stub 建议; + 4. merge_visual_binding_suggestions(按 field_key 跨页去重); + 5. 回写 Profile.definition.xfa_ocr_automark。 + + Args: + payload: Job.payload_json(含 profile_id/document_id/preview_render_checksum)。 + + Returns: + 写入 Job.result_json 的字典。 + + Raises: + XfaOcrAutomarkError: 受控失败(样本缺失 / OCR 引擎不可用等)。 + """ + profile_id = int(payload.get('profile_id') or 0) + document_id = int(payload.get('document_id') or 0) + expected_checksum = str(payload.get('preview_render_checksum') or '').strip() or None + actor_id = payload.get('actor_id') + page_nos_raw = payload.get('page_nos') + page_filter = None + if isinstance(page_nos_raw, list) and page_nos_raw: + page_filter = {int(item) for item in page_nos_raw if str(item).isdigit() or isinstance(item, int)} + + if profile_id <= 0 or document_id <= 0: + raise XfaOcrAutomarkError( + 'profile_id and document_id are required', + error_code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', + retryable=False, + ) + + _audit_automark( + profile_id=profile_id, + document_id=document_id, + event_type='xfa_ocr_started', + actor_id=int(actor_id) if actor_id is not None else None, + detail={ + 'job_id': payload.get('job_id'), + 'preview_render_checksum': expected_checksum, + 'page_nos': sorted(page_filter) if page_filter else None, + 'render_mode': NATIVE_PDF_RENDER_MODE, + }, + ) + + cached = _load_native_pdf_pages_for_ocr(document_id, page_filter=page_filter) + pages = [item for item in (cached.get('pages') or []) if isinstance(item, dict)] + checksum = str(cached.get('preview_render_checksum') or expected_checksum or '') + renderer_version = str(cached.get('renderer_version') or NATIVE_PDF_RENDERER_VERSION) + + # 空白壳 / 无可渲染页:成功返回空建议,datasets 仍可在属性区绑定。 + if not pages: + profile = _profile(profile_id) + definition = dict(profile.definition_json or {}) + definition['xfa_ocr_automark'] = { + 'job_id': payload.get('job_id'), + 'document_id': document_id, + 'preview_render_checksum': checksum, + 'renderer_version': renderer_version, + 'render_mode': NATIVE_PDF_RENDER_MODE, + 'suggestion_count': 0, + 'unresolved_ocr_mismatch_count': 0, + 'suggestions': [], + 'status': 'completed', + 'empty_reason': 'native_pdf_blank_or_unrendered', + } + profile.definition_json = definition + db.session.flush() + result = { + 'status': 'success', + 'profile_id': profile_id, + 'document_id': document_id, + 'preview_render_checksum': checksum, + 'renderer_version': renderer_version, + 'render_mode': NATIVE_PDF_RENDER_MODE, + 'page_count': 0, + 'suggestions': [], + 'unresolved_ocr_mismatch_count': 0, + 'error_code': None, + } + _audit_automark( + profile_id=profile_id, + document_id=document_id, + event_type='xfa_ocr_completed', + actor_id=int(actor_id) if actor_id is not None else None, + detail={ + 'job_id': payload.get('job_id'), + 'suggestion_count': 0, + 'empty_reason': 'native_pdf_blank_or_unrendered', + }, + ) + db.session.commit() + return result + + flat_targets = _dataset_targets_flat(document_id) + suggestions_by_key: dict[str, dict[str, Any]] = {} + needs_review_count = 0 + + for page in pages: + page_no = int(page.get('page_no') or 0) + png = page.get('png_bytes') + if not isinstance(png, (bytes, bytearray)) or not png: + continue + try: + ocr_lines = recognize_preview_page(bytes(png)) + except ServiceUnavailableError as exc: + _audit_automark( + profile_id=profile_id, + document_id=document_id, + event_type='xfa_ocr_failed', + actor_id=int(actor_id) if actor_id is not None else None, + result='failure', + error_code=str(getattr(exc, 'code', None) or AUTOMARK_OCR_UNAVAILABLE), + detail={'page_no': page_no, 'job_id': payload.get('job_id')}, + ) + raise XfaOcrAutomarkError( + 'XFA native PDF OCR is unavailable', + error_code=str(getattr(exc, 'code', None) or AUTOMARK_OCR_UNAVAILABLE), + details=dict(getattr(exc, 'details', None) or {'page_no': page_no}), + retryable=False, + ) from exc + + pending_targets = [ + item for item in flat_targets + if str(item.get('field_key') or '') not in suggestions_by_key + ] + # 无 OCR 行时不向 matcher 传 datasets 目标,避免空白壳刷出 needs_review stub。 + ocr_targets = pending_targets if ocr_lines else [] + widgets = _widget_candidates_for_page( + document_id=document_id, + page_no=page_no, + targets=pending_targets, + ) + if not ocr_lines and not widgets: + continue + + merged = merge_visual_binding_suggestions( + page_no=page_no, + widget_candidates=widgets, + ocr_lines=ocr_lines, + dataset_targets=ocr_targets, + ) + for raw in merged.get('suggested_visual_bindings') or []: + if not isinstance(raw, dict): + continue + suggestion = _normalize_suggestion(raw, page_no=page_no) + suggestion['preview_render_checksum'] = checksum + suggestion['renderer_version'] = renderer_version + key = str(suggestion.get('field_key') or suggestion.get('suggestion_id') or '') + if not key: + continue + previous = suggestions_by_key.get(key) + if previous is None or float(suggestion.get('confidence') or 0) >= float(previous.get('confidence') or 0): + suggestions_by_key[key] = suggestion + + all_suggestions = list(suggestions_by_key.values()) + needs_review_count = sum(1 for item in all_suggestions if item.get('needs_review')) + + profile = _profile(profile_id) + definition = dict(profile.definition_json or {}) + definition['xfa_ocr_automark'] = { + 'job_id': payload.get('job_id'), + 'document_id': document_id, + 'preview_render_checksum': checksum, + 'renderer_version': renderer_version, + 'render_mode': NATIVE_PDF_RENDER_MODE, + 'suggestion_count': len(all_suggestions), + 'unresolved_ocr_mismatch_count': int(needs_review_count), + 'suggestions': all_suggestions, + 'status': 'completed', + } + profile.definition_json = definition + db.session.flush() + + result = { + 'status': 'success', + 'profile_id': profile_id, + 'document_id': document_id, + 'preview_render_checksum': checksum, + 'renderer_version': renderer_version, + 'render_mode': NATIVE_PDF_RENDER_MODE, + 'page_count': int(cached.get('page_count') or len(pages)), + 'suggestions': all_suggestions, + 'unresolved_ocr_mismatch_count': int(needs_review_count), + 'error_code': None, + } + _audit_automark( + profile_id=profile_id, + document_id=document_id, + event_type='xfa_ocr_completed', + actor_id=int(actor_id) if actor_id is not None else None, + detail={ + 'job_id': payload.get('job_id'), + 'suggestion_count': len(all_suggestions), + 'unresolved_ocr_mismatch_count': needs_review_count, + 'preview_render_checksum': checksum, + 'render_mode': NATIVE_PDF_RENDER_MODE, + }, + ) + db.session.commit() + return result + + +def enqueue_xfa_ocr_automark( + profile_id: int, + *, + document_id: int, + actor_id: int | None, + force: bool = False, + page_nos: list[int] | None = None, +) -> dict[str, Any]: + """ + 入队 XFA OCR 自动标记 Job。 + + 核心逻辑:校验 XFA 草稿 → 以原生 PDF 页指纹入队(不调用 /xfa/preview)→ + enqueue shipping_xfa_ocr_automark;同 profile+document+checksum 去重。 + + Args: + profile_id: 草稿 Profile ID。 + document_id: 样本文档 ID。 + actor_id: 管理员 ID。 + force: True 时跳过去重强制新 Job。 + page_nos: 可选页码子集。 + + Returns: + {job_id, status, preview_render_checksum, document_id}。 + """ + profile = _profile(profile_id) + _require_xfa_draft(profile) + if actor_id is None: + raise ConflictError( + 'Actor is required to enqueue XFA OCR automark', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED', + ) + + page_filter = None + if page_nos: + page_filter = {int(item) for item in page_nos if str(item).isdigit() or isinstance(item, int)} + # 入队前算原生页指纹;空白壳也允许入队,Job 将返回空建议。 + native = _load_native_pdf_pages_for_ocr(int(document_id), page_filter=page_filter) + checksum = str(native.get('preview_render_checksum') or '').strip() + if not checksum: + checksum = 'sha256:' + hashlib.sha256(f'native:{document_id}'.encode('utf-8')).hexdigest() + + payload = { + 'profile_id': int(profile_id), + 'document_id': int(document_id), + 'layout_version_id': None, + 'preview_render_checksum': checksum, + 'renderer_version': str(native.get('renderer_version') or NATIVE_PDF_RENDERER_VERSION), + 'render_mode': NATIVE_PDF_RENDER_MODE, + 'page_nos': [int(item) for item in (page_nos or [])], + 'actor_id': int(actor_id), + } + business_ref = f'xfa-ocr-automark:{int(profile_id)}:{int(document_id)}:{checksum}' + job_id = enqueue( + JobType.SHIPPING_XFA_OCR_AUTOMARK, + payload, + domain=SHIPPING_NOTICE_JOB_DOMAIN, + business_ref=business_ref, + created_by_id=int(actor_id), + message='等待 XFA OCR 自动标记', + max_attempts=2, + dedupe_active=not bool(force), + commit=True, + ) + job = db.session.get(Job, int(job_id)) + status = str(job.status if job is not None else 'queued') + return { + 'job_id': int(job_id), + 'status': status, + 'preview_render_checksum': checksum, + 'document_id': int(document_id), + 'profile_id': int(profile_id), + 'render_mode': NATIVE_PDF_RENDER_MODE, + } + + +def get_xfa_ocr_automark_job(job_id: int, *, profile_id: int | None = None) -> dict[str, Any]: + """ + 查询 OCR 自动标记 Job 状态与建议列表。 + + Args: + job_id: Job 主键。 + profile_id: 可选;传入时校验载荷归属。 + + Returns: + {job_id, status, suggestions, error_code, preview_render_checksum, ...}。 + """ + job = db.session.get(Job, int(job_id)) + if job is None or str(job.job_type or '') != JobType.SHIPPING_XFA_OCR_AUTOMARK.value: + raise NotFoundError( + 'XFA OCR automark job not found', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_JOB_NOT_FOUND', + ) + payload = dict(job.payload_json or {}) + if profile_id is not None and int(payload.get('profile_id') or 0) != int(profile_id): + raise NotFoundError( + 'XFA OCR automark job not found for profile', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_JOB_NOT_FOUND', + ) + result = dict(job.result_json or {}) if isinstance(job.result_json, dict) else {} + suggestions = result.get('suggestions') + if not isinstance(suggestions, list): + # Job 仍在跑时,尝试从 definition 读取最近一次结果 + suggestions = [] + if profile_id is not None: + profile = _profile(profile_id) + automark = (profile.definition_json or {}).get('xfa_ocr_automark') + if isinstance(automark, dict) and int(automark.get('job_id') or 0) == int(job_id): + suggestions = list(automark.get('suggestions') or []) + result = {**result, **{k: automark.get(k) for k in ( + 'preview_render_checksum', 'unresolved_ocr_mismatch_count', 'renderer_version', + ) if k in automark}} + return { + 'job_id': int(job.id), + 'status': str(job.status or ''), + 'suggestions': suggestions, + 'error_code': result.get('error_code') or ( + None if str(job.status or '') != 'failed' else 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_AUTOMARK_FAILED' + ), + 'preview_render_checksum': ( + result.get('preview_render_checksum') + or payload.get('preview_render_checksum') + ), + 'renderer_version': result.get('renderer_version') or payload.get('renderer_version'), + 'unresolved_ocr_mismatch_count': result.get('unresolved_ocr_mismatch_count'), + 'document_id': payload.get('document_id'), + 'profile_id': payload.get('profile_id'), + 'message': job.message, + } + + +def _find_suggestion( + profile: ShippingOrderDocumentProfile, + suggestion_id: str, + *, + job_id: int | None = None, +) -> dict[str, Any]: + """从 definition.xfa_ocr_automark 或指定 Job.result 定位建议。""" + definition = dict(profile.definition_json or {}) + automark = definition.get('xfa_ocr_automark') if isinstance(definition.get('xfa_ocr_automark'), dict) else {} + for item in automark.get('suggestions') or []: + if isinstance(item, dict) and str(item.get('suggestion_id') or '') == str(suggestion_id): + return dict(item) + if job_id is not None: + job = db.session.get(Job, int(job_id)) + if job is not None and isinstance(job.result_json, dict): + for item in job.result_json.get('suggestions') or []: + if isinstance(item, dict) and str(item.get('suggestion_id') or '') == str(suggestion_id): + return dict(item) + raise NotFoundError( + 'XFA OCR automark suggestion not found', + code=AUTOMARK_SUGGESTION_NOT_FOUND, + ) + + +def _find_or_create_binding_for_suggestion( + definition: dict[str, Any], + suggestion: dict[str, Any], +) -> tuple[str, dict[str, Any], bool]: + """ + 按 field_key(path_id) 定位 binding;不存在时创建 suggested stub。 + + Returns: + (binding_id, binding, created)。 + """ + field_key = str(suggestion.get('field_key') or '').strip() + bindings = list(definition.get('bindings') or []) + for item in bindings: + if not isinstance(item, dict): + continue + value = item.get('value_binding') if isinstance(item.get('value_binding'), dict) else {} + if field_key and str(value.get('path_id') or '') == field_key: + return str(item.get('binding_id') or ''), item, False + if field_key and str(item.get('field_id') or '') == field_key: + return str(item.get('binding_id') or ''), item, False + + if not field_key: + raise ValidationError( + 'Automark suggestion is missing field_key', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID', + ) + binding_id = f'bind-{secrets.token_hex(8)}' + binding = { + 'binding_id': binding_id, + 'field_id': field_key if field_key.startswith('f-') else f'f-auto-{field_key[-12:]}', + 'field_code': field_key, + 'scope': 'header', + 'value_binding': { + 'type': 'xfa_dataset', + 'path_id': field_key, + 'data_path': f'/data/AUTO/{field_key}', + }, + 'visual_binding': { + 'page_no': int(suggestion.get('page_no') or 1), + 'normalized_bbox': dict(suggestion.get('normalized_bbox') or { + 'x0': 0.0, 'y0': 0.0, 'x1': 0.01, 'y1': 0.01, + }), + 'source': 'suggested', + 'status': 'suggested', + 'confidence': float(suggestion.get('confidence') or 0.0), + 'region_kind': suggestion.get('region_kind') or 'field', + }, + } + # 若已有 header_mappings 同 path_id,复用 field_id/data_path + for mapping in definition.get('header_mappings') or []: + if isinstance(mapping, dict) and str(mapping.get('path_id') or '') == field_key: + binding['field_id'] = str(mapping.get('field_id') or binding['field_id']) + binding['field_code'] = str(mapping.get('field_code') or binding['field_code']) + binding['value_binding']['data_path'] = str(mapping.get('data_path') or binding['value_binding']['data_path']) + break + bindings.append(binding) + definition['bindings'] = bindings + return binding_id, binding, True + + +def accept_xfa_automark_suggestion( + profile_id: int, + suggestion_id: str, + *, + actor_id: int | None, + browser_session_id: str | None, + lease_token: str | None, + operation_id: str | None = None, + request_id: str | None = None, + job_id: int | None = None, + preview_render_checksum: str | None = None, +) -> dict[str, Any]: + """ + 接受 OCR 自动标记建议。 + + 核心逻辑: + - mismatch / needs_review → ValidationError(禁确认); + - high → confirm visual_binding(须 checksum); + - medium/low → 仅写入 suggested 状态与框。 + + Args: + profile_id / suggestion_id: 定位建议。 + actor_id / browser_session_id / lease_token: 编辑租约。 + job_id: 可选,辅助从 Job.result 回读建议。 + preview_render_checksum: 可选覆盖;默认用建议/预览摘要。 + + Returns: + {suggestion_id, action, binding_id, visual_binding, match_class}。 + """ + from app.services.shipping_notice import order_document_profile_lease_service as lease_service + from app.services.shipping_notice import order_document_profile_visual_binding_service as visual_svc + from app.services.shipping_notice.document_layout.xfa_contract import OrderXfaDatasetProfile + from app.services.shipping_notice.order_document_profile_audit_service import ( + build_profile_audit_context, + record_visual_binding_audit, + ) + from app.services.shipping_notice.document_layout.xfa_visual_binding import ( + visual_binding_audit_snapshot, + ) + + if actor_id is None: + raise ConflictError('Edit lease is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED') + profile = _profile(profile_id) + lease_service.require_active_lease( + profile.id, + actor_id=actor_id, + browser_session_id=browser_session_id, + lease_token=lease_token, + ) + definition = _require_xfa_draft(profile) + suggestion = _find_suggestion(profile, suggestion_id, job_id=job_id) + + if suggestion.get('needs_review') or str(suggestion.get('match_class') or '') == 'needs_review': + raise ValidationError( + 'OCR mismatch suggestions cannot be accepted', + code=AUTOMARK_MISMATCH_BLOCKED, + details={'suggestion_id': suggestion_id, 'match_class': suggestion.get('match_class')}, + ) + + match_class = str(suggestion.get('match_class') or 'low') + checksum = str( + preview_render_checksum + or suggestion.get('preview_render_checksum') + or ((definition.get('xfa_ocr_automark') or {}).get('preview_render_checksum') if isinstance(definition.get('xfa_ocr_automark'), dict) else '') + or '' + ).strip() + + binding_id, binding, created = _find_or_create_binding_for_suggestion(definition, suggestion) + before = visual_binding_audit_snapshot(binding) + + visual = { + 'page_no': int(suggestion.get('page_no') or 1), + 'normalized_bbox': dict(suggestion.get('normalized_bbox') or {}), + 'source': 'suggested' if suggestion.get('suggestion_origin') == 'ocr' else ( + suggestion.get('source') or 'suggested' + ), + 'confidence': float(suggestion.get('confidence') or 0.0), + 'region_kind': suggestion.get('region_kind') or 'field', + } + + if match_class == 'high': + # 若新建 stub,先落库 definition 以便 confirm 路径能找到 binding + if created: + OrderXfaDatasetProfile.model_validate(definition) + profile.definition_json = definition + db.session.flush() + confirmed = visual_svc.confirm_xfa_visual_binding( + profile_id, + binding_id, + visual_binding=visual, + path_id=str(suggestion.get('field_key') or '') or None, + actor_id=actor_id, + browser_session_id=browser_session_id, + lease_token=lease_token, + operation_id=operation_id, + request_id=request_id, + preview_render_checksum=checksum or None, + render_mode=NATIVE_PDF_RENDER_MODE, + ) + _mark_suggestion_resolved(profile_id, suggestion_id, decision='accepted_confirmed') + db.session.commit() + return { + 'suggestion_id': suggestion_id, + 'action': 'confirmed', + 'match_class': match_class, + 'binding_id': binding_id, + 'visual_binding': confirmed.get('visual_binding'), + } + + # medium / low:只写 suggested + updated = deepcopy(binding) + next_visual = dict(updated.get('visual_binding') or {}) + next_visual.update(visual) + next_visual['status'] = 'suggested' + next_visual.pop('preview_render_checksum', None) + next_visual.pop('confirmed_on', None) + updated['visual_binding'] = next_visual + bindings = list(definition.get('bindings') or []) + for index, item in enumerate(bindings): + if isinstance(item, dict) and str(item.get('binding_id') or '') == binding_id: + bindings[index] = updated + break + else: + bindings.append(updated) + definition['bindings'] = bindings + OrderXfaDatasetProfile.model_validate(definition) + profile.definition_json = definition + db.session.flush() + after = visual_binding_audit_snapshot(updated) + record_visual_binding_audit( + profile_id=int(profile.id), + document_id=None, + event_type='xfa_visual_binding_suggested', + actor_id=actor_id, + request_id=request_id, + operation_id=operation_id, + before=before, + after=after, + detail={ + 'binding_id': binding_id, + 'action': 'automark_accept_suggested', + 'suggestion_id': suggestion_id, + 'match_class': match_class, + }, + raw_binding_before=binding, + raw_binding_after=updated, + profile_context=build_profile_audit_context(profile), + ) + _mark_suggestion_resolved(profile_id, suggestion_id, decision='accepted_suggested') + db.session.commit() + return { + 'suggestion_id': suggestion_id, + 'action': 'suggested', + 'match_class': match_class, + 'binding_id': binding_id, + 'visual_binding': next_visual, + } + + +def reject_xfa_automark_suggestion( + profile_id: int, + suggestion_id: str, + *, + actor_id: int | None, + browser_session_id: str | None, + lease_token: str | None, + operation_id: str | None = None, + request_id: str | None = None, + reason_code: str | None = None, + job_id: int | None = None, +) -> dict[str, Any]: + """ + 驳回 OCR 自动标记建议;写审计并减少 unresolved mismatch 计数。 + + Args: + profile_id / suggestion_id: 定位建议。 + actor_id / browser_session_id / lease_token: 编辑租约。 + reason_code: 可选驳回原因。 + job_id: 可选。 + + Returns: + {suggestion_id, action=rejected}。 + """ + from app.services.shipping_notice import order_document_profile_lease_service as lease_service + + if actor_id is None: + raise ConflictError('Edit lease is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED') + profile = _profile(profile_id) + lease_service.require_active_lease( + profile.id, + actor_id=actor_id, + browser_session_id=browser_session_id, + lease_token=lease_token, + ) + _require_xfa_draft(profile) + suggestion = _find_suggestion(profile, suggestion_id, job_id=job_id) + _mark_suggestion_resolved( + profile_id, + suggestion_id, + decision='rejected', + reason_code=reason_code, + ) + _audit_automark( + profile_id=profile_id, + document_id=None, + event_type='xfa_visual_binding_rejected', + actor_id=actor_id, + detail={ + 'suggestion_id': suggestion_id, + 'action': 'automark_reject', + 'reason_code': reason_code, + 'match_class': suggestion.get('match_class'), + 'operation_id': operation_id, + 'request_id': request_id, + }, + ) + db.session.commit() + return { + 'suggestion_id': suggestion_id, + 'action': 'rejected', + 'match_class': suggestion.get('match_class'), + 'reason_code': reason_code, + } + + +def _mark_suggestion_resolved( + profile_id: int, + suggestion_id: str, + *, + decision: str, + reason_code: str | None = None, +) -> None: + """更新 definition.xfa_ocr_automark 中建议决策并重算 unresolved mismatch。""" + profile = _profile(profile_id) + definition = dict(profile.definition_json or {}) + automark = definition.get('xfa_ocr_automark') if isinstance(definition.get('xfa_ocr_automark'), dict) else {} + suggestions = list(automark.get('suggestions') or []) + updated_list: list[dict[str, Any]] = [] + for item in suggestions: + if not isinstance(item, dict): + continue + if str(item.get('suggestion_id') or '') == str(suggestion_id): + next_item = dict(item) + next_item['decision'] = decision + if reason_code: + next_item['reason_code'] = reason_code + updated_list.append(next_item) + else: + updated_list.append(item) + unresolved = sum( + 1 for item in updated_list + if item.get('needs_review') and not item.get('decision') + ) + automark = { + **automark, + 'suggestions': updated_list, + 'unresolved_ocr_mismatch_count': unresolved, + } + definition['xfa_ocr_automark'] = automark + preview_meta = definition.get('xfa_preview') if isinstance(definition.get('xfa_preview'), dict) else {} + definition['xfa_preview'] = { + **preview_meta, + 'unresolved_ocr_mismatch_count': unresolved, + } + profile.definition_json = definition + db.session.flush() + + +def demote_stale_confirmed_visual_bindings_on_renderer_bump( + definition: dict[str, Any], + *, + current_renderer_version: str, + current_preview_render_checksum: str | None = None, +) -> dict[str, Any]: + """ + 合成器版本 bump 时,将缺少当前 checksum/版本证据的 confirmed 视觉绑定降为 suggested。 + + 核心逻辑:遍历 bindings;confirmed 且 + renderer_version≠current 或 checksum 与当前不一致(若提供)→ status=suggested, + 清除确认证据字段。不改 value_binding。 + + Args: + definition: XFA definition(就地修改并返回)。 + current_renderer_version: 当前合成器版本。 + current_preview_render_checksum: 可选当前预览 checksum。 + + Returns: + {demoted_count, demoted_binding_ids, definition}。 + """ + current_version = str(current_renderer_version or '').strip() + current_checksum = str(current_preview_render_checksum or '').strip() or None + bindings = list(definition.get('bindings') or []) + demoted_ids: list[str] = [] + next_bindings: list[Any] = [] + for raw in bindings: + if not isinstance(raw, dict): + next_bindings.append(raw) + continue + visual = raw.get('visual_binding') if isinstance(raw.get('visual_binding'), dict) else {} + if str(visual.get('status') or '') != 'confirmed': + next_bindings.append(raw) + continue + item_version = str(visual.get('renderer_version') or '').strip() + item_checksum = str(visual.get('preview_render_checksum') or '').strip() + stale_version = bool(current_version) and item_version != current_version + stale_checksum = bool(current_checksum) and item_checksum != current_checksum + missing_checksum = not item_checksum + if not (stale_version or stale_checksum or missing_checksum): + next_bindings.append(raw) + continue + updated = deepcopy(raw) + next_visual = dict(updated.get('visual_binding') or {}) + next_visual['status'] = 'suggested' + next_visual.pop('confirmed_on', None) + # 保留旧 checksum 供审计对照,但清除确认标记 + updated['visual_binding'] = next_visual + next_bindings.append(updated) + demoted_ids.append(str(updated.get('binding_id') or '')) + definition['bindings'] = next_bindings + return { + 'demoted_count': len(demoted_ids), + 'demoted_binding_ids': demoted_ids, + 'definition': definition, + } diff --git a/backend/app/services/shipping_notice/order_document_profile_xfa_preview_service.py b/backend/app/services/shipping_notice/order_document_profile_xfa_preview_service.py new file mode 100644 index 00000000..b7ae7a52 --- /dev/null +++ b/backend/app/services/shipping_notice/order_document_profile_xfa_preview_service.py @@ -0,0 +1,902 @@ +""" +services/shipping_notice/order_document_profile_xfa_preview_service.py + +用途:订单文档样本的 XFA 合成预览编排(Phase 1–2)——按冻结 Layout/Analysis 生成、 + 缓存并签发单页 PNG 授权;禁止“按 document 最新 Analysis”回退。 +依赖:resolve_frozen_xfa_structure_analysis、compose_xfa_dataset_preview_pages、 + xfa_preview_cache、xfa_preview_contract、preview_grant_store、FileAsset、ProfileAudit。 +逻辑:Admin API POST/GET xfa/preview* 调用本模块;身份不一致 fail-closed 抛 ValidationError。 +""" + +from __future__ import annotations + +import json +import secrets +from typing import Any + +from app.core.errors import NotFoundError, ValidationError +from app.extensions import db +from app.models import ( + FileAsset, + ShippingOrderDocument, + ShippingOrderDocumentProfileAudit, + ShippingXfaStructureAnalysis, +) +from app.services.shipping_notice.document_layout.xfa_preview_cache import ( + build_preview_cache_key, + get_preview_cache, + set_preview_cache, +) +from app.services.shipping_notice.document_layout.xfa_preview_contract import ( + RENDER_MODE, + XFA_PREVIEW_FAILED, + XFA_PREVIEW_STALE, + XFA_PREVIEW_UNAVAILABLE, + XFA_PREVIEW_VALUE_MISMATCH, + PreviewIdentityContext, + is_preview_identity_stale, + preview_identity_to_dict, + shipping_error_code_for_preview, +) +from app.services.shipping_notice.document_layout.xfa_preview_renderer import ( + RENDERER_VERSION, + compose_xfa_dataset_preview_pages, +) +from app.services.shipping_notice.preview_grant_store import preview_grant_store + +PREVIEW_GRANT_TTL_SECONDS = 120 +PREVIEW_GRANT_KEY_PREFIX = 'shipping:order-profile-xfa-synth-preview:' +_XFA_PREVIEW_KINDS = frozenset({'xfa_hybrid', 'pure_xfa'}) + + +def _raise_preview_error( + short_code: str, + message: str, + *, + details: dict[str, Any] | None = None, +) -> None: + """ + 以预览短码映射 SHIPPING.* 后抛出 ValidationError(fail-closed)。 + + Args: + short_code: xfa_preview_contract 短错误码。 + message: 英文技术消息。 + details: 可选诊断细节(不含 PNG/明文路径原文)。 + + Raises: + ValidationError: 始终抛出。 + """ + raise ValidationError( + message, + code=shipping_error_code_for_preview(short_code) or short_code, + details=dict(details or {}), + ) + + +def _audit( + *, + document_id: int, + event_type: str, + actor_id: int | None, + detail: dict[str, Any] | None = None, + profile_id: int | None = None, +) -> None: + """ + 写入 Profile 审计表(合成预览生命周期事件)。 + + 核心逻辑:复用 ShippingOrderDocumentProfileAudit;detail 仅放身份与状态摘要, + 禁止写入 PNG、token 明文或 datasets 全文。 + """ + db.session.add(ShippingOrderDocumentProfileAudit( + profile_id=profile_id, + document_id=int(document_id), + event_type=str(event_type or '').strip()[:48] or 'xfa_preview_requested', + actor_id=actor_id, + detail_json=dict(detail or {}), + )) + + +def _require_sample_document(document_id: int) -> ShippingOrderDocument: + """按主键加载样本文档;缺失时 NotFoundError。""" + document = db.session.get(ShippingOrderDocument, int(document_id)) + if document is None: + raise NotFoundError( + 'Order profile sample document not found', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND', + ) + return document + + +def _preview_grant_store() -> Any: + """返回合成预览页授权存储(可被测试 monkeypatch)。""" + return preview_grant_store() + + +def _norm(value: Any) -> str: + """规范化校验和/指纹比较用字符串。""" + return str(value or '').strip().lower() + + +def _build_identity_context( + *, + document: ShippingOrderDocument, + layout_version_id: int, + analysis: ShippingXfaStructureAnalysis, + preview_render_checksum: str = '', + page_count: int = 0, +) -> PreviewIdentityContext: + """ + 从冻结 Analysis 构造预览身份上下文。 + + Args: + document: 样本文档。 + layout_version_id: 冻结 LayoutVersion 主键。 + analysis: 冻结 StructureAnalysis。 + preview_render_checksum: 合成后的 render checksum;生成前可为空。 + page_count: 页数。 + + Returns: + PreviewIdentityContext。 + """ + return PreviewIdentityContext( + document_id=int(document.id), + layout_version_id=int(layout_version_id), + structure_analysis_id=int(analysis.id), + source_content_hash=_norm(document.content_hash or analysis.source_content_hash), + template_packet_checksum=_norm(analysis.template_packet_checksum), + datasets_packet_checksum=_norm(analysis.datasets_packet_checksum), + dataset_structure_fingerprint=_norm(analysis.dataset_structure_fingerprint), + preview_render_checksum=_norm(preview_render_checksum), + render_mode=RENDER_MODE, + renderer_version=RENDERER_VERSION, + page_count=int(page_count or 0), + ) + + +def _cache_key_for_analysis( + *, + analysis: ShippingXfaStructureAnalysis, + document: ShippingOrderDocument, +) -> str: + """按冻结 Analysis 身份构造预览缓存键(不含 render checksum)。""" + return build_preview_cache_key( + structure_analysis_id=int(analysis.id), + template_packet_checksum=_norm(analysis.template_packet_checksum), + datasets_packet_checksum=_norm(analysis.datasets_packet_checksum), + dataset_structure_fingerprint=_norm(analysis.dataset_structure_fingerprint), + source_content_hash=_norm(document.content_hash or analysis.source_content_hash), + renderer_version=RENDERER_VERSION, + ) + + +def _identity_from_cached(payload: dict[str, Any]) -> PreviewIdentityContext | None: + """从缓存条目还原 PreviewIdentityContext;字段缺失时返回 None。""" + raw = payload.get('identity') if isinstance(payload.get('identity'), dict) else None + if not raw: + return None + try: + return PreviewIdentityContext( + document_id=int(raw['document_id']) if raw.get('document_id') is not None else None, + layout_version_id=( + int(raw['layout_version_id']) if raw.get('layout_version_id') is not None else None + ), + structure_analysis_id=raw.get('structure_analysis_id'), + source_content_hash=_norm(raw.get('source_content_hash')), + template_packet_checksum=_norm(raw.get('template_packet_checksum')), + datasets_packet_checksum=_norm(raw.get('datasets_packet_checksum')), + dataset_structure_fingerprint=_norm(raw.get('dataset_structure_fingerprint')), + preview_render_checksum=_norm(raw.get('preview_render_checksum')), + render_mode=str(raw.get('render_mode') or RENDER_MODE), + renderer_version=str(raw.get('renderer_version') or ''), + page_count=int(raw.get('page_count') or 0), + ) + except (TypeError, ValueError, KeyError): + return None + + +def _assert_capability_matches_analysis( + *, + capability: dict[str, Any], + analysis: ShippingXfaStructureAnalysis, + document_id: int, + layout_version_id: int, +) -> None: + """ + 校验 Layout.xfa_capability 与冻结 Analysis 身份一致。 + + 核心逻辑:structure_analysis_id / template / fingerprint 任一漂移 → STALE。 + """ + cap_id = capability.get('structure_analysis_id') + if cap_id not in (None, '') and int(cap_id) != int(analysis.id): + _raise_preview_error( + XFA_PREVIEW_STALE, + 'Cached XFA preview identity is stale relative to frozen analysis', + details={ + 'document_id': document_id, + 'layout_version_id': layout_version_id, + 'structure_analysis_id': int(analysis.id), + 'capability_structure_analysis_id': int(cap_id), + 'reason': 'structure_analysis_id_mismatch', + }, + ) + expected_fp = _norm(analysis.dataset_structure_fingerprint) + actual_fp = _norm(capability.get('dataset_structure_fingerprint')) + if expected_fp and actual_fp and expected_fp != actual_fp: + _raise_preview_error( + XFA_PREVIEW_STALE, + 'Frozen XFA dataset fingerprint no longer matches layout capability', + details={ + 'document_id': document_id, + 'layout_version_id': layout_version_id, + 'structure_analysis_id': int(analysis.id), + 'reason': 'dataset_structure_fingerprint_mismatch', + }, + ) + expected_tpl = _norm(analysis.template_packet_checksum) + actual_tpl = _norm(capability.get('template_packet_checksum')) + if expected_tpl and actual_tpl and expected_tpl != actual_tpl: + _raise_preview_error( + XFA_PREVIEW_STALE, + 'Frozen XFA template checksum no longer matches layout capability', + details={ + 'document_id': document_id, + 'layout_version_id': layout_version_id, + 'structure_analysis_id': int(analysis.id), + 'reason': 'template_packet_checksum_mismatch', + }, + ) + + +def _assert_live_packets_match_analysis( + *, + analysis: ShippingXfaStructureAnalysis, + live_capability: dict[str, Any], + document_id: int, +) -> None: + """ + 校验即时解析的 packet/指纹与冻结 Analysis 一致。 + + 核心逻辑:指纹或 datasets checksum 不等 → VALUE_MISMATCH(禁止用漂移数据合成)。 + """ + live_fp = _norm(live_capability.get('dataset_structure_fingerprint')) + frozen_fp = _norm(analysis.dataset_structure_fingerprint) + if frozen_fp and live_fp and frozen_fp != live_fp: + _raise_preview_error( + XFA_PREVIEW_VALUE_MISMATCH, + 'Live XFA datasets fingerprint does not match frozen analysis', + details={ + 'document_id': document_id, + 'structure_analysis_id': int(analysis.id), + 'reason': 'live_dataset_fingerprint_mismatch', + }, + ) + packet_checksums = live_capability.get('packet_checksums') + if isinstance(packet_checksums, dict): + live_datasets = _norm(packet_checksums.get('datasets')) + frozen_datasets = _norm(analysis.datasets_packet_checksum) + if frozen_datasets and live_datasets and frozen_datasets != live_datasets: + _raise_preview_error( + XFA_PREVIEW_VALUE_MISMATCH, + 'Live XFA datasets packet checksum does not match frozen analysis', + details={ + 'document_id': document_id, + 'structure_analysis_id': int(analysis.id), + 'reason': 'live_datasets_checksum_mismatch', + }, + ) + + +def _page_metas_without_images(pages: list[dict[str, Any]]) -> list[dict[str, Any]]: + """将合成页列表投影为不含 png_bytes 的元数据。""" + metas: list[dict[str, Any]] = [] + for page in pages: + if not isinstance(page, dict): + continue + echoes = page.get('drawn_field_echoes') or [] + metas.append({ + 'page_no': int(page.get('page_no') or 0), + 'width': float(page.get('width') or 0), + 'height': float(page.get('height') or 0), + 'drawn_echo_count': len(echoes) if isinstance(echoes, list) else 0, + }) + return metas + + +def _issue_page_grants( + *, + document_id: int, + structure_analysis_id: int, + actor_id: int, + pages: list[dict[str, Any]], +) -> list[dict[str, Any]]: + """ + 为合成预览各页签发短时一次性 token。 + + Returns: + ``[{page_no, preview_token, width?, height?}, ...]`` + """ + store = _preview_grant_store() + grants: list[dict[str, Any]] = [] + for page in pages: + if not isinstance(page, dict): + continue + page_no = int(page.get('page_no') or 0) + if page_no <= 0: + continue + grant_token = secrets.token_urlsafe(24) + store.setex( + f'{PREVIEW_GRANT_KEY_PREFIX}{grant_token}', + PREVIEW_GRANT_TTL_SECONDS, + json.dumps({ + 'document_id': int(document_id), + 'structure_analysis_id': int(structure_analysis_id), + 'actor_id': int(actor_id), + 'page_no': page_no, + }, separators=(',', ':')), + ) + item: dict[str, Any] = { + 'page_no': page_no, + 'preview_token': grant_token, + } + if page.get('width') is not None: + item['width'] = float(page.get('width') or 0) + if page.get('height') is not None: + item['height'] = float(page.get('height') or 0) + if 'drawn_echo_count' in page: + item['drawn_echo_count'] = int(page.get('drawn_echo_count') or 0) + grants.append(item) + return grants + + +def _resolve_frozen_preview_context( + document_id: int, + *, + actor_id: int | None, +) -> tuple[ShippingOrderDocument, Any, ShippingXfaStructureAnalysis, dict[str, Any]]: + """ + 解析冻结 Layout/Analysis;禁止 document 最新 Analysis 回退。 + + Returns: + (document, layout_version, analysis, capability)。 + """ + if actor_id is None: + raise NotFoundError( + 'Order profile sample not found', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND', + ) + document = _require_sample_document(document_id) + from app.services.shipping_notice.document_layout.xfa_analysis import ( + resolve_frozen_xfa_structure_analysis, + ) + + layout_version, analysis, capability = resolve_frozen_xfa_structure_analysis(document) + kind = str(analysis.document_kind or capability.get('document_kind') or '').strip() + if kind and kind not in _XFA_PREVIEW_KINDS: + _raise_preview_error( + XFA_PREVIEW_UNAVAILABLE, + 'Synthetic XFA preview is only available for xfa_hybrid/pure_xfa documents', + details={ + 'document_id': int(document.id), + 'document_kind': kind, + 'reason': 'unsupported_document_kind', + }, + ) + _assert_capability_matches_analysis( + capability=capability, + analysis=analysis, + document_id=int(document.id), + layout_version_id=int(layout_version.id), + ) + return document, layout_version, analysis, capability + + +def _load_cached_ready_preview( + *, + document: ShippingOrderDocument, + layout_version_id: int, + analysis: ShippingXfaStructureAnalysis, +) -> dict[str, Any]: + """ + 读取并校验与冻结身份绑定的 ready 缓存;stale/缺失 fail-closed。 + + Returns: + 缓存预览字典(含 pages/png_bytes)。 + """ + cache_key = _cache_key_for_analysis(analysis=analysis, document=document) + cached = get_preview_cache(cache_key) + if not isinstance(cached, dict): + _raise_preview_error( + XFA_PREVIEW_UNAVAILABLE, + 'Synthetic XFA preview is not available; request generation first', + details={ + 'document_id': int(document.id), + 'structure_analysis_id': int(analysis.id), + 'reason': 'cache_miss', + }, + ) + cached_identity = _identity_from_cached(cached) + expected = _build_identity_context( + document=document, + layout_version_id=layout_version_id, + analysis=analysis, + preview_render_checksum=( + cached_identity.preview_render_checksum if cached_identity else '' + ), + page_count=int(cached.get('page_count') or 0), + ) + if cached_identity is None or is_preview_identity_stale( + expected=expected, + actual=cached_identity, + ): + _raise_preview_error( + XFA_PREVIEW_STALE, + 'Synthetic XFA preview cache is stale relative to frozen analysis identity', + details={ + 'document_id': int(document.id), + 'layout_version_id': layout_version_id, + 'structure_analysis_id': int(analysis.id), + 'reason': 'preview_identity_stale', + }, + ) + status = str(cached.get('status') or '').strip() + if status != 'ready': + short = str(cached.get('error_code') or XFA_PREVIEW_UNAVAILABLE) + _raise_preview_error( + short if short.startswith('XFA_PREVIEW_') else XFA_PREVIEW_UNAVAILABLE, + 'Synthetic XFA preview is not ready', + details={ + 'document_id': int(document.id), + 'structure_analysis_id': int(analysis.id), + 'status': status, + 'reason': 'preview_not_ready', + }, + ) + return cached + + +def build_xfa_preview_definition_meta(cached: dict[str, Any]) -> dict[str, Any]: + """ + 从合成预览缓存构造可写入 definition.xfa_preview 的发布证据摘要。 + + 核心逻辑:剥离 png_bytes,保留 status/checksum/renderer_version 与逐页 + source/synthetic page box + page_identity_hash,供 publish gate(BE-3)消费。 + + Args: + cached: 预览缓存字典(compose 结果或 get_preview_cache 命中)。 + + Returns: + definition.xfa_preview 兼容字典(无大图)。 + """ + diagnostics = cached.get('diagnostics') if isinstance(cached.get('diagnostics'), dict) else {} + page_count = int(cached.get('page_count') or 0) + status = str(cached.get('status') or '').strip().lower() + page_evidence = diagnostics.get('pages') if isinstance(diagnostics.get('pages'), list) else [] + safe_pages: list[dict[str, Any]] = [] + for raw in page_evidence: + if not isinstance(raw, dict): + continue + safe_pages.append({ + 'page_no': raw.get('page_no'), + 'source_page_box': raw.get('source_page_box'), + 'synthetic_page_box': raw.get('synthetic_page_box'), + 'page_identity_hash': raw.get('page_identity_hash'), + }) + source_count = diagnostics.get('source_page_count') + synthetic_count = diagnostics.get('synthetic_page_count') + if source_count is None: + source_count = page_count if safe_pages else None + if synthetic_count is None: + synthetic_count = page_count if safe_pages else None + return { + 'status': cached.get('status'), + 'preview_render_checksum': cached.get('preview_render_checksum'), + 'render_mode': cached.get('render_mode') or RENDER_MODE, + 'renderer_version': cached.get('renderer_version') or RENDERER_VERSION, + 'page_count': page_count, + 'pages_ready': list(range(1, page_count + 1)) if status == 'ready' and page_count > 0 else [], + 'source_page_count': source_count, + 'synthetic_page_count': synthetic_count, + 'pages': safe_pages, + } + + +def _public_preview_payload( + *, + cached: dict[str, Any], + page_grants: list[dict[str, Any]], + cache_hit: bool, +) -> dict[str, Any]: + """构造 API 安全响应(不含 png_bytes;含 definition_preview_meta 供草稿落库)。""" + identity = cached.get('identity') if isinstance(cached.get('identity'), dict) else {} + diagnostics = cached.get('diagnostics') if isinstance(cached.get('diagnostics'), dict) else {} + definition_meta = build_xfa_preview_definition_meta(cached) + safe_diagnostics = { + key: diagnostics[key] + for key in ( + 'reason', + 'drawn_echo_count', + 'leaf_count', + 'widget_count', + 'source_page_count', + 'synthetic_page_count', + 'pages', + ) + if key in diagnostics + } + if 'pages' not in safe_diagnostics and definition_meta.get('pages'): + safe_diagnostics['pages'] = definition_meta['pages'] + if 'source_page_count' not in safe_diagnostics and definition_meta.get('source_page_count') is not None: + safe_diagnostics['source_page_count'] = definition_meta['source_page_count'] + if 'synthetic_page_count' not in safe_diagnostics and definition_meta.get('synthetic_page_count') is not None: + safe_diagnostics['synthetic_page_count'] = definition_meta['synthetic_page_count'] + return { + 'document_id': identity.get('document_id'), + 'identity': identity, + 'status': cached.get('status'), + 'error_code': shipping_error_code_for_preview(cached.get('error_code')), + 'render_mode': cached.get('render_mode') or RENDER_MODE, + 'renderer_version': cached.get('renderer_version') or RENDERER_VERSION, + 'page_count': int(cached.get('page_count') or 0), + 'preview_render_checksum': cached.get('preview_render_checksum'), + 'pages': page_grants, + 'expires_in_seconds': PREVIEW_GRANT_TTL_SECONDS, + 'cache_hit': bool(cache_hit), + 'diagnostics': safe_diagnostics, + # BE-3:前端/保存草稿直接写入 definition.xfa_preview,避免发布时缺页身份证据 + 'definition_preview_meta': definition_meta, + 'source_page_count': definition_meta.get('source_page_count'), + 'synthetic_page_count': definition_meta.get('synthetic_page_count'), + } + + +def request_xfa_synthetic_preview( + document_id: int, + *, + actor_id: int | None, + force: bool = False, +) -> dict[str, Any]: + """ + 为冻结 Layout Analysis 生成或复用合成预览,并签发页级短时 token。 + + 核心逻辑: + 1. resolve_frozen_xfa_structure_analysis(禁止最新 Analysis 回退); + 2. 命中且身份一致的 ready 缓存则复用; + 3. 否则读 PDF → 即时解析 datasets 并校验指纹 → compose_xfa_dataset_preview_pages; + 4. 写入 xfa_preview_cache;返回身份 + 状态 + 页元数据(无大图)。 + + Args: + document_id: ShippingOrderDocument 主键。 + actor_id: 管理员 ID(必填)。 + force: True 时忽略 ready 缓存强制重生成。 + + Returns: + 预览摘要字典(含 pages[].preview_token)。 + + Raises: + NotFoundError / ValidationError: 样本缺失或身份/合成失败。 + """ + document, layout_version, analysis, _capability = _resolve_frozen_preview_context( + document_id, actor_id=actor_id, + ) + _audit( + document_id=int(document.id), + event_type='xfa_preview_requested', + actor_id=actor_id, + detail={ + 'layout_version_id': int(layout_version.id), + 'structure_analysis_id': int(analysis.id), + 'force': bool(force), + }, + ) + + cache_key = _cache_key_for_analysis(analysis=analysis, document=document) + cached = None if force else get_preview_cache(cache_key) + cache_hit = False + if isinstance(cached, dict) and str(cached.get('status') or '') == 'ready': + try: + cached = _load_cached_ready_preview( + document=document, + layout_version_id=int(layout_version.id), + analysis=analysis, + ) + cache_hit = True + except ValidationError: + cached = None + + if not cache_hit: + # [STEP 1] 读取 PDF 并即时解析 datasets,校验与冻结 Analysis 身份一致 + asset = db.session.get(FileAsset, int(document.asset_id or 0)) if document.asset_id else None + if asset is None: + _audit( + document_id=int(document.id), + event_type='xfa_preview_failed', + actor_id=actor_id, + detail={'reason': 'asset_missing', 'structure_analysis_id': int(analysis.id)}, + ) + db.session.commit() + _raise_preview_error( + XFA_PREVIEW_UNAVAILABLE, + 'XFA sample asset is unavailable for synthetic preview', + details={'document_id': int(document.id), 'reason': 'asset_missing'}, + ) + + from app.services.file_assets.service import read_asset_bytes + from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf + + try: + pdf_bytes = read_asset_bytes(asset) + except Exception as exc: # noqa: BLE001 — 读失败统一 UNAVAILABLE + _audit( + document_id=int(document.id), + event_type='xfa_preview_failed', + actor_id=actor_id, + detail={'reason': 'asset_read_failed', 'structure_analysis_id': int(analysis.id)}, + ) + db.session.commit() + _raise_preview_error( + XFA_PREVIEW_UNAVAILABLE, + 'Failed to read XFA sample bytes for synthetic preview', + details={'document_id': int(document.id), 'reason': 'asset_read_failed', 'detail': str(exc)[:200]}, + ) + + outcome = analyze_xfa_pdf(pdf_bytes) + live_cap = ( + (outcome.snapshot or {}).get('xfa_capability') + if isinstance(outcome.snapshot, dict) + else {} + ) + if not isinstance(live_cap, dict): + live_cap = {} + try: + _assert_live_packets_match_analysis( + analysis=analysis, + live_capability=live_cap, + document_id=int(document.id), + ) + except ValidationError: + _audit( + document_id=int(document.id), + event_type='xfa_preview_failed', + actor_id=actor_id, + detail={ + 'reason': 'value_mismatch', + 'structure_analysis_id': int(analysis.id), + 'error_code': XFA_PREVIEW_VALUE_MISMATCH, + }, + ) + db.session.commit() + raise + + if outcome.dataset_analysis is None: + _audit( + document_id=int(document.id), + event_type='xfa_preview_failed', + actor_id=actor_id, + detail={'reason': 'dataset_analysis_missing', 'structure_analysis_id': int(analysis.id)}, + ) + db.session.commit() + _raise_preview_error( + XFA_PREVIEW_UNAVAILABLE, + 'XFA datasets analysis is unavailable for synthetic preview', + details={'document_id': int(document.id), 'reason': 'dataset_analysis_missing'}, + ) + + # [STEP 2] 合成预览页 + template_bytes = None + if outcome.packet_result is not None: + template_bytes = outcome.packet_result.packet_bytes_by_name.get('template') + compose_result = compose_xfa_dataset_preview_pages( + pdf_bytes=pdf_bytes, + analysis_or_nodes=outcome.dataset_analysis, + template_bytes=template_bytes, + ) + identity = _build_identity_context( + document=document, + layout_version_id=int(layout_version.id), + analysis=analysis, + preview_render_checksum=str(compose_result.preview_render_checksum or ''), + page_count=int(compose_result.page_count or 0), + ) + cached = { + 'identity': preview_identity_to_dict(identity), + 'status': compose_result.status, + 'error_code': compose_result.error_code, + 'render_mode': compose_result.render_mode, + 'renderer_version': compose_result.renderer_version, + 'page_count': compose_result.page_count, + 'preview_render_checksum': compose_result.preview_render_checksum, + 'pages': list(compose_result.pages or []), + 'diagnostics': dict(compose_result.diagnostics or {}), + } + set_preview_cache(cache_key, cached) + + if compose_result.status != 'ready': + _audit( + document_id=int(document.id), + event_type='xfa_preview_failed', + actor_id=actor_id, + detail={ + 'structure_analysis_id': int(analysis.id), + 'status': compose_result.status, + 'error_code': compose_result.error_code, + 'diagnostics': { + key: compose_result.diagnostics.get(key) + for key in ('reason', 'drawn_echo_count') + if key in (compose_result.diagnostics or {}) + }, + }, + ) + db.session.commit() + short = str(compose_result.error_code or XFA_PREVIEW_FAILED) + _raise_preview_error( + short if short.startswith('XFA_PREVIEW_') else XFA_PREVIEW_FAILED, + 'Synthetic XFA preview generation failed', + details={ + 'document_id': int(document.id), + 'structure_analysis_id': int(analysis.id), + 'status': compose_result.status, + 'error_code': short, + }, + ) + + _audit( + document_id=int(document.id), + event_type='xfa_preview_generated', + actor_id=actor_id, + detail={ + 'layout_version_id': int(layout_version.id), + 'structure_analysis_id': int(analysis.id), + 'page_count': int(compose_result.page_count or 0), + 'preview_render_checksum': compose_result.preview_render_checksum, + 'renderer_version': RENDERER_VERSION, + }, + ) + + page_metas = _page_metas_without_images(list(cached.get('pages') or [])) + page_grants = _issue_page_grants( + document_id=int(document.id), + structure_analysis_id=int(analysis.id), + actor_id=int(actor_id), + pages=page_metas, + ) + db.session.commit() + return _public_preview_payload(cached=cached, page_grants=page_grants, cache_hit=cache_hit) + + +def list_xfa_synthetic_preview_pages( + document_id: int, + *, + actor_id: int | None, +) -> dict[str, Any]: + """ + 列出绑定冻结 Analysis 的最新 ready 合成预览页元数据并重新签发 token。 + + 核心逻辑:resolve_frozen → 校验缓存身份 → 无图元数据 + grant。 + + Args: + document_id: 样本文档主键。 + actor_id: 管理员 ID。 + + Returns: + 与 request 同形的预览摘要(cache_hit=True)。 + """ + document, layout_version, analysis, _capability = _resolve_frozen_preview_context( + document_id, actor_id=actor_id, + ) + cached = _load_cached_ready_preview( + document=document, + layout_version_id=int(layout_version.id), + analysis=analysis, + ) + page_metas = _page_metas_without_images(list(cached.get('pages') or [])) + page_grants = _issue_page_grants( + document_id=int(document.id), + structure_analysis_id=int(analysis.id), + actor_id=int(actor_id), + pages=page_metas, + ) + _audit( + document_id=int(document.id), + event_type='xfa_preview_viewed', + actor_id=actor_id, + detail={ + 'structure_analysis_id': int(analysis.id), + 'layout_version_id': int(layout_version.id), + 'page_count': int(cached.get('page_count') or 0), + 'mode': 'list_pages', + }, + ) + db.session.commit() + return _public_preview_payload(cached=cached, page_grants=page_grants, cache_hit=True) + + +def render_xfa_synthetic_preview_page( + document_id: int, + *, + page_no: int, + token: str, + actor_id: int | None, +) -> bytes: + """ + 消费一次性 token,返回绑定冻结 Analysis 的合成预览单页 PNG。 + + 核心逻辑:校验 grant → 再校验冻结身份与缓存 → 取出 png_bytes。 + + Args: + document_id: 样本文档主键。 + page_no: 1-based 页码。 + token: preview_token。 + actor_id: 管理员 ID。 + + Returns: + PNG 字节。 + + Raises: + NotFoundError: token 无效/重放/越权。 + ValidationError: 预览 stale 或页不存在。 + """ + store = _preview_grant_store() + raw_grant = store.getdel(f'{PREVIEW_GRANT_KEY_PREFIX}{str(token or "")}') + try: + grant = json.loads(raw_grant) if raw_grant else None + except (TypeError, json.JSONDecodeError): + grant = None + if ( + not isinstance(grant, dict) + or actor_id is None + or grant.get('actor_id') != int(actor_id) + or grant.get('page_no') != int(page_no) + or grant.get('document_id') != int(document_id) + ): + raise NotFoundError( + 'Order profile XFA synthetic preview not found', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND', + ) + + document, layout_version, analysis, _capability = _resolve_frozen_preview_context( + document_id, actor_id=actor_id, + ) + if int(grant.get('structure_analysis_id') or 0) != int(analysis.id): + _raise_preview_error( + XFA_PREVIEW_STALE, + 'Synthetic preview grant is bound to a different frozen analysis', + details={ + 'document_id': int(document.id), + 'structure_analysis_id': int(analysis.id), + 'grant_structure_analysis_id': grant.get('structure_analysis_id'), + 'reason': 'grant_analysis_mismatch', + }, + ) + + cached = _load_cached_ready_preview( + document=document, + layout_version_id=int(layout_version.id), + analysis=analysis, + ) + page = next( + ( + item for item in (cached.get('pages') or []) + if isinstance(item, dict) and int(item.get('page_no') or 0) == int(page_no) + ), + None, + ) + png = page.get('png_bytes') if isinstance(page, dict) else None + if not isinstance(png, (bytes, bytearray)) or not png: + raise NotFoundError( + 'Order profile XFA synthetic preview page not found', + code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND', + ) + + _audit( + document_id=int(document.id), + event_type='xfa_preview_viewed', + actor_id=actor_id, + detail={ + 'structure_analysis_id': int(analysis.id), + 'layout_version_id': int(layout_version.id), + 'page_no': int(page_no), + 'mode': 'page_png', + }, + ) + db.session.commit() + return bytes(png) diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index 3404e0b3..bc72ae43 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -1223,11 +1223,11 @@ def _route_xfa_deterministic_unit( definition: dict[str, Any], ) -> DeterministicRouteResult: """ - 执行 XFA 正式确定性提取;失败由 route_deterministic_unit 回退坐标/OCR/通用/Dify。 + 执行 XFA 正式确定性提取;失败关闭为 review_required,禁止回退坐标/OCR/通用正式提取。 核心逻辑:读 PDF → analyze_xfa_pdf → 精确匹配 published 冻结 Profile → 路径提取 → AcroForm/镜像/金额校验 → 组装订单;Run 决策写入结构指纹与 parser identity。 - 未命中或校验失败时返回 review_required + fallback_reason_codes,供上层回退。 + 未命中或校验失败时返回 review_required + fallback_reason_codes,由上层原样返回。 """ from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf @@ -1482,7 +1482,8 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult AI 触发时机:无需调用。Worker 在每个 Unit 执行前调用;已批准模板或通用 Schema 确定性解析可走 deterministic;其余进入复核或 LLM 辅助建议。 - 识别到 xfa_hybrid 时优先走 xfa_dataset;失败回退坐标/OCR/通用确定性,再标记 Dify LLM 兜底。 + 识别到 xfa_hybrid 且 XFA 启用时走 xfa_dataset;失败立即返回 review_required, + 禁止回退坐标/OCR/通用正式提取(建模期 OCR 辅助不受影响)。 """ snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {} @@ -1495,33 +1496,12 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult intake, document = _unit_snapshot(run, unit) layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {} - # [STEP 0] XFA capability:优先 xfa_dataset;失败不终态关闭,回退坐标/OCR/通用/Dify。 - xfa_fallback_reasons: list[str] = [] + # [STEP 0] XFA capability:优先 xfa_dataset;非 deterministic 成功时立即返回,禁止坐标/OCR/通用回退。 if _layout_is_xfa_capable(layout) and xfa_enabled(): - xfa_result = _route_xfa_deterministic_unit( + return _route_xfa_deterministic_unit( run=run, unit=unit, intake=intake, document=document, schema=schema, definition=definition, ) - if ( - xfa_result.execution_mode == 'deterministic' - and xfa_result.orders - and str((xfa_result.decision or {}).get('route_decision') or '') == 'straight_through' - ): - return xfa_result - # 提取成功但需复核时,仍优先保留 XFA 结果,避免空白页坐标误覆盖。 - if xfa_result.execution_mode == 'deterministic' and xfa_result.orders: - return xfa_result - xfa_fallback_reasons = [ - str(code) for code in ((xfa_result.decision or {}).get('fallback_reason_codes') or []) - if str(code).strip() - ] - if not xfa_fallback_reasons: - xfa_fallback_reasons = [ - str(code) for code in ((xfa_result.decision or {}).get('reason_codes') or []) - if str(code).strip() - ] - if not xfa_fallback_reasons: - xfa_fallback_reasons = ['xfa_profile_not_matched'] profile_result = _profile_table_candidates(run, unit=unit) match = profile_result.get('match') if isinstance(profile_result.get('match'), dict) else {} @@ -1545,9 +1525,8 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult 'parsed_table_count': 0, 'approved_table_count': sum(1 for item in tables if isinstance(item, dict) and item.get('auto_create_approved')), 'candidate_summary': candidates, - 'fallback_reason_codes': list(xfa_fallback_reasons), - 'capability_kind': 'coordinate' if not xfa_fallback_reasons else 'xfa_fallback_coordinate', - 'xfa_fallback_reason_codes': list(xfa_fallback_reasons), + 'fallback_reason_codes': [], + 'capability_kind': 'coordinate', } # [STEP 1] 模板确定性路径:唯一匹配表且解析完整时优先走 profile_deterministic。 @@ -1618,9 +1597,9 @@ def _should_attempt_generic_extraction(*, match_status: str, profile_result: dic """ 判断是否允许进入通用 Schema 确定性解析。 - 核心逻辑:无异型特征或未命中模板时可尝试通用路径;layout_drift / ambiguous / - evidence_insufficient 保持 fail-closed。XFA 失败后回退到本路径时,match_status - 来自坐标 matcher,按坐标规则裁决(允许 no_match 进入通用/Dify 兜底)。 + 核心逻辑:仅用于非 XFA 正式路径。无异型特征或未命中坐标模板时可尝试通用路径; + layout_drift / ambiguous / evidence_insufficient / structure_identity_changed 保持 fail-closed。 + XFA-capable 且启用时不会进入本函数(STEP 0 已失败关闭)。 """ status = str(match_status or '').strip() if status in { 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 17923f77..38db8916 100644 --- a/backend/app/services/shipping_notice/order_review_draft_service.py +++ b/backend/app/services/shipping_notice/order_review_draft_service.py @@ -467,6 +467,27 @@ def _validation( can_build = bool(eligibility.get('can_build')) and not any( str(item.get('severity') or '') == 'blocking' for item in issues ) + # [STEP 2] 为缺失/无效字段补齐 field_code + display_name,禁止只返回裸 code。 + enriched_issues: list[dict[str, Any]] = [] + for item in issues: + if not isinstance(item, dict): + continue + row = dict(item) + field_id = str(row.get('field_id') or '').strip() + field_cfg = fields.get(field_id) if field_id else None + if field_cfg and not row.get('field_code'): + row['field_code'] = str(field_cfg.get('field_code') or field_id) + if field_cfg and not row.get('display_name'): + row['display_name'] = str( + field_cfg.get('display_name') + or field_cfg.get('label') + or field_cfg.get('field_code') + or field_id + ) + if str(row.get('code') or '') == 'required_field_missing' and not row.get('reason'): + row['reason'] = 'empty_after_normalization' + enriched_issues.append(row) + return { 'status': 'ready' if can_build else 'needs_review', 'can_build': can_build, @@ -474,7 +495,7 @@ def _validation( 'shadow_would_auto_create': bool(eligibility.get('shadow_would_auto_create')), 'gates': dict(eligibility.get('gates') or {}), 'failed_gates': list(eligibility.get('failed_gates') or []), - 'issues': issues, + 'issues': enriched_issues, 'line_projections': list(eligibility.get('line_projections') or []), 'qualification': eligibility.get('qualification'), # 完整检查需要明确指出缺失字段,不能只返回一个布尔门禁。 @@ -484,6 +505,10 @@ def _validation( 'invalid_lines': list((eligibility.get('assessment') or {}).get('invalid_lines') or []), }, 'enabled_inventory_source_codes': list(eligibility.get('enabled_inventory_source_codes') or []), + # Snapshot 身份:前端必须以 case_no + draft_version + validation_version 校验归属。 + 'case_no': str(case.case_no or ''), + 'document_id': int(case.document_id) if case.document_id else None, + 'draft_version': int(draft.draft_version) if draft is not None else None, } @@ -606,11 +631,41 @@ def _record_change( before_version = int(draft.draft_version) previous_status = str(case.status or 'draft') result = _validation(case) if validate else {'status': 'not_validated', 'issues': []} - draft.validation_result_json = result - draft.issue_summary_json = list(result['issues']) draft.updated_by_id = int(actor_id) draft.draft_version = int(draft.draft_version) + 1 - case.status = 'ready' if validate and result['status'] == 'ready' else 'draft' + # [STEP] 显式校验后绑定 Snapshot 身份到新 draft_version,供前后端丢弃过期结果。 + if validate and isinstance(result, dict): + import hashlib + import json + from datetime import datetime, timezone + + result = dict(result) + result['case_no'] = str(case.case_no or '') + result['document_id'] = int(case.document_id) if case.document_id else None + result['draft_version'] = int(draft.draft_version) + result['validated_at'] = datetime.now(timezone.utc).isoformat() + result['validated_case_no'] = str(case.case_no or '') + result['validated_document_id'] = int(case.document_id) if case.document_id else None + # [STEP] 方案 B:无 DB 迁移;用 checksum 区分同 Draft 的重复校验结果。 + checksum_payload = { + 'case_no': result['case_no'], + 'document_id': result['document_id'], + 'draft_version': result['draft_version'], + 'status': result.get('status'), + 'can_build': result.get('can_build'), + 'can_auto_create': result.get('can_auto_create'), + 'issues': result.get('issues') or [], + 'failed_gates': result.get('failed_gates') or [], + 'validated_at': result['validated_at'], + } + result['validation_checksum'] = hashlib.sha256( + json.dumps(checksum_payload, sort_keys=True, ensure_ascii=False, default=str).encode('utf-8'), + ).hexdigest()[:32] + # 兼容旧前端:validation_version 回落为 draft_version,权威身份以 checksum 为准。 + result['validation_version'] = int(draft.draft_version) + draft.validation_result_json = result + draft.issue_summary_json = list(result.get('issues') or []) + case.status = 'ready' if validate and result.get('status') == 'ready' else 'draft' db.session.add(ShippingOrderReviewCaseEvent( case_id=int(case.id), event_type=event_type, draft_version=int(draft.draft_version), actor_user_id=int(actor_id), operation_json=operation, diff --git a/backend/app/services/shipping_notice/order_review_projection.py b/backend/app/services/shipping_notice/order_review_projection.py index ad628dab..db4a11cb 100644 --- a/backend/app/services/shipping_notice/order_review_projection.py +++ b/backend/app/services/shipping_notice/order_review_projection.py @@ -15,7 +15,10 @@ backend/app/services/shipping_notice/order_review_projection.py workflow_ledger_service.find_item_by_current_case、ShippingNotice(确认后推进态)。 逻辑:只返回工作台展示所需的字段定义、机器/人工草稿值、问题、建单资格与行级库存候选; 固定投影 customer_resolution / field_conflicts / duplicate / profile_match / - reservation / line_fulfillment; + reservation / line_fulfillment / automation; + profile_match 按 is_admin 裁剪(普通用户仅 admin_only 占位); + automation 区分 waiting_to_start / queued / running / manual_fallback,禁止资格冒充正在推进; + 管理员另附 technical_progress(如 document_materialization pending); Case 级暴露 candidate_id / order_task_no(Candidate 一对一 OT,禁止前端回退 Run 根号); 为每行/表头投影 field_meta(value_source / locked / override_reason); 已确认 Case 附带 confirmed_task_no 与 post_confirm_auto_progress,供刷新后恢复「已建单待推进」; @@ -86,6 +89,185 @@ def _project_post_confirm_auto_progress(case: ShippingOrderReviewCase) -> dict[s } +def _stp_waiting_timeout_seconds() -> int: + """STP waiting_to_start 超时秒数(服务端配置,禁止前端硬编码)。""" + try: + from flask import current_app + + return max(int(current_app.config.get('SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS', 120) or 120), 15) + except Exception: # noqa: BLE001 + return 120 + + +def _parse_iso_datetime(value: Any): + """解析 ISO 时间;失败返回 None。""" + from datetime import datetime + + text = str(value or '').strip() + if not text: + return None + try: + if text.endswith('Z'): + text = text[:-1] + '+00:00' + return datetime.fromisoformat(text) + except ValueError: + return None + + +def _project_case_automation_status( + case: ShippingOrderReviewCase, + *, + validation: dict[str, Any] | None, + post_confirm: dict[str, Any] | None, +) -> dict[str, Any]: + """ + 投影用户可见的自动建单/推进状态;资格达标不等于正在推进。 + + 核心逻辑: + - confirmed + needs_retry → failed(可重试) + - confirmed + 已有 Task 且非 retry → queued/running/completed + - 存在 STP Job queued/running → 对应状态 + - STP Job failed → failed(可重试) + - can_auto_create 且未入队 → waiting_to_start;超时无 Job → manual_fallback + - 其余 → idle + + Returns: + status / retryable / task_no / can_auto_create / job_id。 + """ + from datetime import datetime, timezone + + from app.services.shipping_notice.order_stp_auto_create_service import ( + build_stp_idempotency_key, + find_active_stp_job, + find_latest_stp_job, + ) + + can_auto = bool((validation or {}).get('can_auto_create')) + can_build = bool((validation or {}).get('can_build')) + task_no = None + if isinstance(post_confirm, dict): + task_no = str(post_confirm.get('task_no') or '').strip() or None + if post_confirm.get('needs_retry'): + return { + 'status': 'failed', + 'retryable': True, + 'task_no': task_no, + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': None, + 'reason_code': 'post_confirm_auto_progress_failed', + } + if task_no: + process_status = str(post_confirm.get('task_process_status') or '').strip().lower() + if process_status in {'created', ''}: + status = 'queued' + elif process_status in {'completed', 'closed', 'done'}: + status = 'completed' + else: + status = 'running' + return { + 'status': status, + 'retryable': False, + 'task_no': task_no, + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': None, + } + + # [STEP] 查当前有效 STP Job;无有效 Job 时再看最新历史(failed → 可重试)。 + job = None + latest = None + draft = getattr(case, 'current_draft', None) + run = getattr(case, 'run', None) + draft_version = int(draft.draft_version) if draft is not None else None + run_no = str(getattr(run, 'run_no', '') or '') + if draft_version is not None and run_no and case.document_id is not None: + business_ref = build_stp_idempotency_key( + run_no=run_no, + document_id=int(case.document_id), + draft_version=draft_version, + ) + job = find_active_stp_job(business_ref=business_ref) + if job is None: + latest = find_latest_stp_job(business_ref=business_ref) + if job is not None: + job_status = str(job.status or '').strip().lower() + if job_status == 'queued': + return { + 'status': 'queued', + 'retryable': False, + 'task_no': None, + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': int(job.id), + } + if job_status == 'running': + return { + 'status': 'running', + 'retryable': False, + 'task_no': None, + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': int(job.id), + } + if latest is not None and str(latest.status or '').strip().lower() in {'failed', 'dead'}: + return { + 'status': 'failed', + 'retryable': True, + 'task_no': None, + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': int(latest.id), + 'reason_code': 'stp_job_failed', + 'retry_of_job_id': int(latest.id), + } + if latest is not None and str(latest.status or '').strip().lower() in {'succeeded', 'success', 'completed'}: + return { + 'status': 'completed', + 'retryable': False, + 'task_no': None, + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': int(latest.id), + } + + if can_build and can_auto and str(case.status or '') not in {'confirmed', 'non_order', 'quality_issue'}: + # [STEP] waiting 超时且无 STP 记录 → manual_fallback,允许人工确认兜底。 + validated_at = _parse_iso_datetime((validation or {}).get('validated_at')) + anchor = validated_at or getattr(case, 'updated_at', None) or getattr(draft, 'updated_at', None) + if anchor is not None: + if getattr(anchor, 'tzinfo', None) is None: + anchor = anchor.replace(tzinfo=timezone.utc) + age = (datetime.now(timezone.utc) - anchor).total_seconds() + if age >= _stp_waiting_timeout_seconds(): + return { + 'status': 'manual_fallback', + 'retryable': True, + 'task_no': None, + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': None, + 'reason_code': 'stp_waiting_timeout', + } + return { + 'status': 'waiting_to_start', + 'retryable': False, + 'task_no': None, + 'can_auto_create': True, + 'can_build': True, + 'job_id': None, + 'reason_code': 'stp_not_enqueued_yet', + } + return { + 'status': 'idle', + 'retryable': False, + 'task_no': None, + 'can_auto_create': can_auto, + 'can_build': can_build, + 'job_id': None, + } + + def _schema_fields(run: ShippingOrderProcessingRun) -> list[dict[str, Any]]: """投影 Run 冻结 Schema,不读取当前 published Schema。""" snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {} @@ -255,13 +437,38 @@ def _allowed_actions(case: ShippingOrderReviewCase) -> list[str]: actions.append('edit_draft') if case.current_draft is not None and str((case.current_draft.validation_result_json or {}).get('status') or '') == 'ready': actions.append('confirm') + # STP 失败 / manual_fallback:可重试自动建单(与确认兜底互斥由前端按 automation.status 控制)。 + automation = None + try: + automation = _project_case_automation_status( + case, + validation=dict(case.current_draft.validation_result_json or {}) if case.current_draft else None, + post_confirm=_project_post_confirm_auto_progress(case), + ) + except Exception: # noqa: BLE001 + automation = None + if isinstance(automation, dict) and automation.get('retryable') and str(automation.get('status') or '') in { + 'failed', 'manual_fallback', + } and not case.confirmed_task_id: + actions.append('retry_stp_auto_create') if llm_review_enabled() and 'edit_draft' in actions: actions.append('request_llm_suggestion') return actions -def serialize_review_case(case: ShippingOrderReviewCase) -> dict[str, Any]: - """返回一个 Case 的安全详情,用于阶段 1 只读工作台与后续编辑基线。""" +def serialize_review_case( + case: ShippingOrderReviewCase, + *, + is_admin: bool = False, +) -> dict[str, Any]: + """ + 返回一个 Case 的安全详情,用于阶段 1 只读工作台与后续编辑基线。 + + Args: + case: 复核 Case。 + is_admin: 为 True 时返回完整 profile_match 审计;普通用户仅返回 + ``{available: false, visibility: admin_only}``,禁止下发模板 ID/分数/内部原因码。 + """ from app.services.shipping_notice.schema_edit_policy import ( is_excel_ready_for_task, list_editable_formal_field_ids, @@ -327,8 +534,12 @@ def serialize_review_case(case: ShippingOrderReviewCase) -> dict[str, Any]: ) llm_suggestions = [serialize_suggestion(row) for row in rows] process_gate = None + technical_progress = None from app.models import ShippingProcessExecution - from app.services.shipping_notice.process_gate_projection import project_user_gate_summary + from app.services.shipping_notice.process_gate_projection import ( + project_user_gate_summary, + serialize_process_execution, + ) execution = ( ShippingProcessExecution.query @@ -338,10 +549,26 @@ def serialize_review_case(case: ShippingOrderReviewCase) -> dict[str, Any]: ) if execution is not None: process_gate = project_user_gate_summary(execution) + # [STEP] 管理员 technical_progress:如实投影当前技术 Gate(含 pending),不经用户态过滤。 + if is_admin: + full_exec = serialize_process_execution(execution, include_diagnostics=False) + current = full_exec.get('current_gate') if isinstance(full_exec, dict) else None + if isinstance(current, dict) and current.get('gate_code'): + technical_progress = { + 'gate_code': str(current.get('gate_code') or ''), + 'status': str(current.get('status') or ''), + 'blocking_reason_code': current.get('blocking_reason_code'), + } post_confirm = _project_post_confirm_auto_progress(case) confirmed_task_no = None if isinstance(post_confirm, dict) and post_confirm.get('task_no'): confirmed_task_no = str(post_confirm.get('task_no') or '') + validation_snapshot = dict(draft.validation_result_json or {}) if draft is not None else None + automation = _project_case_automation_status( + case, + validation=validation_snapshot, + post_confirm=post_confirm if isinstance(post_confirm, dict) else None, + ) from app.services.shipping_notice.order_review_customer_service import ( project_review_case_customer_resolution, ) @@ -362,6 +589,22 @@ def serialize_review_case(case: ShippingOrderReviewCase) -> dict[str, Any]: ) from app.services.shipping_notice.order_task_service import resolve_order_task_for_candidate + # [STEP] 模板匹配属审计信息:普通用户不得收到模板 ID / 候选分 / 内部原因码。 + if is_admin: + profile_match = project_review_case_profile_match(case) + else: + profile_match = { + 'available': False, + 'visibility': 'admin_only', + 'status': 'hidden', + 'candidates': [], + 'fallback_reason_codes': [], + 'needs_review': False, + 'selected_profile': None, + 'execution_mode': None, + 'route_type': None, + } + # [UI-03] Case 级暴露 Candidate 绑定的 OT,禁止前端回退 Run 根号。 linked_order_task = resolve_order_task_for_candidate( int(case.candidate_id) if case.candidate_id else None, @@ -390,6 +633,8 @@ def serialize_review_case(case: ShippingOrderReviewCase) -> dict[str, Any]: 'confirmed_task_id': int(case.confirmed_task_id) if case.confirmed_task_id else None, 'confirmed_task_no': confirmed_task_no, 'post_confirm_auto_progress': post_confirm, + 'automation': automation, + 'technical_progress': technical_progress, 'candidate': { 'id': int(candidate.id), 'candidate_no': candidate.candidate_no, @@ -399,7 +644,7 @@ def serialize_review_case(case: ShippingOrderReviewCase) -> dict[str, Any]: 'customer_resolution': project_review_case_customer_resolution(case), 'field_conflicts': project_review_case_field_conflicts(case), 'duplicate': project_review_case_duplicate(case), - 'profile_match': project_review_case_profile_match(case), + 'profile_match': profile_match, 'reservation': project_review_case_reservation(case), 'line_fulfillment': project_review_case_line_decisions(case), 'schema': {'schema_version_id': int(run.schema_version_id), 'fields': schema_fields}, diff --git a/backend/app/services/shipping_notice/order_review_resume_service.py b/backend/app/services/shipping_notice/order_review_resume_service.py index df9f9963..b2931922 100644 --- a/backend/app/services/shipping_notice/order_review_resume_service.py +++ b/backend/app/services/shipping_notice/order_review_resume_service.py @@ -2,12 +2,13 @@ services/shipping_notice/order_review_resume_service.py 用途:建单前统一恢复协调器——业务裁决后重校验、Gate 同步、资格重算、 - auto_gate 判断、幂等自动建单与后续推进入队。 + auto_gate 判断、STP 入队(幂等 queued Job)与后续 Worker 建单。 依赖:order_review_draft_service.validate_draft、candidate_qualification_service、 - order_review_confirmation_service、fulfillment_audit、process_gate_dependency。 + order_stp_auto_create_service.ensure_stp_auto_create_for_case、fulfillment_audit、 + process_gate_dependency。 逻辑:由客户确认、重复/冲突裁决、显式草稿校验等入口调用; Gate 通过 ≠ 资格 ready ≠ auto_gate 允许,三者分离; - 自动建单与人工确认共享 confirm_review_case;审计失败则事务回滚。 + 自动建单与人工确认共享 confirm_review_case(由 STP Worker 调用);审计失败则事务回滚。 """ from __future__ import annotations @@ -15,18 +16,13 @@ from __future__ import annotations from typing import Any from app import db -from app.core.errors import AppError, ConflictError, NotFoundError +from app.core.errors import ConflictError, NotFoundError from app.models import ShippingOrderCandidate, ShippingOrderReviewCase from app.services.shipping_notice.candidate_qualification_service import ( recalculate_candidate_qualification, resolve_review_case_customer_resolved, ) from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit -from app.services.shipping_notice.order_review_confirmation_service import ( - confirm_review_case, - finalize_sync_auto_progress_after_commit, - schedule_auto_progress_after_review_confirm, -) from app.services.shipping_notice.order_review_draft_service import ( soft_load_review_case_for_audit, validate_draft, @@ -281,87 +277,77 @@ def resume_after_review_change( 'invalidated_gates': invalidated, } - # [STEP 6] auto_gate:幂等自动建单并入队后续推进。 - draft_version = int(case.current_draft.draft_version) - idempotency_key = ( - f'review-resume:{case.case_no}:v{draft_version}:{trigger_code}' - )[:128] + # [STEP 6] auto_gate:入队 STP 幂等 Job(queued);Worker 再执行 confirm。 + from app.services.shipping_notice.order_stp_auto_create_service import ( + ensure_stp_auto_create_for_case, + ) + + if case.status in {'unreviewed', 'draft'} and snap['qualification_ready']: + case.status = 'ready' + db.session.flush() try: - created = confirm_review_case( - user_id=int(user_id), - case_no=str(case.case_no), - expected_draft_version=draft_version, - idempotency_key=idempotency_key, - warning_acknowledgements=[], + enqueue_result = ensure_stp_auto_create_for_case( + case=case, + commit=False, + refresh_validation=False, ) - task_no = created.get('task_no') - idempotent = bool(created.get('idempotent_replay')) + job_id = enqueue_result.get('job_id') record_fulfillment_audit( event_type='review_auto_create_started', aggregate_type='order_review_case', aggregate_id=str(case.case_no), - action='auto_create', + action='auto_create_enqueued', actor_type='system', actor_id=None, review_case_no=str(case.case_no), owner_user_id=int(user_id), document_id=case.document_id, - task_no=task_no, metadata={ 'trigger': trigger_code, - 'idempotency_key': idempotency_key, - 'idempotent_replay': idempotent, + 'enqueue_status': enqueue_result.get('status'), + 'job_id': job_id, + 'idempotency_key': enqueue_result.get('idempotency_key'), }, source='order_review_resume', strict=True, ) - progress = schedule_auto_progress_after_review_confirm( - task_no=task_no, - idempotent_replay=idempotent, - created_by_id=int(user_id), - commit=False, - ) db.session.commit() - progress = finalize_sync_auto_progress_after_commit(progress) case = _reload_case(user_id=user_id, case_no=case_no) - auto_started = bool( - isinstance(progress, dict) - and str(progress.get('status') or '') in {'queued', 'started', 'running', 'completed', 'ok'} - ) + outcome = 'auto_create_enqueued' + if enqueue_result.get('status') in {'already_queued', 'already_running'}: + outcome = str(enqueue_result.get('status')) + elif enqueue_result.get('status') == 'skipped_needs_review': + outcome = 'waiting_manual_confirm' return { **_empty_resume( gate_recalculated=True, qualification_status=snap['qualification_status'], - qualification_ready=True, + qualification_ready=snap['qualification_ready'], can_build=True, auto_gate_allowed=True, - task_created=True, - task_no=task_no, - auto_progress_started=auto_started or bool( - isinstance(progress, dict) and progress.get('status') - ), - idempotent_replay=idempotent, - outcome='auto_created' if not idempotent else 'idempotent_replay', - message=(progress or {}).get('message') if isinstance(progress, dict) else None, - failed_gates=[], + task_created=False, + outcome=outcome, + message=str(enqueue_result.get('status') or 'enqueued'), + failed_gates=snap['failed_gates'], ), 'case': serialize_review_case(case), 'invalidated_gates': invalidated, - 'auto_progress': progress, + 'stp_enqueue': enqueue_result, } - except AppError as exc: - # [STEP] 自动建单失败:先回滚半成品,再独立事务写失败审计,避免提交中间态。 - db.session.rollback() + except Exception as exc: # noqa: BLE001 record_fulfillment_audit( event_type='stp_auto_create_failed', aggregate_type='order_review_case', - aggregate_id=str(case_no), - action='auto_create_failed', + aggregate_id=str(case.case_no), + action='auto_create_enqueue_failed', actor_type='system', actor_id=None, result='rejected', - error_code=str(getattr(exc, 'code', '') or '') or None, - metadata={'trigger': trigger_code}, + error_code=str(getattr(exc, 'code', '') or type(exc).__name__), + metadata={ + 'trigger': trigger_code, + 'error': str(exc)[:300], + }, source='order_review_resume', strict=True, ) @@ -376,14 +362,13 @@ def resume_after_review_change( gate_recalculated=True, qualification_status=snap['qualification_status'], qualification_ready=snap['qualification_ready'], - can_build=snap['can_build'], - auto_gate_allowed=snap['auto_gate_allowed'], + can_build=True, + auto_gate_allowed=True, outcome='auto_create_failed', - message=str(getattr(exc, 'message', '') or exc), + message=str(exc)[:300], failed_gates=snap['failed_gates'], ), 'case': serialize_review_case(case), - 'error_code': getattr(exc, 'code', None), 'invalidated_gates': invalidated, } diff --git a/backend/app/services/shipping_notice/order_stp_auto_create_service.py b/backend/app/services/shipping_notice/order_stp_auto_create_service.py index 0cf3436c..46b64ffe 100644 --- a/backend/app/services/shipping_notice/order_stp_auto_create_service.py +++ b/backend/app/services/shipping_notice/order_stp_auto_create_service.py @@ -4,20 +4,24 @@ services/shipping_notice/order_stp_auto_create_service.py 用途:对未人工改脏且 Candidate Qualification 合格的复核 Case 执行幂等 STP 自动建单。 依赖:order_review_confirmation_service、draft 资格校验(含 can_auto_create)、 candidate_qualification_service、tool_common(紧急停止 / XFA shadow)、 - fulfillment_audit、xfa_validation(发布后视觉可发布性再验)。 -逻辑:由抽取单元提交 / Run 收尾在 ensure_run_review_cases 之后调用; - 先持久化资格快照;有人工字段覆盖、资格未 ready 或 can_auto_create=false 则跳过; + fulfillment_audit、xfa_validation(发布后视觉可发布性再验)、jobs.queue。 +逻辑:由抽取收尾 / resume / Case GET ensure 调用;资格达标后先写入 STP 幂等 Job(queued), + Worker 再执行 confirm;有人工字段覆盖、资格未 ready 或 can_auto_create=false 则跳过; XFA 与坐标路径共用 Schema/CQ 自动建单总开关;STP 入口再校验 shadow、盲测、白名单、 证据,以及已发布 Profile checksum + 视觉绑定可发布性;失败一律 needs_review。 """ from __future__ import annotations +import logging from typing import Any from app import db from app.core.errors import AppError +from app.jobs.queue import enqueue +from app.jobs.types import JobType from app.models import ( + Job, ShippingOrderCandidate, ShippingOrderProcessingRun, ShippingOrderReviewCase, @@ -37,6 +41,9 @@ from app.services.shipping_notice.tool_common import ( xfa_shadow_mode_enabled, ) +_LOGGER = logging.getLogger(__name__) +SHIPPING_STP_JOB_DOMAIN = 'shipping_notice' + def _persist_case_candidate_qualification( *, @@ -190,6 +197,72 @@ def _revalidate_published_xfa_profile(*, validation: dict[str, Any]) -> tuple[bo return True, None +def _normalize_stp_public_error_code( + raw: Any, + *, + default: str = 'SHIPPING.STP_ENQUEUE_FAILED', +) -> str: + """ + 将 ensure/retry 内部错误码规范为对外 SHIPPING.STP_*。 + + 核心逻辑:已是 SHIPPING.STP_* 原样返回;STP_ 前缀补全;其余内部/XFA 原因一律 + 收敛为 SHIPPING.STP_NOT_ELIGIBLE(细粒度保留在 details.blocking_reason_codes)。 + + Args: + raw: ensure 返回的 error_code 或内部 reason。 + default: 无法归类时的顶层码。 + + Returns: + 对外错误码。 + """ + text = str(raw or '').strip() + if text.startswith('SHIPPING.STP_'): + return text + if text == 'STP_NOT_ELIGIBLE' or text.endswith('_NOT_ELIGIBLE'): + return 'SHIPPING.STP_NOT_ELIGIBLE' + if text.startswith('STP_'): + return f'SHIPPING.{text}' + if text in { + 'skipped_needs_review', + 'not_eligible', + 'no_draft', + 'run_missing', + 'already_confirmed_or_terminal', + }: + return 'SHIPPING.STP_NOT_ELIGIBLE' + if text: + # XFA / 资格细粒度原因不得作为顶层用户错误码。 + return 'SHIPPING.STP_NOT_ELIGIBLE' + return default + + +def _public_stp_error_payload(result: dict[str, Any]) -> tuple[str, dict[str, Any]]: + """ + 从 ensure 结果组装对外 ValidationError 的 code 与 details。 + + Returns: + (SHIPPING.STP_* code, details) + """ + blocking = list(result.get('blocking_reason_codes') or []) + raw = result.get('error_code') + if raw and not str(raw).startswith('SHIPPING.STP_') and str(raw) not in { + 'STP_NOT_ELIGIBLE', + } and not str(raw).startswith('STP_'): + # 内部 reason 下沉到 details。 + if str(raw) not in blocking: + blocking.append(str(raw)) + code = _normalize_stp_public_error_code(raw, default='SHIPPING.STP_ENQUEUE_FAILED') + if str(result.get('status') or '') in { + 'skipped_needs_review', 'not_eligible', 'no_draft', 'run_missing', + }: + code = 'SHIPPING.STP_NOT_ELIGIBLE' + return code, { + 'enqueue_status': result.get('status'), + 'failed_gates': list(result.get('failed_gates') or []), + 'blocking_reason_codes': blocking, + } + + def _xfa_stp_precheck(*, validation: dict[str, Any]) -> tuple[bool, str | None]: """ XFA 路径建单前再次执行试点硬门禁(防御 CQ 快照与配置漂移)。 @@ -309,13 +382,510 @@ def _traceability_metadata( } +def build_stp_idempotency_key( + *, + run_no: str, + document_id: int, + draft_version: int, +) -> str: + """ + 构造 STP 入队幂等键(confirmed 前按 draft_version)。 + + Args: + run_no: 抽取 Run 编号。 + document_id: 文档 ID。 + draft_version: 当前草稿版本。 + + Returns: + 形如 ``stp-auto:{run_no}:doc-{document_id}:v{draft_version}`` 的键。 + """ + return f'stp-auto:{str(run_no)}:doc-{int(document_id)}:v{int(draft_version)}' + + +def find_active_stp_job(*, business_ref: str) -> Job | None: + """ + 按幂等键查找当前有效 STP Job(仅 queued/running)。 + + Args: + business_ref: STP 幂等键。 + + Returns: + 当前有效 Job;无则 None(failed/dead 不算有效,可另建重试 Job)。 + """ + key = str(business_ref or '').strip() + if not key: + return None + return ( + Job.query + .filter( + Job.domain == SHIPPING_STP_JOB_DOMAIN, + Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, + Job.business_ref == key, + Job.status.in_(('queued', 'running')), + ) + .order_by(Job.id.desc()) + .first() + ) + + +def find_latest_stp_job(*, business_ref: str) -> Job | None: + """ + 按幂等键查找最近一条 STP Job(含 failed,供 retry_of 关联)。 + + Args: + business_ref: STP 幂等键。 + + Returns: + 最近 Job 或 None。 + """ + key = str(business_ref or '').strip() + if not key: + return None + return ( + Job.query + .filter( + Job.domain == SHIPPING_STP_JOB_DOMAIN, + Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value, + Job.business_ref == key, + ) + .order_by(Job.id.desc()) + .first() + ) + + +def ensure_stp_auto_create_for_case( + *, + case: ShippingOrderReviewCase, + run: ShippingOrderProcessingRun | None = None, + commit: bool = False, + refresh_validation: bool = False, + force_retry: bool = False, +) -> dict[str, Any]: + """ + 资格达标时确保写入 STP 幂等记录与 queued Job(幂等复用)。 + + 核心逻辑:已 confirmed/有 Task 跳过;可选刷新 validation;XFA 硬门禁与 + 人工改脏阻断;合格则 enqueue(shipping_stp_auto_create),business_ref=幂等键。 + 若历史 Job 为 failed/dead,可新建重试 Job 并写入 retry_of_job_id(保留旧审计)。 + + Args: + case: 复核 Case。 + run: 可选 Run;缺省从 case.run / case.run_id 加载。 + commit: True 时本函数提交事务。 + refresh_validation: True 时重跑 _validation 并写回 Draft。 + force_retry: True 时对 failed/dead 强制新建重试 Job(显式 retry API)。 + + Returns: + 含 status / job_id / idempotency_key / can_auto_create 的摘要。 + """ + if case.confirmed_task_id or case.status in { + 'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending', + }: + return { + 'case_no': case.case_no, + 'status': 'already_confirmed_or_terminal', + 'job_id': None, + 'can_auto_create': False, + } + if case.current_draft is None: + return { + 'case_no': case.case_no, + 'status': 'no_draft', + 'job_id': None, + 'can_auto_create': False, + } + + resolved_run = run + if resolved_run is None: + resolved_run = case.run + if resolved_run is None and case.run_id: + resolved_run = db.session.get(ShippingOrderProcessingRun, int(case.run_id)) + if resolved_run is None: + return { + 'case_no': case.case_no, + 'status': 'run_missing', + 'job_id': None, + 'can_auto_create': False, + } + + candidate = _persist_case_candidate_qualification(case=case, run=resolved_run) + if refresh_validation: + validation = _validation(case) + case.current_draft.validation_result_json = validation + case.current_draft.issue_summary_json = list(validation.get('issues') or []) + else: + validation = ( + dict(case.current_draft.validation_result_json) + if isinstance(case.current_draft.validation_result_json, dict) + else _validation(case) + ) + + is_xfa = _is_xfa_case(candidate=candidate, validation=validation) + if is_xfa: + allowed, block_reason = _xfa_stp_precheck(validation=validation) + if not allowed: + if case.status in {'unreviewed', 'draft', 'ready'}: + case.status = 'draft' + record_fulfillment_audit( + event_type='stp_auto_create_skipped', + aggregate_type='order_review_case', + aggregate_id=str(case.case_no), + action='stp_auto_create_skipped', + actor_type='system', + actor_id=None, + result='ignored', + metadata={ + 'run_no': str(resolved_run.run_no), + 'reason_code': block_reason, + 'traceability': _traceability_metadata( + run=resolved_run, case=case, candidate=candidate, validation=validation, + ), + }, + source='stp_auto_create', + strict=True, + ) + db.session.flush() + if commit: + db.session.commit() + return { + 'case_no': case.case_no, + 'status': 'skipped_needs_review', + 'job_id': None, + 'can_auto_create': False, + 'blocking_reason_codes': [block_reason] if block_reason else [], + 'error_code': 'SHIPPING.STP_NOT_ELIGIBLE', + } + + if not ( + validation.get('status') == 'ready' + and bool(validation.get('can_auto_create')) + and not _draft_has_manual_edits(case) + ): + if case.status in {'unreviewed', 'draft', 'ready'} and not bool(validation.get('can_auto_create')): + case.status = 'draft' if not bool(validation.get('can_build')) else case.status + db.session.flush() + if commit: + db.session.commit() + return { + 'case_no': case.case_no, + 'status': 'skipped_needs_review', + 'job_id': None, + 'can_build': bool(validation.get('can_build')), + 'can_auto_create': bool(validation.get('can_auto_create')), + 'failed_gates': list(validation.get('failed_gates') or []), + 'error_code': 'SHIPPING.STP_NOT_ELIGIBLE', + } + + if case.status in {'unreviewed', 'draft', 'ready'}: + case.status = 'ready' + draft_version = int(case.current_draft.draft_version) + idempotency_key = build_stp_idempotency_key( + run_no=str(resolved_run.run_no), + document_id=int(case.document_id), + draft_version=draft_version, + ) + existing = find_active_stp_job(business_ref=idempotency_key) + if existing is not None and str(existing.status or '') in {'queued', 'running'}: + db.session.flush() + if commit: + db.session.commit() + return { + 'case_no': case.case_no, + 'status': 'reused' if force_retry else ( + 'already_queued' if existing.status == 'queued' else 'already_running' + ), + 'job_id': int(existing.id), + 'idempotency_key': idempotency_key, + 'job_status': str(existing.status), + 'can_auto_create': True, + 'retry_of_job_id': int(existing.retry_of_job_id) if existing.retry_of_job_id else None, + } + + # [STEP] failed/dead 历史 Job 保留审计;新建重试 Job 并挂 retry_of_job_id。 + latest = find_latest_stp_job(business_ref=idempotency_key) + retry_of_job_id = None + if latest is not None and str(latest.status or '') in {'failed', 'dead', 'cancelled'}: + retry_of_job_id = int(latest.id) + elif force_retry and latest is not None: + retry_of_job_id = int(latest.id) + + owner_id = int(case.owner_user_id) if case.owner_user_id is not None else None + payload = { + 'case_no': str(case.case_no), + 'run_no': str(resolved_run.run_no), + 'document_id': int(case.document_id), + 'draft_version': draft_version, + 'idempotency_key': idempotency_key, + 'owner_user_id': owner_id, + } + if retry_of_job_id is not None: + payload['retry_of_job_id'] = retry_of_job_id + job_id = enqueue( + JobType.SHIPPING_STP_AUTO_CREATE, + payload, + domain=SHIPPING_STP_JOB_DOMAIN, + business_ref=idempotency_key, + created_by_id=owner_id, + message='等待 STP 自动建单' if retry_of_job_id is None else '重试 STP 自动建单', + max_attempts=3, + dedupe_statuses=('queued', 'running'), + dedupe_active=True, + commit=False, + ) + job = db.session.get(Job, int(job_id)) + if job is not None and retry_of_job_id is not None: + job.retry_of_job_id = int(retry_of_job_id) + record_fulfillment_audit( + event_type='stp_auto_create_enqueued', + aggregate_type='order_review_case', + aggregate_id=str(case.case_no), + action='stp_auto_create_enqueued' if retry_of_job_id is None else 'stp_auto_create_retried', + actor_type='system', + actor_id=None, + review_case_no=str(case.case_no), + owner_user_id=owner_id, + document_id=case.document_id, + metadata={ + 'run_no': str(resolved_run.run_no), + 'job_id': int(job_id), + 'idempotency_key': idempotency_key, + 'retry_of_job_id': retry_of_job_id, + 'force_retry': bool(force_retry), + 'traceability': _traceability_metadata( + run=resolved_run, case=case, candidate=candidate, validation=validation, + ), + }, + source='stp_auto_create', + strict=True, + ) + db.session.flush() + if commit: + db.session.commit() + return { + 'case_no': case.case_no, + 'status': 'queued', + 'job_id': int(job_id), + 'idempotency_key': idempotency_key, + 'job_status': 'queued', + 'can_auto_create': True, + 'retry_of_job_id': retry_of_job_id, + } + + +def retry_stp_auto_create_for_case( + *, + user_id: int, + case_no: str, +) -> dict[str, Any]: + """ + 显式重试 STP 自动建单入队(失败 / manual_fallback)。 + + 核心逻辑:校验可见性与未 confirmed;force_retry 入队;成功返回 queued/reused+job_id; + 失败抛业务错误(含 error_code),禁止伪装成功。 + + Args: + user_id: 操作人。 + case_no: 复核 Case 编号。 + + Returns: + ``{status, job_id, idempotency_key, case}``。 + + Raises: + AppError: 不可重试或入队失败。 + """ + from app.core.errors import ConflictError, ValidationError + from app.services.shipping_notice.order_review_projection import serialize_review_case + from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user + + case = get_review_case_visible_to_user(case_no, int(user_id), is_admin=False) + if case.confirmed_task_id or str(case.status or '') == 'confirmed': + raise ConflictError( + 'Case already confirmed; use post-confirm auto progress retry', + code='SHIPPING.STP_RETRY_ALREADY_CONFIRMED', + ) + result = ensure_stp_auto_create_for_case( + case=case, + commit=True, + refresh_validation=True, + force_retry=True, + ) + status = str(result.get('status') or '') + if status in {'queued', 'reused', 'already_queued', 'already_running', 'enqueued'}: + case = get_review_case_visible_to_user(case_no, int(user_id), is_admin=False) + normalized = 'reused' if status in {'reused', 'already_queued', 'already_running'} else 'queued' + business_ref = result.get('idempotency_key') + return { + 'status': normalized, + 'job_id': result.get('job_id'), + 'job_status': result.get('job_status') or ('queued' if normalized == 'queued' else status), + 'business_ref': business_ref, + 'idempotency_key': business_ref, + 'retry_of_job_id': result.get('retry_of_job_id'), + 'case': serialize_review_case(case), + } + code, details = _public_stp_error_payload(result) + raise ValidationError( + 'STP auto-create enqueue failed', + code=code, + details=details, + ) + + +def execute_stp_auto_create_job(*, payload: dict[str, Any], job_id: int) -> dict[str, Any]: + """ + Worker 执行 STP 自动建单:confirm_review_case + 确认后推进。 + + 核心逻辑:按 payload.case_no 加载 Case;已 confirmed 则幂等成功;否则用 + 同一 STP 幂等键调用 confirm;成功后 schedule_auto_progress。 + + Args: + payload: Job payload(case_no / draft_version / idempotency_key)。 + job_id: 当前 Job 主键。 + + Returns: + ``{ok, message, ...}``;业务拒绝时 ok=False 且含 error_code。 + """ + case_no = str(payload.get('case_no') or '').strip() + if not case_no: + return {'ok': False, 'error_code': 'SHIPPING.STP_CASE_NO_REQUIRED', 'message': 'case_no required'} + case = ( + ShippingOrderReviewCase.query + .filter_by(case_no=case_no) + .order_by(ShippingOrderReviewCase.id.desc()) + .first() + ) + if case is None: + return {'ok': False, 'error_code': 'SHIPPING.REVIEW_CASE_NOT_FOUND', 'message': 'Case not found'} + if case.confirmed_task_id or str(case.status or '') == 'confirmed': + return { + 'ok': True, + 'message': 'already confirmed', + 'idempotent_replay': True, + 'task_no': str(getattr(case, 'confirmed_task_no', None) or '') or None, + } + if case.current_draft is None: + return {'ok': False, 'error_code': 'SHIPPING.REVIEW_DRAFT_MISSING', 'message': 'Draft missing'} + + draft_version = int(payload.get('draft_version') or case.current_draft.draft_version) + if int(case.current_draft.draft_version) != draft_version: + return { + 'ok': False, + 'error_code': 'SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT', + 'message': 'Draft version changed; re-enqueue required', + } + + run = case.run or ( + db.session.get(ShippingOrderProcessingRun, int(case.run_id)) if case.run_id else None + ) + if run is None: + return {'ok': False, 'error_code': 'SHIPPING.REVIEW_RUN_MISSING', 'message': 'Run missing'} + + # [STEP] 执行前再验资格,防止配置漂移后仍建单。 + ensure_result = ensure_stp_auto_create_for_case( + case=case, + run=run, + commit=False, + refresh_validation=True, + ) + if ensure_result.get('status') in { + 'skipped_needs_review', 'no_draft', 'run_missing', 'already_confirmed_or_terminal', + }: + return { + 'ok': False, + 'error_code': 'SHIPPING.STP_NOT_ELIGIBLE', + 'message': str(ensure_result.get('status') or 'not eligible'), + 'details': ensure_result, + } + + idempotency_key = str( + payload.get('idempotency_key') + or ensure_result.get('idempotency_key') + or build_stp_idempotency_key( + run_no=str(run.run_no), + document_id=int(case.document_id), + draft_version=draft_version, + ) + ) + owner_id = int(case.owner_user_id) + try: + created = confirm_review_case( + user_id=owner_id, + case_no=str(case.case_no), + expected_draft_version=draft_version, + idempotency_key=idempotency_key, + warning_acknowledgements=[], + ) + record_fulfillment_audit( + event_type='stp_auto_create', + aggregate_type='order_review_case', + aggregate_id=str(case.case_no), + action='stp_auto_create', + actor_type='system', + actor_id=None, + review_case_no=str(case.case_no), + owner_user_id=owner_id, + document_id=case.document_id, + task_no=created.get('task_no'), + metadata={ + 'idempotent_replay': bool(created.get('idempotent_replay')), + 'run_no': str(run.run_no), + 'job_id': int(job_id), + 'idempotency_key': idempotency_key, + }, + source='stp_auto_create', + strict=True, + ) + progress = schedule_auto_progress_after_review_confirm( + task_no=created.get('task_no'), + idempotent_replay=bool(created.get('idempotent_replay')), + created_by_id=int(owner_id), + commit=False, + ) + db.session.commit() + progress = finalize_sync_auto_progress_after_commit(progress) + return { + 'ok': True, + 'message': 'STP 自动建单完成', + 'task_no': created.get('task_no'), + 'idempotent_replay': bool(created.get('idempotent_replay')), + 'auto_progress_status': (progress or {}).get('status') if isinstance(progress, dict) else None, + } + except AppError as exc: + record_fulfillment_audit( + event_type='stp_auto_create_failed', + aggregate_type='order_review_case', + aggregate_id=str(case.case_no), + action='stp_auto_create_failed', + actor_type='system', + actor_id=None, + result='rejected', + error_code=str(getattr(exc, 'code', '') or '') or None, + metadata={ + 'run_no': str(run.run_no), + 'job_id': int(job_id), + 'idempotency_key': idempotency_key, + }, + source='stp_auto_create', + strict=True, + ) + try: + db.session.commit() + except Exception: + db.session.rollback() + raise + return { + 'ok': False, + 'error_code': str(getattr(exc, 'code', None) or 'SHIPPING.STP_AUTO_CREATE_FAILED'), + 'message': str(getattr(exc, 'message', None) or exc)[:500], + } + + def maybe_stp_auto_create_for_run(*, run: ShippingOrderProcessingRun) -> list[dict[str, Any]]: """ - 尝试对 Run 下未确认 Case 自动建单。 + 尝试对 Run 下未确认 Case 入队 STP 自动建单。 - 核心逻辑:资格 ready 且无人工改脏 → confirm_review_case;成功后 commit 并 - 触发与人工确认相同的 auto_progress。XFA 与坐标共用统一 CQ(紧急停止已纳入资格)。 - 失败不阻断同 Run 其他 Case;幂等键保证重试不重复 Task。 + 核心逻辑:资格 ready 且无人工改脏 → ensure 写入幂等 Job(queued); + Worker 再执行 confirm。失败不阻断同 Run 其他 Case;幂等键保证只保留一条有效入队。 Args: run: 已 ensure_run_review_cases 的抽取 Run。 @@ -338,153 +908,24 @@ def maybe_stp_auto_create_for_run(*, run: ShippingOrderProcessingRun) -> list[di case = db.session.get(ShippingOrderReviewCase, case_id) if case is None: continue - if case.confirmed_task_id or case.status in { - 'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending', - }: - continue - if case.current_draft is None: - continue - owner_id = int(case.owner_user_id) - draft_version = int(case.current_draft.draft_version) - # [STEP] 持久化 Candidate Qualification 不可变快照(若 Case 已关联候选)。 - candidate = _persist_case_candidate_qualification(case=case, run=run) - validation = _validation(case) - case.current_draft.validation_result_json = validation - case.current_draft.issue_summary_json = list(validation.get('issues') or []) - - is_xfa = _is_xfa_case(candidate=candidate, validation=validation) - if is_xfa: - allowed, block_reason = _xfa_stp_precheck(validation=validation) - if not allowed: - if case.status in {'unreviewed', 'draft', 'ready'}: - case.status = 'draft' - results.append({ - 'case_no': case.case_no, - 'status': 'skipped_needs_review', - 'can_build': bool(validation.get('can_build')), - 'can_auto_create': False, - 'failed_gates': list(validation.get('failed_gates') or []), - 'blocking_reason_codes': [block_reason] if block_reason else [], - 'shadow_would_auto_create': bool(validation.get('shadow_would_auto_create')), - 'traceability': _traceability_metadata( - run=run, case=case, candidate=candidate, validation=validation, - ), - }) - record_fulfillment_audit( - event_type='stp_auto_create_skipped', - aggregate_type='order_review_case', - aggregate_id=str(case.case_no), - action='stp_auto_create_skipped', - actor_type='system', - actor_id=None, - result='ignored', - metadata={ - 'run_no': str(run.run_no), - 'reason_code': block_reason, - 'traceability': _traceability_metadata( - run=run, case=case, candidate=candidate, validation=validation, - ), - }, - source='stp_auto_create', - strict=True, - ) - db.session.flush() - continue - - # [STEP] Candidate Qualification + 无人工改脏才自动建单;否则仅 Review Case。 - if ( - validation.get('status') == 'ready' - and bool(validation.get('can_auto_create')) - and not _draft_has_manual_edits(case) - ): - case.status = 'ready' - db.session.flush() - else: - if case.status in {'unreviewed', 'draft', 'ready'}: - case.status = 'draft' - results.append({ - 'case_no': case.case_no, - 'status': 'skipped_needs_review', - 'can_build': bool(validation.get('can_build')), - 'can_auto_create': bool(validation.get('can_auto_create')), - 'failed_gates': list(validation.get('failed_gates') or []), - }) - db.session.flush() - continue - - idempotency_key = f'stp-auto:{run.run_no}:doc-{int(case.document_id)}:v{draft_version}' try: - created = confirm_review_case( - user_id=owner_id, - case_no=str(case.case_no), - expected_draft_version=draft_version, - idempotency_key=idempotency_key, - warning_acknowledgements=[], + results.append( + ensure_stp_auto_create_for_case( + case=case, + run=run, + commit=True, + refresh_validation=True, + ) ) - record_fulfillment_audit( - event_type='stp_auto_create', - aggregate_type='order_review_case', - aggregate_id=str(case.case_no), - action='stp_auto_create', - actor_type='system', - actor_id=None, - review_case_no=str(case.case_no), - owner_user_id=owner_id, - document_id=case.document_id, - task_no=created.get('task_no'), - metadata={ - 'idempotent_replay': bool(created.get('idempotent_replay')), - 'run_no': str(run.run_no), - 'traceability': _traceability_metadata( - run=run, case=case, candidate=candidate, validation=validation, - ), - }, - source='stp_auto_create', - strict=True, - ) - progress = schedule_auto_progress_after_review_confirm( - task_no=created.get('task_no'), - idempotent_replay=bool(created.get('idempotent_replay')), - created_by_id=int(owner_id) if owner_id is not None else None, - commit=False, - ) - db.session.commit() - progress = finalize_sync_auto_progress_after_commit(progress) - results.append({ - 'case_no': case.case_no, - 'status': 'auto_created' if not created.get('idempotent_replay') else 'idempotent_replay', - 'task_no': created.get('task_no'), - 'auto_progress_status': (progress or {}).get('status') if isinstance(progress, dict) else None, - }) - except AppError as exc: - # confirm 拒绝路径可能已独立 commit;此处仅记录摘要,审计失败必须抛出。 - results.append({ - 'case_no': case.case_no, - 'status': 'auto_create_failed', - 'error_code': getattr(exc, 'code', None), - }) - record_fulfillment_audit( - event_type='stp_auto_create_failed', - aggregate_type='order_review_case', - aggregate_id=str(case.case_no), - action='stp_auto_create_failed', - actor_type='system', - actor_id=None, - result='rejected', - error_code=str(getattr(exc, 'code', '') or '') or None, - metadata={ - 'run_no': str(run.run_no), - 'traceability': _traceability_metadata( - run=run, case=case, candidate=candidate, validation=validation, - ), - }, - source='stp_auto_create', - strict=True, - ) - # 失败节点审计必须持久化;commit 失败回滚后上抛,禁止静默丢审计后继续下一单。 + except Exception as exc: # noqa: BLE001 + _LOGGER.exception('STP enqueue failed for case_id=%s', case_id) try: - db.session.commit() - except Exception: db.session.rollback() - raise + except Exception: # noqa: BLE001 + pass + results.append({ + 'case_no': getattr(case, 'case_no', None), + 'status': 'enqueue_failed', + 'error': str(exc)[:300], + }) return results diff --git a/backend/app/services/shipping_notice/process_gate_projection.py b/backend/app/services/shipping_notice/process_gate_projection.py index 02210fe7..4c686ee5 100644 --- a/backend/app/services/shipping_notice/process_gate_projection.py +++ b/backend/app/services/shipping_notice/process_gate_projection.py @@ -281,6 +281,14 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, 'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', }: blocking = current + # [STEP] 已通过的客户确认不得再成为用户当前阻断;pending/queued 技术 Gate 也不冒充人工优先处理。 + if blocking: + gate_code = str(blocking.get('gate_code') or '').strip().lower() + gate_status = str(blocking.get('status') or '').strip().lower() + if gate_code in {'customer_resolution', 'customer_confirmed'} and gate_status == 'passed': + blocking = None + elif gate_status in {'pending', 'queued', 'running', 'passed', 'skipped'}: + blocking = None diagnostic_hint = None for gate in full.get('gates') or []: for finding in gate.get('findings') or []: @@ -301,6 +309,9 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, if next_action and not is_business_user_action(str(next_action)): next_action = None technical_auto_only = bool(blocking) + # 无当前阻断时禁止残留 confirm_customer,避免「客户已确认」仍显示为优先处理。 + if not blocking and str(next_action or '').strip() == 'confirm_customer': + next_action = None # [STEP] 统一可解释性投影:文案/责任方/下一步与 error_explainability_contract 同源; # request_id 仅真实请求号;execution_no 放入 details 供 Worker 路径关联。 diff --git a/backend/app/services/shipping_notice/processing_ownership.py b/backend/app/services/shipping_notice/processing_ownership.py new file mode 100644 index 00000000..afc1af85 --- /dev/null +++ b/backend/app/services/shipping_notice/processing_ownership.py @@ -0,0 +1,199 @@ +""" +services/shipping_notice/processing_ownership.py + +用途:订单处理投影不一致审计与正式 Notice 任务归属校验(fail-closed)。 +依赖:audit_service.append_shipping_audit_event、processing_projection_invariants 错误码、 + models ShippingOrderTask / ShippingOrderReviewCase、AppError ConflictError、logging。 +逻辑:投影组装后写 inconsistent 审计;履约写 API / service 在执行前校验 Notice↔OT/Case/Run。 +""" + +from __future__ import annotations + +import logging +from typing import Any + +from app.core.errors import ConflictError +from app.extensions import db +from app.models.shipping import ShippingNotice +from app.models.shipping_order_review import ShippingOrderReviewCase +from app.models.shipping_order_task import ShippingOrderTask +from app.services.shipping_notice.audit_service import append_shipping_audit_event +from app.services.shipping_notice.processing_projection_invariants import ( + PROJECTION_INCONSISTENT_ERROR_CODE, + TASK_OWNERSHIP_MISMATCH_ERROR_CODE, +) + +_LOGGER = logging.getLogger(__name__) + + +def record_projection_inconsistency_audit(payload: dict[str, Any]) -> None: + """ + 当投影带有 inconsistency 码时写入 progress_audit 结构化事件。 + + 核心逻辑:不阻断读路径;失败仅打 logger,避免拖垮投影 GET。 + + Args: + payload: reconcile 后的 ShippingProcessingProjection dict。 + """ + code = str(payload.get('projection_inconsistency_code') or '').strip() + if code != PROJECTION_INCONSISTENT_ERROR_CODE: + return + work_item_no = str(payload.get('work_item_no') or '').strip() or None + notice_no = str(payload.get('shipping_notice_no') or '').strip() or None + stage = str(payload.get('stage') or '').strip() or None + try: + append_shipping_audit_event( + event_type='shipping_processing_projection_inconsistent', + aggregate_type='order_task', + aggregate_id=work_item_no or notice_no or 'unknown', + task_no=notice_no, + run_no=str(payload.get('run_no') or '').strip() or None, + review_case_no=str(payload.get('case_no') or '').strip() or None, + conversation_id=str(payload.get('conversation_id') or '').strip() or None, + actor_type='system', + result='blocked', + error_code=PROJECTION_INCONSISTENT_ERROR_CODE, + reason_code=PROJECTION_INCONSISTENT_ERROR_CODE, + reason='shipping_notice_no present with pre-create stage', + metadata={ + 'work_item_no': work_item_no, + 'shipping_notice_no': notice_no, + 'stage': stage, + 'status': str(payload.get('status') or '').strip() or None, + }, + persist_snapshots=False, + ) + db.session.flush() + except Exception: # noqa: BLE001 — 读路径不得因审计失败 500 + _LOGGER.warning( + 'failed to persist projection inconsistency audit code=%s work_item_no=%s', + PROJECTION_INCONSISTENT_ERROR_CODE, + work_item_no, + exc_info=True, + ) + + +def assert_notice_task_ownership( + task: ShippingNotice, + *, + expected_order_task_no: str | None = None, + expected_review_case_no: str | None = None, + expected_run_no: str | None = None, + actor_id: str | int | None = None, +) -> None: + """ + 校验正式 Notice 与当前 Case/Run/OT 归属一致;不一致则抛 AppError。 + + 核心逻辑:调用方传入期望 OT/Case/Run 时,与 Notice.order_task_id 链路比对; + 任一不匹配 → ConflictError(SHIPPING_PROCESSING_TASK_OWNERSHIP_MISMATCH) + 审计。 + + Args: + task: 已加载的 ShippingNotice。 + expected_order_task_no: 工作台权威 OT 编号。 + expected_review_case_no: 当前 Review Case 编号。 + expected_run_no: 当前 Extraction Run 编号。 + actor_id: 操作者 id(审计)。 + + Raises: + ConflictError: 归属不匹配。 + """ + expect_ot = str(expected_order_task_no or '').strip() or None + expect_case = str(expected_review_case_no or '').strip() or None + expect_run = str(expected_run_no or '').strip() or None + if not expect_ot and not expect_case and not expect_run: + return + + order_task: ShippingOrderTask | None = None + ot_id = getattr(task, 'order_task_id', None) + if ot_id is not None: + order_task = db.session.get(ShippingOrderTask, int(ot_id)) + + actual_ot = str(getattr(order_task, 'task_no', None) or '').strip() or None + actual_run = None + if order_task is not None and getattr(order_task, 'extraction_run_id', None): + from app.models.shipping_order_extraction_run import ShippingOrderExtractionRun + run = db.session.get(ShippingOrderExtractionRun, int(order_task.extraction_run_id)) + actual_run = str(getattr(run, 'run_no', None) or '').strip() or None + + actual_case = None + if expect_case: + case = ShippingOrderReviewCase.query.filter_by(case_no=expect_case).first() + if case is None: + actual_case = None + else: + # Case 须指向同一 Notice 或同一 candidate/OT。 + confirmed_id = getattr(case, 'confirmed_task_id', None) + if confirmed_id is not None and int(confirmed_id) == int(task.id): + actual_case = expect_case + elif order_task is not None and getattr(case, 'candidate_id', None) and getattr(order_task, 'candidate_id', None): + if int(case.candidate_id) == int(order_task.candidate_id): + actual_case = expect_case + else: + actual_case = None + + mismatch = False + if expect_ot and actual_ot != expect_ot: + mismatch = True + if expect_run and actual_run and actual_run != expect_run: + mismatch = True + if expect_run and not actual_run: + mismatch = True + if expect_case and actual_case != expect_case: + mismatch = True + + if not mismatch: + return + + _LOGGER.warning( + 'shipping_processing_task_ownership_mismatch code=%s task_no=%s ' + 'expected_ot=%s actual_ot=%s expected_case=%s expected_run=%s actual_run=%s', + TASK_OWNERSHIP_MISMATCH_ERROR_CODE, + getattr(task, 'task_no', None), + expect_ot, + actual_ot, + expect_case, + expect_run, + actual_run, + ) + try: + append_shipping_audit_event( + event_type='shipping_processing_task_ownership_mismatch', + aggregate_type='shipping_notice', + aggregate_id=str(getattr(task, 'task_no', None) or task.id), + task_no=str(getattr(task, 'task_no', None) or '').strip() or None, + run_no=expect_run or actual_run, + review_case_no=expect_case, + actor_type='user' if actor_id is not None else 'system', + actor_id=actor_id, + result='blocked', + error_code=TASK_OWNERSHIP_MISMATCH_ERROR_CODE, + reason_code=TASK_OWNERSHIP_MISMATCH_ERROR_CODE, + reason='formal notice does not belong to current case/run/order task', + metadata={ + 'expected_order_task_no': expect_ot, + 'actual_order_task_no': actual_ot, + 'expected_review_case_no': expect_case, + 'expected_run_no': expect_run, + 'actual_run_no': actual_run, + }, + persist_snapshots=False, + ) + db.session.flush() + except Exception: # noqa: BLE001 + _LOGGER.warning( + 'failed to persist ownership mismatch audit task_no=%s', + getattr(task, 'task_no', None), + exc_info=True, + ) + + raise ConflictError( + message='Formal task does not match the current order processing context', + code=TASK_OWNERSHIP_MISMATCH_ERROR_CODE, + details={ + 'expected_order_task_no': expect_ot, + 'actual_order_task_no': actual_ot, + 'expected_review_case_no': expect_case, + 'expected_run_no': expect_run, + 'actual_run_no': actual_run, + }, + ) diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index 28ef0a1c..047b0c27 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -3,15 +3,17 @@ services/shipping_notice/processing_projection_invariants.py 用途:统一 ShippingProcessingProjection 输出前的 status/stage/gate/action 不变量与 15 阶节点事实,避免四页面各自推导互相矛盾的进度。 -依赖:progress_audit_contract(15 阶 / 节点态 / 动作意图词典)。 +依赖:progress_audit_contract(15 阶 / 节点态 / 动作意图词典)、logging。 逻辑:由 shipping_processing_projection 与 order_task_stage_machine 共用;不读写数据库; Notice→(status,stage) 领域映射供写/读两侧;Extraction Run 完成 ≠ 全流程 completed; Gate 要求复核时强制 waiting_review;download_excel 依赖 excel_ready; - stage_nodes 可表达 invalidated_from_stage 失效。 + stage_nodes 可表达 invalidated_from_stage 失效; + Notice 号与建单前 stage 不一致时 fail-closed 清空履约动作并打结构化告警。 """ from __future__ import annotations +import logging from typing import Any from app.services.shipping_notice.progress_audit_contract import ( @@ -23,11 +25,21 @@ from app.services.shipping_notice.progress_audit_contract import ( shipping_processing_stage_index, ) +_LOGGER = logging.getLogger(__name__) + +# 投影不一致 / 任务归属错误码(与前端 BusinessError / AppError.code 对齐)。 +PROJECTION_INCONSISTENT_ERROR_CODE = 'SHIPPING_PROCESSING_PROJECTION_INCONSISTENT' +TASK_OWNERSHIP_MISMATCH_ERROR_CODE = 'SHIPPING_PROCESSING_TASK_OWNERSHIP_MISMATCH' + # 写操作动作:status=completed 时必须剔除。 _WRITE_ACTION_CODES = frozenset({ 'open_order_review', 'open_review', 'edit_formal_task', + 'confirm_customer', + 'resolve_field_conflicts', + 'adjudicate_duplicate', + 'open_profile_review', 'open_inventory_source_review', 'open_inventory_match_review', 'open_shortage_review', @@ -43,6 +55,25 @@ _WRITE_ACTION_CODES = frozenset({ 'open_fulfillment', }) +# 建单前禁止下发的履约写动作(匹配 / Excel / 上传等)。 +_POST_CREATE_ONLY_ACTION_CODES = frozenset({ + 'open_inventory_match_review', + 'open_shortage_review', + 'upload_inventory_file', + 'regenerate_excel', + 'download_excel', + 'open_manual_upload', +}) + +_POST_CREATE_STAGES = frozenset({ + 'order_creating', + 'inventory_fetching', + 'inventory_matching', + 'excel_generating', + 'freight_uploading', + 'completed', +}) + # 后端可能发出、需映射到契约意图的别名。 _ACTION_CODE_ALIASES: dict[str, str] = { 'open_review': 'open_order_review', @@ -60,7 +91,6 @@ _ACTION_CODE_ALIASES: dict[str, str] = { 'rematch': 'open_inventory_match_review', 'match_inventory': 'open_inventory_match_review', 'generate_excel': 'regenerate_excel', - 'confirm_customer': 'open_order_review', 'freeze_order': 'edit_formal_task', } @@ -239,6 +269,63 @@ def build_stage_nodes( return nodes +def _is_pre_create_stage(stage: str | None) -> bool: + """ + 判断 stage 是否仍在建单前域。 + + Args: + stage: 统一 stage。 + + Returns: + True 表示尚未进入 order_creating 及之后履约阶段。 + """ + code = str(stage or '').strip().lower() + return bool(code) and code not in _POST_CREATE_STAGES and code in SHIPPING_PROCESSING_STAGES + + +def detect_notice_pre_create_inconsistency( + *, + stage: str | None, + shipping_notice_no: str | None, +) -> bool: + """ + 检测「已有正式 Notice 号但 stage 仍在建单前」的投影不一致。 + + Args: + stage: 统一 stage。 + shipping_notice_no: Projection 上的正式任务号。 + + Returns: + True 表示不一致,须 fail-closed 清空履约动作。 + """ + notice = str(shipping_notice_no or '').strip() + return bool(notice) and _is_pre_create_stage(stage) + + +def _is_post_create(*, stage: str, shipping_notice_no: str | None) -> bool: + """ + 判断是否已进入正式履约域(允许下发匹配/Excel/上传等履约动作)。 + + 核心逻辑:Notice 号与建单前 stage 并存时 fail-closed 视为未建单后(禁止履约动作); + 否则有 Notice 或 stage 已过建单则视为 post_create。 + + Args: + stage: 统一 stage。 + shipping_notice_no: Projection 上的正式任务号。 + + Returns: + True 表示允许下发履约动作。 + """ + stage_norm = str(stage or '').strip().lower() + notice = str(shipping_notice_no or '').strip() + # [STEP] 不一致:有正式号但仍停在建单前 stage → 禁止履约动作。 + if detect_notice_pre_create_inconsistency(stage=stage_norm, shipping_notice_no=notice): + return False + if notice: + return True + return stage_norm in _POST_CREATE_STAGES + + def derive_available_actions( *, status: str, @@ -246,13 +333,15 @@ def derive_available_actions( gate: dict[str, Any] | None, legacy_actions: list[str] | None = None, excel_ready: bool = False, + shipping_notice_no: str | None = None, ) -> list[str]: """ 由 Gate / Artifact 等业务事实推导 available_actions,禁止仅凭 stage 猜测可下载。 核心逻辑:Gate next_action 优先;download_excel 仅当 excel_ready; regenerate_excel 仅当处于 excel_generating 且非 automating 且 Excel 未就绪; - open_manual_upload 仅当 Gate 或 legacy 明确给出;completed → view_result。 + open_manual_upload 仅当 Gate 或 legacy 明确给出;completed → view_result; + 建单前剔除匹配/Excel/上传等履约动作(fail-closed)。 Args: status: 统一 status。 @@ -260,12 +349,14 @@ def derive_available_actions( gate: current_gate 摘要。 legacy_actions: 可选旧会话卡动作,仅保留可映射项。 excel_ready: 是否存在 ready 的发货 Excel Artifact。 + shipping_notice_no: 正式 Notice 任务号;空表示建单前。 Returns: 契约动作码列表(去重、保序)。 """ status_norm = str(status or '').strip().lower() stage_norm = str(stage or '').strip().lower() + post_create = _is_post_create(stage=stage_norm, shipping_notice_no=shipping_notice_no) actions: list[str] = [] seen: set[str] = set() gate_action = _gate_next_action(gate) @@ -279,6 +370,9 @@ def derive_available_actions( # [BE-04] download_excel 必须有 ready Artifact,禁止仅因 stage 猜测。 if code == 'download_excel' and not excel_ready: return + # [R4] 建单前禁止履约写动作。 + if not post_create and code in _POST_CREATE_ONLY_ACTION_CODES: + return seen.add(code) actions.append(code) @@ -386,6 +480,21 @@ def reconcile_processing_projection_facts( payload['status'] = status payload['stage'] = stage payload['current_gate'] = gate + notice_no = str(payload.get('shipping_notice_no') or '').strip() or None + # [STEP] Notice 残留 + 建单前 stage:清空履约动作并打结构化告警(审计由投影组装层写入)。 + if detect_notice_pre_create_inconsistency(stage=stage, shipping_notice_no=notice_no): + _LOGGER.warning( + 'shipping_processing_projection_inconsistent code=%s work_item_no=%s ' + 'shipping_notice_no=%s stage=%s', + PROJECTION_INCONSISTENT_ERROR_CODE, + str(payload.get('work_item_no') or '').strip() or None, + notice_no, + stage, + ) + payload['projection_inconsistency_code'] = PROJECTION_INCONSISTENT_ERROR_CODE + else: + payload.pop('projection_inconsistency_code', None) + payload['available_actions'] = derive_available_actions( status=status, stage=stage, @@ -394,7 +503,14 @@ def reconcile_processing_projection_facts( payload.get('available_actions') or [] ), excel_ready=excel_ready, + shipping_notice_no=notice_no, ) + # 不一致时二次保险:即使 Gate 漏网也剔除履约动作。 + if payload.get('projection_inconsistency_code') == PROJECTION_INCONSISTENT_ERROR_CODE: + payload['available_actions'] = [ + code for code in payload['available_actions'] + if code not in _POST_CREATE_ONLY_ACTION_CODES + ] payload['stage_nodes'] = build_stage_nodes( stage=stage, status=status, diff --git a/backend/app/services/shipping_notice/progress_audit_contract.py b/backend/app/services/shipping_notice/progress_audit_contract.py index d0908adc..039426ab 100644 --- a/backend/app/services/shipping_notice/progress_audit_contract.py +++ b/backend/app/services/shipping_notice/progress_audit_contract.py @@ -5,6 +5,7 @@ services/shipping_notice/progress_audit_contract.py 依赖:无外部 IO;被 progress / audit / workflow / projection / OpenAPI 与测试引用。 逻辑:状态、用户可见阶段、健康提示、取消语义、Workflow Item 生命周期、模板评分/ 通用解析/LLM 建议/人工裁决事件码、XFA 解析/映射/提取/对账事件码、 + XFA 合成预览(xfa_preview_*)事件码、 全门禁(Process Gate)恢复审计事件码、 复核工作台布局相关写操作/敏感读取事件码、字段高亮坐标诊断事件码、 对话工作台 chat_* / Candidate 资格 / Workflow 节点事件码(双工作台阶段 5–6)、 @@ -96,6 +97,9 @@ ORDER_TASK_PROGRESS_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({ 'order_task_created', 'order_task_updated', 'order_task_progress_changed', + # 投影不一致 / 任务归属阻断(工作台 fail-closed)。 + 'shipping_processing_projection_inconsistent', + 'shipping_processing_task_ownership_mismatch', }) # 复核工作台布局重构(2026-08-01)业务写 / 敏感读稳定事件字典。 @@ -276,6 +280,10 @@ SHIPPING_PROCESSING_ACTION_INTENTS: Final[tuple[str, ...]] = ( 'none', 'open_order_review', 'edit_formal_task', + 'open_profile_review', + 'confirm_customer', + 'resolve_field_conflicts', + 'adjudicate_duplicate', 'open_inventory_source_review', 'open_inventory_match_review', 'open_shortage_review', @@ -653,6 +661,9 @@ XFA_PROGRESS_EVENT_CODES: Final[frozenset[str]] = frozenset({ 'xfa_document_kind_detected', 'xfa_packet_parsed', 'xfa_structure_analysis_ready', + 'xfa_structure_analysis_reused', + 'xfa_structure_analysis_reuse_rejected', + 'xfa_structure_analysis_reparse_queued', 'xfa_field_tree_accessed', 'xfa_collections_accessed', 'xfa_sensitive_sample_value_read', @@ -689,6 +700,16 @@ XFA_PROGRESS_EVENT_CODES: Final[frozenset[str]] = frozenset({ 'xfa_profile_needs_review', 'order_profile_unified_migration_dry_run', 'order_profile_unified_migration_executed', + # 合成预览(阶段 1 POC) + 'xfa_preview_requested', + 'xfa_preview_generated', + 'xfa_preview_failed', + 'xfa_preview_viewed', + 'xfa_preview_stale', + # OCR 自动标记建议(阶段 3) + 'xfa_ocr_started', + 'xfa_ocr_completed', + 'xfa_ocr_failed', }) # 工作台可用动作扩展(阶段 1/2 下发);既有动作保持兼容。 diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index 45f46e0b..6576d112 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -4,7 +4,8 @@ services/shipping_notice/query_service.py 用途:发货通知读模型 — 任务/批次查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。 依赖:ShippingCase、ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、 ShippingReservation、ShippingOrderReviewCase、ShippingOrderProcessingRun、 - ShippingOrderIntake / ShippingOrderProcessingRunIntake / FileAsset、state_machine、动态订单字段编辑器。 + ShippingOrderIntake / ShippingOrderProcessingRunIntake / FileAsset、state_machine、动态订单字段编辑器、 + order_review_projection(任务中心 STP retry 动作投影)。 逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块; co8 起 shipping_batches 已删除,批次 list API 返回空、按 batch_no 查询返回 None; tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉; @@ -12,6 +13,7 @@ services/shipping_notice/query_service.py 以及统一 shipping_processing_status / progress_version / order_task_no(BE-02), 并注入 review_run_no 供任务中心深链订单处理工作台(UI-04); list_my_todos / count_my_todos 合并建单前 Review Case、未建 OT Intake 与 Task 待办; + serialize_review_case_todo 在 STP failed/manual_fallback 时投影 retry_stp_auto_create; 客户关键字 SQL 同时过滤 Review Case / Intake(文件名)与 Task(客户快照/来源文件名); 待办 todo_category 下推为与状态机同序的 SQL CASE;list 用 UNION ALL + COUNT/OFFSET/LIMIT, 仅水合当前页(禁止 500 截断冒充总数); @@ -1299,7 +1301,8 @@ def serialize_review_case_todo( 将建单前 Review Case 投影为「我的待办」列表项,供打开人工复核深链。 核心逻辑:附带 review_run_no / review_case_no / owner_agent_id / conversation_id; - todo_category 固定 review;entry_surface=review_workbench。 + todo_category 固定 review;entry_surface=review_workbench; + STP failed/manual_fallback 时投影 retry_stp_auto_create(与工作台底栏同一幂等键)。 Args: case: 开放中的 Review Case。 @@ -1321,6 +1324,35 @@ def serialize_review_case_todo( and case.owner_user_id is not None and int(case.owner_user_id) == int(viewer_user_id) ) + allowed_actions: list[str] = [] + action_buttons: list[str] = [] + automation_status: str | None = None + # [STEP] 任务中心与底栏共用 STP 重试入口:仅 failed/manual_fallback + 可处理人。 + try: + from app.services.shipping_notice.order_review_projection import ( + _project_case_automation_status, + _project_post_confirm_auto_progress, + ) + + draft = case.current_draft + automation = _project_case_automation_status( + case, + validation=dict(draft.validation_result_json or {}) if draft is not None else None, + post_confirm=_project_post_confirm_auto_progress(case), + ) + if isinstance(automation, dict): + automation_status = str(automation.get('status') or '').strip() or None + if ( + can_handle + and automation.get('retryable') + and automation_status in {'failed', 'manual_fallback'} + and not case.confirmed_task_id + ): + allowed_actions.append('retry_stp_auto_create') + action_buttons.append('retry_stp_auto_create') + current_todo = '自动建单推进失败,可重试自动推进' + except Exception: # noqa: BLE001 + automation_status = None run_no = str(getattr(run, "run_no", None) or "").strip() or None conversation_id = str(getattr(run, "conversation_id", None) or "").strip() or None owner_agent_id = getattr(run, "owner_agent_id", None) @@ -1343,7 +1375,7 @@ def serialize_review_case_todo( "ui_state": { "checkpoint": "order_review", "checkpoint_kind": str(CheckpointKind.MUST_HUMAN), - "action_buttons": [], + "action_buttons": action_buttons, "summary": { "title": "待人工复核", "message": current_todo, @@ -1351,11 +1383,16 @@ def serialize_review_case_todo( "checkpoint_kind": str(CheckpointKind.MUST_HUMAN), "current_todo": current_todo, "pause_reason": current_todo, - "pause_reason_code": f"review_case_{case.status}", + "pause_reason_code": ( + f"stp_automation_{automation_status}" + if automation_status in {'failed', 'manual_fallback'} + else f"review_case_{case.status}" + ), "next_auto_step": None, "event_at": case.updated_at.isoformat() if case.updated_at else None, "entry_surface": "review_workbench", - "allowed_actions": [], + "allowed_actions": allowed_actions, + "automation_status": automation_status, "issues": [], "error_message": None, }, diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index 2281650e..d9e9c7b2 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -229,6 +229,8 @@ def claim_next_shipping_notice_job() -> Job | None: JobType.SHIPPING_ORDER_EXTRACTION, JobType.SHIPPING_DOCUMENT_LAYOUT, JobType.SHIPPING_PROCESS_GATE, + JobType.SHIPPING_XFA_OCR_AUTOMARK, + JobType.SHIPPING_STP_AUTO_CREATE, ], ) diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index 3c214dcf..eb4535f7 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -40,6 +40,9 @@ from app.services.shipping_notice.processing_projection_invariants import ( derivation_status_for_extraction_run, reconcile_processing_projection_facts, ) +from app.services.shipping_notice.processing_ownership import ( + record_projection_inconsistency_audit, +) from app.services.shipping_notice.progress_audit_contract import ( DIRECT_PDF_ALLOWED_STAGES, ORDER_INTAKE_SOURCE_TYPES, @@ -1030,7 +1033,7 @@ def _project_order_task_work_item( if linked_case is not None: case_no = str(getattr(linked_case, 'case_no', None) or '').strip() or None - return reconcile_processing_projection_facts( + payload = reconcile_processing_projection_facts( { 'work_item_type': 'order_task', 'work_item_no': user_task_no, @@ -1070,6 +1073,10 @@ def _project_order_task_work_item( invalidated_from_stage=invalidated_from_stage, excel_ready=excel_ready, ) + # [STEP] 投影不一致:写审计后剥离内部诊断字段,避免泄漏给前端契约。 + record_projection_inconsistency_audit(payload) + payload.pop('projection_inconsistency_code', None) + return payload def _intake_ids_linked_to_active_ot(*, user_id: int, conversation_id: str) -> set[int]: diff --git a/backend/app/services/shipping_notice/xfa_ocr_adapter.py b/backend/app/services/shipping_notice/xfa_ocr_adapter.py new file mode 100644 index 00000000..6254f272 --- /dev/null +++ b/backend/app/services/shipping_notice/xfa_ocr_adapter.py @@ -0,0 +1,171 @@ +""" +services/shipping_notice/xfa_ocr_adapter.py + +用途:XFA 合成预览页 OCR 适配器(阶段 3 骨架)——将 PNG 预览页识别为文本行与归一化框。 +依赖:document_layout.ocr_pdf(RapidOCR)、AppError;可选 PIL/numpy 解码 PNG。 +逻辑:由 xfa_visual_binding_service / OCR 自动标记编排调用;OCR 引擎不可用时抛 + SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE,不在 import 时加载模型, + 从而不影响普通 PDF 坐标路径。 +""" + +from __future__ import annotations + +import logging +from typing import Any + +from app.core.errors import ServiceUnavailableError + +_LOGGER = logging.getLogger(__name__) + +OCR_UNAVAILABLE_CODE = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE' + + +def _raise_ocr_unavailable(reason: str, *, cause: Exception | None = None) -> None: + """ + 统一抛出 OCR 不可用错误(fail-closed,不污染普通 PDF 路径)。 + + Args: + reason: 人类可读原因(写入 details,不暴露堆栈给客户端)。 + cause: 可选原始异常,仅用于日志。 + + Raises: + ServiceUnavailableError: 固定业务码 OCR_UNAVAILABLE。 + """ + if cause is not None: + _LOGGER.warning('XFA preview OCR unavailable: %s (%s)', reason, cause) + else: + _LOGGER.warning('XFA preview OCR unavailable: %s', reason) + raise ServiceUnavailableError( + 'XFA preview OCR is unavailable', + code=OCR_UNAVAILABLE_CODE, + details={'reason': reason}, + ) + + +def _decode_png_to_ndarray(png_bytes: bytes) -> Any: + """ + 将 PNG 字节解码为 HxWxC ndarray(供 RapidOCR)。 + + 核心逻辑:优先 OpenCV imdecode;失败再试 PIL。解码失败视为 OCR 不可用。 + + Args: + png_bytes: 预览页 PNG 原始字节。 + + Returns: + BGR/RGB ndarray(RapidOCR 可接受)。 + + Raises: + ServiceUnavailableError: 解码依赖或内容不可用。 + """ + if not png_bytes: + _raise_ocr_unavailable('empty_png_bytes') + + # [STEP 1] OpenCV 解码(与 ocr_pdf / PDFium 管线一致) + try: + import cv2 # type: ignore + import numpy as np # type: ignore + + arr = np.frombuffer(png_bytes, dtype=np.uint8) + image = cv2.imdecode(arr, cv2.IMREAD_COLOR) + if image is not None and getattr(image, 'size', 0) > 0: + return image + except Exception as exc: # noqa: BLE001 — 解码失败统一映射为 OCR_UNAVAILABLE + _LOGGER.debug('OpenCV PNG decode failed, trying PIL: %s', exc) + + # [STEP 2] PIL 兜底 + try: + from io import BytesIO + + import numpy as np # type: ignore + from PIL import Image # type: ignore + + with Image.open(BytesIO(png_bytes)) as img: + rgb = img.convert('RGB') + return np.asarray(rgb) + except Exception as exc: # noqa: BLE001 + _raise_ocr_unavailable('png_decode_failed', cause=exc) + _raise_ocr_unavailable('png_decode_empty') + + +def is_ocr_engine_available() -> bool: + """ + 探测 RapidOCR 是否可导入(不强制加载模型权重)。 + + Returns: + True 表示引擎模块可导入;False 表示本进程不可用。 + """ + try: + import rapidocr_onnxruntime # noqa: F401 + + return True + except Exception: # noqa: BLE001 + return False + + +def recognize_preview_page(png_bytes: bytes) -> list[dict[str, Any]]: + """ + 对 XFA 合成预览 PNG 页执行 OCR,返回归一化文本行。 + + 核心逻辑:解码 PNG → 惰性调用 document_layout.ocr_pdf.extract_ocr_lines → + 将页面坐标映射为 0..1 normalized_bbox。引擎缺失或解码失败时抛 OCR_UNAVAILABLE, + 禁止静默空成功。 + + Args: + png_bytes: 单页预览 PNG 字节。 + + Returns: + list[{text, confidence, normalized_bbox}];normalized_bbox 为 {x0,y0,x1,y1}。 + + Raises: + ServiceUnavailableError: OCR 引擎或解码不可用。 + """ + if not is_ocr_engine_available(): + _raise_ocr_unavailable('rapidocr_not_installed') + + image = _decode_png_to_ndarray(png_bytes) + try: + height, width = image.shape[:2] + except Exception as exc: # noqa: BLE001 + _raise_ocr_unavailable('invalid_image_shape', cause=exc) + if width <= 0 or height <= 0: + _raise_ocr_unavailable('invalid_image_dimensions') + + # [STEP 1] 以像素尺寸作为“页面”坐标系,再归一化到 0..1 + try: + from app.services.shipping_notice.document_layout.ocr_pdf import ( + extract_ocr_lines, + page_bbox_to_normalized, + ) + except Exception as exc: # noqa: BLE001 + _raise_ocr_unavailable('ocr_pdf_module_unavailable', cause=exc) + + try: + lines = extract_ocr_lines(image, page_width=float(width), page_height=float(height)) + except Exception as exc: # noqa: BLE001 — 引擎运行失败不得拖垮普通 PDF + _raise_ocr_unavailable('ocr_engine_runtime_failed', cause=exc) + + results: list[dict[str, Any]] = [] + for line in lines or []: + text = str(getattr(line, 'text', '') or '').strip() + if not text: + continue + try: + normalized = page_bbox_to_normalized( + line.bbox, + page_width=float(width), + page_height=float(height), + ) + bbox = { + 'x0': float(normalized.x0), + 'y0': float(normalized.y0), + 'x1': float(normalized.x1), + 'y1': float(normalized.y1), + } + except Exception: # noqa: BLE001 — 单行坏框跳过,不整体失败 + continue + results.append({ + 'text': text, + 'confidence': float(getattr(line, 'confidence', 0.0) or 0.0), + 'normalized_bbox': bbox, + }) + return results diff --git a/backend/app/services/shipping_notice/xfa_ocr_matcher.py b/backend/app/services/shipping_notice/xfa_ocr_matcher.py new file mode 100644 index 00000000..9f30f568 --- /dev/null +++ b/backend/app/services/shipping_notice/xfa_ocr_matcher.py @@ -0,0 +1,222 @@ +""" +services/shipping_notice/xfa_ocr_matcher.py + +用途:XFA OCR 文本与 datasets 值匹配、IoU 评分与置信分层(阶段 3 骨架)。 +依赖:标准库 typing;与 xfa_ocr_adapter / xfa_visual_binding_service 协作。 +逻辑:纯函数;规范化文本后匹配 OCR 行与 datasets 候选值;mismatch 一律 + needs_review,且任何分层都不得自动 confirmed。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Literal + +OcrMatchClass = Literal['high', 'medium', 'low', 'needs_review'] + +# [PARAM_TUNING] IoU / OCR 置信门槛:偏保守,优先 needs_review 而非误自动标记。 +IOU_HIGH = 0.50 +IOU_MEDIUM = 0.30 +IOU_LOW = 0.10 +OCR_CONF_HIGH = 0.90 +OCR_CONF_MEDIUM = 0.80 +OCR_CONF_LOW = 0.70 + + +@dataclass(frozen=True) +class OcrMatchSuggestion: + """单条 OCR→datasets 匹配建议;永不表示已确认。""" + + field_key: str + dataset_value: str + ocr_text: str + normalized_bbox: dict[str, float] + iou: float + ocr_confidence: float + match_class: OcrMatchClass + status: Literal['suggested', 'needs_review'] + auto_confirm_blocked: bool = True + + def to_dict(self) -> dict[str, Any]: + """序列化为安全 DTO。""" + return { + 'field_key': self.field_key, + 'dataset_value': self.dataset_value, + 'ocr_text': self.ocr_text, + 'normalized_bbox': dict(self.normalized_bbox), + 'iou': round(float(self.iou), 4), + 'ocr_confidence': round(float(self.ocr_confidence), 4), + 'match_class': self.match_class, + 'status': self.status, + 'auto_confirm_blocked': True, + } + + +def normalize_match_text(value: str | None) -> str: + """ + 规范化匹配文本:大小写折叠 + 空白折叠。 + + Args: + value: 原始 OCR 或 datasets 文本。 + + Returns: + 用于精确/包含比较的规范化字符串。 + """ + return ''.join(str(value or '').casefold().split()) + + +def compute_iou(a: dict[str, float], b: dict[str, float]) -> float: + """ + 计算两归一化框 IoU。 + + Args: + a/b: {x0,y0,x1,y1},假定 0..1。 + + Returns: + 0..1 IoU;非法框返回 0。 + """ + ax0, ay0 = float(a.get('x0') or 0), float(a.get('y0') or 0) + ax1, ay1 = float(a.get('x1') or 0), float(a.get('y1') or 0) + bx0, by0 = float(b.get('x0') or 0), float(b.get('y0') or 0) + bx1, by1 = float(b.get('x1') or 0), float(b.get('y1') or 0) + if ax1 <= ax0 or ay1 <= ay0 or bx1 <= bx0 or by1 <= by0: + return 0.0 + ix0, iy0 = max(ax0, bx0), max(ay0, by0) + ix1, iy1 = min(ax1, bx1), min(ay1, by1) + if ix1 <= ix0 or iy1 <= iy0: + return 0.0 + inter = (ix1 - ix0) * (iy1 - iy0) + area_a = (ax1 - ax0) * (ay1 - ay0) + area_b = (bx1 - bx0) * (by1 - by0) + union = area_a + area_b - inter + if union <= 0: + return 0.0 + return inter / union + + +def classify_ocr_match( + *, + text_score: float, + iou: float, + ocr_confidence: float, +) -> OcrMatchClass: + """ + 按文本分、IoU、OCR 置信度分层。 + + 核心逻辑:text_score<=0 或 IoU 过低 → needs_review;其余按门槛分 high/medium/low。 + 任意分层均不得自动确认(由调用方强制 status)。 + + Args: + text_score: 0/0.5/1.0(不匹配/包含/精确)。 + iou: 框重叠。 + ocr_confidence: OCR 行置信度。 + + Returns: + high | medium | low | needs_review。 + """ + if text_score <= 0.0 or iou < IOU_LOW: + return 'needs_review' + if text_score >= 1.0 and iou >= IOU_HIGH and ocr_confidence >= OCR_CONF_HIGH: + return 'high' + if text_score >= 0.5 and iou >= IOU_MEDIUM and ocr_confidence >= OCR_CONF_MEDIUM: + return 'medium' + if text_score >= 0.5 and iou >= IOU_LOW and ocr_confidence >= OCR_CONF_LOW: + return 'low' + return 'needs_review' + + +def _text_score(ocr_text: str, dataset_value: str) -> float: + """精确=1.0,互相包含=0.5,否则 0。""" + left = normalize_match_text(ocr_text) + right = normalize_match_text(dataset_value) + if not left or not right: + return 0.0 + if left == right: + return 1.0 + if left in right or right in left: + return 0.5 + return 0.0 + + +def match_ocr_to_datasets( + *, + ocr_lines: list[dict[str, Any]], + dataset_targets: list[dict[str, Any]], +) -> list[dict[str, Any]]: + """ + 将 OCR 行匹配到 datasets 目标值,产出建议列表。 + + 核心逻辑:对每个 dataset 目标选最佳 OCR 行(文本分优先,其次 IoU); + mismatch → status=needs_review;匹配成功也仅 suggested,且 auto_confirm_blocked。 + + Args: + ocr_lines: recognize_preview_page 输出或等价合成行。 + dataset_targets: [{field_key, value, normalized_bbox?}];bbox 可选(用于 IoU)。 + + Returns: + 建议 DTO 列表(每目标至多一条最佳匹配)。 + """ + suggestions: list[dict[str, Any]] = [] + for target in dataset_targets or []: + if not isinstance(target, dict): + continue + field_key = str(target.get('field_key') or target.get('path_id') or '').strip() + dataset_value = str(target.get('value') or target.get('dataset_value') or '') + target_bbox = target.get('normalized_bbox') if isinstance(target.get('normalized_bbox'), dict) else None + if not field_key: + continue + + best: OcrMatchSuggestion | None = None + best_rank = (-1.0, -1.0, -1.0) # text_score, iou, ocr_conf + + for line in ocr_lines or []: + if not isinstance(line, dict): + continue + ocr_text = str(line.get('text') or '') + ocr_bbox = line.get('normalized_bbox') if isinstance(line.get('normalized_bbox'), dict) else {} + ocr_conf = float(line.get('confidence') or 0.0) + text_score = _text_score(ocr_text, dataset_value) + iou = compute_iou(target_bbox, ocr_bbox) if target_bbox else (0.5 if text_score > 0 else 0.0) + rank = (text_score, iou, ocr_conf) + if rank <= best_rank: + continue + best_rank = rank + match_class = classify_ocr_match( + text_score=text_score, + iou=iou, + ocr_confidence=ocr_conf, + ) + # mismatch 或 needs_review → 强制 needs_review status,禁止自动确认 + status: Literal['suggested', 'needs_review'] = ( + 'needs_review' if match_class == 'needs_review' or text_score <= 0 else 'suggested' + ) + best = OcrMatchSuggestion( + field_key=field_key, + dataset_value=dataset_value, + ocr_text=ocr_text, + normalized_bbox={ + 'x0': float(ocr_bbox.get('x0') or 0), + 'y0': float(ocr_bbox.get('y0') or 0), + 'x1': float(ocr_bbox.get('x1') or 0), + 'y1': float(ocr_bbox.get('y1') or 0), + }, + iou=iou, + ocr_confidence=ocr_conf, + match_class=match_class, + status=status, + ) + + if best is None: + suggestions.append(OcrMatchSuggestion( + field_key=field_key, + dataset_value=dataset_value, + ocr_text='', + normalized_bbox={'x0': 0.0, 'y0': 0.0, 'x1': 0.0, 'y1': 0.0}, + iou=0.0, + ocr_confidence=0.0, + match_class='needs_review', + status='needs_review', + ).to_dict()) + else: + suggestions.append(best.to_dict()) + return suggestions diff --git a/backend/app/services/shipping_notice/xfa_visual_binding_service.py b/backend/app/services/shipping_notice/xfa_visual_binding_service.py new file mode 100644 index 00000000..8ee8cd7b --- /dev/null +++ b/backend/app/services/shipping_notice/xfa_visual_binding_service.py @@ -0,0 +1,145 @@ +""" +services/shipping_notice/xfa_visual_binding_service.py + +用途:合并 Widget/template 视觉建议与 OCR 补框建议,仅产出 suggested visual_bindings(阶段 3)。 +依赖:xfa_ocr_matcher;可选上游 Widget 候选;不写 Draft、不自动 confirmed。 +逻辑:先保留 Widget/template 建议;对尚未覆盖的 field_key 用 OCR 匹配填充; + mismatch 标记 needs_review。与 order_document_profile_visual_binding_service + (确认/驳回编排)分工:本模块只做自动标记建议合并。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.shipping_notice.xfa_ocr_matcher import match_ocr_to_datasets + + +def _field_key_from_widget_candidate(candidate: dict[str, Any]) -> str | None: + """ + 从 Widget 候选中提取可对账的 field_key(优先 path_id)。 + + Args: + candidate: suggest_visual_binding_candidates 风格条目。 + + Returns: + path_id / field_key;无法识别时 None。 + """ + for path in candidate.get('path_candidates') or []: + if isinstance(path, dict) and path.get('path_id'): + return str(path['path_id']) + for key in ('field_key', 'path_id', 'binding_id', 'candidate_id'): + if candidate.get(key): + return str(candidate[key]) + return None + + +def _widget_to_suggested_binding(candidate: dict[str, Any], *, page_no: int) -> dict[str, Any]: + """将 Widget 候选投影为 suggested visual_binding 摘要。""" + bbox = candidate.get('normalized_bbox') if isinstance(candidate.get('normalized_bbox'), dict) else {} + return { + 'field_key': _field_key_from_widget_candidate(candidate), + 'page_no': int(candidate.get('page_no') or page_no), + 'normalized_bbox': { + 'x0': float(bbox.get('x0') or 0), + 'y0': float(bbox.get('y0') or 0), + 'x1': float(bbox.get('x1') or 0), + 'y1': float(bbox.get('y1') or 0), + }, + 'source': 'acroform_widget', + 'status': 'suggested', + 'confidence': float(candidate.get('confidence') or 0.0), + 'match_class': 'high' if float(candidate.get('confidence') or 0) >= 0.85 else 'medium', + 'suggestion_origin': 'widget_template', + 'auto_confirm_blocked': True, + } + + +def _ocr_to_suggested_binding(suggestion: dict[str, Any], *, page_no: int) -> dict[str, Any]: + """将 OCR matcher 建议投影为 suggested / needs_review visual_binding 摘要。""" + status = str(suggestion.get('status') or 'needs_review') + # 契约层 visual_binding.status 不含 needs_review;建议层保留,落库前须人工确认 + visual_status = 'suggested' if status == 'suggested' else 'suggested' + return { + 'field_key': suggestion.get('field_key'), + 'page_no': int(page_no), + 'normalized_bbox': dict(suggestion.get('normalized_bbox') or {}), + 'source': 'suggested', + 'status': visual_status, + 'suggestion_status': status, + 'confidence': float(suggestion.get('ocr_confidence') or 0.0), + 'match_class': suggestion.get('match_class') or 'needs_review', + 'suggestion_origin': 'ocr', + 'ocr_text': suggestion.get('ocr_text'), + 'dataset_value': suggestion.get('dataset_value'), + 'iou': suggestion.get('iou'), + 'auto_confirm_blocked': True, + 'needs_review': status == 'needs_review' or suggestion.get('match_class') == 'needs_review', + } + + +def merge_visual_binding_suggestions( + *, + page_no: int, + widget_candidates: list[dict[str, Any]] | None = None, + ocr_lines: list[dict[str, Any]] | None = None, + dataset_targets: list[dict[str, Any]] | None = None, +) -> dict[str, Any]: + """ + 合并 Widget/template 与 OCR 建议,仅返回 suggested visual_bindings。 + + 核心逻辑: + 1. 先落入 Widget/template 候选(优先); + 2. 对未覆盖 field_key 用 OCR matcher 补框; + 3. 全部 auto_confirm_blocked=True,永不 confirmed。 + + Args: + page_no: 页码(1-based)。 + widget_candidates: 上游 Widget/template 候选列表。 + ocr_lines: OCR 适配器输出(可合成,无需真引擎)。 + dataset_targets: datasets 目标 [{field_key, value, normalized_bbox?}]。 + + Returns: + {suggested_visual_bindings, diagnostics};不含 confirmed 绑定。 + """ + # [STEP 1] Widget / template 优先 + covered: set[str] = set() + suggested: list[dict[str, Any]] = [] + for candidate in widget_candidates or []: + if not isinstance(candidate, dict): + continue + binding = _widget_to_suggested_binding(candidate, page_no=page_no) + key = str(binding.get('field_key') or '') + if key: + covered.add(key) + suggested.append(binding) + + # [STEP 2] OCR 仅填充尚未覆盖的目标 + pending_targets = [ + item for item in (dataset_targets or []) + if isinstance(item, dict) + and str(item.get('field_key') or item.get('path_id') or '') not in covered + ] + ocr_suggestions = match_ocr_to_datasets( + ocr_lines=list(ocr_lines or []), + dataset_targets=pending_targets, + ) + needs_review_count = 0 + for item in ocr_suggestions: + binding = _ocr_to_suggested_binding(item, page_no=page_no) + if binding.get('needs_review'): + needs_review_count += 1 + suggested.append(binding) + + diagnostics = { + 'widget_candidate_count': len(widget_candidates or []), + 'ocr_fill_count': len(ocr_suggestions), + 'needs_review_count': needs_review_count, + 'auto_confirm_blocked': True, + 'notes': ['widget_first_then_ocr_fill', 'never_auto_confirm'], + } + return { + 'page_no': int(page_no), + 'suggested_visual_bindings': suggested, + 'diagnostics': diagnostics, + } diff --git a/backend/migrations/versions/cq1a2b3c4d5e_add_stp_job_retry_of_and_active_unique.py b/backend/migrations/versions/cq1a2b3c4d5e_add_stp_job_retry_of_and_active_unique.py new file mode 100644 index 00000000..a8988dba --- /dev/null +++ b/backend/migrations/versions/cq1a2b3c4d5e_add_stp_job_retry_of_and_active_unique.py @@ -0,0 +1,135 @@ +""" +backend/migrations/versions/cq1a2b3c4d5e_add_stp_job_retry_of_and_active_unique.py + +用途:为 STP 自动建单 Job 增加 retry_of_job_id,以及 active(queued/running) 部分唯一索引。 +依赖:Alembic revision cp0a1b2c3d4e。 +逻辑:先合并同幂等键下多余的 queued/running STP Job(保留最大 id),再加列与唯一索引。 + +Revision ID: cq1a2b3c4d5e +Revises: cp0a1b2c3d4e +Create Date: 2026-08-07 00:30:00.000000 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision = 'cq1a2b3c4d5e' +down_revision = 'cp0a1b2c3d4e' +branch_labels = None +depends_on = None + + +def _index_names(table: str) -> set[str]: + bind = op.get_bind() + inspector = sa.inspect(bind) + return {str(ix.get('name') or '') for ix in inspector.get_indexes(table)} + + +def _column_names(table: str) -> set[str]: + bind = op.get_bind() + inspector = sa.inspect(bind) + return {str(col.get('name') or '') for col in inspector.get_columns(table)} + + +def _dedupe_active_stp_jobs() -> None: + """同 domain/business_ref 的多条 queued/running STP Job:保留最大 id,其余标 cancelled。""" + bind = op.get_bind() + groups = bind.execute( + sa.text( + """ + SELECT domain, business_ref + FROM jobs + WHERE job_type = 'shipping_stp_auto_create' + AND status IN ('queued', 'running') + AND business_ref IS NOT NULL + GROUP BY domain, business_ref + HAVING COUNT(*) > 1 + """ + ) + ).fetchall() + for domain, business_ref in groups: + ids = [ + int(row[0]) + for row in bind.execute( + sa.text( + """ + SELECT id + FROM jobs + WHERE domain = :domain + AND job_type = 'shipping_stp_auto_create' + AND business_ref = :business_ref + AND status IN ('queued', 'running') + ORDER BY id DESC + """ + ), + {'domain': str(domain), 'business_ref': str(business_ref)}, + ).fetchall() + ] + if len(ids) < 2: + continue + keep_id = ids[0] + for drop_id in ids[1:]: + bind.execute( + sa.text( + """ + UPDATE jobs + SET status = 'cancelled', + message = '并发去重:合并 active shipping_stp_auto_create', + progress = 100, + locked_by = NULL, + locked_at = NULL, + finished_at = CURRENT_TIMESTAMP, + updated_at = CURRENT_TIMESTAMP + WHERE id = :drop_id + AND id <> :keep_id + AND status IN ('queued', 'running') + """ + ), + {'drop_id': drop_id, 'keep_id': keep_id}, + ) + + +def upgrade() -> None: + """加 retry_of_job_id 列与 STP active 部分唯一索引。""" + if 'retry_of_job_id' not in _column_names('jobs'): + op.add_column('jobs', sa.Column('retry_of_job_id', sa.Integer(), nullable=True)) + op.create_foreign_key( + 'fk_jobs_retry_of_job_id', + 'jobs', + 'jobs', + ['retry_of_job_id'], + ['id'], + ) + op.create_index('ix_jobs_retry_of_job_id', 'jobs', ['retry_of_job_id']) + + _dedupe_active_stp_jobs() + if 'uq_jobs_shipping_stp_auto_create_active_ref' not in _index_names('jobs'): + op.create_index( + 'uq_jobs_shipping_stp_auto_create_active_ref', + 'jobs', + ['domain', 'job_type', 'business_ref'], + unique=True, + postgresql_where=sa.text( + "job_type = 'shipping_stp_auto_create' " + "AND status IN ('queued', 'running') " + "AND business_ref IS NOT NULL" + ), + sqlite_where=sa.text( + "job_type = 'shipping_stp_auto_create' " + "AND status IN ('queued', 'running') " + "AND business_ref IS NOT NULL" + ), + ) + + +def downgrade() -> None: + """删除 STP active 唯一索引与 retry_of_job_id。""" + if 'uq_jobs_shipping_stp_auto_create_active_ref' in _index_names('jobs'): + op.drop_index('uq_jobs_shipping_stp_auto_create_active_ref', table_name='jobs') + if 'retry_of_job_id' in _column_names('jobs'): + if 'ix_jobs_retry_of_job_id' in _index_names('jobs'): + op.drop_index('ix_jobs_retry_of_job_id', table_name='jobs') + op.drop_constraint('fk_jobs_retry_of_job_id', 'jobs', type_='foreignkey') + op.drop_column('jobs', 'retry_of_job_id') diff --git a/backend/scripts/_stp_synthetic_evidence_SNER-20260806.json b/backend/scripts/_stp_synthetic_evidence_SNER-20260806.json new file mode 100644 index 00000000..5efc3ecc --- /dev/null +++ b/backend/scripts/_stp_synthetic_evidence_SNER-20260806.json @@ -0,0 +1,44 @@ +{ + "run_no": "SNER-20260806-AB1F70EE", + "rebuilt": false, + "enqueue_results": [ + { + "case_no": "SORC-BC8338CC6A964B8C", + "status": "already_queued", + "job_id": 882, + "idempotency_key": "stp-auto:SNER-20260806-AB1F70EE:doc-135:v1", + "job_status": "queued", + "can_auto_create": true, + "retry_of_job_id": null + } + ], + "jobs": [ + { + "run_no": "SNER-20260806-AB1F70EE", + "job_id": 882, + "status": "queued", + "business_ref": "stp-auto:SNER-20260806-AB1F70EE:doc-135:v1", + "retry_of_job_id": null, + "domain": "shipping_notice", + "created_at": "2026-08-06T17:22:59.813262" + }, + { + "run_no": "SNER-20260806-AB1F70EE", + "job_id": 877, + "status": "queued", + "business_ref": "stp-auto:SNER-20260806-AB1F70EE:doc-137:v2", + "retry_of_job_id": null, + "domain": "shipping_notice", + "created_at": "2026-08-06T12:58:02.097753" + }, + { + "run_no": "SNER-20260806-AB1F70EE", + "job_id": 876, + "status": "queued", + "business_ref": "stp-auto:SNER-20260806-AB1F70EE:doc-136:v2", + "retry_of_job_id": null, + "domain": "shipping_notice", + "created_at": "2026-08-06T12:58:01.981031" + } + ] +} \ No newline at end of file diff --git a/backend/scripts/verify_stp_synthetic_sner_20260806.py b/backend/scripts/verify_stp_synthetic_sner_20260806.py new file mode 100644 index 00000000..2b73348f --- /dev/null +++ b/backend/scripts/verify_stp_synthetic_sner_20260806.py @@ -0,0 +1,325 @@ +""" +backend/scripts/verify_stp_synthetic_sner_20260806.py + +用途:为冻结验收提供 STP 真实入队证据(run_no / business_ref / job_id / status)。 +依赖:Flask create_app、order_stp_auto_create_service、Job / Review Case 模型。 +逻辑:优先使用 SNER-20260806-AB1F70EE;若不存在则复用现有 shipping_notice Agent + 重建最小 eligible Case,再 ensure 入队并打印/落盘查询结果。 + +用法(在 backend 目录、已激活 venv): + python scripts/verify_stp_synthetic_sner_20260806.py +""" + +from __future__ import annotations + +import json +import sys +import uuid +from datetime import datetime, timedelta, timezone +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +TARGET_RUN_NO = 'SNER-20260806-AB1F70EE' + + +def _print_evidence(rows: list[dict]) -> None: + """打印验收所需字段。""" + print('=== STP synthetic evidence ===') + print(json.dumps(rows, ensure_ascii=False, indent=2, default=str)) + + +def _query_jobs_for_run(run_no: str) -> list[dict]: + """按 business_ref 前缀查询 shipping_stp_auto_create Job。""" + from app.models import Job + + like = f'%{run_no}%' + jobs = ( + Job.query.filter( + Job.job_type == 'shipping_stp_auto_create', + Job.business_ref.ilike(like), + ) + .order_by(Job.id.desc()) + .limit(20) + .all() + ) + return [ + { + 'run_no': run_no, + 'job_id': int(job.id), + 'status': str(job.status), + 'business_ref': str(job.business_ref or ''), + 'retry_of_job_id': int(job.retry_of_job_id) if job.retry_of_job_id else None, + 'domain': str(job.domain or ''), + 'created_at': job.created_at.isoformat() if job.created_at else None, + } + for job in jobs + ] + + +def _find_target_run(): + from app.models import ShippingOrderProcessingRun + + return ShippingOrderProcessingRun.query.filter_by(run_no=TARGET_RUN_NO).first() + + +def _rebuild_minimal_eligible_case(): + """ + 重建最小可入队 Case(仅用于验收证据)。 + + 核心逻辑:复用已存在的 shipping_notice Agent(避免 uq_agents_one_active_shipping_notice); + 新建隔离 User/Session/Intake/Document/Run/Case;写入 can_auto_create validation 后 ensure。 + """ + from app import db + from app.models import ( + Agent, + ChatSession, + FileAsset, + ShippingOrderDocument, + ShippingOrderIntake, + ShippingOrderProcessingRun, + ShippingOrderReviewCase, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + User, + ) + from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan + from app.services.shipping_notice.order_extraction_run_service import ( + create_order_extraction_run, + transition_order_extraction_run, + ) + from app.services.shipping_notice.order_review_service import ensure_run_review_cases + from app.services.shipping_notice.order_stp_auto_create_service import ( + ensure_stp_auto_create_for_case, + ) + + suffix = f'SYN{uuid.uuid4().hex[:8].upper()}' + agent = Agent.query.filter_by(agent_code='shipping_notice', is_active=True).first() + if agent is None: + agent = Agent.query.filter_by(agent_code='shipping_notice').first() + if agent is None: + raise RuntimeError('active shipping_notice agent not found; cannot rebuild synthetic case') + + # [STEP] 真实库可能存在序列漂移;插入前对齐常用表序列,避免 users_pkey 冲突。 + for table, column in ( + ('users', 'id'), + ('chat_sessions', 'id'), + ('file_assets', 'id'), + ('shipping_order_intakes', 'id'), + ('shipping_order_documents', 'id'), + ('shipping_order_schemas', 'id'), + ('shipping_order_schema_versions', 'id'), + ): + db.session.execute( + db.text( + f"SELECT setval(pg_get_serial_sequence('{table}', '{column}'), " + f"COALESCE((SELECT MAX({column}) FROM {table}), 1))" + ) + ) + db.session.commit() + + # [STEP] 开发库序列可能落后于 MAX(id);重建前对齐,避免 users_pkey 冲突。 + from sqlalchemy import text + + for table in ('users', 'chat_sessions', 'file_assets', 'shipping_order_intakes', 'shipping_order_documents'): + try: + db.session.execute(text( + f"SELECT setval(pg_get_serial_sequence('{table}', 'id'), " + f"COALESCE((SELECT MAX(id) FROM {table}), 1))" + )) + except Exception: # noqa: BLE001 + db.session.rollback() + db.session.commit() + + schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').first() + if schema is None: + schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order') + db.session.add(schema) + db.session.flush() + db.session.add(ShippingOrderSchemaVersion( + schema_id=schema.id, + version=1, + status='published', + checksum='a' * 64, + definition_json={ + 'fields': [ + {'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'enabled': True}, + {'field_id': 'po-id', 'field_code': 'po_number', 'scope': 'header', 'enabled': True}, + ], + }, + published_at=datetime.utcnow(), + )) + db.session.flush() + + user = User( + username=f'stp-syn-{suffix.lower()}', + email=f'stp-syn-{suffix.lower()}@example.com', + password_hash='x', + status='active', + ) + user.agents.append(agent) + db.session.add(user) + db.session.flush() + + session = ChatSession( + session_id=f'stp-syn-session-{suffix}', + user_id=user.id, + agent_id=agent.id, + title='STP synthetic evidence', + ) + asset = FileAsset( + asset_no=f'FA-STP-{suffix}', + owner_user_id=user.id, + original_filename=f'stp-syn-{suffix}.pdf', + storage_provider='minio', + storage_bucket='test', + storage_key=f'temporary/{user.id}/stp-syn-{suffix}.pdf', + content_hash=(suffix.lower() * 8)[:64], + file_size=100, + mime_type='application/pdf', + upload_status='ready', + lifecycle_status='temporary', + ) + db.session.add_all([session, asset]) + db.session.flush() + + intake = ShippingOrderIntake( + intake_no=f'SNI-STP-{suffix}', + asset_id=asset.id, + user_id=user.id, + conversation_id=session.session_id, + purpose='shipping_notice', + parse_status='parsed', + parser_version='v6', + extracted_text=f'synthetic stp {suffix}', + structured_result_json={'email': {'from': f'Sales-{suffix}@Example.COM'}}, + expires_at=datetime.utcnow() + timedelta(hours=1), + ) + db.session.add(intake) + db.session.flush() + document = ShippingOrderDocument( + intake_id=intake.id, + asset_id=asset.id, + document_type='attachment', + attachment_key=f'stp-syn-{suffix}.pdf', + filename=f'stp-syn-{suffix}.pdf', + content_hash=(suffix.upper() * 8)[:64], + classification='order_notice', + parse_status='parsed', + extracted_text=f'PO SYN{suffix} QTY 1 EA', + ) + db.session.add(document) + db.session.commit() + + run, _ = create_order_extraction_run( + 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' + # [STEP] 固定 run_no 以便验收脚本可复现查询。 + run.run_no = TARGET_RUN_NO + db.session.flush() + transition_order_extraction_run(run, target_status='processing') + transition_order_extraction_run(run, target_status='review_required', result={}) + cases = ensure_run_review_cases(run=run) + if not cases: + raise RuntimeError('failed to create review cases for synthetic run') + + for case in cases: + draft = case.current_draft + if draft is None: + raise RuntimeError(f'case {case.case_no} missing draft') + draft.validation_result_json = { + 'status': 'ready', + 'can_build': True, + 'can_auto_create': True, + 'failed_gates': [], + 'issues': [], + 'validated_at': datetime.now(timezone.utc).isoformat(), + 'validation_checksum': 'synthetic-stp-evidence-v1', + } + draft.issue_summary_json = [] + case.status = 'ready' + db.session.commit() + + results = [] + for row in ShippingOrderReviewCase.query.filter_by(run_id=int(run.id)).all(): + result = ensure_stp_auto_create_for_case( + case=row, + run=run, + commit=True, + refresh_validation=False, + force_retry=False, + ) + results.append(result) + refreshed = ShippingOrderProcessingRun.query.filter_by(run_no=TARGET_RUN_NO).first() + return refreshed, results + + +def main() -> int: + from app import create_app + from app.models import ShippingOrderReviewCase + from app.services.shipping_notice.order_stp_auto_create_service import ( + ensure_stp_auto_create_for_case, + ) + + app = create_app() + with app.app_context(): + run = _find_target_run() + rebuilt = False + enqueue_results: list[dict] = [] + if run is None: + print(f'[info] run {TARGET_RUN_NO} missing; rebuilding minimal eligible case') + run, enqueue_results = _rebuild_minimal_eligible_case() + rebuilt = True + else: + cases = ShippingOrderReviewCase.query.filter_by(run_id=int(run.id)).all() + print(f'[info] found run id={run.id} cases={len(cases)}') + for case in cases: + if case.confirmed_task_id or str(case.status) == 'confirmed': + continue + draft = case.current_draft + if draft is not None: + validation = dict(draft.validation_result_json or {}) + validation.update({ + 'status': 'ready', + 'can_build': True, + 'can_auto_create': True, + }) + draft.validation_result_json = validation + result = ensure_stp_auto_create_for_case( + case=case, + run=run, + commit=True, + refresh_validation=False, + force_retry=False, + ) + enqueue_results.append(result) + + evidence = _query_jobs_for_run(TARGET_RUN_NO) + payload = { + 'run_no': TARGET_RUN_NO, + 'rebuilt': rebuilt, + 'enqueue_results': enqueue_results, + 'jobs': evidence, + } + out_path = Path(__file__).resolve().parent / '_stp_synthetic_evidence_SNER-20260806.json' + out_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2, default=str), encoding='utf-8') + _print_evidence(evidence) + print(f'[info] wrote {out_path}') + if not evidence: + print('[fail] no shipping_stp_auto_create jobs found') + print('[debug] enqueue_results=', json.dumps(enqueue_results, ensure_ascii=False, default=str)) + return 1 + print('[ok] synthetic STP evidence ready') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 21a6f39e..8702ae73 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -420,6 +420,10 @@ def pytest_configure(config): "markers", "inventory_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入", ) + config.addinivalue_line( + "markers", + "postgres: requires PostgreSQL dialect (skip on SQLite/memory fixtures)", + ) # [STEP] Windows 质量门禁:basetemp 落仓内 + retention=0(见 pytest.ini)。 if not getattr(config.option, 'basetemp', None): basetemp = Path(__file__).resolve().parents[1] / '.pytest_tmp' / 'run' diff --git a/backend/tests/test_shipping_document_layout_lifecycle.py b/backend/tests/test_shipping_document_layout_lifecycle.py index 8c78aa73..9c82393d 100644 --- a/backend/tests/test_shipping_document_layout_lifecycle.py +++ b/backend/tests/test_shipping_document_layout_lifecycle.py @@ -198,9 +198,18 @@ def test_recoverable_ready_layout_is_reused_for_duplicate_document(app): assert scheduled.id != incomplete.id -def test_xfa_layout_reuse_localizes_structure_analysis_for_duplicate_document(app): +def test_xfa_layout_reuse_localizes_structure_analysis_for_duplicate_document(app, monkeypatch): """相同 XFA 文件复用时,目标 Document 必须获得独立 Analysis 并重写快照身份。""" app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True + audit_events: list[str] = [] + + def _capture_audit(**kwargs): + audit_events.append(str(kwargs.get('event_type'))) + + monkeypatch.setattr( + 'app.services.shipping_notice.audit_service.append_shipping_audit_event', + _capture_audit, + ) with app.app_context(): original = _document() source_analysis = ShippingXfaStructureAnalysis( @@ -269,11 +278,21 @@ def test_xfa_layout_reuse_localizes_structure_analysis_for_duplicate_document(ap assert target_analysis.dataset_structure_fingerprint == source_analysis.dataset_structure_fingerprint assert target_capability['structure_analysis_id'] == target_analysis.id assert localized.payload_json['capability']['structure_analysis_id'] == target_analysis.id + assert 'xfa_structure_analysis_reused' in audit_events -def test_xfa_layout_without_source_analysis_is_not_reused(app): +def test_xfa_layout_without_source_analysis_is_not_reused(app, monkeypatch): """XFA 快照声明 ready 但源 Analysis 缺失时必须重新排队,禁止复制伪 ready 状态。""" app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True + audit_events: list[str] = [] + + def _capture_audit(**kwargs): + audit_events.append(str(kwargs.get('event_type'))) + + monkeypatch.setattr( + 'app.services.shipping_notice.audit_service.append_shipping_audit_event', + _capture_audit, + ) with app.app_context(): original = _document() source_layout = record_inline_layout_snapshot(original, { @@ -313,6 +332,8 @@ def test_xfa_layout_without_source_analysis_is_not_reused(app): assert scheduled.status == 'queued' assert duplicate.current_layout_version_id is None assert ShippingXfaStructureAnalysis.query.filter_by(document_id=duplicate.id).count() == 0 + assert 'xfa_structure_analysis_reuse_rejected' in audit_events + assert 'xfa_structure_analysis_reparse_queued' in audit_events def test_layout_parser_fingerprint_change_creates_new_version_without_force(app, monkeypatch): diff --git a/backend/tests/test_shipping_generic_order_gate.py b/backend/tests/test_shipping_generic_order_gate.py index 46fdcf79..f6803bf5 100644 --- a/backend/tests/test_shipping_generic_order_gate.py +++ b/backend/tests/test_shipping_generic_order_gate.py @@ -230,11 +230,11 @@ def test_should_attempt_generic_extraction_rejects_layout_drift(): ) is False -def test_should_attempt_generic_extraction_allows_no_match_after_xfa_fallback(): - """XFA 失败回退后 match_status 来自坐标路径;no_match 允许进入通用/Dify。""" +def test_should_attempt_generic_extraction_allows_no_match_for_coordinate_path(): + """坐标路径 no_match 允许进入通用解析;structure_identity_changed 仍 fail-closed。""" assert _should_attempt_generic_extraction( match_status='no_match', - profile_result={'issues': ['xfa_mirror_collection_mismatch'], 'match': {'status': 'no_match'}}, + profile_result={'issues': [], 'match': {'status': 'no_match'}}, ) is True # 坐标路径自身的 structure_identity_changed 仍 fail-closed。 assert _should_attempt_generic_extraction( @@ -243,8 +243,8 @@ def test_should_attempt_generic_extraction_allows_no_match_after_xfa_fallback(): ) is False -def test_route_deterministic_unit_xfa_failure_falls_back_to_generic(monkeypatch): - """关键断言:XFA capability 文档失败后回退 generic_deterministic。""" +def test_route_deterministic_unit_xfa_failure_does_not_fallback_to_generic(monkeypatch): + """关键断言:XFA capability 文档正式提取失败后不回退 generic/coordinate。""" document = { 'document_id': 90, 'layout_snapshot': { @@ -304,16 +304,24 @@ def test_route_deterministic_unit_xfa_failure_falls_back_to_generic(monkeypatch) 'app.services.shipping_notice.order_extraction_workflow._route_generic_deterministic_unit', _fake_generic, ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workflow._profile_table_candidates', + lambda *_args, **_kwargs: (_ for _ in ()).throw( + AssertionError('no coordinate fallback on XFA formal failure') + ), + ) monkeypatch.setattr( 'app.services.shipping_notice.order_extraction_workflow.generic_extraction_enabled', lambda: True, ) route = route_deterministic_unit(run, unit=unit) - assert generic_called['value'] is True - assert route.decision.get('capability_kind') == 'xfa_fallback_coordinate' + assert generic_called['value'] is False + assert route.execution_mode == 'review_required' + assert route.decision.get('capability_kind') == 'xfa_dataset' + assert route.decision.get('capability_kind') != 'xfa_fallback_coordinate' assert 'xfa_dataset_missing' in ( route.decision.get('fallback_reason_codes') - or route.decision.get('xfa_fallback_reason_codes') + or route.decision.get('reason_codes') or [] ) diff --git a/backend/tests/test_shipping_processing_ownership.py b/backend/tests/test_shipping_processing_ownership.py new file mode 100644 index 00000000..e98a3341 --- /dev/null +++ b/backend/tests/test_shipping_processing_ownership.py @@ -0,0 +1,89 @@ +""" +tests/test_shipping_processing_ownership.py + +用途:验收投影不一致 fail-closed 与任务归属 ConflictError。 +依赖:processing_ownership、processing_projection_invariants、pytest、unittest.mock。 +逻辑:不要求完整履约 E2E;ownership 用 mock 链路;不一致用 reconcile 断言动作剥离。 +""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest + +from app.core.errors import ConflictError +from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership +from app.services.shipping_notice.processing_projection_invariants import ( + PROJECTION_INCONSISTENT_ERROR_CODE, + TASK_OWNERSHIP_MISMATCH_ERROR_CODE, + detect_notice_pre_create_inconsistency, + reconcile_processing_projection_facts, +) + + +def test_detect_notice_pre_create_inconsistency(): + """有正式号 + 建单前 stage → True;履约 stage → False。""" + assert detect_notice_pre_create_inconsistency( + stage='waiting_review', + shipping_notice_no='SN-1', + ) is True + assert detect_notice_pre_create_inconsistency( + stage='inventory_matching', + shipping_notice_no='SN-1', + ) is False + assert detect_notice_pre_create_inconsistency( + stage='waiting_review', + shipping_notice_no=None, + ) is False + + +def test_reconcile_marks_inconsistency_and_strips_fulfillment(): + """服务级拆链:reconcile 后断言 stage/actions/inconsistency 码。""" + payload = reconcile_processing_projection_facts({ + 'status': 'blocked', + 'stage': 'customer_resolving', + 'source_type': 'eml', + 'work_item_no': 'OT-9', + 'shipping_notice_no': 'SN-LEFT', + 'progress_version': 4, + 'current_gate': { + 'gate_code': 'customer', + 'status': 'blocked', + 'next_action_code': 'confirm_customer', + 'blocking_reason_code': 'customer_unresolved', + 'attempt_no': 1, + }, + 'available_actions': ['confirm_customer', 'match_inventory', 'download_excel'], + }, excel_ready=True) + assert payload['stage'] == 'customer_resolving' + assert payload['projection_inconsistency_code'] == PROJECTION_INCONSISTENT_ERROR_CODE + assert 'confirm_customer' in payload['available_actions'] + assert 'open_inventory_match_review' not in payload['available_actions'] + assert 'download_excel' not in payload['available_actions'] + assert len(payload['stage_nodes']) == 15 + + +def test_assert_ownership_noop_without_expected_context(): + """未传期望 OT/Case/Run 时不拦截(兼容旧客户端)。""" + task = SimpleNamespace(id=1, task_no='SN-1', order_task_id=None) + assert_notice_task_ownership(task) + + +def test_assert_ownership_mismatch_raises_conflict(app): + """期望 OT 与 Notice 挂接 OT 不一致时抛出固定错误码。""" + task = SimpleNamespace(id=7, task_no='SN-7', order_task_id=99) + linked_ot = SimpleNamespace(task_no='OT-REAL', extraction_run_id=None, candidate_id=None) + with app.app_context(): + with patch('app.services.shipping_notice.processing_ownership.db') as mock_db, \ + patch('app.services.shipping_notice.processing_ownership.append_shipping_audit_event'): + mock_db.session.get.return_value = linked_ot + mock_db.session.flush = MagicMock() + with pytest.raises(ConflictError) as exc: + assert_notice_task_ownership( + task, + expected_order_task_no='OT-OTHER', + actor_id=1, + ) + assert exc.value.code == TASK_OWNERSHIP_MISMATCH_ERROR_CODE diff --git a/backend/tests/test_shipping_processing_projection.py b/backend/tests/test_shipping_processing_projection.py index 4ec6e306..f879c397 100644 --- a/backend/tests/test_shipping_processing_projection.py +++ b/backend/tests/test_shipping_processing_projection.py @@ -1,9 +1,9 @@ """ backend/tests/test_shipping_processing_projection.py -用途:验收会话级 processing 投影分组、OT 去重与任务—PDF 两层标题规则。 -依赖:Flask/SQLite、create_order_extraction_run、project_conversation_processing。 -逻辑:构造 queued / frozen-failed / completed;断言多 PDF 不占用首文件名、hash 去重计数。 +???????? processing ?????OT ??????PDF ??????? +???Flask/SQLite?create_order_extraction_run?project_conversation_processing? +????? queued / frozen-failed / completed???? PDF ????????hash ????? """ from __future__ import annotations @@ -29,11 +29,11 @@ from tests.test_shipping_order_extraction_runs import _seed_run_input def _ensure_run_order_task(*, run, intake, document) -> None: """ - 为投影测试物化最小 Candidate + OT,并分配 Run.user_task_no。 + ????????? Candidate + OT???? Run.user_task_no? - 核心逻辑:对齐 test_shipping_conversation_processing_api 模式; - Candidate 前 Run 无持久化 OT 时不应出现 order_task 卡; - 重识别继承 OT 时走受控换绑。 + ??????? test_shipping_conversation_processing_api ??? + Candidate ? Run ???? OT ????? order_task ?? + ????? OT ??????? """ candidate = ShippingOrderCandidate.query.filter_by( order_extraction_run_id=int(run.id), @@ -63,7 +63,7 @@ def _ensure_run_order_task(*, run, intake, document) -> None: def test_project_conversation_processing_groups_and_dedupes_user_tasks(app): - """同会话多 Run 投影:按状态分组;同 OT 只保留最新。""" + """???? Run ?????????? OT ??????""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-A') run_processing, _ = create_order_extraction_run( @@ -135,10 +135,10 @@ def test_project_conversation_processing_groups_and_dedupes_user_tasks(app): completed_nos = {row['user_task_no'] for row in projection.get('completed') or []} assert run_processing.user_task_no in processing_nos assert run_failed.user_task_no in needs_nos - # 未查看的 completed 作为成功通知展示在 completed 分组。 + # ???? completed ????????? completed ??? assert run_done.user_task_no in completed_nos - # 关键断言:每个活跃 OT 只出现一次。 + # ????????? OT ?????? all_nos = list(processing_nos | needs_nos | completed_nos) assert len(all_nos) == len(set(all_nos)) == 3 @@ -148,7 +148,10 @@ def test_project_conversation_processing_groups_and_dedupes_user_tasks(app): ) assert failed_task.get('status_label') == 'failed' assert 'view_details' in (failed_task.get('available_actions') or []) - assert failed_task.get('primary_action') + primary = failed_task.get('primary_action') + assert primary + # ???cancel / view_details ???? CTA?BE-01?? + assert primary not in {'cancel_task', 'cancel_run', 'view_details'} done_task = next( row for row in projection['completed'] @@ -158,8 +161,12 @@ def test_project_conversation_processing_groups_and_dedupes_user_tasks(app): assert done_task.get('group') == 'completed' -def test_fingerprint_merge_prefers_newer_processing_over_older_failed(app): - """BE-02:同指纹旧失败 + 新处理中,必须展示新 Run。""" +def test_same_attachment_fingerprint_across_ots_keeps_two_cards(app): + """ + BE-02(产品选择 A):不同 user_task_no 即使附件指纹相同,也各出一张卡。 + + 断言:failed OT + processing OT 同 content_hash → 两张卡;total_tasks == 2。 + """ with app.app_context(): from app.models import FileAsset, ShippingOrderDocument, ShippingOrderIntake from datetime import timedelta @@ -227,13 +234,17 @@ def test_fingerprint_merge_prefers_newer_processing_over_older_failed(app): conversation_id=session.session_id, ) shown = projection['processing'] + projection['needs_action'] - assert len(shown) == 1 - assert shown[0]['user_task_no'] == newer.user_task_no - assert shown[0]['run_no'] == newer.run_no + shown_nos = {row['user_task_no'] for row in shown} + # 跨 OT 同指纹不得折叠:两张独立卡。 + assert len(shown) == 2 + assert shown_nos == {'OT-OLD-FAIL', 'OT-NEW-PROC'} + assert projection['summary']['total_tasks'] == 2 + assert projection['summary']['needs_action'] == 1 + assert projection['summary']['processing'] == 1 def test_completed_current_run_hidden_after_viewed(app): - """UI-04:当前 completed 查看后从右侧收起。""" + """UI-04??? completed ?????????""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-DONE') run, _ = create_order_extraction_run( @@ -262,10 +273,14 @@ def test_completed_current_run_hidden_after_viewed(app): ) shown = after['processing'] + after['needs_action'] + list(after.get('completed') or []) assert all(row['user_task_no'] != run.user_task_no for row in shown) + # ?????? completed ?? history????????? + history_nos = {row['user_task_no'] for row in (after.get('history') or [])} + assert run.user_task_no in history_nos + assert after['summary']['history'] >= 1 def _set_run_documents(run, documents: list[dict]) -> None: - """覆盖 Run 快照 documents,便于断言任务—PDF 两层投影。""" + """?? Run ?? documents????????PDF ?????""" snapshot = dict(run.input_snapshot_json or {}) intakes = list(snapshot.get('intakes') or []) if not intakes: @@ -277,8 +292,8 @@ def _set_run_documents(run, documents: list[dict]) -> None: run.request_snapshot_json = snapshot -def test_single_pdf_task_uses_filename_title(app): - """单 PDF 任务:title 为文件名,file_count=1,display_kind=single。""" +def test_single_pdf_task_title_is_none_for_frontend_unified_label(app): + """BE-05?? PDF ?? title ?? None?????? document_names / objects?""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-1PDF') run, _ = create_order_extraction_run( @@ -306,16 +321,18 @@ def test_single_pdf_task_uses_filename_title(app): row for row in projection['processing'] + projection['needs_action'] if row['user_task_no'] == run.user_task_no ) - assert task['title'] == 'only.pdf' + # ???????????????????????????? title? + assert task['title'] is None assert task['file_count'] == 1 assert task['display_kind'] == 'single_document_task' + assert task.get('document_names') == ['only.pdf'] doc_objects = [obj for obj in (task.get('objects') or []) if obj.get('kind') == 'document'] assert len(doc_objects) == 1 assert doc_objects[0]['filename'] == 'only.pdf' def test_multi_pdf_task_does_not_use_first_filename_as_title(app): - """多 PDF 任务:title 为空,file_count=2,objects 含两个当前 PDF。""" + """? PDF ???title ???file_count=2?objects ????? PDF?""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-2PDF') run, _ = create_order_extraction_run( @@ -362,7 +379,11 @@ def test_multi_pdf_task_does_not_use_first_filename_as_title(app): def test_partial_reparse_keeps_unaffected_pdf_from_source_run(app): - """同 OT 局部重识别:新版 PDF 替换自身,旧 Run 中未重识别 PDF 继续有效。""" + """ + BE-03:同 OT 局部重识别——被替代 Run 不另开顶层卡;有效 PDF 仍折叠保留。 + + 断言:同一 user_task_no 仅一张卡;total_tasks == 1;未重识别 PDF 来自源 Run。 + """ with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-PARTIAL-REPARSE') source, _ = create_order_extraction_run( @@ -412,7 +433,7 @@ def test_partial_reparse_keeps_unaffected_pdf_from_source_run(app): ) replacement.reparse_of_run_id = source.id replacement.reparse_reason = 'field_mapping_error' - # 投影用例无 Case 标记:用同 content_hash 满足严格文档谱系校验。 + # 共享 content_hash,确保同 OT 谱系可交叉识别 PDF 身份。 shared_hash = str(document.content_hash or 'hash-partial-shared') document.content_hash = shared_hash replacement_document.content_hash = shared_hash @@ -437,13 +458,21 @@ def test_partial_reparse_keeps_unaffected_pdf_from_source_run(app): user_id=user.id, conversation_id=session.session_id, ) - task = next( - row for row in projection['processing'] + projection['needs_action'] - if row['user_task_no'] == source.user_task_no + all_cards = ( + projection['processing'] + + projection['needs_action'] + + list(projection.get('completed') or []) + + list(projection.get('history') or []) ) + # BE-03:被替代 Run 不另开顶层卡;同 OT 仅一张。 + matching = [row for row in all_cards if row['user_task_no'] == source.user_task_no] + assert len(matching) == 1 + assert projection['summary']['total_tasks'] == 1 + task = matching[0] + assert task['run_no'] == replacement.run_no doc_objects = [obj for obj in task['objects'] if obj.get('kind') == 'document'] - # 关键断言:任务仍是两份 PDF;每份 PDF 保留其当前生效版本所属 Run。 + # 局部重识别后:有效 PDF 仍为 2;未触碰 PDF 保留源 Run 版本。 assert task['file_count'] == 2 assert task['title'] is None assert task['display_kind'] == 'multi_document_task' @@ -456,7 +485,7 @@ def test_partial_reparse_keeps_unaffected_pdf_from_source_run(app): def test_same_filename_different_hash_counts_as_two_pdfs(app): - """同名不同 hash:file_count=2,不得按文件名误合并。""" + """???? hash?file_count=2???????????""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SAME-NAME') run, _ = create_order_extraction_run( @@ -496,7 +525,7 @@ def test_same_filename_different_hash_counts_as_two_pdfs(app): def test_same_hash_different_document_id_counts_as_one_pdf(app): - """同 hash 不同 document_id(重传):file_count=1。""" + """? hash ?? document_id?????file_count=1?""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SAME-HASH') run, _ = create_order_extraction_run( @@ -535,14 +564,15 @@ def test_same_hash_different_document_id_counts_as_one_pdf(app): ) assert task['file_count'] == 1 assert task['display_kind'] == 'single_document_task' - assert task['title'] == 'order.pdf' + # BE-05: title ?? None?? hash ??????????? + assert task['title'] is None doc_objects = [obj for obj in (task.get('objects') or []) if obj.get('kind') == 'document'] assert len(doc_objects) == 1 assert doc_objects[0]['document_id'] == 22 def test_sparse_snapshot_enriched_by_extraction_units(app): - """快照仅 1 PDF 但 Unit 已拆 2 份时,投影须 multi + file_count=2。""" + """??? 1 PDF ? Unit ?? 2 ?????? multi + file_count=2?""" from app.models import ( FileAsset, ShippingOrderDocument, @@ -589,7 +619,7 @@ def test_sparse_snapshot_enriched_by_extraction_units(app): keep_input_open=True, ) _ensure_run_order_task(run=run, intake=intake, document=document) - # 故意只写 1 份进快照,模拟生产侧栏仍显示单文件名的脏数据。 + # ???? 1 ??????????????????????? _set_run_documents(run, [{ 'document_id': int(document.id), 'root_document_id': int(document.id), @@ -630,7 +660,7 @@ def test_sparse_snapshot_enriched_by_extraction_units(app): @pytest.mark.skip(reason='workflow ledger removed') def test_sparse_snapshot_enriched_by_workflow_items(app): - """快照仅 1 PDF 但同 Run 已有 2 个 WorkflowItem 时,投影须 multi。""" + """??? 1 PDF ?? Run ?? 2 ? WorkflowItem ????? multi?""" with app.app_context(): user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SPARSE-W') from app.models import FileAsset, ShippingOrderDocument @@ -715,3 +745,95 @@ def test_sparse_snapshot_enriched_by_workflow_items(app): assert task['display_kind'] == 'multi_document_task' assert task['title'] is None assert 'peer.pdf' in (task.get('document_names') or []) + + +def test_primary_action_falls_back_to_focus_task_never_cancel(app, monkeypatch): + """BE-01: no business entry -> primary_action=focus_task; never cancel/view_details.""" + with app.app_context(): + from app.services.shipping_notice import conversation_processing_projection as proj_mod + from app.services.shipping_notice import order_extraction_workspace_projection as ws_mod + + user, agent, session, intake, document = _seed_run_input(suffix='PROJ-FOCUS') + 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, + ) + _ensure_run_order_task(run=run, intake=intake, document=document) + db.session.commit() + + monkeypatch.setattr( + ws_mod, + '_run_available_actions', + lambda _run, _units: ['cancel_run', 'view_details'], + ) + primary, actions = proj_mod._resolve_task_actions(run) + assert primary == 'focus_task' + assert 'focus_task' in actions + assert 'view_details' in actions + assert 'cancel_task' in actions or 'cancel_run' in actions + assert primary not in {'cancel_task', 'cancel_run', 'view_details'} + + +def test_summary_has_more_and_returned_metadata_when_truncated(app): + """BE-04: after list truncate, summary keeps full counts + has_more/returned.""" + with app.app_context(): + user, agent, session, intake_a, document_a = _seed_run_input(suffix='PROJ-T0') + run_a, _ = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake_a.intake_no], + keep_input_open=True, + ) + _ensure_run_order_task(run=run_a, intake=intake_a, document=document_a) + run_a.status = 'processing' + run_a.phase = 'extracting' + db.session.commit() + + for suffix, agent_code in ( + ('PROJ-T1', 'shipping_notice_proj_t1'), + ('PROJ-T2', 'shipping_notice_proj_t2'), + ('PROJ-T3', 'shipping_notice_proj_t3'), + ): + _, _, _, intake_x, document_x = _seed_run_input(suffix=suffix, agent_code=agent_code) + intake_x.user_id = user.id + intake_x.conversation_id = session.session_id + db.session.commit() + run_x, _ = create_order_extraction_run( + user=user, + agent_id=agent.id, + conversation_id=session.session_id, + intake_nos=[intake_x.intake_no], + allow_parallel_conversation_runs=True, + keep_input_open=True, + ) + _ensure_run_order_task(run=run_x, intake=intake_x, document=document_x) + run_x.status = 'processing' + run_x.phase = 'extracting' + db.session.commit() + + projection = project_conversation_processing( + user_id=user.id, + conversation_id=session.session_id, + limit=2, + history_limit=1, + ) + summary = projection['summary'] + returned_active = ( + len(projection['needs_action']) + + len(projection['processing']) + + len(projection.get('completed') or []) + ) + # Assert: full counts stay ahead of returned lists; truncate flags match. + assert summary['total_tasks'] >= 4 + assert summary['total_tasks'] >= returned_active + assert summary.get('returned', {}).get('needs_action') == len(projection['needs_action']) + assert summary.get('returned', {}).get('processing') == len(projection['processing']) + assert summary.get('returned', {}).get('completed') == len(projection.get('completed') or []) + assert summary.get('returned', {}).get('history') == len(projection.get('history') or []) + assert summary.get('has_more_active') is True + assert summary.get('truncated', {}).get('active') is True + assert returned_active == 2 diff --git a/backend/tests/test_shipping_review_workbench_state_isolation.py b/backend/tests/test_shipping_review_workbench_state_isolation.py new file mode 100644 index 00000000..d82f7215 --- /dev/null +++ b/backend/tests/test_shipping_review_workbench_state_isolation.py @@ -0,0 +1,239 @@ +""" +tests/test_shipping_review_workbench_state_isolation.py + +用途:锁定复核工作台状态隔离契约——profile_match 管理员裁剪、automation 资格分层、 + Validation Snapshot 身份字段、用户 Gate 不把客户确认/技术 pending 当优先处理。 +依赖:pytest、order_review_projection、process_gate_projection、types.SimpleNamespace。 +逻辑:纯单元/轻量投影测试;不启 Flask 全应用。 +""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import patch + +from app.services.shipping_notice.order_review_projection import ( + _project_case_automation_status, +) +from app.services.shipping_notice.process_gate_projection import project_user_gate_summary + + +def test_automation_waiting_to_start_when_eligible_but_not_queued(): + """资格达标且未建单时只能是 waiting_to_start,不得伪装 running。""" + case = SimpleNamespace( + status='ready', + confirmed_task_id=None, + document_id=10, + current_draft=SimpleNamespace(draft_version=1, updated_at=None), + run=SimpleNamespace(run_no='RUN-1'), + updated_at=None, + ) + with patch( + 'app.services.shipping_notice.order_stp_auto_create_service.find_active_stp_job', + return_value=None, + ), patch( + 'app.services.shipping_notice.order_review_projection._stp_waiting_timeout_seconds', + return_value=3600, + ): + result = _project_case_automation_status( + case, + validation={'can_build': True, 'can_auto_create': True}, + post_confirm=None, + ) + assert result['status'] == 'waiting_to_start' + assert result['retryable'] is False + assert result['task_no'] is None + + +def test_automation_queued_when_stp_job_exists(): + """存在 queued STP Job 时投影 queued,不得停留在 waiting_to_start。""" + case = SimpleNamespace( + status='ready', + confirmed_task_id=None, + document_id=10, + current_draft=SimpleNamespace(draft_version=2, updated_at=None), + run=SimpleNamespace(run_no='RUN-1'), + updated_at=None, + ) + job = SimpleNamespace(id=99, status='queued') + with patch( + 'app.services.shipping_notice.order_stp_auto_create_service.find_active_stp_job', + return_value=job, + ): + result = _project_case_automation_status( + case, + validation={'can_build': True, 'can_auto_create': True}, + post_confirm=None, + ) + assert result['status'] == 'queued' + assert result['job_id'] == 99 + assert result['retryable'] is False + + +def test_automation_failed_retryable_when_post_confirm_needs_retry(): + """确认后推进失败必须可重试,不能只显示已确认。""" + case = SimpleNamespace(status='confirmed', confirmed_task_id=12) + result = _project_case_automation_status( + case, + validation={'can_build': True, 'can_auto_create': True}, + post_confirm={ + 'task_no': 'SN-1', + 'needs_retry': True, + 'status': 'needs_retry', + 'task_process_status': 'created', + }, + ) + assert result['status'] == 'failed' + assert result['retryable'] is True + assert result['task_no'] == 'SN-1' + + +def test_serialize_review_case_hides_profile_match_for_non_admin(): + """普通用户不得收到模板 ID / 候选分;仅 admin_only 占位。""" + from app.services.shipping_notice.order_review_projection import serialize_review_case + + case = SimpleNamespace( + id=1, + case_no='SORC-1', + run_id=1, + unit_id=None, + document_id=10, + candidate_id=None, + status='ready', + disposition=None, + confirmed_task_id=None, + current_draft=None, + run=SimpleNamespace( + run_no='RUN-1', + schema_version_id=1, + input_snapshot_json={'schema': {'definition': {'fields': []}}, 'documents': []}, + ), + ) + + with patch( + 'app.services.shipping_notice.order_review_customer_service.project_review_case_customer_resolution', + return_value={'resolved': True}, + ), patch( + 'app.services.shipping_notice.order_review_field_conflict_service.project_review_case_field_conflicts', + return_value=[], + ), patch( + 'app.services.shipping_notice.order_review_duplicate_service.project_review_case_duplicate', + return_value={'needs_adjudication': False}, + ), patch( + 'app.services.shipping_notice.order_review_reservation_service.project_review_case_reservation', + return_value=None, + ), patch( + 'app.services.shipping_notice.order_review_fulfillment_decision_service.project_review_case_line_decisions', + return_value=None, + ), patch( + 'app.services.shipping_notice.order_task_service.resolve_order_task_for_candidate', + return_value=None, + ), patch( + 'app.services.shipping_notice.order_review_projection.db', + ) as mock_db, patch( + 'app.models.ShippingProcessExecution', + ) as mock_exec: + mock_db.session.get.return_value = None + mock_exec.query.filter_by.return_value.order_by.return_value.first.return_value = None + payload = serialize_review_case(case, is_admin=False) + + assert payload['profile_match']['available'] is False + assert payload['profile_match']['visibility'] == 'admin_only' + assert payload['profile_match'].get('candidates') == [] + assert payload['automation']['status'] in {'idle', 'waiting_to_start'} + + +def test_serialize_review_case_exposes_profile_match_for_admin(): + """管理员 is_admin=True 时须拿到完整 profile_match(UI-04 API 契约)。""" + from app.services.shipping_notice.order_review_projection import serialize_review_case + + case = SimpleNamespace( + id=2, + case_no='SORC-2', + run_id=2, + unit_id=None, + document_id=11, + candidate_id=None, + status='ready', + disposition=None, + confirmed_task_id=None, + current_draft=None, + run=SimpleNamespace( + run_no='RUN-2', + schema_version_id=1, + input_snapshot_json={'schema': {'definition': {'fields': []}}, 'documents': []}, + ), + ) + admin_payload = { + 'available': True, + 'visibility': 'admin', + 'status': 'matched', + 'candidates': [{'profile_id': 9, 'score': 0.91}], + 'selected_profile': {'profile_id': 9, 'profile_code': 'P9'}, + } + + with patch( + 'app.services.shipping_notice.order_review_customer_service.project_review_case_customer_resolution', + return_value={'resolved': True}, + ), patch( + 'app.services.shipping_notice.order_review_field_conflict_service.project_review_case_field_conflicts', + return_value=[], + ), patch( + 'app.services.shipping_notice.order_review_duplicate_service.project_review_case_duplicate', + return_value={'needs_adjudication': False}, + ), patch( + 'app.services.shipping_notice.order_review_reservation_service.project_review_case_reservation', + return_value=None, + ), patch( + 'app.services.shipping_notice.order_review_fulfillment_decision_service.project_review_case_line_decisions', + return_value=None, + ), patch( + 'app.services.shipping_notice.order_task_service.resolve_order_task_for_candidate', + return_value=None, + ), patch( + 'app.services.shipping_notice.order_review_profile_match_service.project_review_case_profile_match', + return_value=admin_payload, + ), patch( + 'app.services.shipping_notice.order_review_projection.db', + ) as mock_db, patch( + 'app.models.ShippingProcessExecution', + ) as mock_exec: + mock_db.session.get.return_value = None + mock_exec.query.filter_by.return_value.order_by.return_value.first.return_value = None + payload = serialize_review_case(case, is_admin=True) + + assert payload['profile_match']['available'] is True + assert payload['profile_match']['visibility'] == 'admin' + assert payload['profile_match']['candidates'][0]['profile_id'] == 9 + + +def test_project_user_gate_summary_clears_stale_confirm_customer(monkeypatch): + """无阻断时不得残留 confirm_customer 下一步。""" + execution = SimpleNamespace(execution_no='EX-1', id=1) + + def fake_serialize(_execution, include_diagnostics=False): + return { + 'execution_no': 'EX-1', + 'status': 'running', + 'current_gate': { + 'gate_code': 'document_materialization', + 'status': 'pending', + 'blocking_reason_code': None, + }, + 'primary_next_action_code': 'confirm_customer', + 'responsible_party': 'system', + 'gates': [], + } + + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_projection.serialize_process_execution', + fake_serialize, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_projection._execution_navigation_refs', + lambda _e: {'case_no': 'SORC-1', 'review_case_no': 'SORC-1', 'review_run_no': 'RUN-1'}, + ) + + summary = project_user_gate_summary(execution) + assert summary['current_blocking_gate'] is None + assert summary['next_action_code'] is None diff --git a/backend/tests/test_shipping_stp_auto_create_api_integration.py b/backend/tests/test_shipping_stp_auto_create_api_integration.py new file mode 100644 index 00000000..abb880ea --- /dev/null +++ b/backend/tests/test_shipping_stp_auto_create_api_integration.py @@ -0,0 +1,287 @@ +""" +tests/test_shipping_stp_auto_create_api_integration.py + +用途:STP 自动建单可重复集成验收——真实 ORM enqueue、Flask Client retry、 + GET 无副作用、failed→retry_of、active 唯一语义。 +依赖:pytest app fixture、Job 模型、order review 测试夹具、parse_api_*。 +逻辑:资格校验可 stub(聚焦入队闭环);enqueue/Job/API 必须真实落库。 +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from unittest.mock import patch + +import pytest + +from app import db +from app.models import Job, User +from app.services.shipping_notice.order_review_service import ensure_run_review_cases +from app.services.shipping_notice.order_stp_auto_create_service import ( + SHIPPING_STP_JOB_DOMAIN, + build_stp_idempotency_key, +) +from tests.conftest import parse_api_data, parse_api_error +from tests.test_shipping_order_extraction_runs import _seed_run_input +from tests.test_shipping_order_review_service import _materialized_run + + +def _eligible_validation() -> dict: + return { + 'status': 'ready', + 'can_build': True, + 'can_auto_create': True, + 'failed_gates': [], + 'issues': [], + 'validated_at': datetime.now(timezone.utc).isoformat(), + 'validation_checksum': 'stp-api-itest-v1', + } + + +def _count_stp_jobs(business_ref: str) -> int: + return int( + Job.query.filter_by( + domain=SHIPPING_STP_JOB_DOMAIN, + job_type='shipping_stp_auto_create', + business_ref=business_ref, + ).count() + ) + + +def _active_stp_jobs(business_ref: str) -> list[Job]: + return ( + Job.query.filter( + Job.domain == SHIPPING_STP_JOB_DOMAIN, + Job.job_type == 'shipping_stp_auto_create', + Job.business_ref == business_ref, + Job.status.in_(('queued', 'running')), + ) + .order_by(Job.id.asc()) + .all() + ) + + +def _seed_eligible_case(app, *, suffix: str): + """创建可登录 owner + eligible Case(资格由 _validation stub 保证)。""" + from app.services.shipping_notice.order_extraction_run_service import ( + transition_order_extraction_run, + ) + + user, agent, session, intake, _document = _seed_run_input(suffix=suffix) + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + run.run_no = f'SNER-ITEST-{suffix}' + transition_order_extraction_run(run, target_status='processing') + transition_order_extraction_run(run, target_status='review_required', result={}) + case = ensure_run_review_cases(run=run)[0] + draft = case.current_draft + assert draft is not None + draft.validation_result_json = _eligible_validation() + draft.issue_summary_json = [] + case.status = 'ready' + db.session.commit() + return user, run, case, draft + + +@pytest.fixture +def stp_eligibility_stubs(monkeypatch): + """真实 enqueue 前提下 stub 资格评估,避免耦合完整 Gate 链。""" + from app.services.shipping_notice import order_stp_auto_create_service as svc + + monkeypatch.setattr(svc, '_validation', lambda _case: _eligible_validation()) + monkeypatch.setattr(svc, '_persist_case_candidate_qualification', lambda **_kwargs: None) + monkeypatch.setattr(svc, '_is_xfa_case', lambda **_kwargs: False) + monkeypatch.setattr(svc, '_draft_has_manual_edits', lambda _case: False) + monkeypatch.setattr(svc, 'record_fulfillment_audit', lambda **_kwargs: None) + + +def test_stp_retry_api_enqueues_reuses_and_get_has_no_side_effect(app, stp_eligibility_stubs): + """Flask Client POST retry:真实 Job、幂等复用、GET 不入队。""" + with app.app_context(): + user, run, case, draft = _seed_eligible_case(app, suffix='STPAPI1') + business_ref = build_stp_idempotency_key( + run_no=str(run.run_no), + document_id=int(case.document_id), + draft_version=int(draft.draft_version), + ) + before = _count_stp_jobs(business_ref) + + from app.core.auth.jwt import issue_local_access_token + + client = app.test_client() + headers = {'Authorization': f'Bearer {issue_local_access_token(user)}'} + + get_before = client.get( + f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}', + headers=headers, + ) + assert get_before.status_code == 200 + assert _count_stp_jobs(business_ref) == before + + first = client.post( + f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/stp-auto-create/retry', + headers=headers, + ) + assert first.status_code == 200 + first_body = first.get_json() + first_data = parse_api_data(first_body) + assert first_body.get('success') is True + assert first_data['status'] in {'queued', 'reused'} + assert first_data['job_id'] + assert first_data['business_ref'] == business_ref + assert _count_stp_jobs(business_ref) == before + 1 + assert len(_active_stp_jobs(business_ref)) == 1 + job_id = int(first_data['job_id']) + + second = client.post( + f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/stp-auto-create/retry', + headers=headers, + ) + assert second.status_code == 200 + second_data = parse_api_data(second.get_json()) + assert second_data['status'] == 'reused' + assert int(second_data['job_id']) == job_id + assert second_data['business_ref'] == business_ref + assert len(_active_stp_jobs(business_ref)) == 1 + assert _count_stp_jobs(business_ref) == before + 1 + + get_after = client.get( + f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}', + headers=headers, + ) + assert get_after.status_code == 200 + assert _count_stp_jobs(business_ref) == before + 1 + + +def test_stp_retry_api_failed_job_creates_retry_of_chain(app, stp_eligibility_stubs): + """failed Job 后 retry 生成新 Job 并写入 retry_of_job_id,仅一个 active。""" + with app.app_context(): + user, run, case, draft = _seed_eligible_case(app, suffix='STPAPI2') + business_ref = build_stp_idempotency_key( + run_no=str(run.run_no), + document_id=int(case.document_id), + draft_version=int(draft.draft_version), + ) + from app.core.auth.jwt import issue_local_access_token + + client = app.test_client() + headers = {'Authorization': f'Bearer {issue_local_access_token(user)}'} + first = client.post( + f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/stp-auto-create/retry', + headers=headers, + ) + first_data = parse_api_data(first.get_json()) + old_id = int(first_data['job_id']) + old = db.session.get(Job, old_id) + assert old is not None + old.status = 'failed' + old.message = 'itest forced failed' + db.session.commit() + + retry = client.post( + f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/stp-auto-create/retry', + headers=headers, + ) + assert retry.status_code == 200 + retry_data = parse_api_data(retry.get_json()) + assert retry_data['status'] == 'queued' + new_id = int(retry_data['job_id']) + assert new_id != old_id + assert int(retry_data.get('retry_of_job_id') or 0) == old_id + assert retry_data['business_ref'] == business_ref + active = _active_stp_jobs(business_ref) + assert len(active) == 1 + assert int(active[0].id) == new_id + retained = db.session.get(Job, old_id) + assert retained is not None + assert retained.status == 'failed' + + +def test_stp_retry_api_confirmed_returns_localized_code(app, stp_eligibility_stubs): + """已 confirmed Case 的 retry 返回 SHIPPING.STP_RETRY_ALREADY_CONFIRMED envelope。""" + with app.app_context(): + user, _run, case, _draft = _seed_eligible_case(app, suffix='STPAPI3') + case.status = 'confirmed' + case.confirmed_task_id = 1 + db.session.commit() + from app.core.auth.jwt import issue_local_access_token + + client = app.test_client() + headers = {'Authorization': f'Bearer {issue_local_access_token(user)}'} + response = client.post( + f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/stp-auto-create/retry', + headers=headers, + ) + assert response.status_code == 409 + error = parse_api_error(response.get_json()) + assert error.get('code') == 'SHIPPING.STP_RETRY_ALREADY_CONFIRMED' + + +def test_stp_retry_api_not_eligible_uses_shipping_stp_code(app, monkeypatch): + """资格失败时顶层 code 必须为 SHIPPING.STP_NOT_ELIGIBLE,细粒度进 details。""" + from app.services.shipping_notice import order_stp_auto_create_service as svc + + with app.app_context(): + user, _run, case, _draft = _seed_eligible_case(app, suffix='STPAPI4') + monkeypatch.setattr( + svc, + 'ensure_stp_auto_create_for_case', + lambda **_kwargs: { + 'status': 'skipped_needs_review', + 'error_code': 'xfa_shadow_mode', + 'blocking_reason_codes': ['xfa_shadow_mode'], + 'job_id': None, + }, + ) + from app.core.auth.jwt import issue_local_access_token + + client = app.test_client() + headers = {'Authorization': f'Bearer {issue_local_access_token(user)}'} + response = client.post( + f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/stp-auto-create/retry', + headers=headers, + ) + assert response.status_code == 400 + error = parse_api_error(response.get_json()) + assert error.get('code') == 'SHIPPING.STP_NOT_ELIGIBLE' + details = error.get('details') or {} + assert 'xfa_shadow_mode' in list(details.get('blocking_reason_codes') or []) + + +@pytest.mark.postgres +def test_stp_active_partial_unique_on_postgres(app, stp_eligibility_stubs): + """PostgreSQL 部分唯一索引:同 business_ref 第二次插入不得产生第二个 active Job。""" + with app.app_context(): + if db.engine.dialect.name != 'postgresql': + pytest.skip('requires PostgreSQL') + user, run, case, draft = _seed_eligible_case(app, suffix='STPPG1') + business_ref = build_stp_idempotency_key( + run_no=str(run.run_no), + document_id=int(case.document_id), + draft_version=int(draft.draft_version), + ) + from app.jobs.queue import enqueue + from app.jobs.types import JobType + + first_id = enqueue( + JobType.SHIPPING_STP_AUTO_CREATE, + {'case_no': case.case_no}, + domain=SHIPPING_STP_JOB_DOMAIN, + business_ref=business_ref, + created_by_id=int(user.id), + message='pg unique first', + commit=True, + ) + # 关闭应用层 dedupe,仅依赖部分唯一索引 + IntegrityError 回落。 + second_id = enqueue( + JobType.SHIPPING_STP_AUTO_CREATE, + {'case_no': case.case_no}, + domain=SHIPPING_STP_JOB_DOMAIN, + business_ref=business_ref, + created_by_id=int(user.id), + message='pg unique second', + dedupe_statuses=(), + dedupe_active=False, + commit=True, + ) + assert int(second_id) == int(first_id) + assert len(_active_stp_jobs(business_ref)) == 1 diff --git a/backend/tests/test_shipping_stp_auto_create_enqueue.py b/backend/tests/test_shipping_stp_auto_create_enqueue.py new file mode 100644 index 00000000..c355a532 --- /dev/null +++ b/backend/tests/test_shipping_stp_auto_create_enqueue.py @@ -0,0 +1,172 @@ +""" +tests/test_shipping_stp_auto_create_enqueue.py + +用途:锁定 STP 自动建单入队 / 显式重试 / Projection / retry_of_job_id 契约。 +依赖:pytest、order_stp_auto_create_service、Job 模型、unittest.mock。 +逻辑:不依赖 Worker 消费;覆盖幂等复用、failed→retry 新 Job、GET 无入队副作用断言辅助。 +""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest + + +def test_ensure_stp_reuses_active_job_without_duplicate(app): + """queued/running 时复用同一 Job,不得再 enqueue。""" + from app.services.shipping_notice import order_stp_auto_create_service as svc + + case = SimpleNamespace( + id=1, + case_no='SORC-STP-1', + status='ready', + confirmed_task_id=None, + document_id=10, + candidate_id=None, + disposition=None, + run_id=1, + run=SimpleNamespace(run_no='SNER-TEST-1', id=1), + owner_user_id=1, + current_draft=SimpleNamespace( + draft_version=2, + validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'}, + issue_summary_json=[], + ), + ) + active = SimpleNamespace(id=77, status='queued', retry_of_job_id=None) + + with patch.object(svc, '_persist_case_candidate_qualification', return_value=None), patch.object( + svc, '_is_xfa_case', return_value=False, + ), patch.object(svc, '_draft_has_manual_edits', return_value=False), patch.object( + svc, 'build_stp_idempotency_key', return_value='stp-auto:SNER-TEST-1:doc-10:v2', + ), patch.object(svc, 'find_active_stp_job', return_value=active), patch.object( + svc, 'find_latest_stp_job', return_value=active, + ), patch.object(svc, 'enqueue') as enqueue_mock, patch.object(svc, 'record_fulfillment_audit'), patch.object( + svc, 'db', + ): + result = svc.ensure_stp_auto_create_for_case(case=case, commit=False) + + assert result['status'] in {'reused', 'already_queued', 'queued'} + assert result['job_id'] == 77 + enqueue_mock.assert_not_called() + + +def test_ensure_stp_force_retry_keeps_failed_and_sets_retry_of(app): + """force_retry 时保留 failed Job,新建 Job 并挂 retry_of_job_id。""" + from app.services.shipping_notice import order_stp_auto_create_service as svc + + case = SimpleNamespace( + id=2, + case_no='SORC-STP-2', + status='ready', + confirmed_task_id=None, + document_id=11, + candidate_id=None, + disposition=None, + run_id=2, + run=SimpleNamespace(run_no='SNER-TEST-2', id=2), + owner_user_id=1, + current_draft=SimpleNamespace( + draft_version=1, + validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'}, + issue_summary_json=[], + ), + ) + failed = SimpleNamespace(id=50, status='failed', retry_of_job_id=None) + new_job = SimpleNamespace(id=51, status='queued', retry_of_job_id=None) + + def _enqueue(*args, **kwargs): + del args, kwargs + return 51 + + with patch.object(svc, '_persist_case_candidate_qualification', return_value=None), patch.object( + svc, '_is_xfa_case', return_value=False, + ), patch.object(svc, '_draft_has_manual_edits', return_value=False), patch.object( + svc, 'build_stp_idempotency_key', return_value='stp-auto:SNER-TEST-2:doc-11:v1', + ), patch.object(svc, 'find_active_stp_job', return_value=None), patch.object( + svc, 'find_latest_stp_job', return_value=failed, + ), patch.object(svc, 'enqueue', side_effect=_enqueue), patch.object( + svc, 'record_fulfillment_audit', + ), patch.object(svc, 'db') as mock_db: + mock_db.session.get.return_value = new_job + mock_db.session.flush = MagicMock() + result = svc.ensure_stp_auto_create_for_case(case=case, commit=False, force_retry=True) + + assert result['status'] == 'queued' + assert result['job_id'] == 51 + assert result.get('retry_of_job_id') == 50 + assert new_job.retry_of_job_id == 50 + + +def test_retry_stp_auto_create_for_case_rejects_confirmed(app): + """已 confirmed Case 不得走 STP retry,须走确认后推进重试。""" + from app.core.errors import ConflictError + from app.services.shipping_notice import order_stp_auto_create_service as svc + + case = SimpleNamespace( + case_no='SORC-STP-3', + status='confirmed', + confirmed_task_id=9, + ) + with patch( + 'app.services.shipping_notice.order_review_service.get_review_case_visible_to_user', + return_value=case, + ): + with pytest.raises(ConflictError) as exc: + svc.retry_stp_auto_create_for_case(user_id=1, case_no='SORC-STP-3') + assert exc.value.code == 'SHIPPING.STP_RETRY_ALREADY_CONFIRMED' + + +def test_retry_stp_raises_structured_error_when_enqueue_not_queued(app): + """入队失败必须抛业务错误,禁止伪装成功。""" + from app.core.errors import ValidationError + from app.services.shipping_notice import order_stp_auto_create_service as svc + + case = SimpleNamespace( + case_no='SORC-STP-4', + status='ready', + confirmed_task_id=None, + ) + with patch( + 'app.services.shipping_notice.order_review_service.get_review_case_visible_to_user', + return_value=case, + ), patch.object( + svc, + 'ensure_stp_auto_create_for_case', + return_value={'status': 'not_eligible', 'error_code': 'SHIPPING.STP_NOT_ELIGIBLE', 'job_id': None}, + ): + with pytest.raises(ValidationError) as exc: + svc.retry_stp_auto_create_for_case(user_id=1, case_no='SORC-STP-4') + assert 'SHIPPING.STP' in str(exc.value.code) + assert exc.value.code == 'SHIPPING.STP_NOT_ELIGIBLE' + + +def test_automation_projection_uses_active_job_over_failed_history(app): + """Projection 只认当前有效 Job;failed 历史不得冒充 queued。""" + from app.services.shipping_notice.order_review_projection import _project_case_automation_status + + case = SimpleNamespace( + status='ready', + confirmed_task_id=None, + document_id=10, + current_draft=SimpleNamespace(draft_version=2, updated_at=None), + run=SimpleNamespace(run_no='RUN-P'), + updated_at=None, + ) + active = SimpleNamespace(id=88, status='queued', retry_of_job_id=50) + with patch( + 'app.services.shipping_notice.order_stp_auto_create_service.find_active_stp_job', + return_value=active, + ), patch( + 'app.services.shipping_notice.order_stp_auto_create_service.find_latest_stp_job', + return_value=SimpleNamespace(id=50, status='failed'), + ): + result = _project_case_automation_status( + case, + validation={'can_build': True, 'can_auto_create': True}, + post_confirm=None, + ) + assert result['status'] == 'queued' + assert result['job_id'] == 88 diff --git a/backend/tests/test_shipping_workbench_action_contract.py b/backend/tests/test_shipping_workbench_action_contract.py new file mode 100644 index 00000000..a92e35b0 --- /dev/null +++ b/backend/tests/test_shipping_workbench_action_contract.py @@ -0,0 +1,201 @@ +""" +tests/test_shipping_workbench_action_contract.py + +用途:订单处理工作台动作契约——表驱动全量码 + 关键写链阶段族约束。 +依赖:processing_projection_invariants、progress_audit_contract、pytest。 +逻辑:不连库;断言每个合法 action_code 可规范化到意图;建单前剔除履约动作; + 关键写链在 post_create 投影中保留并可映射。 +""" + +from __future__ import annotations + +import pytest + +from app.services.shipping_notice.processing_projection_invariants import ( + derive_available_actions, + normalize_action_code, + reconcile_processing_projection_facts, +) +from app.services.shipping_notice.progress_audit_contract import ( + SHIPPING_PROCESSING_ACTION_INTENTS, +) + +# action_code → (intent, stage_family, review_behavior) +# stage_family: pre_create | post_create | any | terminal +# review_behavior: hidden | open_customer_dialog | focus_* | open_inventory_candidates | +# todo | download | retry | view_result | view_record | refresh_strip +_TABLE: list[tuple[str, str, str, str]] = [ + ('open_order_review', 'open_order_review', 'pre_create', 'hidden'), + ('edit_formal_task', 'edit_formal_task', 'any', 'hidden'), + ('open_profile_review', 'open_profile_review', 'pre_create', 'focus_profile_panel'), + ('confirm_customer', 'confirm_customer', 'pre_create', 'open_customer_dialog'), + ('resolve_field_conflicts', 'resolve_field_conflicts', 'pre_create', 'focus_field_conflicts'), + ('adjudicate_duplicate', 'adjudicate_duplicate', 'pre_create', 'focus_duplicate_panel'), + ('open_inventory_source_review', 'open_inventory_source_review', 'pre_create', 'open_inventory_candidates'), + ('confirm_inventory_source', 'open_inventory_source_review', 'post_create', 'todo'), + ('match_inventory', 'open_inventory_match_review', 'post_create', 'todo'), + ('rematch', 'open_inventory_match_review', 'post_create', 'todo'), + ('open_shortage_review', 'open_shortage_review', 'post_create', 'focus_inventory_issues'), + ('upload_inventory_file', 'upload_inventory_file', 'post_create', 'todo'), + ('generate_excel', 'regenerate_excel', 'post_create', 'todo'), + ('regenerate_excel', 'regenerate_excel', 'post_create', 'todo'), + ('download_excel', 'download_excel', 'post_create', 'download'), + ('mark_manual_uploaded', 'open_manual_upload', 'post_create', 'todo'), + ('open_manual_upload', 'open_manual_upload', 'post_create', 'todo'), + ('retry', 'retry', 'any', 'retry'), + ('retry_parse', 'retry', 'pre_create', 'retry'), + ('refresh', 'refresh', 'any', 'refresh_strip'), + ('view_result', 'view_result', 'terminal', 'view_result'), + ('open_fulfillment', 'view_result', 'terminal', 'view_result'), + ('view_record', 'view_record', 'any', 'view_record'), +] + + +@pytest.mark.parametrize('action_code,intent,_family,_behavior', _TABLE) +def test_action_code_normalizes_to_contract_intent(action_code, intent, _family, _behavior): + """每个合法动作码必须映射到契约意图集合。""" + mapped = normalize_action_code(action_code) + assert mapped == intent + assert mapped in SHIPPING_PROCESSING_ACTION_INTENTS + + +def test_unknown_action_code_is_dropped(): + """未知码不得泄漏到 available_actions。""" + assert normalize_action_code('totally_unknown_action_xyz') is None + + +def test_pre_create_projection_strips_fulfillment_actions(): + """建单前禁止下发匹配/Excel/上传等履约动作。""" + payload = reconcile_processing_projection_facts({ + 'status': 'blocked', + 'stage': 'waiting_review', + 'source_type': 'direct_pdf', + 'shipping_notice_no': None, + 'current_gate': { + 'gate_code': 'order_review', + 'status': 'blocked', + 'next_action_code': 'confirm_customer', + 'blocking_reason_code': 'customer_unresolved', + 'attempt_no': 1, + }, + 'available_actions': [ + 'confirm_customer', + 'match_inventory', + 'generate_excel', + 'open_manual_upload', + 'download_excel', + ], + }, excel_ready=True) + actions = set(payload['available_actions']) + assert 'confirm_customer' in actions + assert 'match_inventory' not in actions + assert 'open_inventory_match_review' not in actions + assert 'regenerate_excel' not in actions + assert 'open_manual_upload' not in actions + assert 'download_excel' not in actions + + +def test_post_create_projection_keeps_fulfillment_write_chain(): + """正式 Notice 存在时保留关键履约写链动作。""" + actions = derive_available_actions( + status='blocked', + stage='inventory_matching', + gate={ + 'gate_code': 'inventory_match', + 'status': 'blocked', + 'next_action_code': 'match_inventory', + 'blocking_reason_code': 'inventory_shortage', + 'attempt_no': 1, + }, + legacy_actions=['download_excel'], + excel_ready=True, + shipping_notice_no='SN-100', + ) + assert actions[0] == 'open_inventory_match_review' + assert 'download_excel' in actions + + +def test_confirm_customer_is_not_aliased_to_open_order_review(): + """客户确认不得被折叠为 open_order_review(工作台需独立导航执行)。""" + assert normalize_action_code('confirm_customer') == 'confirm_customer' + + +def test_notice_no_with_pre_create_stage_strips_fulfillment_actions(): + """有正式号但 stage 仍在建单前:fail-closed 清空履约动作,保留建单前 Gate 动作。""" + from app.services.shipping_notice.processing_projection_invariants import ( + PROJECTION_INCONSISTENT_ERROR_CODE, + ) + + payload = reconcile_processing_projection_facts({ + 'status': 'blocked', + 'stage': 'waiting_review', + 'source_type': 'direct_pdf', + 'work_item_no': 'OT-1', + 'shipping_notice_no': 'SN-STALE', + 'current_gate': { + 'gate_code': 'order_review', + 'status': 'blocked', + 'next_action_code': 'confirm_customer', + 'blocking_reason_code': 'customer_unresolved', + 'attempt_no': 1, + }, + 'available_actions': [ + 'confirm_customer', + 'match_inventory', + 'generate_excel', + 'open_manual_upload', + 'download_excel', + ], + }, excel_ready=True) + actions = set(payload['available_actions']) + assert 'confirm_customer' in actions + assert 'match_inventory' not in actions + assert 'open_inventory_match_review' not in actions + assert 'regenerate_excel' not in actions + assert 'open_manual_upload' not in actions + assert 'download_excel' not in actions + assert payload.get('projection_inconsistency_code') == PROJECTION_INCONSISTENT_ERROR_CODE + + +def test_confirm_inventory_source_aliases_to_contract_intent(): + """建单后库存确认仍映射契约意图;前端按 postCreate 分叉执行器。""" + assert normalize_action_code('confirm_inventory_source') == 'open_inventory_source_review' + assert normalize_action_code('open_inventory_source_review') == 'open_inventory_source_review' + + +def test_pre_create_keeps_inventory_source_review_but_strips_match(): + """建单前可下发库存源复核,但禁止匹配等履约写动作。""" + actions = derive_available_actions( + status='blocked', + stage='waiting_review', + gate={ + 'gate_code': 'inventory_source_routing', + 'status': 'blocked', + 'next_action_code': 'open_inventory_source_review', + 'blocking_reason_code': 'require_manual_review', + 'attempt_no': 1, + }, + legacy_actions=['match_inventory', 'generate_excel'], + excel_ready=False, + shipping_notice_no=None, + ) + assert 'open_inventory_source_review' in actions + assert 'open_inventory_match_review' not in actions + assert 'regenerate_excel' not in actions + + +def test_post_create_inventory_source_gate_keeps_contract_intent(): + """正式 Notice 存在时库存源 Gate 仍投影为契约意图码。""" + actions = derive_available_actions( + status='blocked', + stage='inventory_fetching', + gate={ + 'gate_code': 'inventory_source_routing', + 'status': 'blocked', + 'next_action_code': 'confirm_inventory_source', + 'blocking_reason_code': 'require_manual_review', + 'attempt_no': 1, + }, + shipping_notice_no='SN-200', + ) + assert actions[0] == 'open_inventory_source_review' diff --git a/backend/tests/test_shipping_workbench_service_chains.py b/backend/tests/test_shipping_workbench_service_chains.py new file mode 100644 index 00000000..525849a9 --- /dev/null +++ b/backend/tests/test_shipping_workbench_service_chains.py @@ -0,0 +1,164 @@ +""" +tests/test_shipping_workbench_service_chains.py + +用途:订单处理工作台四条履约链的「服务级拆链验证」(非完整 HTTP E2E)。 +依赖:pytest、app fixture、order_task_stage_machine.sync_order_task_stage_for_notice、 + shipping_processing_projection._project_order_task_work_item、既有 seed helpers。 +逻辑:模拟写服务成功后的 Notice/OT 状态 → sync → 投影组装; + 断言 stage / current_gate / available_actions / progress_version。 + 测试名与文档明确标注为服务级拆链,不得表述为完整 E2E。 +""" + +from __future__ import annotations + +import pytest + +from app import db + + +@pytest.fixture +def workbench_chain_ids(app): + """构造挂接 Notice 的 OT + Run,仅返回主键供测试内重新加载。""" + 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='WB-CHAIN') + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + notice = ShippingNotice( + task_no='SN-WB-CHAIN-1', + user_id=user.id, + conversation_id=session.session_id, + source_type='manual', + process_status='draft', + current_step='step3_confirm_customer', + ) + db.session.add(notice) + db.session.flush() + order_task = ShippingOrderTask( + task_no='OT-WB-CHAIN-1', + 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, + ) + 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]): + """按主键加载 Run/Notice/OT,避免跨 app_context 会话脱离。""" + 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 _project_after_sync(notice, order_task, run): + """写后同步 OT 阶段并返回投影(服务级拆链公共步骤)。""" + from app.services.shipping_notice.order_task_stage_machine import ( + sync_order_task_stage_for_notice, + ) + from app.services.shipping_notice.shipping_processing_projection import ( + _project_order_task_work_item, + ) + + before_version = int(getattr(order_task, 'progress_version', None) or 1) + sync_order_task_stage_for_notice(notice, order_task=order_task) + db.session.commit() + db.session.refresh(order_task) + projection = _project_order_task_work_item(run) + return before_version, projection + + +def test_service_chain_customer_confirm_projection(app, workbench_chain_ids): + """ + 服务级拆链:客户确认后(Notice 进入建单/履约准备)投影 stage/actions/version。 + 非完整 E2E:不调用 confirm_customer HTTP,直接写入确认后业务态再 sync+project。 + """ + with app.app_context(): + run, notice, order_task = _load_chain(workbench_chain_ids) + notice.process_status = 'building_order' + notice.current_step = 'step4_match_inventory' + notice.customer_id = 1 + db.session.commit() + + before, projection = _project_after_sync(notice, order_task, run) + assert projection['shipping_notice_no'] == notice.task_no + assert projection['stage'] in { + 'order_creating', 'inventory_fetching', 'inventory_matching', 'waiting_review', + } + assert isinstance(projection.get('available_actions'), list) + assert int(projection['progress_version']) >= before + + +def test_service_chain_inventory_match_projection(app, workbench_chain_ids): + """ + 服务级拆链:库存匹配/重匹配后投影。 + 非完整 E2E:写入匹配中/匹配完成态后 sync+project。 + """ + with app.app_context(): + run, notice, order_task = _load_chain(workbench_chain_ids) + notice.process_status = 'inventory_matching' + notice.current_step = 'step4_match_inventory' + db.session.commit() + + before, projection = _project_after_sync(notice, order_task, run) + assert projection['stage'] in {'inventory_matching', 'inventory_fetching', 'excel_generating'} + assert projection['progress_version'] >= before + assert projection.get('current_gate') is None or isinstance(projection['current_gate'], dict) + assert isinstance(projection.get('available_actions'), list) + + +def test_service_chain_excel_generate_projection(app, workbench_chain_ids): + """ + 服务级拆链:Excel 生成后投影。 + 非完整 E2E:写入 waiting_upload / export 就绪态后 sync+project。 + """ + with app.app_context(): + run, notice, order_task = _load_chain(workbench_chain_ids) + notice.process_status = 'waiting_upload' + notice.current_step = 'step7_upload_freight' + notice.export_file_path = '/tmp/fake-shipping.xlsx' + db.session.commit() + + before, projection = _project_after_sync(notice, order_task, run) + assert projection['stage'] == 'freight_uploading' + assert projection['status'] in {'automating', 'blocked', 'processing', 'needs_action'} + assert int(projection['progress_version']) >= before + assert isinstance(projection.get('available_actions'), list) + + +def test_service_chain_freight_upload_retry_projection(app, workbench_chain_ids): + """ + 服务级拆链:货代上传重试后投影。 + 非完整 E2E:写入上传失败待重试态后 sync+project(不走真实 RPA)。 + """ + with app.app_context(): + run, notice, order_task = _load_chain(workbench_chain_ids) + notice.process_status = 'upload_failed' + notice.current_step = 'step7_upload_freight' + notice.upload_status = 'failed' + notice.export_file_path = '/tmp/fake-shipping.xlsx' + db.session.commit() + + before, projection = _project_after_sync(notice, order_task, run) + assert projection['stage'] == 'freight_uploading' + assert int(projection['progress_version']) >= before + actions = projection.get('available_actions') or [] + assert all(isinstance(code, str) for code in actions) diff --git a/backend/tests/test_shipping_xfa_formal_extraction_route.py b/backend/tests/test_shipping_xfa_formal_extraction_route.py index e6164f37..a26e63eb 100644 --- a/backend/tests/test_shipping_xfa_formal_extraction_route.py +++ b/backend/tests/test_shipping_xfa_formal_extraction_route.py @@ -131,8 +131,8 @@ def test_route_deterministic_unit_xfa_golden_ab(monkeypatch, xfa_pdf_bytes): assert 'datasets_xml' not in blob -def test_route_deterministic_unit_xfa_no_match_falls_back_to_generic(monkeypatch, xfa_pdf_bytes): - """关键断言:Profile 未命中 → 回退通用/OCR/Dify 路径,保留 XFA 失败原因。""" +def test_route_deterministic_unit_xfa_no_match_does_not_fallback_to_generic(monkeypatch, xfa_pdf_bytes): + """关键断言:Profile 未命中 → review_required 失败关闭,禁止通用/坐标正式回退。""" outcome = analyze_xfa_pdf(xfa_pdf_bytes) capability = outcome.snapshot['xfa_capability'] document = { @@ -182,7 +182,6 @@ def test_route_deterministic_unit_xfa_no_match_falls_back_to_generic(monkeypatch **decision, 'route_type': 'generic_deterministic', 'route_decision': 'needs_review', - 'capability_kind': decision.get('capability_kind') or 'xfa_fallback_coordinate', }, orders=[], ) @@ -191,12 +190,20 @@ def test_route_deterministic_unit_xfa_no_match_falls_back_to_generic(monkeypatch 'app.services.shipping_notice.order_extraction_workflow._route_generic_deterministic_unit', _fake_generic, ) + monkeypatch.setattr( + 'app.services.shipping_notice.order_extraction_workflow._profile_table_candidates', + lambda *_args, **_kwargs: (_ for _ in ()).throw( + AssertionError('no coordinate fallback on XFA formal failure') + ), + ) monkeypatch.setattr( 'app.services.shipping_notice.order_extraction_workflow.generic_extraction_enabled', lambda: True, ) route = route_deterministic_unit(run, unit=unit) - assert generic_called['value'] is True - assert route.decision.get('capability_kind') == 'xfa_fallback_coordinate' - codes = route.decision.get('fallback_reason_codes') or route.decision.get('xfa_fallback_reason_codes') or [] + assert generic_called['value'] is False + assert route.execution_mode == 'review_required' + assert route.decision.get('capability_kind') == 'xfa_dataset' + assert route.decision.get('capability_kind') != 'xfa_fallback_coordinate' + codes = route.decision.get('fallback_reason_codes') or route.decision.get('reason_codes') or [] assert 'xfa_profile_not_matched' in codes diff --git a/backend/tests/test_shipping_xfa_frozen_analysis.py b/backend/tests/test_shipping_xfa_frozen_analysis.py new file mode 100644 index 00000000..e3c265bf --- /dev/null +++ b/backend/tests/test_shipping_xfa_frozen_analysis.py @@ -0,0 +1,239 @@ +""" +tests/test_shipping_xfa_frozen_analysis.py + +用途:锁定 BE-2——XFA 结构读取必须绑定 Layout 冻结的 structure_analysis_id。 +依赖:resolve_frozen_xfa_structure_analysis、Flask app、内存 SQLite 模型。 +逻辑:构造 Layout/Analysis 身份;断言禁止回退最新 Analysis。 +""" + +from __future__ import annotations + +import hashlib +import secrets + +import pytest + +from app.core.errors import ValidationError +from app.extensions import db +from app.models import ( + FileAsset, + ShippingDocumentLayoutVersion, + ShippingOrderDocument, + ShippingOrderIntake, + ShippingXfaStructureAnalysis, + User, +) +from app.services.shipping_notice.document_layout.xfa_analysis import ( + resolve_frozen_xfa_structure_analysis, +) + + +def _content_hash(seed: str) -> str: + return hashlib.sha256(seed.encode('utf-8')).hexdigest() + + +def _seed_document(*, seed: str) -> ShippingOrderDocument: + """创建带稳定内容哈希的最小附件 Document。""" + token = secrets.token_hex(4) + content_hash = _content_hash(seed) + user = User( + username=f'xfa-frozen-{token}', + email=f'xfa-frozen-{token}@example.com', + role='user', + status='active', + ) + db.session.add(user) + db.session.flush() + asset = FileAsset( + asset_no=f'FA-XFA-FROZEN-{token}', + owner_user_id=user.id, + original_filename=f'{seed}.pdf', + storage_provider='minio', + storage_bucket='test', + storage_key=f'frozen/{seed}.pdf', + content_hash=content_hash, + file_size=128, + mime_type='application/pdf', + upload_status='ready', + lifecycle_status='referenced', + ) + db.session.add(asset) + db.session.flush() + intake = ShippingOrderIntake( + intake_no=f'SNI-XFA-FROZEN-{token}', + asset_id=asset.id, + user_id=user.id, + purpose='order_document_profile_sample', + 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=f'{seed}.pdf', + filename=f'{seed}.pdf', + content_hash=content_hash, + classification='order_notice', + parse_status='parsed', + ) + db.session.add(document) + db.session.flush() + return document + + +def test_resolve_frozen_analysis_uses_layout_bound_id_not_latest(app): + """关键断言:即使存在更新的 Analysis,仍必须读取 Layout 冻结的主键。""" + with app.app_context(): + document = _seed_document(seed='frozen-latest') + older = ShippingXfaStructureAnalysis( + document_id=document.id, + layout_version_id=None, + source_content_hash=document.content_hash, + document_kind='xfa_hybrid', + analysis_status='ready', + template_packet_checksum='sha256:template', + datasets_packet_checksum='sha256:datasets', + dataset_structure_fingerprint='sha256:structure', + packet_checksums_json={}, + stats_json={}, + security_summary_json={}, + tree_summary_json={'known_path_ids': ['p1']}, + parser_identity='xfa-parser.v1', + contract_version='xfa-contract.v1', + ) + newer = ShippingXfaStructureAnalysis( + document_id=document.id, + layout_version_id=None, + source_content_hash=document.content_hash, + document_kind='xfa_hybrid', + analysis_status='ready', + template_packet_checksum='sha256:template-new', + datasets_packet_checksum='sha256:datasets-new', + dataset_structure_fingerprint='sha256:structure-new', + packet_checksums_json={}, + stats_json={}, + security_summary_json={}, + tree_summary_json={'known_path_ids': ['p2']}, + parser_identity='xfa-parser.v1', + contract_version='xfa-contract.v1', + ) + db.session.add_all([older, newer]) + db.session.flush() + layout = ShippingDocumentLayoutVersion( + document_id=document.id, + version=1, + status='ready', + source_content_hash=document.content_hash, + parser_key='mineru:test', + parser_name='xfa', + backend='pypdf', + contract_version='shipping_document_layout.v1', + payload_json={ + 'status': 'ready', + 'provider': 'xfa', + 'xfa_capability': { + 'structure_analysis_ready': True, + 'structure_analysis_id': older.id, + 'template_packet_checksum': older.template_packet_checksum, + 'dataset_structure_fingerprint': older.dataset_structure_fingerprint, + }, + }, + issues_json=[], + attempt_count=1, + ) + db.session.add(layout) + db.session.flush() + older.layout_version_id = layout.id + document.current_layout_version_id = layout.id + db.session.commit() + + _version, analysis, capability = resolve_frozen_xfa_structure_analysis(document) + assert int(analysis.id) == int(older.id) + assert int(analysis.id) != int(newer.id) + assert int(capability['structure_analysis_id']) == int(older.id) + assert int(_version.id) == int(layout.id) + + +def test_resolve_frozen_analysis_missing_id_fail_closed(app): + """关键断言:Layout 缺少 structure_analysis_id 时抛 XFA_ANALYSIS_MISSING。""" + with app.app_context(): + document = _seed_document(seed='missing-id') + layout = ShippingDocumentLayoutVersion( + document_id=document.id, + version=1, + status='ready', + source_content_hash=document.content_hash, + parser_key='mineru:test', + parser_name='xfa', + backend='pypdf', + contract_version='shipping_document_layout.v1', + payload_json={ + 'status': 'ready', + 'provider': 'xfa', + 'xfa_capability': {'structure_analysis_ready': True}, + }, + issues_json=[], + attempt_count=1, + ) + db.session.add(layout) + db.session.flush() + document.current_layout_version_id = layout.id + db.session.commit() + with pytest.raises(ValidationError) as caught: + resolve_frozen_xfa_structure_analysis(document) + assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_MISSING' + + +def test_resolve_frozen_analysis_identity_mismatch(app): + """关键断言:Analysis 绑定其他 Document 时抛 IDENTITY_MISMATCH。""" + with app.app_context(): + document = _seed_document(seed='mismatch-a') + other = _seed_document(seed='mismatch-b') + foreign = ShippingXfaStructureAnalysis( + document_id=other.id, + layout_version_id=None, + source_content_hash=other.content_hash, + document_kind='xfa_hybrid', + analysis_status='ready', + template_packet_checksum='sha256:template', + datasets_packet_checksum='sha256:datasets', + dataset_structure_fingerprint='sha256:structure', + packet_checksums_json={}, + stats_json={}, + security_summary_json={}, + tree_summary_json={}, + parser_identity='xfa-parser.v1', + contract_version='xfa-contract.v1', + ) + db.session.add(foreign) + db.session.flush() + layout = ShippingDocumentLayoutVersion( + document_id=document.id, + version=1, + status='ready', + source_content_hash=document.content_hash, + parser_key='mineru:test', + parser_name='xfa', + backend='pypdf', + contract_version='shipping_document_layout.v1', + payload_json={ + 'status': 'ready', + 'provider': 'xfa', + 'xfa_capability': { + 'structure_analysis_ready': True, + 'structure_analysis_id': foreign.id, + }, + }, + issues_json=[], + attempt_count=1, + ) + db.session.add(layout) + db.session.flush() + document.current_layout_version_id = layout.id + db.session.commit() + with pytest.raises(ValidationError) as caught: + resolve_frozen_xfa_structure_analysis(document) + assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_IDENTITY_MISMATCH' diff --git a/backend/tests/test_shipping_xfa_ocr_automark.py b/backend/tests/test_shipping_xfa_ocr_automark.py new file mode 100644 index 00000000..dc259f0b --- /dev/null +++ b/backend/tests/test_shipping_xfa_ocr_automark.py @@ -0,0 +1,337 @@ +""" +tests/test_shipping_xfa_ocr_automark.py + +用途:验收 XFA OCR 自动标记入队、accept 分层、mismatch 阻断、发布门禁与 renderer bump 降级。 +依赖:order_document_profile_xfa_automark_service、assert_xfa_synthetic_preview_gate、 + publish_check _blocking_xfa_visual_bindings;mock queue / lease / confirm / native pages。 +逻辑:纯单元为主;enqueue mock 原生页指纹;不依赖真实 RapidOCR / DB 全栈。 +""" + +from __future__ import annotations + +from unittest.mock import MagicMock, patch + +import pytest + +from app.core.errors import ValidationError +from app.services.shipping_notice.order_document_profile_publish_check_service import ( + _blocking_xfa_visual_bindings, +) +from app.services.shipping_notice.order_document_profile_validation_service import ( + assert_xfa_synthetic_preview_gate, +) +from app.services.shipping_notice.order_document_profile_xfa_automark_service import ( + AUTOMARK_MISMATCH_BLOCKED, + accept_xfa_automark_suggestion, + demote_stale_confirmed_visual_bindings_on_renderer_bump, + enqueue_xfa_ocr_automark, +) + +pytestmark = pytest.mark.pure_unit + + +def _source_contract() -> dict: + """最小 XFA source_contract。""" + return { + 'template_packet_checksum': 'sha256:' + ('a' * 64), + 'dataset_structure_fingerprint': 'sha256:' + ('b' * 64), + 'dataset_root_path': '/data', + 'authoritative_line_collection_path': '/data/ITEMS/DATA', + 'mirror_collection_paths': [], + } + + +def _definition_with_binding(*, visual_status: str = 'suggested', region_kind: str = 'field') -> dict: + """构造含统一 binding 的草稿 definition。""" + checksum = 'sha256:' + ('c' * 64) + visual = { + 'page_no': 1, + 'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5}, + 'source': 'suggested', + 'status': visual_status, + 'confidence': 0.95, + 'region_kind': region_kind, + } + if visual_status == 'confirmed': + visual.update({ + 'preview_render_checksum': checksum, + 'render_mode': 'xfa_dataset_preview', + 'confirmed_on': 'xfa_dataset_preview', + 'renderer_version': 'hxops.xfa_static_preview.v1', + }) + return { + 'template_mode': 'xfa_dataset', + 'source_contract': _source_contract(), + 'header_mappings': [], + 'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []}, + 'bindings': [{ + 'binding_id': 'bind-po-001', + 'field_id': 'f-h-po', + 'field_code': 'customer_po_no', + 'scope': 'header', + 'value_binding': { + 'type': 'xfa_dataset', + 'path_id': 'path-po', + 'data_path': '/data/HEADER/EBELN', + }, + 'visual_binding': visual, + }], + 'xfa_preview': { + 'status': 'ready', + 'preview_render_checksum': checksum, + 'render_mode': 'xfa_dataset_preview', + 'renderer_version': 'hxops.xfa_static_preview.v1', + 'page_count': 1, + 'unresolved_ocr_mismatch_count': 0, + }, + 'xfa_ocr_automark': { + 'status': 'completed', + 'preview_render_checksum': checksum, + 'unresolved_ocr_mismatch_count': 0, + 'suggestions': [], + }, + } + + +def test_enqueue_xfa_ocr_automark_returns_job_id(): + """关键断言:enqueue 以原生 PDF 指纹入队,不再依赖 synthetic preview。""" + definition = _definition_with_binding() + profile = MagicMock( + id=12, + status='draft', + template_mode='xfa_dataset', + definition_json=definition, + ) + native = { + 'pages': [{'page_no': 1, 'png_bytes': b'png'}], + 'page_count': 1, + 'preview_render_checksum': 'sha256:' + ('c' * 64), + 'renderer_version': 'hxops.native_pdf.v1', + 'render_mode': 'native_pdf', + } + with patch( + 'app.services.shipping_notice.order_document_profile_xfa_automark_service._profile', + return_value=profile, + ), patch( + 'app.services.shipping_notice.order_document_profile_xfa_automark_service._load_native_pdf_pages_for_ocr', + return_value=native, + ), patch( + 'app.services.shipping_notice.order_document_profile_xfa_automark_service.enqueue', + return_value=4242, + ) as enqueue_mock, patch( + 'app.services.shipping_notice.order_document_profile_xfa_automark_service.db', + ) as db_mock: + job = MagicMock(status='queued') + db_mock.session.get.return_value = job + result = enqueue_xfa_ocr_automark( + 12, + document_id=77, + actor_id=1, + force=False, + ) + assert result['job_id'] == 4242 + assert result['status'] == 'queued' + assert result['preview_render_checksum'].startswith('sha256:') + assert result['render_mode'] == 'native_pdf' + enqueue_mock.assert_called_once() + call_kwargs = enqueue_mock.call_args + assert call_kwargs.args[0].value == 'shipping_xfa_ocr_automark' or str(call_kwargs.args[0]) == 'shipping_xfa_ocr_automark' + + +def test_execute_blank_native_pdf_returns_empty_suggestions(): + """关键断言:空白壳原生页返回空建议成功,不报 XFA_PREVIEW_UNAVAILABLE。""" + from app.services.shipping_notice.order_document_profile_xfa_automark_service import ( + execute_xfa_ocr_automark_job, + ) + + profile = MagicMock( + id=12, + status='draft', + template_mode='xfa_dataset', + definition_json=_definition_with_binding(), + ) + native = { + 'pages': [], + 'page_count': 0, + 'preview_render_checksum': 'sha256:' + ('d' * 64), + 'renderer_version': 'hxops.native_pdf.v1', + 'render_mode': 'native_pdf', + } + with patch( + 'app.services.shipping_notice.order_document_profile_xfa_automark_service._profile', + return_value=profile, + ), patch( + 'app.services.shipping_notice.order_document_profile_xfa_automark_service._load_native_pdf_pages_for_ocr', + return_value=native, + ), patch( + 'app.services.shipping_notice.order_document_profile_xfa_automark_service._audit_automark', + ), patch( + 'app.services.shipping_notice.order_document_profile_xfa_automark_service.db', + ): + result = execute_xfa_ocr_automark_job({ + 'profile_id': 12, + 'document_id': 77, + 'actor_id': 1, + 'job_id': 9, + }) + assert result['status'] == 'success' + assert result['suggestions'] == [] + assert result['error_code'] is None + assert result['page_count'] == 0 + assert profile.definition_json['xfa_ocr_automark']['suggestion_count'] == 0 + + +def test_accept_high_requires_checksum_and_confirms(app): + """关键断言:high 接受走 confirm,且须携带 preview_render_checksum。""" + from app.services.shipping_notice import order_document_profile_lease_service as lease_service + from app.services.shipping_notice import order_document_profile_visual_binding_service as visual_svc + + checksum = 'sha256:' + ('c' * 64) + definition = _definition_with_binding() + definition['xfa_ocr_automark']['suggestions'] = [{ + 'suggestion_id': 'sugg-high-1', + 'field_key': 'path-po', + 'page_no': 1, + 'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5}, + 'match_class': 'high', + 'needs_review': False, + 'confidence': 0.96, + 'region_kind': 'header', + 'preview_render_checksum': checksum, + 'status': 'suggested', + }] + profile = MagicMock( + id=12, + status='draft', + template_mode='xfa_dataset', + definition_json=definition, + ) + + with patch( + 'app.services.shipping_notice.order_document_profile_xfa_automark_service._profile', + return_value=profile, + ), patch.object(lease_service, 'require_active_lease', return_value=object()), patch.object( + visual_svc, + 'confirm_xfa_visual_binding', + return_value={ + 'binding_id': 'bind-po-001', + 'visual_binding': { + 'status': 'confirmed', + 'preview_render_checksum': checksum, + 'region_kind': 'header', + }, + }, + ) as confirm_mock, patch( + 'app.services.shipping_notice.order_document_profile_xfa_automark_service._mark_suggestion_resolved', + ), patch( + 'app.services.shipping_notice.order_document_profile_xfa_automark_service.db', + ): + result = accept_xfa_automark_suggestion( + 12, + 'sugg-high-1', + actor_id=1, + browser_session_id='tab', + lease_token='lease', + ) + assert result['action'] == 'confirmed' + confirm_mock.assert_called_once() + kwargs = confirm_mock.call_args.kwargs + assert kwargs['visual_binding']['region_kind'] == 'header' + + +def test_accept_mismatch_blocked(app): + """关键断言:needs_review / mismatch 接受被阻断。""" + from app.services.shipping_notice import order_document_profile_lease_service as lease_service + + definition = _definition_with_binding() + definition['xfa_ocr_automark']['suggestions'] = [{ + 'suggestion_id': 'sugg-bad-1', + 'field_key': 'path-po', + 'page_no': 1, + 'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5}, + 'match_class': 'needs_review', + 'needs_review': True, + 'status': 'suggested', + }] + profile = MagicMock( + id=12, + status='draft', + template_mode='xfa_dataset', + definition_json=definition, + ) + with patch( + 'app.services.shipping_notice.order_document_profile_xfa_automark_service._profile', + return_value=profile, + ), patch.object(lease_service, 'require_active_lease', return_value=object()): + with pytest.raises(ValidationError) as caught: + accept_xfa_automark_suggestion( + 12, + 'sugg-bad-1', + actor_id=1, + browser_session_id='tab', + lease_token='lease', + ) + assert caught.value.code == AUTOMARK_MISMATCH_BLOCKED + + +def test_publish_gate_blocks_unresolved_ocr_mismatch(): + """关键断言:unresolved_ocr_mismatch_count>0 时发布门禁阻断。""" + with pytest.raises(ValidationError) as caught: + assert_xfa_synthetic_preview_gate( + template_mode='xfa_dataset', + preview_status='ready', + preview_render_checksum='sha256:' + ('c' * 64), + bindings=[{ + 'field_id': 'f-h-po', + 'visual_binding': {'status': 'confirmed'}, + }], + schema_field_ids={'f-h-po'}, + preview_meta={ + 'status': 'ready', + 'page_count': 1, + 'pages_ready': [1], + 'unresolved_ocr_mismatch_count': 2, + 'renderer_version': 'hxops.xfa_static_preview.v1', + }, + current_renderer_version='hxops.xfa_static_preview.v1', + ) + keys = {item['key'] for item in caught.value.details.get('blocking') or []} + assert 'xfa_ocr_unresolved_mismatch' in keys + + +def test_publish_check_blocks_unresolved_mismatch_via_definition(): + """关键断言:_blocking_xfa_visual_bindings 透传 unresolved mismatch。""" + definition = _definition_with_binding(visual_status='confirmed') + definition['xfa_preview']['unresolved_ocr_mismatch_count'] = 1 + definition['xfa_ocr_automark']['unresolved_ocr_mismatch_count'] = 1 + blocking = _blocking_xfa_visual_bindings( + definition=definition, + schema_field_ids={'f-h-po'}, + ) + assert any(item.get('key') == 'xfa_ocr_unresolved_mismatch' for item in blocking) + + +def test_renderer_bump_demotes_confirmed_missing_current_checksum(): + """关键断言:renderer bump / checksum 漂移时 confirmed → suggested。""" + definition = _definition_with_binding(visual_status='confirmed') + result = demote_stale_confirmed_visual_bindings_on_renderer_bump( + definition, + current_renderer_version='hxops.xfa_static_preview.v2', + current_preview_render_checksum='sha256:' + ('d' * 64), + ) + assert result['demoted_count'] == 1 + visual = definition['bindings'][0]['visual_binding'] + assert visual['status'] == 'suggested' + assert 'confirmed_on' not in visual + + +def test_renderer_bump_keeps_matching_confirmed(): + """关键断言:版本与 checksum 均匹配时不降级。""" + definition = _definition_with_binding(visual_status='confirmed') + result = demote_stale_confirmed_visual_bindings_on_renderer_bump( + definition, + current_renderer_version='hxops.xfa_static_preview.v1', + current_preview_render_checksum='sha256:' + ('c' * 64), + ) + assert result['demoted_count'] == 0 + assert definition['bindings'][0]['visual_binding']['status'] == 'confirmed' diff --git a/backend/tests/test_shipping_xfa_ocr_matching.py b/backend/tests/test_shipping_xfa_ocr_matching.py new file mode 100644 index 00000000..ea24bbd7 --- /dev/null +++ b/backend/tests/test_shipping_xfa_ocr_matching.py @@ -0,0 +1,277 @@ +""" +tests/test_shipping_xfa_ocr_matching.py + +用途:阶段 3 OCR 匹配 / 视觉建议合并、阶段 5 合成预览门禁、阶段 6 审计补偿骨架单测。 +依赖:xfa_ocr_matcher、xfa_visual_binding_service、assert_xfa_synthetic_preview_gate、 + audit_compensation_service;合成 bbox/文本,不依赖真实 RapidOCR。 +逻辑:断言 IoU/分层、mismatch→needs_review、Widget 优先 OCR 补框、门禁 fail-closed、 + 补偿记录与 retry stub。 +""" + +from __future__ import annotations + +import pytest + +from app.core.errors import ValidationError +from app.services.shipping_notice.audit_compensation_service import ( + list_pending_compensation, + record_audit_write_failure, + reset_compensation_store_for_tests, + retry_pending, +) +from app.services.shipping_notice.document_layout.xfa_contract import XFA_AUDIT_EVENT_TYPES +from app.services.shipping_notice.order_document_profile_validation_service import ( + assert_xfa_synthetic_preview_gate, +) +from app.services.shipping_notice.xfa_ocr_matcher import ( + classify_ocr_match, + compute_iou, + match_ocr_to_datasets, + normalize_match_text, +) +from app.services.shipping_notice.xfa_visual_binding_service import merge_visual_binding_suggestions + +pytestmark = pytest.mark.pure_unit + + +def test_normalize_and_iou_helpers(): + """关键断言:文本规范化折叠空白;IoU 对重叠框为正。""" + assert normalize_match_text(' Po-123 ') == 'po-123' + iou = compute_iou( + {'x0': 0.1, 'y0': 0.1, 'x1': 0.5, 'y1': 0.3}, + {'x0': 0.2, 'y0': 0.15, 'x1': 0.6, 'y1': 0.35}, + ) + assert 0.0 < iou < 1.0 + assert compute_iou( + {'x0': 0.0, 'y0': 0.0, 'x1': 0.1, 'y1': 0.1}, + {'x0': 0.9, 'y0': 0.9, 'x1': 1.0, 'y1': 1.0}, + ) == 0.0 + + +def test_classify_high_medium_low_and_mismatch_needs_review(): + """关键断言:高/中/低分层;文本不匹配一律 needs_review。""" + assert classify_ocr_match(text_score=1.0, iou=0.6, ocr_confidence=0.95) == 'high' + assert classify_ocr_match(text_score=1.0, iou=0.35, ocr_confidence=0.85) == 'medium' + assert classify_ocr_match(text_score=0.5, iou=0.15, ocr_confidence=0.75) == 'low' + assert classify_ocr_match(text_score=0.0, iou=0.9, ocr_confidence=0.99) == 'needs_review' + + +def test_match_ocr_to_datasets_mismatch_never_auto_confirm(): + """关键断言:OCR 与 datasets 值不符 → needs_review,且 auto_confirm_blocked。""" + ocr_lines = [{ + 'text': 'WRONG-VALUE', + 'confidence': 0.99, + 'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.4, 'y1': 0.3}, + }] + targets = [{ + 'field_key': 'path-po', + 'value': 'PO-1001', + 'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.4, 'y1': 0.3}, + }] + suggestions = match_ocr_to_datasets(ocr_lines=ocr_lines, dataset_targets=targets) + assert len(suggestions) == 1 + item = suggestions[0] + assert item['match_class'] == 'needs_review' + assert item['status'] == 'needs_review' + assert item['auto_confirm_blocked'] is True + + +def test_match_ocr_exact_value_suggested_high(): + """关键断言:精确文本 + 高 IoU/置信 → suggested/high,仍禁止自动确认。""" + bbox = {'x0': 0.2, 'y0': 0.4, 'x1': 0.5, 'y1': 0.5} + suggestions = match_ocr_to_datasets( + ocr_lines=[{'text': 'PO-1001', 'confidence': 0.96, 'normalized_bbox': bbox}], + dataset_targets=[{'field_key': 'path-po', 'value': 'PO-1001', 'normalized_bbox': bbox}], + ) + assert suggestions[0]['match_class'] == 'high' + assert suggestions[0]['status'] == 'suggested' + assert suggestions[0]['auto_confirm_blocked'] is True + + +def test_merge_widget_first_then_ocr_fill(): + """关键断言:Widget 覆盖的 field 不被 OCR 覆盖;未覆盖目标由 OCR 填充。""" + widget_candidates = [{ + 'path_candidates': [{'path_id': 'path-po'}], + 'page_no': 1, + 'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2}, + 'confidence': 0.9, + }] + result = merge_visual_binding_suggestions( + page_no=1, + widget_candidates=widget_candidates, + ocr_lines=[{ + 'text': 'LINE-A', + 'confidence': 0.95, + 'normalized_bbox': {'x0': 0.2, 'y0': 0.5, 'x1': 0.5, 'y1': 0.6}, + }], + dataset_targets=[ + {'field_key': 'path-po', 'value': 'PO-1', 'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2}}, + {'field_key': 'path-line', 'value': 'LINE-A', 'normalized_bbox': {'x0': 0.2, 'y0': 0.5, 'x1': 0.5, 'y1': 0.6}}, + ], + ) + bindings = result['suggested_visual_bindings'] + origins = {item['field_key']: item['suggestion_origin'] for item in bindings} + assert origins['path-po'] == 'widget_template' + assert origins['path-line'] == 'ocr' + assert all(item.get('auto_confirm_blocked') is True for item in bindings) + assert all(item.get('status') != 'confirmed' for item in bindings) + + +def test_assert_xfa_synthetic_preview_gate_blocks_not_ready(): + """关键断言:preview_status 非 ready → 抛 SYNTHETIC_PREVIEW_GATE。""" + with pytest.raises(ValidationError) as caught: + assert_xfa_synthetic_preview_gate( + template_mode='xfa_dataset', + preview_status='failed', + preview_render_checksum='sha256:' + ('a' * 64), + bindings=[{ + 'field_id': 'f-h-po', + 'visual_binding': {'status': 'confirmed'}, + }], + ) + assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SYNTHETIC_PREVIEW_GATE' + keys = {item['key'] for item in caught.value.details.get('blocking') or []} + assert 'xfa_synthetic_preview_not_ready' in keys + + +def test_assert_xfa_synthetic_preview_gate_blocks_missing_checksum_and_unconfirmed(): + """关键断言:缺 checksum + 未确认视觉绑定同时阻断。""" + with pytest.raises(ValidationError) as caught: + assert_xfa_synthetic_preview_gate( + template_mode='xfa_dataset', + preview_status='ready', + preview_render_checksum='', + bindings=[{ + 'field_id': 'f-h-po', + 'visual_binding': {'status': 'suggested'}, + }], + schema_field_ids={'f-h-po'}, + ) + keys = {item['key'] for item in caught.value.details.get('blocking') or []} + assert 'xfa_preview_render_checksum_missing' in keys + assert 'xfa_visual_binding_incomplete' in keys + + +def test_assert_xfa_synthetic_preview_gate_skips_coordinate_and_passes_ready(): + """关键断言:coordinate 跳过;XFA ready+页身份+confirmed 完整证据通过。""" + assert_xfa_synthetic_preview_gate( + template_mode='coordinate', + preview_status=None, + preview_render_checksum=None, + bindings=[], + ) + checksum = 'sha256:' + ('b' * 64) + assert_xfa_synthetic_preview_gate( + template_mode='xfa_dataset', + preview_status='ready', + preview_render_checksum=checksum, + bindings=[{ + 'field_id': 'f-h-po', + 'visual_binding': { + 'status': 'confirmed', + 'preview_render_checksum': checksum, + 'confirmed_on': 'xfa_dataset_preview', + 'renderer_version': 'hxops.xfa_static_preview.v1', + }, + }], + schema_field_ids={'f-h-po'}, + preview_meta={ + 'status': 'ready', + 'preview_render_checksum': checksum, + 'renderer_version': 'hxops.xfa_static_preview.v1', + 'page_count': 1, + 'pages_ready': [1], + 'source_page_count': 1, + 'synthetic_page_count': 1, + 'pages': [{ + 'page_no': 1, + 'source_page_box': {'x0': 0.0, 'y0': 0.0, 'x1': 612.0, 'y1': 792.0}, + 'synthetic_page_box': {'x0': 0.0, 'y0': 0.0, 'x1': 612.0, 'y1': 792.0}, + 'page_identity_hash': 'page-1', + }], + 'unresolved_ocr_mismatch_count': 0, + }, + current_renderer_version='hxops.xfa_static_preview.v1', + ) + + +def test_assert_xfa_synthetic_preview_gate_blocks_missing_page_identity(): + """关键断言:缺 source/synthetic 页身份证据 → xfa_preview_page_identity_missing。""" + with pytest.raises(ValidationError) as caught: + assert_xfa_synthetic_preview_gate( + template_mode='xfa_dataset', + preview_status='ready', + preview_render_checksum='sha256:' + ('b' * 64), + bindings=[], + preview_meta={ + 'status': 'ready', + 'page_count': 1, + 'pages_ready': [1], + }, + ) + keys = {item['key'] for item in caught.value.details.get('blocking') or []} + assert 'xfa_preview_page_identity_missing' in keys + + +def test_assert_xfa_synthetic_preview_gate_blocks_missing_renderer_version(): + """关键断言:confirmed 缺 renderer_version → xfa_preview_renderer_version_mismatch(BE-4)。""" + checksum = 'sha256:' + ('b' * 64) + with pytest.raises(ValidationError) as caught: + assert_xfa_synthetic_preview_gate( + template_mode='xfa_dataset', + preview_status='ready', + preview_render_checksum=checksum, + bindings=[{ + 'field_id': 'f-h-po', + 'visual_binding': { + 'status': 'confirmed', + 'preview_render_checksum': checksum, + 'confirmed_on': 'xfa_dataset_preview', + # 故意缺 renderer_version + }, + }], + schema_field_ids={'f-h-po'}, + preview_meta={ + 'status': 'ready', + 'preview_render_checksum': checksum, + 'renderer_version': 'hxops.xfa_static_preview.v1', + 'page_count': 1, + 'pages_ready': [1], + 'source_page_count': 1, + 'synthetic_page_count': 1, + 'pages': [{ + 'page_no': 1, + 'source_page_box': {'x0': 0.0, 'y0': 0.0, 'x1': 612.0, 'y1': 792.0}, + 'synthetic_page_box': {'x0': 0.0, 'y0': 0.0, 'x1': 612.0, 'y1': 792.0}, + 'page_identity_hash': 'page-1', + }], + }, + current_renderer_version='hxops.xfa_static_preview.v1', + ) + keys = {item['key'] for item in caught.value.details.get('blocking') or []} + assert 'xfa_preview_renderer_version_mismatch' in keys + + +def test_audit_compensation_record_list_retry_stub(): + """关键断言:写失败入队、list pending、retry stub 标记 retried_stub。""" + reset_compensation_store_for_tests() + record = record_audit_write_failure( + event_type='xfa_visual_binding_suggested', + payload={'page_no': 1}, + error='db_commit_failed', + profile_id=12, + ) + assert record['status'] == 'pending' + pending = list_pending_compensation() + assert any(item['id'] == record['id'] for item in pending) + result = retry_pending(limit=10) + assert result['retried'] >= 1 + assert result['note'] == 'stub_only_no_audit_replay' + assert all(item['status'] == 'retried_stub' for item in result['items']) + reset_compensation_store_for_tests() + + +def test_xfa_ocr_audit_event_names_registered(): + """关键断言:OCR 审计事件名已注册于 XFA_AUDIT_EVENT_TYPES。""" + for name in ('xfa_ocr_started', 'xfa_ocr_completed', 'xfa_ocr_failed', 'xfa_visual_binding_suggested'): + assert name in XFA_AUDIT_EVENT_TYPES diff --git a/backend/tests/test_shipping_xfa_preview_identity.py b/backend/tests/test_shipping_xfa_preview_identity.py new file mode 100644 index 00000000..accc4f87 --- /dev/null +++ b/backend/tests/test_shipping_xfa_preview_identity.py @@ -0,0 +1,124 @@ +""" +tests/test_shipping_xfa_preview_identity.py + +用途:验收 XFA 合成预览身份指纹、stale 判定、缓存键与审计事件注册。 +依赖:xfa_preview_contract、xfa_preview_cache、xfa_contract、progress_audit_contract。 +逻辑:纯函数断言;身份字段变化 → stale;同输入指纹稳定。 +""" + +from __future__ import annotations + +import pytest + +from app.services.shipping_notice.document_layout.xfa_contract import ( + XFA_AUDIT_EVENT_TYPES, + XFA_ERROR_CODES, +) +from app.services.shipping_notice.document_layout.xfa_preview_cache import ( + build_preview_cache_key, + clear_preview_cache, + get_preview_cache, + invalidate_preview_cache, + set_preview_cache, +) +from app.services.shipping_notice.document_layout.xfa_preview_contract import ( + RENDER_MODE, + XFA_PREVIEW_AUDIT_EVENT_TYPES, + XFA_PREVIEW_ERROR_CODES, + XFA_PREVIEW_FAILED, + XFA_PREVIEW_PAGE_INCONSISTENT, + XFA_PREVIEW_STALE, + XFA_PREVIEW_UNAVAILABLE, + XFA_PREVIEW_VALUE_MISMATCH, + PreviewIdentityContext, + build_preview_identity_fingerprint, + is_preview_identity_stale, + shipping_error_code_for_preview, +) +from app.services.shipping_notice.document_layout.xfa_preview_renderer import RENDERER_VERSION +from app.services.shipping_notice.progress_audit_contract import XFA_PROGRESS_EVENT_CODES + +pytestmark = pytest.mark.pure_unit + + +def _identity(**overrides) -> PreviewIdentityContext: + """构造最小 PreviewIdentityContext。""" + base = dict( + document_id=10, + layout_version_id=20, + structure_analysis_id='sa-1', + source_content_hash='a' * 64, + template_packet_checksum='t' * 64, + datasets_packet_checksum='d' * 64, + dataset_structure_fingerprint='f' * 64, + preview_render_checksum='r' * 64, + render_mode=RENDER_MODE, + renderer_version=RENDERER_VERSION, + page_count=2, + ) + base.update(overrides) + return PreviewIdentityContext(**base) + + +def test_preview_identity_fingerprint_stable(): + """关键断言:相同身份字段指纹稳定可复现。""" + left = build_preview_identity_fingerprint(_identity()) + right = build_preview_identity_fingerprint(_identity()) + assert left == right + assert len(left) == 64 + + +def test_preview_identity_stale_when_checksum_or_analysis_changes(): + """关键断言:render checksum 或 analysis_id 变化 → stale。""" + expected = _identity() + assert is_preview_identity_stale(expected=expected, actual=_identity()) is False + assert is_preview_identity_stale( + expected=expected, + actual=_identity(preview_render_checksum='z' * 64), + ) is True + assert is_preview_identity_stale( + expected=expected, + actual=_identity(structure_analysis_id='sa-2'), + ) is True + assert is_preview_identity_stale( + expected=expected, + actual=_identity(datasets_packet_checksum='x' * 64), + ) is True + + +def test_preview_error_codes_and_audit_events_registered(): + """关键断言:预览错误码与审计事件已注册到契约 allowlist。""" + assert { + XFA_PREVIEW_STALE, + XFA_PREVIEW_FAILED, + XFA_PREVIEW_UNAVAILABLE, + XFA_PREVIEW_PAGE_INCONSISTENT, + XFA_PREVIEW_VALUE_MISMATCH, + } <= XFA_PREVIEW_ERROR_CODES + assert XFA_PREVIEW_ERROR_CODES <= XFA_ERROR_CODES + assert XFA_PREVIEW_AUDIT_EVENT_TYPES <= XFA_AUDIT_EVENT_TYPES + assert XFA_PREVIEW_AUDIT_EVENT_TYPES <= XFA_PROGRESS_EVENT_CODES + assert shipping_error_code_for_preview(XFA_PREVIEW_STALE).startswith( + 'SHIPPING.ORDER_DOCUMENT_PROFILE_' + ) + + +def test_preview_cache_get_set_invalidate(): + """关键断言:缓存按身份键读写;invalidate 后不可读。""" + clear_preview_cache() + key = build_preview_cache_key( + structure_analysis_id='sa-1', + template_packet_checksum='t' * 64, + datasets_packet_checksum='d' * 64, + dataset_structure_fingerprint='f' * 64, + source_content_hash='a' * 64, + renderer_version=RENDERER_VERSION, + ) + assert get_preview_cache(key) is None + set_preview_cache(key, {'status': 'ready', 'preview_render_checksum': 'r' * 64}) + hit = get_preview_cache(key) + assert hit is not None + assert hit['status'] == 'ready' + invalidate_preview_cache(key) + assert get_preview_cache(key) is None + clear_preview_cache() diff --git a/backend/tests/test_shipping_xfa_preview_renderer.py b/backend/tests/test_shipping_xfa_preview_renderer.py new file mode 100644 index 00000000..ed2f5b25 --- /dev/null +++ b/backend/tests/test_shipping_xfa_preview_renderer.py @@ -0,0 +1,61 @@ +""" +tests/test_shipping_xfa_preview_renderer.py + +用途:硬冻结后验收——完整 flatten 未就绪时 compose 必须 needs_review,禁止 overlay ready。 +依赖:xfa_preview_renderer、xfa_preview_contract、pytest。 +逻辑:断言空 PDF failed;任意有效输入均不得 status=ready;diagnostics.reason=flatten_engine_unavailable。 +""" + +from __future__ import annotations + +import pytest + +from app.services.shipping_notice.document_layout.xfa_preview_contract import ( + RENDER_MODE, + XFA_PREVIEW_UNAVAILABLE, +) +from app.services.shipping_notice.document_layout.xfa_preview_renderer import ( + RENDERER_VERSION, + attempt_offline_xfa_flatten, + compose_xfa_dataset_preview_pages, +) + +pytestmark = pytest.mark.pure_unit + + +def test_compose_without_flatten_engine_is_needs_review_not_ready(): + """关键断言:flatten 未交付 → needs_review,绝非 ready(禁 overlay)。""" + result = compose_xfa_dataset_preview_pages( + pdf_bytes=b'%PDF-1.4 minimal', + analysis_or_nodes={'/data/HEADER/EBELN': '4510039227'}, + page_boxes=[{'page_no': 1, 'width': 612.0, 'height': 792.0}], + ) + assert result.status == 'needs_review' + assert result.error_code == XFA_PREVIEW_UNAVAILABLE + assert result.pages == [] + assert result.preview_render_checksum is None + assert result.render_mode == RENDER_MODE + assert result.renderer_version == RENDERER_VERSION + assert result.diagnostics.get('reason') == 'flatten_engine_unavailable' + assert result.diagnostics.get('operational_status') == 'OPERATIONAL_PENDING' + + +def test_attempt_offline_flatten_same_fail_closed(): + """关键断言:attempt_offline_xfa_flatten 与 compose 同口径 fail-closed。""" + result = attempt_offline_xfa_flatten( + pdf_bytes=b'%PDF-1.4', + analysis_or_nodes={}, + ) + assert result.status == 'needs_review' + assert result.pages == [] + + +def test_empty_pdf_failed_not_ready(): + """关键断言:空 PDF → failed,绝非 ready。""" + result = compose_xfa_dataset_preview_pages( + pdf_bytes=b'', + analysis_or_nodes={'/data/HEADER/EBELN': 'x'}, + ) + assert result.status == 'failed' + assert result.status != 'ready' + assert result.pages == [] diff --git a/backend/tests/test_shipping_xfa_preview_service.py b/backend/tests/test_shipping_xfa_preview_service.py new file mode 100644 index 00000000..295525bc --- /dev/null +++ b/backend/tests/test_shipping_xfa_preview_service.py @@ -0,0 +1,320 @@ +""" +tests/test_shipping_xfa_preview_service.py + +用途:验收 XFA 合成预览服务身份绑定——必须使用冻结 Analysis,stale/mismatch fail-closed。 +依赖:order_document_profile_xfa_preview_service、xfa_preview_cache、Flask app、pytest monkeypatch。 +逻辑:构造 Layout 冻结的 Analysis + 缓存条目;断言缓存身份漂移抛 XFA_PREVIEW_STALE; + 生成路径可 mock compose,避免真实渲染。 +""" + +from __future__ import annotations + +import hashlib +import secrets +from types import SimpleNamespace + +import pytest + +from app.core.errors import ValidationError +from app.extensions import db +from app.models import ( + FileAsset, + ShippingDocumentLayoutVersion, + ShippingOrderDocument, + ShippingOrderIntake, + ShippingXfaStructureAnalysis, + User, +) +from app.services.shipping_notice.document_layout.xfa_preview_cache import ( + clear_preview_cache, + set_preview_cache, +) +from app.services.shipping_notice.document_layout.xfa_preview_contract import ( + RENDER_MODE, + SHIPPING_XFA_PREVIEW_STALE, + SHIPPING_XFA_PREVIEW_UNAVAILABLE, + SHIPPING_XFA_PREVIEW_VALUE_MISMATCH, + preview_identity_to_dict, +) +from app.services.shipping_notice.document_layout.xfa_preview_renderer import RENDERER_VERSION +from app.services.shipping_notice import order_document_profile_xfa_preview_service as preview_svc + + +def _content_hash(seed: str) -> str: + return hashlib.sha256(seed.encode('utf-8')).hexdigest() + + +def _seed_document(*, seed: str) -> ShippingOrderDocument: + """创建带稳定内容哈希的最小附件 Document。""" + token = secrets.token_hex(4) + content_hash = _content_hash(seed) + user = User( + username=f'xfa-preview-{token}', + email=f'xfa-preview-{token}@example.com', + role='user', + status='active', + ) + db.session.add(user) + db.session.flush() + asset = FileAsset( + asset_no=f'FA-XFA-PREVIEW-{token}', + owner_user_id=user.id, + original_filename=f'{seed}.pdf', + storage_provider='minio', + storage_bucket='test', + storage_key=f'preview/{seed}.pdf', + content_hash=content_hash, + file_size=128, + mime_type='application/pdf', + upload_status='ready', + lifecycle_status='referenced', + ) + db.session.add(asset) + db.session.flush() + intake = ShippingOrderIntake( + intake_no=f'SNI-XFA-PREVIEW-{token}', + asset_id=asset.id, + user_id=user.id, + purpose='order_document_profile_sample', + 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=f'{seed}.pdf', + filename=f'{seed}.pdf', + content_hash=content_hash, + classification='order_notice', + parse_status='parsed', + ) + db.session.add(document) + db.session.flush() + return document + + +def _bind_frozen_analysis(document: ShippingOrderDocument, *, fingerprint: str = 'sha256:structure') -> tuple[ + ShippingDocumentLayoutVersion, + ShippingXfaStructureAnalysis, +]: + """写入 Layout 冻结的 StructureAnalysis。""" + analysis = ShippingXfaStructureAnalysis( + document_id=document.id, + layout_version_id=None, + source_content_hash=document.content_hash, + document_kind='xfa_hybrid', + analysis_status='ready', + template_packet_checksum='sha256:template', + datasets_packet_checksum='sha256:datasets', + dataset_structure_fingerprint=fingerprint, + packet_checksums_json={}, + stats_json={}, + security_summary_json={}, + tree_summary_json={'known_path_ids': ['p1']}, + parser_identity='xfa-parser.v1', + contract_version='xfa-contract.v1', + ) + db.session.add(analysis) + db.session.flush() + layout = ShippingDocumentLayoutVersion( + document_id=document.id, + version=1, + status='ready', + source_content_hash=document.content_hash, + parser_key='mineru:test', + parser_name='xfa', + backend='pypdf', + contract_version='shipping_document_layout.v1', + payload_json={ + 'status': 'ready', + 'provider': 'xfa', + 'xfa_capability': { + 'structure_analysis_ready': True, + 'structure_analysis_id': analysis.id, + 'document_kind': 'xfa_hybrid', + 'template_packet_checksum': analysis.template_packet_checksum, + 'dataset_structure_fingerprint': analysis.dataset_structure_fingerprint, + }, + }, + issues_json=[], + attempt_count=1, + ) + db.session.add(layout) + db.session.flush() + analysis.layout_version_id = layout.id + document.current_layout_version_id = layout.id + db.session.commit() + return layout, analysis + + +class _MemoryGrantStore: + """测试用预览授权存储。""" + + def __init__(self) -> None: + self._data: dict[str, str] = {} + + def setex(self, key: str, _ttl: int, value: str) -> None: + self._data[str(key)] = str(value) + + def getdel(self, key: str) -> str | None: + return self._data.pop(str(key), None) + + +@pytest.fixture(autouse=True) +def _clear_preview_cache(): + clear_preview_cache() + yield + clear_preview_cache() + + +def test_list_preview_pages_stale_when_cached_identity_mismatches(app, monkeypatch): + """关键断言:缓存身份与冻结 Analysis 不一致 → SHIPPING.*_XFA_PREVIEW_STALE。""" + with app.app_context(): + document = _seed_document(seed='stale-cache') + layout, analysis = _bind_frozen_analysis(document) + monkeypatch.setattr(preview_svc, '_preview_grant_store', lambda: _MemoryGrantStore()) + monkeypatch.setattr(preview_svc, '_audit', lambda **_kwargs: None) + monkeypatch.setattr(preview_svc.db.session, 'commit', lambda: None) + + # 缓存绑定了错误的 structure_analysis_id / fingerprint + stale_identity = preview_svc._build_identity_context( + document=document, + layout_version_id=int(layout.id), + analysis=analysis, + preview_render_checksum='r' * 64, + page_count=1, + ) + stale_dict = preview_identity_to_dict(stale_identity) + stale_dict['structure_analysis_id'] = int(analysis.id) + 999 + stale_dict['dataset_structure_fingerprint'] = 'sha256:other-structure' + cache_key = preview_svc._cache_key_for_analysis(analysis=analysis, document=document) + set_preview_cache(cache_key, { + 'identity': stale_dict, + 'status': 'ready', + 'error_code': None, + 'render_mode': RENDER_MODE, + 'renderer_version': RENDERER_VERSION, + 'page_count': 1, + 'preview_render_checksum': 'r' * 64, + 'pages': [{'page_no': 1, 'width': 612, 'height': 792, 'png_bytes': b'\x89PNG', 'drawn_field_echoes': []}], + 'diagnostics': {}, + }) + + with pytest.raises(ValidationError) as exc_info: + preview_svc.list_xfa_synthetic_preview_pages(int(document.id), actor_id=1) + assert exc_info.value.code == SHIPPING_XFA_PREVIEW_STALE + + +def test_list_preview_pages_unavailable_when_cache_missing(app, monkeypatch): + """关键断言:无 ready 缓存时 list 直接 UNAVAILABLE(fail-closed)。""" + with app.app_context(): + document = _seed_document(seed='cache-miss') + _bind_frozen_analysis(document) + monkeypatch.setattr(preview_svc, '_audit', lambda **_kwargs: None) + monkeypatch.setattr(preview_svc.db.session, 'commit', lambda: None) + + with pytest.raises(ValidationError) as exc_info: + preview_svc.list_xfa_synthetic_preview_pages(int(document.id), actor_id=1) + assert exc_info.value.code == SHIPPING_XFA_PREVIEW_UNAVAILABLE + + +def test_request_preview_value_mismatch_fail_closed(app, monkeypatch): + """关键断言:即时解析指纹与冻结 Analysis 不一致 → VALUE_MISMATCH。""" + with app.app_context(): + document = _seed_document(seed='value-mismatch') + _bind_frozen_analysis(document, fingerprint='sha256:frozen-fp') + monkeypatch.setattr(preview_svc, '_preview_grant_store', lambda: _MemoryGrantStore()) + monkeypatch.setattr(preview_svc, '_audit', lambda **_kwargs: None) + monkeypatch.setattr(preview_svc.db.session, 'commit', lambda: None) + monkeypatch.setattr( + 'app.services.file_assets.service.read_asset_bytes', + lambda _asset: b'%PDF-1.4 fake', + ) + + fake_outcome = SimpleNamespace( + snapshot={ + 'xfa_capability': { + 'dataset_structure_fingerprint': 'sha256:live-different', + 'packet_checksums': {'datasets': 'sha256:datasets-live'}, + }, + }, + dataset_analysis=SimpleNamespace(leaf_values_by_path={'/a': '1'}), + packet_result=SimpleNamespace(packet_bytes_by_name={}), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.xfa_analysis.analyze_xfa_pdf', + lambda _pdf: fake_outcome, + ) + + with pytest.raises(ValidationError) as exc_info: + preview_svc.request_xfa_synthetic_preview(int(document.id), actor_id=1, force=True) + assert exc_info.value.code == SHIPPING_XFA_PREVIEW_VALUE_MISMATCH + + +def test_request_preview_uses_frozen_analysis_and_mocked_compose(app, monkeypatch): + """关键断言:生成路径绑定冻结 analysis_id,且 compose 结果写入缓存可 list。""" + with app.app_context(): + document = _seed_document(seed='compose-ok') + layout, analysis = _bind_frozen_analysis(document, fingerprint='sha256:ok-fp') + store = _MemoryGrantStore() + monkeypatch.setattr(preview_svc, '_preview_grant_store', lambda: store) + monkeypatch.setattr(preview_svc, '_audit', lambda **_kwargs: None) + monkeypatch.setattr(preview_svc.db.session, 'commit', lambda: None) + monkeypatch.setattr( + 'app.services.file_assets.service.read_asset_bytes', + lambda _asset: b'%PDF-1.4 fake', + ) + + fake_outcome = SimpleNamespace( + snapshot={ + 'xfa_capability': { + 'dataset_structure_fingerprint': 'sha256:ok-fp', + 'packet_checksums': {'datasets': 'sha256:datasets'}, + }, + }, + dataset_analysis=SimpleNamespace(leaf_values_by_path={'/HEADER/EBELN': '4510'}), + packet_result=SimpleNamespace(packet_bytes_by_name={'template': b'