- 重构发货通知的状态与动作获取逻辑:移除从聊天文本解析HXOPS_SHIPPING_ACTIONS注释的旧逻辑,改为统一从后端shipping_ui_state获取任务状态、动作按钮与工作流步骤 - 新增SSE实时推送shipping_ui_state事件,支持前端即时更新聊天气泡与工作台的状态与按钮 - 优化路由与登录流程:调整根路径重定向逻辑,退出登录时跳转到登录页;移除chat路由不必要的props传参;将原路由守卫中的根路径判断迁移到路由配置中 - 完善库存RPA与本地导入流程:新增本地库存文件托管接口,优化RPA回调的文件落盘与任务关联逻辑 - 新增多组单元测试覆盖焦点切换、决策处理、SSE同步等核心场景 - 修复多语言显示逻辑,使用te方法判断翻译key是否存在,避免缺失翻译时的渲染异常 - 新增reparse_inventory菜单动作,支持静默重新解析库存且不追加额外聊天消息 - 重构工作流步骤渲染函数,优先使用后端返回的步骤数据, fallback到本地推导的旧逻辑 - 清理后端旧的chat-actions API接口,将相关逻辑迁移到统一的ui_state接口中
231 lines
8.1 KiB
Python
231 lines
8.1 KiB
Python
"""
|
||
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;批量上传的预检临时文件也在这里统一落盘和清理。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import base64
|
||
import re
|
||
import shutil
|
||
from email import policy
|
||
from email.parser import BytesParser
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from flask import current_app
|
||
|
||
from edkb_system.contracts import Block, Context
|
||
from edkb_system.skills import loader_csv, loader_docx, loader_pdf, ocr
|
||
from app.services.shipping_notice.export import _storage_root
|
||
|
||
|
||
def task_notice_upload_path(task_no: str, filename: str) -> Path:
|
||
"""生成任务级发货通知附件落盘路径(notice_uploads/{task_no}/{filename})。"""
|
||
safe_task = re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown"
|
||
name = str(filename or "").strip() or "notice"
|
||
safe_name = re.sub(r"[^\w\-.]+", "_", name)[:120] or "notice"
|
||
return _storage_root() / "notice_uploads" / safe_task / safe_name
|
||
|
||
|
||
def temp_notice_upload_dir(request_id: str) -> Path:
|
||
"""
|
||
返回批量上传预检使用的请求级临时目录。
|
||
核心逻辑:将同一请求下的临时文件收敛到 `_tmp/{request_id}`,便于 finally 阶段整目录清理。
|
||
Args:
|
||
request_id: 当前请求唯一 ID。
|
||
Returns:
|
||
Path: 临时目录路径。
|
||
"""
|
||
safe_request = re.sub(r"[^\w\-]+", "_", str(request_id or "").strip()) or "unknown"
|
||
return _storage_root() / "notice_uploads" / "_tmp" / safe_request
|
||
|
||
|
||
def save_task_notice_upload(task_no: str, filename: str, data: bytes) -> Path:
|
||
"""保存发货通知附件字节流并返回落盘路径。"""
|
||
path = task_notice_upload_path(task_no, filename)
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
path.write_bytes(data)
|
||
return path
|
||
|
||
|
||
def save_temp_notice_upload(request_id: str, index: int, filename: str, data: bytes) -> Path:
|
||
"""
|
||
保存批量上传预检阶段的临时附件。
|
||
核心逻辑:以请求 ID 作为一级目录、文件序号作为二级目录,避免同请求内同名文件互相覆盖。
|
||
Args:
|
||
request_id: 当前请求唯一 ID。
|
||
index: 当前文件在请求内的顺序号。
|
||
filename: 原始文件名。
|
||
data: 文件字节流。
|
||
Returns:
|
||
Path: 临时落盘路径。
|
||
"""
|
||
name = str(filename or "").strip() or "notice"
|
||
safe_name = re.sub(r"[^\w\-.]+", "_", name)[:120] or "notice"
|
||
safe_index = max(int(index or 0), 1)
|
||
path = temp_notice_upload_dir(request_id) / str(safe_index) / safe_name
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
path.write_bytes(data)
|
||
return path
|
||
|
||
|
||
def cleanup_temp_notice_uploads(request_id: str) -> None:
|
||
"""
|
||
清理指定请求的临时上传目录。
|
||
【AI 触发时机】:仅在批量上传预检完成后调用;正式任务附件目录禁止使用本函数清理。
|
||
Args:
|
||
request_id: 当前请求唯一 ID。
|
||
"""
|
||
path = temp_notice_upload_dir(request_id)
|
||
if path.exists():
|
||
shutil.rmtree(path, ignore_errors=True)
|
||
parent = path.parent
|
||
if parent.exists() and not any(parent.iterdir()):
|
||
parent.rmdir()
|
||
|
||
|
||
def _decode_text(data: bytes) -> str:
|
||
if not data:
|
||
return ""
|
||
for enc in ("utf-8", "utf-8-sig", "gb18030", "gbk"):
|
||
try:
|
||
return data.decode(enc)
|
||
except Exception:
|
||
continue
|
||
return data.decode("utf-8", errors="ignore")
|
||
|
||
|
||
def _html_to_text(html: str) -> str:
|
||
s = re.sub(r"(?is)<(script|style).*?>.*?</\\1>", "", html or "")
|
||
s = re.sub(r"(?is)<br\\s*/?>", "\n", s)
|
||
s = re.sub(r"(?is)</p\\s*>", "\n", s)
|
||
s = re.sub(r"(?is)<[^>]+>", " ", s)
|
||
s = re.sub(r"[ \t]+", " ", s)
|
||
s = re.sub(r"\\n\\s*\\n+", "\n\n", s)
|
||
return s.strip()
|
||
|
||
|
||
def _eml_to_text(data: bytes) -> str:
|
||
msg = BytesParser(policy=policy.default).parsebytes(data)
|
||
parts: list[str] = []
|
||
subject = str(msg.get("subject") or "").strip()
|
||
if subject:
|
||
parts.append(f"Subject: {subject}")
|
||
if msg.is_multipart():
|
||
for part in msg.walk():
|
||
if part.is_multipart():
|
||
continue
|
||
ctype = str(part.get_content_type() or "")
|
||
payload = part.get_payload(decode=True) or b""
|
||
if ctype == "text/plain":
|
||
parts.append(_decode_text(payload).strip())
|
||
elif ctype == "text/html":
|
||
parts.append(_html_to_text(_decode_text(payload)).strip())
|
||
else:
|
||
payload = msg.get_payload(decode=True) or b""
|
||
ctype = str(msg.get_content_type() or "")
|
||
if ctype == "text/html":
|
||
parts.append(_html_to_text(_decode_text(payload)).strip())
|
||
else:
|
||
parts.append(_decode_text(payload).strip())
|
||
return "\n\n".join(x for x in parts if x)
|
||
|
||
|
||
def _image_bytes_to_blocks(raw: bytes) -> list[Block]:
|
||
if not raw:
|
||
return []
|
||
data_uri = "data:image/png;base64," + base64.b64encode(raw).decode("ascii")
|
||
return [
|
||
Block(
|
||
id="img-1",
|
||
page=1,
|
||
type="image",
|
||
text="",
|
||
bbox=(0.0, 0.0, 1000.0, 1000.0),
|
||
meta={"data_uri": data_uri},
|
||
)
|
||
]
|
||
|
||
|
||
def _blocks_to_text(blocks: list[Block]) -> str:
|
||
lines: list[str] = []
|
||
for b in blocks:
|
||
if b.type not in {"paragraph", "ocr_text"}:
|
||
continue
|
||
txt = str(b.text or "").strip()
|
||
if not txt:
|
||
continue
|
||
if b.type == "ocr_text":
|
||
if txt.startswith("OCR_TEXT:"):
|
||
txt = txt[len("OCR_TEXT:") :].strip()
|
||
txt = re.sub(r"(?m)^\s*-\s*", "", txt).strip()
|
||
lines.append(txt)
|
||
text = "\n\n".join(lines)
|
||
text = re.sub(r"\n{3,}", "\n\n", text).strip()
|
||
return text
|
||
|
||
|
||
def extract_notice_text(file_path: Path) -> tuple[str, dict[str, Any]]:
|
||
"""
|
||
从发货通知附件抽取纯文本(PDF/DOCX/CSV/图片 OCR/EML/HTML 等)。
|
||
|
||
Returns:
|
||
tuple[str, dict]: (抽取文本, meta 含 warnings 与 file_type)。
|
||
"""
|
||
path = Path(file_path)
|
||
ext = path.suffix.lower().lstrip(".")
|
||
ctx = Context(file_type=ext)
|
||
warnings: list[str] = []
|
||
|
||
if ext in {"txt", "md", "log"}:
|
||
return _decode_text(path.read_bytes()).strip(), {"warnings": warnings, "file_type": ext}
|
||
if ext in {"html", "htm"}:
|
||
return _html_to_text(_decode_text(path.read_bytes())), {"warnings": warnings, "file_type": ext}
|
||
if ext in {"eml"}:
|
||
return _eml_to_text(path.read_bytes()), {"warnings": warnings, "file_type": ext}
|
||
|
||
blocks: list[Block] = []
|
||
if ext in {"pdf"}:
|
||
blocks = loader_pdf.run({"file_path": str(path)}, ctx)
|
||
elif ext in {"docx"}:
|
||
blocks = loader_docx.run({"file_path": str(path)}, ctx)
|
||
elif ext in {"csv"}:
|
||
blocks = loader_csv.run({"file_path": str(path)}, ctx)
|
||
elif ext in {"png", "jpg", "jpeg", "webp"}:
|
||
blocks = _image_bytes_to_blocks(path.read_bytes())
|
||
else:
|
||
warnings.append(f"unsupported_file_type:{ext}")
|
||
|
||
if blocks:
|
||
has_images = any(b.type == "image" for b in blocks)
|
||
if has_images:
|
||
blocks = ocr.run(blocks, ctx)
|
||
text = _blocks_to_text(blocks)
|
||
return text.strip(), {"warnings": warnings + list(ctx.warnings), "file_type": ext}
|
||
|
||
return "", {"warnings": warnings + list(ctx.warnings), "file_type": ext}
|
||
|
||
|
||
def guess_source_type(filename: str) -> str:
|
||
"""按扩展名推断 source_type(pdf / email / manual)。"""
|
||
ext = str(Path(filename or "").suffix or "").lower().lstrip(".")
|
||
if ext in {"pdf"}:
|
||
return "pdf"
|
||
if ext in {"eml"}:
|
||
return "email"
|
||
return "manual"
|
||
|
||
|
||
def max_notice_chars() -> int:
|
||
"""发货通知正文最大字符数(SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS,默认 200000)。"""
|
||
raw = str(current_app.config.get("SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS") or "").strip()
|
||
try:
|
||
value = int(raw) if raw else 0
|
||
except Exception:
|
||
value = 0
|
||
return value if value > 0 else 200000
|