""" services/shipping_notice/notice_lines.py 用途:发货通知订单行的标准化、文档级回填、质量校验与完整度评估(对外统一入口)。 依赖:notice_line_constants、notice_line_values、notice_line_table、reservation_id。 逻辑:由 extract/task_workflow 等上游模块调用本文件;表格解析委托 notice_line_table,字段归一化委托 notice_line_values。 """ from __future__ import annotations from typing import Any from app.services.shipping_notice.notice_line_constants import ( HEADER_SKIP_TOKENS, NOTICE_COLUMN_MAP, NOTICE_FIELD_LABELS, NOTICE_LINE_FIELDS, ) from app.services.shipping_notice.notice_line_table import ( parse_notice_table_rows, parse_notice_table_text, ) from app.services.shipping_notice.notice_line_values import ( extract_currency, map_notice_header, norm_header, normalize_currency, normalize_line_no, normalize_required_date, parse_number, ) from app.services.shipping_notice.reservation_id import ( extract_reservation_id, find_reservation_id_in_document, looks_like_reservation_id, is_valid_reservation_id, validated_reservation_id, ) # 向后兼容:旧代码/tests 仍可从 notice_lines 引用私有别名 _HEADER_SKIP_TOKENS = HEADER_SKIP_TOKENS _extract_currency = extract_currency _norm_header = norm_header _map_notice_header = map_notice_header _parse_number = parse_number def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None: """ 标准化单条发货通知订单行。 核心逻辑:校验 SKU 与数量必填项,统一字段别名、币种、交期和 Reservation ID,并在缺少 amount 时按单价回填。 Args: raw: 原始订单行字典,可包含多种字段别名。 Returns: dict[str, Any] | None: 归一化后的订单行;若缺少关键字段则返回 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", } line_no = normalize_line_no( raw.get("line_no") or raw.get("lineNo") or raw.get("item") or raw.get("item_no") or raw.get("itemNo") or raw.get("Item") or raw.get("Item No") ) if line_no: line["line_no"] = line_no reservation_id = extract_reservation_id( raw.get("reservation_id") or raw.get("reservationId") or raw.get("com_id") or raw.get("reservation_order") or raw.get("pr_number") or raw.get("prNumber") or raw.get("PR Number") ) if reservation_id: line["reservation_id"] = reservation_id evidence = raw.get("reservation_id_evidence") if isinstance(evidence, dict): line["reservation_id_evidence"] = dict(evidence) 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) currency = normalize_currency(raw.get("currency") or raw.get("Currency")) if not currency: currency = extract_currency( raw.get("unit_price"), raw.get("price"), raw.get("amount"), raw.get("total"), ) if currency: line["currency"] = currency required_date = normalize_required_date( raw.get("required_date") or raw.get("delivery_date") or raw.get("deliveryDate") or raw.get("eta") or raw.get("ETA") ) if required_date: line["required_date"] = required_date vendor_part_number = str( raw.get("vendor_part_number") or raw.get("vendorPartNumber") or raw.get("vendor_pn") or raw.get("supplier_part_number") or raw.get("supplierPartNumber") or "" ).strip() if vendor_part_number: line["vendor_part_number"] = vendor_part_number optional_aliases = { "po_number": ("po_number", "poNumber", "PO", "PO Number"), "allocation_id": ("allocation_id", "allocationId", "Allocation ID"), "source_type": ( "source_type", "sourceType", "Source Type", "hub_code", "hubCode", "Hub Code", "Hub", "HUB", ), "customer_sku": ("customer_sku", "customerSku", "allocated_hhpn", "Allocated HHPN"), } for field, aliases in optional_aliases.items(): value = next((str(raw.get(alias) or "").strip() for alias in aliases if raw.get(alias)), "") if value: line[field] = value 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]]: """ 批量标准化订单行列表。 核心逻辑:逐行调用 `normalize_notice_line`,自动过滤掉无效、缺 SKU 或缺数量的脏数据。 """ 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 adjudicate_notice_lines( lines: list[dict[str, Any]], *, raw_text: str = "", ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], str]: """ 对 LLM 候选订单行执行后端真值裁决,并输出可审计问题清单。 核心逻辑:先从保留列边界的原文解析结构证据;非法候选仅在同 SKU 唯一命中合法表格值时纠正, 否则清空并阻断。合法候选与明确表格证据冲突时保留候选但标记阻断,禁止静默覆盖。 Args: lines: 已完成基础标准化的 LLM/启发式候选行。 raw_text: 原始通知正文;仅 TSV/HTML 保留下来的明确列关系可作为自动纠错证据。 Returns: tuple: (裁决后的业务行、parse_issues、validation_status)。 """ evidence_lines = parse_notice_table_text(raw_text) if "\t" in str(raw_text or "") else [] evidence_by_sku: dict[str, list[dict[str, Any]]] = {} for evidence_line in evidence_lines: sku = str(evidence_line.get("sku") or "").strip() evidence = evidence_line.get("reservation_id_evidence") source_column = norm_header(evidence.get("source_column")) if isinstance(evidence, dict) else "" if sku and source_column and validated_reservation_id(evidence_line.get("reservation_id")): evidence_by_sku.setdefault(sku, []).append(evidence_line) adjudicated: list[dict[str, Any]] = [] issues: list[dict[str, Any]] = [] for index, source_line in enumerate(lines): line = dict(source_line) raw_candidate = str(line.get("reservation_id") or "").strip() candidate = validated_reservation_id(raw_candidate) line_sku = str(line.get("sku") or "").strip() line_vendor_part = str(line.get("vendor_part_number") or "").strip() matches = list(evidence_by_sku.get(line_sku, [])) if not matches: matches = [ item for candidates in evidence_by_sku.values() for item in candidates if ( str(item.get("vendor_part_number") or "").strip() and ( str(item.get("vendor_part_number") or "").strip() == line_vendor_part or str(item.get("vendor_part_number") or "").strip() in line_sku ) ) ] evidence_values = { validated_reservation_id(item.get("reservation_id")) for item in matches if validated_reservation_id(item.get("reservation_id")) } evidence_values.discard("") if candidate and evidence_values and candidate not in evidence_values: issues.append( { "line_index": index, "sku": line.get("sku"), "field": "reservation_id", "reason": "source_conflict", "severity": "blocking", "raw_value": raw_candidate, "evidence_values": sorted(evidence_values), } ) elif not candidate and len(evidence_values) == 1: resolved = next(iter(evidence_values)) line["reservation_id"] = resolved evidence_line = matches[0] evidence = evidence_line.get("reservation_id_evidence") or {} issues.append( { "line_index": index, "sku": line.get("sku"), "field": "reservation_id", "reason": "value_corrected", "severity": "info", "raw_value": raw_candidate, "resolved_value": resolved, "resolution_basis": f"email_table.{evidence.get('source_column') or 'Reservation ID'}", } ) elif not candidate: line.pop("reservation_id", None) issues.append( { "line_index": index, "sku": line.get("sku"), "field": "reservation_id", "reason": "missing" if not raw_candidate else "invalid_format", "severity": "blocking", "raw_value": raw_candidate, } ) else: line["reservation_id"] = candidate adjudicated.append(line) status = "needs_review" if any(item.get("severity") == "blocking" for item in issues) else "ready" return adjudicated, issues, status def enrich_notice_with_document_reservation( parsed: dict[str, Any], *, raw_text: str = "", ) -> dict[str, Any]: """ 用文档级 Reservation ID 回填缺失的订单行。 核心逻辑:优先从 parsed 字段中找 document-level Reservation ID,找不到再从原始文本中兜底提取。 """ doc_rid = "" for key in ( "reservation_id", "reservationId", "document_reservation_id", "pr_number", "prNumber", "PR Number", ): extracted = validated_reservation_id(parsed.get(key)) if extracted: doc_rid = extracted break if not doc_rid: doc_rid = find_reservation_id_in_document(raw_text) if not doc_rid: return parsed lines = parsed.get("lines") if not isinstance(lines, list): return parsed for line in lines: if not isinstance(line, dict): continue if not str(line.get("reservation_id") or "").strip(): line["reservation_id"] = doc_rid parsed["reservation_id"] = doc_rid parsed.pop("document_reservation_id", None) return parsed def enrich_notice_with_document_required_date(parsed: dict[str, Any]) -> dict[str, Any]: """用文档级 required_date 回填缺失的订单行交期。""" doc_date = normalize_required_date( parsed.get("required_date") or parsed.get("document_required_date") ) if not doc_date: return parsed lines = parsed.get("lines") if not isinstance(lines, list): return parsed has_line_dates = any( isinstance(line, dict) and str(line.get("required_date") or "").strip() for line in lines ) if not has_line_dates: parsed["required_date"] = doc_date for line in lines: if not isinstance(line, dict): continue if not str(line.get("required_date") or "").strip(): line["required_date"] = doc_date parsed.pop("document_required_date", None) return parsed def enrich_notice_with_document_currency(parsed: dict[str, Any]) -> dict[str, Any]: """用文档级币种回填缺失的订单行币种。""" doc_currency = normalize_currency( parsed.get("currency") or parsed.get("document_currency") ) if not doc_currency: return parsed lines = parsed.get("lines") if not isinstance(lines, list): return parsed has_line_currency = any( isinstance(line, dict) and str(line.get("currency") or "").strip() for line in lines ) if not has_line_currency: parsed["currency"] = doc_currency for line in lines: if not isinstance(line, dict): continue if not str(line.get("currency") or "").strip(): line["currency"] = doc_currency parsed.pop("document_currency", None) return parsed def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]: """ 生成订单行解析质量告警。 核心逻辑:检查 Reservation ID、价格字段等关键完整性,输出给前端/Agent 的提醒文本。 """ 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;当前匹配规则会阻断后续库存匹配," "若订单含 COM ID / Reservation Order 请返回解析阶段核对表头。" ) elif missing_reservation: warnings.append( f"部分订单行缺少 Reservation ID({len(missing_reservation)}/{len(lines)} 行)," "当前匹配规则会阻断后续库存匹配,请先修正解析结果。" ) invalid_reservation = [ line["sku"] for line in lines if str(line.get("reservation_id") or "").strip() and not is_valid_reservation_id(line.get("reservation_id")) ] if invalid_reservation: warnings.append( f"{len(invalid_reservation)} 行 Reservation ID 不满足业务格式契约,请核对来源列与原始值。" ) 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: """ 评估订单行解析完整度。 核心逻辑:按 SKU、数量、Reservation ID、价格等字段覆盖率计算 0~1 分数。 """ 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 is_valid_reservation_id(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) __all__ = [ "NOTICE_COLUMN_MAP", "NOTICE_FIELD_LABELS", "NOTICE_LINE_FIELDS", "enrich_notice_with_document_currency", "enrich_notice_with_document_required_date", "enrich_notice_with_document_reservation", "adjudicate_notice_lines", "normalize_notice_line", "normalize_notice_lines", "notice_parse_completeness", "parse_notice_table_rows", "parse_notice_table_text", "validate_notice_lines", ]