把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与 枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa 持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀, 上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。 Co-authored-by: Cursor <cursoragent@cursor.com>
293 lines
11 KiB
Python
293 lines
11 KiB
Python
"""
|
||
services/shipping_notice/onhand_mapping.py
|
||
|
||
用途:按用户维护的库存字段 ID 标准化列映射,并校验字段能力是否完整。
|
||
依赖:FreightRpaOnhandField、match_rule_desc、标准 `json`/`typing` 能力。
|
||
逻辑:正式库存链始终保留字段 ID;临时候选也只能引用库存字段目录 ID。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from typing import Any
|
||
|
||
from app.models import FreightRpaOnhandField
|
||
|
||
from app.services.shipping_notice.match_rule_desc import resolve_match_rule
|
||
|
||
LEGACY_SYSTEM_FIELDS = ("part_number", "aws_part_number", "reservation_id", "available_qty", "warehouse_id")
|
||
LEGACY_REQUIRED_FIELDS = ("part_number", "reservation_id", "available_qty")
|
||
|
||
|
||
def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, FreightRpaOnhandField]:
|
||
"""读取映射中的库存字段目录记录;非 ID 映射仅保留给临时上传的旧链路。"""
|
||
try:
|
||
ids = {int(key) for key in field_mapping}
|
||
except (TypeError, ValueError):
|
||
return {}
|
||
if not ids or any(item <= 0 for item in ids):
|
||
return {}
|
||
rows = FreightRpaOnhandField.query.filter(
|
||
FreightRpaOnhandField.id.in_(ids), FreightRpaOnhandField.status == 'active',
|
||
).all()
|
||
return {str(row.id): row for row in rows}
|
||
|
||
|
||
def _uses_catalog_ids(field_mapping: dict[str, Any]) -> bool:
|
||
"""判断映射键是否为字段目录 ID;纯数字键绝不能回退成旧运行字段。"""
|
||
if not field_mapping:
|
||
return False
|
||
try:
|
||
return all(int(key) > 0 for key in field_mapping)
|
||
except (TypeError, ValueError):
|
||
return False
|
||
|
||
|
||
def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str], dict[str, FreightRpaOnhandField]]:
|
||
"""验证“目录 ID → 原始表头”并保留字段 ID,禁止运行期依赖字段名称或内部编码。"""
|
||
catalog = _catalog_by_id(field_mapping)
|
||
if _uses_catalog_ids(field_mapping):
|
||
if len(catalog) != len(field_mapping):
|
||
return {}, {}
|
||
return ({str(item.id): str(field_mapping[str(item.id)]).strip() for item in catalog.values()}, catalog)
|
||
# 临时会话上传尚未绑定库存站点时沿用受控旧格式;正式解析方案不会走该分支。
|
||
return ({str(key): str(value).strip() for key, value in field_mapping.items()}, {})
|
||
|
||
|
||
def usage_field_ids() -> dict[str, set[str]]:
|
||
"""按业务用途返回启用字段 ID;程序校验能力角色而不限定字段名称。"""
|
||
rows = FreightRpaOnhandField.query.filter(
|
||
FreightRpaOnhandField.status == 'active',
|
||
).all()
|
||
result: dict[str, set[str]] = {}
|
||
for row in rows:
|
||
result.setdefault(row.usage_type, set()).add(str(row.id))
|
||
return result
|
||
|
||
|
||
def normalize_field_mapping(raw: Any) -> dict[str, str] | None:
|
||
"""规范库存字段目录 ID 到来源栏位的映射;缺必要用途字段时返回 None。"""
|
||
data: dict[str, Any] | None = None
|
||
if isinstance(raw, dict):
|
||
data = raw
|
||
elif isinstance(raw, str) and raw.strip():
|
||
import json
|
||
|
||
try:
|
||
parsed = json.loads(raw)
|
||
if isinstance(parsed, dict):
|
||
data = parsed
|
||
except json.JSONDecodeError:
|
||
return None
|
||
if not data:
|
||
return None
|
||
|
||
inner = data.get("mapping") if isinstance(data.get("mapping"), dict) else data
|
||
if not isinstance(inner, dict):
|
||
return None
|
||
|
||
result: dict[str, str] = {}
|
||
for key in LEGACY_SYSTEM_FIELDS:
|
||
value = inner.get(key)
|
||
if value is None:
|
||
continue
|
||
text = str(value).strip()
|
||
if text:
|
||
result[key] = text
|
||
return result if all(field in result for field in LEGACY_REQUIRED_FIELDS) else None
|
||
|
||
|
||
def _suggest_runtime_field_mapping(headers: list[str]) -> dict[str, str]:
|
||
"""基于表头名称的规则推断列映射(LLM 不可用时的 fallback)。"""
|
||
from app.services.shipping_notice.onhand_snapshot import _column_map, _map_header
|
||
|
||
col_map = _column_map()
|
||
norm_headers = [str(h or "").strip() for h in headers]
|
||
lower_index = {h.lower(): h for h in norm_headers if h}
|
||
|
||
def pick(*candidates: str) -> str | None:
|
||
for cand in candidates:
|
||
if cand in norm_headers:
|
||
return cand
|
||
hit = lower_index.get(cand.lower())
|
||
if hit:
|
||
return hit
|
||
for h in norm_headers:
|
||
mapped = _map_header(h, col_map)
|
||
if mapped in candidates:
|
||
return h
|
||
return None
|
||
|
||
mapping: dict[str, str] = {}
|
||
part_number = pick(
|
||
"part_number",
|
||
"Supplier Sku",
|
||
"Supplier SKU",
|
||
"Supplier Part Number",
|
||
"Supplier Part No",
|
||
"Part Number",
|
||
"Part No",
|
||
"料号",
|
||
"SKU",
|
||
)
|
||
if part_number:
|
||
mapping["part_number"] = part_number
|
||
|
||
aws_part_number = pick("aws_part_number", "AWS Sku", "AWS SKU", "AWS SKU#", "AWS Sku#")
|
||
if aws_part_number:
|
||
mapping["aws_part_number"] = aws_part_number
|
||
|
||
reservation = pick(
|
||
"reservation_id",
|
||
"Reservation ID",
|
||
"COM ID",
|
||
"Reservation Order",
|
||
"Resevation Order",
|
||
"Reservation No",
|
||
)
|
||
if reservation:
|
||
mapping["reservation_id"] = reservation
|
||
|
||
qty = pick("available_qty", "Qty Available", "可用数量", "Available Qty", "On Hand Qty")
|
||
if not qty:
|
||
qty = pick("qty", "Qty", "数量", "Quantity")
|
||
if qty:
|
||
mapping["available_qty"] = qty
|
||
|
||
warehouse = pick("warehouse_id", "Warehouse ID", "Warehouse", "Warehouse Code", "WH ID")
|
||
if warehouse:
|
||
mapping["warehouse_id"] = warehouse
|
||
|
||
return mapping
|
||
|
||
|
||
def suggest_field_mapping(headers: list[str], *, as_catalog: bool = False) -> dict[str, str]:
|
||
"""按用户字段显示名称确定性推荐表头;正式配置不内置任何字段名称词典。"""
|
||
if not as_catalog:
|
||
return _suggest_runtime_field_mapping(headers)
|
||
from app.services.shipping_notice.onhand_structure_fingerprint import normalise_header
|
||
|
||
rows = FreightRpaOnhandField.query.filter_by(status='active').all()
|
||
header_by_name: dict[str, list[str]] = {}
|
||
for header in headers:
|
||
normalized = normalise_header(header)
|
||
if normalized:
|
||
header_by_name.setdefault(normalized, []).append(str(header).strip())
|
||
result: dict[str, str] = {}
|
||
for row in rows:
|
||
candidates = header_by_name.get(normalise_header(row.display_name), [])
|
||
if len(candidates) == 1:
|
||
result[str(row.id)] = candidates[0]
|
||
return result
|
||
|
||
|
||
def mapping_is_complete(field_mapping: dict[str, str]) -> bool:
|
||
"""映射是否至少提供一个匹配字段和且仅一个库存数量字段。"""
|
||
runtime_mapping, catalog = runtime_field_mapping(field_mapping)
|
||
if catalog:
|
||
mapped = set(runtime_mapping)
|
||
usages = usage_field_ids()
|
||
return bool(mapped & usages.get('match_identity', set())) and len(mapped & usages.get('inventory_quantity', set())) == 1
|
||
return all(bool(runtime_mapping.get(field)) for field in LEGACY_REQUIRED_FIELDS)
|
||
|
||
|
||
def validate_field_mapping_against_headers(
|
||
headers: list[str],
|
||
field_mapping: dict[str, str],
|
||
) -> list[str]:
|
||
"""校验映射列名是否存在于表头;返回中文错误消息列表。"""
|
||
norm_headers = [str(h or "").strip() for h in headers]
|
||
lower_set = {h.lower() for h in norm_headers if h}
|
||
errors: list[str] = []
|
||
runtime_mapping, catalog = runtime_field_mapping(field_mapping)
|
||
if not runtime_mapping:
|
||
return ['库存字段目录中存在已停用或不存在的字段']
|
||
required_codes = set(LEGACY_REQUIRED_FIELDS)
|
||
if catalog:
|
||
usages = usage_field_ids()
|
||
required_codes = (set(runtime_mapping) & usages.get('match_identity', set())) | (set(runtime_mapping) & usages.get('inventory_quantity', set()))
|
||
for key, name in runtime_mapping.items():
|
||
label = catalog.get(key).display_name if key in catalog else key
|
||
if not name:
|
||
if key in required_codes:
|
||
errors.append(f"缺少 {label} 列映射")
|
||
continue
|
||
if name not in norm_headers and name.lower() not in lower_set:
|
||
preview = ", ".join(norm_headers[:8])
|
||
if len(norm_headers) > 8:
|
||
preview += "..."
|
||
errors.append(f'列名 "{name}" 不在表头中(当前表头: {preview})')
|
||
return errors
|
||
|
||
|
||
def resolve_columns_from_field_mapping(
|
||
headers: list[str],
|
||
field_mapping: dict[str, str],
|
||
) -> dict[str, int | None]:
|
||
"""将显式 field_mapping 转为库存字段 ID → 列索引;未配置字段不自动猜测。"""
|
||
norm_headers = [str(h or "").strip() for h in headers]
|
||
lower_to_idx = {h.lower(): i for i, h in enumerate(norm_headers) if h}
|
||
# Excel exports may contain line breaks or repeated whitespace in a
|
||
# visible header (for example ``Qty\nAvailable``). Explicit published
|
||
# mappings must still resolve deterministically without guessing a field.
|
||
normalized_to_idx: dict[str, int] = {}
|
||
for index, header in enumerate(norm_headers):
|
||
key = re.sub(r"[^a-z0-9]+", "", header.lower())
|
||
if key and key not in normalized_to_idx:
|
||
normalized_to_idx[key] = index
|
||
|
||
def idx_for(header_name: str | None) -> int | None:
|
||
if not header_name:
|
||
return None
|
||
name = str(header_name).strip()
|
||
if not name:
|
||
return None
|
||
if name in norm_headers:
|
||
return norm_headers.index(name)
|
||
exact_lower = lower_to_idx.get(name.lower())
|
||
if exact_lower is not None:
|
||
return exact_lower
|
||
normalized = re.sub(r"[^a-z0-9]+", "", name.lower())
|
||
return normalized_to_idx.get(normalized)
|
||
|
||
runtime_mapping, _catalog = runtime_field_mapping(field_mapping)
|
||
if not runtime_mapping:
|
||
return {}
|
||
return {field_code: idx_for(header_name) for field_code, header_name in runtime_mapping.items()}
|
||
|
||
|
||
def build_column_meta_from_mapping(
|
||
headers: list[str],
|
||
field_mapping: dict[str, str],
|
||
*,
|
||
mapping_source: str = "rules",
|
||
) -> dict[str, Any]:
|
||
"""由规则建议或已发布方案构建 column_meta(含匹配说明与来源栏位)。"""
|
||
runtime_mapping, catalog = runtime_field_mapping(field_mapping)
|
||
columns = resolve_columns_from_field_mapping(headers, field_mapping)
|
||
|
||
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
|
||
|
||
labels = {str(item.id): item.display_name for item in catalog.values()}
|
||
match_rule, match_key, match_rule_source = resolve_match_rule(runtime_mapping)
|
||
return {
|
||
"headers": [str(h or "").strip() for h in headers],
|
||
"mapping_source": mapping_source,
|
||
"field_mapping": dict(field_mapping),
|
||
"mapping": {
|
||
field_id: {
|
||
"inventory_field_id": int(field_id) if field_id.isdigit() else None,
|
||
"label": labels.get(field_id, field_id),
|
||
"source_column": source_column(index),
|
||
}
|
||
for field_id, index in columns.items()
|
||
},
|
||
"match_key": match_key,
|
||
"match_rule": match_rule,
|
||
"match_rule_source": match_rule_source,
|
||
}
|