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
@@ -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,
|
||||
}
|
||||
Reference in new issue
Block a user