""" 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 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_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, ) # 仅保留无业务配置的值工具私有别名;表头业务别名不再从本模块导出。 _extract_currency = extract_currency _norm_header = norm_header _map_notice_header = map_notice_header _parse_number = parse_number def split_part_number_tokens(value: Any) -> list[str]: """ 将复合料号文本拆成稳定的原子候选 token。 核心逻辑:仅把 `/` 视为业务确认的组合分隔符,去除空段和首尾空白;本函数不猜测 token 角色。 Args: value: 原始表格单元格或 LLM 候选值。 Returns: 保持原顺序且去重的非空 token;无值时返回空数组。 """ tokens: list[str] = [] for part in str(value or '').split('/'): token = part.strip() if token and token not in tokens: tokens.append(token) return tokens def resolve_composite_part_numbers(value: Any) -> dict[str, str]: """ 按已冻结 TEMP 业务规则解析二段复合料号。 核心逻辑:仅当恰有两个原子 token 且其中一个以 TEMP- 开头时,确定 TEMP 为客户料号、另一段为内部料号; 其余组合保持未解析,交由字段冲突流程处理。 Args: value: 可能包含 `/` 的原始料号文本。 Returns: 可确定时返回 part_number/customer_part_number;否则返回空对象。 """ tokens = split_part_number_tokens(value) if len(tokens) != 2: return {} customer_tokens = [token for token in tokens if token.upper().startswith('TEMP-')] if len(customer_tokens) != 1: return {} customer_part_number = customer_tokens[0] part_number = next(token for token in tokens if token != customer_part_number) return { 'part_number': part_number, 'customer_part_number': customer_part_number, } def non_atomic_part_number_field(raw: dict[str, Any] | None) -> str | None: """ 检查订单行三类料号是否违反原子值契约。 核心逻辑:内部料号仅允许命中已冻结 TEMP 二段拆分规则;客户料号与 AWS 料号出现 `/` 时直接返回字段名。 Args: raw: 待检查的原始订单行。 Returns: 首个非法字段名;全部合法时返回 None。 """ if not isinstance(raw, dict): return None raw_part_number = str(raw.get("part_number") or "").strip() if "/" in raw_part_number and not resolve_composite_part_numbers(raw_part_number): return "part_number" for field in ("customer_part_number", "aws_part_number"): if "/" in str(raw.get(field) or "").strip(): return field return None def _canonicalize_schema_line_aliases( raw: dict[str, Any], *, schema_definition: dict[str, Any] | None, ) -> dict[str, Any]: """ 以本次冻结 Schema 的明细字段别名将输入键归一化为 field_code。 核心逻辑:字段代码优先于别名;同一原始行的多个别名同时映射一个字段时不静默选值, 仅保留已存在的字段代码。无 Schema 时只接受调用方提供的正式字段代码。 Args: raw: 原始订单行,键可能为邮件/PDF 表头或正式字段代码。 schema_definition: 本次 Run 冻结的完整订单 Schema。 Returns: 使用正式 field_code 作为键的订单行副本。 """ canonical = dict(raw) if not schema_definition: return canonical aliases: dict[str, str] = {} ambiguous_aliases: set[str] = set() for field in schema_definition.get('fields') or []: if not isinstance(field, dict) or not field.get('enabled', True): continue if str(field.get('scope') or 'line').strip().lower() != 'line': continue field_code = str(field.get('field_code') or '').strip() if not field_code: continue for name in (field_code, field.get('display_name'), *(field.get('aliases') or [])): normalized = norm_header(name) if not normalized: continue previous = aliases.get(normalized) if previous is None: aliases[normalized] = field_code elif previous != field_code: ambiguous_aliases.add(normalized) mapped_values: dict[str, Any] = {} ambiguous_codes: set[str] = set() for name, value in raw.items(): normalized_name = norm_header(name) field_code = None if normalized_name in ambiguous_aliases else aliases.get(normalized_name) if not field_code or field_code in canonical: continue if field_code in mapped_values: ambiguous_codes.add(field_code) continue mapped_values[field_code] = value for field_code, value in mapped_values.items(): if field_code not in ambiguous_codes: canonical[field_code] = value return canonical def normalize_notice_line( raw: dict[str, Any] | None, *, schema_definition: dict[str, Any] | None = None, ) -> dict[str, Any] | None: """ 标准化单条发货通知订单行。 核心逻辑:校验原子 part_number 与数量必填项,统一币种、交期和 Reservation ID,并在缺少 amount 时按单价回填。 Args: raw: 原始订单行字典,可包含多种字段别名。 schema_definition: 冻结 Schema;提供时仅保留其中已启用的字段,且不注入默认 UOM。 Returns: dict[str, Any] | None: 归一化后的订单行;若缺少关键字段则返回 None。 """ if not isinstance(raw, dict): return None raw = _canonicalize_schema_line_aliases(raw, schema_definition=schema_definition) if non_atomic_part_number_field(raw): return None raw_part_number = str(raw.get("part_number") or "").strip() composite = resolve_composite_part_numbers(raw_part_number) part_number = composite.get('part_number') or raw_part_number if not part_number or "/" in part_number: return None qty = parse_number(raw.get("qty")) if qty is None or qty <= 0: return None enabled_fields = { str(item.get("field_code") or "").strip() for item in (schema_definition or {}).get("fields", []) if isinstance(item, dict) and item.get("enabled", True) } field_enabled = lambda code: not schema_definition or code in enabled_fields line: dict[str, Any] = {"part_number": part_number, "qty": qty} raw_uom = str(raw.get("uom") or "").strip() if raw_uom and field_enabled("uom"): line["uom"] = raw_uom reservation_id = extract_reservation_id(raw.get("reservation_id")) if reservation_id and field_enabled("reservation_id"): line["reservation_id"] = reservation_id evidence = raw.get("reservation_id_evidence") if isinstance(evidence, dict) and field_enabled("reservation_id"): line["reservation_id_evidence"] = dict(evidence) unit_price = parse_number(raw.get("unit_price")) if unit_price is not None and field_enabled("unit_price"): line["unit_price"] = unit_price amount = parse_number(raw.get("amount")) # Schema 使用 canonical line_amount_with_tax;内部通知行仍保留 amount 键供下游消费。 if amount is not None and field_enabled("line_amount_with_tax"): line["amount"] = amount elif unit_price is not None and field_enabled("line_amount_with_tax"): line["amount"] = round(unit_price * qty, 4) currency = normalize_currency(raw.get("currency")) if not currency: currency = extract_currency( raw.get("unit_price"), raw.get("amount"), ) if currency and field_enabled("currency"): line["currency"] = currency required_date = normalize_required_date(raw.get("required_date")) if required_date and field_enabled("required_date"): line["required_date"] = required_date optional_fields = ( "po_number", "allocation_id", "inventory_source_hint", "customer_part_number", "aws_part_number", "line_remark", ) if composite.get('customer_part_number'): if field_enabled('customer_part_number'): line['customer_part_number'] = composite['customer_part_number'] for field in optional_fields: value = str(raw.get(field) or "").strip() if value and field_enabled(field): line[field] = value return line def normalize_notice_lines( lines: list[Any] | None, *, schema_definition: dict[str, Any] | None = None, ) -> list[dict[str, Any]]: """ 批量标准化订单行列表。 核心逻辑:逐行调用 `normalize_notice_line`,自动过滤缺原子 part_number 或缺数量的脏数据。 """ 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, schema_definition=schema_definition, ) if parsed: normalized.append(parsed) return normalized def adjudicate_notice_lines( lines: list[dict[str, Any]], *, raw_text: str = "", schema_definition: dict[str, Any] | None = None, ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], str]: """ 对 LLM 候选订单行执行后端真值裁决,并输出可审计问题清单。 核心逻辑:先从保留列边界的原文解析结构证据;非法候选仅在同 part_number 唯一命中合法表格值时纠正, 否则清空并阻断。合法候选与明确表格证据冲突时保留候选但标记阻断,禁止静默覆盖。 Args: lines: 已完成基础标准化的 LLM/启发式候选行。 raw_text: 原始通知正文;仅 TSV/HTML 保留下来的明确列关系可作为自动纠错证据。 schema_definition: 本次处理明确选择的完整订单 Schema;缺失时不生成表格纠错证据。 Returns: tuple: (裁决后的业务行、parse_issues、validation_status)。 """ if schema_definition and "\t" in str(raw_text or ""): from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract evidence_lines = parse_notice_table_text( raw_text, contract=compile_table_header_contract(schema_definition), ) else: evidence_lines = [] evidence_by_part_number: dict[str, list[dict[str, Any]]] = {} for evidence_line in evidence_lines: part_number = str(evidence_line.get("part_number") or "").strip() evidence = evidence_line.get("reservation_id_evidence") source_column = norm_header(evidence.get("source_column")) if isinstance(evidence, dict) else "" if part_number and source_column and validated_reservation_id(evidence_line.get("reservation_id")): evidence_by_part_number.setdefault(part_number, []).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_part_number = str(line.get("part_number") or "").strip() matches = list(evidence_by_part_number.get(line_part_number, [])) 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, "part_number": line.get("part_number"), "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, "part_number": line.get("part_number"), "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, "part_number": line.get("part_number"), "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("未解析到有效订单行(需至少包含内部料号与需求数量)。") return warnings missing_reservation = [line["part_number"] 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["part_number"] 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: """ 评估订单行解析完整度。 核心逻辑:按内部料号、数量、Reservation ID、价格等字段覆盖率计算 0~1 分数。 """ if not lines: return 0.0 scores: list[float] = [] for line in lines: item = 0.0 if line.get("part_number"): 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_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", "non_atomic_part_number_field", "notice_parse_completeness", "parse_notice_table_rows", "parse_notice_table_text", "resolve_composite_part_numbers", "split_part_number_tokens", "validate_notice_lines", ]