Files
syops/backend/app/services/shipping_notice/match.py
T

105 lines
3.2 KiB
Python

from __future__ import annotations
from typing import Any
from app.services.shipping_notice.reservation_id import normalize_reservation_id
def _norm(value: Any) -> str:
return str(value or "").strip()
def _norm_reservation(value: Any) -> str:
return normalize_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
try:
qty = float(row.get("available_qty") or 0)
except (TypeError, ValueError):
qty = 0.0
key = _line_key(sku, row.get("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 rid:
return inv_totals.get((sku_n, rid), 0.0)
# 订单未带 Reservation ID 时,按 SKU 汇总所有 reservation 的可用量
return sum(qty for (s, _r), qty in inv_totals.items() if s == sku_n)
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}