""" services/shipping_notice/match.py 用途:执行订单行与库存行的匹配、缺货判断与匹配结果汇总。 依赖:shipping_notice.i18n、reservation_id 归一化工具、标准聚合逻辑。 逻辑:由 fulfillment_workflow.match_inventory 调用本文件,把通知订单行与库存快照比对后返回匹配状态和缺货明细。 """ from __future__ import annotations from typing import Any, Callable 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]: """按 (sku, reservation_id) 汇总库存 available_qty。""" 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]], *, progress_callback: Callable[[int, int], None] | None = None, ) -> tuple[str, list[dict[str, Any]], dict[str, Any]]: """ 将订单行与库存行按 (sku, reservation_id) 匹配,计算 fulfillable/partial/unfulfillable。 核心逻辑:聚合库存 → 逐行比对 required vs available → 汇总 match_status 与 shortages。 Returns: tuple: (match_status, line_results, shortage_json)。 """ # [STEP 1] 按 (sku, reservation_id) 聚合库存可用量。 inv_totals = _aggregate_inventory(inventory_lines) line_results: list[dict[str, Any]] = [] shortages: list[dict[str, Any]] = [] has_partial = False has_shortage = False # [STEP 2] 逐订单行计算 ok/partial/shortage 并收集缺口明细。 total_lines = len(notice_lines) for index, line in enumerate(notice_lines, start=1): 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 progress_callback is not None: progress_callback(index, total_lines) # [STEP 3] 汇总整体 match_status(fulfillable / partial / unfulfillable)。 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: """ 生成 match_inventory 固定 Markdown 表格摘要(Agent 须原文展示给用户)。 Args: match_status: fulfillable / partial / unfulfillable 等。 line_results: match_notice_lines 返回的逐行结果。 task_no: 可选任务编号,用于标题行。 lang: 可选语言码(zh-CN/en/th 等)。 """ 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)