Merge branch 'dev' into hugo-shipping-notice
# Conflicts: # backend/app/api/chat.py # backend/app/services/shipping_notice/chat_actions.py
This commit is contained in:
commit
7a9c36d16b
17 files changed
+1014
-357
No files matched your search
@@ -11,6 +11,7 @@ from app.services.shipping_notice.state_machine import (
|
||||
ALL_ACTION_IDS,
|
||||
ALL_CHECKPOINT_IDS,
|
||||
CHECKPOINT_REGISTRY,
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
TaskTransition,
|
||||
TaskUiState,
|
||||
action_buttons_for_checkpoint,
|
||||
@@ -21,6 +22,7 @@ from app.services.shipping_notice.state_machine import (
|
||||
human_options_for_checkpoint,
|
||||
human_options_for_task,
|
||||
human_options_for_task_or_checkpoint,
|
||||
inventory_source_action_buttons,
|
||||
resolve_task_ui_state,
|
||||
ui_state_for_checkpoint,
|
||||
upload_req_options_for_task,
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
services/shipping_notice/notice_upload.py
|
||||
|
||||
用途:管理发货通知附件上传、文本抽取、OCR/文档解析与文件落盘。
|
||||
用途:管理发货通知附件上传、文本抽取、截断与统一接入结果模型。
|
||||
依赖:edkb_system 的 PDF/Docx/CSV/OCR 技能、export._storage_root、Flask current_app 配置。
|
||||
逻辑:由 workspace_shipping_notice 和 task_workflow 上游入口调用本文件,把原始附件转成可解析文本后交给 extract/task_workflow;批量上传的预检临时文件也在这里统一落盘和清理。
|
||||
逻辑:workspace 单票建单、批量建单、重新上传三条入口均经 intake_notice_attachment / intake_temp_notice_uploads
|
||||
收敛抽取与失败分流;下游 extract/task_workflow 只消费 NoticeIntakeResult。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,10 +12,11 @@ from __future__ import annotations
|
||||
import base64
|
||||
import re
|
||||
import shutil
|
||||
from dataclasses import dataclass, field
|
||||
from email import policy
|
||||
from email.parser import BytesParser
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from typing import Any, Literal, Sequence
|
||||
|
||||
from flask import current_app
|
||||
|
||||
@@ -228,3 +230,237 @@ def max_notice_chars() -> int:
|
||||
except Exception:
|
||||
value = 0
|
||||
return value if value > 0 else 200000
|
||||
|
||||
|
||||
EMPTY_TEXT_REJECT_MESSAGE = "notice text is empty after extraction"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NoticeIntakeResult:
|
||||
"""
|
||||
发货通知附件统一接入结果。
|
||||
|
||||
三条工作台入口(单票建单 / 批量建单 / 重新上传)共用本模型,避免抽取、截断与失败分流行为漂移。
|
||||
"""
|
||||
|
||||
filename: str
|
||||
source_type: str
|
||||
source_file_type: str | None
|
||||
text: str
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
meta: dict[str, Any] = field(default_factory=dict)
|
||||
status: Literal["accepted", "empty_text", "extract_failed"] = "empty_text"
|
||||
saved_path: Path | None = None
|
||||
|
||||
@property
|
||||
def accepted(self) -> bool:
|
||||
"""抽取成功且正文非空。"""
|
||||
return self.status == "accepted"
|
||||
|
||||
def to_notice_item(self) -> dict[str, Any]:
|
||||
"""批量建单 notice_items 载荷项。"""
|
||||
return {
|
||||
"source_type": self.source_type,
|
||||
"source_file_name": self.filename,
|
||||
"source_file_type": self.source_file_type,
|
||||
"raw_text": self.text,
|
||||
"warnings": list(self.warnings),
|
||||
}
|
||||
|
||||
def to_accepted_file_summary(self) -> dict[str, Any]:
|
||||
"""批量预检 accepted_files 摘要项。"""
|
||||
return {
|
||||
"filename": self.filename,
|
||||
"source_type": self.source_type,
|
||||
"source_file_type": self.source_file_type,
|
||||
"text_length": len(self.text),
|
||||
"warnings": list(self.warnings),
|
||||
}
|
||||
|
||||
def to_rejected_file_summary(self) -> dict[str, Any]:
|
||||
"""批量预检 rejected_files 摘要项。"""
|
||||
return {
|
||||
"filename": self.filename,
|
||||
"source_type": self.source_type,
|
||||
"source_file_type": self.source_file_type,
|
||||
"reason": "empty_text",
|
||||
"message": EMPTY_TEXT_REJECT_MESSAGE,
|
||||
"warnings": list(self.warnings),
|
||||
}
|
||||
|
||||
def to_notice_upload_meta(self) -> dict[str, Any]:
|
||||
"""API data.notice_upload 响应字段。"""
|
||||
payload = dict(self.meta) if isinstance(self.meta, dict) else {}
|
||||
payload["filename"] = self.filename
|
||||
payload["warnings"] = list(self.warnings)
|
||||
return payload
|
||||
|
||||
|
||||
def notice_source_file_type(upload: Any) -> str | None:
|
||||
"""从 Flask/Werkzeug 上传对象提取 MIME type;为空时返回 None。"""
|
||||
return str(getattr(upload, "mimetype", "") or "").strip() or None
|
||||
|
||||
|
||||
def truncate_notice_text(text: str, warnings: list[str] | None = None) -> tuple[str, list[str]]:
|
||||
"""
|
||||
按配置上限截断发货通知正文,并追加统一 warning 标记。
|
||||
|
||||
Args:
|
||||
text: 抽取后的原始正文。
|
||||
warnings: 已有 warnings,截断时会追加 notice_text_truncated 项。
|
||||
|
||||
Returns:
|
||||
tuple[str, list[str]]: (截断后正文, 更新后的 warnings)。
|
||||
"""
|
||||
ws = list(warnings or [])
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
ws.append(f"notice_text_truncated:{limit}")
|
||||
return text, ws
|
||||
|
||||
|
||||
def intake_notice_attachment(
|
||||
*,
|
||||
filename: str,
|
||||
raw: bytes,
|
||||
source_file_type: str | None = None,
|
||||
storage: Literal["task", "temp"] = "task",
|
||||
task_no: str | None = None,
|
||||
temp_request_id: str | None = None,
|
||||
temp_index: int = 1,
|
||||
) -> NoticeIntakeResult:
|
||||
"""
|
||||
单份发货通知附件的统一接入:落盘 → 抽取 → 截断 → 失败分流。
|
||||
|
||||
核心逻辑:三条工作台入口均调用本函数,保证 empty_text / extract_failed 与 warnings 语义一致。
|
||||
|
||||
Args:
|
||||
filename: 原始文件名。
|
||||
raw: 文件字节流。
|
||||
source_file_type: MIME type,可为空。
|
||||
storage: task 为任务级持久化目录;temp 为批量预检临时目录。
|
||||
task_no: storage=task 时必填。
|
||||
temp_request_id: storage=temp 时必填。
|
||||
temp_index: storage=temp 时文件序号,避免同名覆盖。
|
||||
|
||||
Returns:
|
||||
NoticeIntakeResult: 含 accepted / empty_text / extract_failed 状态与截断后正文。
|
||||
"""
|
||||
name = str(filename or "").strip() or "notice"
|
||||
source_type = guess_source_type(name)
|
||||
saved_path: Path | None = None
|
||||
text = ""
|
||||
meta: dict[str, Any] = {}
|
||||
warnings: list[str] = []
|
||||
status: Literal["accepted", "empty_text", "extract_failed"] = "empty_text"
|
||||
|
||||
try:
|
||||
if storage == "task":
|
||||
if not task_no:
|
||||
raise ValueError("task_no is required for task storage")
|
||||
saved_path = save_task_notice_upload(task_no, name, raw or b"")
|
||||
else:
|
||||
if not temp_request_id:
|
||||
raise ValueError("temp_request_id is required for temp storage")
|
||||
saved_path = save_temp_notice_upload(temp_request_id, temp_index, name, raw or b"")
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else []
|
||||
except Exception as exc:
|
||||
warnings = [f"notice_extract_failed:{exc}"]
|
||||
status = "extract_failed"
|
||||
return NoticeIntakeResult(
|
||||
filename=name,
|
||||
source_type=source_type,
|
||||
source_file_type=source_file_type,
|
||||
text="",
|
||||
warnings=warnings,
|
||||
meta=meta if isinstance(meta, dict) else {},
|
||||
status=status,
|
||||
saved_path=saved_path,
|
||||
)
|
||||
|
||||
if not str(text or "").strip():
|
||||
return NoticeIntakeResult(
|
||||
filename=name,
|
||||
source_type=source_type,
|
||||
source_file_type=source_file_type,
|
||||
text="",
|
||||
warnings=warnings,
|
||||
meta=meta if isinstance(meta, dict) else {},
|
||||
status="empty_text",
|
||||
saved_path=saved_path,
|
||||
)
|
||||
|
||||
text, warnings = truncate_notice_text(text, warnings)
|
||||
return NoticeIntakeResult(
|
||||
filename=name,
|
||||
source_type=source_type,
|
||||
source_file_type=source_file_type,
|
||||
text=text,
|
||||
warnings=warnings,
|
||||
meta=meta if isinstance(meta, dict) else {},
|
||||
status="accepted",
|
||||
saved_path=saved_path,
|
||||
)
|
||||
|
||||
|
||||
def intake_temp_notice_uploads(
|
||||
temp_request_id: str,
|
||||
uploads: Sequence[Any],
|
||||
) -> tuple[list[NoticeIntakeResult], list[NoticeIntakeResult]]:
|
||||
"""
|
||||
批量建单入口:逐份附件接入并在 finally 外由调用方清理临时目录。
|
||||
|
||||
Args:
|
||||
temp_request_id: 请求级临时目录 ID。
|
||||
uploads: Flask request.files 中的上传对象序列。
|
||||
|
||||
Returns:
|
||||
tuple[list, list]: (accepted 结果列表, rejected 结果列表)。
|
||||
"""
|
||||
accepted: list[NoticeIntakeResult] = []
|
||||
rejected: list[NoticeIntakeResult] = []
|
||||
for index, upload in enumerate(uploads, start=1):
|
||||
raw = upload.read() or b""
|
||||
result = intake_notice_attachment(
|
||||
filename=upload.filename or "notice",
|
||||
raw=raw,
|
||||
source_file_type=notice_source_file_type(upload),
|
||||
storage="temp",
|
||||
temp_request_id=temp_request_id,
|
||||
temp_index=index,
|
||||
)
|
||||
if result.accepted:
|
||||
accepted.append(result)
|
||||
else:
|
||||
rejected.append(result)
|
||||
return accepted, rejected
|
||||
|
||||
|
||||
def build_notice_file_summary(
|
||||
*,
|
||||
total_files: int,
|
||||
accepted: Sequence[NoticeIntakeResult],
|
||||
rejected: Sequence[NoticeIntakeResult],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建批量上传预检摘要,供前端回显与测试断言。
|
||||
|
||||
Args:
|
||||
total_files: 请求内附件总数。
|
||||
accepted: 接入成功的结果列表。
|
||||
rejected: 接入失败的结果列表。
|
||||
|
||||
Returns:
|
||||
dict: total/accepted/rejected 计数与文件明细。
|
||||
"""
|
||||
accepted_files = [item.to_accepted_file_summary() for item in accepted]
|
||||
rejected_files = [item.to_rejected_file_summary() for item in rejected]
|
||||
return {
|
||||
"total_files": total_files,
|
||||
"accepted_count": len(accepted_files),
|
||||
"rejected_count": len(rejected_files),
|
||||
"accepted_files": accepted_files,
|
||||
"rejected_files": rejected_files,
|
||||
}
|
||||
Reference in new issue
Block a user