把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与 枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa 持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀, 上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。 Co-authored-by: Cursor <cursoragent@cursor.com>
780 lines
29 KiB
Python
780 lines
29 KiB
Python
"""
|
||
services/shipping_notice/onhand_snapshot.py
|
||
|
||
用途:解析库存 Excel/文本快照,抽取表头、库存行与字段对齐预览,为库存映射与匹配流程提供基础数据。
|
||
依赖:openpyxl、xlrd、reservation_id、Flask current_app 配置、Path 文件操作。
|
||
逻辑:由 onhand_workflow、onhand_mapping_workflow 等上游模块调用本文件读取库存附件,再把解析结果传给字段映射确认和库存匹配链路。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import re
|
||
import shutil
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from flask import current_app
|
||
from openpyxl import load_workbook
|
||
|
||
from app.services.shipping_notice.reservation_id import normalize_reservation_id, validated_reservation_id
|
||
|
||
|
||
# 默认列映射:Supplier Sku 是内部主匹配料号;AWS Sku 仅作可选追溯字段。
|
||
DEFAULT_COLUMN_MAP = {
|
||
# 内部料号
|
||
"Supplier Sku": "part_number",
|
||
"Supplier SKU": "part_number",
|
||
"Supplier Part Number": "part_number",
|
||
"Supplier Part No": "part_number",
|
||
"料号": "part_number",
|
||
"SKU": "part_number",
|
||
"sku": "part_number",
|
||
"SKU#": "part_number",
|
||
"Part Number": "part_number",
|
||
"Part No": "part_number",
|
||
"Part No.": "part_number",
|
||
"P/N": "part_number",
|
||
"PN": "part_number",
|
||
# AWS 追溯料号
|
||
"AWS Sku": "aws_part_number",
|
||
"AWS SKU": "aws_part_number",
|
||
"Aws Sku": "aws_part_number",
|
||
"AWS SKU#": "aws_part_number",
|
||
"AWS Sku#": "aws_part_number",
|
||
# Reservation
|
||
"Reservation ID": "reservation_id",
|
||
"Reservation Id": "reservation_id",
|
||
"reservation_id": "reservation_id",
|
||
"COM ID": "reservation_id",
|
||
"Reservation Order": "reservation_id",
|
||
# Quantity — 优先 Qty Available,其次 Qty
|
||
"Qty Available": "available_qty",
|
||
"Available": "available_qty",
|
||
"Avail Qty": "available_qty",
|
||
"可用数量": "available_qty",
|
||
"可用量": "available_qty",
|
||
"available_qty": "available_qty",
|
||
"库存": "available_qty",
|
||
"On Hand": "available_qty",
|
||
"OnHand": "available_qty",
|
||
"On Hand Qty": "available_qty",
|
||
"OnHand Qty": "available_qty",
|
||
"Qty On Hand": "available_qty",
|
||
"Qty": "qty",
|
||
"qty": "qty",
|
||
"数量": "qty",
|
||
# Warehouse:动态 Source 必须保留行级 Warehouse,不能只记录整个文件的单一值。
|
||
"Warehouse ID": "warehouse_id",
|
||
"Warehouse": "warehouse_id",
|
||
"Warehouse Code": "warehouse_id",
|
||
"WH ID": "warehouse_id",
|
||
# ODM
|
||
"ODM ID": "odm_id",
|
||
"ODM Id": "odm_id",
|
||
"ODM Code": "odm_id",
|
||
"Ship to ODM Code": "odm_id",
|
||
"Ship To ODM Code": "odm_id",
|
||
}
|
||
|
||
_RESERVATION_HEADER_PRIORITY = (
|
||
"reservation_id",
|
||
"Reservation ID",
|
||
"COM ID",
|
||
"Reservation Order",
|
||
)
|
||
|
||
|
||
def _column_map() -> dict[str, str]:
|
||
raw = current_app.config.get("FREIGHT_INVENTORY_COLUMN_MAP")
|
||
if isinstance(raw, dict) and raw:
|
||
return {str(k): str(v) for k, v in raw.items()}
|
||
if isinstance(raw, str) and raw.strip():
|
||
try:
|
||
parsed = json.loads(raw)
|
||
if isinstance(parsed, dict):
|
||
return {str(k): str(v) for k, v in parsed.items()}
|
||
except json.JSONDecodeError:
|
||
pass
|
||
return DEFAULT_COLUMN_MAP
|
||
|
||
|
||
def _normalize_ascii_key(text: str) -> str:
|
||
raw = str(text or "").strip().lower()
|
||
if not raw:
|
||
return ""
|
||
return re.sub(r"[^a-z0-9]+", "", raw)
|
||
|
||
|
||
def _map_header(header: str, col_map: dict[str, str]) -> str | None:
|
||
text = str(header or "").strip()
|
||
if not text:
|
||
return None
|
||
if text in col_map:
|
||
return col_map[text]
|
||
lower = text.lower()
|
||
for key, value in col_map.items():
|
||
if key.lower() == lower:
|
||
return value
|
||
norm = _normalize_ascii_key(text)
|
||
if not norm:
|
||
return None
|
||
norm_map = {_normalize_ascii_key(k): v for k, v in col_map.items() if _normalize_ascii_key(k)}
|
||
return norm_map.get(norm)
|
||
return None
|
||
|
||
|
||
def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> dict[str, int | None]:
|
||
idx_part_number = idx_aws_part_number = idx_reservation = idx_available = idx_qty = idx_odm = idx_warehouse = None
|
||
for i, h in enumerate(headers):
|
||
mapped = _map_header(h, col_map)
|
||
if mapped == "part_number" and idx_part_number is None:
|
||
idx_part_number = i
|
||
elif mapped == "aws_part_number" and idx_aws_part_number is None:
|
||
idx_aws_part_number = i
|
||
elif mapped == "reservation_id" and idx_reservation is None:
|
||
idx_reservation = i
|
||
elif mapped == "available_qty" and idx_available is None:
|
||
idx_available = i
|
||
elif mapped == "qty" and idx_qty is None:
|
||
idx_qty = i
|
||
elif mapped == "odm_id" and idx_odm is None:
|
||
idx_odm = i
|
||
elif mapped == "warehouse_id" and idx_warehouse is None:
|
||
idx_warehouse = i
|
||
|
||
# 若 reservation 列未命中,按 AWS 模板常见列名再试
|
||
if idx_reservation is None:
|
||
for i, h in enumerate(headers):
|
||
norm = str(h or "").strip().lower()
|
||
if norm in {"com id", "reservation order", "reservation id"}:
|
||
idx_reservation = i
|
||
break
|
||
|
||
return {
|
||
"part_number": idx_part_number,
|
||
"aws_part_number": idx_aws_part_number,
|
||
"reservation_id": idx_reservation,
|
||
"available_qty": idx_available,
|
||
"qty": idx_qty,
|
||
"odm_id": idx_odm,
|
||
"warehouse_id": idx_warehouse,
|
||
}
|
||
|
||
|
||
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_qty(value: Any) -> float:
|
||
try:
|
||
return float(str(value).replace(",", "").strip())
|
||
except (TypeError, ValueError):
|
||
return 0.0
|
||
|
||
|
||
def _normalize_inventory_row(
|
||
row: list[Any] | tuple[Any, ...],
|
||
columns: dict[str, int | None],
|
||
*,
|
||
default_part_number_index: int | None = None,
|
||
default_qty_index: int = 1,
|
||
configured_mapping: bool = False,
|
||
) -> dict[str, Any] | None:
|
||
# Published profiles use inventory field IDs as row keys. Field purpose and
|
||
# value type come from the user-maintained catalog, never from a fixed code.
|
||
if configured_mapping and columns and all(str(field_id).isdigit() for field_id in columns):
|
||
from app.models import FreightRpaOnhandField
|
||
|
||
field_ids = {int(field_id) for field_id in columns if str(field_id).isdigit()}
|
||
catalog = {
|
||
str(item.id): item
|
||
for item in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(field_ids)).all()
|
||
}
|
||
parsed = {
|
||
field_id: _cell(row, index)
|
||
for field_id, index in columns.items()
|
||
if index is not None and _cell(row, index) not in (None, '')
|
||
}
|
||
match_fields = [field_id for field_id, item in catalog.items() if item.usage_type == 'match_identity']
|
||
if not any(str(parsed.get(field_id) or '').strip() for field_id in match_fields):
|
||
return None
|
||
for field_id, value in list(parsed.items()):
|
||
field = catalog.get(field_id)
|
||
if field is None:
|
||
continue
|
||
if field.value_type in {'integer', 'decimal'}:
|
||
parsed[field_id] = _parse_qty(value)
|
||
elif field.value_type == 'date':
|
||
parsed[field_id] = value.isoformat() if hasattr(value, 'isoformat') else str(value).strip()
|
||
else:
|
||
parsed[field_id] = str(value).strip()
|
||
# 正式运行快照对外统一 canonical 字段;同时保留字段 ID 供审计和旧 Profile 回放。
|
||
canonical_by_code = {
|
||
'part_number': 'part_number',
|
||
'reservation_id': 'reservation_id',
|
||
'available_qty': 'available_qty',
|
||
'qty': 'available_qty',
|
||
'unit': 'uom',
|
||
'warehouse_id': 'warehouse_id',
|
||
'warehouse_code': 'warehouse_id',
|
||
}
|
||
for field_id, field in catalog.items():
|
||
target = canonical_by_code.get(str(field.field_code or '').strip())
|
||
if target and parsed.get(field_id) not in (None, ''):
|
||
parsed[target] = parsed[field_id]
|
||
if 'reservation_id' in parsed:
|
||
parsed['reservation_id'] = validated_reservation_id(parsed['reservation_id'])
|
||
if 'part_number' in parsed:
|
||
parsed['part_number'] = str(parsed['part_number'] or '').strip()
|
||
if 'available_qty' in parsed:
|
||
parsed['available_qty'] = _parse_qty(parsed['available_qty'])
|
||
return parsed
|
||
|
||
idx_part_number = columns.get("part_number")
|
||
if idx_part_number is None:
|
||
idx_part_number = default_part_number_index
|
||
if idx_part_number is None:
|
||
return None
|
||
part_number = str(_cell(row, idx_part_number) or "").strip()
|
||
if not part_number:
|
||
return None
|
||
|
||
skip_tokens = {
|
||
"part_number",
|
||
"supplier sku",
|
||
"料号",
|
||
"qty",
|
||
"qty available",
|
||
"可用数量",
|
||
"reservation id",
|
||
"com id",
|
||
}
|
||
if part_number.lower() in skip_tokens:
|
||
return None
|
||
|
||
reservation_id = ""
|
||
idx_res = columns.get("reservation_id")
|
||
if idx_res is not None:
|
||
reservation_id = validated_reservation_id(_cell(row, idx_res))
|
||
|
||
idx_avail = columns.get("available_qty")
|
||
idx_qty = columns.get("qty")
|
||
if idx_avail is not None:
|
||
available_qty = _parse_qty(_cell(row, idx_avail))
|
||
elif idx_qty is not None:
|
||
available_qty = _parse_qty(_cell(row, idx_qty))
|
||
else:
|
||
available_qty = _parse_qty(_cell(row, default_qty_index))
|
||
|
||
parsed: dict[str, Any] = {
|
||
"part_number": part_number,
|
||
"available_qty": available_qty,
|
||
}
|
||
idx_aws = columns.get("aws_part_number")
|
||
if idx_aws is not None:
|
||
aws_part_number = str(_cell(row, idx_aws) or "").strip()
|
||
if aws_part_number:
|
||
parsed["aws_part_number"] = aws_part_number
|
||
if reservation_id:
|
||
parsed["reservation_id"] = reservation_id
|
||
idx_odm = columns.get("odm_id")
|
||
if idx_odm is not None:
|
||
odm_id = str(_cell(row, idx_odm) or "").strip()
|
||
if odm_id:
|
||
parsed["odm_id"] = odm_id
|
||
idx_warehouse = columns.get("warehouse_id")
|
||
if idx_warehouse is not None:
|
||
warehouse_id = str(_cell(row, idx_warehouse) or "").strip().upper()
|
||
if warehouse_id:
|
||
parsed["warehouse_id"] = warehouse_id
|
||
return parsed
|
||
|
||
|
||
def _score_header_candidate(cells: list[Any]) -> int:
|
||
"""按通用表格结构给候选表头评分,固定库存词典只作为旧临时链加分项。"""
|
||
headers = [str(c or "").strip() for c in cells]
|
||
non_empty = [h for h in headers if h]
|
||
if len(non_empty) < 2:
|
||
return 0
|
||
|
||
col_map = _column_map()
|
||
mapped_fields: set[str] = set()
|
||
for h in headers:
|
||
mapped = _map_header(h, col_map)
|
||
if mapped:
|
||
mapped_fields.add(mapped)
|
||
|
||
text_cells = sum(1 for value in non_empty if isinstance(value, str) and str(value).strip())
|
||
unique_cells = len({str(value).strip().casefold() for value in non_empty})
|
||
score = len(non_empty) + text_cells + unique_cells + len(mapped_fields) * 10
|
||
if "part_number" in mapped_fields and ("available_qty" in mapped_fields or "qty" in mapped_fields):
|
||
score += 30
|
||
return score
|
||
|
||
|
||
def find_inventory_header_row_index(rows: list[list[Any]], *, max_scan: int = 40) -> int:
|
||
"""在前 max_scan 行中选取最像库存表头的行索引(跳过标题/空行)。"""
|
||
best_idx = 0
|
||
best_score = 0
|
||
for i, row in enumerate(rows[:max_scan]):
|
||
score = _score_header_candidate(list(row))
|
||
if score > best_score:
|
||
best_score = score
|
||
best_idx = i
|
||
return best_idx if best_score > 0 else 0
|
||
|
||
|
||
def _load_excel_rows(
|
||
path: Path, *, max_rows: int | None = None, sheet_name: str | None = None,
|
||
) -> tuple[list[list[Any]], int]:
|
||
"""Load configured worksheet or CSV rows; returns rows and total row count hint."""
|
||
suffix = path.suffix.lower()
|
||
if suffix == ".csv":
|
||
from app.services.shipping_notice.onhand_file_identity import load_inventory_csv_rows
|
||
|
||
rows = load_inventory_csv_rows(path, max_rows=max_rows)
|
||
try:
|
||
total = sum(1 for _ in path.open("r", encoding="utf-8", errors="ignore"))
|
||
except OSError:
|
||
total = len(rows)
|
||
return rows, int(total)
|
||
|
||
if suffix == ".xls":
|
||
import xlrd
|
||
|
||
book = xlrd.open_workbook(filename=str(path), on_demand=True)
|
||
try:
|
||
if sheet_name:
|
||
try:
|
||
sheet = book.sheet_by_name(sheet_name)
|
||
except xlrd.biffh.XLRDError as exc:
|
||
raise ValueError(f'Inventory worksheet not found: {sheet_name}') from exc
|
||
else:
|
||
sheet = book.sheet_by_index(0)
|
||
row_limit = sheet.nrows if max_rows is None else min(sheet.nrows, max_rows)
|
||
rows = [
|
||
[_xls_cell_value(book, sheet.cell(row_index, column_index)) for column_index in range(sheet.ncols)]
|
||
for row_index in range(row_limit)
|
||
]
|
||
return rows, int(sheet.nrows)
|
||
finally:
|
||
book.release_resources()
|
||
|
||
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
|
||
try:
|
||
if sheet_name and sheet_name not in wb.sheetnames:
|
||
raise ValueError(f'Inventory worksheet not found: {sheet_name}')
|
||
ws = wb[sheet_name] if sheet_name else wb.active
|
||
rows: list[list[Any]] = []
|
||
for i, row in enumerate(ws.iter_rows(values_only=True)):
|
||
if max_rows is not None and i >= max_rows:
|
||
break
|
||
rows.append(list(row))
|
||
total = ws.max_row or len(rows)
|
||
finally:
|
||
wb.close()
|
||
return rows, int(total)
|
||
|
||
|
||
def _xls_cell_value(book: Any, cell: Any) -> Any:
|
||
"""将 xlrd 单元格值规范为与 openpyxl 接近的 Python 值。"""
|
||
import xlrd
|
||
|
||
if cell.ctype == xlrd.XL_CELL_EMPTY:
|
||
return None
|
||
if cell.ctype == xlrd.XL_CELL_DATE:
|
||
return xlrd.xldate_as_datetime(cell.value, book.datemode)
|
||
if cell.ctype == xlrd.XL_CELL_NUMBER and float(cell.value).is_integer():
|
||
return int(cell.value)
|
||
return cell.value
|
||
|
||
|
||
def _rows_from_table_text(raw_text: str) -> list[list[str]]:
|
||
rows: list[list[str]] = []
|
||
for line in raw_text.splitlines():
|
||
stripped = line.strip()
|
||
if not stripped or re.match(r"^[\|\-\s]+$", stripped) or stripped.startswith("#"):
|
||
continue
|
||
if "|" in stripped:
|
||
cells = [c.strip() for c in stripped.strip("|").split("|")]
|
||
cells = [c for c in cells if c]
|
||
elif "\t" in stripped:
|
||
cells = [c.strip() for c in stripped.split("\t") if c.strip()]
|
||
else:
|
||
cells = [c.strip() for c in re.split(r"[,,;;]+", stripped) if c.strip()]
|
||
if cells:
|
||
rows.append(cells)
|
||
return rows
|
||
|
||
|
||
from app.services.shipping_notice.notice_lines import NOTICE_FIELD_LABELS
|
||
|
||
|
||
def describe_inventory_columns(
|
||
headers: list[str],
|
||
*,
|
||
field_mapping: dict[str, str] | None = None,
|
||
mapping_source: str = "rules",
|
||
) -> dict[str, Any]:
|
||
"""根据规则建议或已发布方案生成库存栏位与匹配规则的审计描述。"""
|
||
if field_mapping:
|
||
from app.services.shipping_notice.onhand_mapping import build_column_meta_from_mapping
|
||
|
||
return build_column_meta_from_mapping(
|
||
headers,
|
||
field_mapping,
|
||
mapping_source=mapping_source,
|
||
)
|
||
|
||
from app.services.shipping_notice.match_rule_desc import resolve_match_rule
|
||
|
||
col_map = _column_map()
|
||
columns = _resolve_inventory_columns(headers, col_map)
|
||
|
||
def source_column(index: int | None) -> str | None:
|
||
if index is None or index >= len(headers):
|
||
return None
|
||
text = str(headers[index] or "").strip()
|
||
return text or None
|
||
|
||
qty_source = source_column(columns.get("available_qty"))
|
||
qty_note = "Qty Available"
|
||
if not qty_source:
|
||
qty_source = source_column(columns.get("qty"))
|
||
qty_note = "Qty"
|
||
|
||
inferred_mapping: dict[str, str] = {}
|
||
part_number_src = source_column(columns.get("part_number"))
|
||
if part_number_src:
|
||
inferred_mapping["part_number"] = part_number_src
|
||
aws_part_number_src = source_column(columns.get("aws_part_number"))
|
||
if aws_part_number_src:
|
||
inferred_mapping["aws_part_number"] = aws_part_number_src
|
||
rid_src = source_column(columns.get("reservation_id"))
|
||
if rid_src:
|
||
inferred_mapping["reservation_id"] = rid_src
|
||
if qty_source:
|
||
inferred_mapping["available_qty"] = qty_source
|
||
|
||
match_rule, match_key, match_rule_source = resolve_match_rule(inferred_mapping)
|
||
|
||
return {
|
||
"headers": [str(h or "").strip() for h in headers],
|
||
"mapping": {
|
||
"part_number": {
|
||
"system_field": "part_number",
|
||
"label": "Supplier Sku / 内部料号",
|
||
"source_column": part_number_src,
|
||
},
|
||
"aws_part_number": {
|
||
"system_field": "aws_part_number",
|
||
"label": "AWS Sku / AWS 料号",
|
||
"source_column": aws_part_number_src,
|
||
},
|
||
"reservation_id": {
|
||
"system_field": "reservation_id",
|
||
"label": "Reservation ID",
|
||
"source_column": rid_src,
|
||
"alternatives": list(_RESERVATION_HEADER_PRIORITY),
|
||
},
|
||
"available_qty": {
|
||
"system_field": "available_qty",
|
||
"label": "可用数量",
|
||
"source_column": qty_source,
|
||
"qty_preference": qty_note,
|
||
},
|
||
},
|
||
"match_key": match_key,
|
||
"match_rule": match_rule,
|
||
"match_rule_source": match_rule_source,
|
||
}
|
||
|
||
|
||
def build_field_alignment_preview(
|
||
inventory_lines: list[dict[str, Any]],
|
||
notice_lines: list[dict[str, Any]],
|
||
*,
|
||
column_meta: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""生成 match_inventory 前的人工确认预览(样本行、warnings、match_rule)。"""
|
||
warnings: list[str] = []
|
||
mapping = column_meta or {}
|
||
inv_mapping = mapping.get("mapping") if isinstance(mapping.get("mapping"), dict) else {}
|
||
|
||
order_has_reservation = any(str(line.get("reservation_id") or "").strip() for line in notice_lines)
|
||
inv_has_reservation = any(str(line.get("reservation_id") or "").strip() for line in inventory_lines)
|
||
res_source = (inv_mapping.get("reservation_id") or {}).get("source_column")
|
||
|
||
if notice_lines and not order_has_reservation:
|
||
warnings.append("订单未解析到 Reservation ID,但当前规则要求 Reservation ID 必填;请重新解析发货通知。")
|
||
if inventory_lines and not inv_has_reservation:
|
||
warnings.append("库存行未提供 Reservation ID(这些行将不参与匹配);如需按 Reservation ID 精确匹配,请补齐库存 Reservation ID。")
|
||
if inventory_lines and not res_source:
|
||
warnings.append("库存表未识别到 Reservation ID 相关列(COM ID / Reservation Order 等)。")
|
||
|
||
part_number_source = (inv_mapping.get("part_number") or {}).get("source_column")
|
||
if notice_lines and inventory_lines and not part_number_source:
|
||
warnings.append("库存表未识别 Supplier Sku / 内部料号列,无法执行库存匹配。")
|
||
|
||
qty_source = (inv_mapping.get("available_qty") or {}).get("source_column")
|
||
if inventory_lines and not qty_source:
|
||
warnings.append("库存表未识别 Qty Available / Qty 列,请核对数量列映射。")
|
||
|
||
notice_preview = [
|
||
{
|
||
"part_number": str(line.get("part_number") or "").strip(),
|
||
"customer_part_number": str(line.get("customer_part_number") or "").strip(),
|
||
"aws_part_number": str(line.get("aws_part_number") or "").strip(),
|
||
"reservation_id": str(line.get("reservation_id") or "").strip(),
|
||
"qty": line.get("qty"),
|
||
"unit_price": line.get("unit_price"),
|
||
"amount": line.get("amount"),
|
||
}
|
||
for line in notice_lines[:5]
|
||
]
|
||
sample_inventory = [
|
||
{
|
||
"part_number": line.get("part_number"),
|
||
"aws_part_number": line.get("aws_part_number"),
|
||
"reservation_id": line.get("reservation_id", ""),
|
||
"available_qty": line.get("available_qty"),
|
||
}
|
||
for line in inventory_lines[:5]
|
||
]
|
||
|
||
field_mapping_meta = mapping.get("field_mapping") if isinstance(mapping.get("field_mapping"), dict) else {}
|
||
fallback_mapping = {
|
||
k: str((inv_mapping.get(k) or {}).get("source_column") or "").strip()
|
||
for k in ("part_number", "aws_part_number", "reservation_id", "available_qty")
|
||
}
|
||
fallback_mapping = {k: v for k, v in fallback_mapping.items() if v}
|
||
if not fallback_mapping and field_mapping_meta:
|
||
fallback_mapping = {k: str(v).strip() for k, v in field_mapping_meta.items() if str(v).strip()}
|
||
|
||
from app.services.shipping_notice.match_rule_desc import build_match_rule_fallback, resolve_match_rule
|
||
|
||
match_rule = str(mapping.get("match_rule") or "").strip()
|
||
if not match_rule and fallback_mapping:
|
||
match_rule = build_match_rule_fallback(
|
||
fallback_mapping,
|
||
match_key=mapping.get("match_key") if isinstance(mapping.get("match_key"), list) else None,
|
||
)
|
||
if not match_rule:
|
||
match_rule, _, _ = resolve_match_rule(fallback_mapping or {"part_number": "Supplier Sku", "available_qty": "qty"})
|
||
|
||
return {
|
||
"match_rule": match_rule,
|
||
"match_rule_source": mapping.get("match_rule_source"),
|
||
"inventory_columns": mapping,
|
||
"notice_fields": NOTICE_FIELD_LABELS,
|
||
"sample_notice_lines": notice_preview,
|
||
"sample_inventory_lines": sample_inventory,
|
||
"inventory_row_count": len(inventory_lines),
|
||
"notice_line_count": len(notice_lines),
|
||
"warnings": warnings,
|
||
}
|
||
|
||
|
||
def parse_inventory_rows(
|
||
headers: list[str],
|
||
data_rows: list[list[Any]],
|
||
*,
|
||
field_mapping: dict[str, str] | None = None,
|
||
) -> list[dict[str, Any]]:
|
||
"""按表头与数据行解析库存表格(Excel 或文档提取文本共用)。"""
|
||
if field_mapping:
|
||
from app.services.shipping_notice.onhand_mapping import resolve_columns_from_field_mapping
|
||
|
||
columns = resolve_columns_from_field_mapping(headers, field_mapping)
|
||
else:
|
||
col_map = _column_map()
|
||
columns = _resolve_inventory_columns(headers, col_map)
|
||
has_header = any(index is not None for index in columns.values()) if field_mapping else (
|
||
columns.get("part_number") is not None or columns.get("available_qty") is not None or columns.get("qty") is not None
|
||
)
|
||
if not has_header and headers and not field_mapping:
|
||
has_header = any(_map_header(h, _column_map()) for h in headers)
|
||
|
||
lines: list[dict[str, Any]] = []
|
||
for row in data_rows:
|
||
if not row:
|
||
continue
|
||
parsed = _normalize_inventory_row(list(row), columns, configured_mapping=bool(field_mapping))
|
||
if parsed:
|
||
lines.append(parsed)
|
||
return lines
|
||
|
||
|
||
def parse_inventory_text(
|
||
raw_text: str,
|
||
*,
|
||
field_mapping: dict[str, str] | None = None,
|
||
) -> tuple[list[dict[str, Any]], list[str], dict[str, Any]]:
|
||
"""从聊天文本或文档提取器输出解析库存表格(TSV/CSV 形式)。"""
|
||
warnings: list[str] = []
|
||
empty_meta: dict[str, Any] = {"headers": [], "mapping": {}, "match_key": ["part_number", "reservation_id"]}
|
||
text = str(raw_text or "").strip()
|
||
if not text:
|
||
return [], ["empty inventory text"], empty_meta
|
||
|
||
rows = _rows_from_table_text(text)
|
||
if not rows:
|
||
return [], ["no table rows detected"], empty_meta
|
||
|
||
header = rows[0]
|
||
if field_mapping:
|
||
from app.services.shipping_notice.onhand_mapping import resolve_columns_from_field_mapping
|
||
|
||
has_header = True
|
||
column_meta = describe_inventory_columns(
|
||
header,
|
||
field_mapping=field_mapping,
|
||
mapping_source="manual",
|
||
)
|
||
else:
|
||
col_map = _column_map()
|
||
columns = _resolve_inventory_columns(header, col_map)
|
||
has_header = columns.get("part_number") is not None or any(_map_header(h, col_map) for h in header)
|
||
column_meta = describe_inventory_columns(header) if has_header else empty_meta
|
||
|
||
data_rows: list[list[Any]] = rows[1:] if has_header else rows
|
||
|
||
lines = parse_inventory_rows(
|
||
header if has_header else [],
|
||
data_rows if has_header else rows,
|
||
field_mapping=field_mapping,
|
||
)
|
||
if not lines:
|
||
warnings.append("no inventory lines parsed from text")
|
||
return lines, warnings, column_meta
|
||
|
||
|
||
def read_inventory_schema_preview(
|
||
path: Path,
|
||
*,
|
||
max_sample_rows: int = 5,
|
||
) -> dict[str, Any]:
|
||
"""仅读取表头与样本行(供 LLM 推断列映射,不加载全量数据)。"""
|
||
from app.services.shipping_notice.onhand_mapping import suggest_field_mapping
|
||
|
||
scan_rows, total_rows = _load_excel_rows(path, max_rows=40)
|
||
if not scan_rows:
|
||
return {
|
||
"headers": [],
|
||
"sample_rows": [],
|
||
"suggested_mapping": {},
|
||
"row_count_hint": 0,
|
||
"header_row_index": 1,
|
||
}
|
||
|
||
header_idx = find_inventory_header_row_index(scan_rows)
|
||
headers = [str(c or "").strip() for c in scan_rows[header_idx]]
|
||
sample_rows = [
|
||
[str(c) if c is not None else "" for c in r]
|
||
for r in scan_rows[header_idx + 1 : header_idx + 1 + max_sample_rows]
|
||
]
|
||
suggested = suggest_field_mapping(headers)
|
||
data_row_count = max(0, total_rows - header_idx - 1)
|
||
return {
|
||
"headers": headers,
|
||
"sample_rows": sample_rows,
|
||
"suggested_mapping": suggested,
|
||
"header_row_index": header_idx + 1,
|
||
"mapping_targets": {
|
||
"part_number": "Supplier Sku / 内部料号",
|
||
"aws_part_number": "AWS Sku / AWS 料号(可选)",
|
||
"reservation_id": "Reservation ID / COM ID(必填)",
|
||
"available_qty": "可用数量 / Qty Available / Qty",
|
||
},
|
||
"row_count_hint": data_row_count,
|
||
}
|
||
|
||
|
||
def parse_inventory_excel_with_meta(
|
||
path: Path,
|
||
*,
|
||
field_mapping: dict[str, str] | None = None,
|
||
mapping_source: str = "rules",
|
||
header_row_index: int | None = None,
|
||
sheet_name: str | None = None,
|
||
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||
"""
|
||
解析库存 Excel 并返回标准化行与 column_meta。
|
||
|
||
核心逻辑:选择工作表 → 定位表头行 → describe_inventory_columns → parse_inventory_rows。
|
||
"""
|
||
rows, _total = _load_excel_rows(path, sheet_name=sheet_name)
|
||
if not rows:
|
||
return [], {"headers": [], "mapping": {}, "match_key": ["part_number", "reservation_id"]}
|
||
|
||
header_idx: int | None = None
|
||
if header_row_index is not None:
|
||
try:
|
||
idx = int(header_row_index) - 1
|
||
except (TypeError, ValueError):
|
||
idx = -1
|
||
if 0 <= idx < len(rows):
|
||
header_idx = idx
|
||
if header_idx is None:
|
||
header_idx = find_inventory_header_row_index(rows)
|
||
headers = [str(c or "").strip() for c in rows[header_idx]]
|
||
data_rows = [list(r) for r in rows[header_idx + 1 :] if r]
|
||
if not field_mapping:
|
||
from app.services.shipping_notice.onhand_mapping import suggest_field_mapping
|
||
|
||
suggested = suggest_field_mapping(headers)
|
||
if suggested.get("part_number") and suggested.get("available_qty"):
|
||
field_mapping = suggested
|
||
mapping_source = "rules"
|
||
|
||
lines = parse_inventory_rows(headers, data_rows, field_mapping=field_mapping)
|
||
meta = describe_inventory_columns(
|
||
headers,
|
||
field_mapping=field_mapping,
|
||
mapping_source=mapping_source if field_mapping else "rules",
|
||
)
|
||
meta["header_row_index"] = header_idx + 1
|
||
meta["sheet_name"] = sheet_name
|
||
return lines, meta
|
||
|
||
|
||
def parse_inventory_excel(path: Path) -> list[dict[str, Any]]:
|
||
"""parse_inventory_excel_with_meta 的便捷封装,仅返回库存行列表。"""
|
||
lines, _meta = parse_inventory_excel_with_meta(path)
|
||
return lines
|
||
|
||
|
||
def ingest_inventory_file(
|
||
source_path: Path,
|
||
*,
|
||
move_to: Path | None = None,
|
||
field_mapping: dict[str, str] | None = None,
|
||
mapping_source: str = "rules",
|
||
header_row_index: int | None = None,
|
||
sheet_name: str | None = None,
|
||
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||
"""
|
||
解析库存文件并可选择移动至 processed 目录(RPA drop 摄入用)。
|
||
|
||
Returns:
|
||
tuple: (inventory_lines, column_meta)。
|
||
"""
|
||
lines, column_meta = parse_inventory_excel_with_meta(
|
||
source_path,
|
||
field_mapping=field_mapping,
|
||
mapping_source=mapping_source,
|
||
header_row_index=header_row_index,
|
||
sheet_name=sheet_name,
|
||
)
|
||
if move_to:
|
||
move_to.mkdir(parents=True, exist_ok=True)
|
||
target = move_to / source_path.name
|
||
if target.exists():
|
||
target = move_to / f"{source_path.stem}_{datetime.utcnow().strftime('%H%M%S')}{source_path.suffix}"
|
||
shutil.move(str(source_path), str(target))
|
||
return lines, column_meta
|