- 在环境配置中新增 SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 选项,默认关闭,需显式开启以支持自动上传。 - 引入新的 pytest.ini 文件,增加测试标记以支持自动化测试。 - 删除不再使用的 seed_shipping_notice_agents.py 文件,简化代码库。 - 更新相关 API,增强发货通知与候选资格评估功能,支持多种筛选条件。 - 增强文档与代码注释,反映新的业务逻辑与功能要求。
190 lines
6.4 KiB
Python
190 lines
6.4 KiB
Python
"""
|
||
services/shipping_notice/attachment_integrity.py
|
||
|
||
用途:判定 Intake 的 EML/附件解析是否完整,供建批门禁与重试资格复用。
|
||
依赖:error_explainability_contract(warning→稳定原因码)、标准库。
|
||
逻辑:由 batch_from_intakes、intake_service.retry_intake_parse 调用;
|
||
BLOCKING_WARNING_PREFIXES 与前端 shippingNoticeAttachmentIntegrity.ts 契约一致
|
||
(由 tests 校验两端前缀集合);可投影 attachment_reason_codes 供审计/UI。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from typing import Any
|
||
|
||
from app.services.shipping_notice.error_explainability_contract import (
|
||
build_explainability_reason,
|
||
map_attachment_warning_to_reason_code,
|
||
primary_attachment_reason_from_warnings,
|
||
)
|
||
|
||
# 顶层 / 附件行 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
|
||
|
||
preview_status = str(structured.get('preview_status') or '').strip().lower()
|
||
if preview_status == 'directory_incomplete':
|
||
return True
|
||
if structured.get('attachment_directory_complete') is False:
|
||
return True
|
||
|
||
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
|
||
|
||
|
||
def collect_attachment_reason_codes(structured: dict[str, Any] | None) -> list[str]:
|
||
"""
|
||
从 structured_result / parse_summary 收集已映射的附件稳定原因码(去重保序)。
|
||
|
||
Args:
|
||
structured: Intake structured_result_json 或 parse_summary。
|
||
|
||
Returns:
|
||
稳定原因码列表;无映射时为空。
|
||
"""
|
||
if not isinstance(structured, dict):
|
||
return []
|
||
codes: list[str] = []
|
||
seen: set[str] = set()
|
||
|
||
def _push(warning: str) -> None:
|
||
code = map_attachment_warning_to_reason_code(warning)
|
||
if code and code not in seen:
|
||
seen.add(code)
|
||
codes.append(code)
|
||
|
||
for item in structured.get('warnings') or []:
|
||
_push(str(item or ''))
|
||
for row in structured.get('attachments') or []:
|
||
if not isinstance(row, dict):
|
||
continue
|
||
for item in row.get('warnings') or []:
|
||
_push(str(item or ''))
|
||
return codes
|
||
|
||
|
||
def primary_attachment_reason_code(structured: dict[str, Any] | None) -> str | None:
|
||
"""
|
||
取附件解析的主稳定原因码(首个可映射 warning)。
|
||
|
||
Args:
|
||
structured: Intake structured_result_json 或 parse_summary。
|
||
|
||
Returns:
|
||
稳定原因码或 None。
|
||
"""
|
||
codes = collect_attachment_reason_codes(structured)
|
||
if codes:
|
||
return codes[0]
|
||
if not isinstance(structured, dict):
|
||
return None
|
||
return primary_attachment_reason_from_warnings(list(structured.get('warnings') or []))
|
||
|
||
|
||
def attachment_incomplete_error_details(
|
||
structured: dict[str, Any] | None,
|
||
*,
|
||
intake_nos: list[str] | None = None,
|
||
reason: str | None = None,
|
||
extra: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
构造 INTAKE_ATTACHMENTS_INCOMPLETE 的可解释 details。
|
||
|
||
核心逻辑:从 structured 投影 attachment_reason_codes 与统一 explainability;
|
||
无 warning 映射时回落 attachment_corrupted,保证调用方始终带稳定 reason_code。
|
||
|
||
Args:
|
||
structured: Intake structured_result_json / parse_summary。
|
||
intake_nos: 相关 Intake 编号。
|
||
reason: 调用点细分原因(如 no_eligible_selected_attachment)。
|
||
extra: 额外业务事实(如 missing_attachment_keys)。
|
||
|
||
Returns:
|
||
供 ConflictError.details 使用的字典。
|
||
"""
|
||
codes = collect_attachment_reason_codes(structured)
|
||
primary = primary_attachment_reason_code(structured) or 'attachment_corrupted'
|
||
details: dict[str, Any] = {
|
||
'reason_code': primary,
|
||
'attachment_reason_codes': codes,
|
||
'explainability': build_explainability_reason(
|
||
reason_code=primary,
|
||
details={
|
||
'attachment_reason_codes': codes,
|
||
**({'reason': reason} if reason else {}),
|
||
},
|
||
),
|
||
}
|
||
if intake_nos:
|
||
details['intake_nos'] = [str(item) for item in intake_nos if str(item or '').strip()]
|
||
if reason:
|
||
details['reason'] = str(reason)[:128]
|
||
if isinstance(extra, dict):
|
||
for key, value in extra.items():
|
||
if value is not None and key not in details:
|
||
details[key] = value
|
||
return details
|