""" services/shipping_notice/match.py 用途:按解析方案配置的字段关系执行库存匹配、缺货判断与结果汇总。 依赖:shipping_notice.i18n、动态订单字段投影、标准聚合逻辑。 逻辑:由 fulfillment_workflow 传入订单字段 ID、库存字段 ID 和数量字段 ID,字段名称不参与匹配。 """ from __future__ import annotations from typing import Any, Callable from app.services.shipping_notice.i18n import resolve_lang, t def _norm(value: Any) -> str: return str(value or "").strip() def _match_identity(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None: """按配置字段列表构造确定性匹配键;任一字段为空时该行不可匹配。""" values = tuple(_norm(row.get(field)).casefold() for field in fields) return values if values and all(values) else None def _aggregate_inventory( inventory_lines: list[dict[str, Any]], *, match_fields: list[str], quantity_field: str, ) -> dict[tuple[str, ...], float]: """按用户配置的库存匹配字段组合汇总唯一数量字段。""" totals: dict[tuple[str, ...], float] = {} for row in inventory_lines: key = _match_identity(row, match_fields) if key is None: continue try: qty = float(row.get(quantity_field) or 0) except (TypeError, ValueError): qty = 0.0 totals[key] = totals.get(key, 0.0) + qty return totals def match_notice_lines( notice_lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]], *, match_keys: list[dict[str, str]], quantity_field_id: str, progress_callback: Callable[[int, int], None] | None = None, ) -> tuple[str, list[dict[str, Any]], dict[str, Any]]: """ 按订单字段 ID 到库存字段 ID 的配置关系匹配,计算 fulfillable/partial/unfulfillable。 核心逻辑:聚合库存 → 逐行比对 required vs available → 汇总 match_status 与 shortages。 Returns: tuple: (match_status, line_results, shortage_json)。 """ order_fields = [str(item.get('order_field_id') or '') for item in match_keys] inventory_fields = [str(item.get('inventory_field_id') or '') for item in match_keys] if not order_fields or any(not item for item in order_fields + inventory_fields) or not quantity_field_id: raise ValueError('库存解析方案缺少有效的匹配字段或库存数量字段') inv_totals = _aggregate_inventory( inventory_lines, match_fields=inventory_fields, quantity_field=quantity_field_id, ) 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): order_key = _match_identity(line, order_fields) try: required = float(line.get("__required_qty") or 0) except (TypeError, ValueError): required = 0.0 available = inv_totals.get(order_key, 0.0) if order_key is not None else 0.0 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 = { "part_number": _norm(line.get("__display_part_number")), "reservation_id": _norm(line.get("__display_reservation_id")), "order_match_values": { order_field: line.get(order_field) for order_field in order_fields }, "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.part_number', 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('part_number'))} | " 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)