Files
syops/backend/app/services/shipping_notice/match.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

188 lines
5.9 KiB
Python

from __future__ import annotations
from typing import Any
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.reservation_id import extract_reservation_id
def _norm(value: Any) -> str:
return str(value or "").strip()
def _norm_reservation(value: Any) -> str:
return extract_reservation_id(value)
def _line_key(sku: str, reservation_id: str | None) -> tuple[str, str]:
return (_norm(sku), _norm_reservation(reservation_id))
def _aggregate_inventory(inventory_lines: list[dict[str, Any]]) -> dict[tuple[str, str], float]:
"""Sum available_qty by (AWS Sku, Reservation ID). Same key rows are aggregated."""
totals: dict[tuple[str, str], float] = {}
for row in inventory_lines:
sku = _norm(row.get("sku"))
if not sku:
continue
reservation_id = _norm_reservation(row.get("reservation_id"))
if not reservation_id:
continue
try:
qty = float(row.get("available_qty") or 0)
except (TypeError, ValueError):
qty = 0.0
key = _line_key(sku, reservation_id)
totals[key] = totals.get(key, 0.0) + qty
return totals
def _available_for_notice_line(
sku: str,
reservation_id: str | None,
inv_totals: dict[tuple[str, str], float],
) -> float:
sku_n = _norm(sku)
rid = _norm_reservation(reservation_id)
if not rid:
return 0.0
return inv_totals.get((sku_n, rid), 0.0)
def match_notice_lines(
notice_lines: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
) -> tuple[str, list[dict[str, Any]], dict[str, Any]]:
inv_totals = _aggregate_inventory(inventory_lines)
line_results: list[dict[str, Any]] = []
shortages: list[dict[str, Any]] = []
has_partial = False
has_shortage = False
for line in notice_lines:
sku = _norm(line.get("sku"))
reservation_id = _norm_reservation(line.get("reservation_id")) or None
try:
required = float(line.get("qty") or 0)
except (TypeError, ValueError):
required = 0.0
available = _available_for_notice_line(sku, reservation_id, inv_totals)
if available >= required:
line_status = "ok"
shortage = 0.0
elif available > 0:
line_status = "partial"
shortage = required - available
has_partial = True
else:
line_status = "shortage"
shortage = required
has_shortage = True
result = {
"sku": sku,
"reservation_id": reservation_id or "",
"required_qty": required,
"available_qty": available,
"shortage_qty": shortage,
"line_status": line_status,
}
line_results.append(result)
if shortage > 0:
shortages.append(result)
if not notice_lines:
return "unfulfillable", line_results, {"lines": shortages}
if has_shortage and not has_partial and all(r["line_status"] == "shortage" for r in line_results):
match_status = "unfulfillable"
elif has_partial or has_shortage:
match_status = "partial"
else:
match_status = "fulfillable"
return match_status, line_results, {"lines": shortages}
def _fmt_qty(value: float) -> str:
if value == int(value):
return str(int(value))
return f"{value:g}"
def _md_cell(value: Any) -> str:
text = str(value or "").strip() or "-"
return text.replace("|", "\\|")
def format_match_summary(
match_status: str,
line_results: list[dict[str, Any]],
*,
task_no: str | None = None,
lang: str | None = None,
) -> str:
"""Fixed Markdown table for match_inventory responses (Agent must display verbatim)."""
resolved = resolve_lang({"lang": lang} if lang else None)
if not line_results:
return t("match.no_lines", lang=resolved)
lines: list[str] = []
if task_no:
lines.append(t("match.title", lang=resolved).format(task_no=task_no))
lines.append("")
lines.append(t("match.subtitle", lang=resolved))
lines.append("")
lines.append(
"| # | "
f"{t('field.reservation_id', lang=resolved)} | "
f"{t('field.sku', lang=resolved)} | "
f"{t('match.col.order_qty', lang=resolved)} | "
f"{t('match.col.inv_qty', lang=resolved)} | "
f"{t('match.col.gap', lang=resolved)} | "
f"{t('match.col.status', lang=resolved)} |"
)
lines.append("|---:|---|---|---:|---:|---:|---|")
status_keys = {
"ok": "match.status.ok",
"partial": "match.status.partial",
"shortage": "match.status.shortage",
}
for index, row in enumerate(line_results, 1):
try:
required = float(row.get("required_qty") or 0)
except (TypeError, ValueError):
required = 0.0
try:
available = float(row.get("available_qty") or 0)
except (TypeError, ValueError):
available = 0.0
try:
shortage = float(row.get("shortage_qty") or 0)
except (TypeError, ValueError):
shortage = 0.0
status = str(row.get("line_status") or "")
status_label = t(status_keys.get(status, "match.status.unknown"), lang=resolved)
gap_cell = "-" if shortage <= 0 else _fmt_qty(shortage)
lines.append(
"| "
f"{index} | "
f"{_md_cell(row.get('reservation_id'))} | "
f"{_md_cell(row.get('sku'))} | "
f"{_fmt_qty(required)} | "
f"{_fmt_qty(available)} | "
f"{gap_cell} | "
f"{status_label} |"
)
lines.append("")
conclusion_key = f"match.conclusion.{match_status}"
conclusion = t(conclusion_key, lang=resolved)
if conclusion == conclusion_key:
conclusion = t("match.conclusion.other", lang=resolved).format(status=match_status)
lines.append(conclusion)
return "\n".join(lines)