""" services/shipping_notice/export.py 用途:生成发货通知对应的货代出货 Excel,并管理模板与导出文件存储路径。 依赖:openpyxl、app.models.ShippingTask、path_utils、Flask current_app 配置。 逻辑:由 fulfillment_workflow.generate_excel 调用本文件,根据任务数据填充模板后返回导出文件路径。 """ from __future__ import annotations from datetime import datetime from pathlib import Path from shutil import copy2 from typing import Any from flask import current_app from openpyxl import Workbook, load_workbook from app.models import ShippingTask from app.path_utils import backend_dir, resolve_backend_relative_path DEFAULT_HEADERS = [ "客户名称", "客户代码", "收货地址", "要求交期", "料号", "发货数量", "单位", "备注", ] HEADER_SHEET = "PVMI Pull Request Header" DETAIL_SHEET = "PVMI Pull Request Detail" DATA_START_ROW = 4 def _storage_root() -> Path: """发货通知文件存储根目录(exports/notice_uploads/inventory_uploads 的父路径)。""" root = str(current_app.config.get("SHIPPING_NOTICE_STORAGE_ROOT") or "").strip() if root: return Path(resolve_backend_relative_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(resolve_backend_relative_path(configured)) if path.is_file(): return path bundled = backend_dir() / "templates" / "freight_shipment_upload.xlsx" return bundled if bundled.is_file() else None def _is_pvmi_workbook(wb) -> bool: return HEADER_SHEET in wb.sheetnames and DETAIL_SHEET in wb.sheetnames def _format_delivery_date(value: Any) -> str: text = str(value or "").strip() if not text: return "" for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%d/%m/%Y", "%m/%d/%Y", "%Y%m%d"): try: parsed = datetime.strptime(text[:10], fmt) return parsed.strftime("%m/%d/%Y") except ValueError: continue if len(text) >= 10 and text[4] == "-" and text[7] == "-": try: parsed = datetime.strptime(text[:10], "%Y-%m-%d") return parsed.strftime("%m/%d/%Y") except ValueError: pass return text def _delivery_date_for_task(task: ShippingTask) -> str: if task.required_date: formatted = _format_delivery_date(task.required_date) if formatted: return formatted for line in task.lines_json or []: if not isinstance(line, dict): continue formatted = _format_delivery_date(line.get("required_date")) if formatted: return formatted return "" def _resolve_odm_id(task: ShippingTask) -> str: notice_lines = [line for line in (task.lines_json or []) if isinstance(line, dict)] inventory_lines = [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)] if not inventory_lines: return "" inv_by_key: dict[tuple[str, str], dict[str, Any]] = {} for row in inventory_lines: key = ( str(row.get("sku") or "").strip(), str(row.get("reservation_id") or "").strip(), ) inv_by_key[key] = row for line in notice_lines: key = ( str(line.get("sku") or "").strip(), str(line.get("reservation_id") or "").strip(), ) matched = inv_by_key.get(key) if matched: odm_id = str(matched.get("odm_id") or "").strip() if odm_id: return odm_id for row in inventory_lines: odm_id = str(row.get("odm_id") or "").strip() if odm_id: return odm_id return "" def _line_po_number(task: ShippingTask, line: dict[str, Any]) -> str: for value in (line.get("po_number"), task.po_number): text = str(value or "").strip() if text: return text return "" def _line_currency(task: ShippingTask, line: dict[str, Any]) -> str: for value in (line.get("currency"), getattr(task, "currency", None)): text = str(value or "").strip().upper() if text: return text return "" def _line_vendor_part_number(line: dict[str, Any]) -> str: return str(line.get("vendor_part_number") or "").strip() def _clear_sheet_data_rows(ws, *, from_row: int = DATA_START_ROW) -> None: if ws.max_row < from_row: return for row_idx in range(from_row, ws.max_row + 1): for col_idx in range(1, ws.max_column + 1): ws.cell(row_idx, col_idx).value = None def _fill_pvmi_template(task: ShippingTask, path: Path) -> None: wb = load_workbook(filename=str(path)) header_ws = wb[HEADER_SHEET] detail_ws = wb[DETAIL_SHEET] _clear_sheet_data_rows(detail_ws) _clear_sheet_data_rows(header_ws, from_row=DATA_START_ROW) if header_ws.cell(DATA_START_ROW, 1).value in (None, ""): header_ws.cell(DATA_START_ROW, 1).value = "AWSDU" if header_ws.cell(DATA_START_ROW, 2).value in (None, ""): header_ws.cell(DATA_START_ROW, 2).value = "n" if header_ws.cell(DATA_START_ROW, 3).value in (None, ""): header_ws.cell(DATA_START_ROW, 3).value = "WEL" if header_ws.cell(DATA_START_ROW, 4).value in (None, ""): header_ws.cell(DATA_START_ROW, 4).value = "normal" header_ws.cell(DATA_START_ROW, 5).value = _delivery_date_for_task(task) header_ws.cell(DATA_START_ROW, 6).value = _resolve_odm_id(task) header_ws.cell(DATA_START_ROW, 7).value = task.task_no notice_lines = [line for line in (task.lines_json or []) if isinstance(line, dict)] if not notice_lines: notice_lines = [{}] for index, line in enumerate(notice_lines, start=1): row_idx = DATA_START_ROW + index - 1 line_no = str(line.get("line_no") or index).strip() qty = line.get("qty") amount = line.get("amount") detail_ws.cell(row_idx, 1).value = task.task_no detail_ws.cell(row_idx, 2).value = line_no detail_ws.cell(row_idx, 4).value = _line_vendor_part_number(line) detail_ws.cell(row_idx, 5).value = qty if qty is not None else "" detail_ws.cell(row_idx, 7).value = _line_po_number(task, line) detail_ws.cell(row_idx, 10).value = amount if amount is not None else "" detail_ws.cell(row_idx, 11).value = _line_currency(task, line) wb.save(path) 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 "", task.required_date or "", line.get("sku") or "", line.get("qty") or "", line.get("uom") or "EA", line.get("remark") or "", ] def _fill_legacy_template(task: ShippingTask, path: Path) -> None: wb = load_workbook(filename=str(path)) ws = wb.active lines = task.lines_json or [None] if ws.max_row == 1 and not any(ws.cell(1, c).value for c in range(1, 9)): ws.append(DEFAULT_HEADERS) 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 _sanitize_filename(name: str) -> str: cleaned = "".join(ch for ch in (name or "") if ch.isalnum() or ch in {"-", "_", "."}) return cleaned or "shipment.xlsx" def _export_filename(task: ShippingTask, ts: str) -> str: pattern = str(current_app.config.get("SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN") or "").strip() if not pattern: pattern = "shipment_{task_no}_{ts}.xlsx" try: name = pattern.format(task_no=task.task_no, ts=ts, date=ts[:8]) except Exception: name = f"shipment_{task.task_no}_{ts}.xlsx" if not str(name).lower().endswith(".xlsx"): name = f"{name}.xlsx" return _sanitize_filename(str(name)) def generate_shipment_excel(task: ShippingTask) -> tuple[str, str]: """ 基于任务数据生成货代发货 Excel 并写入 exports 目录。 【AI 触发时机】:由 generate_excel Tool 调用;Agent 禁止直接操作文件系统。 核心逻辑:复制 PVMI/legacy 模板 → 填充 Header/Detail 或 legacy 行 → 返回 (绝对路径, 文件名)。 Returns: tuple[str, str]: (export_file_path, export_file_name)。 """ root = _storage_root() / "exports" root.mkdir(parents=True, exist_ok=True) ts = datetime.utcnow().strftime("%Y%m%d%H%M%S") filename = _export_filename(task, ts) path = root / filename template = _default_template_path() if template: copy2(template, path) wb = load_workbook(filename=str(path), read_only=True) try: is_pvmi = _is_pvmi_workbook(wb) finally: wb.close() if is_pvmi: _fill_pvmi_template(task, path) else: _fill_legacy_template(task, path) else: _fill_blank_workbook(task, path) return str(path), filename