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 ShippingCase 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(case: ShippingCase, line: dict | None) -> list: line = line or {} return [ case.customer_name or "", case.customer_code or "", case.ship_to or "", case.required_date or "", line.get("sku") or "", line.get("qty") or "", line.get("uom") or "EA", line.get("remark") or "", ] def _fill_from_template(case: ShippingCase, path: Path) -> None: wb = load_workbook(filename=str(path)) ws = wb.active lines = case.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(case, line)) wb.save(path) def _fill_blank_workbook(case: ShippingCase, path: Path) -> None: wb = Workbook() ws = wb.active ws.title = "Shipment" ws.append(DEFAULT_HEADERS) lines = case.lines_json or [None] for line in lines: ws.append(_row_values(case, line)) wb.save(path) def generate_shipment_excel(case: ShippingCase) -> tuple[str, str]: root = _storage_root() / "exports" root.mkdir(parents=True, exist_ok=True) filename = f"shipment_{case.case_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(case, path) else: _fill_blank_workbook(case, path) return str(path), filename