Files
syops/backend/app/services/shipping_notice/attachment_integrity.py
T

83 lines
2.8 KiB
Python

"""
services/shipping_notice/attachment_integrity.py
用途:判定 Intake 的 EML/附件解析是否完整,供建批门禁与重试资格复用。
依赖:仅标准库(与 structured_result_json / parse_summary 形状对齐)。
逻辑:由 batch_from_intakes、intake_service.retry_intake_parse 调用;
BLOCKING_WARNING_PREFIXES 与前端 shippingNoticeAttachmentIntegrity.ts 契约一致
(由 tests 校验两端前缀集合)。
"""
from __future__ import annotations
from typing import Any
# 顶层 / 附件行 warnings 前缀:出现任一即视为不完整(与前端门禁契约对齐)
BLOCKING_WARNING_PREFIXES: tuple[str, ...] = (
'eml_nesting_depth_exceeded:',
'eml_attachment_limit_exceeded:',
'eml_total_attachment_size_exceeded:',
'eml_nested_message_unreadable',
'eml_attachment_text_budget_exhausted:',
'eml_attachment_text_truncated:',
'notice_text_truncated:',
)
_INCOMPLETE_ATTACHMENT_STATUSES = frozenset({'failed', 'empty', 'skipped'})
def is_blocking_warning(text: str) -> bool:
"""
判定单条 warning 是否为完整性阻断项。
Args:
text: warning 原文。
Returns:
True 表示该警告会使 Intake 被视为附件解析不完整。
"""
normalized = str(text or '')
return any(normalized.startswith(prefix) for prefix in BLOCKING_WARNING_PREFIXES)
def is_attachment_parse_incomplete(structured: dict[str, Any] | None) -> bool:
"""
判定 structured_result_json / parse_summary 是否存在未完整解析的附件。
核心逻辑:阻断警告(深度/数量/总大小/不可读嵌套/文本预算或截断)、
attachment_count > 已登记数、或任一行 parse_status 为 failed/empty/skipped
均视为不完整;duplicate 仅去重提示,不阻断。
Args:
structured: Intake 的 structured_result_json 或 API 下发的 parse_summary。
Returns:
True 表示不可用该 Intake 直接建批,应拒绝或允许重试解析。
"""
if not isinstance(structured, dict):
return False
warnings = structured.get('warnings') or []
for item in warnings:
if is_blocking_warning(str(item or '')):
return True
rows = structured.get('attachments') or []
if not isinstance(rows, list):
rows = []
total = int(structured.get('attachment_count') or 0)
if total > len(rows):
return True
for row in rows:
if not isinstance(row, dict):
continue
status = str(row.get('parse_status') or '').strip().lower()
if status in _INCOMPLETE_ATTACHMENT_STATUSES:
return True
for item in row.get('warnings') or []:
if is_blocking_warning(str(item or '')):
return True
return False