Merge branch 'dev-new' into runny827

This commit is contained in:
runny committed 2026-09-10 22:01:56 +08:00
commit f1beb6fefb
112 files changed
+6300 -586

No files matched your search

@@ -1,10 +1,11 @@
"""
backend/app/services/schedule/shipping_inventory_rpa_archive.py
用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)。
用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
依赖:ScheduleRun、ShippingInventoryFile、shipping_inventory_rpa_finalize.is_shipping_inventory_rpa_task。
逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary;
query_service 只读 summary;api/schedule/runs 按 raw_inventory_zip_path send_file。
企微/下载展示名用「库存RPA-日期-时刻-结果|库存」;包内条目仅「序号_仓码」;
完整 source_code / inventory_file_no 只写在 manifest.json;磁盘归档键仍为 {run_no}.zip。
"""
from __future__ import annotations
@@ -12,6 +13,7 @@ from __future__ import annotations
import json
import re
import zipfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
@@ -21,6 +23,7 @@ from app import db
from app.core.errors import NotFoundError
from app.models import ScheduleRun, ShippingInventoryFile
from app.services.schedule.shipping_inventory_rpa_finalize import is_shipping_inventory_rpa_task
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
_RAW_ZIP_NOT_FOUND_MESSAGE = "原始库存包不存在,请重新执行或联系管理员"
@@ -48,9 +51,63 @@ def get_inventory_archive_dir() -> str:
return str(archive_dir)
def inventory_raw_zip_download_name(run_no: str) -> str:
"""浏览器下载时使用的 ZIP 文件名。"""
return f"inventory-rpa-raw-{run_no}.zip"
def _attachment_when_from_run(run: ScheduleRun) -> datetime:
"""
推导企微/下载展示名中的当地时刻。
核心逻辑:started_at → created_at → finished_at → 解析 RUN{yyyyMMddHHmmss}* → utcnow;
上述时刻在库内均为 UTC naive(含 run_no 时间戳),格式化前转到任务
schedule_timezone(缺省 Asia/Shanghai)。完整 run_no 仍留在卡片与磁盘归档键。
"""
when_utc: datetime | None = None
for value in (run.started_at, run.created_at, run.finished_at):
if isinstance(value, datetime):
when_utc = value
break
if when_utc is None:
match = re.match(r"^RUN(\d{14})", str(run.run_no or "").strip())
if match:
try:
when_utc = datetime.strptime(match.group(1), "%Y%m%d%H%M%S")
except ValueError:
when_utc = None
if when_utc is None:
when_utc = datetime.now(timezone.utc).replace(tzinfo=None)
task = getattr(run, "task", None)
tz_name = getattr(task, "schedule_timezone", None) if task is not None else None
tz = resolve_schedule_tzinfo(tz_name)
if when_utc.tzinfo is None:
when_utc = when_utc.replace(tzinfo=timezone.utc)
return when_utc.astimezone(tz)
def inventory_rpa_attachment_stem(run: ScheduleRun) -> str:
"""
库存 RPA 企微附件共用前缀:库存RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。
Args:
run: 排程执行记录。
Returns:
不含角色后缀与扩展名的展示名前缀。
"""
when = _attachment_when_from_run(run)
return f"库存RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}"
def inventory_rpa_result_excel_name(run: ScheduleRun) -> str:
"""库存 RPA 结果 Excel 的企微/下载展示名。"""
return f"{inventory_rpa_attachment_stem(run)}-结果.xlsx"
def inventory_raw_zip_download_name(run: ScheduleRun) -> str:
"""
库存 ZIP 的企微/浏览器下载展示名。
核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。
"""
return f"{inventory_rpa_attachment_stem(run)}-库存.zip"
def _inventory_raw_zip_archive_path(run_no: str) -> Path:
@@ -157,7 +214,6 @@ def persist_inventory_rpa_raw_zip_archive(
index=zip_index,
source_code=source_code,
warehouse_id=warehouse_id,
inventory_file_no=inventory_file_no,
original_suffix=storage_path.suffix or ".xlsx",
)
archive.write(storage_path, arcname=entry_name)
@@ -236,7 +292,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
if not _is_allowed_inventory_archive_path(zip_path):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
return zip_path.resolve(), inventory_raw_zip_download_name(run.run_no)
return zip_path.resolve(), inventory_raw_zip_download_name(run)
def _sanitize_zip_segment(value: str) -> str:
@@ -245,25 +301,33 @@ def _sanitize_zip_segment(value: str) -> str:
return cleaned or "unknown"
def _zip_entry_label(*, source_code: str, warehouse_id: str) -> str:
"""
包内短标签:优先 source_code(库存站点业务键,Crane 等无固定仓码也能辨认)。
warehouse_id / inventory_file_no 已写入 manifest.json;条目名不必再叠仓码。
"""
source = str(source_code or "").strip()
if source:
return source
warehouse = str(warehouse_id or "").strip()
if warehouse and warehouse.lower() != "unknown":
return warehouse
return "inventory"
def _build_zip_entry_name(
*,
index: int,
source_code: str,
warehouse_id: str,
inventory_file_no: str,
original_suffix: str,
) -> str:
"""生成 ZIP 内单文件条目名(不含目录)。"""
base = "_".join(
filter(
None,
[
f"{index:03d}",
_sanitize_zip_segment(source_code),
_sanitize_zip_segment(warehouse_id),
_sanitize_zip_segment(inventory_file_no),
],
)
)
"""
生成 ZIP 内单文件条目名(不含目录)。
核心逻辑:`{序号}_{source_code}.{ext}`;序号保证极端撞名时仍唯一。
"""
label = _sanitize_zip_segment(_zip_entry_label(source_code=source_code, warehouse_id=warehouse_id))
suffix = original_suffix if original_suffix.startswith(".") else f".{original_suffix}"
return f"{base}{suffix}"
return f"{index:03d}_{label}{suffix}"
@@ -493,6 +493,11 @@ def _finalize_shipping_inventory_schedule_run_impl(
errors.append(f"Excel导出失败: {excel_exc}")
if status == "success":
status = "partial_failed"
else:
# 企微/下载展示名:库存RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
from app.services.schedule.shipping_inventory_rpa_archive import inventory_rpa_result_excel_name
file_name = inventory_rpa_result_excel_name(run)
step_logs = list(run.step_logs or [])
step_logs.append({