feat(shipping-notice): 收敛复核状态隔离、STP 重试幂等与 XFA 合成预览标注
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
84a881b554
commit
74270adc22
149 files changed
+20111
-3871
No files matched your search
+8
-1
@@ -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
|
||||
|
||||
@@ -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/<int:document_id>/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/<int:document_id>/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/<int:document_id>/xfa/preview/pages/<int:page_no>',
|
||||
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/<int:document_id>/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/<int:profile_id>/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/<int:profile_id>/xfa/automark/jobs/<int:job_id>',
|
||||
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/<int:profile_id>/xfa/automark/suggestions/<string:suggestion_id>/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/<int:profile_id>/xfa/automark/suggestions/<string:suggestion_id>/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/<int:profile_id>/unified-migration/dry-run',
|
||||
methods=['POST'],
|
||||
|
||||
@@ -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/<task_no>/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/<case_no>/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/<case_no>/access/version-history',
|
||||
methods=['POST'],
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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',
|
||||
}),
|
||||
}
|
||||
|
||||
|
||||
@@ -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])
|
||||
@@ -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',
|
||||
}
|
||||
@@ -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',
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
@@ -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 '')
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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(
|
||||
|
||||
@@ -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<value>-?\d+(?:\.\d+)?)\s*(?P<unit>pt|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
|
||||
]
|
||||
@@ -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),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
+111
-7
@@ -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%。
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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(
|
||||
|
||||
+104
-7
@@ -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),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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},
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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 路径关联。
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
)
|
||||
@@ -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,
|
||||
|
||||
@@ -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 下发);既有动作保持兼容。
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -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,
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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')
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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())
|
||||
@@ -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'
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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 []
|
||||
)
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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'
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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'
|
||||
@@ -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'
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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 == []
|
||||
@@ -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'<template/>'}),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.xfa_analysis.analyze_xfa_pdf',
|
||||
lambda _pdf: fake_outcome,
|
||||
)
|
||||
|
||||
compose_calls: list[dict] = []
|
||||
|
||||
def _fake_compose(**kwargs):
|
||||
compose_calls.append(kwargs)
|
||||
return SimpleNamespace(
|
||||
status='ready',
|
||||
error_code=None,
|
||||
render_mode=RENDER_MODE,
|
||||
renderer_version=RENDERER_VERSION,
|
||||
page_count=1,
|
||||
preview_render_checksum='c' * 64,
|
||||
pages=[{
|
||||
'page_no': 1,
|
||||
'width': 612.0,
|
||||
'height': 792.0,
|
||||
'png_bytes': b'\x89PNG\r\n\x1a\n',
|
||||
'drawn_field_echoes': [{'path_id': 'path-1', 'value': '4510'}],
|
||||
}],
|
||||
diagnostics={'drawn_echo_count': 1},
|
||||
)
|
||||
|
||||
monkeypatch.setattr(preview_svc, 'compose_xfa_dataset_preview_pages', _fake_compose)
|
||||
|
||||
payload = preview_svc.request_xfa_synthetic_preview(int(document.id), actor_id=7, force=True)
|
||||
assert payload['status'] == 'ready'
|
||||
assert payload['identity']['structure_analysis_id'] == int(analysis.id)
|
||||
assert payload['identity']['layout_version_id'] == int(layout.id)
|
||||
assert payload['pages'] and payload['pages'][0]['preview_token']
|
||||
assert 'png_bytes' not in payload['pages'][0]
|
||||
assert len(compose_calls) == 1
|
||||
|
||||
listed = preview_svc.list_xfa_synthetic_preview_pages(int(document.id), actor_id=7)
|
||||
assert listed['cache_hit'] is True
|
||||
assert listed['identity']['structure_analysis_id'] == int(analysis.id)
|
||||
assert listed['page_count'] == 1
|
||||
@@ -177,6 +177,63 @@ def test_preview_token_rejects_replay(app):
|
||||
assert caught.value.details.get('reason') == 'token_replay'
|
||||
|
||||
|
||||
def test_redis_unavailable_fail_closed_outside_memory_allowlist(app, monkeypatch):
|
||||
"""关键断言:非允许环境 Redis 不可用时须 STORE_UNAVAILABLE,不得内存消费成功。"""
|
||||
with app.app_context():
|
||||
app.config['TESTING'] = False
|
||||
app.config['ENV_NAME'] = 'prod'
|
||||
app.config['XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI'] = False
|
||||
|
||||
def _boom():
|
||||
raise RuntimeError('redis down')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.redis_client.get_redis_client',
|
||||
_boom,
|
||||
)
|
||||
rule = _rule_set(status='confirmed')
|
||||
token = _issue_token(app, rule)
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
verify_and_consume_split_preview_token(
|
||||
token,
|
||||
actor_id=7,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_id='path-a',
|
||||
rule_fingerprint=split_rule_preview_fingerprint(rule),
|
||||
sample_checksum=SAMPLE_CHECKSUM,
|
||||
analysis_id=99,
|
||||
template_packet_checksum=FAKE_PATH_CONTEXT['template_packet_checksum'],
|
||||
dataset_structure_fingerprint=FAKE_PATH_CONTEXT['dataset_structure_fingerprint'],
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_CONFIRM_STORE_UNAVAILABLE'
|
||||
|
||||
|
||||
def test_confirm_integrity_propagates_store_unavailable(app, monkeypatch):
|
||||
"""关键断言:确认保存路径不得把 STORE_UNAVAILABLE 误映射为 CONFIRM_REJECTED。"""
|
||||
with app.app_context():
|
||||
app.config['TESTING'] = False
|
||||
app.config['ENV_NAME'] = 'prod'
|
||||
app.config['XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI'] = False
|
||||
monkeypatch.setattr(
|
||||
'app.services.redis_client.get_redis_client',
|
||||
lambda: (_ for _ in ()).throw(RuntimeError('redis down')),
|
||||
)
|
||||
rule = _rule_set(status='confirmed')
|
||||
token = _issue_token(app, rule)
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
_enforce_split_rule_confirmation_integrity(
|
||||
previous_definition={},
|
||||
definition={'split_rules': [rule]},
|
||||
confirmation_tokens={'path-a': token},
|
||||
actor_id=7,
|
||||
profile_id=11,
|
||||
document_id=22,
|
||||
path_context=FAKE_PATH_CONTEXT,
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_CONFIRM_STORE_UNAVAILABLE'
|
||||
|
||||
|
||||
def test_preview_token_rejects_sample_checksum_mismatch(app):
|
||||
"""关键断言:样本 checksum 不匹配时确认须被拒绝。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -248,6 +248,8 @@ def test_confirm_service_calls_record_audit_when_definition_ready():
|
||||
browser_session_id='sess',
|
||||
lease_token='lease',
|
||||
operation_id='op-1',
|
||||
preview_render_checksum='sha256:' + ('d' * 64),
|
||||
render_mode='xfa_dataset_preview',
|
||||
)
|
||||
assert result['status'] == 'confirmed'
|
||||
assert audit_mock.call_count == 1
|
||||
|
||||
@@ -105,10 +105,12 @@ def test_visual_binding_audit_events_registered():
|
||||
|
||||
|
||||
def test_confirm_visual_binding_writes_before_after_audit(app):
|
||||
"""确认视觉绑定必须写入 before/after 审计摘要。"""
|
||||
"""确认视觉绑定必须写入 before/after 审计摘要,且须携带合成预览 checksum。"""
|
||||
from app.services.shipping_notice import order_document_profile_visual_binding_service as svc
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_contract import RENDER_MODE
|
||||
|
||||
checksum = 'sha256:' + ('c' * 64)
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
@@ -149,7 +151,7 @@ def test_confirm_visual_binding_writes_before_after_audit(app):
|
||||
with patch.object(svc.db.session, 'flush', lambda: None):
|
||||
with patch.object(svc.db.session, 'commit', lambda: None):
|
||||
with patch.object(svc, 'record_visual_binding_audit') as audit_mock:
|
||||
svc.confirm_xfa_visual_binding(
|
||||
result = svc.confirm_xfa_visual_binding(
|
||||
1,
|
||||
'bind-test-001',
|
||||
visual_binding={
|
||||
@@ -162,6 +164,8 @@ def test_confirm_visual_binding_writes_before_after_audit(app):
|
||||
actor_id=1,
|
||||
browser_session_id='tab',
|
||||
lease_token='lease',
|
||||
preview_render_checksum=checksum,
|
||||
render_mode=RENDER_MODE,
|
||||
)
|
||||
audit_mock.assert_called_once()
|
||||
kwargs = audit_mock.call_args.kwargs
|
||||
@@ -170,3 +174,71 @@ def test_confirm_visual_binding_writes_before_after_audit(app):
|
||||
assert kwargs['after']['status'] == 'confirmed'
|
||||
assert kwargs['before']['normalized_bbox']['x0'] == 0.1
|
||||
assert kwargs['after']['normalized_bbox']['x0'] == 0.11
|
||||
assert result['visual_binding']['preview_render_checksum'] == checksum
|
||||
assert result['visual_binding']['render_mode'] == RENDER_MODE
|
||||
assert result['visual_binding']['confirmed_on'] == RENDER_MODE
|
||||
|
||||
|
||||
def test_confirm_visual_binding_requires_synthetic_preview_checksum(app):
|
||||
"""关键断言:缺 preview_render_checksum / render_mode 时确认 fail-closed。"""
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice import order_document_profile_visual_binding_service as svc
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'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': [],
|
||||
},
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [{
|
||||
'binding_id': 'bind-test-002',
|
||||
'field_id': 'f-po',
|
||||
'field_code': 'customer_po_no',
|
||||
'scope': 'header',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-ebeln',
|
||||
'data_path': '/data/HEADER/EBELN',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.9,
|
||||
},
|
||||
}],
|
||||
}
|
||||
with patch.object(lease_service, 'require_active_lease', return_value=object()):
|
||||
with patch.object(svc, '_profile') as profile_mock:
|
||||
profile = type('P', (), {
|
||||
'id': 1,
|
||||
'status': 'draft',
|
||||
'template_mode': 'xfa_dataset',
|
||||
'definition_json': definition,
|
||||
})()
|
||||
profile_mock.return_value = profile
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
svc.confirm_xfa_visual_binding(
|
||||
1,
|
||||
'bind-test-002',
|
||||
visual_binding={
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.11, 'y0': 0.11, 'x1': 0.31, 'y1': 0.21},
|
||||
'source': 'manual_draw',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
path_id=None,
|
||||
actor_id=1,
|
||||
browser_session_id='tab',
|
||||
lease_token='lease',
|
||||
)
|
||||
assert caught.value.code == (
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_CONFIRM_REQUIRES_SYNTHETIC_PREVIEW'
|
||||
)
|
||||
@@ -29,7 +29,7 @@ def _source_contract() -> dict:
|
||||
|
||||
|
||||
def _confirmed_binding(*, field_id: str, field_code: str, status: str = 'confirmed') -> dict:
|
||||
"""构造最小统一绑定。"""
|
||||
"""构造最小统一绑定(原生 PDF 画布确认证据)。"""
|
||||
return {
|
||||
'binding_id': f'bind-{field_id}-aaaa-bbbb',
|
||||
'field_id': field_id,
|
||||
@@ -46,6 +46,10 @@ def _confirmed_binding(*, field_id: str, field_code: str, status: str = 'confirm
|
||||
'source': 'manual_draw',
|
||||
'status': status,
|
||||
'confidence': 1.0,
|
||||
**({
|
||||
'render_mode': 'native_pdf',
|
||||
'confirmed_on': 'native_pdf',
|
||||
} if status == 'confirmed' else {}),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -86,13 +90,20 @@ def test_dual_binding_source_blocks_publish():
|
||||
|
||||
|
||||
def test_unconfirmed_visual_binding_blocks_publish():
|
||||
"""关键断言:正式字段视觉状态非 confirmed → xfa_visual_binding_incomplete。"""
|
||||
"""关键断言:坐标类字段未确认视觉框 → incomplete;datasets 仅 suggested 视觉不阻断。"""
|
||||
coord = _confirmed_binding(field_id='f-h-po', field_code='customer_po_no', status='suggested')
|
||||
coord['value_binding'] = {
|
||||
'type': 'pdf_coordinate',
|
||||
'region_id': 'region-po',
|
||||
'path_id': None,
|
||||
'data_path': None,
|
||||
}
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [_confirmed_binding(field_id='f-h-po', field_code='customer_po_no', status='suggested')],
|
||||
'bindings': [coord],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
@@ -100,9 +111,21 @@ def test_unconfirmed_visual_binding_blocks_publish():
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_visual_binding_incomplete' for item in blocking)
|
||||
|
||||
datasets_only = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [_confirmed_binding(field_id='f-h-po', field_code='customer_po_no', status='suggested')],
|
||||
}
|
||||
assert _blocking_xfa_visual_bindings(
|
||||
definition=datasets_only,
|
||||
schema_field_ids={'f-h-po'},
|
||||
) == []
|
||||
|
||||
|
||||
def test_confirmed_bindings_pass_visual_gate():
|
||||
"""关键断言:全部正式字段 confirmed → 无视觉阻断。"""
|
||||
"""关键断言:datasets path 可发布(视觉可选);原生 PDF confirmed 不阻断。"""
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
@@ -117,6 +140,76 @@ def test_confirmed_bindings_pass_visual_gate():
|
||||
assert blocking == []
|
||||
|
||||
|
||||
def test_legacy_synthetic_confirmed_requires_reconfirm():
|
||||
"""关键断言:旧 xfa_dataset_preview 确认框视为未重确认。"""
|
||||
binding = _confirmed_binding(field_id='f-h-po', field_code='customer_po_no')
|
||||
binding['visual_binding']['confirmed_on'] = 'xfa_dataset_preview'
|
||||
binding['visual_binding']['render_mode'] = 'xfa_dataset_preview'
|
||||
# 仅视觉过期时 datasets path 仍可发布;若清掉 path 才 incomplete。
|
||||
binding['value_binding']['type'] = 'pdf_coordinate'
|
||||
binding['value_binding']['region_id'] = 'region-po'
|
||||
binding['value_binding']['path_id'] = None
|
||||
binding['value_binding']['data_path'] = None
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [binding],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_visual_binding_incomplete' for item in blocking)
|
||||
|
||||
|
||||
def test_confirmed_bindings_missing_renderer_version_no_longer_block():
|
||||
"""关键断言:本期不再要求 renderer_version / synthetic checksum。"""
|
||||
binding = _confirmed_binding(field_id='f-h-po', field_code='customer_po_no')
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [binding],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert blocking == []
|
||||
assert not any(item.get('key') == 'xfa_preview_renderer_version_mismatch' for item in blocking)
|
||||
|
||||
|
||||
def test_confirmed_bindings_missing_page_identity_no_longer_block():
|
||||
"""关键断言:本期不再要求 synthetic 页身份。"""
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [_confirmed_binding(field_id='f-h-po', field_code='customer_po_no')],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert blocking == []
|
||||
assert not any(item.get('key') == 'xfa_preview_page_identity_missing' for item in blocking)
|
||||
|
||||
|
||||
def test_audit_compensation_health_fail_closed():
|
||||
"""关键断言:补偿骨架未完成真实重放 → healthy=False。"""
|
||||
from app.services.shipping_notice.audit_compensation_service import (
|
||||
is_audit_compensation_healthy,
|
||||
reset_compensation_store_for_tests,
|
||||
)
|
||||
|
||||
reset_compensation_store_for_tests()
|
||||
assert is_audit_compensation_healthy() is False
|
||||
|
||||
|
||||
def test_validation_metrics_threshold_blocks_below_100_percent():
|
||||
"""关键断言:摘要指标 < 1.0 时发布门禁阻断。"""
|
||||
blocking = _blocking_xfa_validation_metrics({
|
||||
|
||||
@@ -227,6 +227,7 @@
|
||||
- 订单附件结构化必须支持版本化订单坐标 Profile v2。模板真相为静态文档锚点、表区相对坐标、独立表头布局、明细物理行布局、字段区域到稳定 `field_id + field_code` 的绑定、注册解析器、跨页/终止规则;表头文字只能用于建议、校准和匹配,不能决定最终字段。已发布版本不可原地修改,同模板发布新版本时原子退役旧版本;Run 必须复制完整 published Profile,不能只保存当前 Profile ID。
|
||||
- **XFA 客户采购订单(PO)数据路径 Profile(2026-08-04)**:对含 `/XFA datasets` 且 datasets 已保存最终业务值的混合型 XFA PDF,新增 `template_mode=xfa_dataset`,从受控 XML 路径提取 Header/Line;普通 PDF 继续 `coordinate`。第一版不执行 XFA 脚本/FormCalc、不自动合并多明细集合、不回退 OCR/VLM/猜列;管理员在映射工作台选择唯一权威集合并绑定冻结 Schema 字段。正式提取须精确命中唯一 published Profile,并完成 AcroForm/镜像集合/业务恒等式对账;失败一律 `needs_review`。自动建单与坐标路径共用 Schema `auto_creation_policy` / 统一 Candidate Qualification(**无**独立 XFA 自动建单环境变量);须客户/checksum/场景白名单、当前 checksum 盲测批准与 CQ 全绿后方可试点;5 日 live shadow 与生产审批完成前不得开启生产自动建单。Dify 不参与 XFA 解析(见 [xfa-profile-dify-config.md](features/shipping-notice/xfa-profile-dify-config.md))。权威方案/验收:[xfa-profile-implementation-plan.md](features/shipping-notice/xfa-profile-implementation-plan.md)、[xfa-profile-acceptance.md](features/shipping-notice/xfa-profile-acceptance.md)。
|
||||
- **XFA 统一视觉标注、字段拆分与精确解析(2026-08-05 冻结)**:普通 PDF 与 XFA 共用同一页面画框工作台;XFA 正式值仍只从 datasets 读取,页面框仅作视觉证据。所有正式字段必须同时具备已确认 `value_binding` 与 `visual_binding`。声明式拆分支持所有 Header/明细字符串字段;匹配优先级固定为 `prefix > regex > position > unmatched`;同优先级冲突 `needs_review`;`evidence_only` 保留但不写 Schema。正则优先 RE2。现有模板一次性迁移到统一 binding,不要求人工从零重建。发布门禁含视觉覆盖、拆分安全、独立盲测与编辑/审核职责分离;自动建单须发布门禁与 CQ/STP 运行门禁全部通过。Dify 不参与解析主链。权威方案:[xfa-unified-visual-split-implementation-plan.md](features/shipping-notice/xfa-unified-visual-split-implementation-plan.md);验收:[xfa-profile-acceptance.md](features/shipping-notice/xfa-profile-acceptance.md) §15;线框:[shipping-xfa-profile-wireframes.md](prototype/shipping-xfa-profile-wireframes.md)。
|
||||
- **XFA 合成预览 + OCR 自动标记(2026-08-06 冻结)**:增量方案。XFA 权威画布为 `template + datasets` 合成预览(PDFium 页图仅辅助);OCR 只做补框/校验/建议,不覆盖 datasets;视觉确认必须在合成预览上并绑定 `preview_render_checksum`;运行时 XFA 失败禁止回退坐标/OCR。阶段 0–4 可上线人工建模(`SHIPPING_NOTICE_XFA_AUTO_CREATE_ENABLED` 默认关);阶段 5 须独立盲测 + CQ/STP + shadow + 审计补偿硬前置后才开自动建单。权威:[xfa-synthetic-preview-ocr-implementation-plan.md](features/shipping-notice/xfa-synthetic-preview-ocr-implementation-plan.md)。
|
||||
- **XFA 字段拆分映射(历史增量,已由统一方案接管)**:早期曾落地多阶段 `stages[]` 流水线与独立 XFA 映射页。统一方案冻结后,拆分语义以 `prefix > regex > position > unmatched` 为准,工作台并入统一画框编辑器;历史契约文档 [xfa-field-split-mapping.md](features/shipping-notice/xfa-field-split-mapping.md) 仅作迁移对照,不再作为新开发权威。
|
||||
- 业务管理员必须通过受控样本页面维护订单坐标 Profile:可配置相对区域、静态锚点、独立表头/明细布局和注册解析器;不得编辑 HTML、原始 bbox、JSON、正则、脚本、Prompt 或结构指纹。草稿更新使用乐观锁;每个明细字段区域必须绑定 Schema 允许的 `pdf_coordinate`/`ocr_coordinate` 来源和最低证据等级;不可变版本可复制为新草稿或退役。
|
||||
- Profile 治理必须保存模板模式、训练样本计数和不含锚点正文的匹配策略摘要;训练/标注样本、盲测样本及其增删、草稿保存、区域/字段绑定变化、测试执行/批准、发布和退役均追加审计。样本文档被训练或盲测引用后不得删除;审计不得保存 PDF、HTML、对象存储地址、正文或凭据。
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
# 订单复核工作台状态隔离契约
|
||||
|
||||
> 状态:**本轮冻结实现契约(2026-08-06)**
|
||||
> 范围:Case/PDF 切换隔离、Evidence focus 消费、Validation Snapshot 绑定、automation 文案、profile_match 权限裁剪
|
||||
> 非范围:Gate Handler 全链补齐、正式邮件多附件第二阶段回归、统一前端 View Model 重构
|
||||
|
||||
---
|
||||
|
||||
## 1. 状态分层
|
||||
|
||||
```text
|
||||
Document / PDF
|
||||
↓
|
||||
Review Case + Draft
|
||||
↓
|
||||
Validation Snapshot
|
||||
↓
|
||||
Build Eligibility / Process Gate / Automation
|
||||
↓
|
||||
Unified Progress Projection(Run 级进度条)
|
||||
```
|
||||
|
||||
| 绑定 | 范围 |
|
||||
| --- | --- |
|
||||
| 顶部 15 步进度 | **整 Run**(切换 PDF 不跳变) |
|
||||
| 字段 / 证据 / 资格 / 当前阻断 / automation | **当前 Case** |
|
||||
|
||||
---
|
||||
|
||||
## 2. Case 切换
|
||||
|
||||
1. 记录目标 `case_no`,递增 `caseLoadGeneration`
|
||||
2. `resetCaseTransientState()`:清空 Case、Evidence、字段/证据焦点、预览、本地错误;**保留** Run 级 `reviewProgressContext`
|
||||
3. 并行请求 Case + Evidence
|
||||
4. 写入前校验 `generation` 与 `requestedCaseNo`
|
||||
5. URL 同步 `case` + `document_id`;清除 `focus`、`candidate`
|
||||
|
||||
同 Run 仅切换 PDF 时:**禁止**走整页 `load()`(会清空进度并误闪「正在加载」);路由 watch 须走轻量 `selectCase`。
|
||||
|
||||
历史版判定:仅 `status=superseded` 或 `version_replaced && case_no≠current_case_no`。
|
||||
同 Run 多 PDF 并列 Case **不是**历史版。
|
||||
|
||||
### Evidence / focus
|
||||
|
||||
- `focus=evidence` **仅首次深链消费一次**,消费后 `router.replace` 删除
|
||||
- 切换 PDF **不得**自动打开证据模式
|
||||
- 普通浮窗:切换时关闭
|
||||
- dock:保留布局,清空旧证据/预览后加载新文档
|
||||
- 切到当前版本:强制关闭浮窗并清历史 banner 上下文
|
||||
|
||||
---
|
||||
|
||||
## 3. Validation Snapshot
|
||||
|
||||
显式校验后 `validation_result_json` 必须绑定:
|
||||
|
||||
```json
|
||||
{
|
||||
"case_no": "SORC-...",
|
||||
"document_id": 137,
|
||||
"draft_version": 3,
|
||||
"validation_checksum": "ab12...",
|
||||
"validated_at": "...",
|
||||
"validated_case_no": "SORC-...",
|
||||
"validated_document_id": 137,
|
||||
"status": "ready|needs_review|not_validated",
|
||||
"issues": [
|
||||
{
|
||||
"field_id": "...",
|
||||
"field_code": "customer_po_number",
|
||||
"display_name": "客户 PO 号",
|
||||
"reason": "empty_after_normalization"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
字段旁红标、Build Eligibility、`field_completeness` Gate 必须消费同一 Snapshot,禁止各自重推断。
|
||||
前端以 `case_no + document_id + draft_version + validation_checksum` 校验归属(无 DB 迁移)。
|
||||
|
||||
前端:响应返回前显示「正在校验」;无新 `validation_checksum` 时显示「待重新校验」,不得继续展示旧红标。
|
||||
|
||||
---
|
||||
|
||||
## 4. Automation 文案
|
||||
|
||||
```text
|
||||
can_auto_create=true ≠ 正在推进
|
||||
```
|
||||
|
||||
| 后端事实 | 用户文案 |
|
||||
| --- | --- |
|
||||
| `automation.status=waiting_to_start` | 已满足自动建单条件,等待系统启动(保留人工确认兜底) |
|
||||
| `queued` / Job 已入队 | 系统正在自动建单(隐藏确认) |
|
||||
| `running` + Task | 系统正在自动推进(隐藏确认) |
|
||||
| `failed` / `manual_fallback` | 自动推进失败,可重试;未 confirmed 时可人工确认 |
|
||||
| 超时无 STP 记录 | `manual_fallback`(阈值 `SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS`) |
|
||||
|
||||
Case 投影字段:`automation: { status, retryable, task_no, can_auto_create, can_build, job_id }`;
|
||||
管理员另附 `technical_progress: { gate_code, status }`。
|
||||
|
||||
STP 入队路径:资格达标 → `ensure_stp_auto_create_for_case` → Job `queued`(幂等键 `stp-auto:{run_no}:doc-{id}:v{ver}`)。
|
||||
|
||||
XFA:`can_auto_create=false` 时不得显示 automating;不放宽冻结门禁。
|
||||
|
||||
---
|
||||
|
||||
## 5. profile_match 权限
|
||||
|
||||
- 判定:`user.role == 'admin'`
|
||||
- 普通用户 Case API:
|
||||
|
||||
```json
|
||||
{
|
||||
"available": false,
|
||||
"visibility": "admin_only"
|
||||
}
|
||||
```
|
||||
|
||||
- 管理员:完整模板审计对象
|
||||
- 禁止仅靠前端 `v-if` 隐藏敏感字段
|
||||
|
||||
---
|
||||
|
||||
## 6. 当前阻断
|
||||
|
||||
- 用户态只允许一个 `current_blocking_gate`
|
||||
- 客户确认通过后不得再投影 `confirm_customer` / 「优先处理:客户已确认」
|
||||
- `pending|queued|running` 技术 Gate 不冒充人工优先处理;普通用户看 `automation.status`
|
||||
|
||||
---
|
||||
|
||||
## 7. 幂等(本轮沿用)
|
||||
|
||||
```text
|
||||
STP 入队:stp-auto:{run_no}:doc-{document_id}:v{draft_version}
|
||||
confirmed / Task 存在后:Case/document 级业务建单锁定
|
||||
```
|
||||
@@ -13,13 +13,13 @@
|
||||
|
||||
> 详细方案/验收/Dify:**[xfa-profile-implementation-plan.md](xfa-profile-implementation-plan.md)**、**[xfa-profile-acceptance.md](xfa-profile-acceptance.md)**、**[xfa-profile-dify-config.md](xfa-profile-dify-config.md)**(Dify = **NONE**)。
|
||||
|
||||
**运行时**:上传物化后 Layout/Extraction Worker 先探测 `/AcroForm` + `/XFA`。`xfa_hybrid` 且 `SHIPPING_NOTICE_XFA_ENABLED=true` 时优先走 `xfa_dataset` Profile;失败回退坐标/OCR/通用确定性,再进入 Dify LLM 辅助复核。普通 PDF 仍走 Coordinate / MinerU / 通用路径。
|
||||
**运行时**:上传物化后 Layout/Extraction Worker 先探测 `/AcroForm` + `/XFA`。`xfa_hybrid` / `pure_xfa` 且 `SHIPPING_NOTICE_XFA_ENABLED=true` 时走 `xfa_dataset` Profile(冻结 Layout → `structure_analysis_id` → datasets → confirmed bindings → confirmed split_rules)。**XFA 正式解析失败一律 `needs_review`,禁止回退坐标/OCR/通用确定性作为正式提取。** 建模阶段唯一标注图源为**离线完整 flatten 有效页**(须与 Acrobat/官方阅读器人眼正式外观一致);**禁止** XFA 壳 PDF、PDFium 壳图、overlay 作为图源/确认/发布证据。OCR 仅可在 flatten 页上作自动标记建议,不得替代 datasets。普通 PDF(`plain_pdf` / 无 XFA 的 `acroform`)仍走 Coordinate / MinerU / 通用路径。权威硬冻结见 [xfa-synthetic-preview-ocr-implementation-plan.md](./xfa-synthetic-preview-ocr-implementation-plan.md) §0。
|
||||
|
||||
**Profile**:`template_mode=xfa_dataset` 鉴别联合 definition;映射工作台选择唯一权威集合并绑定冻结 Schema 字段;验证/盲测/发布复用版本中心,结构签名替代版面签名门禁;published/retired 只读。
|
||||
|
||||
**门禁**:精确唯一 published 命中;权威集合存在;镜像集合与 AcroForm 对账;金额恒等式;其后与坐标路径共用统一 Candidate Qualification / STP 自动建单(Schema `auto_creation_policy`),**无**独立 XFA 自动建单开关 / 审计密钥。
|
||||
|
||||
**故障处理**:XFA 解析未命中或对账失败 → 回退坐标/OCR/通用/Dify;紧急停止用全局 `EXTRACTION_EMERGENCY_STOP`,**不删除**审计与加密快照。完整快照 Fernet 由 `SECRET_KEY` 派生。
|
||||
**故障处理**:XFA 解析未命中、对账失败、合成预览不可用或身份漂移 → `needs_review`(不回退坐标/OCR 正式提取)。紧急停止用全局 `EXTRACTION_EMERGENCY_STOP`,**不删除**审计与加密快照。完整快照 Fernet 由 `SECRET_KEY` 派生。合成预览与 OCR 自动标记见 [xfa-synthetic-preview-ocr-implementation-plan.md](./xfa-synthetic-preview-ocr-implementation-plan.md)。
|
||||
|
||||
**阶段状态**:0–5 PASS;6 并入统一 CQ/STP;7 文档 PASS。
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
# XFA Flatten 引擎重新评审:受控 Acrobat / 官方系 CLI Sidecar
|
||||
|
||||
> 日期:2026-08-06
|
||||
> 性质:**选型评审**(不替代 [xfa-synthetic-preview-ocr-implementation-plan.md](./xfa-synthetic-preview-ocr-implementation-plan.md) §0)
|
||||
> 范围:对照硬冻结(离线、可复现 checksum、禁不受控脚本、人眼≈Acrobat、首期曾禁商业运行时)重新评估「官方系 sidecar」
|
||||
> 结论摘要:**推荐进入受控 POC 的是 Adobe PDF Library + Forms Extension / Datalogics PDF Forms Flattener CLI,而非桌面 Acrobat/Reader `/t` 打印链路。**
|
||||
|
||||
---
|
||||
|
||||
## 1. 评审问题
|
||||
|
||||
上一版冻结写明「首期不引入商业运行时」。现因:
|
||||
|
||||
- 自研完整 XFA flatten 周期与风险过高;
|
||||
- PDFium / overlay 已被明确禁止作为图源;
|
||||
- Golden 标准本身就是 Acrobat/官方阅读器人眼外观;
|
||||
|
||||
故重新评审:**是否允许受控、离线的官方同源引擎以 sidecar 形式接入**。
|
||||
|
||||
---
|
||||
|
||||
## 2. 候选方案对照
|
||||
|
||||
| 方案 | 形态 | 与 Acrobat 外观关系 | 离线 | 可脚本/服务端 | 可复现 checksum | 不受控脚本风险 | 首期可行性 |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| **A. 桌面 Acrobat / Reader + `/t` 打虚拟打印机** | GUI 进程 + 打印队列 | 高(就是桌面渲染) | 可 | 差(Windows GUI、不稳定) | 差(字体/驱动/异步) | 高(COM/打印/交互) | **不推荐** |
|
||||
| **B. Datalogics PDF Forms Flattener CLI** | 官方 Adobe PDF Library 同源商业 CLI | 高(厂商声明匹配 Acrobat Desktop) | 支持 offline `.lic` | 好 | 好(固定版本+输入→输出) | 低(无 JS 执行面,若配置禁脚本) | **推荐 POC** |
|
||||
| **C. Adobe PDF Library + Forms Extension SDK** | 嵌入式 SDK(Datalogics 渠道) | 高(同源) | 可按许可 | 最好 | 最好 | 低(可控 API) | **中长期首选** |
|
||||
| **D. 纯开源自研** | 自建 | 难对齐 Acrobat | 是 | 是 | 是 | 可控 | 周期不可接受作首期达标 |
|
||||
| **E. 客户上传 Acrobat 导出正式 PDF** | 人工 golden | 最高(人验件) | 是 | 是 | 是 | 无 | 仅建模辅助,**不能冒充引擎 ready**(§10 已禁) |
|
||||
|
||||
---
|
||||
|
||||
## 3. 对硬冻结逐条判定
|
||||
|
||||
### 3.1 「首期不引入商业运行时」
|
||||
|
||||
- **原意**:避免不可审计的黑盒、桌面 Acrobat 乱入、以及未评估的商业依赖。
|
||||
- **修订建议(需产品/安全书面确认)**:
|
||||
**允许「受控商业官方同源引擎」**,条件是:
|
||||
1. 供应商为 Adobe 授权渠道(Datalogics / Adobe PDF Library);
|
||||
2. 部署形态为 **离线 sidecar 或进程内 SDK**,禁止调用桌面 GUI;
|
||||
3. 安全评估通过(无任意脚本、无外联激活或已办 offline license);
|
||||
4. 版本钉死 + 输出纳入 `preview_render_checksum` / `renderer_version`;
|
||||
5. Feature flag 默认关,G4 人眼一致通过前不得 `FLATTEN_ENGINE_READY=true`。
|
||||
|
||||
未获书面确认前,代码主路径仍保持 `needs_review`。
|
||||
|
||||
### 3.2 离线 / 禁不受控脚本 / 可复现
|
||||
|
||||
| 要求 | B CLI | C SDK | A 桌面打印 |
|
||||
| --- | --- | --- | --- |
|
||||
| 离线 | offline offline.lic | 许可可控 | 依赖本机 Acrobat 安装 |
|
||||
| 禁不受控脚本 | 需在 POC 中确认关闭 XFA JS | API 层可关 | Reader 可能执行表单脚本 |
|
||||
| 可复现 | 固定 CLI 版本 + 输入字节 → 输出 PDF hash | 同左 | 打印链路难复现 |
|
||||
|
||||
### 3.3 人眼一致性(Golden = Acrobat)
|
||||
|
||||
- B/C 基于 Adobe PDF Library + Forms,厂商明确对标 Acrobat Desktop 渲染,与本产品 Golden 定义同向。
|
||||
- A 虽也是 Acrobat,但打印→虚拟打印机→再转 PDF 引入额外光栅/驱动差,**反而不利于稳定对标**。
|
||||
|
||||
### 3.4 与 HXOPS 部署形态
|
||||
|
||||
| 约束 | 建议 |
|
||||
| --- | --- |
|
||||
| 后端 Linux/Docker 为主 | **优先 B Linux `.bsx` 或 C SDK Linux**;避免绑死 Windows GUI |
|
||||
| Windows Worker 已有 RPA 机 | 可作 **隔离 POC 环境**,不宜作为唯一生产路径 |
|
||||
| Gevent / 同步 Job | sidecar 必须走 **异步 Job**(已有 `SHIPPING_XFA_*` job 模式),超时 fail-closed → `needs_review` |
|
||||
|
||||
---
|
||||
|
||||
## 4. 推荐架构(若批准商业 sidecar)
|
||||
|
||||
```text
|
||||
Admin 请求合成预览
|
||||
│
|
||||
▼
|
||||
order_document_profile_xfa_preview_service
|
||||
│
|
||||
▼
|
||||
XfaFlattenEngine.resolve()
|
||||
│
|
||||
├── flag 关 / 未授权 → NullEngine → needs_review
|
||||
│
|
||||
└── AdobeFormsFlattenSidecar (B 或 C)
|
||||
│
|
||||
├─ 输入:冻结 Analysis 身份下的 PDF(+ 可选 datasets 包)
|
||||
├─ 输出:静态 flatten PDF 字节
|
||||
├─ 再 rasterize → PNG pages + page_identity + checksum
|
||||
└─ renderer_version = adobe_pdfl_forms.<vendor_ver>
|
||||
```
|
||||
|
||||
**禁止**:
|
||||
|
||||
- 桌面 Acrobat `/t` 作为生产路径;
|
||||
- 把 sidecar 失败回退到 PDFium 壳图 / overlay;
|
||||
- 在未开 `SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY` 时返回 ready。
|
||||
|
||||
---
|
||||
|
||||
## 5. POC 准入清单(未完成前不得声称可用)
|
||||
|
||||
1. **法务/采购**:Adobe PDF Library / Forms Extension 或 PDF Forms Flattener 报价与内部使用许可(含 Docker/多实例)。
|
||||
2. **安全**:威胁模型(文件输入、临时目录、无网络、禁 JS、权限最小化);offline license 流程。
|
||||
3. **技术 POC(隔离机)**:
|
||||
- ≥3 hybrid + ≥1 pure(若有)真实客户 XFA;
|
||||
- sidecar 输出 vs Acrobat 打开并排人眼对比;
|
||||
- 同输入两次 checksum 一致;
|
||||
- 失败样本 100% `needs_review`(无空白 ready)。
|
||||
4. **工程**:Job 化、超时、审计事件、`renderer_version` 钉死、与现有 preview grant 对齐。
|
||||
5. **门禁**:仅 POC 通过 + G4 达标后,才允许将 `SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY` 置 true。
|
||||
|
||||
---
|
||||
|
||||
## 6. 明确不推荐项
|
||||
|
||||
1. **Acrobat Reader `/t` + 虚拟打印机**:不稳定、难复现、依赖 GUI、运维与安全面过大。
|
||||
2. **未评估的第三方“免费 XFA 工具”**:与官方 Golden 不对齐,许可与供应链风险。
|
||||
3. **用客户上传正式 PDF 冒充引擎 ready**:违反 §10;最多作人眼交叉样本,不作自动图源。
|
||||
|
||||
---
|
||||
|
||||
## 7. 决策请求(需你确认)
|
||||
|
||||
请选择其一:
|
||||
|
||||
| 选项 | 含义 |
|
||||
| --- | --- |
|
||||
| **B1** | 批准修订冻结:允许 **Datalogics PDF Forms Flattener CLI** 作受控 sidecar;立即启动隔离 POC + 采购/安全并行 |
|
||||
| **B2** | 批准 **Adobe PDF Library + Forms Extension SDK** 嵌入(周期更长,集成更干净) |
|
||||
| **B3** | 仅做桌面 Acrobat `/t` 可行性探针(**不建议**作生产,仅留档) |
|
||||
| **B0** | 暂不开放商业运行时;继续只保持 fail-closed |
|
||||
|
||||
**评审组建议:选 B1(快)或 B2(稳);不要选 B3 作生产路径。**
|
||||
|
||||
## 8. 免费开源候选速览(2026-08-06)
|
||||
|
||||
| 项目 | 许可 | 实际能力 | 能否满足 §0「≈Acrobat 人眼外观」 |
|
||||
| --- | --- | --- | --- |
|
||||
| **xfa-rescue** | MIT | datasets 填值 + Poppler `pdftoppm` 出静态图;**不**跑完整 LiveCycle/XFA 脚本与动态布局 | **否**(自述不 emulate Adobe runtime) |
|
||||
| **pdfer / xfa-web** | 开源 | 结构提取、填 datasets、Web 表单;flatten 非 Acrobat 级渲染 | **否** |
|
||||
| **xfa-extract / xfa-fill** | MIT | 只提取/回写 datasets,不做页面 flatten | **否** |
|
||||
| **PDFium + XFA+V8** | BSD 系 | 可选编译开启 XFA;实验性,需 V8;与 Acrobat 一致性无保证;触发「不受控脚本」红线 | **高风险 / 基本否** |
|
||||
| **Poppler / LibreOffice** | 开源 | **不支持**完整 XFA 渲染 | **否** |
|
||||
| **iText pdfXFA** | **商业** | 有免费在线 demo,库本身需授权 | 非免费开源 |
|
||||
| **PDFluent** | 源码可见但**非 OSI 开源**;引擎不可抽取嵌入 | 桌面可 flatten | 不合规嵌入后端 |
|
||||
|
||||
**结论:** 目前**没有**免费开源引擎能稳定达到你们 Golden(Acrobat 人眼正式外观 + 动态 XFA)。开源只适合 datasets 提取(你们已有)或实验性探测,不能作为达标 flatten 图源。
|
||||
@@ -0,0 +1,227 @@
|
||||
# XFA 原生 PDF 画布 + 字段级混合数据源实施方案
|
||||
|
||||
> 状态:**需求硬冻结(2026-08-07 夜 · UI 纯增量)**;**A1 属性区 DOM 合并已落地**;**OCR 已断开 synthetic preview**(置信度 ≈ 97%)
|
||||
> 日期:2026-08-07
|
||||
> 性质:**产品口径改写**——尽快可用;以原生 PDF 标注台为主;字段级准确取值;不宣称 Acrobat 级 XFA 动态外观还原
|
||||
> 废止:2026-08-06 晚 §0「唯一 flatten 图源 / 禁壳图 / 全环境禁发 / flatten 阻断标注与发布」全部约束
|
||||
> **产品一句话**:XFA 不是第二种标注产品,而是普通 PDF 标注页面上的一种字段读取方式。
|
||||
|
||||
权威冻结语义以本文 **§0 + §0.1** 为准。
|
||||
历史统一视觉方案见 [xfa-unified-visual-split-implementation-plan.md](./xfa-unified-visual-split-implementation-plan.md)。
|
||||
Flatten 商业引擎评审(未来专项)见 [xfa-flatten-engine-acrobat-sidecar-review.md](./xfa-flatten-engine-acrobat-sidecar-review.md)。
|
||||
|
||||
---
|
||||
|
||||
## 0. 最终验收定义(硬冻结)
|
||||
|
||||
> 同一模板、同一普通 PDF 标注界面;画布为 PDFium 原生页图;每个业务字段独立选择正式取值来源(`xfa_dataset` / `pdf_coordinate` / `ocr_coordinate`)。本方案解决「准确取值与可建模发布」,不解决「完整还原 Acrobat 中的 XFA 动态外观」。datasets 覆盖仅为建模辅助,不得宣称与 flatten/Acrobat 外观等价。
|
||||
|
||||
| 项 | 冻结口径 |
|
||||
| --- | --- |
|
||||
| 产品壳 | **唯一页面** `OrderProfileEditorPage`;同一画布/工具栏/属性区 DOM;XFA 只插条件增量 |
|
||||
| 编辑画布 | **唯一编辑图源** = `authorizeOrderProfilePreviewPages` → PDFium 页图;与非 XFA 同路径 |
|
||||
| `/xfa/preview` synthetic | **不作编辑画布**;可保留诊断/审计/未来 flatten 专项;暂不删接口 |
|
||||
| 坐标系 | `normalized_bbox` 绑定**原生 PDF 页**;旧 `confirmed_on=xfa_dataset_preview` / flatten checksum 框不自动迁移,降级重确认 |
|
||||
| 混合数据源 | 同模板可混用;UI:标签右侧/坐标=`pdf_coordinate`,OCR=`ocr_coordinate`,XFA datasets=`xfa_dataset`;无 `manual` |
|
||||
| datasets 字段 | 正式值读 path;**视觉框可选**;无框可发布结构映射,但不得声称有视觉证据 |
|
||||
| 坐标/OCR 字段 | 必须已确认视觉框;OCR 另需 OCR 配置 |
|
||||
| 明细集合 | 正式取值仅 `ITEMS[*]` + 列映射;集合重确认入口收进属性区「数据源摘要 → 重新确认集合」弹窗 |
|
||||
| datasets 覆盖 | 默认开;开关在属性区「样本值显示」;**无**画布上方独立开关条;关后可确认,轻量提示 |
|
||||
| 跨源对账 | 正式值永不被 OCR 覆盖;仅启用对账的字段;发布前未处理 mismatch=0;运行时 → `needs_review` |
|
||||
| 空白壳 | 允许仅 datasets 结构映射发布;**无**专用黄条;警告并入普通画布/属性提示槽 |
|
||||
| 发布 | 字段门禁通过即可发;**移除** flatten/synthetic/renderer/checksum 硬门禁 |
|
||||
| Flatten / 自动建单 | flatten flag 与 XFA 专属 auto-create **不参与**画布、发布、`can_auto_create` |
|
||||
| G4 | ≥5 真实客户 XFA;验收=混合数据源+原生画布+datasets+OCR/拆分;不绑 flatten 人眼一致 |
|
||||
|
||||
**最终验收口令:**
|
||||
|
||||
> 关闭所有 XFA 增量后,页面结构、画布、工具栏和属性区与普通 PDF 无法区分;开启 XFA 后,只增加「读取方式为 datasets 时的数据源、样本值、拆分规则」,以及普通建议区中的可折叠 OCR 建议。
|
||||
|
||||
---
|
||||
|
||||
## 0.1 UI 纯增量硬冻结(2026-08-07 夜,不再扩展)
|
||||
|
||||
### 必须成立
|
||||
|
||||
```text
|
||||
一个页面 · 一个画布 · 一套工具栏 · 一套普通字段属性区 DOM(A1)
|
||||
三个 XFA 增量:
|
||||
1. 读取方式中的 XFA datasets + 数据源字段 + 样本值
|
||||
2. 拆分规则维护(属性区一行 + 现有弹窗)
|
||||
3. 普通建议区可折叠 OCR 建议(无独立 XfaAutoMarkPanel 外壳)
|
||||
```
|
||||
|
||||
### 属性区(A1)
|
||||
|
||||
- 普通 PDF `aside.config` **原结构保留**;XFA **只插入条件增量**。
|
||||
- 选中框时保留:标签 / Schema、明细表区设置、锚点提示、识别结果、原有确认/删除等。
|
||||
- XFA 额外:读取方式、数据源字段、datasets 样本值、拆分规则;集合重确认收进「数据源摘要 → [重新确认集合]」。
|
||||
- 普通 PDF 继续现有读取方式;XFA 在**同一控件**增加 `XFA datasets`。
|
||||
|
||||
### 必须从最终 UI 删除(不做折叠保留)
|
||||
|
||||
- 「预览与 OCR 状态」整块
|
||||
- 独立「明细集合 / 权威集合 / 重新确认集合」主面板
|
||||
- 「必填覆盖」页面级汇总
|
||||
- 独立 `XfaAutoMarkPanel` 外壳
|
||||
- 画布上方 datasets 覆盖开关条
|
||||
- 空白壳黄色专用警告条
|
||||
|
||||
错误/加载/重试 → 普通 PDF 画布已有槽位。
|
||||
|
||||
### 画布与工具栏
|
||||
|
||||
- 必须完整工具集(选择/画框/移动/复制/删除/撤销重做/锚点/表头/明细行/排除/自动建议/缩放翻页)。
|
||||
- **禁止**用户可见的 `xfa_visual` 精简工具集名称或工具限制。
|
||||
|
||||
### 识别结果
|
||||
|
||||
- 原样保留该区域;按读取方式显示 datasets 样本值 / 坐标值 / OCR+置信度;不新增独立 XFA 结果面板。
|
||||
|
||||
### 数据层
|
||||
|
||||
- `useOrderProfileXfaDesk` 可暂留为数据层:不渲染独立工作台、不维护独立画布、不决定页面布局。
|
||||
- 后端旧 synthetic / `assert_xfa_synthetic_preview_gate` 可暂留,但须断开编辑画布与发布硬门禁;不要求本轮物理删除。
|
||||
|
||||
### 禁止再出现
|
||||
|
||||
独立 XFA 工作台 / 画布 / 工具栏 / 左栏树 / 全屏错误壳 / XFA 专属自动建单分支。
|
||||
|
||||
产品形态一句话:
|
||||
|
||||
> XFA 不是第二种标注产品,而是普通 PDF 标注页面上的一种字段读取方式。
|
||||
|
||||
---
|
||||
|
||||
## 1. 职责分层
|
||||
|
||||
| 层 | 职责 |
|
||||
| --- | --- |
|
||||
| 原生 PDF 页图 | **编辑/标注画布**与视觉确认坐标系 |
|
||||
| XFA datasets | `type=xfa_dataset` 字段的**正式业务值** |
|
||||
| OCR / 坐标 | 可见内容的正式取值(各自 binding type);不得覆盖 datasets 正式值 |
|
||||
| datasets 覆盖层 | 建模辅助显示样本值;非正式外观、非 flatten |
|
||||
| 人工确认 | 映射/拆分/视觉确认生效条件 |
|
||||
|
||||
禁止:OCR 自动覆盖 datasets 正式值;未配置正式数据源的必填字段发布;把原生空白壳 + 简单覆盖宣称成完整 flatten。
|
||||
|
||||
---
|
||||
|
||||
## 2. 冻结语义摘要(与 §0 对齐)
|
||||
|
||||
1. 编辑画布 = PDFium 原生页;XFA 与非 XFA 同路径加载预览。
|
||||
2. `normalized_bbox` = 原生 PDF 页坐标;旧 synthetic/flatten 确认框降级重确认。
|
||||
3. 同模板字段可混用三种 `value_binding.type`;无 `manual` 运行时类型。
|
||||
4. `xfa_dataset`:path 必填,视觉可选;`pdf_coordinate` / `ocr_coordinate`:confirmed 视觉必填。
|
||||
5. 明细正式取值 = 集合通配 + 列映射;可选视觉辅助不进 datasets 硬门禁。
|
||||
6. 跨源 mismatch:运行时 `needs_review`;发布前未处理数必须为 0;比对范围收窄到显式对账字段。
|
||||
7. 发布允许人工建模通过字段门禁后上线;去掉 flatten/synthetic/renderer/checksum 硬阻断。
|
||||
8. Flatten 相关 flag 仅未来专项;不进当前画布、发布、`can_auto_create`。
|
||||
9. `can_auto_create` 不按模板类型硬编码关死;本方案也不主动开启自动建单。
|
||||
10. 空白壳可结构发布;警告并入普通画布/属性提示槽(无专用黄条);OCR/坐标不可无证据发布。
|
||||
11. G4 改为新能力闭环验收,不绑 Acrobat flatten 外观。
|
||||
12. `/xfa/preview` 保留但不驱动编辑画布。
|
||||
13. UI 必须 A1:同一 `aside.config` DOM;禁止 XFA 整支 `v-if` 属性区;禁止用户可见 `xfa_visual` 精简工具集。
|
||||
14. 最终验收口令见 §0:关增量后与普通 PDF 无法区分。
|
||||
|
||||
---
|
||||
|
||||
## 3. 发布最低集(本期)
|
||||
|
||||
必须满足:
|
||||
|
||||
- 必填 Schema 字段均已配置正式数据源之一;
|
||||
- datasets path 存在且可读取;
|
||||
- 集合使用通配 path + 列映射,且集合 path **样本值可读**;
|
||||
- 若配置拆分规则,另过拆分预览/确认门禁;
|
||||
- OCR/坐标字段具备 confirmed visual binding(OCR 另需配置);
|
||||
- 未处理跨源 mismatch = 0;
|
||||
- 审计日志完整。
|
||||
|
||||
明确**不**作为本期发布硬门禁:
|
||||
|
||||
- flatten engine ready;
|
||||
- synthetic preview ready;
|
||||
- renderer_version 一致;
|
||||
- preview checksum 绑定。
|
||||
|
||||
---
|
||||
|
||||
## 4. 上线分界与 G4
|
||||
|
||||
| 阶段 | 内容 | 上线含义 |
|
||||
| --- | --- | --- |
|
||||
| 0 | 文档硬冻结(§0 + §0.1 UI 纯增量) | **已完成** |
|
||||
| 1 | 画布切回原生 PDF;解除 flatten 对标注/发布阻断 | **代码已切** |
|
||||
| 2 | 放开同模板混合 `value_binding.type`;datasets 视觉可选 | **代码已切** |
|
||||
| 3 | **UI A1**:拆掉 `aside.config` 的 XFA 整支 `v-if`;属性区同一 DOM + 条件增量 | **未达标(本轮主攻)** |
|
||||
| 4 | 删除专用状态块/黄条/覆盖开关条/独立 AutoMark 外壳;OCR 进普通建议区 | **未达标** |
|
||||
| 5 | 完整工具栏;禁止用户可见 `xfa_visual` 精简工具集 | **未达标** |
|
||||
| 6 | 发布门禁按字段最低集;旧框降级;synthetic 断开编辑/发布 | **大部分已切** |
|
||||
| 7 | G4:≥5 真实客户样本按新目标验收 | 未开始 |
|
||||
|
||||
G4 样本目标:混合数据源 + 原生画布 + datasets 映射 + OCR/拆分闭环。
|
||||
|
||||
---
|
||||
|
||||
## 5. 实施文件地图(摘要)
|
||||
|
||||
| 方向 | 位置 |
|
||||
| --- | --- |
|
||||
| **本轮主攻 UI A1** | `OrderProfileEditorPage.vue`:拆掉 `aside.config` 的 XFA 整支 `v-if`;属性区同一 DOM + 条件增量(读取方式/数据源/样本/拆分);删除专用状态块/黄条/覆盖开关条;OCR 进普通建议区;完整工具栏、禁 `xfa_visual` 精简集 |
|
||||
| 数据层 | `useOrderProfileXfaDesk.ts`:可暂留;不渲染独立工作台、不决定布局 |
|
||||
| 覆盖层 | 属性区「样本值显示」选项控制;默认开;关确认轻量提示 |
|
||||
| 契约 | `xfa_contract.py`:同模板混合 binding(已切) |
|
||||
| 发布门禁 | publish_check:字段最低集;无 flatten/synthetic 硬阻断(已切) |
|
||||
| 资格 | `candidate_qualification_service.py`:无 XFA flatten/专属 flag(已切) |
|
||||
| 后端旧路径 | synthetic API / `assert_xfa_synthetic_preview_gate`:断开编辑与发布即可,本轮不物理删除 |
|
||||
| 测试 | A1 属性区同树 / 工具栏完整 / 删除专用块 / vitest |
|
||||
|
||||
---
|
||||
|
||||
## 6. 与既有文档关系
|
||||
|
||||
| 文档 | 关系 |
|
||||
| --- | --- |
|
||||
| [xfa-unified-visual-split-implementation-plan.md](./xfa-unified-visual-split-implementation-plan.md) | 基线;本方案改写画布与发布口径 |
|
||||
| [technical.md](./technical.md) | 须同步:编辑图源=原生 PDF;混合数据源;发布按字段门禁 |
|
||||
| [xfa-profile-acceptance.md](./xfa-profile-acceptance.md) | 按本文 §0/§3/§4 重写验收 |
|
||||
| [xfa-flatten-engine-acrobat-sidecar-review.md](./xfa-flatten-engine-acrobat-sidecar-review.md) | 降为**未来视觉等价专项**,不阻塞本期 |
|
||||
|
||||
---
|
||||
|
||||
## 7. 能力边界(必须对外一致表述)
|
||||
|
||||
```text
|
||||
datasets 取值:可以准确实现
|
||||
混合 OCR/坐标:可以实现
|
||||
统一画框:可以实现
|
||||
完整 XFA 外观:当前不能保证
|
||||
空白壳上的有效视觉标注:需要位置证据或正式页面图
|
||||
原生空白 PDF + datasets 简单覆盖 ≠ 真正 flatten
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. 历史稿归档(已废止,防回潮)
|
||||
|
||||
### 8.1 2026-08-06 晚 §0(flatten 唯一图源)——**全文废止**
|
||||
|
||||
- ~~唯一图源 = 离线完整 flatten~~
|
||||
- ~~禁止 PDFium 壳图 / 原生 PDF 作画布~~
|
||||
- ~~不能 flatten → needs_review 且禁标注~~
|
||||
- ~~全环境禁止发布 XFA~~
|
||||
- ~~overlay 删除且不得辅助建模~~
|
||||
- ~~G4 绑 Acrobat 人眼一致~~
|
||||
- ~~can_auto_create 绑 flatten / XFA 专属 flag~~
|
||||
|
||||
### 8.2 2026-08-06 下午稿 / UI 收敛轮——部分废止
|
||||
|
||||
仍有效并入本期:EditorPage 共用台、右侧 datasets/拆分/OCR 增量、集合重确认弹窗、AutoMark 默认折叠、专属样式克制。
|
||||
|
||||
废止:flatten 非 ready 禁标注、假 ready 禁壳图(与「原生画布合法」冲突的表述)、全环境禁发。
|
||||
|
||||
### 8.3 Flatten 引擎选型
|
||||
|
||||
商业 flatten sidecar 评审结论仍作未来专项参考;**本期不依赖、不阻塞发布与标注**。
|
||||
`FLATTEN_ENGINE_READY=true` 仅在未来视觉等价专项 POC/G4 通过后考虑。
|
||||
@@ -115,6 +115,13 @@ npm run build
|
||||
| 阶段 6 运维 | 5 日 live shadow / 生产审批仍为 **OPERATIONAL PENDING**(见 xfa-profile-acceptance §9) |
|
||||
| 负载测试 | `test_shipping_xfa_visual_mapping_load` 为本地合成软阈值(2s),不替代生产 P95 SLA |
|
||||
| 旧 definition 分支 | **已移除正式提取运行时兼容**(bindings-only);迁移 Execute 清空 legacy mappings |
|
||||
| BE-1′ Redis 确认令牌 fail-closed | **已收口(本轮)**:消费确认令牌时 Redis 不可用 → `XFA_SPLIT_CONFIRM_STORE_UNAVAILABLE`;Memory JTI 仅 TESTING/单进程开发开关 |
|
||||
| BE-2′ 冻结 structure_analysis_id | **已收口(本轮)**:admin/runtime 一律按 Layout 冻结 ID 精确读;三错误码 MISSING / IDENTITY_MISMATCH / STALE |
|
||||
| BE-3′ Analysis 复用审计 | **已收口(本轮)**:`xfa_structure_analysis_reused` / `reuse_rejected` / `reparse_queued`(仅复用失败后重排队) |
|
||||
| UI-1′ ConfirmStep 加载失败门禁 | **已收口(本轮)**:错误卡 + Reload(树/集合)+ 人工 Re-parse;阻断创建/下一步 |
|
||||
| UI-2′ 四语言错误码 | **已收口(本轮)**:STORE_UNAVAILABLE / XFA_UNAVAILABLE / ANALYSIS_* |
|
||||
| UI-3 分块体积 | **技术债(本轮明确不修)**:ConfirmStep/Workbench 体积;不阻塞验收 |
|
||||
| BE-4′ Legacy DTO 与正式 bindings 契约分离 | **技术债(本轮明确不修)**:迁移可读层仍共存;正式路径已 bindings-only |
|
||||
|
||||
## 5. 自动建单双层门禁(冻结)
|
||||
|
||||
|
||||
@@ -81,10 +81,12 @@
|
||||
| **订单模板版面签名 Matcher** | 代码已落地(待真实样本灰度) | 版面签名存 ValidationRun;Profile 轻量引用;Matcher 三态证据 + Top-N 解析验证;表头签名直接消费既有 `header_layout.region`,签名生成与运行时统一视觉词组和坐标口径;跨模板发布门禁与发布检查页;重识别亲和性校验签名;`SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED` 控制全量切换。说明:[order-profile-layout-signature.md](features/shipping-notice/order-profile-layout-signature.md) |
|
||||
| **XFA 数据路径 Profile(阶段 0–7)** | 阶段 0–7 代码收口 | `template_mode=xfa_dataset`:安全 packet/XML 解析、结构分析、映射工作台、正式提取(失败回退 OCR/通用/Dify)、验证/盲测/发布、完整快照由 `SECRET_KEY` 派生加密(**无独立审计密钥**)、自动建单并入统一 CQ/STP。Dify 主链:**NONE**([xfa-profile-dify-config.md](features/shipping-notice/xfa-profile-dify-config.md))。方案/验收:[xfa-profile-implementation-plan.md](features/shipping-notice/xfa-profile-implementation-plan.md)、[xfa-profile-acceptance.md](features/shipping-notice/xfa-profile-acceptance.md)。 |
|
||||
| **XFA 统一视觉标注 + 字段拆分(阶段 0–8)** | 阶段 0–8 **CODE GATE PASS(2026-08-06)**;评审阻断 UI-1/BE-1~BE-7 **已收口**;生产 shadow / 全量 Execute **OPERATIONAL PENDING** | 普通 PDF/XFA **统一 EditorPage 外壳**;`value_binding` + `visual_binding`;拆分优先级 `prefix > regex > position > unmatched`;RE2;正式提取 bindings-only;视觉/镜像/证据发布门禁;预览确认令牌;敏感值权限审计;CQ/STP 再验;一次性迁移;视觉绑定双写统一加密快照。Dify:**NONE**。权威:[xfa-unified-visual-split-implementation-plan.md](features/shipping-notice/xfa-unified-visual-split-implementation-plan.md);验收 §15:[xfa-profile-acceptance.md](features/shipping-notice/xfa-profile-acceptance.md);合规报告:[xfa-unified-visual-split-compliance-report.md](features/shipping-notice/xfa-unified-visual-split-compliance-report.md)。 |
|
||||
| **XFA 合成预览 + OCR 自动标记(阶段 0–6)** | 阶段 0–5 **代码骨架已落地**;阶段 6 补偿为进程内/Redis 骨架;真实客户资格集 / shadow / 自动建单 flag **OPERATIONAL PENDING** | 权威画布=合成预览;OCR 仅建议;datasets 真值;确认须 `preview_render_checksum`;运行时 XFA 失败不回退;人工建模 0–4 / 自动建单 5+审计补偿。权威:[xfa-synthetic-preview-ocr-implementation-plan.md](features/shipping-notice/xfa-synthetic-preview-ocr-implementation-plan.md)。 |
|
||||
| **XFA 字段拆分映射(历史)** | 已被统一方案接管 | 早期 `stages[]` 流水线与独立映射页能力将在统一方案阶段 1/4 对齐并收口;对照文档:[xfa-field-split-mapping.md](features/shipping-notice/xfa-field-split-mapping.md)。 |
|
||||
| 订单模板录入 UX 重构(阶段 0-7) | 已完成 | 已完成 Draft Revision、Lease、向导、独立草稿编辑器自动保存、不可变验证运行与两步发布报告;样本上传仅负责资产保存和 PDF/EML Document 物化,版面解析作为后台预热且不阻断上传。盲测复核区分准备中、兼容性诊断和正式复核:仅 ready Layout 的真实 table_id 可确认,确认时冻结 LayoutVersion/checksum/parser 身份,执行不回读最新布局;临时 PDF 恢复仅作诊断。同模板族历史 annotation/training/新旧 blind test 文档可重新复核复用,当前版本建模样本仍严格排除。编辑器在可见状态自动续租。Dify 无需配置变更。 |
|
||||
| 订单人工复核工作台(阶段 0-7) | 已实现 | 每个 PDF Unit 一个 Review Case,机器 Candidate/Extraction 不可变、人工 Draft 独立版本化;按 PDF 独立处置、证据复核与原子确认建单,不支持多订单 PDF 或跨 PDF 合并/拆分。字段和明细可按冻结 bbox 定位 PDF 原文(明细按 table/cell 反查),版本历史按需展开;确认后展示 `auto_progress` 真实结果/检查点并可直达任务进度工作台。单 PDF 重识别复用 WorkflowItem 真实状态展示已提交/版面解析/字段提取/草稿生成,完成后自动打开新版;“跳转当前版本”点击时强制刷新工作项,目标未就绪时明确提示。 |
|
||||
| **复核工作台布局重构(阶段 0–5)** | 已实现(待真机视觉签署) | 替换旧三栏:主编辑区 + 阻断摘要侧栏;PDF **默认右下角浮动证据面板**(八向 resize、记忆尺寸位置、展开/移侧;用户主动「固定为侧栏」才双栏),不挤占订单网格;Ctrl/Cmd+滚轮与适合宽度/页面;溢出拖拽平移;双击字段定位与证据联动高亮;异常字段 Alt+[/] 导航;真正按需加载;Chat/证据/pdfjs 异步分包;AI/版本历史/完整检查按需抽屉且审计失败阻断展示;确认与自动推进态解耦并可重试;同事务入队 `shipping_notice_run`;单一主滚动 + sticky 底栏。真机三档 viewport 清单见 layout-plan §11.1。权威方案:[review-workbench-layout-plan.md](features/shipping-notice/review-workbench-layout-plan.md)。 |
|
||||
| **复核工作台状态隔离(Case/证据/资格/自动化)** | 进行中(本轮代码已落地) | Case 切换请求代次 + 瞬态清理;`focus=evidence` 首次消费;Validation Snapshot 绑定 case/draft/validation_version;普通用户 `profile_match` 后端裁剪;客户确认后不再「优先处理:客户已确认」;`can_auto_create` 仅显示「等待系统启动」。契约:[review-workbench-state-isolation-contract.md](features/shipping-notice/review-workbench-state-isolation-contract.md)。 |
|
||||
| **双工作台架构 + Candidate Qualification(阶段 0–6)** | 阶段 0–6 达标(评审整改后) | **已完成**:双工作台边界;Candidate Qualification(追加式快照 + 审计);模板审批不再硬阻断自动建单;对话「本次处理中」轻量侧栏;复核返回对话;货代上传 RPA 可按 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED` 接入自动链;Process Gate 对话内恢复;审计事件字典含 chat_* / qualification / upload_rpa。权威:[review-workbench-layout-plan.md](features/shipping-notice/review-workbench-layout-plan.md) §0。 |
|
||||
| **对话侧 Task 进度与「本次处理中」** | 阶段 2–5 已实现 | 侧栏以用户可见任务(OT)分组为主路径;`ShippingConversationProcessingCard` + processing API;`WF-...` 下沉;发送走统一提交无确认框。 |
|
||||
| **会话多任务聚合与统一提交(阶段 0–5)** | 整改中 | 契约冻结(§1.6.1);统一提交 + 独立 submission 幂等;同 PDF 指纹继承 OT(跨 Schema);投影按「当前有效最新 Run」;未查看 completed 仍可见;任务级取消/重试均走 Run API;状态四语言 + 更新时间。权威:technical.md §1.6.1。 |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/admin/api/shipping-order-document-profile.api.ts
|
||||
* 用途:订单文档 Profile 管理、MinerU 样本选择、XFA 统一建议/视觉绑定与发布 API。
|
||||
* 用途:订单文档 Profile 管理、MinerU 样本选择、XFA 统一建议/视觉绑定/合成预览与发布 API。
|
||||
* 依赖:shared/api/client、auth headers、Profile DTO。
|
||||
* 逻辑:页面只使用结构化接口;结构指纹和 HTML 始终由后端持有;XFA suggest/preview 零写 Draft。
|
||||
*/
|
||||
@@ -291,6 +291,78 @@ export const previewOrderProfileSampleXfaValue = (
|
||||
{ method: 'POST', body: JSON.stringify({ path_id: pathId, reveal: Boolean(options?.reveal) }), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 生成或复用绑定冻结 Analysis 的 XFA 合成预览(身份 + 页元数据,不含大图)。 */
|
||||
export const requestOrderProfileSampleXfaSyntheticPreview = (
|
||||
documentId: number,
|
||||
options?: { force?: boolean },
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaSyntheticPreviewResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/preview`,
|
||||
{ method: 'POST', body: JSON.stringify({ force: Boolean(options?.force) }), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 列出最新 ready 合成预览页并重新签发短时 token。 */
|
||||
export const listOrderProfileSampleXfaSyntheticPreviewPages = (documentId: number) =>
|
||||
requestJson<import('../types/shipping-order-document-profile.types').XfaSyntheticPreviewResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/preview/pages`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/**
|
||||
* 合成预览单页 PNG 的受控路径(配合 preview_token 用 fetch 拉取 blob)。
|
||||
* @param documentId 样本文档 ID
|
||||
* @param pageNo 1-based 页码
|
||||
*/
|
||||
export const orderProfileSampleXfaSyntheticPreviewPagePath = (documentId: number, pageNo: number) =>
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/xfa/preview/pages/${pageNo}`;
|
||||
|
||||
/** 入队 XFA OCR 自动标记 Job(须合成预览 ready)。 */
|
||||
export const enqueueOrderProfileXfaOcrAutomark = (
|
||||
profileId: number,
|
||||
payload: { document_id: number; force?: boolean },
|
||||
) => requestJson<{ job_id: number; status: string; preview_render_checksum?: string }>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/automark`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 轮询 OCR 自动标记 Job 状态与建议。 */
|
||||
export const getOrderProfileXfaOcrAutomarkJob = (profileId: number, jobId: number) =>
|
||||
requestJson<{
|
||||
job_id: number;
|
||||
status: string;
|
||||
suggestions?: Array<Record<string, unknown>>;
|
||||
error_code?: string | null;
|
||||
preview_render_checksum?: string | null;
|
||||
}>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/automark/jobs/${jobId}`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 接受自动标记建议(high→confirmed;medium/low→suggested)。 */
|
||||
export const acceptOrderProfileXfaOcrAutomarkSuggestion = (
|
||||
profileId: number,
|
||||
suggestionId: string,
|
||||
payload: {
|
||||
job_id?: number;
|
||||
preview_render_checksum: string;
|
||||
render_mode?: string;
|
||||
browser_session_id?: string;
|
||||
lease_token?: string;
|
||||
},
|
||||
) => requestJson<Record<string, unknown>>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/automark/suggestions/${encodeURIComponent(suggestionId)}/accept`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 拒绝自动标记建议。 */
|
||||
export const rejectOrderProfileXfaOcrAutomarkSuggestion = (
|
||||
profileId: number,
|
||||
suggestionId: string,
|
||||
payload?: { job_id?: number; browser_session_id?: string; lease_token?: string },
|
||||
) => requestJson<Record<string, unknown>>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/automark/suggestions/${encodeURIComponent(suggestionId)}/reject`,
|
||||
{ method: 'POST', body: JSON.stringify(payload || {}), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 预览拆分规则并签发确认令牌;默认脱敏,reveal 需敏感读权限。 */
|
||||
export const previewOrderProfileSampleXfaSplitRules = (
|
||||
documentId: number,
|
||||
@@ -347,7 +419,7 @@ export const suggestOrderProfileXfaVisualBindings = (
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 确认视觉绑定;须携带 Lease / operation_id。 */
|
||||
/** 确认视觉绑定;须携带 Lease / operation_id / 合成预览证据。 */
|
||||
export const confirmOrderProfileXfaVisualBinding = (
|
||||
profileId: number,
|
||||
bindingId: string,
|
||||
@@ -357,6 +429,8 @@ export const confirmOrderProfileXfaVisualBinding = (
|
||||
browser_session_id: string;
|
||||
lease_token: string;
|
||||
operation_id: string;
|
||||
preview_render_checksum?: string | null;
|
||||
render_mode?: string | null;
|
||||
},
|
||||
) => requestJson<import('../types/shipping-order-document-profile.types').XfaVisualBindingMutationResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/xfa/visual-bindings/${encodeURIComponent(bindingId)}/confirm`,
|
||||
|
||||
+4
-1
@@ -36,6 +36,7 @@ const documentId = ref(0);
|
||||
const tableId = ref('');
|
||||
const authoritativePathId = ref('');
|
||||
const mirrorPathIds = ref<string[]>([]);
|
||||
const xfaContextReady = ref(false);
|
||||
const browserSessionId = crypto.randomUUID();
|
||||
let sampleRefreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
@@ -50,7 +51,7 @@ const stepThreeLabel = computed(() => (
|
||||
const canNext = computed(() => {
|
||||
if (step.value === 1) return Boolean(identity.displayName.trim() && identity.schemaId);
|
||||
if (step.value === 2) return Boolean(documentId.value);
|
||||
if (isXfaSample.value) return Boolean(authoritativePathId.value);
|
||||
if (isXfaSample.value) return Boolean(xfaContextReady.value && authoritativePathId.value);
|
||||
return Boolean(tableId.value);
|
||||
});
|
||||
const steps = computed(() => [
|
||||
@@ -111,6 +112,7 @@ watch(documentId, async (id) => {
|
||||
tableId.value = '';
|
||||
authoritativePathId.value = '';
|
||||
mirrorPathIds.value = [];
|
||||
xfaContextReady.value = false;
|
||||
tables.value = [];
|
||||
if (!id) return;
|
||||
await loadTables(id);
|
||||
@@ -222,6 +224,7 @@ onBeforeUnmount(stopSampleRefresh);
|
||||
:mirror-path-ids="mirrorPathIds"
|
||||
@update:authoritative-path-id="authoritativePathId = $event"
|
||||
@update:mirror-path-ids="mirrorPathIds = $event"
|
||||
@update:context-ready="xfaContextReady = $event"
|
||||
/>
|
||||
<OrderProfileModelStartStep v-else v-model="tableId" :tables="tables" />
|
||||
</main>
|
||||
|
||||
+1024
-235
File diff suppressed because it is too large.
Load diff
+255
-118
@@ -1,12 +1,15 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/OrderProfileXfaWorkbench.spec.ts
|
||||
* 用途:挂载统一编辑器 desk 内 XFA 片段并验证布局与诊断抽屉(无独立 Header)。
|
||||
* 依赖:Vitest、@vue/test-utils、OrderProfileXfaWorkbench。
|
||||
* 用途:冒烟验证弃用薄包装与 useOrderProfileXfaDesk 默认 synthetic / dirty 契约。
|
||||
* 依赖:Vitest、@vue/test-utils、OrderProfileXfaWorkbench、useOrderProfileXfaDesk。
|
||||
* 逻辑:不再断言三栏 datasets 左栏;断言 desk 可加载且默认原生 PDF 画布。
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { defineComponent, h, nextTick } from 'vue';
|
||||
import OrderProfileXfaWorkbench from './OrderProfileXfaWorkbench.vue';
|
||||
import { useOrderProfileXfaDesk } from './composables/useOrderProfileXfaDesk';
|
||||
|
||||
const { saveDraftMock, splitPreviewMock, detailDefinition } = vi.hoisted(() => ({
|
||||
saveDraftMock: vi.fn(),
|
||||
@@ -39,6 +42,7 @@ const baseDefinition = {
|
||||
total_amount_policy: 'must_equal_line_sum' as const,
|
||||
},
|
||||
split_rules: [],
|
||||
bindings: [],
|
||||
};
|
||||
|
||||
vi.mock('vue-router', () => ({
|
||||
@@ -47,7 +51,7 @@ vi.mock('vue-router', () => ({
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/composables/useMessage', () => ({
|
||||
useMessage: () => ({ success: vi.fn(), error: vi.fn() }),
|
||||
useMessage: () => ({ success: vi.fn(), error: vi.fn(), info: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
@@ -88,6 +92,40 @@ vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
pages: [{ page_no: 1, preview_token: 'token' }],
|
||||
expires_in_seconds: 60,
|
||||
})),
|
||||
requestOrderProfileSampleXfaSyntheticPreview: vi.fn(async () => ({
|
||||
document_id: 85,
|
||||
identity: {
|
||||
document_id: 85,
|
||||
layout_version_id: 1,
|
||||
structure_analysis_id: 1,
|
||||
source_content_hash: 'a'.repeat(64),
|
||||
template_packet_checksum: 't',
|
||||
datasets_packet_checksum: 'd',
|
||||
dataset_structure_fingerprint: 'f',
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
render_mode: 'xfa_dataset_preview',
|
||||
renderer_version: 'hxops.xfa_static_preview.v1',
|
||||
page_count: 1,
|
||||
},
|
||||
status: 'ready',
|
||||
render_mode: 'xfa_dataset_preview',
|
||||
renderer_version: 'hxops.xfa_static_preview.v1',
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
page_count: 1,
|
||||
pages: [{ page_no: 1, preview_token: 'synth-token' }],
|
||||
expires_in_seconds: 60,
|
||||
cache_hit: false,
|
||||
})),
|
||||
listOrderProfileSampleXfaSyntheticPreviewPages: vi.fn(),
|
||||
enqueueOrderProfileXfaOcrAutomark: vi.fn(async () => ({ job_id: 9, status: 'queued' })),
|
||||
getOrderProfileXfaOcrAutomarkJob: vi.fn(async () => ({
|
||||
job_id: 9,
|
||||
status: 'succeeded',
|
||||
suggestions: [],
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
})),
|
||||
acceptOrderProfileXfaOcrAutomarkSuggestion: vi.fn(),
|
||||
rejectOrderProfileXfaOcrAutomarkSuggestion: vi.fn(),
|
||||
suggestOrderProfileXfaUnifiedMapping: vi.fn(),
|
||||
acquireOrderDocumentProfileEditLease: vi.fn(async () => ({ lease_token: 'lease', expires_at: new Date().toISOString() })),
|
||||
renewOrderDocumentProfileEditLease: vi.fn(),
|
||||
@@ -95,6 +133,8 @@ vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
saveOrderDocumentProfileDraft: (...args: unknown[]) => saveDraftMock(...args),
|
||||
previewOrderProfileSampleXfaSplitRules: (...args: unknown[]) => splitPreviewMock(...args),
|
||||
previewOrderProfileSampleXfaValue: vi.fn(),
|
||||
confirmOrderProfileXfaVisualBinding: vi.fn(),
|
||||
rejectOrderProfileXfaVisualBinding: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-schema.api', () => ({
|
||||
@@ -107,110 +147,32 @@ vi.mock('@/features/admin/api/shipping-order-schema.api', () => ({
|
||||
enabled: true, aliases: [], normalizer_key: 'trim', validator_keys: [], enum_options: [],
|
||||
evidence_policy: { required: false, source_precedence: [], conflict_policy: 'fail', allow_single_source: true },
|
||||
comparator_key: 'exact',
|
||||
}, {
|
||||
field_id: 'f-bill', field_code: 'bill_to_customer', scope: 'header', display_name: '账款客户', required: false,
|
||||
enabled: true, aliases: [], normalizer_key: 'trim', validator_keys: [], enum_options: [],
|
||||
evidence_policy: { required: false, source_precedence: [], conflict_policy: 'fail', allow_single_source: true },
|
||||
comparator_key: 'exact',
|
||||
}, {
|
||||
field_id: 'f-line', field_code: 'part_number', scope: 'line', display_name: '料号', required: false,
|
||||
enabled: true, aliases: [], normalizer_key: 'trim', validator_keys: [], enum_options: [],
|
||||
evidence_policy: { required: false, source_precedence: [], conflict_policy: 'fail', allow_single_source: true },
|
||||
comparator_key: 'exact',
|
||||
}],
|
||||
},
|
||||
}],
|
||||
})),
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
fallbackLocale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
common: { yes: '是', no: '否', close: '关闭' },
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
templateModes: { xfa_dataset: 'XFA' },
|
||||
workbench: {
|
||||
headerReturnToLibrary: '返回',
|
||||
headerSaveDraft: '保存',
|
||||
headerValidate: '验证',
|
||||
headerRecoverLease: '恢复',
|
||||
headerTakeOverLease: '接管',
|
||||
saveStatus: { saved: '已保存', saving: '保存中', failed: '失败', readonly: '只读' },
|
||||
leaveConfirm: '离开?',
|
||||
annotationCanvasAriaLabel: '画布',
|
||||
loadingPage: '加载',
|
||||
selectBoundPdf: '选择 PDF',
|
||||
zoomIn: '+', zoomOut: '-', fitPage: '适合',
|
||||
pageNavigation: '页',
|
||||
},
|
||||
xfaUnified: {
|
||||
drawFieldBox: '画框',
|
||||
suggesting: '分析中',
|
||||
openDiagnostics: '高级诊断',
|
||||
diagnosticsDrawerTitle: '诊断',
|
||||
diagnosticsSummary: '{mapped}/{total}',
|
||||
candidatePanelTitle: '候选',
|
||||
acceptCandidate: '采用',
|
||||
confirmVisual: '确认',
|
||||
rejectVisual: '驳回',
|
||||
visualStatus: { suggested: '建议', confirmed: '已确认', rejected: '已驳回', needs_review: '待复核' },
|
||||
},
|
||||
xfaWorkbench: {
|
||||
loading: '加载', loadFailed: '失败', saved: '已保存', saveFailed: '失败', scopeMismatch: 'scope',
|
||||
treeTitle: '树', searchPaths: '搜', collectionBadge: '集合', treeEmpty: '空',
|
||||
schemaTitle: 'Schema', selectLeafFirst: '选叶子', unbind: '解除',
|
||||
filter: { all: '全部', unmapped: '未映射', required: '必填' },
|
||||
scope: { header: '表头', line: '明细' },
|
||||
previewTitle: '预览', blockersTitle: '阻断', currentNode: '节点', noneSelected: '无',
|
||||
headerMaps: '表头映射', lineMaps: '明细映射', requiredCoverage: '{mapped}/{total}',
|
||||
maskedSample: '脱敏', noMappings: '无映射', crossChecksTitle: '交叉校验',
|
||||
crossCheck: { acroform: 'AcroForm', mirror: '镜像', lineAmount: '金额', totalAmount: '总额' },
|
||||
previewHint: '验证页', retryLoad: '重试',
|
||||
blocker: {
|
||||
authoritative_collection_required: '权威必选',
|
||||
duplicate_field_binding: '重复',
|
||||
required_fields_unmapped: '必填未映射',
|
||||
},
|
||||
collectionsTitle: '集合', authoritativeCollection: '权威', selectAuthoritative: '选择',
|
||||
mirrorCollections: '镜像', rowCount: '{count} 行',
|
||||
},
|
||||
xfaUnified: {
|
||||
drawFieldBox: '画字段框', suggesting: '匹配中', suggestFailed: '建议失败',
|
||||
candidatePanelTitle: '候选', acceptCandidate: '采用',
|
||||
confirmVisual: '确认', rejectVisual: '驳回',
|
||||
confirmSuccess: '确认成功', confirmFailed: '确认失败',
|
||||
rejectSuccess: '驳回成功', rejectFailed: '驳回失败',
|
||||
diagnosticsSummary: '{mapped}/{total}', openDiagnostics: '高级诊断',
|
||||
diagnosticsDrawerTitle: '诊断',
|
||||
visualStatus: { suggested: '建议', confirmed: '已确认', rejected: '已驳回', needs_review: '待复核' },
|
||||
},
|
||||
xfaSplit: {
|
||||
title: '拆分', addRule: '新增', deleteConfirm: '删除?', deleteRule: '删', ruleLabel: '规则 {index}', unnamedRule: '未命名',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
describe('OrderProfileXfaWorkbench (deprecated thin wrapper)', () => {
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh',
|
||||
messages: { zh: { common: { close: '关闭' }, admin: { shippingOrderProfiles: { xfaWorkbench: { loading: '加载中' } } } } },
|
||||
});
|
||||
|
||||
describe('OrderProfileXfaWorkbench', () => {
|
||||
beforeEach(() => {
|
||||
detailDefinition.value = structuredClone(baseDefinition);
|
||||
saveDraftMock.mockReset();
|
||||
splitPreviewMock.mockReset();
|
||||
detailDefinition.value = null;
|
||||
vi.stubGlobal('fetch', vi.fn(async () => ({
|
||||
ok: true,
|
||||
blob: async () => new Blob([new Uint8Array([137, 80, 78, 71])], { type: 'image/png' }),
|
||||
})));
|
||||
vi.stubGlobal('URL', {
|
||||
...URL,
|
||||
createObjectURL: vi.fn(() => 'blob:mock-page'),
|
||||
revokeObjectURL: vi.fn(),
|
||||
});
|
||||
// Canvas-related absolute URL safety: relative /api fetch must not throw in jsdom.
|
||||
vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
expect(url.startsWith('/') || url.startsWith('http')).toBe(true);
|
||||
return {
|
||||
ok: true,
|
||||
blob: async () => new Blob(['png'], { type: 'image/png' }),
|
||||
};
|
||||
}));
|
||||
});
|
||||
|
||||
const mountPage = async () => {
|
||||
@@ -218,40 +180,215 @@ describe('OrderProfileXfaWorkbench', () => {
|
||||
props: defaultProps,
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
for (let i = 0; i < 30; i += 1) {
|
||||
await flushPromises();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
if (wrapper.find('.xfa-workbench__desk').exists()) break;
|
||||
await nextTick();
|
||||
if (wrapper.find('[data-testid="xfa-thin-canvas"]').exists()) break;
|
||||
}
|
||||
return wrapper;
|
||||
};
|
||||
|
||||
it('mounts canvas-first desk after bootstrap without standalone header', async () => {
|
||||
it('mounts thin deprecated desk without three-column left datasets tree', async () => {
|
||||
const wrapper = await mountPage();
|
||||
expect(wrapper.find('[data-testid="xfa-workbench-deprecated"]').exists()).toBe(true);
|
||||
expect(wrapper.find('.xfa-workbench__desk').exists()).toBe(true);
|
||||
expect(wrapper.find('.xfa-workbench__header').exists()).toBe(false);
|
||||
expect(wrapper.find('.xfa-workbench__canvas').exists()).toBe(true);
|
||||
expect(wrapper.find('.canvas-shell').exists()).toBe(true);
|
||||
expect(wrapper.find('.xfa-tree').exists()).toBe(false);
|
||||
|
||||
await wrapper.find('.xfa-workbench__diagnostics-trigger button').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.find('.diagnostics-drawer').exists()).toBe(true);
|
||||
expect(wrapper.find('.diagnostics-drawer .xfa-tree').exists()).toBe(true);
|
||||
expect(wrapper.find('.diagnostics-drawer .add-rule').exists()).toBe(false);
|
||||
expect(wrapper.find('.xfa-workbench__left').exists()).toBe(false);
|
||||
expect(wrapper.find('.xfa-workbench__panel').exists()).toBe(false);
|
||||
}, 15000);
|
||||
|
||||
it('opens readonly diagnostics drawer from panel footer', async () => {
|
||||
it('defaults to native preview mode after load', async () => {
|
||||
const wrapper = await mountPage();
|
||||
expect(wrapper.find('.xfa-workbench__panel').exists()).toBe(true);
|
||||
await wrapper.find('.xfa-workbench__diagnostics-trigger button').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.find('.diagnostics-drawer').exists()).toBe(true);
|
||||
expect(wrapper.find('.diagnostics-drawer .add-rule').exists()).toBe(false);
|
||||
});
|
||||
const vm = wrapper.vm as unknown as { getDesk: () => { previewMode: string; syntheticPreviewStatus: string } };
|
||||
const desk = vm.getDesk();
|
||||
expect(desk.previewMode).toBe('native');
|
||||
expect(['ready', 'loading', 'unavailable', 'failed', 'stale', 'idle']).toContain(desk.syntheticPreviewStatus);
|
||||
}, 15000);
|
||||
|
||||
it('emits dirty-change when local definition diverges from saved snapshot', async () => {
|
||||
const wrapper = await mountPage();
|
||||
expect(wrapper.emitted('dirty-change')?.[0]).toEqual([false]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useOrderProfileXfaDesk', () => {
|
||||
beforeEach(() => {
|
||||
detailDefinition.value = structuredClone(baseDefinition);
|
||||
vi.stubGlobal('fetch', vi.fn(async () => ({
|
||||
ok: true,
|
||||
blob: async () => new Blob(['png'], { type: 'image/png' }),
|
||||
})));
|
||||
});
|
||||
|
||||
it('demotes confirmed visual bindings when collections are reconfirmed', async () => {
|
||||
detailDefinition.value = {
|
||||
...structuredClone(baseDefinition),
|
||||
bindings: [{
|
||||
binding_id: 'b1',
|
||||
field_id: 'f1',
|
||||
field_code: 'customer_po_no',
|
||||
scope: 'header',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'invoiced-to-path', data_path: null },
|
||||
visual_binding: {
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
|
||||
source: 'user_drawn',
|
||||
status: 'confirmed',
|
||||
region_kind: 'field',
|
||||
confirmed_on: 'xfa_dataset_preview',
|
||||
preview_render_checksum: 'r'.repeat(64),
|
||||
},
|
||||
}],
|
||||
};
|
||||
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52,
|
||||
leaseToken: 'lease',
|
||||
saveState: 'saved',
|
||||
editorSessionId: 'sess',
|
||||
enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: {
|
||||
plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { blocker: { authoritative_collection_required: 'need auth' }, loadFailed: 'fail' },
|
||||
xfaDesk: { collectionsReconfirmedHint: 'ok' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
} } } } })],
|
||||
},
|
||||
});
|
||||
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value && desk.definition.value) break;
|
||||
}
|
||||
expect(desk.definition.value).toBeTruthy();
|
||||
expect(desk.loadError.value).toBe(false);
|
||||
|
||||
desk.draftAuthoritativePathId.value = 'items-data';
|
||||
desk.draftMirrorPathIds.value = [];
|
||||
desk.confirmReconfirmCollections();
|
||||
expect(desk.authoritativePathId.value).toBe('items-data');
|
||||
expect(desk.definition.value?.bindings?.[0]?.visual_binding.status).toBe('suggested');
|
||||
}, 15000);
|
||||
|
||||
it('duplicateSelectedBinding clears path/schema and keeps geometry', async () => {
|
||||
detailDefinition.value = {
|
||||
...structuredClone(baseDefinition),
|
||||
bindings: [{
|
||||
binding_id: 'b1',
|
||||
field_id: 'f1',
|
||||
field_code: 'customer_po_no',
|
||||
scope: 'header',
|
||||
value_binding: { type: 'xfa_dataset', path_id: 'invoiced-to-path', data_path: null },
|
||||
visual_binding: {
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
|
||||
source: 'user_drawn',
|
||||
status: 'confirmed',
|
||||
region_kind: 'header',
|
||||
confirmed_on: 'xfa_dataset_preview',
|
||||
},
|
||||
}],
|
||||
};
|
||||
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52,
|
||||
leaseToken: 'lease',
|
||||
saveState: 'saved',
|
||||
editorSessionId: 'sess',
|
||||
enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: {
|
||||
plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
} } } } })],
|
||||
},
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value && desk.definition.value) break;
|
||||
}
|
||||
desk.selectedBindingId.value = 'b1';
|
||||
desk.duplicateSelectedBinding();
|
||||
const copy = desk.definition.value?.bindings?.find((item) => item.binding_id !== 'b1');
|
||||
expect(copy).toBeTruthy();
|
||||
expect(copy?.field_code).toBe('');
|
||||
expect(copy?.value_binding.path_id).toBe('');
|
||||
expect(copy?.visual_binding.status).toBe('suggested');
|
||||
expect((copy?.visual_binding as { region_kind?: string }).region_kind).toBe('header');
|
||||
expect(copy?.visual_binding.normalized_bbox).toEqual({ x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 });
|
||||
}, 15000);
|
||||
|
||||
it('annotationDisabled when native pages missing; datasets hidden for anchor', async () => {
|
||||
detailDefinition.value = structuredClone(baseDefinition);
|
||||
let desk!: ReturnType<typeof useOrderProfileXfaDesk>;
|
||||
const Host = defineComponent({
|
||||
setup() {
|
||||
desk = useOrderProfileXfaDesk({
|
||||
profileId: 52,
|
||||
leaseToken: 'lease',
|
||||
saveState: 'saved',
|
||||
editorSessionId: 'sess',
|
||||
enabled: true,
|
||||
});
|
||||
return () => h('div');
|
||||
},
|
||||
});
|
||||
mount(Host, {
|
||||
global: {
|
||||
plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: { admin: { shippingOrderProfiles: {
|
||||
xfaWorkbench: { loadFailed: 'fail' },
|
||||
xfaAutoMark: { enqueueFailed: 'e', jobFailed: 'j' },
|
||||
} } } } })],
|
||||
},
|
||||
});
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await flushPromises();
|
||||
if (!desk.loading.value && desk.definition.value) break;
|
||||
}
|
||||
// 原生页授权就绪后,synthetic 失败不应禁标注。
|
||||
desk.pageGrants.value = [{ page_no: 1, preview_token: 'token' }];
|
||||
desk.pageGrant.value = { page_no: 1, preview_token: 'token' };
|
||||
desk.pageLoadError.value = null;
|
||||
desk.syntheticPreviewStatus.value = 'unavailable';
|
||||
expect(desk.annotationDisabled.value).toBe(false);
|
||||
|
||||
desk.pageGrant.value = null;
|
||||
desk.pageGrants.value = [];
|
||||
expect(desk.annotationDisabled.value).toBe(true);
|
||||
|
||||
desk.definition.value = {
|
||||
...desk.definition.value!,
|
||||
bindings: [{
|
||||
binding_id: 'anchor-1',
|
||||
field_id: 'a1',
|
||||
field_code: '',
|
||||
scope: 'header',
|
||||
value_binding: { type: 'xfa_dataset', path_id: '', data_path: null },
|
||||
visual_binding: {
|
||||
page_no: 1,
|
||||
normalized_bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
|
||||
source: 'user_drawn',
|
||||
status: 'suggested',
|
||||
region_kind: 'anchor',
|
||||
},
|
||||
}],
|
||||
};
|
||||
desk.selectedBindingId.value = 'anchor-1';
|
||||
expect(desk.showDatasetsSection.value).toBe(false);
|
||||
}, 15000);
|
||||
});
|
||||
+32
-1163
File diff suppressed because it is too large.
Load diff
+62
-6
@@ -1,9 +1,9 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue
|
||||
用途:展示受控 PDF 单页预览,并以相对坐标框支持选择、拖动和缩放区域。
|
||||
用途:展示受控 PDF/XFA flatten 单页预览,并以相对坐标框支持选择、拖动和缩放区域。
|
||||
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion。
|
||||
逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动;
|
||||
画布区域 aria-label 走四语言 i18n,供辅助技术正确读出只读/标注模式。
|
||||
画布区域 aria-label 走四语言 i18n;可选 emptyHint/loadError 区分 XFA page_unavailable 与 PDF 缺样本空态。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
@@ -36,6 +36,10 @@ const props = defineProps<{
|
||||
orderFieldValueState?: 'idle' | 'loading' | 'ready' | 'failed';
|
||||
/** full=坐标全工具;xfa_visual=仅 XFA 画框。 */
|
||||
annotationToolSet?: 'full' | 'xfa_visual';
|
||||
/** 无图时空态文案;缺省为「选择已绑定的 PDF 样本」。 */
|
||||
emptyHint?: string | null;
|
||||
/** 外部注入的页加载错误(如 XFA page_unavailable);优先于空态提示。 */
|
||||
loadError?: string | null;
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const readonlyMode = computed(() => props.mode === 'readonly');
|
||||
@@ -56,10 +60,16 @@ const emit = defineEmits<{
|
||||
page: [pageNo: number];
|
||||
acceptSuggestion: [];
|
||||
rejectSuggestion: [];
|
||||
/** 页图拉取失败(父级可标 page_unavailable)。 */
|
||||
loadFailed: [];
|
||||
/** 用户点击重试(父级决定重拉 grant 或 flatten)。 */
|
||||
retry: [];
|
||||
}>();
|
||||
|
||||
const imageUrl = ref('');
|
||||
const loading = ref(false);
|
||||
/** 本组件内 fetch 失败文案;与 props.loadError 合并展示。 */
|
||||
const internalLoadError = ref<string | null>(null);
|
||||
const canvas = ref<HTMLElement | null>(null);
|
||||
const viewport = ref<HTMLElement | null>(null);
|
||||
const zoom = ref(1);
|
||||
@@ -72,12 +82,26 @@ let activePan: { startX: number; startY: number; scrollLeft: number; scrollTop:
|
||||
let creationStart: { x: number; y: number } | null = null;
|
||||
const creationRegion = ref<OrderProfileCanvasRegion['region'] | null>(null);
|
||||
|
||||
/** 下载一次性 PNG 并在组件卸载或切页时回收浏览器 blob。 */
|
||||
const displayLoadError = computed(() => props.loadError || internalLoadError.value || null);
|
||||
const emptyStateText = computed(() => (
|
||||
props.emptyHint || t('admin.shippingOrderProfiles.workbench.selectBoundPdf')
|
||||
));
|
||||
|
||||
/**
|
||||
* 下载一次性 PNG 并在组件卸载或切页时回收浏览器 blob。
|
||||
* 核心逻辑:失败时写入 internalLoadError 并 emit loadFailed,避免误导为「未绑定样本」。
|
||||
*/
|
||||
const loadPage = async () => {
|
||||
if (!props.profileId || !props.grant) return;
|
||||
if (!props.profileId || !props.grant) {
|
||||
URL.revokeObjectURL(imageUrl.value);
|
||||
imageUrl.value = '';
|
||||
internalLoadError.value = null;
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
URL.revokeObjectURL(imageUrl.value);
|
||||
imageUrl.value = '';
|
||||
internalLoadError.value = null;
|
||||
try {
|
||||
const previewPath = props.previewPagePath
|
||||
|| `/api/admin/shipping-notice/order-document-profiles/${props.profileId}/preview-pages`;
|
||||
@@ -87,11 +111,22 @@ const loadPage = async () => {
|
||||
);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
imageUrl.value = URL.createObjectURL(await response.blob());
|
||||
} catch {
|
||||
internalLoadError.value = t('admin.shippingOrderProfiles.workbench.canvasUnavailable');
|
||||
emit('loadFailed');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 用户点击画布重试:清除内部错误并通知父级。
|
||||
*/
|
||||
const onRetryClick = () => {
|
||||
internalLoadError.value = null;
|
||||
emit('retry');
|
||||
};
|
||||
|
||||
/** 将指针移动映射为相对坐标;readonly 模式只保留选中,不允许几何变化。 */
|
||||
const move = (event: PointerEvent) => {
|
||||
if (!activeDrag || !canvas.value || readonlyMode.value) return;
|
||||
@@ -253,7 +288,13 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
</div>
|
||||
</header>
|
||||
<div v-if="loading" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
|
||||
<div v-else-if="!imageUrl" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.selectBoundPdf') }}</div>
|
||||
<div v-else-if="displayLoadError" class="canvas-state canvas-state--error" role="alert">
|
||||
<p>{{ displayLoadError }}</p>
|
||||
<button type="button" class="canvas-retry" @click="onRetryClick">
|
||||
{{ t('admin.shippingOrderProfiles.workbench.retryCanvas') }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-else-if="!imageUrl" class="canvas-state">{{ emptyStateText }}</div>
|
||||
<div v-else class="canvas-work-area" :class="{ readonly: readonlyMode }">
|
||||
<aside v-if="!readonlyMode" class="annotation-tools">
|
||||
<template v-if="xfaVisualTools">
|
||||
@@ -323,7 +364,22 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
.zoom-control { justify-self: end; }
|
||||
.canvas-toolbar output { min-width: 3.4rem; color: #f8fafc; text-align: center; }
|
||||
.zoom-control .fit-action { padding-inline: .65rem; }
|
||||
.canvas-state { display: grid; min-height: 32rem; place-items: center; color: #94a3b8; font-size: .875rem; }
|
||||
.canvas-state { display: grid; min-height: 32rem; place-items: center; color: #94a3b8; font-size: .875rem; gap: .75rem; }
|
||||
.canvas-state--error { color: #fecaca; }
|
||||
.canvas-retry {
|
||||
display: inline-flex;
|
||||
min-height: 2rem;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 1px solid #475569;
|
||||
border-radius: .35rem;
|
||||
background: #1e293b;
|
||||
padding: .35rem .75rem;
|
||||
color: #e2e8f0;
|
||||
font-size: .78rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.canvas-retry:hover { border-color: #60a5fa; background: #26364f; }
|
||||
.canvas-work-area { display: flex; min-height: 0; flex: 1; gap: .6rem; }
|
||||
.canvas-work-area.readonly { gap: 0; }
|
||||
.canvas-viewport { position: relative; min-width: 0; flex: 1; overflow: auto; }
|
||||
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/components/OrderProfileXfaConfirmStep.spec.ts
|
||||
* 用途:验证 XFA 集合候选在未选择权威集合时仍可见,且真正无候选时才显示空状态。
|
||||
* 依赖:Vitest、@vue/test-utils、OrderProfileXfaConfirmStep 及其 XFA API。
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import OrderProfileXfaConfirmStep from './OrderProfileXfaConfirmStep.vue';
|
||||
|
||||
const { getFieldTree, getCollections, reparseSample } = vi.hoisted(() => ({
|
||||
getFieldTree: vi.fn(),
|
||||
getCollections: vi.fn(),
|
||||
reparseSample: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/admin/api/shipping-order-document-profile.api', () => ({
|
||||
getOrderProfileSampleXfaFieldTree: getFieldTree,
|
||||
getOrderProfileSampleXfaCollections: getCollections,
|
||||
reparseOrderProfileSampleLayout: reparseSample,
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: {
|
||||
shippingOrderProfiles: {
|
||||
wizard: {
|
||||
sampleSelected: '已选样本',
|
||||
xfa: {
|
||||
loading: '加载中',
|
||||
loadErrorTitle: '加载失败',
|
||||
loadErrorHint: '请重试',
|
||||
reload: '重新加载',
|
||||
reparseSample: '重新解析样本',
|
||||
noCollections: '没有可用数据集',
|
||||
intro: 'XFA',
|
||||
noBlankPdf: '不使用空白 PDF',
|
||||
scriptNotice: '不会执行脚本',
|
||||
},
|
||||
},
|
||||
xfaUnified: { createBlockersTitle: '创建前阻断项' },
|
||||
xfaWorkbench: {
|
||||
collectionsTitle: '集合',
|
||||
collectionEvidenceHint: '证据',
|
||||
authoritativeCollection: '权威集合',
|
||||
mirrorCollections: '镜像集合',
|
||||
recommendedAuthoritative: '推荐权威',
|
||||
selectedAuthoritative: '已选权威',
|
||||
rowCount: '{count} 行',
|
||||
nonEmptyCoverage: '{filled}/{total} {percent}',
|
||||
excludedCollections: '排除集合 {count}',
|
||||
allCandidatesExcluded: '全部被排除',
|
||||
emptyStructureReason: '空结构',
|
||||
collectionReason: { data_description_structure: '结构描述', empty_structure: '空结构' },
|
||||
},
|
||||
xfa: { documentKinds: { xfa_hybrid: 'XFA 动态表单' } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const sample = {
|
||||
document_id: 132,
|
||||
intake_id: 1,
|
||||
intake_no: 'INT-1',
|
||||
filename: '4510039227.pdf',
|
||||
table_count: 0,
|
||||
document_kind: 'xfa_hybrid',
|
||||
xfa_analysis_ready: true,
|
||||
purpose: 'order_document_profile_sample' as const,
|
||||
parse_status: 'ready',
|
||||
is_template_sample: true,
|
||||
can_delete: true,
|
||||
};
|
||||
|
||||
function mountStep() {
|
||||
return mount(OrderProfileXfaConfirmStep, {
|
||||
global: { plugins: [i18n] },
|
||||
props: { documentId: 132, sample, authoritativePathId: '', mirrorPathIds: [] },
|
||||
});
|
||||
}
|
||||
|
||||
describe('OrderProfileXfaConfirmStep', () => {
|
||||
it('未选择权威集合时仍显示可选数据集', async () => {
|
||||
getFieldTree.mockResolvedValue({ tree: {} });
|
||||
getCollections.mockResolvedValue({
|
||||
collection_candidates: [{
|
||||
path_id: 'items', collection_path_hash: 'h1', row_count: 1,
|
||||
path_label: 'datasets / data / ITEMS / DATA', field_names: ['MATNR'],
|
||||
field_count: 1, non_empty_field_count: 1, non_empty_rate: 1,
|
||||
sample_fields: [{ field_name: 'MATNR', display_value: 'TEMP-S', display_policy: 'partial' }],
|
||||
selectable: true, recommended_role: 'authoritative',
|
||||
}],
|
||||
excluded_collection_candidates: [],
|
||||
});
|
||||
|
||||
const wrapper = mountStep();
|
||||
await vi.waitFor(() => expect(wrapper.text()).toContain('datasets / data / ITEMS / DATA'));
|
||||
expect(wrapper.find('input[type="radio"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('创建前阻断项');
|
||||
});
|
||||
|
||||
it('没有任何候选集合时才显示空状态', async () => {
|
||||
getFieldTree.mockResolvedValue({ tree: {} });
|
||||
getCollections.mockResolvedValue({ collection_candidates: [], excluded_collection_candidates: [] });
|
||||
|
||||
const wrapper = mountStep();
|
||||
await vi.waitFor(() => expect(wrapper.text()).toContain('没有可用数据集'));
|
||||
expect(wrapper.find('input[type="radio"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
+115
-15
@@ -1,18 +1,19 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileXfaConfirmStep.vue
|
||||
用途:创建向导第三步——XFA 样本结构与明细集合确认(不要求 table_id)。
|
||||
依赖:XFA collections API、XfaCollectionSelector、vue-i18n。
|
||||
逻辑:父级传入 documentId 与 v-model 集合 path_id;watch(immediate) 加载上下文,
|
||||
避免 onMounted 再次触发导致重复请求。
|
||||
依赖:XFA collections/field-tree API、layout-reparse API、XfaCollectionSelector、vue-i18n。
|
||||
逻辑:父级传入 documentId 与 v-model 集合 path_id;加载失败以独立错误态阻断创建,
|
||||
区分「无合格集合」与「分析不可用」;重新解析需二次确认且不自动触发。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
getOrderProfileSampleXfaCollections,
|
||||
getOrderProfileSampleXfaFieldTree,
|
||||
reparseOrderProfileSampleLayout,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type { OrderProfileSampleDocument } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { flattenXfaTreeNodes } from '../xfaProfileMapping.utils';
|
||||
@@ -27,19 +28,27 @@ const props = defineProps<{
|
||||
const emit = defineEmits<{
|
||||
'update:authoritativePathId': [value: string];
|
||||
'update:mirrorPathIds': [value: string[]];
|
||||
/** 加载失败态变化:父级须据此阻断创建按钮 */
|
||||
'update:contextReady': [value: boolean];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const message = useMessage();
|
||||
const loading = ref(false);
|
||||
const reparsing = ref(false);
|
||||
const loadError = ref<{ code?: string; message: string } | null>(null);
|
||||
const collections = ref<Awaited<ReturnType<typeof getOrderProfileSampleXfaCollections>> | null>(null);
|
||||
const flatNodes = ref(flattenXfaTreeNodes(null));
|
||||
const excludedCollections = computed(() => collections.value?.excluded_collection_candidates || []);
|
||||
const contextReady = computed(() => !loading.value && !loadError.value && collections.value != null);
|
||||
|
||||
/** 创建草稿前的阻断摘要(权威集合必选等)。 */
|
||||
/**
|
||||
* 创建草稿前的阻断摘要(权威集合必选等);加载失败时不计入“无集合”。
|
||||
*/
|
||||
const createBlockers = computed(() => {
|
||||
if (loadError.value || !collections.value) return [];
|
||||
const items: string[] = [];
|
||||
const selectable = (collections.value?.collection_candidates || []).filter((item) => item.selectable !== false);
|
||||
const selectable = (collections.value.collection_candidates || []).filter((item) => item.selectable !== false);
|
||||
if (!props.authoritativePathId && selectable.length) {
|
||||
items.push(t('admin.shippingOrderProfiles.xfaWorkbench.blocker.authoritative_collection_required'));
|
||||
}
|
||||
@@ -54,32 +63,87 @@ const documentKindLabel = computed(() => {
|
||||
return t(`admin.shippingOrderProfiles.xfa.documentKinds.${kind}`, kind);
|
||||
});
|
||||
|
||||
/**
|
||||
* 将 BusinessError 映射为用户可见文案(优先四语言 errors.codes)。
|
||||
* @param error - 捕获异常
|
||||
*/
|
||||
function resolveLoadErrorMessage(error: unknown): { code?: string; message: string } {
|
||||
if (error instanceof BusinessError) {
|
||||
const code = String(error.code || '').trim() || undefined;
|
||||
return {
|
||||
code,
|
||||
message: resolveLocalizedErrorMessage(code, error.message)
|
||||
|| t('admin.shippingOrderProfiles.wizard.xfa.loadFailed'),
|
||||
};
|
||||
}
|
||||
return { message: t('admin.shippingOrderProfiles.wizard.xfa.loadFailed') };
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载 XFA 集合候选与字段树(用于展示标签)。
|
||||
* @returns 完成后更新 flatNodes 与 collections。
|
||||
* 核心逻辑:并发请求;失败写入 loadError 且清空 collections,禁止误显示“没有集合”。
|
||||
*/
|
||||
async function loadXfaContext(): Promise<void> {
|
||||
if (!props.documentId) return;
|
||||
loading.value = true;
|
||||
loadError.value = null;
|
||||
collections.value = null;
|
||||
flatNodes.value = flattenXfaTreeNodes(null);
|
||||
emit('update:contextReady', false);
|
||||
try {
|
||||
const [treeResp, collectionResp] = await Promise.all([
|
||||
getOrderProfileSampleXfaFieldTree(props.documentId),
|
||||
getOrderProfileSampleXfaCollections(props.documentId),
|
||||
]);
|
||||
collections.value = collectionResp;
|
||||
flatNodes.value = flattenXfaTreeNodes(treeResp.tree as import('@/features/admin/types/shipping-order-document-profile.types').XfaFieldTreeNode);
|
||||
flatNodes.value = flattenXfaTreeNodes(
|
||||
treeResp.tree as import('@/features/admin/types/shipping-order-document-profile.types').XfaFieldTreeNode,
|
||||
);
|
||||
if (!props.authoritativePathId && collectionResp.collection_candidates.length === 1) {
|
||||
const only = collectionResp.collection_candidates[0];
|
||||
if (only?.path_id) emit('update:authoritativePathId', only.path_id);
|
||||
}
|
||||
emit('update:contextReady', true);
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.xfa.loadFailed'));
|
||||
loadError.value = resolveLoadErrorMessage(error);
|
||||
message.error(loadError.value.message);
|
||||
emit('update:contextReady', false);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅重新请求字段树与集合(不触发样本重新解析)。
|
||||
*/
|
||||
async function reloadContext(): Promise<void> {
|
||||
await loadXfaContext();
|
||||
}
|
||||
|
||||
/**
|
||||
* 独立“重新解析样本”:二次确认后调用 layout-reparse;成功后提示用户再点重新加载。
|
||||
*/
|
||||
async function reparseSample(): Promise<void> {
|
||||
if (!props.documentId || reparsing.value) return;
|
||||
const ok = window.confirm(t('admin.shippingOrderProfiles.wizard.xfa.reparseConfirm'));
|
||||
if (!ok) return;
|
||||
reparsing.value = true;
|
||||
try {
|
||||
await reparseOrderProfileSampleLayout(props.documentId);
|
||||
message.success(t('admin.shippingOrderProfiles.wizard.xfa.reparseStarted'));
|
||||
} catch (error) {
|
||||
message.error(
|
||||
error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: t('admin.shippingOrderProfiles.wizard.xfa.reparseFailed'),
|
||||
);
|
||||
} finally {
|
||||
reparsing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
|
||||
watch(contextReady, (ready) => emit('update:contextReady', ready));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -95,13 +159,29 @@ watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
|
||||
<li>{{ t('admin.shippingOrderProfiles.wizard.xfa.scriptNotice') }}</li>
|
||||
</ul>
|
||||
</article>
|
||||
|
||||
<p v-if="loading" class="xfa-confirm-step__loading">{{ t('admin.shippingOrderProfiles.wizard.xfa.loading') }}</p>
|
||||
<aside v-else-if="createBlockers.length" class="xfa-confirm-step__blockers" role="status">
|
||||
<strong>{{ t('admin.shippingOrderProfiles.xfaUnified.createBlockersTitle') }}</strong>
|
||||
<ul>
|
||||
<li v-for="(item, index) in createBlockers" :key="index">{{ item }}</li>
|
||||
</ul>
|
||||
|
||||
<aside v-else-if="loadError" class="xfa-confirm-step__error" role="alert">
|
||||
<strong>{{ t('admin.shippingOrderProfiles.wizard.xfa.loadErrorTitle') }}</strong>
|
||||
<p>{{ loadError.message }}</p>
|
||||
<p v-if="loadError.code" class="xfa-confirm-step__error-code">{{ loadError.code }}</p>
|
||||
<p class="xfa-confirm-step__error-hint">{{ t('admin.shippingOrderProfiles.wizard.xfa.loadErrorHint') }}</p>
|
||||
<div class="xfa-confirm-step__error-actions">
|
||||
<button type="button" class="xfa-confirm-step__btn" @click="reloadContext">
|
||||
{{ t('admin.shippingOrderProfiles.wizard.xfa.reload') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="xfa-confirm-step__btn xfa-confirm-step__btn--secondary"
|
||||
:disabled="reparsing"
|
||||
@click="reparseSample"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.wizard.xfa.reparseSample') }}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<XfaCollectionSelector
|
||||
v-else-if="collections && (collections.collection_candidates?.length || excludedCollections.length)"
|
||||
:candidates="collections.collection_candidates || []"
|
||||
@@ -111,7 +191,20 @@ watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
|
||||
@update:authoritative-path-id="emit('update:authoritativePathId', $event)"
|
||||
@update:mirror-path-ids="emit('update:mirrorPathIds', $event)"
|
||||
/>
|
||||
<p v-else-if="!loading" class="xfa-confirm-step__loading">{{ t('admin.shippingOrderProfiles.wizard.xfa.noCollections') }}</p>
|
||||
|
||||
<aside v-if="createBlockers.length" class="xfa-confirm-step__blockers" role="status">
|
||||
<strong>{{ t('admin.shippingOrderProfiles.xfaUnified.createBlockersTitle') }}</strong>
|
||||
<ul>
|
||||
<li v-for="(item, index) in createBlockers" :key="index">{{ item }}</li>
|
||||
</ul>
|
||||
</aside>
|
||||
|
||||
<p
|
||||
v-if="collections && !collections.collection_candidates?.length && !excludedCollections.length"
|
||||
class="xfa-confirm-step__loading"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.wizard.xfa.noCollections') }}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -124,4 +217,11 @@ watch(() => props.documentId, () => void loadXfaContext(), { immediate: true });
|
||||
.xfa-confirm-step__loading { margin: 0; color: var(--text-muted); }
|
||||
.xfa-confirm-step__blockers { padding: 12px 14px; border: 1px solid var(--status-warning-border); border-radius: var(--radius-control); background: var(--status-warning-bg); color: var(--status-warning-fg); font-size: .84rem; }
|
||||
.xfa-confirm-step__blockers ul { margin: 6px 0 0; padding-left: 18px; }
|
||||
.xfa-confirm-step__error { padding: 14px 16px; border: 1px solid var(--status-danger-border, #f1aeb5); border-radius: var(--radius-control); background: var(--status-danger-bg, #fff5f5); color: var(--status-danger-fg, #9b1c1c); font-size: .86rem; display: flex; flex-direction: column; gap: 8px; }
|
||||
.xfa-confirm-step__error-code { margin: 0; font-family: ui-monospace, monospace; font-size: .75rem; opacity: .85; }
|
||||
.xfa-confirm-step__error-hint { margin: 0; color: var(--text-secondary); }
|
||||
.xfa-confirm-step__error-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 4px; }
|
||||
.xfa-confirm-step__btn { padding: 6px 12px; border-radius: var(--radius-control); border: 1px solid var(--border-default); background: var(--bg-surface); cursor: pointer; font-size: .84rem; }
|
||||
.xfa-confirm-step__btn--secondary { background: transparent; }
|
||||
.xfa-confirm-step__btn:disabled { opacity: .6; cursor: not-allowed; }
|
||||
</style>
|
||||
+281
@@ -0,0 +1,281 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaAutoMarkPanel.vue
|
||||
用途:XFA OCR/Widget 自动标记建议面板;支持轮询进度与接受/调整/拒绝。
|
||||
依赖:vue-i18n;由 OrderProfileEditorPage(XFA desk)嵌入并接线 automark API。
|
||||
逻辑:props 驱动 suggestions/jobStatus;动作按钮在非 disabled 时 emit 给父级持久化。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
/** 自动标记建议条目。 */
|
||||
export interface XfaAutoMarkSuggestion {
|
||||
suggestion_id: string;
|
||||
field_key?: string | null;
|
||||
field_code?: string | null;
|
||||
suggestion_origin?: 'widget_template' | 'ocr' | string | null;
|
||||
confidence?: number | null;
|
||||
status?: string | null;
|
||||
match_class?: string | null;
|
||||
summary?: string | null;
|
||||
ocr_text?: string | null;
|
||||
dataset_value?: string | null;
|
||||
iou?: number | null;
|
||||
needs_review?: boolean | null;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
suggestions?: XfaAutoMarkSuggestion[];
|
||||
disabled?: boolean;
|
||||
initiallyExpanded?: boolean;
|
||||
/** queued|running|succeeded|failed|idle */
|
||||
jobStatus?: string | null;
|
||||
jobError?: string | null;
|
||||
}>(), {
|
||||
suggestions: () => [],
|
||||
disabled: false,
|
||||
initiallyExpanded: true,
|
||||
jobStatus: 'idle',
|
||||
jobError: null,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
accept: [suggestion: XfaAutoMarkSuggestion];
|
||||
adjust: [suggestion: XfaAutoMarkSuggestion];
|
||||
reject: [suggestion: XfaAutoMarkSuggestion];
|
||||
retry: [];
|
||||
'run-full': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const expanded = ref(props.initiallyExpanded);
|
||||
|
||||
watch(() => props.initiallyExpanded, (v) => { expanded.value = v; });
|
||||
|
||||
const items = computed(() => props.suggestions || []);
|
||||
const empty = computed(() => items.value.length === 0);
|
||||
const running = computed(() => ['queued', 'running', 'pending'].includes(String(props.jobStatus || '')));
|
||||
|
||||
/**
|
||||
* 切换面板展开/收起。
|
||||
*/
|
||||
function toggleExpanded(): void {
|
||||
expanded.value = !expanded.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发出接受建议事件。
|
||||
*/
|
||||
function onAccept(suggestion: XfaAutoMarkSuggestion): void {
|
||||
if (props.disabled || suggestion.needs_review || suggestion.match_class === 'needs_review') return;
|
||||
emit('accept', suggestion);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发出调整建议事件(定位到画布手工改框)。
|
||||
*/
|
||||
function onAdjust(suggestion: XfaAutoMarkSuggestion): void {
|
||||
if (props.disabled) return;
|
||||
emit('adjust', suggestion);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发出驳回建议事件。
|
||||
*/
|
||||
function onReject(suggestion: XfaAutoMarkSuggestion): void {
|
||||
if (props.disabled) return;
|
||||
emit('reject', suggestion);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析建议来源展示文案。
|
||||
*/
|
||||
function originLabel(origin: string | null | undefined): string {
|
||||
if (origin === 'widget_template') return t('admin.shippingOrderProfiles.xfaAutoMark.originWidget');
|
||||
if (origin === 'ocr') return t('admin.shippingOrderProfiles.xfaAutoMark.originOcr');
|
||||
return t('admin.shippingOrderProfiles.xfaAutoMark.originUnknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* mismatch / needs_review 禁止直接接受。
|
||||
*/
|
||||
function acceptBlocked(item: XfaAutoMarkSuggestion): boolean {
|
||||
return Boolean(item.needs_review || item.match_class === 'needs_review');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-auto-mark" :aria-label="t('admin.shippingOrderProfiles.xfaAutoMark.title')">
|
||||
<button
|
||||
type="button"
|
||||
class="xfa-auto-mark__header"
|
||||
:aria-expanded="expanded"
|
||||
@click="toggleExpanded"
|
||||
>
|
||||
<span class="xfa-auto-mark__title">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.title') }}
|
||||
</span>
|
||||
<span class="xfa-auto-mark__count">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.count', { count: items.length }) }}
|
||||
</span>
|
||||
<span v-if="running" class="xfa-auto-mark__job">{{ t('admin.shippingOrderProfiles.xfaAutoMark.running') }}</span>
|
||||
<span class="xfa-auto-mark__chevron">{{ expanded ? '▾' : '▸' }}</span>
|
||||
</button>
|
||||
|
||||
<div v-if="expanded" class="xfa-auto-mark__body">
|
||||
<p class="xfa-auto-mark__hint">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.hint') }}
|
||||
</p>
|
||||
<div class="xfa-auto-mark__toolbar">
|
||||
<button type="button" class="action-btn" :disabled="disabled || running" @click="emit('run-full')">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.runFull') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="jobStatus === 'failed'"
|
||||
type="button"
|
||||
class="action-btn"
|
||||
:disabled="disabled"
|
||||
@click="emit('retry')"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.retry') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="jobError" class="xfa-auto-mark__error">{{ jobError }}</p>
|
||||
<p v-if="empty && !running" class="xfa-auto-mark__empty">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.empty') }}
|
||||
</p>
|
||||
<ul v-else class="xfa-auto-mark__list">
|
||||
<li
|
||||
v-for="item in items"
|
||||
:key="item.suggestion_id"
|
||||
class="xfa-auto-mark__item"
|
||||
>
|
||||
<div class="xfa-auto-mark__meta">
|
||||
<span class="xfa-auto-mark__field">
|
||||
{{ item.field_code || item.field_key || item.suggestion_id }}
|
||||
</span>
|
||||
<span class="xfa-auto-mark__origin">{{ originLabel(item.suggestion_origin) }}</span>
|
||||
<span v-if="item.match_class" class="xfa-auto-mark__class">{{ item.match_class }}</span>
|
||||
<span v-if="item.confidence != null" class="xfa-auto-mark__confidence">
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.confidence', {
|
||||
value: Math.round(Number(item.confidence) * 100),
|
||||
}) }}
|
||||
</span>
|
||||
</div>
|
||||
<p v-if="item.summary" class="xfa-auto-mark__summary">{{ item.summary }}</p>
|
||||
<p v-else-if="item.ocr_text || item.dataset_value" class="xfa-auto-mark__summary">
|
||||
OCR: {{ item.ocr_text || '—' }} · datasets: {{ item.dataset_value || '—' }}
|
||||
</p>
|
||||
<div class="xfa-auto-mark__actions">
|
||||
<button
|
||||
type="button"
|
||||
class="action-btn action-btn--active"
|
||||
:disabled="disabled || acceptBlocked(item)"
|
||||
@click="onAccept(item)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.accept') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="action-btn action-btn--active"
|
||||
:disabled="disabled"
|
||||
@click="onAdjust(item)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.adjust') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="action-btn action-btn--active action-btn--danger"
|
||||
:disabled="disabled"
|
||||
@click="onReject(item)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaAutoMark.reject') }}
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-auto-mark {
|
||||
border-top: 1px solid #7dd3fc;
|
||||
border-radius: 0;
|
||||
background: #ecfeff;
|
||||
overflow: hidden;
|
||||
color: #155e75;
|
||||
}
|
||||
.xfa-auto-mark__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
padding: 0.65rem 0.9rem;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
color: #155e75;
|
||||
}
|
||||
.xfa-auto-mark__title { font-size: 0.75rem; font-weight: 600; }
|
||||
.xfa-auto-mark__count, .xfa-auto-mark__job {
|
||||
border-radius: 999px;
|
||||
background: #bae6fd;
|
||||
padding: 0.15rem 0.4rem;
|
||||
font-size: 0.72rem;
|
||||
color: #0e7490;
|
||||
}
|
||||
.xfa-auto-mark__chevron { margin-left: auto; color: #0e7490; font-size: 0.75rem; }
|
||||
.xfa-auto-mark__body { padding: 0 0.9rem 0.75rem; border-top: 1px solid #a5f3fc; }
|
||||
.xfa-auto-mark__hint, .xfa-auto-mark__empty { margin: 0.5rem 0 0; font-size: 0.75rem; color: #0e7490; }
|
||||
.xfa-auto-mark__error { margin: 0.35rem 0 0; font-size: 0.75rem; color: #b91c1c; }
|
||||
.xfa-auto-mark__toolbar { display: flex; gap: 0.35rem; margin-top: 0.45rem; }
|
||||
.xfa-auto-mark__toolbar .action-btn {
|
||||
border: 1px solid #0891b2;
|
||||
border-radius: 0.35rem;
|
||||
background: #fff;
|
||||
padding: 0.35rem 0.55rem;
|
||||
color: #0e7490;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.xfa-auto-mark__list {
|
||||
list-style: none;
|
||||
margin: 0.5rem 0 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
}
|
||||
.xfa-auto-mark__item {
|
||||
padding: 0.5rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 0.375rem;
|
||||
background: #fff;
|
||||
}
|
||||
.xfa-auto-mark__meta { display: flex; flex-wrap: wrap; gap: 0.4rem; align-items: center; }
|
||||
.xfa-auto-mark__field { font-size: 0.8125rem; font-weight: 600; color: #0f172a; }
|
||||
.xfa-auto-mark__origin, .xfa-auto-mark__confidence, .xfa-auto-mark__class {
|
||||
font-size: 0.6875rem;
|
||||
color: #64748b;
|
||||
background: #f1f5f9;
|
||||
border-radius: 0.25rem;
|
||||
padding: 0.1rem 0.35rem;
|
||||
}
|
||||
.xfa-auto-mark__summary { margin: 0.35rem 0 0; font-size: 0.75rem; color: #475569; }
|
||||
.xfa-auto-mark__actions { display: flex; gap: 0.35rem; margin-top: 0.45rem; }
|
||||
.action-btn {
|
||||
font-size: 0.75rem;
|
||||
padding: 0.2rem 0.5rem;
|
||||
border-radius: 0.25rem;
|
||||
border: 1px solid #cbd5e1;
|
||||
background: #f8fafc;
|
||||
color: #334155;
|
||||
}
|
||||
.action-btn:disabled { cursor: not-allowed; opacity: 0.45; }
|
||||
.action-btn--active { cursor: pointer; opacity: 1; }
|
||||
.action-btn--active:hover:not(:disabled) { border-color: #60a5fa; background: #eff6ff; }
|
||||
.action-btn--danger { color: #991b1b; border-color: #fecaca; }
|
||||
</style>
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaPreviewModeToggle.vue
|
||||
用途:【已废止 / DEPRECATED】原 XFA 原始 PDF / 合成预览双模式切换。
|
||||
依赖:vue-i18n、XfaPreviewCanvasMode 类型。
|
||||
逻辑:硬冻结后 EditorPage 不再导入;保留文件仅防旧引用,请勿在新产品路径使用。
|
||||
替代:唯一 flatten 合成图源;见 useOrderProfileXfaDesk + OrderProfileEditorPage 共享 desk。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { XfaPreviewCanvasMode } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
/** @deprecated 双预览模式已废止;请勿再挂载本组件。 */
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue: XfaPreviewCanvasMode;
|
||||
status?: 'idle' | 'loading' | 'ready' | 'failed' | 'stale' | 'unavailable';
|
||||
pageCount?: number;
|
||||
disabled?: boolean;
|
||||
}>(), {
|
||||
status: 'idle',
|
||||
pageCount: 0,
|
||||
disabled: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [mode: XfaPreviewCanvasMode];
|
||||
'mode-change': [mode: XfaPreviewCanvasMode];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const statusText = computed(() => {
|
||||
switch (props.status) {
|
||||
case 'loading':
|
||||
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusLoading');
|
||||
case 'ready':
|
||||
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusReady', {
|
||||
pages: props.pageCount || 0,
|
||||
});
|
||||
case 'failed':
|
||||
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusFailed');
|
||||
case 'stale':
|
||||
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusStale');
|
||||
case 'unavailable':
|
||||
return t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.statusUnavailable');
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 切换预览模式并同步 v-model / mode-change。
|
||||
* @param mode 目标模式
|
||||
*/
|
||||
function selectMode(mode: XfaPreviewCanvasMode): void {
|
||||
if (props.disabled || mode === props.modelValue) return;
|
||||
emit('update:modelValue', mode);
|
||||
emit('mode-change', mode);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="xfa-preview-mode-toggle"
|
||||
role="group"
|
||||
:aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.label')"
|
||||
>
|
||||
<span class="xfa-preview-mode-toggle__label">
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.label') }}
|
||||
</span>
|
||||
<div class="xfa-preview-mode-toggle__buttons">
|
||||
<button
|
||||
type="button"
|
||||
class="mode-btn"
|
||||
:class="{ active: modelValue === 'original' }"
|
||||
:disabled="disabled"
|
||||
:aria-pressed="modelValue === 'original'"
|
||||
@click="selectMode('original')"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.original') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="mode-btn"
|
||||
:class="{ active: modelValue === 'synthetic' }"
|
||||
:disabled="disabled"
|
||||
:aria-pressed="modelValue === 'synthetic'"
|
||||
@click="selectMode('synthetic')"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.xfaWorkbench.previewMode.synthetic') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="statusText" class="xfa-preview-mode-toggle__status" :data-status="status">
|
||||
{{ statusText }}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.xfa-preview-mode-toggle {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem 0.75rem;
|
||||
margin-bottom: 0.5rem;
|
||||
padding: 0.35rem 0;
|
||||
}
|
||||
.xfa-preview-mode-toggle__label {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: #475569;
|
||||
}
|
||||
.xfa-preview-mode-toggle__buttons {
|
||||
display: inline-flex;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 0.375rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
.mode-btn {
|
||||
appearance: none;
|
||||
border: 0;
|
||||
background: #f8fafc;
|
||||
color: #334155;
|
||||
font-size: 0.75rem;
|
||||
padding: 0.3rem 0.65rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.mode-btn + .mode-btn {
|
||||
border-left: 1px solid #cbd5e1;
|
||||
}
|
||||
.mode-btn.active {
|
||||
background: #0f172a;
|
||||
color: #f8fafc;
|
||||
}
|
||||
.mode-btn:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.xfa-preview-mode-toggle__status {
|
||||
margin: 0;
|
||||
font-size: 0.7rem;
|
||||
color: #64748b;
|
||||
}
|
||||
.xfa-preview-mode-toggle__status[data-status='failed'],
|
||||
.xfa-preview-mode-toggle__status[data-status='stale'] {
|
||||
color: #b45309;
|
||||
}
|
||||
.xfa-preview-mode-toggle__status[data-status='ready'] {
|
||||
color: #047857;
|
||||
}
|
||||
</style>
|
||||
+1668
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* features/admin/types/shipping-order-document-profile.types.ts
|
||||
* 用途:订单文档坐标模板、XFA 统一绑定(value/visual/split)、受控样本预览和字段区域 DTO。
|
||||
* 用途:订单文档坐标模板、XFA 统一绑定(value/visual/split)、合成预览与受控样本预览 DTO。
|
||||
* 依赖:无。
|
||||
* 逻辑:管理页面只提交样本选择、白名单解析器与受控 path_id;不持有或提交 HTML/
|
||||
* 完整 XML、原始 PDF bytes 或对象存储地址。template_mode 为鉴别联合入口。
|
||||
@@ -136,6 +136,15 @@ export interface XfaVisualBinding {
|
||||
source: XfaVisualBindingSource;
|
||||
status: XfaVisualBindingStatus;
|
||||
confidence?: number;
|
||||
/** 合成预览渲染校验和(确认时必填)。 */
|
||||
preview_render_checksum?: string | null;
|
||||
/** 须为 xfa_dataset_preview。 */
|
||||
render_mode?: string | null;
|
||||
/** 确认时写入的合成器版本(BE-4 发布门禁必填)。 */
|
||||
renderer_version?: string | null;
|
||||
/** 确认画布,通常为 xfa_dataset_preview。 */
|
||||
confirmed_on?: string | null;
|
||||
region_kind?: string | null;
|
||||
}
|
||||
|
||||
/** 字段对拆分段的引用。 */
|
||||
@@ -815,6 +824,72 @@ export interface OrderProfileUsagePage {
|
||||
|
||||
/** 受控预览授权只对单页生效,令牌不得持久化或复用。 */
|
||||
export interface OrderProfilePreviewPageGrant { page_no: number; preview_token: string; }
|
||||
|
||||
/** XFA 合成预览身份上下文(与后端 PreviewIdentityContext 对齐)。 */
|
||||
export interface XfaSyntheticPreviewIdentity {
|
||||
document_id: number | null;
|
||||
layout_version_id: number | null;
|
||||
structure_analysis_id: number | string | null;
|
||||
source_content_hash: string;
|
||||
template_packet_checksum: string;
|
||||
datasets_packet_checksum: string;
|
||||
dataset_structure_fingerprint: string;
|
||||
preview_render_checksum: string;
|
||||
render_mode: string;
|
||||
renderer_version: string;
|
||||
page_count: number;
|
||||
}
|
||||
|
||||
/** 合成预览页元数据(含短时 token,不含 PNG)。 */
|
||||
export interface XfaSyntheticPreviewPageMeta {
|
||||
page_no: number;
|
||||
preview_token: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
drawn_echo_count?: number;
|
||||
}
|
||||
|
||||
/** 可写入 definition.xfa_preview 的发布证据(无 PNG)。 */
|
||||
export interface XfaPreviewDefinitionMeta {
|
||||
status?: string | null;
|
||||
preview_render_checksum?: string | null;
|
||||
render_mode?: string;
|
||||
renderer_version?: string;
|
||||
page_count?: number;
|
||||
pages_ready?: number[];
|
||||
source_page_count?: number | null;
|
||||
synthetic_page_count?: number | null;
|
||||
pages?: Array<{
|
||||
page_no?: number;
|
||||
source_page_box?: Record<string, number>;
|
||||
synthetic_page_box?: Record<string, number>;
|
||||
page_identity_hash?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
/** POST/GET xfa/preview 响应摘要。 */
|
||||
export interface XfaSyntheticPreviewResponse {
|
||||
document_id: number | null;
|
||||
identity: XfaSyntheticPreviewIdentity;
|
||||
status: 'ready' | 'needs_review' | 'failed' | 'stale' | string;
|
||||
error_code?: string | null;
|
||||
render_mode: string;
|
||||
renderer_version: string;
|
||||
page_count: number;
|
||||
preview_render_checksum?: string | null;
|
||||
pages: XfaSyntheticPreviewPageMeta[];
|
||||
expires_in_seconds: number;
|
||||
cache_hit: boolean;
|
||||
diagnostics?: Record<string, unknown>;
|
||||
/** BE-3:前端落库 definition.xfa_preview 用 */
|
||||
definition_preview_meta?: XfaPreviewDefinitionMeta;
|
||||
source_page_count?: number | null;
|
||||
synthetic_page_count?: number | null;
|
||||
}
|
||||
|
||||
/** 工作台预览模式:原始 PDFium 对照 vs datasets 合成权威画布。 */
|
||||
export type XfaPreviewCanvasMode = 'original' | 'synthetic';
|
||||
|
||||
export interface OrderProfileBoundSample {
|
||||
id: number;
|
||||
document_id: number;
|
||||
|
||||
@@ -86,6 +86,28 @@ function jsonPost(body?: unknown): RequestInit {
|
||||
};
|
||||
}
|
||||
|
||||
/** 订单处理工作台履约写归属上下文(与后端 assert_notice_task_ownership 对齐)。 */
|
||||
export type ShippingFulfillmentOwnershipContext = {
|
||||
expectedOrderTaskNo?: string;
|
||||
expectedReviewCaseNo?: string;
|
||||
expectedRunNo?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* 将归属上下文序列化为 API snake_case 载荷字段。
|
||||
*/
|
||||
function ownershipPayload(ownership?: ShippingFulfillmentOwnershipContext | null): Record<string, string> {
|
||||
if (!ownership) return {};
|
||||
const out: Record<string, string> = {};
|
||||
const ot = String(ownership.expectedOrderTaskNo || '').trim();
|
||||
const caseNo = String(ownership.expectedReviewCaseNo || '').trim();
|
||||
const run = String(ownership.expectedRunNo || '').trim();
|
||||
if (ot) out.expected_order_task_no = ot;
|
||||
if (caseNo) out.expected_review_case_no = caseNo;
|
||||
if (run) out.expected_run_no = run;
|
||||
return out;
|
||||
}
|
||||
|
||||
function assertShippingOk<T extends ShippingApiStatusPayload>(body: T): T {
|
||||
if (body.status === 'failed') {
|
||||
throw new BusinessError({
|
||||
@@ -401,6 +423,24 @@ export const validateWorkspaceShippingOrderReviewDraft = (caseNo: string, expect
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
|
||||
);
|
||||
|
||||
/**
|
||||
* 显式重试 STP 自动建单入队(failed / manual_fallback)。
|
||||
* 核心逻辑:POST 专用 retry;成功返回 queued/reused + job_id;失败为业务错误。
|
||||
* @param caseNo - 复核 Case 编号
|
||||
*/
|
||||
export const retryWorkspaceShippingOrderStpAutoCreate = (caseNo: string) =>
|
||||
requestJson<{
|
||||
status: string;
|
||||
job_id?: number | null;
|
||||
job_status?: string | null;
|
||||
idempotency_key?: string | null;
|
||||
retry_of_job_id?: number | null;
|
||||
case?: ShippingOrderReviewCase;
|
||||
}>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/stp-auto-create/retry`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}) },
|
||||
);
|
||||
|
||||
/**
|
||||
* 为复核明细人工选定一个或多个已启用库存源候选。
|
||||
* 核心逻辑:携带 expected_draft_version 乐观锁;服务端写入行级 inventory_routing 后重跑资格校验。
|
||||
@@ -1205,12 +1245,16 @@ export async function removeWorkspaceShippingNoticeLine(
|
||||
/**
|
||||
* 执行库存匹配。
|
||||
* @param taskNo - 发货任务编号
|
||||
* @param ownership - 可选工作台归属上下文
|
||||
* @returns 匹配结果与后续动作提示
|
||||
*/
|
||||
export async function matchWorkspaceShippingInventory(taskNo: string) {
|
||||
export async function matchWorkspaceShippingInventory(
|
||||
taskNo: string,
|
||||
ownership?: ShippingFulfillmentOwnershipContext | null,
|
||||
) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/match-inventory`,
|
||||
jsonPost(),
|
||||
jsonPost(ownershipPayload(ownership)),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
@@ -1265,12 +1309,16 @@ export async function markWorkspaceShippingManualUploaded(
|
||||
/**
|
||||
* 重试将发货 Excel 上传至货代系统。
|
||||
* @param taskNo - 发货任务编号
|
||||
* @param ownership - 可选工作台归属上下文
|
||||
* @returns RPA 上传触发或等待结果
|
||||
*/
|
||||
export async function retryWorkspaceShippingUpload(taskNo: string) {
|
||||
export async function retryWorkspaceShippingUpload(
|
||||
taskNo: string,
|
||||
ownership?: ShippingFulfillmentOwnershipContext | null,
|
||||
) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/retry-upload`,
|
||||
jsonPost(),
|
||||
jsonPost(ownershipPayload(ownership)),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
@@ -1278,12 +1326,16 @@ export async function retryWorkspaceShippingUpload(taskNo: string) {
|
||||
/**
|
||||
* 生成发货 Excel。
|
||||
* @param taskNo - 发货任务编号
|
||||
* @param ownership - 可选工作台归属上下文
|
||||
* @returns 生成结果,成功时通常会包含下载链接
|
||||
*/
|
||||
export async function generateWorkspaceShippingExcel(taskNo: string) {
|
||||
export async function generateWorkspaceShippingExcel(
|
||||
taskNo: string,
|
||||
ownership?: ShippingFulfillmentOwnershipContext | null,
|
||||
) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/generate-excel`,
|
||||
jsonPost(),
|
||||
jsonPost(ownershipPayload(ownership)),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
+185
-1
@@ -27,6 +27,10 @@ function mountSummary(eligibility: ShippingOrderReviewBuildEligibility, customer
|
||||
canBuildYes: '可建单',
|
||||
canBuildNo: '待处理',
|
||||
blockReasons: { require_manual_review: '需人工确认', unknown: '未知阻断' },
|
||||
gates: {
|
||||
customer_confirmed: '客户已确认',
|
||||
required_fields_complete: '必填字段完整',
|
||||
},
|
||||
},
|
||||
workbench: {
|
||||
primaryBlock: '首要阻断原因',
|
||||
@@ -95,6 +99,25 @@ describe('ReviewBuildEligibilitySummary', () => {
|
||||
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').text()).toContain('✓');
|
||||
});
|
||||
|
||||
it('ignores failed_gates customer_confirmed when customer is already resolved', () => {
|
||||
// 关键断言:客户已确认后不得再把「客户已确认」门禁文案投影为优先处理。
|
||||
const wrapper = mountSummary({
|
||||
can_build: false,
|
||||
status: 'blocked',
|
||||
issues: [],
|
||||
failed_gates: ['customer_confirmed', 'required_fields_complete'],
|
||||
gates: {
|
||||
customer_confirmed: true,
|
||||
required_fields_complete: false,
|
||||
},
|
||||
line_projections: [],
|
||||
}, true);
|
||||
|
||||
const block = wrapper.find('[data-testid="review-eligibility-primary-block"]');
|
||||
expect(block.exists()).toBe(true);
|
||||
expect(block.text()).not.toContain('客户已确认');
|
||||
});
|
||||
|
||||
it('projects concrete manual review facts before falling back to generic copy', () => {
|
||||
const wrapper = mountSummary({
|
||||
can_build: false,
|
||||
@@ -122,8 +145,9 @@ describe('ReviewBuildEligibilitySummary', () => {
|
||||
line_projections: [],
|
||||
});
|
||||
|
||||
// 有门禁 i18n 时优先展示业务门禁名,禁止露出内部 gate code。
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').text())
|
||||
.toContain('未知问题');
|
||||
.toContain('必填字段完整');
|
||||
expect(wrapper.text()).not.toContain('required_fields_complete');
|
||||
});
|
||||
|
||||
@@ -140,4 +164,164 @@ describe('ReviewBuildEligibilitySummary', () => {
|
||||
expect(wrapper.text()).not.toContain('can_build');
|
||||
expect(wrapper.text()).not.toContain('can_auto_create');
|
||||
});
|
||||
|
||||
it('hides primary-block under focusBuildability for inventory combo (UI-03)', () => {
|
||||
// 关键断言:库存阻断由 Gate 卡表达时,资格摘要不得再输出首要阻断标题。
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
issues: '问题',
|
||||
exceptionNav: { prev: '上', next: '下', prevHint: '', nextHint: '' },
|
||||
issueCodes: { unknown: '未知问题' },
|
||||
buildEligibility: {
|
||||
title: '订单检查',
|
||||
canBuildYes: '可建单',
|
||||
canBuildNo: '待处理',
|
||||
blockReasons: { require_manual_review: '需人工确认', unknown: '未知阻断' },
|
||||
gates: { required_fields_complete: '必填字段完整' },
|
||||
},
|
||||
workbench: {
|
||||
primaryBlock: '首要阻断原因',
|
||||
blockCount: '阻断项 {count} 项',
|
||||
viewFullChecks: '查看完整检查',
|
||||
manualReview: {
|
||||
customer: '请确认客户',
|
||||
field: '请确认字段:{field}',
|
||||
lineInventory: '第 {line} 行:请确认库存来源(候选:{candidates})',
|
||||
noCandidates: '暂无候选',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const wrapper = mount(ReviewBuildEligibilitySummary, {
|
||||
props: {
|
||||
eligibility: {
|
||||
can_build: false,
|
||||
status: 'blocked',
|
||||
issues: [{
|
||||
code: 'require_manual_review',
|
||||
severity: 'blocking',
|
||||
explainability: { message: '库存来源待确认' },
|
||||
}],
|
||||
line_projections: [],
|
||||
},
|
||||
focusBuildability: true,
|
||||
exceptionCount: 2,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-build-eligibility-summary"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-exception-nav"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('hides primary-block under focusBuildability for field completeness combo (UI-03)', () => {
|
||||
// 关键断言:字段阻断组合态下资格卡只保留摘要与异常导航,不输出第二份首要阻断。
|
||||
const wrapper = mount(ReviewBuildEligibilitySummary, {
|
||||
props: {
|
||||
eligibility: {
|
||||
can_build: false,
|
||||
status: 'blocked',
|
||||
issues: [{
|
||||
code: 'required_field_missing',
|
||||
severity: 'blocking',
|
||||
field_code: 'po_number',
|
||||
}],
|
||||
assessment: { missing_required_fields: ['po_number'], invalid_lines: [] },
|
||||
line_projections: [],
|
||||
},
|
||||
fieldLabels: { po_number: 'PO' },
|
||||
focusBuildability: true,
|
||||
exceptionCount: 1,
|
||||
},
|
||||
global: {
|
||||
plugins: [createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
issueCodes: { unknown: '未知' },
|
||||
issues: '问题',
|
||||
exceptionNav: { prev: '上', next: '下', prevHint: '', nextHint: '' },
|
||||
buildEligibility: {
|
||||
title: '订单检查',
|
||||
canBuildYes: '可建单',
|
||||
canBuildNo: '待处理',
|
||||
gates: {},
|
||||
blockReasons: { unknown: '未知' },
|
||||
},
|
||||
workbench: {
|
||||
primaryBlock: '首要阻断原因',
|
||||
blockCount: '{count}',
|
||||
viewFullChecks: '查看完整检查',
|
||||
missingRequiredFields: '缺失必填',
|
||||
conflictFields: '冲突',
|
||||
manualReview: {
|
||||
customer: '',
|
||||
field: '请确认字段:{field}',
|
||||
lineInventory: '',
|
||||
noCandidates: '',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})],
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('hides primary-block when technical_auto_only leaves business gate inactive (UI-03)', () => {
|
||||
// 关键断言:仅技术 Gate pending 时 focusBuildability=false,资格卡可展示阻断;本测验证开启 focus 时仍唯一。
|
||||
const wrapper = mount(ReviewBuildEligibilitySummary, {
|
||||
props: {
|
||||
eligibility: {
|
||||
can_build: true,
|
||||
can_auto_create: true,
|
||||
status: 'qualified',
|
||||
issues: [],
|
||||
line_projections: [],
|
||||
},
|
||||
focusBuildability: true,
|
||||
},
|
||||
global: {
|
||||
plugins: [createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
chat: {
|
||||
shippingOrderReview: {
|
||||
buildEligibility: {
|
||||
title: '订单检查',
|
||||
canBuildYes: '可建单',
|
||||
canBuildNo: '待处理',
|
||||
gates: {},
|
||||
},
|
||||
workbench: {
|
||||
primaryBlock: '首要阻断原因',
|
||||
viewFullChecks: '查看完整检查',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})],
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-build-eligibility-badge"]').text()).toContain('可建单');
|
||||
});
|
||||
});
|
||||
+15
-3
@@ -66,7 +66,7 @@ const blockingIssueCount = computed(() => {
|
||||
return blocking.length || issues.length;
|
||||
});
|
||||
|
||||
/** 首要阻断文案。 */
|
||||
/** 首要阻断文案:仅来自当前未解决业务问题;客户已确认时不得再显示客户确认阻断。 */
|
||||
const primaryBlockMessage = computed(() => {
|
||||
const issues = effectiveIssues.value;
|
||||
const primary = issues.find((item) => String(item.severity || '') === 'blocking') || issues[0];
|
||||
@@ -78,7 +78,13 @@ const primaryBlockMessage = computed(() => {
|
||||
return !reason.startsWith('customer_');
|
||||
});
|
||||
if (!blockedLines.length) {
|
||||
const failedGate = (props.eligibility?.failed_gates || [])[0];
|
||||
const failedGate = (props.eligibility?.failed_gates || []).find((gate) => {
|
||||
const code = String(gate || '').trim().toLowerCase();
|
||||
if (props.customerResolved === true && (code === 'customer_confirmed' || code === 'customer_resolution')) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (!failedGate) return '';
|
||||
const gateKey = `chat.shippingOrderReview.buildEligibility.gates.${failedGate}`;
|
||||
return te(gateKey) ? t(gateKey) : t('chat.shippingOrderReview.issueCodes.unknown');
|
||||
@@ -116,7 +122,13 @@ const primaryBlockMessage = computed(() => {
|
||||
if (message) return message;
|
||||
const key = `chat.shippingOrderReview.issueCodes.${code}`;
|
||||
if (code && te(key)) return t(key);
|
||||
const failedGate = (props.eligibility?.failed_gates || [])[0];
|
||||
const failedGate = (props.eligibility?.failed_gates || []).find((gate) => {
|
||||
const gateCode = String(gate || '').trim().toLowerCase();
|
||||
if (props.customerResolved === true && (gateCode === 'customer_confirmed' || gateCode === 'customer_resolution')) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (failedGate) {
|
||||
const gateKey = `chat.shippingOrderReview.buildEligibility.gates.${failedGate}`;
|
||||
return te(gateKey) ? t(gateKey) : t('chat.shippingOrderReview.issueCodes.unknown');
|
||||
|
||||
+4
@@ -97,6 +97,10 @@ async function openSelectDialog() {
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
openSelectDialog,
|
||||
});
|
||||
|
||||
/**
|
||||
* 按关键词搜索标准客户。
|
||||
*/
|
||||
|
||||
@@ -117,6 +117,24 @@ async function onRefresh() {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚焦裁决区并短暂高亮动作按钮(Footer / Resolver 委托)。
|
||||
*/
|
||||
function focusAdjudication() {
|
||||
const root = document.querySelector('[data-testid="review-duplicate-panel"]');
|
||||
root?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||||
const actions = document.querySelector('[data-testid="review-duplicate-actions"]');
|
||||
if (!(actions instanceof HTMLElement)) return;
|
||||
actions.classList.add('ring-2', 'ring-amber-400');
|
||||
window.setTimeout(() => {
|
||||
actions.classList.remove('ring-2', 'ring-amber-400');
|
||||
}, 1600);
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
focusAdjudication,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -168,7 +186,11 @@ async function onRefresh() {
|
||||
</span>
|
||||
</p>
|
||||
|
||||
<div v-if="editable && duplicate?.needs_adjudication" class="mt-3 space-y-2">
|
||||
<div
|
||||
v-if="editable && duplicate?.needs_adjudication"
|
||||
class="mt-3 space-y-2 rounded-lg transition-shadow"
|
||||
data-testid="review-duplicate-actions"
|
||||
>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-if="allowed.has('open_existing')"
|
||||
|
||||
@@ -71,6 +71,24 @@ function onFocus(conflict: ShippingOrderReviewFieldConflict) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚焦第一个未解决冲突(Footer / Resolver 委托)。
|
||||
*/
|
||||
function focusFirstConflict() {
|
||||
const first = openConflicts.value[0];
|
||||
if (!first) return;
|
||||
onFocus(first);
|
||||
void Promise.resolve().then(() => {
|
||||
document
|
||||
.querySelector(`[data-testid="review-field-conflict-${first.conflict_key}"]`)
|
||||
?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||||
});
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
focusFirstConflict,
|
||||
});
|
||||
|
||||
/**
|
||||
* 采用某一候选值。
|
||||
*/
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewWorkbenchFooter.vue
|
||||
用途:订单处理工作台底部唯一写操作栏(处置 / 保存 / 流程恢复动作)。
|
||||
用途:订单处理工作台底部唯一写操作栏(处置 / 保存 / 统一流程动作)。
|
||||
依赖:vue-i18n、lucide-vue-next、ActionPresentation。
|
||||
逻辑:ShippingOrderReviewView 传入 available_actions 与流程动作投影;sticky bottom;
|
||||
系统自动推进中隐藏无效主写按钮;流程写操作经 flow-action emit。
|
||||
只读查看时仍可展示 view_result/view_record;写按钮受 actionsExecutable 约束;
|
||||
流程写操作经 flow-action emit(与 Resolver 同链);flowBusy||saving 时禁用。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
@@ -17,19 +18,34 @@ const props = withDefaults(defineProps<{
|
||||
saving: boolean;
|
||||
isReadOnly: boolean;
|
||||
hasDraft: boolean;
|
||||
/** can_build && can_auto_create 时隐藏确认按钮并展示自动推进提示 */
|
||||
/** queued|running 时隐藏确认按钮 */
|
||||
hideConfirmBecauseAutoGate?: boolean;
|
||||
/** waiting/queued/running 时展示自动建单提示(可与确认按钮并存) */
|
||||
showAutoGateHint?: boolean;
|
||||
/** failed/manual_fallback 时展示「重试自动推进」 */
|
||||
showStpRetry?: boolean;
|
||||
/** 自动资格提示文案(等待启动 / 正在推进);由父级按真实 Job 状态计算 */
|
||||
autoGateHint?: string;
|
||||
/** 未保存本地修改计数(硬拦截与底栏提示同源) */
|
||||
unsavedCount?: number;
|
||||
/** 统一流程动作(原进度条 ActionBar);surface=review */
|
||||
flowPresentation?: ActionPresentation | null;
|
||||
/** 系统自动推进中:隐藏主写按钮 */
|
||||
automating?: boolean;
|
||||
/** 是否允许业务写(只读查看为 false) */
|
||||
actionsExecutable?: boolean;
|
||||
/** 统一流程动作提交中 */
|
||||
flowBusy?: boolean;
|
||||
}>(), {
|
||||
unsavedCount: 0,
|
||||
flowPresentation: null,
|
||||
automating: false,
|
||||
hideConfirmBecauseAutoGate: false,
|
||||
showAutoGateHint: false,
|
||||
showStpRetry: false,
|
||||
autoGateHint: '',
|
||||
actionsExecutable: true,
|
||||
flowBusy: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -39,6 +55,7 @@ const emit = defineEmits<{
|
||||
'upload-replacement': [event: Event];
|
||||
validate: [];
|
||||
confirm: [];
|
||||
'retry-stp': [];
|
||||
'flow-action': [item: ActionPresentationItem];
|
||||
}>();
|
||||
|
||||
@@ -51,8 +68,6 @@ function hasAction(action: string): boolean {
|
||||
return props.availableActions.includes(action);
|
||||
}
|
||||
|
||||
const showFooter = computed(() => props.hasDraft && !props.isReadOnly);
|
||||
|
||||
const flowItems = computed((): ActionPresentationItem[] => {
|
||||
const presentation = props.flowPresentation;
|
||||
if (!presentation) return [];
|
||||
@@ -64,6 +79,20 @@ const flowItems = computed((): ActionPresentationItem[] => {
|
||||
return items.filter((item) => item.intent !== 'refresh');
|
||||
});
|
||||
|
||||
const hasViewOnlyFlow = computed(() => flowItems.value.some((item) => (
|
||||
item.intent === 'view_result'
|
||||
|| item.intent === 'view_record'
|
||||
|| item.intent === 'open_profile_review'
|
||||
)));
|
||||
|
||||
/** 可编辑底栏,或只读但仍有导航/查看类流程动作。 */
|
||||
const showFooter = computed(() => (
|
||||
props.hasDraft && (!props.isReadOnly || hasViewOnlyFlow.value)
|
||||
));
|
||||
|
||||
const controlsBusy = computed(() => props.saving || props.flowBusy);
|
||||
const canWriteCaseActions = computed(() => props.actionsExecutable && !props.isReadOnly);
|
||||
|
||||
/**
|
||||
* 流程动作文案。
|
||||
*/
|
||||
@@ -71,7 +100,7 @@ function flowLabel(item: ActionPresentationItem): string {
|
||||
if (te(item.labelKey)) return t(item.labelKey);
|
||||
const gateKey = `workspace.shippingNotice.processGate.actions.${item.actionCode}`;
|
||||
if (te(gateKey)) return t(gateKey);
|
||||
return item.actionCode;
|
||||
return t('chat.shippingProcessing.action.none');
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -81,13 +110,15 @@ function flowLabel(item: ActionPresentationItem): string {
|
||||
class="sticky bottom-0 z-20 flex shrink-0 flex-col gap-3 border-t border-slate-200 bg-white/95 p-3 shadow-[0_-4px_12px_rgba(15,23,42,0.06)] backdrop-blur sm:flex-row sm:items-center sm:justify-between dark:border-slate-800 dark:bg-slate-900/95"
|
||||
data-testid="review-footer-actions"
|
||||
:data-automating="automating ? '1' : '0'"
|
||||
:data-flow-busy="flowBusy ? '1' : '0'"
|
||||
:data-actions-executable="actionsExecutable ? '1' : '0'"
|
||||
>
|
||||
<div class="order-1 flex flex-wrap items-center gap-2 sm:order-1">
|
||||
<template v-if="!automating">
|
||||
<template v-if="!automating && canWriteCaseActions">
|
||||
<button
|
||||
v-if="hasAction('mark_non_order')"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
:disabled="controlsBusy"
|
||||
class="rounded border border-rose-200 px-3 py-2 text-sm text-rose-700 hover:bg-rose-50 disabled:opacity-50 dark:border-rose-900 dark:text-rose-300 dark:hover:bg-rose-950/40"
|
||||
@click="emit('mark-non-order')"
|
||||
>
|
||||
@@ -96,7 +127,7 @@ function flowLabel(item: ActionPresentationItem): string {
|
||||
<button
|
||||
v-if="hasAction('mark_quality_issue')"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
:disabled="controlsBusy"
|
||||
class="rounded border border-amber-200 px-3 py-2 text-sm text-amber-800 hover:bg-amber-50 disabled:opacity-50 dark:border-amber-900 dark:text-amber-200 dark:hover:bg-amber-950/40"
|
||||
@click="emit('mark-quality-issue')"
|
||||
>
|
||||
@@ -105,7 +136,7 @@ function flowLabel(item: ActionPresentationItem): string {
|
||||
<button
|
||||
v-if="hasAction('reparse')"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
:disabled="controlsBusy"
|
||||
class="inline-flex items-center gap-1 rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 disabled:opacity-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
|
||||
@click="emit('reparse')"
|
||||
>
|
||||
@@ -114,12 +145,13 @@ function flowLabel(item: ActionPresentationItem): string {
|
||||
<label
|
||||
v-if="hasAction('mark_quality_issue')"
|
||||
class="cursor-pointer rounded border border-slate-300 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
|
||||
:class="controlsBusy ? 'pointer-events-none opacity-50' : ''"
|
||||
>
|
||||
<input
|
||||
class="sr-only"
|
||||
type="file"
|
||||
accept="application/pdf,.pdf"
|
||||
:disabled="saving"
|
||||
:disabled="controlsBusy"
|
||||
@change="emit('upload-replacement', $event)"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.uploadReplacement') }}
|
||||
@@ -130,7 +162,7 @@ function flowLabel(item: ActionPresentationItem): string {
|
||||
v-for="item in flowItems"
|
||||
:key="`${item.intent}-${item.actionCode}`"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
:disabled="controlsBusy"
|
||||
class="rounded border border-slate-300 px-3 py-2 text-sm text-slate-700 hover:bg-slate-50 disabled:opacity-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
|
||||
:data-testid="`review-footer-flow-${item.intent}`"
|
||||
:data-intent="item.intent"
|
||||
@@ -156,17 +188,27 @@ function flowLabel(item: ActionPresentationItem): string {
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.automatingFooterHint') }}
|
||||
</p>
|
||||
<p
|
||||
v-else-if="hideConfirmBecauseAutoGate"
|
||||
v-else-if="showAutoGateHint && canWriteCaseActions"
|
||||
class="text-xs text-muted"
|
||||
data-testid="review-auto-gate-hint"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.buildEligibility.autoGateProgressHint') }}
|
||||
{{ autoGateHint || t('chat.shippingOrderReview.buildEligibility.autoGateWaitingHint') }}
|
||||
</p>
|
||||
<template v-if="!automating">
|
||||
<template v-if="!automating && canWriteCaseActions">
|
||||
<button
|
||||
v-if="showStpRetry || hasAction('retry_stp_auto_create')"
|
||||
type="button"
|
||||
:disabled="controlsBusy"
|
||||
class="inline-flex items-center gap-1 rounded border border-amber-400 bg-amber-50 px-3 py-2 text-sm text-amber-950 disabled:opacity-50 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100"
|
||||
data-testid="review-retry-stp-auto-create"
|
||||
@click="emit('retry-stp')"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />{{ t('chat.shippingOrderReview.autoProgress.retryStp') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="hasAction('validate')"
|
||||
type="button"
|
||||
:disabled="saving"
|
||||
:disabled="controlsBusy"
|
||||
class="inline-flex items-center gap-1 rounded bg-sky-600 px-3 py-2 text-sm text-white disabled:opacity-50"
|
||||
@click="emit('validate')"
|
||||
>
|
||||
@@ -175,7 +217,7 @@ function flowLabel(item: ActionPresentationItem): string {
|
||||
<button
|
||||
v-if="hasAction('confirm') && !hideConfirmBecauseAutoGate"
|
||||
type="button"
|
||||
:disabled="saving || !canConfirmBuild"
|
||||
:disabled="controlsBusy || !canConfirmBuild"
|
||||
class="rounded bg-emerald-600 px-3 py-2 text-sm font-medium text-white disabled:opacity-50"
|
||||
data-testid="review-confirm-create"
|
||||
:title="!canConfirmBuild ? t('chat.shippingOrderReview.buildEligibility.confirmBlocked') : undefined"
|
||||
|
||||
+65
-17
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/chat/components/shipping-review/ReviewWorkflowProgressPanel.spec.ts
|
||||
* 用途:订单处理台进度面板——紧凑五域条;人工入口仅 Gate 动作。
|
||||
* 用途:订单处理台进度面板——压缩 Strip;人工入口仅 Gate 动作。
|
||||
* 依赖:vitest、@vue/test-utils、vue-i18n stub、RouterLink stub。
|
||||
* 逻辑:有 processingProjection 才渲染 ReviewProgressStrip;无页内 15 阶展开;manual upload 入口需 nextActionCode。
|
||||
* 逻辑:有 processingProjection 才渲染 ReviewProgressStrip;无五域芯片;manual upload 入口需 nextActionCode。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
ShippingProcessingProjection,
|
||||
ShippingReviewProgressContext,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import { SHIPPING_PROCESSING_STAGES } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const messages = {
|
||||
en: {
|
||||
@@ -36,14 +37,12 @@ const messages = {
|
||||
completedOfTotal: '{done} of {total} done',
|
||||
remainingHint: '{count} remaining',
|
||||
positionOfTotal: '{current} / {total}',
|
||||
domainReceiveParse: 'Receive',
|
||||
domainCandidateIdentity: 'Candidate',
|
||||
domainOrderConfirm: 'Confirm',
|
||||
domainInventoryHandle: 'Inventory',
|
||||
domainFulfillmentShip: 'Ship',
|
||||
currentNeedLabel: 'Need: ',
|
||||
systemProcessingNeed: 'System processing',
|
||||
progressTitleWithStage: 'Order processing · {stage}',
|
||||
systemProcessingWithStage: 'System processing · {stage}',
|
||||
viewProcessDetails: 'View process details',
|
||||
viewFullProcess: 'View full process',
|
||||
stageNodesUnavailable: 'Progress details unavailable',
|
||||
},
|
||||
gateReasons: { generic: 'Needs action' },
|
||||
status: {
|
||||
@@ -51,10 +50,7 @@ const messages = {
|
||||
blocked: 'Blocked',
|
||||
processing: 'Processing',
|
||||
},
|
||||
stage: {
|
||||
freight_uploading: 'Uploading to freight',
|
||||
excel_generating: 'Generating Excel',
|
||||
},
|
||||
stage: Object.fromEntries(SHIPPING_PROCESSING_STAGES.map((s) => [s, s])),
|
||||
action: {
|
||||
refresh: 'Refresh',
|
||||
},
|
||||
@@ -72,6 +68,20 @@ const messages = {
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 构造含权威 15 阶的最小投影片段。
|
||||
*/
|
||||
function withStageNodes(
|
||||
partial: Partial<ShippingProcessingProjection>,
|
||||
): Partial<ShippingProcessingProjection> {
|
||||
const stageNodes = SHIPPING_PROCESSING_STAGES.map((stage, absoluteIndex) => ({
|
||||
stage,
|
||||
absoluteIndex,
|
||||
status: (absoluteIndex < 5 ? 'passed' : absoluteIndex === 5 ? 'running' : 'pending') as const,
|
||||
}));
|
||||
return { stageNodes, ...partial };
|
||||
}
|
||||
|
||||
/**
|
||||
* 挂载进度面板。
|
||||
*/
|
||||
@@ -81,12 +91,17 @@ function mountPanel(extras?: {
|
||||
processingProjection?: Partial<ShippingProcessingProjection> | null;
|
||||
}) {
|
||||
const i18n = createI18n({ legacy: false, locale: 'en', messages });
|
||||
const projection = extras?.processingProjection === null
|
||||
? null
|
||||
: extras?.processingProjection
|
||||
? withStageNodes(extras.processingProjection)
|
||||
: null;
|
||||
return mount(ReviewWorkflowProgressPanel, {
|
||||
props: {
|
||||
item: null as ShippingReviewProgressContext | null,
|
||||
taskNo: extras?.taskNo ?? 'SN-1',
|
||||
polling: extras?.polling ?? true,
|
||||
processingProjection: (extras?.processingProjection || null) as ShippingProcessingProjection | null,
|
||||
processingProjection: projection as ShippingProcessingProjection | null,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
@@ -109,21 +124,29 @@ describe('ReviewWorkflowProgressPanel', () => {
|
||||
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('renders compact domain strip without inline 15-node expand', () => {
|
||||
it('renders compressed strip with 15 nodes and without domain chips', () => {
|
||||
const wrapper = mountPanel({
|
||||
polling: false,
|
||||
processingProjection: {
|
||||
status: 'processing',
|
||||
stage: 'excel_generating',
|
||||
status: 'waiting_review',
|
||||
stage: 'waiting_review',
|
||||
sourceType: 'eml',
|
||||
currentGate: {
|
||||
gateCode: 'order_review',
|
||||
status: 'blocked',
|
||||
nextActionCode: 'confirm_customer',
|
||||
blockingReasonCode: 'generic',
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-progress-unavailable"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-progress-strip"]').exists()).toBe(true);
|
||||
expect(wrapper.findAll('[data-testid="review-progress-domains"] [data-domain]').length).toBe(5);
|
||||
expect(wrapper.find('[data-testid="review-progress-domains"]').exists()).toBe(false);
|
||||
expect(wrapper.findAll('[data-testid="review-progress-stage-nodes"] [data-stage]')).toHaveLength(15);
|
||||
expect(wrapper.find('[data-testid="review-progress-expand-full"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="unified-action-bar"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-progress-open-details"]').exists()).toBe(true);
|
||||
expect(wrapper.get('[data-testid="review-progress-title"]').text()).toContain('Order processing');
|
||||
});
|
||||
|
||||
it('hides manual CTA while automating freight upload', () => {
|
||||
@@ -133,9 +156,13 @@ describe('ReviewWorkflowProgressPanel', () => {
|
||||
status: 'automating',
|
||||
stage: 'freight_uploading',
|
||||
sourceType: 'eml',
|
||||
currentGate: null,
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-progress-strip"]').exists()).toBe(true);
|
||||
expect(wrapper.get('[data-testid="review-progress-title"]').text()).toContain('System processing');
|
||||
expect(wrapper.find('[data-testid="review-progress-refresh"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-progress-current-need"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-manual-upload-next-steps"]').exists()).toBe(false);
|
||||
});
|
||||
@@ -178,5 +205,26 @@ describe('ReviewWorkflowProgressPanel', () => {
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-manual-upload-next-steps"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-generic-next-steps"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('never renders generic next-steps for blocked non-upload gates', () => {
|
||||
const wrapper = mountPanel({
|
||||
polling: false,
|
||||
processingProjection: {
|
||||
status: 'blocked',
|
||||
stage: 'waiting_review',
|
||||
sourceType: 'eml',
|
||||
currentGate: {
|
||||
gateCode: 'order_review',
|
||||
status: 'blocked',
|
||||
nextActionCode: 'confirm_customer',
|
||||
blockingReasonCode: 'generic',
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('[data-testid="review-progress-current-need"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="review-generic-next-steps"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="review-manual-upload-next-steps"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
+19
-92
@@ -1,8 +1,9 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewWorkflowProgressPanel.vue
|
||||
用途:订单处理工作台只读进度区(ReviewProgressStrip)+ Gate / 人工上传下一步提示。
|
||||
依赖:vue-i18n、ShippingProcessingProjection、ReviewProgressStrip。
|
||||
逻辑:节点高亮只读统一投影;打开流程详情 / 刷新 emit 给宿主;写操作不在本面板。
|
||||
用途:订单处理工作台只读进度区外壳——挂载压缩版 ReviewProgressStrip + 人工上传入口。
|
||||
依赖:vue-i18n、ShippingProcessingProjection、ReviewProgressStrip、shippingProcessingFulfillment。
|
||||
逻辑:标题与「当前需要」由 Strip 统一渲染;surface=review 永不渲染 review-generic-next-steps;
|
||||
仅人工上传保留任务台跳转;其他 Gate 只靠 Strip + Footer;写操作不在本面板。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
@@ -15,10 +16,6 @@ import type {
|
||||
import {
|
||||
projectionRequiresManualUploadWorkbench,
|
||||
} from '@/features/chat/shipping/shippingProcessingFulfillment';
|
||||
import {
|
||||
resolveShippingProcessingStatusLabel,
|
||||
shippingProcessingStageKey,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import ReviewProgressStrip from '@/features/shipping-progress/components/ReviewProgressStrip.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -34,52 +31,18 @@ const emit = defineEmits<{
|
||||
refresh: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const { t } = useI18n();
|
||||
|
||||
const hasProjection = computed(() => Boolean(props.processingProjection));
|
||||
|
||||
const unifiedStatusLabel = computed(() => {
|
||||
const status = props.processingProjection?.status;
|
||||
if (!status) return '';
|
||||
return resolveShippingProcessingStatusLabel(status, te, t);
|
||||
});
|
||||
|
||||
const unifiedStageLabel = computed(() => {
|
||||
const stage = props.processingProjection?.stage;
|
||||
if (!stage) return '';
|
||||
const key = shippingProcessingStageKey(stage);
|
||||
return te(key) ? t(key) : stage;
|
||||
});
|
||||
|
||||
/**
|
||||
* 仅当 Gate next_action 明确指人工上传且非 RPA 阶段时展示任务台入口。
|
||||
* 仅当 Gate next_action 明确指人工上传且非 RPA 阶段时展示任务台入口(非纯文案重复)。
|
||||
*/
|
||||
const showTaskWorkbenchLink = computed(() => {
|
||||
if (!props.processingProjection) return false;
|
||||
if (!projectionRequiresManualUploadWorkbench(props.processingProjection)) return false;
|
||||
return Boolean(String(props.taskNo || '').trim());
|
||||
});
|
||||
|
||||
/**
|
||||
* blocked 且非人工上传时展示通用下一步提示(来自 Gate 动作 i18n)。
|
||||
*/
|
||||
const showGenericNextSteps = computed(() => {
|
||||
const projection = props.processingProjection;
|
||||
if (!projection || showTaskWorkbenchLink.value) return false;
|
||||
const nextAction = String(projection.currentGate?.nextActionCode || '').trim();
|
||||
if (!nextAction) return false;
|
||||
const status = String(projection.status || '').trim().toLowerCase();
|
||||
return status === 'blocked' || status === 'needs_action';
|
||||
});
|
||||
|
||||
const genericNextStepMessage = computed(() => {
|
||||
const code = String(props.processingProjection?.currentGate?.nextActionCode || '').trim();
|
||||
if (code) {
|
||||
const gateKey = `workspace.shippingNotice.processGate.actions.${code}`;
|
||||
if (te(gateKey)) return t(gateKey);
|
||||
}
|
||||
return t('chat.shippingOrderReview.workflowProgress.nextStepsGeneric');
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -87,50 +50,21 @@ const genericNextStepMessage = computed(() => {
|
||||
class="rounded-xl border border-default bg-surface-soft/60 p-3"
|
||||
data-testid="review-workflow-progress-panel"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.title') }}
|
||||
</div>
|
||||
<div
|
||||
v-if="hasProjection && (unifiedStatusLabel || unifiedStageLabel)"
|
||||
class="mt-0.5 text-[11px] text-secondary"
|
||||
data-testid="review-progress-unified-label"
|
||||
>
|
||||
<span v-if="unifiedStatusLabel">{{ unifiedStatusLabel }}</span>
|
||||
<span v-if="unifiedStageLabel"> · {{ unifiedStageLabel }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="!hasProjection"
|
||||
class="mt-0.5 text-[11px] text-amber-700 dark:text-amber-300"
|
||||
data-testid="review-progress-unavailable"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.progressUnavailable') }}
|
||||
</div>
|
||||
<div v-else class="mt-0.5 text-[11px] text-secondary">
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.subtitle') }}
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
v-if="polling"
|
||||
class="shrink-0 text-[11px] text-muted"
|
||||
data-testid="review-workflow-progress-polling"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.polling') }}
|
||||
</span>
|
||||
<div
|
||||
v-if="!hasProjection"
|
||||
class="text-[11px] text-amber-700 dark:text-amber-300"
|
||||
data-testid="review-progress-unavailable"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.progressUnavailable') }}
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="processingProjection"
|
||||
class="mt-3"
|
||||
data-testid="review-progress-nodes"
|
||||
>
|
||||
<ReviewProgressStrip
|
||||
:projection="processingProjection"
|
||||
@open-process-details="emit('open-process-details')"
|
||||
@refresh="emit('refresh')"
|
||||
/>
|
||||
</div>
|
||||
<ReviewProgressStrip
|
||||
v-else-if="processingProjection"
|
||||
:projection="processingProjection"
|
||||
:polling="polling"
|
||||
@open-process-details="emit('open-process-details')"
|
||||
@refresh="emit('refresh')"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="showTaskWorkbenchLink"
|
||||
@@ -146,12 +80,5 @@ const genericNextStepMessage = computed(() => {
|
||||
{{ t('chat.shippingOrderReview.workflowProgress.openTaskWorkbench') }}
|
||||
</RouterLink>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="showGenericNextSteps"
|
||||
class="mt-3 rounded-md border border-default bg-surface-soft px-2.5 py-2 text-[11px] text-secondary"
|
||||
data-testid="review-generic-next-steps"
|
||||
>
|
||||
<p>{{ genericNextStepMessage }}</p>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
+155
-42
@@ -1,8 +1,9 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts
|
||||
* 用途:验收右侧任务分组卡——needs_action/processing 与短时反馈标签。
|
||||
* 用途:验收右侧任务分组卡——needs_action / processing / 处理记录三子段与动作层级。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、ShippingConversationProcessingCard。
|
||||
* 逻辑:构造 ConversationProcessingProjection;断言分组、焦点 emit;右侧不渲染 history。
|
||||
* 逻辑:构造 ConversationProcessingProjection;断言分组文案、处理记录折叠与三类子段、
|
||||
* UI-02 单一详情入口、UI-03 history 截断角标、有 workItem 时无任务级主/次按钮。
|
||||
*/
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
@@ -22,7 +23,7 @@ const i18n = createI18n({
|
||||
|
||||
function buildProjection(): ConversationProcessingProjection {
|
||||
return {
|
||||
summary: { total_tasks: 3, processing: 1, needs_action: 1, completed: 1, history: 0 },
|
||||
summary: { total_tasks: 3, processing: 1, needs_action: 1, completed: 1, history: 2 },
|
||||
focused_task_no: 'OT-PROC',
|
||||
recent_task_no: 'OT-PROC',
|
||||
needs_action: [{
|
||||
@@ -55,15 +56,28 @@ function buildProjection(): ConversationProcessingProjection {
|
||||
can_append: false,
|
||||
available_actions: ['view_details'],
|
||||
}],
|
||||
history: [{
|
||||
user_task_no: 'OT-HIST',
|
||||
group: 'history',
|
||||
status_label: 'completed',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-HIST',
|
||||
can_append: false,
|
||||
viewed: true,
|
||||
}],
|
||||
history: [
|
||||
{
|
||||
user_task_no: 'OT-HIST',
|
||||
group: 'history',
|
||||
status_label: 'completed',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-HIST',
|
||||
can_append: false,
|
||||
viewed: true,
|
||||
available_actions: ['view_details'],
|
||||
},
|
||||
{
|
||||
user_task_no: 'OT-CANCEL',
|
||||
group: 'history',
|
||||
status_label: 'cancelled',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-CANCEL',
|
||||
can_append: false,
|
||||
viewed: true,
|
||||
available_actions: ['view_details'],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -103,7 +117,7 @@ function buildWorkItem(
|
||||
}
|
||||
|
||||
describe('ShippingConversationProcessingCard', () => {
|
||||
it('renders needs_action / processing / completed groups, hides history on the right panel', async () => {
|
||||
it('renders needs_action / processing groups and collapsible processing records with three subsections', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection: buildProjection() },
|
||||
global: { plugins: [i18n] },
|
||||
@@ -113,18 +127,88 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
expect(wrapper.find('[data-testid="shipping-conversation-processing-card"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-needs_action"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-processing"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-completed"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-DONE"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('需要你处理 · 1 个任务');
|
||||
expect(wrapper.text()).toContain('系统处理中 · 1 个任务');
|
||||
expect(wrapper.text()).toContain('刚刚创建');
|
||||
expect(wrapper.text()).toContain('已完成');
|
||||
// UI-04:右侧不展示处理记录分组。
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-history"]').exists()).toBe(false);
|
||||
|
||||
// 处理记录默认折叠;标题 count = completed + history 返回条数。
|
||||
const historyGroup = wrapper.find('[data-testid="shipping-processing-group-history"]');
|
||||
expect(historyGroup.exists()).toBe(true);
|
||||
expect(historyGroup.text()).toContain('处理记录 · 3');
|
||||
expect(wrapper.find('[data-testid="shipping-processing-history-body"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-DONE"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-HIST"]').exists()).toBe(false);
|
||||
|
||||
await wrapper.find('[data-testid="shipping-processing-history-toggle"]').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
expect(wrapper.find('[data-testid="shipping-processing-history-body"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-history-completed"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-history-versions"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-history-cancelled"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-DONE"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-HIST"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-CANCEL"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-history-completed"]').text()).toContain('已完成');
|
||||
expect(wrapper.find('[data-testid="shipping-processing-history-versions"]').text()).toContain('历史版本');
|
||||
expect(wrapper.find('[data-testid="shipping-processing-history-cancelled"]').text()).toContain('已取消');
|
||||
});
|
||||
|
||||
it('renders multi-PDF task title instead of first filename', async () => {
|
||||
it('shows history more badge when summary.history exceeds returned history length', async () => {
|
||||
const projection = buildProjection();
|
||||
projection.summary.history = 14;
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: { projection },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// UI-03:折叠态即可看到「还有 N 条」。
|
||||
expect(wrapper.find('[data-testid="shipping-processing-history-more"]').text()).toContain('还有 12 条');
|
||||
await wrapper.find('[data-testid="shipping-processing-history-toggle"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="shipping-processing-history-truncated"]').text())
|
||||
.toContain('仅展示最近 2 条,另有 12 条未显示');
|
||||
});
|
||||
|
||||
it('falls back to generic truncated hint when hasMoreHistory but no reliable hidden count', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: buildProjection(),
|
||||
hasMoreHistory: true,
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="shipping-processing-history-more"]').exists()).toBe(false);
|
||||
await wrapper.find('[data-testid="shipping-processing-history-toggle"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="shipping-processing-history-truncated"]').text())
|
||||
.toContain('列表已截断,仅展示最近任务');
|
||||
});
|
||||
|
||||
it('keeps processing-record cards read-only without primary CTA or progress', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: buildProjection(),
|
||||
workItems: [
|
||||
buildWorkItem('OT-DONE', { status: 'completed', stage: 'completed' }),
|
||||
],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
await wrapper.find('[data-testid="shipping-processing-history-toggle"]').trigger('click');
|
||||
await flushPromises();
|
||||
|
||||
const doneCard = wrapper.find('[data-testid="shipping-processing-task-OT-DONE"]');
|
||||
expect(doneCard.find('[data-testid="sidebar-progress-inline"]').exists()).toBe(false);
|
||||
expect(doneCard.find('[data-testid="shipping-processing-task-actions"]').exists()).toBe(false);
|
||||
expect(doneCard.find('[data-testid="shipping-processing-action-view_details"]').exists()).toBe(true);
|
||||
expect(doneCard.find('[data-testid="shipping-processing-action-cancel_task"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('uses expand-files as the only detail entry when canExpandFileDetails', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
@@ -151,12 +235,49 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
await flushPromises();
|
||||
expect(wrapper.text()).toContain('订单识别任务');
|
||||
expect(wrapper.text()).toContain('2 个 PDF');
|
||||
expect(wrapper.text()).toContain('4518838152.pdf、4518838154.pdf');
|
||||
expect(wrapper.text()).toContain('取消整个任务');
|
||||
// 主标题不得单独伪装成首个 PDF 文件名任务。
|
||||
expect(wrapper.text()).toContain('主文件:4518838152.pdf');
|
||||
const titleEl = wrapper.find('[data-testid="shipping-processing-task-OT-MULTI"] .text-sm.font-semibold');
|
||||
expect(titleEl.text()).toContain('订单识别任务');
|
||||
expect(titleEl.text()).not.toContain('4518838152.pdf');
|
||||
|
||||
// UI-02:有文件对象时不双开「查看详情」与「展开文件详情」。
|
||||
expect(wrapper.find('[data-testid="shipping-processing-expand-files"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-action-view_details"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-action-cancel_task"]').exists()).toBe(false);
|
||||
await wrapper.find('[data-testid="shipping-processing-expand-files"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-overflow-actions"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-action-cancel_task"]').text()).toContain('取消整个任务');
|
||||
});
|
||||
|
||||
it('shows view_details when task cannot expand file details, and keeps cancel as overflow', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
summary: { total_tasks: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
needs_action: [{
|
||||
user_task_no: 'OT-SINGLE',
|
||||
group: 'needs_action',
|
||||
status_label: 'pending_review',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-SINGLE',
|
||||
can_append: false,
|
||||
available_actions: ['view_details', 'cancel_task'],
|
||||
objects: [],
|
||||
}],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
},
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.find('[data-testid="shipping-processing-expand-files"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-action-view_details"]').exists()).toBe(true);
|
||||
// 无文件对象时取消可直接挂在卡上(低频文字链,非主 CTA)。
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-overflow-actions"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-action-cancel_task"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('shows multi-document title from authoritative projection without workflow fallback', async () => {
|
||||
@@ -192,7 +313,7 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
expect(titleEl.text()).not.toContain('4518838152.pdf');
|
||||
});
|
||||
|
||||
it('falls back to unnamed PDF instead of internal OT number', async () => {
|
||||
it('uses unified order recognition title instead of internal OT number', async () => {
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
projection: {
|
||||
@@ -214,7 +335,7 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.text()).toContain('未命名 PDF');
|
||||
expect(wrapper.text()).toContain('订单识别任务');
|
||||
expect(wrapper.text()).not.toContain('20260803-A13F95D2');
|
||||
});
|
||||
|
||||
@@ -242,7 +363,6 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
});
|
||||
await flushPromises();
|
||||
const needCard = wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]');
|
||||
// 关键断言:待操作聚焦卡必须有用户可见 ring,不能只写 data-focused。
|
||||
expect(needCard.attributes('data-focused')).toBe('1');
|
||||
expect(needCard.classes().join(' ')).toContain('ring-brand-400');
|
||||
const other = wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]');
|
||||
@@ -264,12 +384,10 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
const taskRoot = wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]');
|
||||
const buttons = taskRoot.findAll('button');
|
||||
// 最后一个按钮是展开/收起文件详情
|
||||
await buttons[buttons.length - 1].trigger('click');
|
||||
const expandBtn = wrapper.find('[data-testid="shipping-processing-expand-files"]');
|
||||
await expandBtn.trigger('click');
|
||||
expect(wrapper.emitted('expandFiles')?.[0]?.[0]).toMatchObject({ user_task_no: 'OT-NEED' });
|
||||
await buttons[buttons.length - 1].trigger('click');
|
||||
await expandBtn.trigger('click');
|
||||
expect(wrapper.emitted('collapseFiles')).toBeTruthy();
|
||||
});
|
||||
|
||||
@@ -294,7 +412,7 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
expect(wrapper.findAll('[data-testid^="shipping-processing-task-"]')).toHaveLength(20);
|
||||
expect(wrapper.findAll('article[data-testid^="shipping-processing-task-"]')).toHaveLength(20);
|
||||
expect(wrapper.findAll('[data-testid="shipping-conversation-processing-card"]')).toHaveLength(1);
|
||||
});
|
||||
|
||||
@@ -344,7 +462,6 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
expect(wrapper.find('[data-testid="shipping-processing-group-order-intake"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-intake-SNI-1"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('po.pdf');
|
||||
// 关键断言:失败恢复元信息(原因 / Attempt / 资产)出现在材料卡。
|
||||
expect(wrapper.find('[data-testid="shipping-processing-intake-recovery"]').exists()).toBe(true);
|
||||
expect(wrapper.text()).toContain('SHIPPING_NOTICE.INTAKE_PARSE_FAILED');
|
||||
await wrapper.find('[data-testid="shipping-processing-intake-action-retry_parse"]').trigger('click');
|
||||
@@ -354,7 +471,7 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('renders each PDF task with its own compact projection, including completed tasks', async () => {
|
||||
it('hides task-level primary/secondary when workItem exists but keeps expand-files entry', async () => {
|
||||
const projection = buildProjection();
|
||||
const wrapper = mount(ShippingConversationProcessingCard, {
|
||||
props: {
|
||||
@@ -367,23 +484,19 @@ describe('ShippingConversationProcessingCard', () => {
|
||||
buildWorkItem('OT-PROC', {
|
||||
stage: 'inventory_matching',
|
||||
}),
|
||||
buildWorkItem('OT-DONE', {
|
||||
status: 'completed',
|
||||
stage: 'completed',
|
||||
}),
|
||||
],
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
// 未聚焦时:needs_action/processing 显示紧凑进度;已完成默认收起(UI-05)。
|
||||
expect(wrapper.findAll('[data-testid="sidebar-progress-inline"]')).toHaveLength(2);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-DONE"] [data-testid="sidebar-progress-inline"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]').text()).toContain('待复核');
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]').text()).toContain('库存匹配');
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-DONE"]').text()).toContain('已完成');
|
||||
expect(wrapper.findAll('[data-testid="shipping-processing-task-actions"]')).toHaveLength(0);
|
||||
// UI-02:有 workItem 时仍保留展开文件详情(OT-NEED 为多文件)。
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"] [data-testid="shipping-processing-expand-files"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"] [data-testid="shipping-processing-action-view_details"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it('maps internal review_case_draft status to a user-facing review label', async () => {
|
||||
|
||||
+427
-203
@@ -1,15 +1,16 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingConversationProcessingCard.vue
|
||||
* 用途:右侧「本次处理中」顶层任务卡——按 needs_action / processing / completed 展示。
|
||||
* 用途:右侧「本次处理中」顶层任务卡——needs_action / processing / 处理记录。
|
||||
* 依赖:vue-i18n、ConversationProcessingProjection、conversationProcessingState、
|
||||
* shippingProcessingLabels、SidebarProgressInline。
|
||||
* 逻辑:由 ShippingWorkflowTimeline 嵌入;只消费统一 projection / workItems,禁止 Workflow fallback;
|
||||
* 单 PDF 主标题用文件名,多 PDF 用「订单识别任务」;右侧不渲染 history;
|
||||
* 仅聚焦卡展开完整 SidebarProgressInline,未聚焦显示紧凑单行,已完成默认收起(UI-05);
|
||||
* 单 PDF 不展示「展开文件详情」。
|
||||
* conversationProcessingDisplay、actionPresentation、shippingProcessingLabels、SidebarProgressInline。
|
||||
* 逻辑:由 ShippingWorkflowTimeline 嵌入;只消费统一 projection / workItems;
|
||||
* 统一「订单识别任务」+ 主文件副标题;处理记录默认折叠(已完成/历史版本/已取消);
|
||||
* UI-02:有文件对象时次要入口仅为「展开文件详情」,无文件对象时才「查看详情」;
|
||||
* 有 workItem 时不渲染任务级主/次按钮,仍可保留展开文件入口;
|
||||
* UI-03:history 截断时折叠标题显示「还有 N 条」,展开底部显示明细截断文案。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, watch } from 'vue';
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ChevronDown, ChevronRight } from 'lucide-vue-next';
|
||||
import type {
|
||||
@@ -17,6 +18,7 @@ import type {
|
||||
ConversationProcessingUserTask,
|
||||
ShippingProcessingProjection,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import { getPrimaryDocumentName } from '@/features/chat/shipping/conversationProcessingDisplay';
|
||||
import {
|
||||
createConversationProcessingUiState,
|
||||
focusTaskManually,
|
||||
@@ -32,8 +34,9 @@ import {
|
||||
shippingProcessingSourceTypeKey,
|
||||
shippingProcessingStageKey,
|
||||
} from '@/features/chat/shipping/shippingProcessingLabels';
|
||||
import { resolveConversationTaskActionPresentation } from '@/features/shipping-progress/actionPresentation';
|
||||
import SidebarProgressInline from '@/features/shipping-progress/components/SidebarProgressInline.vue';
|
||||
import type { ActionPresentationItem } from '@/features/shipping-progress/types';
|
||||
import type { ActionPresentation, ActionPresentationItem } from '@/features/shipping-progress/types';
|
||||
|
||||
const props = defineProps<{
|
||||
projection: ConversationProcessingProjection | null;
|
||||
@@ -41,6 +44,8 @@ const props = defineProps<{
|
||||
workItems?: ShippingProcessingProjection[] | null;
|
||||
/** 当前会话 ID;切换时重置本地焦点/展开状态 */
|
||||
conversationId?: string | null;
|
||||
/** 后端截断提示:history 还有未返回内容时在处理记录底部展示 */
|
||||
hasMoreHistory?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -60,6 +65,8 @@ const emit = defineEmits<{
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const uiState = createConversationProcessingUiState();
|
||||
/** 处理记录整组默认折叠。 */
|
||||
const historySectionExpanded = ref(false);
|
||||
|
||||
/** 唯一进度源:统一 conversation_processing / work_items 合成投影。 */
|
||||
const activeProjection = computed((): ConversationProcessingProjection | null => (
|
||||
@@ -81,6 +88,31 @@ const hasContent = computed(() => Boolean(
|
||||
));
|
||||
|
||||
const completedTasks = computed(() => activeProjection.value?.completed || []);
|
||||
const historyTasks = computed(() => activeProjection.value?.history || []);
|
||||
|
||||
/** history 中非取消 →「历史版本」。 */
|
||||
const historyVersionTasks = computed(() => historyTasks.value.filter(
|
||||
(task) => String(task.status_label || '').trim().toLowerCase() !== 'cancelled',
|
||||
));
|
||||
|
||||
/** history 中明确 cancelled →「已取消」。 */
|
||||
const cancelledHistoryTasks = computed(() => historyTasks.value.filter(
|
||||
(task) => String(task.status_label || '').trim().toLowerCase() === 'cancelled',
|
||||
));
|
||||
|
||||
/** 处理记录标题计数:当前返回的 completed + history。 */
|
||||
const recordTaskCount = computed(() => (
|
||||
completedTasks.value.length + historyTasks.value.length
|
||||
));
|
||||
|
||||
/**
|
||||
* history 未返回条数:summary.history - 当前 history[];不可靠时为 0(不猜数)。
|
||||
*/
|
||||
const hiddenHistoryCount = computed(() => {
|
||||
const summaryTotal = Number(activeProjection.value?.summary?.history || 0);
|
||||
if (!Number.isFinite(summaryTotal) || summaryTotal <= 0) return 0;
|
||||
return Math.max(0, summaryTotal - historyTasks.value.length);
|
||||
});
|
||||
|
||||
const focusedTaskNo = computed(() => resolveFocusedTask(uiState, {
|
||||
serverFocusedTaskNo: activeProjection.value?.focused_task_no,
|
||||
@@ -106,6 +138,7 @@ watch(
|
||||
(next, prev) => {
|
||||
if (next === prev) return;
|
||||
resetConversationProcessingUiState(uiState);
|
||||
historySectionExpanded.value = false;
|
||||
},
|
||||
);
|
||||
|
||||
@@ -151,48 +184,35 @@ function isMultiDocumentTask(task: ConversationProcessingUserTask): boolean {
|
||||
function canExpandFileDetails(task: ConversationProcessingUserTask): boolean {
|
||||
if (isMultiDocumentTask(task)) return true;
|
||||
const objects = Array.isArray(task.objects) ? task.objects : [];
|
||||
return objects.length > 1;
|
||||
return objects.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* UI-05:仅聚焦且非已完成卡展开完整进度;未聚焦显示紧凑单行;已完成默认不展进度。
|
||||
* 活跃卡进度:聚焦全量 / 未聚焦紧凑;处理记录(completed/history)永不展实时进度。
|
||||
*/
|
||||
function progressModeForTask(task: ConversationProcessingUserTask): 'full' | 'compact' | 'hidden' {
|
||||
if (!projectionForTask(task)) return 'hidden';
|
||||
const group = String(task.group || '').trim();
|
||||
if (group === 'completed' || group === 'history') return 'hidden';
|
||||
const focused = focusedTaskNo.value === task.user_task_no;
|
||||
const completed = String(task.group || '').trim() === 'completed'
|
||||
|| String(task.status_label || '').trim().toLowerCase() === 'completed';
|
||||
if (completed && !focused) return 'hidden';
|
||||
if (focused) return 'full';
|
||||
return 'compact';
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务主标题:单 PDF 用文件名;多 PDF 用 i18n「订单识别任务」;禁止 OT/Run 编号。
|
||||
* 任务主标题:统一「订单识别任务」;禁止用 filename / task.title / OT 编号。
|
||||
*/
|
||||
function taskLabel(task: ConversationProcessingUserTask): string {
|
||||
if (isMultiDocumentTask(task)) {
|
||||
return t('chat.shippingProcessing.multiPdfTaskTitle');
|
||||
}
|
||||
const title = String(task.title || '').trim();
|
||||
if (title) return title;
|
||||
return t('chat.shippingProcessing.unnamedPdf');
|
||||
function taskLabel(_task: ConversationProcessingUserTask): string {
|
||||
return t('chat.shippingProcessing.multiPdfTaskTitle');
|
||||
}
|
||||
|
||||
/**
|
||||
* 多 PDF 副标题:前两个文件名;超过两个时追加「等 N 个 PDF」。
|
||||
* 主文件副标题:有主文件名时渲染「主文件:{name}」。
|
||||
*/
|
||||
function documentNamesPreview(task: ConversationProcessingUserTask): string {
|
||||
const names = (Array.isArray(task.document_names) ? task.document_names : [])
|
||||
.map((name) => String(name || '').trim())
|
||||
.filter(Boolean);
|
||||
if (names.length <= 1) return '';
|
||||
const head = names.slice(0, 2).join(t('chat.shippingProcessing.multiPdfNameSeparator'));
|
||||
if (names.length === 2) return head;
|
||||
return t('chat.shippingProcessing.multiPdfNamesMore', {
|
||||
names: head,
|
||||
count: names.length,
|
||||
});
|
||||
function primaryFileLabel(task: ConversationProcessingUserTask): string {
|
||||
const name = getPrimaryDocumentName(task);
|
||||
if (!name) return '';
|
||||
return t('chat.shippingProcessing.primaryFile', { name });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -214,32 +234,6 @@ function statusLabel(task: ConversationProcessingUserTask): string {
|
||||
return resolveShippingProcessingStatusLabel(String(task.status_label || ''), te, t);
|
||||
}
|
||||
|
||||
/**
|
||||
* 最近活动时间:当天仅时分;昨天带「昨天」;更早带月日。
|
||||
*/
|
||||
function activityLabel(task: ConversationProcessingUserTask): string {
|
||||
const raw = String(task.last_activity_at || '').trim();
|
||||
if (!raw) return '';
|
||||
const date = new Date(raw);
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
const hh = String(date.getHours()).padStart(2, '0');
|
||||
const mm = String(date.getMinutes()).padStart(2, '0');
|
||||
const time = `${hh}:${mm}`;
|
||||
const now = new Date();
|
||||
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const startOfTarget = new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
||||
const dayDiff = Math.round((startOfToday.getTime() - startOfTarget.getTime()) / 86400000);
|
||||
if (dayDiff === 0) {
|
||||
return t('chat.shippingProcessing.updatedAt', { time });
|
||||
}
|
||||
if (dayDiff === 1) {
|
||||
return t('chat.shippingProcessing.updatedYesterday', { time });
|
||||
}
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
return t('chat.shippingProcessing.updatedOnDate', { date: `${month}-${day}`, time });
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否高亮 needs_action 任务。
|
||||
*/
|
||||
@@ -258,81 +252,141 @@ function isDetailsExpanded(task: ConversationProcessingUserTask): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务级可见操作:只展示后端权威动作中的业务入口。
|
||||
* 解析任务卡 ActionPresentation(cancel/view_details 不作主 CTA)。
|
||||
*/
|
||||
function visibleTaskActions(task: ConversationProcessingUserTask): string[] {
|
||||
const actions = Array.isArray(task.available_actions) ? task.available_actions : [];
|
||||
const preferred = [
|
||||
'view_details',
|
||||
'open_review',
|
||||
'enter_manual_review',
|
||||
'retry_failed_documents',
|
||||
'retry_failed_attachments',
|
||||
'cancel_task',
|
||||
'cancel_run',
|
||||
];
|
||||
const seen = new Set<string>();
|
||||
const result: string[] = [];
|
||||
for (const code of preferred) {
|
||||
if (!actions.includes(code) || seen.has(code)) continue;
|
||||
// 别名去重:只保留一套展示
|
||||
if (code === 'open_review' && seen.has('enter_manual_review')) continue;
|
||||
if (code === 'enter_manual_review' && seen.has('open_review')) continue;
|
||||
if (code === 'retry_failed_documents' && seen.has('retry_failed_attachments')) continue;
|
||||
if (code === 'retry_failed_attachments' && seen.has('retry_failed_documents')) continue;
|
||||
if (code === 'cancel_task' && seen.has('cancel_run')) continue;
|
||||
if (code === 'cancel_run' && seen.has('cancel_task')) continue;
|
||||
seen.add(code);
|
||||
result.push(code);
|
||||
}
|
||||
return result;
|
||||
function taskActionPresentation(task: ConversationProcessingUserTask): ActionPresentation {
|
||||
return resolveConversationTaskActionPresentation(task, { surface: 'right' });
|
||||
}
|
||||
|
||||
/**
|
||||
* 动作按钮文案:任务级取消在多 PDF 时明确为「取消整个任务」。
|
||||
* 唯一主 CTA(实心按钮);处理记录只读卡不调用。
|
||||
*/
|
||||
function actionLabel(task: ConversationProcessingUserTask, action: string): string {
|
||||
const code = String(action || '').trim();
|
||||
function primaryActionItem(task: ConversationProcessingUserTask): ActionPresentationItem | null {
|
||||
return taskActionPresentation(task).primary;
|
||||
}
|
||||
|
||||
/**
|
||||
* 次要文字链:有文件对象时可展开 → 不返回 view_details(改由展开文件入口承载);
|
||||
* 无文件对象时优先 view_details,否则取非 cancel 的 presentation.secondary。
|
||||
*/
|
||||
function secondaryActionItem(task: ConversationProcessingUserTask): ActionPresentationItem | null {
|
||||
if (canExpandFileDetails(task)) return null;
|
||||
const presentation = taskActionPresentation(task);
|
||||
const candidates = [
|
||||
presentation.secondary,
|
||||
...presentation.overflow,
|
||||
].filter((item): item is ActionPresentationItem => Boolean(item));
|
||||
const viewDetails = candidates.find(
|
||||
(item) => String(item.actionCode || '').trim().toLowerCase() === 'view_details',
|
||||
);
|
||||
if (viewDetails) return viewDetails;
|
||||
const secondary = presentation.secondary;
|
||||
if (!secondary) return null;
|
||||
const code = String(secondary.actionCode || '').trim().toLowerCase();
|
||||
if (code === 'cancel_task' || code === 'cancel_run' || code === 'view_details') return null;
|
||||
return secondary;
|
||||
}
|
||||
|
||||
/**
|
||||
* 低频溢出动作:排除已展示的主/次 CTA 与 view_details。
|
||||
*/
|
||||
function overflowActionItems(task: ConversationProcessingUserTask): ActionPresentationItem[] {
|
||||
const presentation = taskActionPresentation(task);
|
||||
const shown = new Set(
|
||||
[primaryActionItem(task)?.actionCode, secondaryActionItem(task)?.actionCode]
|
||||
.map((code) => String(code || '').trim().toLowerCase())
|
||||
.filter(Boolean),
|
||||
);
|
||||
shown.add('view_details');
|
||||
return [presentation.secondary, ...presentation.overflow]
|
||||
.filter((item): item is ActionPresentationItem => Boolean(item))
|
||||
.filter((item) => {
|
||||
const code = String(item.actionCode || '').trim().toLowerCase();
|
||||
return Boolean(code) && !shown.has(code);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否展示低频溢出:有文件对象时仅展开后显示;无文件对象时直接挂在卡上(如取消)。
|
||||
* 有 workItem 时不渲染任务级溢出(动作由进度条负责)。
|
||||
*/
|
||||
function shouldShowOverflowActions(task: ConversationProcessingUserTask): boolean {
|
||||
if (projectionForTask(task)) return false;
|
||||
if (!overflowActionItems(task).length) return false;
|
||||
if (canExpandFileDetails(task)) return isDetailsExpanded(task);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否渲染任务级主/次动作区(不含「展开文件详情」文件控制)。
|
||||
*/
|
||||
function shouldShowTaskLevelActions(task: ConversationProcessingUserTask): boolean {
|
||||
if (projectionForTask(task)) return false;
|
||||
return Boolean(primaryActionItem(task) || secondaryActionItem(task));
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理记录只读卡:仅保留 view_details 文字链(无主 CTA / 取消 / 重解析)。
|
||||
*/
|
||||
function recordViewDetailsItem(task: ConversationProcessingUserTask): ActionPresentationItem | null {
|
||||
const presentation = taskActionPresentation(task);
|
||||
const candidates = [
|
||||
presentation.primary,
|
||||
presentation.secondary,
|
||||
...presentation.overflow,
|
||||
].filter((item): item is ActionPresentationItem => Boolean(item));
|
||||
return candidates.find(
|
||||
(item) => String(item.actionCode || '').trim().toLowerCase() === 'view_details',
|
||||
) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 动作按钮文案:优先 presentation labelKey;多 PDF 取消明确为「取消整个任务」。
|
||||
*/
|
||||
function presentationActionLabel(task: ConversationProcessingUserTask, item: ActionPresentationItem): string {
|
||||
const code = String(item.actionCode || '').trim();
|
||||
if (
|
||||
(code === 'cancel_task' || code === 'cancel_run')
|
||||
&& isMultiDocumentTask(task)
|
||||
) {
|
||||
return t('chat.shippingProcessing.cancelEntireTask');
|
||||
}
|
||||
if (code === 'cancel_task' || code === 'cancel_run') {
|
||||
return t('chat.shippingProcessing.cancelEntireTaskSingle');
|
||||
}
|
||||
const key = String(item.labelKey || '').trim();
|
||||
if (key && te(key)) return t(key);
|
||||
const extractionKey = `chat.shippingOrderExtractionAction.${code}`;
|
||||
if (te(extractionKey)) return t(extractionKey);
|
||||
const aliases: Record<string, string> = {
|
||||
open_review: 'chat.shippingOrderExtractionAction.enter_manual_review',
|
||||
retry_failed_documents: 'chat.shippingOrderExtractionAction.retry_failed_attachments',
|
||||
};
|
||||
const alias = aliases[code];
|
||||
if (alias && te(alias)) return t(alias);
|
||||
return code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行任务级动作:view_details 展开文件;其余交给父级。
|
||||
* 执行任务级动作:view_details / focus_task 本地聚焦;其余交给父级。
|
||||
* 非权威任务号禁止向后端 focus/viewed 写接口。
|
||||
*/
|
||||
function onTaskAction(task: ConversationProcessingUserTask, action: string) {
|
||||
const code = String(action || '').trim();
|
||||
if (!code) return;
|
||||
if (code === 'view_details') {
|
||||
focusTaskManually(uiState, task.user_task_no, { expandDetails: true });
|
||||
markTaskViewed(uiState, task.user_task_no);
|
||||
emit('expandFiles', task);
|
||||
if (code === 'view_details' || code === 'focus_task') {
|
||||
focusTaskManually(uiState, task.user_task_no, { expandDetails: code === 'view_details' });
|
||||
if (code === 'view_details') {
|
||||
markTaskViewed(uiState, task.user_task_no);
|
||||
emit('expandFiles', task);
|
||||
}
|
||||
if (task.user_task_authoritative !== false) {
|
||||
emit('focus', task.user_task_no);
|
||||
emit('viewed', task.user_task_no);
|
||||
if (code === 'view_details') emit('viewed', task.user_task_no);
|
||||
}
|
||||
return;
|
||||
}
|
||||
emit('taskAction', { task, action: code });
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换处理记录整组折叠。
|
||||
*/
|
||||
function toggleHistorySection() {
|
||||
historySectionExpanded.value = !historySectionExpanded.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Intake 材料标题:文件名 / 邮件主题 / Intake 编号。
|
||||
*/
|
||||
@@ -516,14 +570,13 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
<span v-if="activityLabel(task)">{{ activityLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="documentNamesPreview(task)"
|
||||
v-if="primaryFileLabel(task)"
|
||||
class="mt-0.5 truncate text-[11px] text-muted"
|
||||
data-testid="shipping-processing-task-document-names"
|
||||
data-testid="shipping-processing-task-primary-file"
|
||||
>
|
||||
{{ documentNamesPreview(task) }}
|
||||
{{ primaryFileLabel(task) }}
|
||||
</div>
|
||||
<div
|
||||
v-if="task.recent_append_count"
|
||||
@@ -546,25 +599,47 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
@action="(item) => emit('projectionAction', { projection: projectionForTask(task)!, item })"
|
||||
/>
|
||||
<div
|
||||
v-if="visibleTaskActions(task).length && !projectionForTask(task)"
|
||||
class="mt-1.5 flex flex-wrap gap-1.5"
|
||||
v-if="shouldShowTaskLevelActions(task) || (!projectionForTask(task) && canExpandFileDetails(task))"
|
||||
class="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1"
|
||||
data-testid="shipping-processing-task-actions"
|
||||
>
|
||||
<button
|
||||
v-for="action in visibleTaskActions(task)"
|
||||
:key="`${task.user_task_no}-${action}`"
|
||||
v-if="!projectionForTask(task) && primaryActionItem(task)"
|
||||
type="button"
|
||||
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
|
||||
:data-testid="`shipping-processing-action-${action}`"
|
||||
@click="onTaskAction(task, action)"
|
||||
class="rounded-md border border-brand-300 bg-brand-600 px-2.5 py-1 text-[11px] font-medium text-white hover:bg-brand-700 dark:border-brand-700 dark:bg-brand-700 dark:hover:bg-brand-600"
|
||||
:data-testid="`shipping-processing-action-${primaryActionItem(task)!.actionCode}`"
|
||||
@click="onTaskAction(task, primaryActionItem(task)!.actionCode)"
|
||||
>
|
||||
{{ actionLabel(task, action) }}
|
||||
{{ presentationActionLabel(task, primaryActionItem(task)!) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canExpandFileDetails(task)"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
|
||||
data-testid="shipping-processing-expand-files"
|
||||
@click="onToggleDetails(task)"
|
||||
>
|
||||
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
|
||||
<ChevronRight v-else class="h-3 w-3" />
|
||||
{{ isDetailsExpanded(task)
|
||||
? t('chat.shippingProcessing.collapseFileDetails')
|
||||
: t('chat.shippingProcessing.expandFileDetails') }}
|
||||
</button>
|
||||
<button
|
||||
v-else-if="secondaryActionItem(task)"
|
||||
type="button"
|
||||
class="text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
|
||||
:data-testid="`shipping-processing-action-${secondaryActionItem(task)!.actionCode}`"
|
||||
@click="onTaskAction(task, secondaryActionItem(task)!.actionCode)"
|
||||
>
|
||||
{{ presentationActionLabel(task, secondaryActionItem(task)!) }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-if="canExpandFileDetails(task)"
|
||||
v-else-if="canExpandFileDetails(task)"
|
||||
type="button"
|
||||
class="mt-1.5 flex items-center gap-1 text-[11px] text-secondary hover:text-primary"
|
||||
class="mt-1.5 inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
|
||||
data-testid="shipping-processing-expand-files"
|
||||
@click="onToggleDetails(task)"
|
||||
>
|
||||
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
|
||||
@@ -573,6 +648,22 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
? t('chat.shippingProcessing.collapseFileDetails')
|
||||
: t('chat.shippingProcessing.expandFileDetails') }}
|
||||
</button>
|
||||
<div
|
||||
v-if="shouldShowOverflowActions(task)"
|
||||
class="mt-1.5 flex flex-wrap gap-x-3 gap-y-1"
|
||||
data-testid="shipping-processing-task-overflow-actions"
|
||||
>
|
||||
<button
|
||||
v-for="item in overflowActionItems(task)"
|
||||
:key="`${task.user_task_no}-overflow-${item.actionCode}`"
|
||||
type="button"
|
||||
class="text-[11px] text-muted underline-offset-2 hover:text-secondary hover:underline"
|
||||
:data-testid="`shipping-processing-action-${item.actionCode}`"
|
||||
@click="onTaskAction(task, item.actionCode)"
|
||||
>
|
||||
{{ presentationActionLabel(task, item) }}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
@@ -606,14 +697,13 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
<span v-if="activityLabel(task)">{{ activityLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="documentNamesPreview(task)"
|
||||
v-if="primaryFileLabel(task)"
|
||||
class="mt-0.5 truncate text-[11px] text-muted"
|
||||
data-testid="shipping-processing-task-document-names"
|
||||
data-testid="shipping-processing-task-primary-file"
|
||||
>
|
||||
{{ documentNamesPreview(task) }}
|
||||
{{ primaryFileLabel(task) }}
|
||||
</div>
|
||||
<div
|
||||
v-if="task.recent_append_count"
|
||||
@@ -636,25 +726,47 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
@action="(item) => emit('projectionAction', { projection: projectionForTask(task)!, item })"
|
||||
/>
|
||||
<div
|
||||
v-if="visibleTaskActions(task).length && !projectionForTask(task)"
|
||||
class="mt-1.5 flex flex-wrap gap-1.5"
|
||||
v-if="shouldShowTaskLevelActions(task) || (!projectionForTask(task) && canExpandFileDetails(task))"
|
||||
class="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1"
|
||||
data-testid="shipping-processing-task-actions"
|
||||
>
|
||||
<button
|
||||
v-for="action in visibleTaskActions(task)"
|
||||
:key="`${task.user_task_no}-${action}`"
|
||||
v-if="!projectionForTask(task) && primaryActionItem(task)"
|
||||
type="button"
|
||||
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
|
||||
:data-testid="`shipping-processing-action-${action}`"
|
||||
@click="onTaskAction(task, action)"
|
||||
class="rounded-md border border-brand-300 bg-brand-600 px-2.5 py-1 text-[11px] font-medium text-white hover:bg-brand-700 dark:border-brand-700 dark:bg-brand-700 dark:hover:bg-brand-600"
|
||||
:data-testid="`shipping-processing-action-${primaryActionItem(task)!.actionCode}`"
|
||||
@click="onTaskAction(task, primaryActionItem(task)!.actionCode)"
|
||||
>
|
||||
{{ actionLabel(task, action) }}
|
||||
{{ presentationActionLabel(task, primaryActionItem(task)!) }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canExpandFileDetails(task)"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
|
||||
data-testid="shipping-processing-expand-files"
|
||||
@click="onToggleDetails(task)"
|
||||
>
|
||||
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
|
||||
<ChevronRight v-else class="h-3 w-3" />
|
||||
{{ isDetailsExpanded(task)
|
||||
? t('chat.shippingProcessing.collapseFileDetails')
|
||||
: t('chat.shippingProcessing.expandFileDetails') }}
|
||||
</button>
|
||||
<button
|
||||
v-else-if="secondaryActionItem(task)"
|
||||
type="button"
|
||||
class="text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
|
||||
:data-testid="`shipping-processing-action-${secondaryActionItem(task)!.actionCode}`"
|
||||
@click="onTaskAction(task, secondaryActionItem(task)!.actionCode)"
|
||||
>
|
||||
{{ presentationActionLabel(task, secondaryActionItem(task)!) }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-if="canExpandFileDetails(task)"
|
||||
v-else-if="canExpandFileDetails(task)"
|
||||
type="button"
|
||||
class="mt-1.5 flex items-center gap-1 text-[11px] text-secondary hover:text-primary"
|
||||
class="mt-1.5 inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
|
||||
data-testid="shipping-processing-expand-files"
|
||||
@click="onToggleDetails(task)"
|
||||
>
|
||||
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
|
||||
@@ -663,85 +775,197 @@ function onIntakeAction(item: ShippingProcessingProjection, action: string) {
|
||||
? t('chat.shippingProcessing.collapseFileDetails')
|
||||
: t('chat.shippingProcessing.expandFileDetails') }}
|
||||
</button>
|
||||
<div
|
||||
v-if="shouldShowOverflowActions(task)"
|
||||
class="mt-1.5 flex flex-wrap gap-x-3 gap-y-1"
|
||||
data-testid="shipping-processing-task-overflow-actions"
|
||||
>
|
||||
<button
|
||||
v-for="item in overflowActionItems(task)"
|
||||
:key="`${task.user_task_no}-overflow-${item.actionCode}`"
|
||||
type="button"
|
||||
class="text-[11px] text-muted underline-offset-2 hover:text-secondary hover:underline"
|
||||
:data-testid="`shipping-processing-action-${item.actionCode}`"
|
||||
@click="onTaskAction(task, item.actionCode)"
|
||||
>
|
||||
{{ presentationActionLabel(task, item) }}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-if="completedTasks.length"
|
||||
data-testid="shipping-processing-group-completed"
|
||||
v-if="recordTaskCount > 0"
|
||||
data-testid="shipping-processing-group-history"
|
||||
>
|
||||
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-emerald-700 dark:text-emerald-300">
|
||||
{{ resolveShippingProcessingMessage('groupCompleted', te, t, { count: completedTasks.length }) }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in completedTasks"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border border-default bg-surface px-2.5 py-2"
|
||||
:class="focusedTaskNo === task.user_task_no
|
||||
? 'ring-1 ring-brand-400'
|
||||
: ''"
|
||||
:data-testid="`shipping-processing-task-${task.user_task_no}`"
|
||||
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
|
||||
<button
|
||||
type="button"
|
||||
class="mb-1.5 flex w-full items-center justify-between gap-2 text-left text-[11px] font-semibold uppercase tracking-wide text-slate-600 dark:text-slate-300"
|
||||
data-testid="shipping-processing-history-toggle"
|
||||
@click="toggleHistorySection"
|
||||
>
|
||||
<span class="inline-flex min-w-0 items-center gap-1">
|
||||
<ChevronDown v-if="historySectionExpanded" class="h-3 w-3 shrink-0" />
|
||||
<ChevronRight v-else class="h-3 w-3 shrink-0" />
|
||||
<span>{{ resolveShippingProcessingMessage('groupProcessingRecords', te, t, { count: recordTaskCount }) }}</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="hiddenHistoryCount > 0"
|
||||
class="shrink-0 font-medium normal-case tracking-normal text-muted"
|
||||
data-testid="shipping-processing-history-more"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="w-full text-left"
|
||||
@click="onSelectTask(task)"
|
||||
>
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
<span v-if="activityLabel(task)">{{ activityLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="documentNamesPreview(task)"
|
||||
class="mt-0.5 truncate text-[11px] text-muted"
|
||||
data-testid="shipping-processing-task-document-names"
|
||||
>
|
||||
{{ documentNamesPreview(task) }}
|
||||
</div>
|
||||
</button>
|
||||
<SidebarProgressInline
|
||||
v-if="progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
|
||||
class="mt-1.5 border-t border-current/10 pt-1.5"
|
||||
:projection="projectionForTask(task)!"
|
||||
:compact="progressModeForTask(task) === 'compact'"
|
||||
@action="(item) => emit('projectionAction', { projection: projectionForTask(task)!, item })"
|
||||
/>
|
||||
<div
|
||||
v-if="visibleTaskActions(task).length && !projectionForTask(task)"
|
||||
class="mt-1.5 flex flex-wrap gap-1.5"
|
||||
data-testid="shipping-processing-task-actions"
|
||||
>
|
||||
<button
|
||||
v-for="action in visibleTaskActions(task)"
|
||||
:key="`${task.user_task_no}-${action}`"
|
||||
type="button"
|
||||
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
|
||||
:data-testid="`shipping-processing-action-${action}`"
|
||||
@click="onTaskAction(task, action)"
|
||||
>
|
||||
{{ actionLabel(task, action) }}
|
||||
</button>
|
||||
{{ t('chat.shippingProcessing.historyMoreCount', { count: hiddenHistoryCount }) }}
|
||||
</span>
|
||||
</button>
|
||||
<div
|
||||
v-if="historySectionExpanded"
|
||||
class="space-y-3"
|
||||
data-testid="shipping-processing-history-body"
|
||||
>
|
||||
<div
|
||||
v-if="completedTasks.length"
|
||||
data-testid="shipping-processing-history-completed"
|
||||
>
|
||||
<div class="mb-1 text-[11px] font-medium text-emerald-700 dark:text-emerald-300">
|
||||
{{ resolveShippingProcessingMessage('groupRecordCompleted', te, t) }}
|
||||
</div>
|
||||
<button
|
||||
v-if="canExpandFileDetails(task)"
|
||||
type="button"
|
||||
class="mt-1.5 flex items-center gap-1 text-[11px] text-secondary hover:text-primary"
|
||||
@click="onToggleDetails(task)"
|
||||
>
|
||||
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
|
||||
<ChevronRight v-else class="h-3 w-3" />
|
||||
{{ isDetailsExpanded(task)
|
||||
? t('chat.shippingProcessing.collapseFileDetails')
|
||||
: t('chat.shippingProcessing.expandFileDetails') }}
|
||||
</button>
|
||||
</article>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in completedTasks"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border border-default bg-surface/80 px-2.5 py-2"
|
||||
:data-testid="`shipping-processing-task-${task.user_task_no}`"
|
||||
data-record="1"
|
||||
>
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="primaryFileLabel(task)"
|
||||
class="mt-0.5 truncate text-[11px] text-muted"
|
||||
data-testid="shipping-processing-task-primary-file"
|
||||
>
|
||||
{{ primaryFileLabel(task) }}
|
||||
</div>
|
||||
<button
|
||||
v-if="recordViewDetailsItem(task)"
|
||||
type="button"
|
||||
class="mt-1.5 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
|
||||
:data-testid="`shipping-processing-action-${recordViewDetailsItem(task)!.actionCode}`"
|
||||
@click="onTaskAction(task, recordViewDetailsItem(task)!.actionCode)"
|
||||
>
|
||||
{{ presentationActionLabel(task, recordViewDetailsItem(task)!) }}
|
||||
</button>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="historyVersionTasks.length"
|
||||
data-testid="shipping-processing-history-versions"
|
||||
>
|
||||
<div class="mb-1 text-[11px] font-medium text-slate-600 dark:text-slate-300">
|
||||
{{ resolveShippingProcessingMessage('groupRecordHistoryVersions', te, t) }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in historyVersionTasks"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border border-default bg-surface/80 px-2.5 py-2"
|
||||
:data-testid="`shipping-processing-task-${task.user_task_no}`"
|
||||
data-record="1"
|
||||
>
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="primaryFileLabel(task)"
|
||||
class="mt-0.5 truncate text-[11px] text-muted"
|
||||
data-testid="shipping-processing-task-primary-file"
|
||||
>
|
||||
{{ primaryFileLabel(task) }}
|
||||
</div>
|
||||
<button
|
||||
v-if="recordViewDetailsItem(task)"
|
||||
type="button"
|
||||
class="mt-1.5 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
|
||||
:data-testid="`shipping-processing-action-${recordViewDetailsItem(task)!.actionCode}`"
|
||||
@click="onTaskAction(task, recordViewDetailsItem(task)!.actionCode)"
|
||||
>
|
||||
{{ presentationActionLabel(task, recordViewDetailsItem(task)!) }}
|
||||
</button>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="cancelledHistoryTasks.length"
|
||||
data-testid="shipping-processing-history-cancelled"
|
||||
>
|
||||
<div class="mb-1 text-[11px] font-medium text-slate-500 dark:text-slate-400">
|
||||
{{ resolveShippingProcessingMessage('groupRecordCancelled', te, t) }}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<article
|
||||
v-for="task in cancelledHistoryTasks"
|
||||
:key="task.user_task_no"
|
||||
class="rounded-lg border border-dashed border-default bg-surface/60 px-2.5 py-2 opacity-90"
|
||||
:data-testid="`shipping-processing-task-${task.user_task_no}`"
|
||||
data-record="1"
|
||||
>
|
||||
<div class="text-sm font-semibold text-primary">
|
||||
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
|
||||
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
|
||||
<span>{{ statusLabel(task) }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="primaryFileLabel(task)"
|
||||
class="mt-0.5 truncate text-[11px] text-muted"
|
||||
data-testid="shipping-processing-task-primary-file"
|
||||
>
|
||||
{{ primaryFileLabel(task) }}
|
||||
</div>
|
||||
<button
|
||||
v-if="recordViewDetailsItem(task)"
|
||||
type="button"
|
||||
class="mt-1.5 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
|
||||
:data-testid="`shipping-processing-action-${recordViewDetailsItem(task)!.actionCode}`"
|
||||
@click="onTaskAction(task, recordViewDetailsItem(task)!.actionCode)"
|
||||
>
|
||||
{{ presentationActionLabel(task, recordViewDetailsItem(task)!) }}
|
||||
</button>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="hiddenHistoryCount > 0"
|
||||
class="text-[11px] text-muted"
|
||||
data-testid="shipping-processing-history-truncated"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.historyTruncatedDetail', {
|
||||
shown: historyTasks.length,
|
||||
hidden: hiddenHistoryCount,
|
||||
}) }}
|
||||
</div>
|
||||
<div
|
||||
v-else-if="hasMoreHistory"
|
||||
class="text-[11px] text-muted"
|
||||
data-testid="shipping-processing-history-truncated"
|
||||
>
|
||||
{{ t('chat.shippingProcessing.summaryTruncatedHint') }}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
+104
-146
@@ -1,18 +1,15 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.spec.ts
|
||||
* 用途:覆盖批次进度卡摘要、阶段、健康提醒与刷新/取消/重试动作。
|
||||
* 用途:覆盖对话区订单识别摘要卡——标题、状态行、handling 一行摘要、唯一主 CTA、查看详情。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、本域组件与 DTO 类型。
|
||||
* 逻辑:断言过程通知、摘要计数、取消确认与重试;逐 PDF 深链仍由右侧面板承担。
|
||||
* 逻辑:断言不再渲染进度列表/刷新取消/完整 handling 卡片;失败重试与需处理继续处理互斥。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { ref } from 'vue';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ShippingOrderExtractionCard from './ShippingOrderExtractionCard.vue';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
import type { ShippingProcessingProjection } from '../../types/shipping.api.types';
|
||||
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
@@ -43,7 +40,7 @@ const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): Shipping
|
||||
userVisibleStage: 'extracting',
|
||||
elapsedSeconds: 75,
|
||||
},
|
||||
availableActions: ['refresh_status', 'cancel_run'],
|
||||
availableActions: ['refresh_status', 'cancel_run', 'view_details'],
|
||||
healthTips: [{ code: 'processing_slow', thresholdSeconds: 60, idleOrElapsedSeconds: 90 }],
|
||||
terminal: false,
|
||||
refreshFailed: false,
|
||||
@@ -54,17 +51,23 @@ const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): Shipping
|
||||
});
|
||||
|
||||
describe('ShippingOrderExtractionCard', () => {
|
||||
it('renders batch summary, current stage, health tip and action buttons', () => {
|
||||
// 冷启动 transform 较慢时放宽超时,避免首测误伤。
|
||||
it('renders summary title, file count, system processing and no progress/refresh/cancel', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-1' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).toContain('PO-450003.pdf');
|
||||
expect(wrapper.text()).toContain('提取订单字段中');
|
||||
// 关键断言:对话卡只保留摘要标题与系统处理中状态。
|
||||
expect(wrapper.text()).toContain('订单识别任务');
|
||||
expect(wrapper.text()).toContain('3 个文件');
|
||||
expect(wrapper.text()).toContain('系统处理中');
|
||||
expect(wrapper.text()).toContain('处理时间偏长');
|
||||
expect(wrapper.text()).toContain('刷新状态');
|
||||
expect(wrapper.text()).toContain('取消本次识别');
|
||||
expect(wrapper.text()).toContain('查看详情');
|
||||
expect(wrapper.text()).not.toContain('刷新状态');
|
||||
expect(wrapper.text()).not.toContain('取消本次识别');
|
||||
expect(wrapper.text()).not.toContain('PO-450003.pdf');
|
||||
expect(wrapper.text()).not.toContain('提取订单字段中');
|
||||
expect(wrapper.findAll('[data-testid="chat-progress-summary-list"]').length).toBe(0);
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-summary"]').length).toBe(0);
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-document-result"]').length).toBe(0);
|
||||
}, 30_000);
|
||||
|
||||
@@ -91,12 +94,12 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).toContain('发现重复文件');
|
||||
expect(wrapper.text()).toContain('订单识别任务');
|
||||
expect(wrapper.text()).toContain('已关联已有任务');
|
||||
expect(wrapper.text()).not.toContain('需人工处理');
|
||||
});
|
||||
|
||||
it('does not label generated candidates as manual-review exceptions', () => {
|
||||
it('renders candidate confirmation as status notice with continue CTA', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -129,13 +132,14 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
stubs: { 'router-link': true },
|
||||
},
|
||||
});
|
||||
// 关键断言:成功候选可待人工确认,但绝不能提示为识别异常。
|
||||
expect(wrapper.text()).toContain('订单候选已生成');
|
||||
expect(wrapper.text()).toContain('候选待人工确认');
|
||||
expect(wrapper.text()).toContain('候选待人工确认 · 2 项');
|
||||
expect(wrapper.text()).toContain('继续处理');
|
||||
expect(wrapper.text()).not.toContain('部分附件需人工处理');
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(0);
|
||||
});
|
||||
|
||||
it('renders mixed handling items with reasons instead of a vague needs-action notice', () => {
|
||||
it('renders one handling summary line without per-item actions or affected refs', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -183,17 +187,51 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).toContain('部分附件处理失败');
|
||||
expect(wrapper.text()).toContain('订单待补信息');
|
||||
expect(wrapper.text()).toContain('自动冻结受阻');
|
||||
expect(wrapper.text()).toContain('文件损坏、加密或无法读取');
|
||||
expect(wrapper.text()).toContain('影响对象:');
|
||||
expect(wrapper.text()).toContain('ST-88');
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(3);
|
||||
// 无统一投影时仍允许 handlingItems 主按钮(过渡兜底)。
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-primary-action"]').length).toBeGreaterThan(0);
|
||||
expect(wrapper.text()).toContain('附件处理失败 · 3 项');
|
||||
expect(wrapper.text()).not.toContain('订单待补信息');
|
||||
expect(wrapper.text()).not.toContain('影响对象:');
|
||||
expect(wrapper.text()).not.toContain('ST-88');
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(0);
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-primary-action"]').length).toBe(0);
|
||||
// 失败优先:唯一主 CTA 为重试解析。
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').text()).toContain('重试解析');
|
||||
});
|
||||
|
||||
it('hides handling primary actions when unified processing projection is present (UI-01)', () => {
|
||||
it('shows continue CTA for review-required without retry', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
status: 'review_required',
|
||||
availableActions: ['enter_manual_review', 'view_details'],
|
||||
primaryNotice: 'candidate_confirmation',
|
||||
handlingItems: [{
|
||||
category: 'candidate_confirmation',
|
||||
count: 1,
|
||||
reasonCodes: [],
|
||||
affectedRefs: [],
|
||||
primaryAction: 'review_candidate',
|
||||
}],
|
||||
healthTips: [],
|
||||
currentActivity: null,
|
||||
summary: {
|
||||
totalDocuments: 1,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 1,
|
||||
reviewRequiredDocuments: 1,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 1,
|
||||
},
|
||||
}),
|
||||
runNo: 'SNER-REVIEW',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').text()).toContain('继续处理');
|
||||
expect(wrapper.text()).not.toContain('重试解析');
|
||||
});
|
||||
|
||||
it('does not render multi-OT ChatProgressSummary list', () => {
|
||||
const projection = {
|
||||
workItemType: 'order_task' as const,
|
||||
workItemNo: 'OT-UI01',
|
||||
@@ -228,134 +266,36 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
userTaskNo: 'OT-UI01',
|
||||
availableActions: ['review_candidate', 'view_details'],
|
||||
primaryNotice: 'candidate_confirmation',
|
||||
handlingItems: [
|
||||
{
|
||||
category: 'candidate_confirmation',
|
||||
count: 1,
|
||||
reasonCodes: [],
|
||||
affectedRefs: [],
|
||||
primaryAction: 'review_candidate',
|
||||
},
|
||||
{
|
||||
category: 'parse_failed',
|
||||
count: 1,
|
||||
reasonCodes: ['layout_failed'],
|
||||
affectedRefs: [],
|
||||
primaryAction: 'retry_failed_documents',
|
||||
},
|
||||
],
|
||||
handlingItems: [{
|
||||
category: 'candidate_confirmation',
|
||||
count: 1,
|
||||
reasonCodes: [],
|
||||
affectedRefs: [],
|
||||
primaryAction: 'review_candidate',
|
||||
}],
|
||||
healthTips: [],
|
||||
currentActivity: null,
|
||||
summary: {
|
||||
totalDocuments: 1,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 1,
|
||||
reviewRequiredDocuments: 1,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 1,
|
||||
},
|
||||
}),
|
||||
runNo: 'SNER-UI01',
|
||||
processingProjection: projection,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
ChatProgressSummary: true,
|
||||
ProcessGateRecoveryCard: true,
|
||||
'router-link': true,
|
||||
},
|
||||
},
|
||||
});
|
||||
// 主操作只来自投影 Presenter;已被 Gate/进度表达的 handling 项不重复列出。
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-primary-action"]').length).toBe(0);
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(1);
|
||||
});
|
||||
|
||||
it('renders one unified progress summary for each PDF under the same root task', () => {
|
||||
const buildWorkItem = (
|
||||
taskNo: string,
|
||||
filename: string,
|
||||
documentId: number,
|
||||
): ShippingProcessingProjection => ({
|
||||
workItemType: 'order_task',
|
||||
workItemNo: taskNo,
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'OT-ROOT',
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SUB-1',
|
||||
intakeNo: 'INT-1',
|
||||
status: 'processing',
|
||||
stage: 'document_parsing',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-06T00:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: ['view_details'],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename,
|
||||
documentId,
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 1,
|
||||
customerName: null,
|
||||
poNumber: null,
|
||||
},
|
||||
childOrderTasks: [],
|
||||
});
|
||||
const workItems = [
|
||||
buildWorkItem('OT-ROOT', 'PO-001.pdf', 1),
|
||||
buildWorkItem('OT-CHILD', 'PO-002.pdf', 2),
|
||||
];
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({ userTaskNo: 'OT-ROOT' }),
|
||||
runNo: 'SNER-MULTI-PDF',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
provide: {
|
||||
[SHIPPING_WORKFLOW_KEY as symbol]: {
|
||||
processing: ref(null),
|
||||
processingWorkItems: ref(workItems),
|
||||
loading: ref(false),
|
||||
error: ref(null),
|
||||
refresh: async () => undefined,
|
||||
focusConversationTask: async () => undefined,
|
||||
markConversationTaskViewed: async () => undefined,
|
||||
stop: () => undefined,
|
||||
},
|
||||
},
|
||||
stubs: {
|
||||
ChatProgressSummary: {
|
||||
props: ['projection'],
|
||||
template: '<div data-testid="chat-progress-summary">{{ projection.workItemNo }}</div>',
|
||||
},
|
||||
ProcessGateRecoveryCard: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.findAll('[data-testid="chat-progress-summary"]')).toHaveLength(2);
|
||||
expect(wrapper.text()).toContain('PO-001.pdf');
|
||||
expect(wrapper.text()).toContain('PO-002.pdf');
|
||||
});
|
||||
|
||||
it('emits cancel after confirmation', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
availableActions: ['cancel_run', 'refresh_status'],
|
||||
}),
|
||||
runNo: 'SNER-1',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const cancelBtn = wrapper.findAll('button').find((b) => b.text().includes('取消本次识别'));
|
||||
expect(cancelBtn).toBeTruthy();
|
||||
await cancelBtn!.trigger('click');
|
||||
expect(wrapper.text()).toContain('确认取消本次识别');
|
||||
const textarea = wrapper.find('textarea');
|
||||
await textarea.setValue('不再需要识别');
|
||||
const confirmBtn = wrapper.findAll('button').find((b) => b.text() === '取消本次识别');
|
||||
await confirmBtn!.trigger('click');
|
||||
expect(wrapper.emitted('cancel')?.[0]).toEqual(['不再需要识别']);
|
||||
expect(wrapper.findAll('[data-testid="chat-progress-summary-list"]').length).toBe(0);
|
||||
expect(wrapper.text()).not.toContain('PO.pdf');
|
||||
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').text()).toContain('继续处理');
|
||||
});
|
||||
|
||||
it('emits retry for failed attachments', async () => {
|
||||
it('emits retry for failed attachments via primary CTA', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
@@ -375,8 +315,26 @@ describe('ShippingOrderExtractionCard', () => {
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const retryBtn = wrapper.findAll('button').find((b) => b.text().includes('重试失败附件'));
|
||||
await retryBtn!.trigger('click');
|
||||
const retryBtn = wrapper.find('[data-testid="shipping-order-extraction-primary-action"]');
|
||||
expect(retryBtn.text()).toContain('重试解析');
|
||||
await retryBtn.trigger('click');
|
||||
expect(wrapper.emitted('retry')?.length).toBe(1);
|
||||
});
|
||||
|
||||
it('keeps view details as secondary text link only', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
availableActions: ['view_details'],
|
||||
healthTips: [],
|
||||
}),
|
||||
runNo: 'SNER-1',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
const details = wrapper.find('[data-testid="shipping-order-extraction-view-details"]');
|
||||
expect(details.exists()).toBe(true);
|
||||
expect(details.classes().join(' ')).toContain('underline-offset-2');
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-extraction-primary-action"]').length).toBe(0);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user