feat(shipping-notice): 完成货代发货通知全流程开发与代码重构

- 新增PO号提取、预约ID解析(支持`PR@xxx`格式)工具,完善库存匹配逻辑
- 新增库存映射缓存、匹配/解析结果格式化摘要,优化用户提示
- 修复数据库迁移脚本未检查表存在的问题,避免全新部署失败
- 新增路径工具类统一管理相对路径,优化配置文件处理逻辑
- 归档旧文档,将部署、Dify配置合并到`shipping_notice.md`
- 新增完整单元测试与集成测试覆盖核心流程
- 更新前端国际化与会话管理逻辑,优化界面交互
This commit is contained in:
hugo committed 2026-06-04 15:26:34 +08:00
1 parent b62082758b
commit 8deae3146b
65 files changed
+6477 -1937

No files matched your search

@@ -4,16 +4,22 @@ import re
from typing import Any
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",
)
@@ -30,7 +36,16 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
"Material": "sku",
"Material No": "sku",
"产品编号": "sku",
"Item No": "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",
@@ -58,6 +73,13 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
"小计": "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",
@@ -66,6 +88,27 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
"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",
@@ -74,11 +117,15 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
}
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 = {
@@ -94,6 +141,11 @@ _HEADER_SKIP_TOKENS = {
"unit price",
"金额",
"amount",
"currency",
"币种",
"line no",
"item no",
"项次",
}
@@ -138,6 +190,110 @@ def _cell(row: list[Any] | tuple[Any, ...], index: int | None) -> Any:
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
@@ -147,8 +303,11 @@ def _parse_number(value: Any) -> float | 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(text)
return float(match.group(0))
except (TypeError, ValueError):
return None
@@ -162,7 +321,7 @@ def _infer_reservation_id_from_row(
if i in skip_indices:
continue
if looks_like_reservation_id(cell):
return normalize_reservation_id(cell)
return extract_reservation_id(cell)
return ""
@@ -197,10 +356,17 @@ def _parse_notice_row(
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 = normalize_reservation_id(_cell(row, idx_res))
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)
@@ -208,23 +374,48 @@ def _parse_notice_row(
parsed["reservation_id"] = reservation_id
idx_price = columns.get("unit_price")
price_cell = None
if idx_price is not None:
unit_price = _parse_number(_cell(row, idx_price))
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 = _parse_number(_cell(row, idx_amount))
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)
@@ -252,11 +443,26 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
"uom": str(raw.get("uom") or "EA").strip() or "EA",
}
reservation_id = normalize_reservation_id(
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
@@ -271,6 +477,38 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
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
remark = str(raw.get("remark") or raw.get("note") or "").strip()
if remark:
line["remark"] = remark
@@ -289,6 +527,126 @@ def normalize_notice_lines(lines: list[Any] | None) -> list[dict[str, Any]]:
return normalized
def enrich_notice_with_document_reservation(
parsed: dict[str, Any],
*,
raw_text: str = "",
) -> dict[str, Any]:
"""Apply document-level PR Number / @1000140351 reservation id to lines missing it."""
doc_rid = ""
for key in (
"reservation_id",
"reservationId",
"document_reservation_id",
"pr_number",
"prNumber",
"PR Number",
):
extracted = extract_reservation_id(parsed.get(key))
if extracted and looks_like_reservation_id(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]:
"""Apply document-level required_date to lines missing their own delivery 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]:
"""Apply document-level currency to lines missing their own currency."""
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 parse_notice_table_text(raw_text: str) -> 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:
@@ -337,23 +695,6 @@ def parse_notice_table_rows(headers: list[str], data_rows: list[list[Any]]) -> l
return lines
def parse_notice_table_text(raw_text: str) -> 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 :]
return parse_notice_table_rows(header, data_rows)
def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]:
warnings: list[str] = []
if not lines: