from __future__ import annotations import re from typing import Any from app.services.shipping_notice.reservation_id import ( looks_like_reservation_id, normalize_reservation_id, ) NOTICE_LINE_FIELDS = ( "sku", "qty", "unit_price", "amount", "reservation_id", "uom", "remark", ) # 订单行表头 → 系统字段(发货通知 PDF/Excel/邮件表格) NOTICE_COLUMN_MAP: dict[str, str] = { # SKU "料号": "sku", "SKU": "sku", "sku": "sku", "AWS Sku": "sku", "AWS SKU": "sku", "Part Number": "sku", "Material": "sku", "Material No": "sku", "产品编号": "sku", "Item No": "sku", # 需求数量 "数量": "qty", "Qty": "qty", "qty": "qty", "Quantity": "qty", "需求数量": "qty", "订购数量": "qty", "Order Qty": "qty", "Ship Qty": "qty", "发货数量": "qty", # 单价 "单价": "unit_price", "Unit Price": "unit_price", "unit_price": "unit_price", "Price": "unit_price", "Unit Cost": "unit_price", "价格": "unit_price", # 金额 "金额": "amount", "Amount": "amount", "amount": "amount", "Total": "amount", "Line Amount": "amount", "Line Total": "amount", "小计": "amount", "总价": "amount", "Total Amount": "amount", # Reservation ID "Reservation ID": "reservation_id", "Reservation Id": "reservation_id", "reservation_id": "reservation_id", "COM ID": "reservation_id", "Reservation Order": "reservation_id", "Reservation No": "reservation_id", "Resv ID": "reservation_id", # 单位 "单位": "uom", "UOM": "uom", "uom": "uom", "Unit": "uom", } NOTICE_FIELD_LABELS = { "sku": "SKU / 料号", "qty": "需求数量", "unit_price": "单价", "amount": "金额", "reservation_id": "Reservation ID(常见纯数字,如 1000140351)", } _HEADER_SKIP_TOKENS = { "sku", "料号", "aws sku", "qty", "quantity", "数量", "reservation id", "com id", "单价", "unit price", "金额", "amount", } def _norm_header(value: Any) -> str: return re.sub(r"\s+", " ", str(value or "").strip().lower()) def _map_notice_header(header: str, col_map: dict[str, str] | None = None) -> str | None: text = str(header or "").strip() if not text: return None mapping = col_map or NOTICE_COLUMN_MAP if text in mapping: return mapping[text] norm = _norm_header(text) for key, field in mapping.items(): if _norm_header(key) == norm: return field return None def _resolve_notice_columns(headers: list[str]) -> dict[str, int | None]: columns: dict[str, int | None] = {field: None for field in NOTICE_LINE_FIELDS if field not in {"uom", "remark"}} for i, header in enumerate(headers): mapped = _map_notice_header(header) if mapped and columns.get(mapped) is None: columns[mapped] = i # Reservation 列名兜底 if columns.get("reservation_id") is None: for i, header in enumerate(headers): norm = _norm_header(header) if norm in {"com id", "reservation order", "reservation id", "reservation no", "resv id"}: columns["reservation_id"] = i break return columns def _cell(row: list[Any] | tuple[Any, ...], index: int | None) -> Any: if index is None or index >= len(row): return None return row[index] def _parse_number(value: Any) -> float | None: if value is None: return None text = str(value).strip() if not text: return None text = text.replace(",", "").replace(",", "") if text.startswith("$") or text.startswith("¥") or text.startswith("¥"): text = text[1:].strip() try: return float(text) except (TypeError, ValueError): return None def _infer_reservation_id_from_row( row: list[Any] | tuple[Any, ...], *, skip_indices: set[int], ) -> str: for i, cell in enumerate(row): if i in skip_indices: continue if looks_like_reservation_id(cell): return normalize_reservation_id(cell) return "" def _parse_notice_row( row: list[Any] | tuple[Any, ...], columns: dict[str, int | None], *, default_sku_index: int = 0, default_qty_index: int = 1, ) -> dict[str, Any] | None: idx_sku = columns.get("sku") if idx_sku is None: idx_sku = default_sku_index sku = str(_cell(row, idx_sku) or "").strip() if not sku: return None if sku.lower() in _HEADER_SKIP_TOKENS: return None idx_qty = columns.get("qty") if idx_qty is not None: qty = _parse_number(_cell(row, idx_qty)) else: qty = _parse_number(_cell(row, default_qty_index)) if qty is None or qty <= 0: return None parsed: dict[str, Any] = {"sku": sku, "qty": qty, "uom": "EA"} skip_indices: set[int] = {idx_sku} if idx_qty is not None: skip_indices.add(idx_qty) idx_res = columns.get("reservation_id") reservation_id = "" if idx_res is not None: reservation_id = normalize_reservation_id(_cell(row, idx_res)) skip_indices.add(idx_res) else: reservation_id = _infer_reservation_id_from_row(row, skip_indices=skip_indices) if reservation_id: parsed["reservation_id"] = reservation_id idx_price = columns.get("unit_price") if idx_price is not None: unit_price = _parse_number(_cell(row, idx_price)) if unit_price is not None: parsed["unit_price"] = unit_price idx_amount = columns.get("amount") if idx_amount is not None: amount = _parse_number(_cell(row, idx_amount)) if amount is not None: parsed["amount"] = amount idx_uom = columns.get("uom") if idx_uom is not None: uom = str(_cell(row, idx_uom) or "").strip() if uom: parsed["uom"] = uom # 若仅有 qty * unit_price,可推算 amount if "amount" not in parsed and "unit_price" in parsed: computed = round(parsed["unit_price"] * qty, 4) if computed > 0: parsed["amount"] = computed return parsed def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None: if not isinstance(raw, dict): return None sku = str(raw.get("sku") or raw.get("part_number") or raw.get("material") or "").strip() if not sku: return None qty = _parse_number(raw.get("qty") if raw.get("qty") is not None else raw.get("quantity")) if qty is None or qty <= 0: return None line: dict[str, Any] = { "sku": sku, "qty": qty, "uom": str(raw.get("uom") or "EA").strip() or "EA", } reservation_id = normalize_reservation_id( raw.get("reservation_id") or raw.get("reservationId") or raw.get("com_id") or raw.get("reservation_order") ) if reservation_id: line["reservation_id"] = reservation_id unit_price = _parse_number(raw.get("unit_price") if raw.get("unit_price") is not None else raw.get("price")) if unit_price is not None: line["unit_price"] = unit_price amount = _parse_number(raw.get("amount") if raw.get("amount") is not None else raw.get("total")) if amount is not None: line["amount"] = amount elif unit_price is not None: line["amount"] = round(unit_price * qty, 4) remark = str(raw.get("remark") or raw.get("note") or "").strip() if remark: line["remark"] = remark return line def normalize_notice_lines(lines: list[Any] | None) -> list[dict[str, Any]]: if not isinstance(lines, list): return [] normalized: list[dict[str, Any]] = [] for item in lines: parsed = normalize_notice_line(item if isinstance(item, dict) else None) if parsed: normalized.append(parsed) return normalized def _score_notice_header_row(cells: list[Any]) -> int: headers = [str(c or "").strip() for c in cells] if len([h for h in headers if h]) < 2: return 0 mapped: set[str] = set() for h in headers: field = _map_notice_header(h) if field: mapped.add(field) score = len(mapped) * 10 if "sku" in mapped and "qty" in mapped: score += 30 if "reservation_id" in mapped: score += 10 if "unit_price" in mapped or "amount" in mapped: score += 5 return score def _find_notice_header_row_index(rows: list[list[Any]], *, max_scan: int = 40) -> int: best_idx = 0 best_score = 0 for i, row in enumerate(rows[:max_scan]): score = _score_notice_header_row(list(row)) if score > best_score: best_score = score best_idx = i return best_idx if best_score > 0 else 0 def parse_notice_table_rows(headers: list[str], data_rows: list[list[Any]]) -> list[dict[str, Any]]: columns = _resolve_notice_columns(headers) has_header = columns.get("sku") is not None or columns.get("qty") is not None if not has_header and headers: has_header = any(_map_notice_header(h) for h in headers) if not has_header: return [] lines: list[dict[str, Any]] = [] for row in data_rows: if not row: continue parsed = _parse_notice_row(list(row), columns) if parsed: lines.append(parsed) return lines def parse_notice_table_text(raw_text: str) -> list[dict[str, Any]]: from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text text = str(raw_text or "").strip() if not text: return [] rows = _rows_from_table_text(text) if not rows: return [] header_idx = _find_notice_header_row_index(rows) header = [str(c or "").strip() for c in rows[header_idx]] data_rows = rows[header_idx + 1 :] return parse_notice_table_rows(header, data_rows) def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]: warnings: list[str] = [] if not lines: warnings.append("未解析到有效订单行(需至少包含 SKU 与需求数量)。") return warnings missing_reservation = [line["sku"] for line in lines if not str(line.get("reservation_id") or "").strip()] if missing_reservation and len(missing_reservation) == len(lines): warnings.append( "订单行未解析到 Reservation ID;后续将仅按 SKU 汇总库存比对," "若订单含 COM ID / Reservation Order 请核对表头。" ) elif missing_reservation: warnings.append( f"部分订单行缺少 Reservation ID({len(missing_reservation)}/{len(lines)} 行)," "这些行将按 SKU 汇总库存比对。" ) invalid_reservation = [ line["sku"] for line in lines if str(line.get("reservation_id") or "").strip() and not looks_like_reservation_id(line.get("reservation_id")) ] if invalid_reservation: warnings.append( f"{len(invalid_reservation)} 行 Reservation ID 非典型纯数字格式(常见为 8~12 位,如 1000140351)," "请核对是否解析正确。" ) missing_price = sum(1 for line in lines if line.get("unit_price") is None and line.get("amount") is None) if missing_price: warnings.append(f"{missing_price} 行未解析到单价或金额(不影响库存匹配)。") return warnings def notice_parse_completeness(lines: list[dict[str, Any]]) -> float: """0~1 score for how complete order lines are (sku/qty/reservation/price).""" if not lines: return 0.0 scores: list[float] = [] for line in lines: item = 0.0 if line.get("sku"): item += 0.35 if line.get("qty"): item += 0.35 if line.get("reservation_id"): item += 0.15 if line.get("unit_price") is not None or line.get("amount") is not None: item += 0.15 scores.append(item) return round(sum(scores) / len(scores), 4)