Files
syops/backend/app/services/shipping_notice/export.py
T
hugo c18c0394d0 feat(shipping_notice): 完成货代发货通知全流程功能迭代与重构
主要变更:
1.  移除废弃的发货通知字段抽取独立Workflow Agent相关代码
2.  重构Dify服务调用,新增inputs参数支持注入环境变量配置的工具API地址与密钥
3.  新增auto_progress工具API与checkpoint catalog接口,支持流程自动推进
4.  统一字段命名,将column_mapping_json改为map_json并兼容旧有调用
5.  重构库存匹配、解析结果的展示格式,改为标准化多语言Markdown表格
6.  新增ODM ID库存字段支持,优化库存解析与映射逻辑
7.  新增LibreOffice转换隔离Profile配置,避免多实例运行冲突
8.  新增完整环境变量配置、数据库迁移脚本与测试用例
9.  适配前端代码,更新字段命名与聊天跳转逻辑
10. 更新OpenAPI规范适配Dify工具调用,删除已归档的旧部署文档
2026-06-08 16:07:20 +08:00

264 lines
8.3 KiB
Python

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:
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]:
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