Files
syops/backend/app/services/shipping_notice/onhand_upload.py
T
hugoandCursor 39fe3c05f2 feat(freight-rpa): 库存/收料改名在手/入站,报表归属RPA,类名统一FreightRpa
把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与
枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa
持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀,
上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 10:46:06 +08:00

391 lines
14 KiB
Python

"""
services/shipping_notice/onhand_upload.py
用途:管理任务级库存附件上传、落盘、schema preview 读取与文本长度限制。
依赖:onhand_snapshot、export._storage_root、Werkzeug FileStorage、Flask current_app 配置。
逻辑:由 onhand_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息;
正式附件使用版本化文件名 + .current_inventory 原子指针,避免多格式并存或崩溃后误读旧文件。
"""
from __future__ import annotations
import hashlib
import re
import shutil
from datetime import datetime
from pathlib import Path
from typing import Any
from flask import current_app
from werkzeug.datastructures import FileStorage
from app.models import FreightRpaOnhandReportFile, ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.export import _storage_root
from app.services.shipping_notice.onhand_file_store import inventory_storage_suffix_for_path
_TASK_INVENTORY_SUFFIXES = (".xls", ".xlsx", ".csv")
_TASK_INVENTORY_MARKER = ".current_inventory"
_TASK_INVENTORY_VERSION_PREFIX = "inventory_"
def _inventory_file_sha256(path: Path) -> str:
"""计算库存附件 SHA256,用于幂等安装判断。"""
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _task_inventory_attachment_marker_path(task_no: str) -> Path:
"""任务当前正式库存附件指针文件路径。"""
return _task_inventory_upload_dir(task_no) / _TASK_INVENTORY_MARKER
def _atomic_write_task_inventory_marker(task_no: str, attachment_filename: str) -> None:
"""通过临时文件 + os.replace 原子切换 .current_inventory 指针。"""
import os
marker = _task_inventory_attachment_marker_path(task_no)
tmp = marker.with_name(f"{marker.name}.tmp")
marker.parent.mkdir(parents=True, exist_ok=True)
tmp.write_text(attachment_filename, encoding="utf-8")
os.replace(tmp, marker)
def _read_task_inventory_attachment_marker(task_no: str) -> Path | None:
"""读取指针文件并校验对应附件仍存在。"""
marker = _task_inventory_attachment_marker_path(task_no)
if not marker.is_file():
return None
name = marker.read_text(encoding="utf-8").strip()
if not name:
return None
path = _task_inventory_upload_dir(task_no) / name
if path.is_file() and _is_task_inventory_attachment_name(path.name):
return path
return None
def _is_task_inventory_attachment_name(name: str) -> bool:
"""判断文件名是否为合法任务库存附件。"""
lowered = str(name or "").lower()
if not lowered.startswith("inventory"):
return False
return any(lowered.endswith(suffix) for suffix in _TASK_INVENTORY_SUFFIXES)
def _versioned_task_inventory_path(task_no: str, suffix: str) -> Path:
"""生成不可变版本化任务库存附件路径。"""
token = datetime.utcnow().strftime("%Y%m%d%H%M%S%f")
normalized = suffix if suffix in _TASK_INVENTORY_SUFFIXES else ".xlsx"
return _task_inventory_upload_dir(task_no) / f"{_TASK_INVENTORY_VERSION_PREFIX}{token}{normalized}"
def _list_task_inventory_attachment_candidates(task_no: str) -> list[Path]:
"""列出任务目录下全部库存附件候选文件。"""
base = _task_inventory_upload_dir(task_no)
if not base.is_dir():
return []
return [
path
for path in base.iterdir()
if path.is_file() and _is_task_inventory_attachment_name(path.name)
]
def _cleanup_superseded_task_inventory_files(task_no: str, *, keep_name: str) -> list[str]:
"""
指针切换后清理旧版附件(best effort)。
Returns:
未能删除的文件名列表。
"""
warnings: list[str] = []
for path in _list_task_inventory_attachment_candidates(task_no):
if path.name == keep_name:
continue
try:
path.unlink()
except OSError as exc:
warnings.append(f"{path.name}:{str(exc)[:80]}")
return warnings
def install_task_inventory_attachment_from_file(
task_no: str,
source_path: str | Path,
*,
source_file_name: str | None = None,
) -> Path:
"""
将源库存文件安装为任务正式附件(版本化文件名 + 原子 marker 切换)。
【AI 触发时机】:RPA 回调晋升失败补偿、人工修复任务附件时调用;不依赖重新消费 callback。
核心逻辑:复制到 inventory_{timestamp}{suffix} → 原子切换 .current_inventory → 清理旧附件。
若当前正式附件与源文件内容一致则幂等返回现有路径。
Args:
task_no: 发货任务号。
source_path: 源库存文件(通常为 inv_file.storage_path 或 staging)。
source_file_name: 可选展示名,仅用于日志语义。
Returns:
安装后的正式附件路径。
Raises:
FileNotFoundError: 源文件不存在。
OSError: 复制或 marker 切换失败。
"""
source = Path(source_path)
if not source.is_file():
raise FileNotFoundError(f"未找到库存源文件: {source}")
current = resolve_task_inventory_upload_path(task_no)
if current is not None and _inventory_file_sha256(current) == _inventory_file_sha256(source):
return current
suffix = inventory_storage_suffix_for_path(source)
versioned = _versioned_task_inventory_path(task_no, suffix)
versioned.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, versioned)
try:
_atomic_write_task_inventory_marker(task_no, versioned.name)
_cleanup_superseded_task_inventory_files(task_no, keep_name=versioned.name)
except Exception:
if versioned.is_file():
try:
versioned.unlink()
except OSError:
pass
raise
if source_file_name:
_ = source_file_name
return versioned
def rebuild_task_inventory_attachment_from_snapshot(
task: ShippingOrderTask | ShippingNotice | str,
inv_file: FreightRpaOnhandReportFile,
) -> Path:
"""
从已提交库存快照 storage_path 幂等重建任务正式附件。
【AI 触发时机】:RPA 回调 DB 已提交但任务附件晋升失败,或运维人工补偿时调用。
Args:
task: 任务对象或 task_no。
inv_file: 已链接的库存快照。
Returns:
重建后的任务正式附件路径。
"""
task_no = str(getattr(task, "task_no", task) or "").strip()
if not task_no:
raise ValueError("task_no is required")
storage_path = Path(str(inv_file.storage_path or ""))
if not storage_path.is_file() or str(inv_file.storage_path or "").startswith("failed://"):
raise FileNotFoundError(
f"库存快照托管文件不存在: {inv_file.onhand_file_no}",
)
return install_task_inventory_attachment_from_file(
task_no,
storage_path,
source_file_name=str(inv_file.source_file_name or storage_path.name),
)
def inventory_text_max_chars() -> int:
"""库存粘贴文本最大字符数(SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS,默认 80000)。"""
try:
return int(current_app.config.get("SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS") or 80000)
except (TypeError, ValueError):
return 80000
def _task_inventory_upload_dir(task_no: str) -> Path:
"""任务级库存附件目录(inventory_uploads/{task_no})。"""
safe = _sanitize_task_no(task_no)
return _storage_root() / "inventory_uploads" / safe
def task_inventory_upload_path(task_no: str, *, suffix: str | None = None) -> Path:
"""
任务级库存附件标准落盘路径(默认 inventory.xlsx)。
suffix 仅允许 .xls / .xlsx / .csv,用于 RPA 回调保留源文件格式。
"""
normalized = (suffix or ".xlsx").lower()
if normalized not in _TASK_INVENTORY_SUFFIXES:
normalized = ".xlsx"
return _task_inventory_upload_dir(task_no) / f"inventory{normalized}"
def _recover_and_repair_task_inventory_marker(task_no: str) -> Path | None:
"""
marker 缺失或损坏时扫描附件目录并修复 .current_inventory。
核心逻辑:仅在此路径下根据 mtime 选择候选;修复后返回已提交附件。
"""
candidates = _list_task_inventory_attachment_candidates(task_no)
if not candidates:
return None
versioned = [
path
for path in candidates
if path.name.startswith(_TASK_INVENTORY_VERSION_PREFIX)
]
if versioned:
chosen = max(versioned, key=lambda item: item.stat().st_mtime)
elif len(candidates) == 1:
chosen = candidates[0]
else:
chosen = max(candidates, key=lambda item: item.stat().st_mtime)
_atomic_write_task_inventory_marker(task_no, chosen.name)
return chosen
def resolve_task_inventory_upload_path(task_no: str) -> Path | None:
"""
返回任务当前已提交的正式库存附件路径。
核心逻辑:marker 有效且目标文件存在时必须无条件相信 marker;
仅 marker 缺失或损坏时才执行恢复扫描并同步修复 marker。
"""
marked = _read_task_inventory_attachment_marker(task_no)
if marked is not None:
return marked
return _recover_and_repair_task_inventory_marker(task_no)
def save_task_inventory_upload(task_no: str, upload: FileStorage) -> Path:
"""保存 werkzeug FileStorage 库存上传并返回落盘路径。"""
suffix = ".xlsx"
filename = str(getattr(upload, "filename", "") or "").lower()
if filename.endswith((".xls", ".csv")):
suffix = Path(filename).suffix
staging_dir = _task_inventory_upload_dir(task_no) / ".staging"
staging_dir.mkdir(parents=True, exist_ok=True)
staging = staging_dir / f"manual_upload_{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}{suffix}"
upload.save(str(staging))
try:
return install_task_inventory_attachment_from_file(task_no, staging)
finally:
delete_staged_task_inventory_file(staging)
def save_task_inventory_local_file(task_no: str, source_path: str | Path) -> Path:
"""
保存本地已存在的库存文件到任务标准库存目录。
【AI 触发时机】:当 RPA 或其他后台流程已经拿到本地 Excel,需要把它正式纳入系统托管目录时调用。
核心逻辑:校验 source_path 存在后,按源文件格式复制到版本化任务附件路径,
让 RPA 下载与人工上传共用同一套任务级库存附件路径,并保留 .xls/.xlsx/.csv 格式。
Args:
task_no: 发货任务号,禁止为空。
source_path: 本地现有库存文件路径,必须指向真实文件。
Returns:
Path: 系统托管后的任务库存文件路径。
Raises:
FileNotFoundError: 源文件不存在时抛出。
"""
source = Path(source_path)
if not source.is_file():
raise FileNotFoundError(f"未找到库存源文件: {source}")
return install_task_inventory_attachment_from_file(
task_no,
source,
source_file_name=source.name,
)
def _sanitize_task_no(task_no: str) -> str:
"""将任务号规范为库存上传目录名。"""
return re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown"
def stage_task_inventory_callback_file(
task_no: str,
source_path: str | Path,
*,
run_no: str | None = None,
) -> Path:
"""
将 RPA 回调文件复制到本轮唯一 staging 路径,避免在校验前覆盖任务正式附件。
核心逻辑:按源文件格式落盘至 inventory_uploads/{task_no}/.staging/rpa_callback_{token}{suffix}。
Args:
task_no: 发货任务号。
source_path: Worker 回调提供的本地库存文件。
run_no: 可选轮次号,用于生成稳定且唯一的 staging 文件名。
Returns:
Path: staging 文件路径。
Raises:
FileNotFoundError: 源文件不存在。
"""
source = Path(source_path)
if not source.is_file():
raise FileNotFoundError(f"未找到库存源文件: {source}")
token = re.sub(
r"[^\w\-]+",
"_",
str(run_no or "").strip() or datetime.utcnow().strftime("%Y%m%d%H%M%S%f"),
)
suffix = source.suffix.lower() if source.suffix else ".xlsx"
staging_dir = _storage_root() / "inventory_uploads" / _sanitize_task_no(task_no) / ".staging"
staging_dir.mkdir(parents=True, exist_ok=True)
staging_path = staging_dir / f"rpa_callback_{token}{suffix}"
shutil.copy2(source, staging_path)
return staging_path
def promote_staged_task_inventory_file(task_no: str, staging_path: str | Path) -> Path:
"""
校验与数据库提交成功后,将 staging 安装为任务正式库存附件。
核心逻辑:版本化落盘 + 原子 marker 切换 + 异步清理旧附件;旧附件删除失败返回 warning 列表。
"""
import os
staging = Path(staging_path)
if not staging.is_file():
raise FileNotFoundError(f"未找到 staging 库存文件: {staging}")
suffix = staging.suffix.lower() if staging.suffix else ".xlsx"
if suffix not in _TASK_INVENTORY_SUFFIXES:
suffix = ".xlsx"
versioned = _versioned_task_inventory_path(task_no, suffix)
versioned.parent.mkdir(parents=True, exist_ok=True)
os.replace(staging, versioned)
try:
_atomic_write_task_inventory_marker(task_no, versioned.name)
cleanup_warnings = _cleanup_superseded_task_inventory_files(task_no, keep_name=versioned.name)
if cleanup_warnings:
raise OSError(f"legacy_attachment_cleanup_failed:{';'.join(cleanup_warnings)[:200]}")
except Exception:
if versioned.is_file():
try:
versioned.unlink()
except OSError:
pass
raise
try:
staging.parent.rmdir()
except OSError:
pass
return versioned
def delete_staged_task_inventory_file(staging_path: str | Path | None) -> None:
"""删除本轮 staging 库存文件(失败回滚用,不触碰任务正式附件)。"""
if not staging_path:
return
path = Path(staging_path)
if not path.is_file():
return
try:
path.unlink()
except OSError:
return
try:
path.parent.rmdir()
except OSError:
pass