feat(file-check): 更新文件检核工具 API Key 配置及相关文档

This commit is contained in:
hugo committed 2026-06-17 22:29:15 +08:00
1 parent 634dee4b81
commit 55cf7ff734
74 files changed
+1525 -1182

No files matched your search

@@ -1,436 +1,46 @@
"""
services/shipping_notice/notice_lines.py
用途:标准化发货通知订单行,并从文本/表格中抽取可用于后续库存匹配的行级结构化数据。
依赖:reservation_id、inventory_snapshot 的表格转行工具、正则与字段映射常量。
逻辑:由 extract/task_workflow 等上游模块调用本文件完成订单行归一化,再把结果交给匹配、人工更正与摘要生成链路。
用途:发货通知订单行的标准化、文档级回填、质量校验与完整度评估(对外统一入口)。
依赖:notice_line_constants、notice_line_values、notice_line_table、reservation_id。
逻辑:由 extract/task_workflow 等上游模块调用本文件;表格解析委托 notice_line_table,字段归一化委托 notice_line_values。
"""
from __future__ import annotations
import re
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,
normalize_reservation_id,
)
NOTICE_LINE_FIELDS = (
"line_no",
"sku",
"qty",
"unit_price",
"amount",
"currency",
"reservation_id",
"required_date",
"vendor_part_number",
"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
"项次": "line_no",
"line_no": "line_no",
"Line No": "line_no",
"Line Number": "line_no",
"Line #": "line_no",
"Line": "line_no",
"Item": "line_no",
"Item No": "line_no",
"Item Number": "line_no",
# 需求数量
"数量": "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",
# 币种
"Currency": "currency",
"currency": "currency",
"Curr": "currency",
"CCY": "currency",
"币种": "currency",
"币别": "currency",
# 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",
"PR Number": "reservation_id",
"PR No": "reservation_id",
"PR#": "reservation_id",
# 交货日期
"Required Date": "required_date",
"Delivery Date": "required_date",
"required_date": "required_date",
"ETA": "required_date",
"交期": "required_date",
"交货日期": "required_date",
"要求交期": "required_date",
"Required Delivery Date": "required_date",
# 供应商料号
"Vendor Part Number": "vendor_part_number",
"Vendor Part No": "vendor_part_number",
"Vendor PN": "vendor_part_number",
"vendor_part_number": "vendor_part_number",
"Supplier Part No": "vendor_part_number",
"Supplier Part Number": "vendor_part_number",
"MPN": "vendor_part_number",
"供应商料号": "vendor_part_number",
# 单位
"单位": "uom",
"UOM": "uom",
"uom": "uom",
"Unit": "uom",
}
NOTICE_FIELD_LABELS = {
"line_no": "项次 / Item / Line No",
"sku": "SKU / 料号",
"qty": "需求数量",
"unit_price": "单价",
"amount": "金额",
"currency": "币种",
"reservation_id": "Reservation ID(常见纯数字,如 1000140351)",
"required_date": "要求交期 / 交货日期",
"vendor_part_number": "供应商料号",
}
_HEADER_SKIP_TOKENS = {
"sku",
"料号",
"aws sku",
"qty",
"quantity",
"数量",
"reservation id",
"com id",
"单价",
"unit price",
"金额",
"amount",
"currency",
"币种",
"line no",
"item no",
"项次",
}
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 _normalize_line_no(value: Any) -> str:
if value is None:
return ""
if isinstance(value, float) and value.is_integer():
return str(int(value))
text = str(value).strip()
if not text:
return ""
if text.lower() in _HEADER_SKIP_TOKENS:
return ""
num = _parse_number(text)
if num is not None and num == int(num):
compact = text.replace(",", "").replace(",", "")
if re.fullmatch(r"\d+(?:\.0+)?", compact):
return str(int(num))
return text
def _normalize_required_date(value: Any) -> str:
text = str(value or "").strip()
if not text:
return ""
m = re.match(r"^(\d{4})[/.-](\d{1,2})[/.-](\d{1,2})$", text)
if m:
return f"{m.group(1)}-{int(m.group(2)):02d}-{int(m.group(3)):02d}"
return text
_KNOWN_CURRENCY_CODES = frozenset(
{
"USD",
"EUR",
"GBP",
"JPY",
"CNY",
"RMB",
"HKD",
"TWD",
"SGD",
"AUD",
"CAD",
"KRW",
"INR",
"CHF",
"SEK",
"NOK",
"DKK",
"MYR",
"THB",
"VND",
"PHP",
"IDR",
"MXN",
"BRL",
"NZD",
}
)
_CURRENCY_ALIASES = {
"人民币": "CNY",
"美元": "USD",
"欧元": "EUR",
"英镑": "GBP",
"日元": "JPY",
"港币": "HKD",
"港元": "HKD",
"新台币": "TWD",
"新加坡元": "SGD",
"澳元": "AUD",
"加元": "CAD",
}
def _normalize_currency(value: Any) -> str:
text = str(value or "").strip()
if not text:
return ""
upper = text.upper()
if upper in _KNOWN_CURRENCY_CODES:
return "CNY" if upper == "RMB" else upper
if text in _CURRENCY_ALIASES:
return _CURRENCY_ALIASES[text]
return ""
def _extract_currency(*values: Any) -> str:
for value in values:
text = str(value or "").strip()
if not text:
continue
normalized = _normalize_currency(text)
if normalized:
return normalized
if text.startswith("$"):
return "USD"
if text.startswith("¥") or text.startswith("¥"):
return "CNY"
match = re.search(r"\b([A-Z]{3})\b", text.upper())
if match and match.group(1) in _KNOWN_CURRENCY_CODES:
code = match.group(1)
return "CNY" if code == "RMB" else code
return ""
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()
match = re.search(r"[-+]?\d+(?:\.\d+)?", text)
if not match:
return None
try:
return float(match.group(0))
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 extract_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_line_no = columns.get("line_no")
if idx_line_no is not None:
line_no = _normalize_line_no(_cell(row, idx_line_no))
skip_indices.add(idx_line_no)
if line_no:
parsed["line_no"] = line_no
idx_res = columns.get("reservation_id")
reservation_id = ""
if idx_res is not None:
reservation_id = extract_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")
price_cell = None
if idx_price is not None:
price_cell = _cell(row, idx_price)
unit_price = _parse_number(price_cell)
if unit_price is not None:
parsed["unit_price"] = unit_price
idx_amount = columns.get("amount")
amount_cell = None
if idx_amount is not None:
amount_cell = _cell(row, idx_amount)
amount = _parse_number(amount_cell)
if amount is not None:
parsed["amount"] = amount
idx_currency = columns.get("currency")
currency = _extract_currency(
_cell(row, idx_currency) if idx_currency is not None else None,
price_cell,
amount_cell,
)
if currency:
parsed["currency"] = currency
idx_uom = columns.get("uom")
if idx_uom is not None:
uom = str(_cell(row, idx_uom) or "").strip()
if uom:
parsed["uom"] = uom
idx_required_date = columns.get("required_date")
if idx_required_date is not None:
required_date = _normalize_required_date(_cell(row, idx_required_date))
if required_date:
parsed["required_date"] = required_date
idx_vendor_part = columns.get("vendor_part_number")
if idx_vendor_part is not None:
vendor_part_number = str(_cell(row, idx_vendor_part) or "").strip()
if vendor_part_number:
parsed["vendor_part_number"] = vendor_part_number
# 若仅有 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
# 向后兼容:旧代码/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:
@@ -451,7 +61,7 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
if not sku:
return None
qty = _parse_number(raw.get("qty") if raw.get("qty") is not None else raw.get("quantity"))
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
@@ -461,7 +71,7 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
"uom": str(raw.get("uom") or "EA").strip() or "EA",
}
line_no = _normalize_line_no(
line_no = normalize_line_no(
raw.get("line_no")
or raw.get("lineNo")
or raw.get("item")
@@ -485,19 +95,19 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
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"))
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"))
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"))
currency = normalize_currency(raw.get("currency") or raw.get("Currency"))
if not currency:
currency = _extract_currency(
currency = extract_currency(
raw.get("unit_price"),
raw.get("price"),
raw.get("amount"),
@@ -506,7 +116,7 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
if currency:
line["currency"] = currency
required_date = _normalize_required_date(
required_date = normalize_required_date(
raw.get("required_date")
or raw.get("delivery_date")
or raw.get("deliveryDate")
@@ -539,11 +149,6 @@ def normalize_notice_lines(lines: list[Any] | None) -> list[dict[str, Any]]:
批量标准化订单行列表。
核心逻辑:逐行调用 `normalize_notice_line`,自动过滤掉无效、缺 SKU 或缺数量的脏数据。
Args:
lines: 原始订单行列表。
Returns:
list[dict[str, Any]]: 标准化后的有效订单行集合。
"""
if not isinstance(lines, list):
return []
@@ -564,12 +169,6 @@ def enrich_notice_with_document_reservation(
用文档级 Reservation ID 回填缺失的订单行。
核心逻辑:优先从 parsed 字段中找 document-level Reservation ID,找不到再从原始文本中兜底提取。
Args:
parsed: 已解析出的发货通知结构。
raw_text: 原始发货通知文本,用于补充文档级 Reservation ID。
Returns:
dict[str, Any]: 已完成文档级 Reservation ID 回填的解析结果。
"""
doc_rid = ""
for key in (
@@ -607,17 +206,8 @@ def enrich_notice_with_document_reservation(
def enrich_notice_with_document_required_date(parsed: dict[str, Any]) -> dict[str, Any]:
"""
用文档级 required_date 回填缺失的订单行交期。
核心逻辑:统一格式化文档级日期,并在订单行未给出独立交期时逐行补齐。
Args:
parsed: 已解析出的发货通知结构。
Returns:
dict[str, Any]: 已完成文档级交期回填的解析结果。
"""
doc_date = _normalize_required_date(
"""用文档级 required_date 回填缺失的订单行交期。"""
doc_date = normalize_required_date(
parsed.get("required_date") or parsed.get("document_required_date")
)
if not doc_date:
@@ -644,17 +234,8 @@ def enrich_notice_with_document_required_date(parsed: dict[str, Any]) -> dict[st
def enrich_notice_with_document_currency(parsed: dict[str, Any]) -> dict[str, Any]:
"""
用文档级币种回填缺失的订单行币种。
核心逻辑:统一币种代码,并在订单行未给出币种时沿用文档级币种。
Args:
parsed: 已解析出的发货通知结构。
Returns:
dict[str, Any]: 已完成文档级币种回填的解析结果。
"""
doc_currency = _normalize_currency(
"""用文档级币种回填缺失的订单行币种。"""
doc_currency = normalize_currency(
parsed.get("currency") or parsed.get("document_currency")
)
if not doc_currency:
@@ -680,108 +261,11 @@ def enrich_notice_with_document_currency(parsed: dict[str, Any]) -> dict[str, An
return parsed
def parse_notice_table_text(raw_text: str) -> list[dict[str, Any]]:
"""
从发货通知原始文本中的表格片段解析订单行。
核心逻辑:先借助 inventory_snapshot 的通用表格拆行工具得到二维表,再识别表头并解析数据行。
Args:
raw_text: 原始发货通知文本,通常来自 PDF/OCR/邮件正文。
Returns:
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 :]
lines = parse_notice_table_rows(header, data_rows)
doc_rid = find_reservation_id_in_document(text)
if doc_rid:
for line in lines:
if not line.get("reservation_id"):
line["reservation_id"] = doc_rid
return lines
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]]:
"""
按表头定义解析发货通知表格数据行。
核心逻辑:根据 headers 推断列映射,仅在识别到有效表头时逐行提取 SKU、数量、金额等字段。
Args:
headers: 表头行。
data_rows: 表头之后的数据行集合。
Returns:
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 validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]:
"""
生成订单行解析质量告警。
核心逻辑:检查 Reservation ID、价格字段等关键完整性,输出给前端/Agent 的提醒文本。
Args:
lines: 已标准化的订单行列表。
Returns:
list[str]: 告警文案列表,为空表示未发现明显问题。
"""
warnings: list[str] = []
if not lines:
@@ -791,13 +275,13 @@ def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]:
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 请核对表头。"
"订单行未解析到 Reservation ID;当前匹配规则会阻断后续库存匹配,"
"若订单含 COM ID / Reservation Order 请返回解析阶段核对表头。"
)
elif missing_reservation:
warnings.append(
f"部分订单行缺少 Reservation ID({len(missing_reservation)}/{len(lines)} 行),"
"这些行将按 SKU 汇总库存比对。"
"当前匹配规则会阻断后续库存匹配,请先修正解析结果。"
)
invalid_reservation = [
@@ -824,11 +308,6 @@ def notice_parse_completeness(lines: list[dict[str, Any]]) -> float:
评估订单行解析完整度。
核心逻辑:按 SKU、数量、Reservation ID、价格等字段覆盖率计算 0~1 分数。
Args:
lines: 已标准化的订单行列表。
Returns:
float: 0~1 之间的解析完整度分数。
"""
if not lines:
return 0.0
@@ -845,3 +324,19 @@ def notice_parse_completeness(lines: list[dict[str, Any]]) -> float:
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",
"normalize_notice_line",
"normalize_notice_lines",
"notice_parse_completeness",
"parse_notice_table_rows",
"parse_notice_table_text",
"validate_notice_lines",
]