Files
syops/backend/app/services/shipping_notice/export.py
T
hugo 8deae3146b feat(shipping-notice): 完成货代发货通知全流程开发与代码重构
- 新增PO号提取、预约ID解析(支持`PR@xxx`格式)工具,完善库存匹配逻辑
- 新增库存映射缓存、匹配/解析结果格式化摘要,优化用户提示
- 修复数据库迁移脚本未检查表存在的问题,避免全新部署失败
- 新增路径工具类统一管理相对路径,优化配置文件处理逻辑
- 归档旧文档,将部署、Dify配置合并到`shipping_notice.md`
- 新增完整单元测试与集成测试覆盖核心流程
- 更新前端国际化与会话管理逻辑,优化界面交互
2026-06-04 15:26:34 +08:00

95 lines
2.6 KiB
Python

from __future__ import annotations
import os
from datetime import datetime
from pathlib import Path
from shutil import copy2
from flask import current_app
from openpyxl import Workbook, load_workbook
from app.models import ShippingTask
DEFAULT_HEADERS = [
"客户名称",
"客户代码",
"收货地址",
"要求交期",
"料号",
"发货数量",
"单位",
"备注",
]
def _storage_root() -> Path:
root = str(current_app.config.get("SHIPPING_NOTICE_STORAGE_ROOT") or "").strip()
if root:
return Path(root)
return Path(current_app.instance_path) / "shipping_notice"
def _default_template_path() -> Path | None:
configured = str(current_app.config.get("FREIGHT_SHIPMENT_TEMPLATE_PATH") or "").strip()
if configured:
path = Path(configured)
if path.is_file():
return path
bundled = Path(__file__).resolve().parents[2] / "templates" / "freight_shipment_upload.xlsx"
return bundled if bundled.is_file() else None
def _row_values(task: ShippingTask, line: dict | None) -> list:
line = line or {}
return [
task.customer_name or "",
task.customer_code or "",
task.ship_to or "",
line.get("required_date") or task.required_date or "",
line.get("sku") or "",
line.get("qty") or "",
line.get("uom") or "EA",
line.get("remark") or "",
]
def _fill_from_template(task: ShippingTask, path: Path) -> None:
wb = load_workbook(filename=str(path))
ws = wb.active
lines = task.lines_json or [None]
start_row = ws.max_row + 1 if ws.max_row >= 1 else 2
if ws.max_row == 1 and not any(ws.cell(1, c).value for c in range(1, 9)):
ws.append(DEFAULT_HEADERS)
start_row = 2
for line in lines:
ws.append(_row_values(task, line))
wb.save(path)
def _fill_blank_workbook(task: ShippingTask, path: Path) -> None:
wb = Workbook()
ws = wb.active
ws.title = "Shipment"
ws.append(DEFAULT_HEADERS)
lines = task.lines_json or [None]
for line in lines:
ws.append(_row_values(task, line))
wb.save(path)
def generate_shipment_excel(task: ShippingTask) -> tuple[str, str]:
root = _storage_root() / "exports"
root.mkdir(parents=True, exist_ok=True)
filename = f"shipment_{task.task_no}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx"
path = root / filename
template = _default_template_path()
if template:
copy2(template, path)
_fill_from_template(task, path)
else:
_fill_blank_workbook(task, path)
return str(path), filename