feat(shipping-notice): 实现货代发货通知的库存全流程与对话交互

This commit is contained in:
hugo committed 2026-06-03 11:09:46 +08:00
1 parent a5cc48b6aa
commit 2607f4a9f6
26 files changed
+5013 -256

No files matched your search

+23 -31
View File
@@ -28,41 +28,10 @@ def _dify_openapi_spec() -> dict:
return build_dify_openapi_spec(_tool_api_base_url())
def _require_tool_key():
configured = (
str(current_app.config.get("SHIPPING_NOTICE_TOOL_API_KEY") or "").strip()
or str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
)
if not configured:
return jsonify({"error": "SHIPPING_NOTICE_TOOL_API_KEY is not configured"}), 503
incoming = (
str(request.headers.get("X-Shipping-Tool-Key") or "").strip()
or str(request.headers.get("X-Integration-Key") or "").strip()
)
if incoming and incoming == configured:
return None
return jsonify({"error": "Unauthorized"}), 401
def _payload() -> dict:
return request.get_json(silent=True) or {}
@shipping_notice_bp.before_request
def _auth_tools():
if request.endpoint in {
"shipping_notice.openapi_spec",
"shipping_notice.openapi_dify_yaml",
"shipping_notice.download_case_export",
}:
return None
err = _require_tool_key()
if err:
return err
return None
@shipping_notice_bp.route("/tools/openapi.json", methods=["GET"])
def openapi_spec():
return jsonify(_dify_openapi_spec())
@@ -86,6 +55,29 @@ def tool_parse_notice():
return jsonify(shipping_tools.parse_notice(_payload()))
@shipping_notice_bp.route("/tools/parse_inventory", methods=["POST"])
def tool_parse_inventory():
return jsonify(shipping_tools.parse_inventory(_payload()))
@shipping_notice_bp.route("/tools/upload_inventory_file", methods=["POST"])
def tool_upload_inventory_file():
"""Multipart upload — parse server-side without sending Excel through LLM."""
case_id = str(request.form.get("case_id") or request.args.get("case_id") or "").strip()
upload = request.files.get("file")
return jsonify(shipping_tools.upload_inventory_file(case_id, upload))
@shipping_notice_bp.route("/tools/get_inventory_schema_preview", methods=["POST"])
def tool_get_inventory_schema_preview():
return jsonify(shipping_tools.get_inventory_schema_preview(_payload()))
@shipping_notice_bp.route("/tools/apply_inventory_mapping", methods=["POST"])
def tool_apply_inventory_mapping():
return jsonify(shipping_tools.apply_inventory_mapping(_payload()))
@shipping_notice_bp.route("/tools/ensure_inventory", methods=["POST"])
def tool_ensure_inventory():
return jsonify(shipping_tools.ensure_inventory(_payload()))
@@ -4,6 +4,7 @@ from flask import Blueprint, jsonify, request, send_file
from pathlib import Path
from app.auth_jwt import get_current_user
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
from app.services.shipping_notice.query_service import (
get_case_for_user,
list_cases_for_user,
@@ -41,6 +42,57 @@ def workspace_shipping_case_detail(case_no: str):
return jsonify(serialize_case_detail(case))
@workspace_shipping_notice_bp.route("/shipping-cases/<case_no>/chat-actions", methods=["GET"])
def workspace_shipping_case_chat_actions(case_no: str):
user, err = _require_user()
if err:
return err
case = get_case_for_user(case_no, user.id)
if not case:
return jsonify({"error": "Not found"}), 404
return jsonify(build_chat_actions_payload(case))
@workspace_shipping_notice_bp.route("/shipping-cases/<case_no>/upload-inventory", methods=["POST"])
def workspace_upload_shipping_inventory(case_no: str):
"""Hxops chat UI: upload inventory Excel with user auth (not Tool Key)."""
user, err = _require_user()
if err:
return err
case = get_case_for_user(case_no, user.id)
if not case:
return jsonify({"error": "Not found"}), 404
upload = request.files.get("file")
from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.upload_inventory_file(case.case_no, upload))
@workspace_shipping_notice_bp.route("/shipping-cases/<case_no>/submit-decision", methods=["POST"])
def workspace_submit_shipping_decision(case_no: str):
"""Hxops chat UI: submit shipping decision with user auth (bypass Dify tool routing)."""
user, err = _require_user()
if err:
return err
case = get_case_for_user(case_no, user.id)
if not case:
return jsonify({"error": "Not found"}), 404
data = request.get_json(silent=True) or {}
decision = str(data.get("decision") or "").strip()
if not decision:
return jsonify({"error": "decision is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"case_id": case.case_no, "decision": decision}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.submit_decision(payload))
@workspace_shipping_notice_bp.route("/shipping-cases/<case_no>/export", methods=["GET"])
def workspace_shipping_case_export(case_no: str):
user, err = _require_user()
+4
View File
@@ -98,6 +98,10 @@ class Config:
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
)
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
)
FREIGHT_INVENTORY_DROP_DIR = os.getenv('FREIGHT_INVENTORY_DROP_DIR')
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = os.getenv('FREIGHT_RPA_INVENTORY_TRIGGER_DIR')
FREIGHT_UPLOAD_QUEUE_DIR = os.getenv('FREIGHT_UPLOAD_QUEUE_DIR')
@@ -0,0 +1,102 @@
from __future__ import annotations
from typing import Any
from app.models import ShippingCase
ACTION_SPECS: dict[str, dict[str, str]] = {
"confirm": {"label": "确认", "message": "确认", "variant": "primary"},
"reject": {"label": "驳回", "message": "驳回", "variant": "danger"},
"reparse": {"label": "重新解析", "message": "重新解析", "variant": "secondary"},
"confirm_inventory_mapping": {"label": "确认", "message": "确认", "variant": "primary"},
"correct_inventory_mapping": {"label": "更正映射", "message": "更正映射", "variant": "secondary"},
"reparse_inventory": {"label": "重新上传", "message": "重新上传库存", "variant": "secondary"},
"rematch": {"label": "重新匹配", "message": "重新匹配", "variant": "secondary"},
"retry_rpa": {"label": "重试 RPA", "message": "重试 RPA 导出库存", "variant": "secondary"},
"upload_inventory_file": {
"label": "选择库存文件",
"message": "我要上传库存 Excel",
"variant": "secondary",
},
"retry_upload": {"label": "重试上传", "message": "重试上传货代", "variant": "secondary"},
"download_excel": {"label": "下载 Excel", "message": "下载发货 Excel", "variant": "secondary"},
"mark_manual_uploaded": {
"label": "已手工上传",
"message": "已在货代系统手工上传完成",
"variant": "primary",
},
"paste_inventory_json": {
"label": "粘贴库存",
"message": "我粘贴库存小表",
"variant": "secondary",
},
}
def human_options_for_case(case: ShippingCase) -> list[str] | None:
if case.process_status == "rejected" or case.review_status == "rejected":
return []
reason = case.pending_human_reason
if reason == "inventory_field_mapping_review" or case.review_status == "inventory_mapping_review":
return ["confirm_inventory_mapping", "correct_inventory_mapping", "reparse_inventory", "reject"]
if reason == "inventory_mapping_inference":
return ["upload_inventory_file", "paste_inventory_json"]
if reason == "inventory_unavailable":
return ["retry_rpa", "upload_inventory_file"]
if reason == "inventory_shortage" or case.review_status == "inventory_shortage_review":
return ["confirm", "reject", "rematch"]
if reason == "low_parse_confidence" or case.review_status == "parse_review":
return ["confirm", "reject", "reparse"]
if reason == "upload_rpa_failed" or case.process_status == "upload_failed":
return ["retry_upload", "download_excel", "mark_manual_uploaded"]
if reason == "inventory_rpa_pending" or (
case.process_status == "waiting_inventory" and reason == "inventory_rpa_pending"
):
return ["retry_rpa", "upload_inventory_file"]
if reason == "upload_rpa_pending" or case.process_status == "waiting_upload":
return ["retry_upload", "download_excel", "mark_manual_uploaded"]
return None
def checkpoint_for_case(case: ShippingCase) -> str | None:
if case.process_status == "rejected" or case.review_status == "rejected":
return "rejected"
reason = case.pending_human_reason
if reason == "inventory_field_mapping_review" or case.review_status == "inventory_mapping_review":
return "inventory_field_mapping_review"
if reason == "low_parse_confidence" or case.review_status == "parse_review":
return "parse_review"
if reason == "inventory_shortage" or case.review_status == "inventory_shortage_review":
return "inventory_shortage_review"
if reason == "inventory_unavailable":
return "inventory_upload_required"
if reason == "inventory_mapping_inference":
return "inventory_mapping_inference"
if reason == "upload_rpa_failed" or case.process_status == "upload_failed":
return "upload_failed"
return None
def build_action_buttons(option_ids: list[str] | None) -> list[dict[str, str]]:
if not option_ids:
return []
buttons: list[dict[str, str]] = []
for option_id in option_ids:
spec = ACTION_SPECS.get(option_id)
if not spec:
continue
buttons.append({"id": option_id, **spec})
return buttons
def build_chat_actions_payload(case: ShippingCase) -> dict[str, Any]:
options = human_options_for_case(case)
buttons = build_action_buttons(options)
return {
"case_no": case.case_no,
"checkpoint": checkpoint_for_case(case),
"process_status": case.process_status,
"review_status": case.review_status,
"pending_human_reason": case.pending_human_reason,
"action_buttons": buttons,
}
+75 -14
View File
@@ -6,6 +6,11 @@ from typing import Any
from app.services.dify import DifyService
from app.services.shipping_notice.agent_resolver import resolve_extract_agent
from app.services.shipping_notice.notice_lines import (
normalize_notice_lines,
parse_notice_table_text,
validate_notice_lines,
)
def _parse_workflow_outputs(result: dict[str, Any]) -> dict[str, Any] | None:
@@ -30,6 +35,17 @@ def _parse_workflow_outputs(result: dict[str, Any]) -> dict[str, Any] | None:
return outputs if outputs else None
def _finalize_notice_parse(parsed: dict[str, Any], *, base_confidence: float) -> tuple[dict[str, Any], float, list[str]]:
lines = normalize_notice_lines(parsed.get("lines") if isinstance(parsed.get("lines"), list) else [])
parsed = {**parsed, "lines": lines}
warnings = validate_notice_lines(lines)
from app.services.shipping_notice.notice_lines import notice_parse_completeness
completeness = notice_parse_completeness(lines)
confidence = min(base_confidence, 0.95) * (0.5 + 0.5 * completeness) if lines else base_confidence * 0.5
return parsed, round(confidence, 4), warnings
def extract_notice_fields(
*,
raw_text: str,
@@ -39,7 +55,7 @@ def extract_notice_fields(
warnings: list[str] = []
if structured and isinstance(structured, dict):
return structured, float(structured.get("confidence") or 0.95), warnings
return _finalize_notice_parse(structured, base_confidence=float(structured.get("confidence") or 0.95))
agent = resolve_extract_agent()
if agent and raw_text.strip():
@@ -51,31 +67,76 @@ def extract_notice_fields(
)
parsed = _parse_workflow_outputs(result)
if parsed:
confidence = float(parsed.get("confidence") or 0.85)
return parsed, confidence, warnings
finalized, confidence, line_warnings = _finalize_notice_parse(
parsed,
base_confidence=float(parsed.get("confidence") or 0.85),
)
warnings.extend(line_warnings)
return finalized, confidence, warnings
warnings.append("workflow_returned_no_structured_output")
except Exception as exc:
warnings.append(f"workflow_error:{exc}")
return _heuristic_extract(raw_text), 0.5, warnings
heuristic, confidence, heuristic_warnings = _heuristic_extract(raw_text)
warnings.extend(heuristic_warnings)
return _finalize_notice_parse(heuristic, base_confidence=confidence)
def _heuristic_extract(raw_text: str) -> dict[str, Any]:
def _heuristic_extract(raw_text: str) -> tuple[dict[str, Any], float, list[str]]:
text = str(raw_text or "").strip()
warnings: list[str] = []
customer_name = ""
m = re.search(r"客户[::]\s*(\S+)", text)
if m:
customer_name = m.group(1)
lines: list[dict[str, Any]] = []
lines = parse_notice_table_text(text)
if lines:
return (
{
"customer_name": customer_name,
"customer_code": "",
"ship_to": "",
"required_date": "",
"lines": lines,
"confidence": 0.72,
},
0.72,
warnings,
)
lines = []
for m in re.finditer(r"([A-Za-z0-9\-_]{3,})\s*[xX×*]\s*(\d+(?:\.\d+)?)", text):
lines.append({"sku": m.group(1), "qty": float(m.group(2)), "uom": "EA"})
return {
"customer_name": customer_name,
"customer_code": "",
"ship_to": "",
"required_date": "",
"lines": lines,
"confidence": 0.5 if lines else 0.3,
}
# 尝试纯数字 Reservation ID + SKU + Qty 的自由文本模式(如 1000140351 10-40594-001 2)
if not lines:
for m in re.finditer(
r"(?P<resv>\d{8,12})\s+([A-Za-z0-9\-_]{3,})\s+(\d+(?:\.\d+)?)",
text,
):
lines.append(
{
"reservation_id": m.group("resv"),
"sku": m.group(2),
"qty": float(m.group(3)),
"uom": "EA",
}
)
if not lines:
warnings.append("heuristic_no_lines_detected")
confidence = 0.5 if lines else 0.3
return (
{
"customer_name": customer_name,
"customer_code": "",
"ship_to": "",
"required_date": "",
"lines": lines,
"confidence": confidence,
},
confidence,
warnings,
)
@@ -0,0 +1,185 @@
from __future__ import annotations
from typing import Any
SYSTEM_FIELDS = ("sku", "reservation_id", "available_qty")
def normalize_field_mapping(raw: Any) -> dict[str, str] | None:
"""Parse LLM/manual mapping: system_field -> Excel column header name."""
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 SYSTEM_FIELDS:
value = inner.get(key)
if value is None:
continue
text = str(value).strip()
if text:
result[key] = text
return result if "sku" in result and "available_qty" in result else None
def suggest_field_mapping(headers: list[str]) -> dict[str, str]:
"""Rule-based fallback mapping from header names."""
from app.services.shipping_notice.inventory_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] = {}
sku = pick("sku", "AWS Sku", "AWS SKU", "料号", "Part Number", "Material")
if sku:
mapping["sku"] = sku
reservation = pick(
"reservation_id",
"Reservation ID",
"COM ID",
"Reservation 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
return mapping
def mapping_is_complete(field_mapping: dict[str, str]) -> bool:
return bool(field_mapping.get("sku") and field_mapping.get("available_qty"))
def validate_field_mapping_against_headers(
headers: list[str],
field_mapping: dict[str, str],
) -> list[str]:
"""Return error messages when mapped column names are missing from headers."""
norm_headers = [str(h or "").strip() for h in headers]
lower_set = {h.lower() for h in norm_headers if h}
errors: list[str] = []
labels = {
"sku": "sku",
"reservation_id": "reservation_id",
"available_qty": "available_qty",
}
for key, label in labels.items():
name = str(field_mapping.get(key) or "").strip()
if not name:
if key in ("sku", "available_qty"):
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]:
"""Map system fields to column indexes using explicit header names."""
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}
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)
return lower_to_idx.get(name.lower())
columns: dict[str, int | None] = {
"sku": idx_for(field_mapping.get("sku")),
"reservation_id": idx_for(field_mapping.get("reservation_id")),
"available_qty": None,
"qty": None,
}
avail_header = field_mapping.get("available_qty")
if avail_header:
columns["available_qty"] = idx_for(avail_header)
return columns
def build_column_meta_from_mapping(
headers: list[str],
field_mapping: dict[str, str],
*,
mapping_source: str = "rules",
) -> dict[str, Any]:
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
qty_header = field_mapping.get("available_qty")
return {
"headers": [str(h or "").strip() for h in headers],
"mapping_source": mapping_source,
"field_mapping": dict(field_mapping),
"mapping": {
"sku": {
"system_field": "sku",
"label": "AWS Sku / 料号",
"source_column": source_column(columns.get("sku")),
},
"reservation_id": {
"system_field": "reservation_id",
"label": "Reservation ID",
"source_column": source_column(columns.get("reservation_id")),
},
"available_qty": {
"system_field": "available_qty",
"label": "可用数量",
"source_column": qty_header or source_column(columns.get("available_qty")),
"qty_preference": "available_qty",
},
},
"match_key": ["sku", "reservation_id"],
"match_rule": "按 SKU + Reservation ID(若有)汇总可用数量,与订单 qty 比对",
}
@@ -1,7 +1,6 @@
from __future__ import annotations
import json
import os
import re
import shutil
from datetime import datetime
@@ -11,70 +10,509 @@ 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
# 默认列映射:含 AWS DUB On Hand Inventory 模板(AWS Sku / Reservation ID / Qty)
DEFAULT_COLUMN_MAP = {
# SKU
"料号": "sku",
"SKU": "sku",
"sku": "sku",
"AWS Sku": "sku",
"AWS SKU": "sku",
"Aws Sku": "sku",
# 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_qty",
"可用量": "available_qty",
"available_qty": "available_qty",
"库存": "available_qty",
"Qty": "qty",
"qty": "qty",
"数量": "qty",
}
_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 parse_inventory_excel(path: Path) -> list[dict[str, Any]]:
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
return None
def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> dict[str, int | None]:
idx_sku = idx_reservation = idx_available = idx_qty = None
for i, h in enumerate(headers):
mapped = _map_header(h, col_map)
if mapped == "sku" and idx_sku is None:
idx_sku = 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
# 若 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 {
"sku": idx_sku,
"reservation_id": idx_reservation,
"available_qty": idx_available,
"qty": idx_qty,
}
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_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
skip_tokens = {
"sku",
"料号",
"aws sku",
"qty",
"qty available",
"可用数量",
"reservation id",
"com id",
}
if sku.lower() in skip_tokens:
return None
reservation_id = ""
idx_res = columns.get("reservation_id")
if idx_res is not None:
reservation_id = normalize_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] = {
"sku": sku,
"available_qty": available_qty,
}
if reservation_id:
parsed["reservation_id"] = reservation_id
return parsed
def _score_header_candidate(cells: list[Any]) -> int:
"""Score how likely a row is the inventory column header (not a title row)."""
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)
score = len(mapped_fields) * 10
if "sku" 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:
"""Pick the row that best matches known inventory column names (skip title rows)."""
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) -> tuple[list[list[Any]], int]:
"""Load worksheet rows; returns (rows, total_row_count_hint)."""
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
try:
ws = wb.active
rows = list(ws.iter_rows(values_only=True))
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()
if not rows:
return []
return rows, int(total)
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]
else:
cells = [c.strip() for c in re.split(r"[\t,,;;]+", 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]:
"""Human-readable column mapping for field-alignment review."""
if field_mapping:
from app.services.shipping_notice.inventory_mapping import build_column_meta_from_mapping
return build_column_meta_from_mapping(headers, field_mapping, mapping_source=mapping_source)
headers = [str(c or "").strip() for c in rows[0]]
col_map = _column_map()
idx_sku = idx_qty = None
for i, h in enumerate(headers):
key = col_map.get(h) or col_map.get(h.lower())
if key == "sku":
idx_sku = i
elif key == "available_qty":
idx_qty = i
if idx_sku is None:
idx_sku = 0
if idx_qty is None:
idx_qty = 1 if len(headers) > 1 else 0
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"
return {
"headers": [str(h or "").strip() for h in headers],
"mapping": {
"sku": {
"system_field": "sku",
"label": "AWS Sku",
"source_column": source_column(columns.get("sku")),
},
"reservation_id": {
"system_field": "reservation_id",
"label": "Reservation ID",
"source_column": source_column(columns.get("reservation_id")),
"alternatives": list(_RESERVATION_HEADER_PRIORITY),
},
"available_qty": {
"system_field": "available_qty",
"label": "可用数量",
"source_column": qty_source,
"qty_preference": qty_note,
},
},
"match_key": ["sku", "reservation_id"],
"match_rule": "按 AWS Sku + Reservation ID 汇总可用数量,与订单 qty 比对",
}
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]:
"""Preview for human confirmation before match_inventory."""
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 order_has_reservation and not inv_has_reservation:
warnings.append(
"订单含 Reservation ID,但库存未解析到 reservation_id;"
"请确认是否将 COM ID / Reservation Order 列映射为 Reservation ID。"
)
if order_has_reservation and not res_source:
warnings.append("库存表未识别到 Reservation ID 相关列(COM ID / Reservation Order 等)。")
sku_source = (inv_mapping.get("sku") or {}).get("source_column")
if notice_lines and inventory_lines and not sku_source:
warnings.append("库存表未识别到 AWS 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 = [
{
"sku": str(line.get("sku") 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 = [
{
"sku": line.get("sku"),
"reservation_id": line.get("reservation_id", ""),
"available_qty": line.get("available_qty"),
}
for line in inventory_lines[:5]
]
return {
"match_rule": mapping.get("match_rule") or describe_inventory_columns([])["match_rule"],
"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]]:
"""Parse inventory table rows (Excel or document-extractor text)."""
if field_mapping:
from app.services.shipping_notice.inventory_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 = columns["sku"] is not None or columns["available_qty"] is not None or columns["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 rows[1:]:
for row in data_rows:
if not row:
continue
sku = str(row[idx_sku] or "").strip() if idx_sku < len(row) else ""
if not sku:
continue
try:
qty = float(row[idx_qty] if idx_qty < len(row) else 0)
except (TypeError, ValueError):
qty = 0.0
lines.append({"sku": sku, "available_qty": qty})
parsed = _normalize_inventory_row(list(row), columns)
if parsed:
lines.append(parsed)
return lines
def ingest_inventory_file(source_path: Path, *, move_to: Path | None = None) -> list[dict[str, Any]]:
lines = parse_inventory_excel(source_path)
def parse_inventory_text(
raw_text: str,
*,
field_mapping: dict[str, str] | None = None,
) -> tuple[list[dict[str, Any]], list[str], dict[str, Any]]:
"""Parse inventory from chat text or document-extractor output (Excel/CSV tables)."""
warnings: list[str] = []
empty_meta: dict[str, Any] = {"headers": [], "mapping": {}, "match_key": ["sku", "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.inventory_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["sku"] 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]:
"""Read headers + sample rows only (safe for LLM context)."""
from app.services.shipping_notice.inventory_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": {
"sku": "料号 / AWS Sku",
"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",
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
rows, _total = _load_excel_rows(path)
if not rows:
return [], {"headers": [], "mapping": {}, "match_key": ["sku", "reservation_id"]}
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.inventory_mapping import suggest_field_mapping
suggested = suggest_field_mapping(headers)
if suggested.get("sku") 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
return lines, meta
def parse_inventory_excel(path: Path) -> list[dict[str, Any]]:
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",
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
lines, column_meta = parse_inventory_excel_with_meta(
source_path,
field_mapping=field_mapping,
mapping_source=mapping_source,
)
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
return lines, column_meta
@@ -0,0 +1,63 @@
from __future__ import annotations
import re
from pathlib import Path
from typing import Any
from flask import current_app
from werkzeug.datastructures import FileStorage
from app.services.shipping_notice.export import _storage_root
from app.services.shipping_notice.inventory_snapshot import (
parse_inventory_excel_with_meta,
read_inventory_schema_preview,
)
def inventory_text_max_chars() -> int:
try:
return int(current_app.config.get("SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS") or 80000)
except (TypeError, ValueError):
return 80000
def case_inventory_upload_path(case_no: str) -> Path:
safe = re.sub(r"[^\w\-]+", "_", str(case_no or "").strip()) or "unknown"
return _storage_root() / "inventory_uploads" / safe / "inventory.xlsx"
def save_case_inventory_upload(case_no: str, upload: FileStorage) -> Path:
path = case_inventory_upload_path(case_no)
path.parent.mkdir(parents=True, exist_ok=True)
upload.save(str(path))
return path
def read_case_inventory_schema_preview(case_no: str) -> dict[str, Any]:
path = case_inventory_upload_path(case_no)
if not path.is_file():
raise FileNotFoundError(f"未找到 case {case_no} 的库存上传文件")
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = path.name
return preview
def parse_uploaded_case_inventory(
case_no: str,
*,
field_mapping: dict[str, str] | None = None,
mapping_source: str = "rules",
) -> tuple[list[dict[str, Any]], dict[str, Any], Path]:
path = case_inventory_upload_path(case_no)
if not path.is_file():
raise FileNotFoundError(f"未找到 case {case_no} 的库存上传文件")
lines, column_meta = parse_inventory_excel_with_meta(
path,
field_mapping=field_mapping,
mapping_source=mapping_source,
)
return lines, column_meta, path
def has_uploaded_case_inventory(case_no: str) -> bool:
return case_inventory_upload_path(case_no).is_file()
+50 -11
View File
@@ -3,19 +3,55 @@ from __future__ import annotations
from typing import Any
from app.services.shipping_notice.reservation_id import normalize_reservation_id
def _norm(value: Any) -> str:
return str(value or "").strip()
def _norm_reservation(value: Any) -> str:
return normalize_reservation_id(value)
def _line_key(sku: str, reservation_id: str | None) -> tuple[str, str]:
return (_norm(sku), _norm_reservation(reservation_id))
def _aggregate_inventory(inventory_lines: list[dict[str, Any]]) -> dict[tuple[str, str], float]:
"""Sum available_qty by (AWS Sku, Reservation ID). Same key rows are aggregated."""
totals: dict[tuple[str, str], float] = {}
for row in inventory_lines:
sku = _norm(row.get("sku"))
if not sku:
continue
try:
qty = float(row.get("available_qty") or 0)
except (TypeError, ValueError):
qty = 0.0
key = _line_key(sku, row.get("reservation_id"))
totals[key] = totals.get(key, 0.0) + qty
return totals
def _available_for_notice_line(
sku: str,
reservation_id: str | None,
inv_totals: dict[tuple[str, str], float],
) -> float:
sku_n = _norm(sku)
rid = _norm_reservation(reservation_id)
if rid:
return inv_totals.get((sku_n, rid), 0.0)
# 订单未带 Reservation ID 时,按 SKU 汇总所有 reservation 的可用量
return sum(qty for (s, _r), qty in inv_totals.items() if s == sku_n)
def match_notice_lines(
notice_lines: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
) -> tuple[str, list[dict[str, Any]], dict[str, Any]]:
inv_map: dict[str, float] = {}
for row in inventory_lines:
sku = str(row.get("sku") or "").strip()
if not sku:
continue
try:
inv_map[sku] = float(row.get("available_qty") or 0)
except (TypeError, ValueError):
inv_map[sku] = 0.0
inv_totals = _aggregate_inventory(inventory_lines)
line_results: list[dict[str, Any]] = []
shortages: list[dict[str, Any]] = []
@@ -23,12 +59,14 @@ def match_notice_lines(
has_shortage = False
for line in notice_lines:
sku = str(line.get("sku") or "").strip()
sku = _norm(line.get("sku"))
reservation_id = _norm_reservation(line.get("reservation_id")) or None
try:
required = float(line.get("qty") or 0)
except (TypeError, ValueError):
required = 0.0
available = inv_map.get(sku, 0.0)
available = _available_for_notice_line(sku, reservation_id, inv_totals)
if available >= required:
line_status = "ok"
shortage = 0.0
@@ -43,6 +81,7 @@ def match_notice_lines(
result = {
"sku": sku,
"reservation_id": reservation_id or "",
"required_qty": required,
"available_qty": available,
"shortage_qty": shortage,
@@ -0,0 +1,410 @@
from __future__ import annotations
import re
from typing import Any
from app.services.shipping_notice.reservation_id import (
looks_like_reservation_id,
normalize_reservation_id,
)
NOTICE_LINE_FIELDS = (
"sku",
"qty",
"unit_price",
"amount",
"reservation_id",
"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 No": "sku",
# 需求数量
"数量": "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",
# 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",
# 单位
"单位": "uom",
"UOM": "uom",
"uom": "uom",
"Unit": "uom",
}
NOTICE_FIELD_LABELS = {
"sku": "SKU / 料号",
"qty": "需求数量",
"unit_price": "单价",
"amount": "金额",
"reservation_id": "Reservation ID(常见纯数字,如 1000140351)",
}
_HEADER_SKIP_TOKENS = {
"sku",
"料号",
"aws sku",
"qty",
"quantity",
"数量",
"reservation id",
"com id",
"单价",
"unit price",
"金额",
"amount",
}
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 _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()
try:
return float(text)
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 normalize_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_res = columns.get("reservation_id")
reservation_id = ""
if idx_res is not None:
reservation_id = normalize_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")
if idx_price is not None:
unit_price = _parse_number(_cell(row, idx_price))
if unit_price is not None:
parsed["unit_price"] = unit_price
idx_amount = columns.get("amount")
if idx_amount is not None:
amount = _parse_number(_cell(row, idx_amount))
if amount is not None:
parsed["amount"] = amount
idx_uom = columns.get("uom")
if idx_uom is not None:
uom = str(_cell(row, idx_uom) or "").strip()
if uom:
parsed["uom"] = uom
# 若仅有 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
def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
if not isinstance(raw, dict):
return None
sku = str(raw.get("sku") or raw.get("part_number") or raw.get("material") or "").strip()
if not sku:
return None
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
line: dict[str, Any] = {
"sku": sku,
"qty": qty,
"uom": str(raw.get("uom") or "EA").strip() or "EA",
}
reservation_id = normalize_reservation_id(
raw.get("reservation_id")
or raw.get("reservationId")
or raw.get("com_id")
or raw.get("reservation_order")
)
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"))
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"))
if amount is not None:
line["amount"] = amount
elif unit_price is not None:
line["amount"] = round(unit_price * qty, 4)
remark = str(raw.get("remark") or raw.get("note") or "").strip()
if remark:
line["remark"] = remark
return line
def normalize_notice_lines(lines: list[Any] | None) -> list[dict[str, Any]]:
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)
if parsed:
normalized.append(parsed)
return normalized
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]]:
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 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:
warnings.append("未解析到有效订单行(需至少包含 SKU 与需求数量)。")
return warnings
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 请核对表头。"
)
elif missing_reservation:
warnings.append(
f"部分订单行缺少 Reservation ID({len(missing_reservation)}/{len(lines)} 行),"
"这些行将按 SKU 汇总库存比对。"
)
invalid_reservation = [
line["sku"]
for line in lines
if str(line.get("reservation_id") or "").strip()
and not looks_like_reservation_id(line.get("reservation_id"))
]
if invalid_reservation:
warnings.append(
f"{len(invalid_reservation)} 行 Reservation ID 非典型纯数字格式(常见为 8~12 位,如 1000140351),"
"请核对是否解析正确。"
)
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:
"""0~1 score for how complete order lines are (sku/qty/reservation/price)."""
if not lines:
return 0.0
scores: list[float] = []
for line in lines:
item = 0.0
if line.get("sku"):
item += 0.35
if line.get("qty"):
item += 0.35
if 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)
@@ -48,7 +48,6 @@ def _post_op(
},
}
},
"security": [{"ShippingToolKey": []}],
}
}
@@ -69,17 +68,6 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。",
},
"servers": [{"url": server}],
"components": {
"securitySchemes": {
"ShippingToolKey": {
"type": "apiKey",
"in": "header",
"name": "X-Shipping-Tool-Key",
"description": "与 hxops SHIPPING_NOTICE_TOOL_API_KEY 相同",
}
}
},
"security": [{"ShippingToolKey": []}],
"paths": {
"/tools/create_case": _post_op(
"create_case",
@@ -100,9 +88,50 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
required=["case_id"],
),
"/tools/parse_inventory": _post_op(
"parse_inventory",
"解析库存。大 Excel 禁止 raw_inventory_text(会超 LLM token);"
"先 POST /tools/upload_inventory_file 上传,再 get_inventory_schema_preview → "
"apply_inventory_mapping;或 use_uploaded_file=true(规则映射兜底)。小表可粘贴文本。"
"成功后 stop_agent_turn,等 confirm_inventory_mapping 后再 match。",
{
"case_id": case_id,
"use_uploaded_file": _str_prop(
"true=解析该 case 已上传的 Excel(服务端直传,不经过 LLM)",
enum=["true", "false"],
),
"column_mapping_json": _str_prop(
'可选,列映射 JSON 字符串,如 {"sku":"AWS Sku","available_qty":"Qty Available"}'
),
"raw_inventory_text": _str_prop(
"仅小表(约 <8 万字符)。大 Excel 勿传此字段,改用 upload_inventory_file"
),
"inventory_lines_json": _str_prop(
'可选,已整理好的 JSON 数组字符串,如 [{"sku":"A001","available_qty":10}]'
),
},
required=["case_id"],
),
"/tools/get_inventory_schema_preview": _post_op(
"get_inventory_schema_preview",
"读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)",
{"case_id": case_id},
required=["case_id"],
),
"/tools/apply_inventory_mapping": _post_op(
"apply_inventory_mapping",
"应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认",
{
"case_id": case_id,
"column_mapping_json": _str_prop(
'列映射 JSON,如 {"sku":"料号","reservation_id":"COM ID","available_qty":"Qty Available"}'
),
},
required=["case_id", "column_mapping_json"],
),
"/tools/ensure_inventory": _post_op(
"ensure_inventory",
"确保库存快照可用(RPA 或手工 JSON)",
"确保库存快照可用(RPA 自动导出;对话库存请优先用 parse_inventory)",
{
"case_id": case_id,
"mode": _str_prop("auto=自动/RPA;retry_rpa=重试 RPA", enum=["auto", "retry_rpa"]),
@@ -114,7 +143,8 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
),
"/tools/match_inventory": _post_op(
"match_inventory",
"匹配发货需求与库存",
"匹配发货需求与库存。前置条件:submit_decision(confirm_inventory_mapping) 已成功;"
"未确认时调用会被拒绝并返回 forbidden_next_tools",
{
"case_id": case_id,
"inventory_lines_json": _str_prop("可选,覆盖库存 JSON 数组后再匹配"),
@@ -123,20 +153,31 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
),
"/tools/submit_decision": _post_op(
"submit_decision",
"人工复核决策",
"人工复核决策。case_id 与 conversation_id 至少传一个;用户确认时禁止 create_case",
{
"case_id": case_id,
"conversation_id": _str_prop("Dify 会话 ID;用户仅回复「确认」时用于定位 case"),
"decision": _str_prop(
"confirm=确认继续;reject=驳回;rematch=重新匹配;reparse=重新解析",
enum=["confirm", "reject", "rematch", "reparse"],
"confirm=确认继续;reject=驳回;rematch=重新匹配;reparse=重新解析;"
"confirm_inventory_mapping=确认库存字段对齐;correct_inventory_mapping=更正列映射;reparse_inventory=重新上传库存",
enum=[
"confirm",
"confirm_parse",
"reject",
"rematch",
"reparse",
"confirm_inventory_mapping",
"correct_inventory_mapping",
"reparse_inventory",
],
),
"comment": _str_prop("备注(可选)"),
},
required=["case_id", "decision"],
required=["decision"],
),
"/tools/generate_shipment_excel": _post_op(
"generate_shipment_excel",
"生成固定模板发货 Excel",
"生成固定模板发货 Excel(须 match_inventory 成功且 process_status=matched)",
{"case_id": case_id},
required=["case_id"],
),
@@ -155,9 +196,11 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
),
"/tools/get_case_status": _post_op(
"get_case_status",
"查询 case 当前状态与 human_options",
{"case_id": case_id},
required=["case_id"],
"查询 case 当前状态与 human_options。case_id 与 conversation_id 至少传一个",
{
"case_id": case_id,
"conversation_id": _str_prop("Dify 会话 ID"),
},
),
},
}
@@ -0,0 +1,41 @@
from __future__ import annotations
import re
from typing import Any
# 常见 Reservation ID:纯数字,如 1000140351(通常 8~12 位)
RESERVATION_ID_NUMERIC_RE = re.compile(r"^\d{8,12}$")
def normalize_reservation_id(value: Any) -> str:
"""Normalize reservation id; Excel often stores numeric ids as float."""
if value is None:
return ""
if isinstance(value, bool):
return ""
if isinstance(value, float):
if value != value: # NaN
return ""
if value.is_integer():
return str(int(value))
text = str(value).strip()
elif isinstance(value, int):
text = str(value)
else:
text = str(value).strip()
if not text:
return ""
text = text.replace(",", "").replace(",", "").strip()
if re.fullmatch(r"\d+\.0+", text):
text = text.split(".", 1)[0]
return text
def looks_like_reservation_id(value: Any) -> bool:
text = normalize_reservation_id(value)
return bool(text and RESERVATION_ID_NUMERIC_RE.fullmatch(text))
@@ -10,6 +10,10 @@ def tool_response(
message: str = "",
data: dict[str, Any] | None = None,
human_options: list[str] | None = None,
checkpoint: str | None = None,
next_required_action: str | None = None,
forbidden_next_tools: list[str] | None = None,
stop_agent_turn: bool = False,
) -> dict[str, Any]:
payload: dict[str, Any] = {
"status": status,
@@ -20,4 +24,12 @@ def tool_response(
payload["case_id"] = case_id
if human_options:
payload["human_options"] = human_options
if checkpoint:
payload["checkpoint"] = checkpoint
if next_required_action:
payload["next_required_action"] = next_required_action
if forbidden_next_tools:
payload["forbidden_next_tools"] = forbidden_next_tools
if stop_agent_turn:
payload["stop_agent_turn"] = True
return payload
+708 -72
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import re
import uuid
from datetime import datetime
from pathlib import Path
@@ -12,7 +13,24 @@ from app.models import ShippingCase, ShippingCaseEvent
from app.services.shipping_notice.export import generate_shipment_excel
from app.services.shipping_notice.extract import extract_notice_fields
from app.services.shipping_notice.match import match_notice_lines
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
from app.services.shipping_notice.inventory_snapshot import (
build_field_alignment_preview,
ingest_inventory_file,
parse_inventory_text,
)
from app.services.shipping_notice.inventory_mapping import (
mapping_is_complete,
normalize_field_mapping,
validate_field_mapping_against_headers,
)
from app.services.shipping_notice.inventory_upload import (
case_inventory_upload_path,
has_uploaded_case_inventory,
inventory_text_max_chars,
parse_uploaded_case_inventory,
read_case_inventory_schema_preview,
save_case_inventory_upload,
)
from app.services.shipping_notice.rpa import (
find_latest_inventory_file,
inventory_processed_dir,
@@ -22,6 +40,165 @@ from app.services.shipping_notice.rpa import (
from app.services.shipping_notice.tool_response import tool_response
def _mapping_review_enabled() -> bool:
val = current_app.config.get("SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW")
if val is None:
return True
return str(val).lower() not in {"0", "false", "no", "off"}
def _awaiting_inventory_mapping_confirm(case: ShippingCase) -> bool:
return case.review_status == "inventory_mapping_review"
def _match_completed(case: ShippingCase) -> bool:
return bool(
case.process_status == "matched"
and case.match_status
and isinstance(case.line_results_json, list)
and len(case.line_results_json) > 0
)
def _excel_gate_error(case: ShippingCase) -> str | None:
if case.process_status == "uploaded" and case.export_file_path:
return None
if not _match_completed(case):
return "尚未完成库存匹配。请先上传库存、确认字段对齐并调用 match_inventory。"
return None
def _latest_inventory_column_meta(case: ShippingCase) -> dict[str, Any] | None:
if case.id is None:
return None
events = (
ShippingCaseEvent.query.filter_by(case_id=case.id)
.order_by(ShippingCaseEvent.id.desc())
.limit(30)
.all()
)
for event in events:
detail = event.detail_json or {}
meta = detail.get("column_meta")
if isinstance(meta, dict) and meta:
return meta
return None
def _field_alignment_for_case(case: ShippingCase, column_meta: dict[str, Any] | None = None) -> dict[str, Any]:
meta = column_meta or _latest_inventory_column_meta(case)
return build_field_alignment_preview(
case.inventory_lines_json or [],
case.lines_json or [],
column_meta=meta,
)
def _inventory_mapping_checkpoint_response(
case: ShippingCase,
*,
message: str,
column_meta: dict[str, Any] | None = None,
extra_data: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Agent MUST stop and wait for user before match_inventory."""
field_alignment = _field_alignment_for_case(case, column_meta)
data = {
**_serialize_case(case),
"field_alignment": field_alignment,
**(extra_data or {}),
}
return tool_response(
status="needs_human",
case_id=case.case_no,
message=message,
data=data,
human_options=["confirm_inventory_mapping", "correct_inventory_mapping", "reparse_inventory", "reject"],
checkpoint="inventory_field_mapping_review",
next_required_action=(
"向用户展示 data.field_alignment 后停止本轮;"
"用户口头确认后调用 submit_decision(decision=confirm_inventory_mapping);"
"禁止在同一轮调用 match_inventory"
),
forbidden_next_tools=[
"match_inventory",
"generate_shipment_excel",
"upload_to_freight",
],
stop_agent_turn=True,
)
def _inventory_loaded_response(
case: ShippingCase,
inventory_lines: list[dict[str, Any]],
*,
warnings: list[str] | None = None,
column_meta: dict[str, Any] | None = None,
source: str,
require_mapping_review: bool,
event_type: str,
) -> dict[str, Any]:
case.inventory_lines_json = inventory_lines
case.process_status = "inventory_ready"
case.error_message = None
field_alignment = _field_alignment_for_case(case, column_meta)
if require_mapping_review and _mapping_review_enabled():
case.review_status = "inventory_mapping_review"
case.pending_human_reason = "inventory_field_mapping_review"
_log_event(
case,
event_type,
{
"row_count": len(inventory_lines),
"warnings": warnings or [],
"source": source,
"mapping_review": True,
"column_meta": column_meta,
},
)
db.session.commit()
return _inventory_mapping_checkpoint_response(
case,
message=(
f"【必须暂停】已解析库存 {len(inventory_lines)} 行。"
"请先向用户展示字段对齐表并等待确认;"
"禁止在本轮调用 match_inventory。"
),
column_meta=column_meta,
extra_data={
"inventory_row_count": len(inventory_lines),
"warnings": warnings or [],
},
)
case.review_status = None
case.pending_human_reason = None
_log_event(
case,
event_type,
{
"row_count": len(inventory_lines),
"warnings": warnings or [],
"source": source,
"column_meta": column_meta,
},
)
db.session.commit()
return tool_response(
status="ok",
case_id=case.case_no,
message=f"已载入库存 {len(inventory_lines)} 行,可进行匹配。",
data={
**_serialize_case(case),
"inventory_row_count": len(inventory_lines),
"field_alignment": field_alignment,
"warnings": warnings or [],
},
)
def _parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | None:
raw = payload.get("inventory_lines")
if isinstance(raw, list) and raw:
@@ -53,6 +230,14 @@ def _log_event(case: ShippingCase, event_type: str, detail: dict[str, Any] | Non
))
_CASE_NO_RE = re.compile(r"SN-\d{8}-[A-F0-9]{8}", re.IGNORECASE)
def _extract_case_no(text: str) -> str | None:
match = _CASE_NO_RE.search(str(text or ""))
return match.group(0).upper() if match else None
def _get_case(case_id: str) -> ShippingCase | None:
value = str(case_id or "").strip()
if not value:
@@ -65,6 +250,34 @@ def _get_case(case_id: str) -> ShippingCase | None:
return None
def _resolve_case_from_payload(payload: dict[str, Any]) -> ShippingCase | None:
"""Resolve case by case_id/case_no, embedded SN- in text fields, or conversation_id."""
if not isinstance(payload, dict):
return None
for key in ("case_id", "case_no"):
case = _get_case(str(payload.get(key) or ""))
if case:
return case
for key in ("comment", "user_message", "raw_text", "query"):
hint = _extract_case_no(str(payload.get(key) or ""))
if hint:
case = _get_case(hint)
if case:
return case
conv_id = str(payload.get("conversation_id") or "").strip()
if conv_id:
return (
ShippingCase.query.filter_by(conversation_id=conv_id)
.filter(ShippingCase.process_status.notin_(["rejected"]))
.order_by(ShippingCase.id.desc())
.first()
)
return None
def _serialize_case(case: ShippingCase) -> dict[str, Any]:
return {
"case_no": case.case_no,
@@ -87,6 +300,26 @@ def _serialize_case(case: ShippingCase) -> dict[str, Any]:
def create_case(payload: dict[str, Any]) -> dict[str, Any]:
conv_id = str(payload.get("conversation_id") or "").strip()
if conv_id:
existing = (
ShippingCase.query.filter_by(conversation_id=conv_id)
.filter(ShippingCase.process_status.notin_(["rejected"]))
.order_by(ShippingCase.id.desc())
.first()
)
if existing and existing.process_status != "uploaded":
return tool_response(
status="ok",
case_id=existing.case_no,
message=(
f"当前会话已有进行中的发货任务 {existing.case_no},请勿重复 create_case。"
"用户确认/驳回时请 submit_decision,并带上 case_id 或 conversation_id。"
),
data=_serialize_case(existing),
checkpoint="case_already_exists",
)
case = ShippingCase(
case_no=_generate_case_no(),
user_id=payload.get("user_id"),
@@ -107,10 +340,14 @@ def create_case(payload: dict[str, Any]) -> dict[str, Any]:
def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
case = _get_case(str(payload.get("case_id") or ""))
case = _resolve_case_from_payload(payload)
if not case:
return tool_response(status="failed", message="未找到 case_id")
conv_id = str(payload.get("conversation_id") or "").strip()
if conv_id and not case.conversation_id:
case.conversation_id = conv_id
raw_text = str(payload.get("raw_text") or case.raw_content or "").strip()
structured = payload.get("structured") if isinstance(payload.get("structured"), dict) else None
parsed, confidence, warnings = extract_notice_fields(
@@ -138,7 +375,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status="needs_human",
case_id=case.case_no,
message="解析置信度较低,请核对客户、料号、数量是否正确。",
message="解析置信度较低,请核对 SKU、需求数量、Reservation ID、单价与金额是否正确。",
data={**_serialize_case(case), "warnings": warnings},
human_options=["confirm", "reject", "reparse"],
)
@@ -153,25 +390,283 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
)
def _resolve_inventory_field_mapping(payload: dict[str, Any]) -> tuple[dict[str, str] | None, str]:
raw = payload.get("column_mapping_json")
if raw is None:
raw = payload.get("field_mapping")
field_mapping = normalize_field_mapping(raw)
if field_mapping:
return field_mapping, "llm"
return None, "rules"
def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"""Parse inventory from uploaded file, chat text, or structured JSON."""
case = _resolve_case_from_payload(payload)
if not case:
return tool_response(status="failed", message="未找到 case_id")
use_uploaded = str(payload.get("use_uploaded_file") or "").strip().lower() in {
"1",
"true",
"yes",
}
raw_text = str(payload.get("raw_inventory_text") or "").strip()
inventory_lines = _parse_inventory_lines(payload)
warnings: list[str] = []
column_meta: dict[str, Any] | None = None
source = "parse"
field_mapping, mapping_source = _resolve_inventory_field_mapping(payload)
if use_uploaded or (not inventory_lines and not raw_text and has_uploaded_case_inventory(case.case_no)):
if not has_uploaded_case_inventory(case.case_no):
return tool_response(
status="needs_human",
case_id=case.case_no,
message="未找到已上传的库存文件。请先 POST /tools/upload_inventory_file 上传 Excel。",
data=_serialize_case(case),
human_options=["upload_inventory_file", "retry_rpa"],
checkpoint="inventory_upload_required",
stop_agent_turn=True,
)
inventory_lines, column_meta, path = parse_uploaded_case_inventory(
case.case_no,
field_mapping=field_mapping,
mapping_source=mapping_source,
)
source = "uploaded_file"
warnings.append(f"parsed from uploaded file: {path.name}")
elif not inventory_lines:
structured = payload.get("structured") if isinstance(payload.get("structured"), dict) else None
if structured and isinstance(structured.get("lines"), list):
inventory_lines = structured["lines"]
source = "structured"
elif raw_text:
max_chars = inventory_text_max_chars()
if len(raw_text) > max_chars:
_log_event(
case,
"inventory_text_too_large",
{"chars": len(raw_text), "max_chars": max_chars},
)
db.session.commit()
return tool_response(
status="needs_human",
case_id=case.case_no,
message=(
f"库存文本过大({len(raw_text)} 字符,上限 {max_chars})。"
"请勿将 Excel 全文传入 LLM;请用 HTTP 节点调用 "
"POST /tools/upload_inventory_file 上传,再 "
"parse_inventory(use_uploaded_file=true)。"
),
data=_serialize_case(case),
human_options=["upload_inventory_file", "retry_rpa"],
checkpoint="inventory_upload_required",
next_required_action="upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
forbidden_next_tools=["match_inventory"],
stop_agent_turn=True,
)
inventory_lines, warnings, column_meta = parse_inventory_text(
raw_text,
field_mapping=field_mapping,
)
if not inventory_lines:
_log_event(case, "inventory_parse_failed", {"warnings": warnings, "use_uploaded": use_uploaded})
db.session.commit()
return tool_response(
status="needs_human",
case_id=case.case_no,
message="未能解析库存明细。大 Excel 请 upload_inventory_file;小表可粘贴;无库存可走 RPA。",
data={**_serialize_case(case), "warnings": warnings},
human_options=["reparse_inventory", "retry_rpa", "paste_inventory_json"],
)
return _inventory_loaded_response(
case,
inventory_lines,
warnings=warnings,
column_meta=column_meta,
source=source,
require_mapping_review=True,
event_type="inventory_parsed",
)
def get_inventory_schema_preview(payload: dict[str, Any]) -> dict[str, Any]:
"""Return headers + sample rows for LLM column mapping (small payload)."""
case = _resolve_case_from_payload(payload)
if not case:
return tool_response(status="failed", message="未找到 case_id")
if not has_uploaded_case_inventory(case.case_no):
return tool_response(
status="needs_human",
case_id=case.case_no,
message="未找到已上传的库存文件。请先 POST /tools/upload_inventory_file 上传 Excel。",
data=_serialize_case(case),
human_options=["upload_inventory_file", "retry_rpa"],
checkpoint="inventory_upload_required",
stop_agent_turn=True,
)
try:
preview = read_case_inventory_schema_preview(case.case_no)
except OSError as exc:
return tool_response(status="failed", case_id=case.case_no, message=f"读取库存表头失败: {exc}")
_log_event(case, "inventory_schema_preview", {"headers": preview.get("headers")})
db.session.commit()
return tool_response(
status="ok",
case_id=case.case_no,
message=(
"已读取库存表头与样例行。请根据 schema_preview 推断列映射,"
"调用 apply_inventory_mapping(column_mapping_json=...)。"
),
data={**_serialize_case(case), "schema_preview": preview},
checkpoint="inventory_mapping_inference",
next_required_action=(
"根据 data.schema_preview.headers 与 sample_rows 推断 JSON:"
'{"sku":"<列名>","reservation_id":"<列名>","available_qty":"<列名>"},'
"再调用 apply_inventory_mapping"
),
forbidden_next_tools=["match_inventory"],
)
def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]:
"""Apply LLM/manual column mapping and parse full uploaded inventory file."""
case = _resolve_case_from_payload(payload)
if not case:
return tool_response(status="failed", message="未找到 case_id")
field_mapping, mapping_source = _resolve_inventory_field_mapping(payload)
if not field_mapping or not mapping_is_complete(field_mapping):
return tool_response(
status="failed",
case_id=case.case_no,
message=(
"column_mapping_json 无效或不完整。"
'需要 {"sku":"列名","available_qty":"列名","reservation_id":"列名(可选)"}'
),
data=_serialize_case(case),
)
if not has_uploaded_case_inventory(case.case_no):
return tool_response(
status="needs_human",
case_id=case.case_no,
message="未找到已上传的库存文件。请先 upload_inventory_file。",
data=_serialize_case(case),
checkpoint="inventory_upload_required",
stop_agent_turn=True,
)
try:
preview = read_case_inventory_schema_preview(case.case_no)
except OSError as exc:
return tool_response(status="failed", case_id=case.case_no, message=f"读取库存表头失败: {exc}")
mapping_errors = validate_field_mapping_against_headers(
preview.get("headers") or [],
field_mapping,
)
if mapping_errors:
header_row = preview.get("header_row_index") or 1
return tool_response(
status="failed",
case_id=case.case_no,
message=(
"列映射与 Excel 表头不匹配。"
f"(表头在第 {header_row} 行)"
+ " ".join(mapping_errors)
+ " 请根据 schema_preview.headers 重新调用 apply_inventory_mapping。"
),
data={**_serialize_case(case), "schema_preview": preview},
)
try:
inventory_lines, column_meta, path = parse_uploaded_case_inventory(
case.case_no,
field_mapping=field_mapping,
mapping_source=mapping_source,
)
except FileNotFoundError as exc:
return tool_response(status="failed", case_id=case.case_no, message=str(exc))
except OSError as exc:
return tool_response(status="failed", case_id=case.case_no, message=f"解析库存失败: {exc}")
warnings = [f"parsed with mapping from uploaded file: {path.name}"]
return _inventory_loaded_response(
case,
inventory_lines,
warnings=warnings,
column_meta=column_meta,
source="uploaded_file_mapping",
require_mapping_review=True,
event_type="inventory_mapping_applied",
)
def upload_inventory_file(case_id: str, upload: Any) -> dict[str, Any]:
"""Save multipart Excel; return schema preview for LLM mapping (no full parse)."""
case = _get_case(str(case_id or ""))
if not case:
return tool_response(status="failed", message="未找到 case_id")
if upload is None or not getattr(upload, "filename", None):
return tool_response(status="failed", case_id=case.case_no, message="未收到 file 字段")
filename = str(upload.filename or "").strip()
if not filename.lower().endswith((".xlsx", ".xls", ".csv")):
return tool_response(
status="failed",
case_id=case.case_no,
message="仅支持 .xlsx / .xls / .csv 库存文件",
)
try:
save_case_inventory_upload(case.case_no, upload)
preview = read_case_inventory_schema_preview(case.case_no)
except OSError as exc:
return tool_response(status="failed", case_id=case.case_no, message=f"保存库存文件失败: {exc}")
case.process_status = "waiting_inventory"
case.pending_human_reason = "inventory_mapping_inference"
_log_event(
case,
"inventory_file_uploaded",
{"filename": filename, "headers": preview.get("headers")},
)
db.session.commit()
return tool_response(
status="ok",
case_id=case.case_no,
message=(
"库存文件已上传。请根据 schema_preview 推断列映射,"
"调用 apply_inventory_mapping;或 get_inventory_schema_preview 重新读取表头。"
),
data={**_serialize_case(case), "schema_preview": preview},
checkpoint="inventory_mapping_inference",
next_required_action="apply_inventory_mapping(column_mapping_json=...)",
forbidden_next_tools=["match_inventory"],
)
def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
case = _get_case(str(payload.get("case_id") or ""))
case = _resolve_case_from_payload(payload)
if not case:
return tool_response(status="failed", message="未找到 case_id")
mode = str(payload.get("mode") or "auto").strip().lower()
inventory_lines = _parse_inventory_lines(payload)
if inventory_lines:
case.inventory_lines_json = inventory_lines
case.process_status = "inventory_ready"
case.pending_human_reason = None
case.error_message = None
_log_event(case, "inventory_uploaded", {"row_count": len(inventory_lines)})
db.session.commit()
return tool_response(
status="ok",
case_id=case.case_no,
message=f"已载入库存 {len(inventory_lines)} 行,可进行匹配。",
data=_serialize_case(case),
return _inventory_loaded_response(
case,
inventory_lines,
source="manual_json",
require_mapping_review=False,
event_type="inventory_uploaded",
)
if mode == "retry_rpa" or mode == "auto":
@@ -179,18 +674,15 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
processed = inventory_processed_dir()
if latest and processed:
try:
lines = ingest_inventory_file(latest, move_to=processed)
lines, column_meta = ingest_inventory_file(latest, move_to=processed)
if lines:
case.inventory_lines_json = lines
case.process_status = "inventory_ready"
case.pending_human_reason = None
_log_event(case, "inventory_rpa_drop_ingested", {"file": latest.name, "rows": len(lines)})
db.session.commit()
return tool_response(
status="ok",
case_id=case.case_no,
message=f"已从 RPA 落盘载入库存 {len(lines)} 行。",
data=_serialize_case(case),
return _inventory_loaded_response(
case,
lines,
column_meta=column_meta,
source="rpa_drop",
require_mapping_review=True,
event_type="inventory_rpa_drop_ingested",
)
except Exception as exc:
case.error_message = str(exc)[:500]
@@ -219,12 +711,17 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
)
if case.inventory_lines_json:
if _awaiting_inventory_mapping_confirm(case):
return _inventory_mapping_checkpoint_response(
case,
message="库存已解析但未确认字段对齐,请先展示 field_alignment 并等待用户确认。",
)
case.process_status = "inventory_ready"
db.session.commit()
return tool_response(
status="ok",
case_id=case.case_no,
message="已有库存快照,可进行匹配。",
message="已有库存快照且字段对齐已确认,可调用 match_inventory。",
data=_serialize_case(case),
)
@@ -242,10 +739,16 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
case = _get_case(str(payload.get("case_id") or ""))
case = _resolve_case_from_payload(payload)
if not case:
return tool_response(status="failed", message="未找到 case_id")
if _awaiting_inventory_mapping_confirm(case):
return _inventory_mapping_checkpoint_response(
case,
message="【禁止匹配】尚未确认库存字段对齐。请先展示 field_alignment,等用户确认后再 submit_decision(confirm_inventory_mapping)。",
)
inventory_lines = _parse_inventory_lines(payload)
if inventory_lines:
case.inventory_lines_json = inventory_lines
@@ -289,9 +792,15 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
case = _get_case(str(payload.get("case_id") or ""))
case = _resolve_case_from_payload(payload)
if not case:
return tool_response(status="failed", message="未找到 case_id")
return tool_response(
status="failed",
message=(
"未找到 case。用户说「确认/重新解析/驳回」时禁止 create_case。"
"请先 get_case_status(conversation_id=...) 或 submit_decision 带上 case_id。"
),
)
decision = str(payload.get("decision") or "").strip().lower()
comment = str(payload.get("comment") or "").strip()
@@ -309,16 +818,64 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
data=_serialize_case(case),
)
if decision in {"confirm", "confirmed"}:
case.review_status = "confirmed"
case.process_status = "matched"
case.pending_human_reason = None
_log_event(case, "decision_confirmed", {"comment": comment})
db.session.commit()
if decision in {"confirm", "confirmed", "confirm_parse"}:
if case.review_status == "inventory_shortage_review" or case.pending_human_reason == "inventory_shortage":
case.review_status = "confirmed"
case.process_status = "matched"
case.pending_human_reason = None
_log_event(case, "decision_confirmed_shortage", {"comment": comment})
db.session.commit()
return tool_response(
status="ok",
case_id=case.case_no,
message="已确认部分发货,可继续生成 Excel 并上传货代系统。",
data=_serialize_case(case),
)
if (
decision == "confirm_parse"
or case.review_status == "parse_review"
or case.pending_human_reason == "low_parse_confidence"
or (
case.process_status in {"parsed", "pending_review", "created"}
and not _match_completed(case)
)
):
case.review_status = None
case.process_status = "parsed"
case.pending_human_reason = None
_log_event(case, "parse_confirmed", {"comment": comment})
db.session.commit()
return tool_response(
status="ok",
case_id=case.case_no,
message=(
"发货通知已确认。"
"请先处理库存(ensure_inventory / parse_inventory → confirm_inventory_mapping → match_inventory)。"
"禁止跳过匹配直接 generate_shipment_excel。"
),
data=_serialize_case(case),
checkpoint="parse_confirmed",
next_required_action="ensure_inventory 或 parse_inventory",
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
if _match_completed(case):
case.review_status = "confirmed"
case.pending_human_reason = None
_log_event(case, "decision_confirmed", {"comment": comment})
db.session.commit()
return tool_response(
status="ok",
case_id=case.case_no,
message="已确认,可继续生成 Excel 并上传货代系统。",
data=_serialize_case(case),
)
return tool_response(
status="ok",
status="failed",
case_id=case.case_no,
message="已确认,可继续生成 Excel 并上传货代系统。",
message="当前状态无法使用 confirm。请先完成库存匹配,或使用 confirm_inventory_mapping / reparse。",
data=_serialize_case(case),
)
@@ -327,6 +884,94 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
db.session.commit()
return match_inventory({"case_id": case.case_no})
if decision == "confirm_inventory_mapping":
if not _awaiting_inventory_mapping_confirm(case):
return tool_response(
status="failed",
case_id=case.case_no,
message="当前无需确认库存字段对齐。",
data=_serialize_case(case),
)
case.review_status = None
case.pending_human_reason = None
_log_event(case, "inventory_mapping_confirmed", {"comment": comment})
db.session.commit()
return tool_response(
status="ok",
case_id=case.case_no,
message="字段对齐已确认。现在可以调用 match_inventory(仅在本轮或下一轮,勿与 parse_inventory 同轮)。",
data=_serialize_case(case),
checkpoint="inventory_mapping_confirmed",
next_required_action="match_inventory",
)
if decision == "correct_inventory_mapping":
if not _awaiting_inventory_mapping_confirm(case):
return tool_response(
status="failed",
case_id=case.case_no,
message="当前不在库存字段对齐确认步骤,无法更正映射。",
data=_serialize_case(case),
)
case.inventory_lines_json = None
case.review_status = None
case.pending_human_reason = "inventory_mapping_inference"
case.process_status = "waiting_inventory"
_log_event(case, "inventory_mapping_correction_requested", {"comment": comment})
db.session.commit()
upload_path = case_inventory_upload_path(case.case_no)
if upload_path.is_file():
try:
preview = read_case_inventory_schema_preview(case.case_no)
except OSError as exc:
return tool_response(
status="failed",
case_id=case.case_no,
message=f"读取库存表头失败: {exc}",
data=_serialize_case(case),
)
else:
meta = _latest_inventory_column_meta(case) or {}
preview = {
"headers": meta.get("headers") or [],
"sample_rows": [],
"suggested_mapping": meta.get("field_mapping") or {},
"note": "无已上传 Excel;请粘贴库存小表或重新上传后 apply_inventory_mapping / parse_inventory。",
}
return tool_response(
status="ok",
case_id=case.case_no,
message=(
"已回到列映射步骤。请根据 schema_preview 提供新的 column_mapping_json,"
"再调用 apply_inventory_mapping。"
),
data={**_serialize_case(case), "schema_preview": preview},
checkpoint="inventory_mapping_inference",
next_required_action="apply_inventory_mapping(column_mapping_json=...)",
forbidden_next_tools=["match_inventory"],
)
if decision == "reparse_inventory":
case.inventory_lines_json = None
case.review_status = None
case.pending_human_reason = None
if case.process_status == "inventory_ready":
case.process_status = "parsed"
upload_path = case_inventory_upload_path(case.case_no)
if upload_path.is_file():
try:
upload_path.unlink()
except OSError:
pass
_log_event(case, "inventory_reparse_requested", {"comment": comment})
db.session.commit()
return tool_response(
status="ok",
case_id=case.case_no,
message="已清除库存快照,请重新上传或粘贴库存后调用 parse_inventory。",
data=_serialize_case(case),
)
if decision == "reparse":
return parse_notice({"case_id": case.case_no, "raw_text": case.raw_content or ""})
@@ -334,16 +979,19 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
case = _get_case(str(payload.get("case_id") or ""))
case = _resolve_case_from_payload(payload)
if not case:
return tool_response(status="failed", message="未找到 case_id")
if case.process_status not in {"matched", "uploaded"} and case.review_status != "confirmed":
gate_error = _excel_gate_error(case)
if gate_error:
return tool_response(
status="failed",
case_id=case.case_no,
message="当前状态不允许生成 Excel,请先完成匹配或人工确认。",
message=gate_error,
data=_serialize_case(case),
forbidden_next_tools=["upload_to_freight"],
next_required_action="match_inventory(须先完成库存上传与字段对齐确认)",
)
path, filename = generate_shipment_excel(case)
@@ -361,7 +1009,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
case = _get_case(str(payload.get("case_id") or ""))
case = _resolve_case_from_payload(payload)
if not case:
return tool_response(status="failed", message="未找到 case_id")
@@ -414,9 +1062,12 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
def get_case_status(payload: dict[str, Any]) -> dict[str, Any]:
case = _get_case(str(payload.get("case_id") or ""))
case = _resolve_case_from_payload(payload)
if not case:
return tool_response(status="failed", message="未找到 case_id")
return tool_response(
status="failed",
message="未找到 case。请提供 case_id 或 conversation_id(Dify 会话 ID)。",
)
return tool_response(
status="ok",
case_id=case.case_no,
@@ -427,24 +1078,13 @@ def get_case_status(payload: dict[str, Any]) -> dict[str, Any]:
def _human_options_for_case(case: ShippingCase) -> list[str] | None:
reason = case.pending_human_reason
if reason == "inventory_unavailable":
return ["retry_rpa", "upload_inventory_file"]
if reason == "inventory_shortage":
return ["confirm", "reject", "rematch"]
if reason == "low_parse_confidence" or case.review_status == "parse_review":
return ["confirm", "reject", "reparse"]
if reason == "upload_rpa_failed" or case.process_status == "upload_failed":
return ["retry_upload", "download_excel", "mark_manual_uploaded"]
if reason == "inventory_rpa_pending" or case.process_status == "waiting_inventory":
return ["retry_rpa", "upload_inventory_file"]
if reason == "upload_rpa_pending" or case.process_status == "waiting_upload":
return ["retry_upload", "download_excel", "mark_manual_uploaded"]
return None
from app.services.shipping_notice.chat_actions import human_options_for_case
return human_options_for_case(case)
def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
case = _get_case(str(payload.get("case_no") or ""))
case = _resolve_case_from_payload(payload)
if not case:
return tool_response(status="failed", message="未找到 case_id")
@@ -469,23 +1109,19 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(status="failed", case_id=case.case_no, message="库存文件不存在")
processed = inventory_processed_dir()
lines = ingest_inventory_file(path, move_to=processed)
case.inventory_lines_json = lines
case.process_status = "inventory_ready"
case.pending_human_reason = None
case.error_message = None
_log_event(case, "inventory_rpa_ready", {"file": path.name, "rows": len(lines)})
db.session.commit()
return tool_response(
status="ok",
case_id=case.case_no,
message=f"RPA 库存已就绪,共 {len(lines)} 行。",
data=_serialize_case(case),
lines, column_meta = ingest_inventory_file(path, move_to=processed)
return _inventory_loaded_response(
case,
lines,
column_meta=column_meta,
source="rpa_callback",
require_mapping_review=True,
event_type="inventory_rpa_ready",
)
def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
case = _get_case(str(payload.get("case_no") or ""))
case = _resolve_case_from_payload(payload)
if not case:
return tool_response(status="failed", message="未找到 case_id")