diff --git a/.env.dev b/.env.dev index 9eccc536..33cc611c 100644 --- a/.env.dev +++ b/.env.dev @@ -58,7 +58,7 @@ MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000 # 货代发货通知 Agent SHIPPING_NOTICE_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh # OpenAPI / Dify Tool 调用基地址(默认等于 PUBLIC_BASE_URL) -SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.100.192:8890 +SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.36.114:5052/api/shipping-notice SHIPPING_NOTICE_STORAGE_ROOT=backend/data/shipping_notice FREIGHT_INVENTORY_DROP_DIR=backend/data/freight_rpa/inventory_drop FREIGHT_RPA_INVENTORY_TRIGGER_DIR=backend/data/freight_rpa/inventory_triggers diff --git a/backend/app/api/shipping_notice_tools.py b/backend/app/api/shipping_notice_tools.py index 296f2746..d0d0403e 100644 --- a/backend/app/api/shipping_notice_tools.py +++ b/backend/app/api/shipping_notice_tools.py @@ -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())) diff --git a/backend/app/api/workspace_shipping_notice.py b/backend/app/api/workspace_shipping_notice.py index cd40fb07..5007432d 100644 --- a/backend/app/api/workspace_shipping_notice.py +++ b/backend/app/api/workspace_shipping_notice.py @@ -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//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//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//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//export", methods=["GET"]) def workspace_shipping_case_export(case_no: str): user, err = _require_user() diff --git a/backend/app/config.py b/backend/app/config.py index 66e39288..60d431ae 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -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') diff --git a/backend/app/services/shipping_notice/chat_actions.py b/backend/app/services/shipping_notice/chat_actions.py new file mode 100644 index 00000000..e41c6366 --- /dev/null +++ b/backend/app/services/shipping_notice/chat_actions.py @@ -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, + } diff --git a/backend/app/services/shipping_notice/extract.py b/backend/app/services/shipping_notice/extract.py index e970b582..5750b8b6 100644 --- a/backend/app/services/shipping_notice/extract.py +++ b/backend/app/services/shipping_notice/extract.py @@ -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\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, + ) diff --git a/backend/app/services/shipping_notice/inventory_mapping.py b/backend/app/services/shipping_notice/inventory_mapping.py new file mode 100644 index 00000000..24e99db6 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_mapping.py @@ -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 比对", + } diff --git a/backend/app/services/shipping_notice/inventory_snapshot.py b/backend/app/services/shipping_notice/inventory_snapshot.py index 83d8f084..a8b18d1c 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot.py +++ b/backend/app/services/shipping_notice/inventory_snapshot.py @@ -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 diff --git a/backend/app/services/shipping_notice/inventory_upload.py b/backend/app/services/shipping_notice/inventory_upload.py new file mode 100644 index 00000000..c0d37e3d --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_upload.py @@ -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() diff --git a/backend/app/services/shipping_notice/match.py b/backend/app/services/shipping_notice/match.py index 7fd87d79..1334ea31 100644 --- a/backend/app/services/shipping_notice/match.py +++ b/backend/app/services/shipping_notice/match.py @@ -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, diff --git a/backend/app/services/shipping_notice/notice_lines.py b/backend/app/services/shipping_notice/notice_lines.py new file mode 100644 index 00000000..1ef87294 --- /dev/null +++ b/backend/app/services/shipping_notice/notice_lines.py @@ -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) diff --git a/backend/app/services/shipping_notice/openapi_spec.py b/backend/app/services/shipping_notice/openapi_spec.py index 613426cc..1571cbb8 100644 --- a/backend/app/services/shipping_notice/openapi_spec.py +++ b/backend/app/services/shipping_notice/openapi_spec.py @@ -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"), + }, ), }, } diff --git a/backend/app/services/shipping_notice/reservation_id.py b/backend/app/services/shipping_notice/reservation_id.py new file mode 100644 index 00000000..caa4c8cc --- /dev/null +++ b/backend/app/services/shipping_notice/reservation_id.py @@ -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)) diff --git a/backend/app/services/shipping_notice/tool_response.py b/backend/app/services/shipping_notice/tool_response.py index 51b110d0..b21938d4 100644 --- a/backend/app/services/shipping_notice/tool_response.py +++ b/backend/app/services/shipping_notice/tool_response.py @@ -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 diff --git a/backend/app/services/shipping_notice/tools.py b/backend/app/services/shipping_notice/tools.py index 1afeaea2..0e391687 100644 --- a/backend/app/services/shipping_notice/tools.py +++ b/backend/app/services/shipping_notice/tools.py @@ -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") diff --git a/backend/tests/test_shipping_notice_extract.py b/backend/tests/test_shipping_notice_extract.py new file mode 100644 index 00000000..f06ff2dc --- /dev/null +++ b/backend/tests/test_shipping_notice_extract.py @@ -0,0 +1,111 @@ +from app.services.shipping_notice.extract import extract_notice_fields +from app.services.shipping_notice.notice_lines import ( + normalize_notice_line, + parse_notice_table_rows, + parse_notice_table_text, + validate_notice_lines, +) +from app.services.shipping_notice.reservation_id import ( + looks_like_reservation_id, + normalize_reservation_id, +) + + +def test_normalize_reservation_id_from_excel_float(): + assert normalize_reservation_id(1000140351.0) == "1000140351" + assert normalize_reservation_id("1000140351.0") == "1000140351" + assert looks_like_reservation_id("1000140351") + + +def test_parse_notice_table_numeric_reservation_id(): + text = """ +AWS Sku\tReservation ID\tQty\tUnit Price\tAmount +10-40594-001\t1000140351\t2\t15.5\t31.0 +""" + lines = parse_notice_table_text(text) + assert lines[0]["reservation_id"] == "1000140351" + + +def test_infer_reservation_id_without_header(): + headers = ["AWS Sku", "Ref", "Qty"] + rows = [["10-40594-001", 1000140351, 2]] + lines = parse_notice_table_rows(headers, rows) + assert lines[0]["reservation_id"] == "1000140351" + + +def test_parse_notice_table_with_all_fields(): + text = """ +AWS Sku\tReservation ID\tQty\tUnit Price\tAmount +10-40594-001\tAWS-311\t2\t15.5\t31.0 +10-40594-002\tORD-3002\t1\t20\t20 +""" + lines = parse_notice_table_text(text) + assert len(lines) == 2 + assert lines[0]["sku"] == "10-40594-001" + assert lines[0]["reservation_id"] == "AWS-311" + assert lines[0]["qty"] == 2 + assert lines[0]["unit_price"] == 15.5 + assert lines[0]["amount"] == 31.0 + + +def test_normalize_notice_line_aliases(): + line = normalize_notice_line( + { + "part_number": "A-001", + "quantity": "3", + "com_id": "COM-99", + "price": "12.5", + } + ) + assert line == { + "sku": "A-001", + "qty": 3.0, + "uom": "EA", + "reservation_id": "COM-99", + "unit_price": 12.5, + "amount": 37.5, + } + + +def test_extract_notice_fields_structured(): + structured = { + "customer_name": "ACME", + "lines": [ + { + "sku": "10-40594-001", + "qty": 2, + "reservation_id": "AWS-311", + "unit_price": 10, + "amount": 20, + } + ], + "confidence": 0.9, + } + parsed, confidence, warnings = extract_notice_fields(raw_text="", structured=structured) + assert parsed["lines"][0]["reservation_id"] == "AWS-311" + assert parsed["lines"][0]["amount"] == 20 + assert confidence >= 0.8 + assert not any("未解析到有效订单行" in w for w in warnings) + + +def test_validate_notice_lines_missing_reservation(): + warnings = validate_notice_lines([{"sku": "A001", "qty": 1, "uom": "EA"}]) + assert any("Reservation ID" in w for w in warnings) + + +def test_heuristic_table_skips_title_row(): + from app.services.shipping_notice.extract import _heuristic_extract + + text = """ +Shipping Notice +AWS Sku\tReservation Order\tOrder Qty\tUnit Price\tLine Amount +10-40594-001\tORD-3002\t4\t5\t20 +""" + parsed, confidence, _ = _heuristic_extract(text) + assert len(parsed["lines"]) == 1 + assert parsed["lines"][0]["sku"] == "10-40594-001" + assert parsed["lines"][0]["reservation_id"] == "ORD-3002" + assert parsed["lines"][0]["qty"] == 4 + assert parsed["lines"][0]["unit_price"] == 5 + assert parsed["lines"][0]["amount"] == 20 + assert confidence >= 0.5 diff --git a/backend/tests/test_shipping_notice_inventory_aws.py b/backend/tests/test_shipping_notice_inventory_aws.py new file mode 100644 index 00000000..cb1cef6b --- /dev/null +++ b/backend/tests/test_shipping_notice_inventory_aws.py @@ -0,0 +1,73 @@ +"""Tests for AWS inventory template parsing.""" + +from pathlib import Path + +from openpyxl import Workbook + +from app.services.shipping_notice.inventory_snapshot import ( + parse_inventory_rows, + parse_inventory_text, + read_inventory_schema_preview, +) +from app.services.shipping_notice.match import match_notice_lines + + +def _write_title_row_inventory_xlsx(path: Path) -> None: + wb = Workbook() + ws = wb.active + ws.append(["AWS DUB On Hand Inventory by Location"]) + ws.append([]) + ws.append(["AWS Sku", "COM ID", "Qty Available", "Qty"]) + ws.append(["10-40594-001", "AWS-311", 2, 1]) + wb.save(str(path)) + wb.close() + + +def test_read_inventory_schema_preview_skips_title_row(app, tmp_path): + path = tmp_path / "aws_title.xlsx" + _write_title_row_inventory_xlsx(path) + with app.app_context(): + preview = read_inventory_schema_preview(path) + assert preview["header_row_index"] == 3 + assert preview["headers"] == ["AWS Sku", "COM ID", "Qty Available", "Qty"] + assert preview["suggested_mapping"]["sku"] == "AWS Sku" + assert preview["suggested_mapping"]["available_qty"] == "Qty Available" + assert preview["sample_rows"][0][0] == "10-40594-001" + + +def test_parse_aws_inventory_headers(app): + with app.app_context(): + headers = ["AWS Sku", "COM ID", "Qty Available", "Qty"] + data = [ + ["10-40594-001", "AWS-311", 2, 1], + ["10-40594-002", "ORD-3002", 0, 5], + ] + lines = parse_inventory_rows(headers, data) + assert len(lines) == 2 + assert lines[0]["sku"] == "10-40594-001" + assert lines[0]["reservation_id"] == "AWS-311" + assert lines[0]["available_qty"] == 2.0 + assert lines[1]["reservation_id"] == "ORD-3002" + assert lines[1]["available_qty"] == 0.0 + + +def test_match_aggregates_same_sku_reservation(): + notice = [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 3}] + inventory = [ + {"sku": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 1}, + {"sku": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 2}, + ] + status, results, _ = match_notice_lines(notice, inventory) + assert status == "fulfillable" + assert results[0]["available_qty"] == 3.0 + + +def test_parse_inventory_text_aws_table(app): + with app.app_context(): + text = "AWS Sku\tReservation Order\tQty\n10-40594-001\tORD-3002\t4" + lines, warnings, column_meta = parse_inventory_text(text) + assert not warnings or "no inventory" not in warnings[0] + assert lines[0]["sku"] == "10-40594-001" + assert lines[0]["reservation_id"] == "ORD-3002" + assert lines[0]["available_qty"] == 4.0 + assert column_meta["mapping"]["reservation_id"]["source_column"] == "Reservation Order" diff --git a/backend/tests/test_shipping_notice_reservation_id.py b/backend/tests/test_shipping_notice_reservation_id.py new file mode 100644 index 00000000..91c1bb83 --- /dev/null +++ b/backend/tests/test_shipping_notice_reservation_id.py @@ -0,0 +1,15 @@ +from app.services.shipping_notice.match import match_notice_lines +from app.services.shipping_notice.reservation_id import normalize_reservation_id + + +def test_match_numeric_reservation_id(): + notice = [{"sku": "10-40594-001", "reservation_id": "1000140351", "qty": 2}] + inventory = [{"sku": "10-40594-001", "reservation_id": 1000140351.0, "available_qty": 3}] + status, results, _ = match_notice_lines(notice, inventory) + assert status == "fulfillable" + assert results[0]["reservation_id"] == "1000140351" + assert results[0]["available_qty"] == 3 + + +def test_normalize_reservation_id_string(): + assert normalize_reservation_id("1000140351") == "1000140351" diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py index a796968c..33c30cae 100644 --- a/backend/tests/test_shipping_notice_tools.py +++ b/backend/tests/test_shipping_notice_tools.py @@ -3,12 +3,8 @@ from app.models import ShippingCase def _tool_headers(app): - key = app.config.get("SHIPPING_NOTICE_TOOL_API_KEY") or app.config.get("INTEGRATION_API_KEY") or "test-tool-key" - app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = key - app.config["INTEGRATION_API_KEY"] = key return { "Content-Type": "application/json", - "X-Shipping-Tool-Key": key, } @@ -127,8 +123,221 @@ def test_openapi_spec_public(app, client): assert spec["servers"][0]["url"] == "http://tool-api.example.com/api/shipping-notice" props = spec["paths"]["/tools/create_case"]["post"]["requestBody"]["content"]["application/json"]["schema"]["properties"] assert "raw_content" in props - assert "ShippingToolKey" in spec["components"]["securitySchemes"] assert "/rpa/" not in str(spec["paths"]) + assert "/tools/parse_inventory" in spec["paths"] + assert "/tools/get_inventory_schema_preview" in spec["paths"] + assert "/tools/apply_inventory_mapping" in spec["paths"] + + +def test_parse_inventory_from_chat_text(app, client): + headers = _tool_headers(app) + + create_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual"}, + ) + case_id = create_res.get_json()["case_id"] + + client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "case_id": case_id, + "structured": { + "customer_name": "ACME", + "lines": [{"sku": "A001", "qty": 10, "uom": "EA"}], + "confidence": 0.95, + }, + }, + ) + + inv_text = "料号\t可用数量\nA001\t10\nB002\t5" + parse_inv = client.post( + "/api/shipping-notice/tools/parse_inventory", + headers=headers, + json={"case_id": case_id, "raw_inventory_text": inv_text}, + ) + assert parse_inv.status_code == 200 + data = parse_inv.get_json() + assert data["status"] == "needs_human" + assert data.get("checkpoint") == "inventory_field_mapping_review" + assert data.get("stop_agent_turn") is True + assert "match_inventory" in (data.get("forbidden_next_tools") or []) + assert "field_alignment" in data["data"] + + confirm_res = client.post( + "/api/shipping-notice/tools/submit_decision", + headers=headers, + json={"case_id": case_id, "decision": "confirm_inventory_mapping"}, + ) + assert confirm_res.get_json()["status"] == "ok" + + match_res = client.post( + "/api/shipping-notice/tools/match_inventory", + headers=headers, + json={"case_id": case_id}, + ) + assert match_res.get_json()["status"] == "ok" + + +def test_parse_inventory_empty_needs_human(app, client): + headers = _tool_headers(app) + create_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual"}, + ) + case_id = create_res.get_json()["case_id"] + res = client.post( + "/api/shipping-notice/tools/parse_inventory", + headers=headers, + json={"case_id": case_id, "raw_inventory_text": " "}, + ) + assert res.get_json()["status"] == "needs_human" + assert "reparse_inventory" in (res.get_json().get("human_options") or []) + + +def test_match_by_aws_sku_and_reservation_id(app, client): + headers = _tool_headers(app) + create_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual"}, + ) + case_id = create_res.get_json()["case_id"] + + client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "case_id": case_id, + "structured": { + "customer_name": "AWS", + "lines": [ + {"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 2, "uom": "EA"}, + {"sku": "10-40594-001", "reservation_id": "ORD-3002", "qty": 1, "uom": "EA"}, + ], + "confidence": 0.95, + }, + }, + ) + + inv_text = ( + "AWS Sku\tCOM ID\tQty Available\n" + "10-40594-001\tAWS-311\t2\n" + "10-40594-001\tORD-3002\t0\n" + ) + client.post( + "/api/shipping-notice/tools/parse_inventory", + headers=headers, + json={"case_id": case_id, "raw_inventory_text": inv_text}, + ) + client.post( + "/api/shipping-notice/tools/submit_decision", + headers=headers, + json={"case_id": case_id, "decision": "confirm_inventory_mapping"}, + ) + + match_res = client.post( + "/api/shipping-notice/tools/match_inventory", + headers=headers, + json={"case_id": case_id}, + ) + data = match_res.get_json() + assert data["status"] == "needs_human" + results = {r["reservation_id"]: r for r in data["data"]["line_results"]} + assert results["AWS-311"]["line_status"] == "ok" + assert results["ORD-3002"]["line_status"] == "shortage" + + +def test_match_inventory_blocked_before_mapping_confirm(app, client): + headers = _tool_headers(app) + create_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual"}, + ) + case_id = create_res.get_json()["case_id"] + + client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "case_id": case_id, + "structured": { + "customer_name": "AWS", + "lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}], + "confidence": 0.95, + }, + }, + ) + client.post( + "/api/shipping-notice/tools/parse_inventory", + headers=headers, + json={ + "case_id": case_id, + "raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n", + }, + ) + + match_res = client.post( + "/api/shipping-notice/tools/match_inventory", + headers=headers, + json={"case_id": case_id}, + ) + blocked = match_res.get_json() + assert blocked["status"] == "needs_human" + assert blocked.get("checkpoint") == "inventory_field_mapping_review" + assert blocked.get("stop_agent_turn") is True + assert "field_alignment" in blocked["data"] + mapping = blocked["data"]["field_alignment"] + assert mapping["inventory_columns"]["mapping"]["sku"]["source_column"] == "AWS Sku" + assert mapping["inventory_columns"]["mapping"]["reservation_id"]["source_column"] == "COM ID" + + +def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path): + headers = _tool_headers(app) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") + + create_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual"}, + ) + case_id = create_res.get_json()["case_id"] + + client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "case_id": case_id, + "structured": { + "customer_name": "AWS", + "lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}], + "confidence": 0.95, + }, + }, + ) + client.post( + "/api/shipping-notice/tools/parse_inventory", + headers=headers, + json={ + "case_id": case_id, + "raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n", + }, + ) + + correct_res = client.post( + "/api/shipping-notice/tools/submit_decision", + headers=headers, + json={"case_id": case_id, "decision": "correct_inventory_mapping"}, + ) + data = correct_res.get_json() + assert data["status"] == "ok" + assert data.get("checkpoint") == "inventory_mapping_inference" + assert "schema_preview" in data["data"] + assert data["data"]["schema_preview"]["headers"] == ["AWS Sku", "COM ID", "Qty Available"] def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch): @@ -164,8 +373,9 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch): ) assert cb_res.status_code == 200 data = cb_res.get_json() - assert data["status"] == "ok" + assert data["status"] == "needs_human" assert data["data"]["process_status"] == "inventory_ready" + assert "confirm_inventory_mapping" in (data.get("human_options") or []) def test_rpa_upload_callback(app, client, tmp_path): @@ -220,3 +430,271 @@ def test_rpa_upload_callback(app, client, tmp_path): assert cb_res.status_code == 200 assert cb_res.get_json()["status"] == "ok" assert cb_res.get_json()["data"]["freight_ref_no"] == "FR-001" + + +def test_upload_inventory_file_parses_server_side(app, client, tmp_path): + headers = _tool_headers(app) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") + app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 1000 + + create_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual"}, + ) + case_id = create_res.get_json()["case_id"] + + client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "case_id": case_id, + "structured": { + "customer_name": "AWS", + "lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}], + "confidence": 0.95, + }, + }, + ) + + from io import BytesIO + + from openpyxl import Workbook + + buf = BytesIO() + wb = Workbook() + ws = wb.active + ws.append(["AWS Sku", "COM ID", "Qty Available"]) + ws.append(["10-40594-001", "AWS-311", 5]) + wb.save(buf) + wb.close() + buf.seek(0) + + upload_res = client.post( + "/api/shipping-notice/tools/upload_inventory_file", + headers={k: v for k, v in headers.items() if k.lower() != "content-type"}, + data={ + "case_id": case_id, + "file": (buf, "inventory.xlsx"), + }, + ) + assert upload_res.status_code == 200 + upload_data = upload_res.get_json() + assert upload_data["status"] == "ok" + assert upload_data.get("checkpoint") == "inventory_mapping_inference" + preview = upload_data["data"]["schema_preview"] + assert preview["headers"] == ["AWS Sku", "COM ID", "Qty Available"] + assert preview["suggested_mapping"]["sku"] == "AWS Sku" + + apply_res = client.post( + "/api/shipping-notice/tools/apply_inventory_mapping", + headers=headers, + json={ + "case_id": case_id, + "column_mapping_json": preview["suggested_mapping"], + }, + ) + apply_data = apply_res.get_json() + assert apply_data["status"] == "needs_human" + assert apply_data.get("checkpoint") == "inventory_field_mapping_review" + assert apply_data["data"]["field_alignment"]["inventory_row_count"] == 1 + + +def test_get_inventory_schema_preview(app, client, tmp_path): + headers = _tool_headers(app) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") + + create_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual"}, + ) + case_id = create_res.get_json()["case_id"] + + missing = client.post( + "/api/shipping-notice/tools/get_inventory_schema_preview", + headers=headers, + json={"case_id": case_id}, + ) + assert missing.get_json()["checkpoint"] == "inventory_upload_required" + + +def test_apply_inventory_mapping_custom_headers(app, client, tmp_path): + headers = _tool_headers(app) + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") + + create_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual"}, + ) + case_id = create_res.get_json()["case_id"] + + from io import BytesIO + + from openpyxl import Workbook + + buf = BytesIO() + wb = Workbook() + ws = wb.active + ws.append(["Part No", "Resv", "On Hand"]) + ws.append(["SKU-99", "R-1", 12]) + wb.save(buf) + wb.close() + buf.seek(0) + + client.post( + "/api/shipping-notice/tools/upload_inventory_file", + headers={k: v for k, v in headers.items() if k.lower() != "content-type"}, + data={"case_id": case_id, "file": (buf, "inv.xlsx")}, + ) + + apply_res = client.post( + "/api/shipping-notice/tools/apply_inventory_mapping", + headers=headers, + json={ + "case_id": case_id, + "column_mapping_json": { + "sku": "Part No", + "reservation_id": "Resv", + "available_qty": "On Hand", + }, + }, + ) + apply_data = apply_res.get_json() + assert apply_data["status"] == "needs_human" + assert apply_data["data"]["inventory_row_count"] == 1 + sample = apply_data["data"]["field_alignment"]["sample_inventory_lines"][0] + assert sample["sku"] == "SKU-99" + assert sample["available_qty"] == 12 + + +def test_confirm_parse_does_not_skip_inventory_match(app, client): + headers = _tool_headers(app) + + create_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual"}, + ) + case_id = create_res.get_json()["case_id"] + + client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "case_id": case_id, + "structured": { + "customer_name": "Wistron", + "lines": [{"sku": "504-010213-001", "qty": 9, "uom": "EA"}], + "confidence": 0.95, + }, + }, + ) + + confirm_res = client.post( + "/api/shipping-notice/tools/submit_decision", + headers=headers, + json={"case_id": case_id, "decision": "confirm"}, + ) + confirm_data = confirm_res.get_json() + assert confirm_data["status"] == "ok" + assert confirm_data.get("checkpoint") == "parse_confirmed" + assert "generate_shipment_excel" in (confirm_data.get("forbidden_next_tools") or []) + + excel_res = client.post( + "/api/shipping-notice/tools/generate_shipment_excel", + headers=headers, + json={"case_id": case_id}, + ) + excel_data = excel_res.get_json() + assert excel_data["status"] == "failed" + assert "匹配" in excel_data["message"] + + with app.app_context(): + case = ShippingCase.query.filter_by(case_no=case_id).first() + assert case is not None + assert case.process_status == "parsed" + assert case.match_status is None + + +def test_submit_decision_by_conversation_id(app, client): + headers = _tool_headers(app) + + create_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual", "conversation_id": "conv-test-001"}, + ) + case_id = create_res.get_json()["case_id"] + + client.post( + "/api/shipping-notice/tools/parse_notice", + headers=headers, + json={ + "case_id": case_id, + "conversation_id": "conv-test-001", + "structured": { + "customer_name": "Wistron", + "lines": [{"sku": "504-010213-001", "qty": 9, "uom": "EA"}], + "confidence": 0.95, + }, + }, + ) + + confirm_res = client.post( + "/api/shipping-notice/tools/submit_decision", + headers=headers, + json={"conversation_id": "conv-test-001", "decision": "confirm"}, + ) + confirm_data = confirm_res.get_json() + assert confirm_data["status"] == "ok" + assert confirm_data["case_id"] == case_id + assert confirm_data.get("checkpoint") == "parse_confirmed" + + dup_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual", "conversation_id": "conv-test-001"}, + ) + dup_data = dup_res.get_json() + assert dup_data["case_id"] == case_id + assert dup_data.get("checkpoint") == "case_already_exists" + + +def test_parse_inventory_rejects_oversized_text(app, client): + headers = _tool_headers(app) + app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 100 + + create_res = client.post( + "/api/shipping-notice/tools/create_case", + headers=headers, + json={"source_type": "manual"}, + ) + case_id = create_res.get_json()["case_id"] + + res = client.post( + "/api/shipping-notice/tools/parse_inventory", + headers=headers, + json={"case_id": case_id, "raw_inventory_text": "x" * 200}, + ) + data = res.get_json() + assert data["status"] == "needs_human" + assert data.get("checkpoint") == "inventory_upload_required" + assert "过大" in data["message"] + + +def test_chat_actions_empty_when_case_rejected(app): + from app.services.shipping_notice.chat_actions import build_chat_actions_payload, human_options_for_case + + with app.app_context(): + case = ShippingCase( + case_no="SN-20260101-TEST0001", + source_type="manual", + process_status="rejected", + review_status="rejected", + ) + assert human_options_for_case(case) == [] + payload = build_chat_actions_payload(case) + assert payload["checkpoint"] == "rejected" + assert payload["action_buttons"] == [] diff --git a/docs/openapi/shipping_notice_tools.dify.json b/docs/openapi/shipping_notice_tools.dify.json index b4542940..bf8c37b4 100644 --- a/docs/openapi/shipping_notice_tools.dify.json +++ b/docs/openapi/shipping_notice_tools.dify.json @@ -7,22 +7,7 @@ }, "servers": [ { - "url": "http://192.168.100.192:8890/api/shipping-notice" - } - ], - "components": { - "securitySchemes": { - "ShippingToolKey": { - "type": "apiKey", - "in": "header", - "name": "X-Shipping-Tool-Key", - "description": "与 hxops SHIPPING_NOTICE_TOOL_API_KEY 相同" - } - } - }, - "security": [ - { - "ShippingToolKey": [] + "url": "http://127.0.0.1:5052/api/shipping-notice" } ], "paths": { @@ -77,12 +62,7 @@ } } } - }, - "security": [ - { - "ShippingToolKey": [] - } - ] + } } }, "/tools/parse_notice": { @@ -125,19 +105,156 @@ } } } - }, - "security": [ - { - "ShippingToolKey": [] + } + } + }, + "/tools/parse_inventory": { + "post": { + "operationId": "parse_inventory", + "summary": "解析库存。大 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。", + "description": "解析库存。大 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。", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "case_id": { + "type": "string", + "description": "发货任务编号,如 SN-20260529-ABCD1234" + }, + "use_uploaded_file": { + "type": "string", + "description": "true=解析该 case 已上传的 Excel(服务端直传,不经过 LLM)", + "enum": [ + "true", + "false" + ] + }, + "column_mapping_json": { + "type": "string", + "description": "可选,列映射 JSON 字符串,如 {\"sku\":\"AWS Sku\",\"available_qty\":\"Qty Available\"}" + }, + "raw_inventory_text": { + "type": "string", + "description": "仅小表(约 <8 万字符)。大 Excel 勿传此字段,改用 upload_inventory_file" + }, + "inventory_lines_json": { + "type": "string", + "description": "可选,已整理好的 JSON 数组字符串,如 [{\"sku\":\"A001\",\"available_qty\":10}]" + } + }, + "required": [ + "case_id" + ] + } + } } - ] + }, + "responses": { + "200": { + "description": "Tool response (status: ok|running|needs_human|failed)", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + } + } + }, + "/tools/get_inventory_schema_preview": { + "post": { + "operationId": "get_inventory_schema_preview", + "summary": "读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)", + "description": "读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "case_id": { + "type": "string", + "description": "发货任务编号,如 SN-20260529-ABCD1234" + } + }, + "required": [ + "case_id" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Tool response (status: ok|running|needs_human|failed)", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + } + } + }, + "/tools/apply_inventory_mapping": { + "post": { + "operationId": "apply_inventory_mapping", + "summary": "应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认", + "description": "应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认", + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "case_id": { + "type": "string", + "description": "发货任务编号,如 SN-20260529-ABCD1234" + }, + "column_mapping_json": { + "type": "string", + "description": "列映射 JSON,如 {\"sku\":\"料号\",\"reservation_id\":\"COM ID\",\"available_qty\":\"Qty Available\"}" + } + }, + "required": [ + "case_id", + "column_mapping_json" + ] + } + } + } + }, + "responses": { + "200": { + "description": "Tool response (status: ok|running|needs_human|failed)", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + } } }, "/tools/ensure_inventory": { "post": { "operationId": "ensure_inventory", - "summary": "确保库存快照可用(RPA 或手工 JSON)", - "description": "确保库存快照可用(RPA 或手工 JSON)", + "summary": "确保库存快照可用(RPA 自动导出;对话库存请优先用 parse_inventory)", + "description": "确保库存快照可用(RPA 自动导出;对话库存请优先用 parse_inventory)", "parameters": [], "requestBody": { "required": true, @@ -181,19 +298,14 @@ } } } - }, - "security": [ - { - "ShippingToolKey": [] - } - ] + } } }, "/tools/match_inventory": { "post": { "operationId": "match_inventory", - "summary": "匹配发货需求与库存", - "description": "匹配发货需求与库存", + "summary": "匹配发货需求与库存。前置条件:submit_decision(confirm_inventory_mapping) 已成功;未确认时调用会被拒绝并返回 forbidden_next_tools", + "description": "匹配发货需求与库存。前置条件:submit_decision(confirm_inventory_mapping) 已成功;未确认时调用会被拒绝并返回 forbidden_next_tools", "parameters": [], "requestBody": { "required": true, @@ -229,12 +341,7 @@ } } } - }, - "security": [ - { - "ShippingToolKey": [] - } - ] + } } }, "/tools/submit_decision": { @@ -256,12 +363,14 @@ }, "decision": { "type": "string", - "description": "confirm=确认继续;reject=驳回;rematch=重新匹配;reparse=重新解析", + "description": "confirm=确认继续;reject=驳回;rematch=重新匹配;reparse=重新解析;confirm_inventory_mapping=确认库存字段对齐;reparse_inventory=重新上传库存", "enum": [ "confirm", "reject", "rematch", - "reparse" + "reparse", + "confirm_inventory_mapping", + "reparse_inventory" ] }, "comment": { @@ -288,12 +397,7 @@ } } } - }, - "security": [ - { - "ShippingToolKey": [] - } - ] + } } }, "/tools/generate_shipment_excel": { @@ -332,12 +436,7 @@ } } } - }, - "security": [ - { - "ShippingToolKey": [] - } - ] + } } }, "/tools/upload_to_freight": { @@ -389,12 +488,7 @@ } } } - }, - "security": [ - { - "ShippingToolKey": [] - } - ] + } } }, "/tools/get_case_status": { @@ -433,12 +527,7 @@ } } } - }, - "security": [ - { - "ShippingToolKey": [] - } - ] + } } } } diff --git a/docs/shipping_notice.md b/docs/shipping_notice.md new file mode 100644 index 00000000..ce38a77f --- /dev/null +++ b/docs/shipping_notice.md @@ -0,0 +1,932 @@ +# 货代发货通知 — 完整手册 + +> **唯一技术文档**:货代发货通知相关的部署、Dify 配置、OpenAPI、Agent 指令与运维说明 **仅维护本文件**(`docs/shipping_notice.md`),请勿另建分散 md。 +> **业务操作说明**:[`shipping_notice_business.md`](./shipping_notice_business.md)(面向货代/跟单等业务人员,无程序与 Dify 内容)。 +> **同步维护**:流程、字段规则、人工确认节点等变更时,**须同时更新本文件与 `shipping_notice_business.md`**。 + +Hxops **货代发货通知 Agent** 的部署、Dify 配置、OpenAPI、大库存 HTTP 直传与 Agent 指令合集。 + +**Tool API 基路径**:`/api/shipping-notice` +**OpenAPI**:`GET /api/shipping-notice/tools/openapi.json` +**鉴权 Header**:`X-Shipping-Tool-Key` + +--- + +## 目录 + +0. [业务操作说明(另册)](#业务操作说明另册) +1. [部署 Runbook](#1-部署-runbook) +2. [Dify OpenAPI 配置](#2-dify-openapi-配置) +3. [OpenAPI 变更说明](#3-openapi-变更说明) +4. [大库存 Excel — HTTP 直传](#4-大库存-excel--http-直传) +5. [Agent 系统指令(粘贴用)](#5-agent-系统指令粘贴用) +6. [Chatflow 画布参考](#6-chatflow-画布参考) + - [6.0 总览](#60-总览) + - [6.1 前置](#61-前置) + - [6.2 开始节点](#62-开始节点) + - [6.3 附件分类](#63-附件分类) + - [6.4 PDF 分支 → 文档提取器](#64-pdf-分支--文档提取器) + - [6.5 xlsx 分支 → HTTP 上传](#65-xlsx-分支--http-上传) + - [6.6 合并 Agent 输入(必做)](#66-合并-agent-输入必做) + - [6.7 Agent 节点](#67-agent-节点) + - [6.8 提取 case_id](#68-提取-case_id) + - [6.9 直接回复](#69-直接回复) + - [6.10 各轮对照 · 验收 · 速查](#610-各轮对照--验收--速查) +7. [相关代码与文件](#7-相关代码与文件) + +--- + +## 业务操作说明(另册) + +面向业务人员的流程、字段、确认节点与 FAQ 见 **[`shipping_notice_business.md`](./shipping_notice_business.md)**。 +IT / 开发改流程时,请同步更新该文件,避免聊天助手行为与业务培训材料不一致。 + +--- + +## 1. 部署 Runbook + +### 1.1 数据库迁移 + +```bash +cd backend +flask db upgrade +``` + +### 1.2 环境变量(`.env.dev` 示例) + +```env +# Tool API(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同) +SHIPPING_NOTICE_TOOL_API_KEY=your-tool-key +SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.36.114:5052/api/shipping-notice + +# 文件存储(可选,默认 instance/shipping_notice) +SHIPPING_NOTICE_STORAGE_ROOT=backend/data/shipping_notice + +# 库存文本上限(超过则必须 HTTP 上传) +SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000 + +# RPA 目录(开发机本地路径,需 RPA worker 与 backend 一致) +FREIGHT_INVENTORY_DROP_DIR=backend/data/freight_rpa/inventory_drop +FREIGHT_RPA_INVENTORY_TRIGGER_DIR=backend/data/freight_rpa/inventory_triggers +FREIGHT_UPLOAD_QUEUE_DIR=backend/data/freight_rpa/upload_queue +FREIGHT_RPA_UPLOAD_TRIGGER_DIR=backend/data/freight_rpa/upload_triggers + +# 发货 Excel 模板(可选) +FREIGHT_SHIPMENT_TEMPLATE_PATH=backend/templates/freight_shipment_upload.xlsx + +# AWS 库存列映射(可选) +# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} + +# 字段对齐确认(生产建议 true) +# SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true + +# Dify Chatflow / Workflow(seed 脚本用) +SHIPPING_NOTICE_CHAT_DIFY_APP_ID= +SHIPPING_NOTICE_CHAT_DIFY_API_KEY= +SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1 +SHIPPING_NOTICE_EXTRACT_DIFY_APP_ID= +SHIPPING_NOTICE_EXTRACT_DIFY_API_KEY= +``` + +生成模板(若尚未存在): + +```bash +python backend/scripts/generate_freight_shipment_template.py +``` + +### 1.3 注册 Agent 记录 + +```bash +cd backend +python seed_shipping_notice_agents.py +``` + +在 Dify 创建同名应用后,把 `dify_app_id` / API Key 写入 `.env` 并重新 seed。 + +### 1.4 Mock RPA(开发) + +```powershell +$env:HXOPS_API_BASE = "http://127.0.0.1:5052" +$env:SHIPPING_NOTICE_TOOL_API_KEY = "your-tool-key" +$env:FREIGHT_RPA_MOCK = "true" +python scripts/rpa/freight_rpa_worker.py +``` + +Worker 脚本:`scripts/rpa/freight_rpa_worker.py`(监听 `FREIGHT_RPA_*` 目录,Mock 模式设 `FREIGHT_RPA_MOCK=true`)。 + +### 1.5 前端入口 + +- 工作台侧边栏 **货代发货**(只读 case 列表) +- 独立路由 `/shipping-notice` +- **在 Chat 中继续** → `/chat/{agentId}?case_id=SN-...` + +### 1.6 端到端验证 + +```bash +cd backend +pytest tests/test_shipping_notice_tools.py -q +``` + +Tool 流程:`create_case` → `parse_notice` → HTTP 上传 / `get_inventory_schema_preview` → `apply_inventory_mapping` → 字段对齐确认 → `match_inventory` → `generate_shipment_excel` → `upload_to_freight`。 + +### 1.7 待业务提供 + +- 货代系统库存导出 SOP + 样例 Excel 列名 +- **AWS 库存模板**(默认映射):`AWS Sku` → sku,`COM ID` / `Reservation Order` → reservation_id,`Qty Available` → 可用数量;匹配键 **SKU + Reservation ID** +- 货代上传 SOP + 正式上传模板列映射 +- 生产 Windows RPA 脚本 + +--- + +## 2. Dify OpenAPI 配置 + +### 2.1 前置条件 + + +| 项 | 说明 | +| --------- | ----------------------------------------- | +| hxops 可访问 | Dify 必须能 HTTP 访问 **hxops 后端**(不是 Dify 自己) | +| Tool Key | `.env` 中 `SHIPPING_NOTICE_TOOL_API_KEY` | +| Dify 应用 | Chatflow,名称 **货代发货通知 Agent** | + + +### 2.2 端口说明(易混) + + +| 端口 | 服务 | Tool 是否用这个 | +| -------- | -------------------- | ---------------------------- | +| **8882** | Dify | ❌ 不要写进 OpenAPI `servers.url` | +| **8890** | hxops 前端 + `/api` 反代 | ✅ 部署联调 | +| **5052** | hxops backend 直连 | ✅ 本机 / Dify 访问宿主机 | + + +OpenAPI `servers[0].url` 示例: + +- `http://192.168.100.192:8890/api/shipping-notice` +- `http://192.168.36.114:5052/api/shipping-notice` + +验证: + +```bash +curl -s http://192.168.100.192:8890/api/shipping-notice/tools/openapi.json | head +``` + +导出静态 OpenAPI: + +```bash +cd backend +set SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.100.192:8890 +python scripts/export_shipping_notice_openapi.py +# → docs/openapi/shipping_notice_tools.dify.json +``` + +### 2.3 步骤 1 — 创建 Chatflow 应用 + +1. Dify → **工作室** → **创建应用** → **Chatflow** +2. 名称:**货代发货通知 Agent** +3. 写入 `.env.dev` 后 `python seed_shipping_notice_agents.py` + +### 2.4 步骤 2 — 导入自定义工具 + +**方式 A — URL 导入(推荐)** + +``` +http://192.168.100.192:8890/api/shipping-notice/tools/openapi.json +``` + +鉴权:Header `X-Shipping-Tool-Key` = `SHIPPING_NOTICE_TOOL_API_KEY` + +确认 **11** 个 operation:`create_case`、`parse_notice`、`parse_inventory`、`get_inventory_schema_preview`、`apply_inventory_mapping`、`ensure_inventory`、`match_inventory`、`submit_decision`、`generate_shipment_excel`、`upload_to_freight`、`get_case_status`。 + +**方式 B — 粘贴** `docs/openapi/shipping_notice_tools.dify.json` + +另有大库存专用 HTTP(**不在 OpenAPI 里**,画布 HTTP 节点配置): + +``` +POST /api/shipping-notice/tools/upload_inventory_file +``` + +### 2.5 步骤 3 — Agent + 工具 + +1. Agent 节点 → 工具 → 勾选全部 11 个 operation +2. **最大迭代次数** ≥ 10;策略 **Function Calling** +3. **指令**:粘贴 [第 5 节 Agent 系统指令](#5-agent-系统指令粘贴用) 全文 +4. **画布**:按 [§6 Chatflow 画布参考](#6-chatflow-画布参考) 搭建(**必做「合并 Agent 输入」Code**) + +### 2.6 步骤 4 — 发布验证 + +1. 发布 Chatflow +2. 第 1 轮:发货通知 → 获得 `case_id` +3. 第 2 轮:上传库存 `.xlsx` → HTTP 直传 → `apply_inventory_mapping` → 字段对齐确认 → 匹配 + +### 2.7 常见问题 + + +| 问题 | 处理 | +| ---------------------- | --------------------------------------------------- | +| OpenAPI invalid schema | 用 `/tools/openapi.json`;POST 含 `parameters: []` | +| Tool 401 | 检查 `X-Shipping-Tool-Key` | +| Tool 连接失败 | `servers.url` 勿用 `localhost`;Dify SSRF 需放行 hxops IP | +| Agent 不调工具 | 已发布、已绑工具、已粘贴第 5 节指令 | +| token 超限 | 库存 Excel 勿进文档提取器 → 第 4 节 HTTP | +| Agent 跳过字段对齐 | 更新第 5 节指令;重导 OpenAPI | + + +字段抽取 Workflow **「发货通知字段抽取」** 由 `parse_notice` 内部调用,Chatflow 无需再绑。 + +**订单行必抽字段**(`lines[]` 每行): + +| 系统字段 | 含义 | 常见表头 | +|---------|------|---------| +| `sku` | SKU / 料号 | AWS Sku、料号、Part Number | +| `qty` | 需求数量 | Qty、Order Qty、数量、发货数量 | +| `unit_price` | 单价 | Unit Price、单价、Price | +| `amount` | 金额 | Amount、Line Amount、金额、小计 | +| `reservation_id` | Reservation ID | Reservation ID、COM ID;**常见为 8~12 位纯数字**(如 `1000140351`) | + +Workflow / 规则解析输出示例: + +```json +{ + "customer_name": "ACME", + "lines": [ + { + "sku": "10-40594-001", + "qty": 2, + "unit_price": 15.5, + "amount": 31.0, + "reservation_id": "1000140351", + "uom": "EA" + } + ], + "confidence": 0.9 +} +``` + +**库存匹配**(后端 `match_inventory`):按 **SKU + Reservation ID** 汇总库存可用量,与订单 `qty` 比对;单价/金额仅用于展示与导出,不参与匹配。 + +--- + +## 3. OpenAPI 变更说明 + +### 3.1 变更摘要 + + +| 类别 | 变更 | Dify 是否要改 | +| ----------------- | ------------------------------------------------------------------- | ------------ | +| Tool 数量 | **11** 个(+`get_inventory_schema_preview`、`apply_inventory_mapping`) | 重新导入 | +| Tool 响应 | 新增 `checkpoint`、`stop_agent_turn`、`forbidden_next_tools` | 更新 Agent 指令 | +| `submit_decision` | +`confirm_inventory_mapping`、`reparse_inventory` | 重新导入 OpenAPI | +| `parse_inventory` | +`use_uploaded_file`、`column_mapping_json`;大文本拒绝 | 重导 + 更新指令 | +| 大库存 | HTTP 上传 → `schema_preview` → `apply_inventory_mapping` | 画布 + 指令 | +| 列映射 | LLM 只推断 **列名映射**;完整解析在后端 | 更新 Agent 指令 | + + +**Breaking change**:不能 `parse_inventory` 同轮连调 `match_inventory`;须 `confirm_inventory_mapping` 后再匹配。 + +### 3.2 标准流程 + +```text +create_case → parse_notice → HTTP 上传(或 RPA 落盘 / 小表 parse_inventory) + → get_inventory_schema_preview(若 HTTP 已返回 schema_preview 可跳过) + → apply_inventory_mapping(column_mapping_json=...) + → 展示 field_alignment → submit_decision(confirm_inventory_mapping) + → match_inventory → generate_shipment_excel → upload_to_freight +``` + +### 3.3 `submit_decision` decision 枚举 + +```json +["confirm", "confirm_parse", "reject", "rematch", "reparse", "confirm_inventory_mapping", "correct_inventory_mapping", "reparse_inventory"] +``` + + +| decision | 何时用 | +| -------------------------------- | --------------------------------------- | +| `confirm` / `confirm_parse` | **发货通知解析**确认(match **之前**;不会设为 matched) | +| `confirm_inventory_mapping` | 字段对齐确认(match **之前**) | +| `correct_inventory_mapping` | 更正列映射(回到 `inventory_mapping_inference`) | +| `reparse_inventory` | 重新上传库存 | +| `confirm` | 库存不足时确认部分发货(match **之后**,此时才会 matched) | +| `reject` / `rematch` / `reparse` | 驳回 / 重匹配 / 重解析发货通知 | + + +### 3.4 库存列映射(LLM 推断 + 后端解析) + + +| 阶段 | checkpoint | 说明 | +| ---------------------------- | -------------------------------- | ------------------------------------------------------------------- | +| HTTP 上传成功 | `inventory_mapping_inference` | 返回 `data.schema_preview`(headers + sample_rows + suggested_mapping) | +| `apply_inventory_mapping` 成功 | `inventory_field_mapping_review` | 返回 `data.field_alignment`,`stop_agent_turn=true` | +| 用户确认后 | `inventory_mapping_confirmed` | 可调用 `match_inventory` | + + +`column_mapping_json` 示例: + +```json +{"sku":"AWS Sku","reservation_id":"COM ID","available_qty":"Qty Available"} +``` + +### 3.5 `apply_inventory_mapping` 成功响应(字段对齐开启时) + + +| 字段 | 值 | +| ---------------------- | ----------------------------------------------------------------- | +| `status` | `needs_human` | +| `checkpoint` | `inventory_field_mapping_review` | +| `stop_agent_turn` | `true` | +| `forbidden_next_tools` | `match_inventory`, `generate_shipment_excel`, `upload_to_freight` | + + +### 3.6 `field_alignment` 结构(节选) + +```json +{ + "match_rule": "按 AWS Sku + Reservation ID 汇总可用数量,与订单 qty 比对", + "inventory_columns": { "mapping": { "sku": {}, "reservation_id": {}, "available_qty": {} } }, + "sample_notice_lines": [], + "sample_inventory_lines": [], + "inventory_row_count": 120, + "notice_line_count": 3, + "warnings": [] +} +``` + +### 3.7 可选后端配置 + +```env +SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=false # 测试可关字段对齐 +SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000 +FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} +``` + +--- + +## 4. 大库存 Excel — HTTP 直传 + +### 4.1 原则 + +AWS 库存 Excel 经文档提取器可达 **100 万+ tokens**,会触发 LLM 失败。**大 Excel never 进 LLM**;在 hxops 服务端解析。 + +### 4.2 如何判断走 HTTP 还是文档提取器 + + +| 条件 | 路径 | +| --------------------------- | ------------------------------------------------- | +| `.xlsx` / `.xls` / `.csv` | **HTTP** `upload_inventory_file` | +| 文件名含 Inventory / 库存 / stock | **HTTP** | +| `.pdf` / Word / 邮件 | **文档提取器** → `parse_notice` | +| 聊天粘贴几行小表 | **Agent** → `parse_inventory(raw_inventory_text)` | + + +```text +.xlsx / .xls / .csv → HTTP(永远) +.pdf / Word → 文档提取器 +``` + +### 4.3 HTTP 节点地址 + +``` +POST http://192.168.36.114:5052/api/shipping-notice/tools/upload_inventory_file +``` + +(或 `http://192.168.100.192:8890/api/shipping-notice/tools/upload_inventory_file`) + + +| 项 | 值 | +| --------- | ---------------------------------------------------------------------------------------- | +| Method | POST | +| Headers | `X-Shipping-Tool-Key: `(勿设 Content-Type: application/json) | +| Body | form-data | +| `case_id` | `{{#conversation.shipping_case_id#}}` | +| `file` | 开始节点库存 xlsx | + + +### 4.4 case_id 配置(会话变量) + +1. 建会话变量 `**shipping_case_id**` +2. 第 1 轮 Agent 后 → **Code 节点**: + + +| Code 参数名 | 绑定 | +| ------------ | ---------------- | +| `agent_text` | Agent → **text** | + + +```python +import re + +def main(agent_text: str) -> dict: + m = re.search(r"SN-\d{8}-[A-F0-9]{8}", agent_text or "", re.I) + return {"shipping_case_id": m.group(0) if m else ""} +``` + +1. **变量赋值** → `conversation.shipping_case_id` +2. 第 2 轮 HTTP 的 `case_id` = `{{#conversation.shipping_case_id#}}` + +第 2 轮也可从 `sys.query` 提取(用户消息带 `SN-...`):Code 参数 `user_query` ← 开始 → `sys.query`。 + +**无 case_id 时不要调 HTTP**,提示用户先发发货通知。 + +### 4.5 推荐画布(单画布 + 合并 Code) + +```text +开始 → 附件分类 → [PDF→文档提取器 | xlsx→HTTP] → 合并 Agent 输入 → Agent → 提取 case_id → 回复 +``` + +详见 [§6 Chatflow 画布参考](#6-chatflow-画布参考)。 + +### 4.6 后端接口 + +**上传(仅保存 + 返回 schema_preview,不解析全文)** + +```http +POST /api/shipping-notice/tools/upload_inventory_file +multipart: case_id + file +``` + +响应含 `data.schema_preview`:`headers`、`sample_rows`、`suggested_mapping`(规则兜底)。 + +**Agent 推断列映射并解析(Tool)** + +```json +{ + "case_id": "SN-...", + "column_mapping_json": "{\"sku\":\"AWS Sku\",\"reservation_id\":\"COM ID\",\"available_qty\":\"Qty Available\"}" +} +``` + +或先 `get_inventory_schema_preview`,再 `apply_inventory_mapping`。 + +**规则映射兜底(可选)** + +```json +{ "case_id": "SN-...", "use_uploaded_file": "true" } +``` + +**curl 自测** + +```powershell +curl.exe -X POST "http://127.0.0.1:5052/api/shipping-notice/tools/upload_inventory_file" ` + -H "X-Shipping-Tool-Key: YOUR_KEY" ` + -F "case_id=SN-20260529-TEST001" ` + -F "file=@D:\path\to\inventory.xlsx" +``` + +### 4.7 Agent Query 模板(不含 Excel 正文) + +Agent **输入变量**(均来自 §6.6「合并 Agent 输入」Code,勿直接绑文档提取器 / HTTP): + +| Agent 变量 | 绑定 | +|------------|------| +| `extracted_text` | `合并 Agent 输入.extracted_text` | +| `inventory_upload_message` | `合并 Agent 输入.inventory_upload_message` | + +Query 模板: + +```jinja2 +{% if inventory_upload_message %} +{{ inventory_upload_message }} +{% endif %} + +{% if conversation.shipping_case_id %} +当前 case_id:{{#conversation.shipping_case_id#}}(确认/驳回时必须使用,禁止 create_case) +{% endif %} + +用户消息: +{{#sys.query#}} + +{% if extracted_text %} +发货通知提取内容(仅 parse_notice,勿用于库存): +{{ extracted_text }} +{% endif %} +``` + +> **第 2 轮仅上传库存 Excel 时**:不要接文档提取器,Query 里 `extracted_text` 应为空;库存信息来自 HTTP 的 `schema_preview` / Tool,不是 `extracted_text`。 + +--- + +## 5. Agent 系统指令(粘贴用) + +将 **以下全文** 粘贴到 Dify Agent 节点 **指令 / Instructions**。 + +--- + +### ⛔ 最高优先级(违反即错误) + +你处于 **状态机** 中。必须读取 Tool 返回的 `**checkpoint`**、`**stop_agent_turn**`、`**forbidden_next_tools**`。 + +#### 规则 A — 库存字段对齐是硬门禁 + +当 `apply_inventory_mapping` / `parse_inventory` / RPA 落盘返回: + +- `status` = `needs_human` +- `checkpoint` = `inventory_field_mapping_review` +- `stop_agent_turn` = `true` + +**立刻停止调用任何 Tool**,展示 `data.field_alignment`,**结束本轮,等待用户**。 + +**禁止同轮连调**:`apply_inventory_mapping → match_inventory` ❌ + +#### 规则 A2 — HTTP 上传后先推断列映射 + +当 HTTP 上传或 `get_inventory_schema_preview` 返回: + +- `checkpoint` = `inventory_mapping_inference` +- `data.schema_preview` 含 `headers`、`sample_rows`、`suggested_mapping` + +**你必须**根据表头与样例行推断 `column_mapping_json`(仅列名,不含全表数据),然后调用 `apply_inventory_mapping`。 + +`column_mapping_json` 格式: + +```json +{"sku":"","reservation_id":"","available_qty":""} +``` + +若 `suggested_mapping` 已完整且合理,可直接使用;否则根据 headers 自行推断。 + +#### 规则 B — 只有用户确认后才能匹配 + +1. 用户确认 **发货通知解析** → `submit_decision(confirm)` → 收到 `checkpoint=parse_confirmed` → **必须先做库存**,禁止 `generate_shipment_excel` +2. 库存字段对齐 → `submit_decision(confirm_inventory_mapping)` → `checkpoint=inventory_mapping_confirmed` +3. **下一轮** `match_inventory`(必须真实调用,不可臆造 matched) +4. `match_inventory` 成功且 `process_status=matched` 后,才可 `generate_shipment_excel` + + +| decision | 何时用 | +| --------------------------- | -------------------------------------------- | +| `confirm` / `confirm_parse` | 发货通知解析确认(**不会**设为 matched,禁止 generate_excel) | +| `confirm_inventory_mapping` | 字段对齐(match **前**) | +| `confirm` | 库存不足(match **后**,确认部分发货) | + + +#### 规则 C — 被拦截时不得重试 match +回到规则 A,展示 `field_alignment`,等用户确认。 +#### 规则 E — 用户确认时禁止重建 case +当用户回复 **确认 / 重新解析 / 驳回**(或点击按钮)时: +1. **禁止** 调用 `create_case`(即使 submit 失败也不要重建) +2. 优先 `get_case_status(conversation_id={{sys.conversation_id}})` 取回 `case_id` +3. 再 `submit_decision(decision=confirm|reparse|reject, case_id=..., conversation_id=...)` +4. `submit_decision(confirm)` 返回 `checkpoint=parse_confirmed` 表示**成功**,下一步做库存,不是失败 +`create_case` 必须带 `conversation_id={{sys.conversation_id}}`,以便后续轮次找回 case。 +#### 规则 D — 大库存 Excel 禁止进 LLM +**禁止** 将库存 Excel 全文传入 `raw_inventory_text`。 +- 大文件:Chatflow HTTP 上传 → 读 `schema_preview` → `apply_inventory_mapping` +- 小表(几行粘贴)才用 `parse_inventory(raw_inventory_text)` +--- +### 角色与流程 +你是 **货代发货通知助手**,通过 Hxops Tool API 处理发货指令。 +```text +create_case → parse_notice → HTTP 上传 / 小表 parse_inventory + → get_inventory_schema_preview(可选)→ apply_inventory_mapping + → 【暂停】field_alignment → confirm_inventory_mapping → match_inventory + → generate_shipment_excel → upload_to_freight +``` +### Tool 响应字段 +| 字段 | 含义 | +| ---------------------- | -------------------- | +| `checkpoint` | 当前卡点 | +| `stop_agent_turn` | true = 本轮停止 | +| `forbidden_next_tools` | 禁止调用的 Tool | +| `data.schema_preview` | 表头 + 样例行(LLM 推断列映射用) | +| `data.field_alignment` | 字段对齐详情 | +### 字段对齐展示模板 + +```text +【库存字段对齐确认 — 请确认后才能匹配】case_id: xxx + +匹配规则:{field_alignment.match_rule} + +| 系统字段 | 库存 Excel 列 | 订单字段 | +|---------|--------------|---------| +| AWS Sku | {mapping.sku.source_column} | sku | +| Reservation ID | {mapping.reservation_id.source_column} | reservation_id | +| 可用数量 | {mapping.available_qty.source_column} | qty | +| — | — | unit_price / amount(订单展示,不参与匹配) | + +订单样例 / 库存样例 / warnings … + +请回复「确认」「重新上传」或「取消」 +``` + +**然后停止,不要在本轮调 Tool。** + + +| 用户说 | 调用 | +| ------------ | -------------------------------------------------------- | +| 点击 **确认** 按钮 | `submit_decision(confirm_inventory_mapping)` 或 `confirm` | +| 点击 **重新上传** | `submit_decision(reparse_inventory)` | +| 点击 **驳回/取消** | `submit_decision(reject)` | + + +> **Hxops 聊天页**(`/chat`)会在 Agent 回复下方自动显示操作按钮,用户无需打字。 + +**Hxops 聊天页上传库存(三种方式):** + +| 入口 | 作用 | +|------|------| +| **「1 / 2 / 3」数字选项** | 按 Agent **上一轮菜单**解析:如 `1=上传`、`3=重试 RPA`(不会固定写死) | +| **「选择库存文件」按钮** | 弹出文件选择器,POST 到 hxops | +| **输入框左侧 📎 附件** | 把文件随消息发给 Dify(取决于 Chatflow 画布) | + +数字 **`1` 不会固定等于 RPA**;系统会读取 Agent 消息里 `1.` `2.` `3.` 各行含义后再执行。 + +### 其他步骤摘要 + +- **parse_notice**:`raw_text` = 用户消息 + 发货通知提取内容(**不含**库存 Excel) +- **ensure_inventory**:仅无库存时 RPA;同样可能触发 field_alignment +- **match_inventory**:须先 `confirm_inventory_mapping`;不足时 `confirm/reject/rematch` +- **upload_to_freight**:RPA 或 `manual_confirm` + `freight_ref_no` + +### 对话风格 + +- 简洁中文;复述 `case_id` +- 不编造列名、数量、单号;以 Tool `data` 为准 +- **禁止**在未调用 `match_inventory` 成功前声称「已匹配 matched」或生成 Excel + +--- + +## 6. Chatflow 画布参考 + +> 每轮用户消息:**开始 → 附件分流 → 合并 Agent 输入 → Agent → 提取 case_id → 回复**。 +> PDF 走文档提取器;xlsx 走 HTTP;**Agent 只接「合并 Agent 输入」**,不直接接提取器 / HTTP。 + +### 6.0 总览 + +```mermaid +flowchart TD + START[开始] --> CLASSIFY[附件分类] + CLASSIFY --> IF_PDF{PDF/Word?} + CLASSIFY --> IF_XLSX{xlsx?} + + IF_PDF -->|是| EXTRACT[文档提取器] + IF_XLSX -->|是+有case_id| HTTP[HTTP 上传] + IF_XLSX -->|是+无case_id| WARN[无 case_id 提示] + + EXTRACT --> MERGE[合并 Agent 输入] + HTTP --> PARSE[解析 HTTP 响应] + PARSE --> MERGE + WARN --> MERGE + CLASSIFY --> MERGE + + MERGE --> AGENT[Agent] + AGENT --> CASE[提取 case_id] + CASE --> ASSIGN[变量赋值] + ASSIGN --> ANSWER[直接回复] +``` + +| # | 节点 | 作用 | +|---|------|------| +| 1 | 开始 | 文字 + 可选附件 | +| 2 | 附件分类 | Code,判断 PDF / xlsx | +| 3 | 文档提取器 | 仅 PDF/Word,输出 `text` | +| 4 | HTTP + 解析响应 | 仅 xlsx 且有 `shipping_case_id` | +| 5 | 无 case_id 提示 | xlsx 但尚无 case_id 时 | +| 6 | **合并 Agent 输入** | **必做**,汇总两个 Agent 变量 | +| 7 | Agent | 11 Tools + Query §4.7 + 指令 §5 | +| 8 | 提取 case_id + 变量赋值 | 写入 `conversation.shipping_case_id` | +| 9 | 直接回复 | `{{#Agent.text#}}` | + +--- + +### 6.1 前置 + +**会话变量**:`shipping_case_id`(string,初始 `""`) + +**自定义工具(11 个)**:见 §2.4 + +--- + +### 6.2 开始节点 + +| 配置 | 值 | +|------|-----| +| 文件上传 | 开启,多文件 | +| 允许类型 | `.pdf` `.doc` `.docx` · `.xlsx` `.xls` `.csv` | + +--- + +### 6.3 附件分类 + +Code 节点 `附件分类`:`query` ← `sys.query`,`files` ← 开始文件列表。 + +```python +def main(query: str, files: list | None = None) -> dict: + files = files or [] + has_xlsx = has_notice_doc = False + for f in files: + name = str((f or {}).get("filename") or (f or {}).get("name") or "").lower() + ext = name.rsplit(".", 1)[-1] if "." in name else "" + if ext in {"xlsx", "xls", "csv"}: + has_xlsx = True + elif ext in {"pdf", "doc", "docx"}: + has_notice_doc = True + if any(k in name for k in ("inventory", "stock", "onhand", "库存")): + has_xlsx, has_notice_doc = True, False + return {"has_xlsx": has_xlsx, "has_notice_doc": has_notice_doc} +``` + +--- + +### 6.4 PDF 分支 → 文档提取器 + +**IF** `has_notice_doc == true` **且** `has_xlsx == false` → **文档提取器** `发货通知提取` + +| 配置 | 绑定 | +|------|------| +| 输入文件 | 开始 → PDF/Word 附件 | +| 输出 | `text`(供 §6.6 的 `doc_text`) | + +库存 xlsx **禁止**进文档提取器。 + +--- + +### 6.5 xlsx 分支 → HTTP 上传 + +**IF** `has_xlsx == true`: + +| 子条件 | 节点 | +|--------|------| +| 有 `conversation.shipping_case_id` | HTTP `upload_inventory_file` → Code `解析上传响应` | +| 无 case_id | Code `无 case_id 提示`(不调用 HTTP) | + +**HTTP 节点** + +| 项 | 值 | +|----|-----| +| URL | `http://192.168.100.192:8890/api/shipping-notice/tools/upload_inventory_file` | +| Header | `X-Shipping-Tool-Key` | +| form-data | `case_id` = `{{#conversation.shipping_case_id#}}`,`file` = 开始附件 xlsx | + +**解析上传响应** + +```python +import json + +def main(body: str) -> dict: + try: + data = json.loads(body or "{}") + except json.JSONDecodeError: + return {"inventory_upload_message": f"上传失败:非 JSON。{str(body)[:200]}"} + if data.get("status") != "ok": + return {"inventory_upload_message": f"上传失败:{data.get('message')}"} + preview = ((data.get("data") or {}).get("schema_preview")) or {} + headers = preview.get("headers") or [] + suggested = preview.get("suggested_mapping") or {} + parts = [f"库存已 HTTP 上传。checkpoint={data.get('checkpoint')}。", f"case_id={data.get('case_id')}。"] + if headers: + parts.append("表头: " + " | ".join(str(h) for h in headers[:12])) + if suggested: + parts.append("suggested_mapping=" + json.dumps(suggested, ensure_ascii=False)) + parts.append("请调用 apply_inventory_mapping。") + return {"inventory_upload_message": " ".join(parts)} +``` + +**无 case_id 提示** + +```python +def main() -> dict: + return { + "inventory_upload_message": ( + "已收到库存 Excel,但尚无 case_id。" + "请先上传发货通知并完成 parse_notice,获得 SN-... 后再传库存。" + ) + } +``` + +--- + +### 6.6 合并 Agent 输入(必做) + +**所有分支汇合后、Agent 之前**,添加 Code 节点 `合并 Agent 输入`: + +| 输入参数 | 绑定 | +|----------|------| +| `doc_text` | `发货通知提取.text`(未跑提取器时为空) | +| `http_msg` | `解析上传响应.inventory_upload_message`(未跑 HTTP 时为空) | +| `no_case_msg` | `无 case_id 提示.inventory_upload_message`(未跑时为空) | + +```python +def main(doc_text: str = "", http_msg: str = "", no_case_msg: str = "") -> dict: + return { + "extracted_text": doc_text or "", + "inventory_upload_message": http_msg or no_case_msg or "", + } +``` + +**Agent 变量绑定(Dify 操作)** + +1. Agent 节点 → **变量** → 添加 `extracted_text`(String)→ 值选 **`合并 Agent 输入.extracted_text`** +2. 再添加 `inventory_upload_message`(String)→ 值选 **`合并 Agent 输入.inventory_upload_message`** +3. Query 模板用 §4.7(引用上述两个变量 + `{{#sys.query#}}` + `conversation.shipping_case_id`) + +纯文字轮次(无 PDF、无 xlsx):三个输入均为空,Agent 仅靠 `sys.query` 与 case_id 工作。 + +**校验**:仅 PDF 时 Query 能看到发货通知正文;仅 xlsx 时 `extracted_text` 为空、`inventory_upload_message` 有内容。 + +--- + +### 6.7 Agent 节点 + +| 项 | 值 | +|----|-----| +| 工具 | 11 个 operation 全选 | +| 策略 | Function Calling,迭代 ≥ 10 | +| 指令 | §5 全文 | +| Query | §4.7 | +| 输入变量 | 仅 §6.6 两个输出 | + +| 轮次 | Agent 主要 Tool | +|------|----------------| +| 1 | `create_case` → `parse_notice` | +| 2 | `apply_inventory_mapping`(HTTP 已上传后) | +| 3 | `submit_decision` / `match_inventory` | +| 4+ | `generate_shipment_excel` → `upload_to_freight` | + +`create_case` 必带:`conversation_id={{sys.conversation_id}}` + +--- + +### 6.8 提取 case_id + +Code `提取 case_id`:`agent_text` ← Agent.text,`user_query` ← sys.query + +```python +import re +_CASE = re.compile(r"SN-\d{8}-[A-F0-9]{8}", re.I) + +def main(agent_text: str, user_query: str) -> dict: + for t in (agent_text or "", user_query or ""): + m = _CASE.search(t) + if m: + return {"shipping_case_id": m.group(0).upper()} + return {"shipping_case_id": ""} +``` + +**变量赋值**:`conversation.shipping_case_id` ← `提取 case_id.shipping_case_id`(非空时写入) + +--- + +### 6.9 直接回复 + +```text +{{#货代 Agent.text#}} +``` + +--- + +### 6.10 各轮对照 · 验收 · 速查 + +**各轮路径** + +| 轮次 | 用户 | 画布 | +|------|------|------| +| 1 | 发货通知 PDF | 提取器 → 合并 → Agent → case_id | +| 2 | 库存 xlsx | HTTP → 合并 → Agent | +| 3+ | 确认 / 更正映射 | 合并(空)→ Agent | + +**Hxops `/chat`**:确认 / 更正映射 / 上传库存等按钮**直接调 hxops API**;Agent Query 必须用 `{{#sys.query#}}`。 + +**验收清单** + +- [ ] `合并 Agent 输入` 在 Agent 之前 +- [ ] Agent 变量只绑合并 Code,不直接绑提取器 / HTTP +- [ ] Query 含 `{{#sys.query#}}` +- [ ] xlsx 只走 HTTP;PDF 只走提取器 +- [ ] `shipping_case_id` 第 1 轮后能写入 +- [ ] `pytest tests/test_shipping_notice_tools.py` 通过 + +**Tool 速查** + +| 输入 | Tool | +|------|------| +| 发货通知 PDF/文字 | `parse_notice` | +| 库存大 Excel | HTTP → `apply_inventory_mapping` | +| 库存小表 | `parse_inventory(raw_inventory_text)` | +| 字段对齐后 | `match_inventory` | + +**典型顺序**:`create_case` → `parse_notice` → HTTP → `apply_inventory_mapping` → 确认 → `match_inventory` → `generate_shipment_excel` → `upload_to_freight` + +**匹配规则**:SKU + Reservation ID 汇总 Qty Available,与订单 qty 比对(后端执行) + +--- + +## 7. 相关代码与文件 + + +| 路径 | 说明 | +| ------------------------------------------------------------ | --------------------------------- | +| `docs/shipping_notice_business.md` | 业务操作说明(与本文同步维护) | +| `backend/app/services/shipping_notice/tools.py` | Tool 状态机 | +| `backend/app/services/shipping_notice/match.py` | SKU + Reservation 匹配 | +| `backend/app/services/shipping_notice/inventory_snapshot.py` | Excel/文本解析 | +| `backend/app/services/shipping_notice/inventory_mapping.py` | LLM/规则列映射 | +| `backend/app/services/shipping_notice/inventory_upload.py` | 大文件上传 + schema preview | +| `backend/app/services/shipping_notice/openapi_spec.py` | OpenAPI 生成 | +| `backend/app/api/shipping_notice_tools.py` | Tool 路由 + `upload_inventory_file` | +| `docs/openapi/shipping_notice_tools.dify.json` | 静态 OpenAPI | +| `GET /api/shipping-notice/tools/openapi.json` | 动态 OpenAPI | +| `backend/tests/test_shipping_notice_tools.py` | 集成测试 | +| `scripts/rpa/freight_rpa_worker.py` | RPA Worker | + + diff --git a/docs/shipping_notice_business.md b/docs/shipping_notice_business.md new file mode 100644 index 00000000..48177b94 --- /dev/null +++ b/docs/shipping_notice_business.md @@ -0,0 +1,409 @@ +# 货代发货通知 — 业务操作说明 + +> **面向对象**:货代、跟单、仓储等业务人员。 +> **配套技术文档**:[`shipping_notice.md`](./shipping_notice.md)(部署、系统配置,供 IT / 开发维护)。 +> **维护约定**:发货流程、字段规则、人工确认节点等发生变更时,**须同时更新本文件与 `shipping_notice.md`**,避免业务说明与系统行为不一致。 + +--- + +## 目录 + +1. [功能概述](#1-功能概述) +2. [入口与任务编号](#2-入口与任务编号) +3. [需要准备哪些资料](#3-需要准备哪些资料) +4. [订单与库存字段说明](#4-订单与库存字段说明) +5. [完整操作流程](#5-完整操作流程) +6. [各阶段您需要做什么](#6-各阶段您需要做什么) +7. [库存匹配规则](#7-库存匹配规则) +8. [库存不足时的处理](#8-库存不足时的处理) +9. [生成发货 Excel 与上传货代](#9-生成发货-excel-与上传货代) +10. [任务状态说明](#10-任务状态说明) +11. [常见操作速查](#11-常见操作速查) +12. [常见问题](#12-常见问题) +13. [待业务侧补充的规范](#13-待业务侧补充的规范) + +--- + +## 1. 功能概述 + +**货代发货通知助手**帮助业务人员把客户发来的发货指令(邮件、微信文字、PDF、Word 等)转成可执行的发货动作,主要能力包括: + +1. **解析发货通知**:自动识别客户、收货信息,以及每一行的 SKU、数量、单价、金额、Reservation ID 等。 +2. **载入库存**:上传库存 Excel,或由系统自动从货代/仓库系统导出库存(若已配置自动化)。 +3. **核对库存**:按 SKU + Reservation ID + 需求数量,与库存表比对是否可满足。 +4. **生成发货文件**:生成符合货代要求的发货 Excel。 +5. **上传货代系统**:自动或手工确认上传至货代平台。 + +整个过程中,系统在关键节点会**暂停并请您确认**,避免误发、错配。 + +--- + +## 2. 入口与任务编号 + +### 2.1 从哪里进入 + +| 入口 | 说明 | +|------|------| +| **工作台聊天** | 打开「货代发货通知」智能助手,在对话中上传文件或粘贴文字,逐步完成全流程(推荐) | +| **货代发货列表** | 查看历史任务状态;可从某条任务「在 Chat 中继续」回到对应对话 | + +### 2.2 任务编号(SN-…) + +每处理一笔新的发货需求,系统会分配唯一**任务编号**,格式类似: + +```text +SN-20260529-A1B2C3D4 +``` + +后续所有上传、确认、匹配、导出都围绕**同一任务编号**进行。请在对照库存、核对结果时始终关注助手回复中的该编号,**不要在同一对话里重复发起「新建任务」**,以免数据分散。 + +--- + +## 3. 需要准备哪些资料 + +| 顺序 | 资料 | 格式 | 用途 | +|------|------|------|------| +| 1 | **发货通知 / 订单** | PDF、Word,或邮件/微信正文 | 解析客户、SKU、数量、Reservation ID、单价、金额等 | +| 2 | **库存快照** | Excel(.xlsx / .xls / .csv) | 与订单行核对可用库存;大表请直接上传文件,不要整表粘贴到聊天框 | +| 3 | (可选)**货代发货模板** | 由 IT 配置 | 生成最终上传货代用的 Excel | + +**顺序要求**:须先完成发货通知解析并确认,再上传库存。若尚未有任务编号就上传库存 Excel,系统会提示您先提交发货通知。 + +--- + +## 4. 订单与库存字段说明 + +### 4.1 订单行(来自发货通知) + +系统会从发货通知中**逐行**提取以下信息(表头名称因客户而异,助手会尽量自动识别): + +| 字段 | 业务含义 | 常见表头示例 | +|------|----------|--------------| +| **SKU / 料号** | 物料编码 | AWS Sku、料号、Part Number | +| **需求数量** | 本次应发数量 | Qty、Order Qty、数量、发货数量 | +| **单价** | 单行单价 | Unit Price、单价、Price | +| **金额** | 单行金额 | Amount、Line Amount、金额、小计 | +| **Reservation ID** | 预留/订单占用编号,用于与库存精确对应 | Reservation ID、COM ID;**常见为 8~12 位纯数字**,如 `1000140351` | + +**说明**: + +- **SKU、需求数量、Reservation ID** 是库存核对的核心字段。 +- **单价、金额** 主要用于展示与导出,**不参与**「够不够货」的自动比对。 +- 若订单含 Reservation ID 而库存表未正确对应,系统会在「字段对齐」环节给出警告。 + +**订单行示例**(便于理解系统解析目标): + +| SKU | Reservation ID | 需求数量 | 单价 | 金额 | +|-----|----------------|----------|------|------| +| 10-40594-001 | 1000140351 | 2 | 15.50 | 31.00 | +| 10-40594-002 | 1000140352 | 1 | 20.00 | 20.00 | + +### 4.2 库存表(来自仓库/货代导出) + +库存 Excel 至少需要能对应到以下列(列名因模板而异,上传后需您确认映射): + +| 字段 | 业务含义 | 常见列名示例 | +|------|----------|--------------| +| **SKU / 料号** | 与订单 SKU 一致 | AWS Sku、料号 | +| **Reservation ID** | 与订单 Reservation ID 一致 | COM ID、Reservation Order、Reservation ID | +| **可用数量** | 当前可发数量 | Qty Available、可用数量、Qty | + +**AWS 库存模板**(当前系统默认支持)示例: + +- `AWS Sku` → SKU +- `COM ID` / `Reservation Order` → Reservation ID +- `Qty Available` → 可用数量 + +若您的库存表带标题行(如「AWS DUB On Hand Inventory by Location」),系统会尝试跳过标题行,自动识别真正的表头。 + +--- + +## 5. 完整操作流程 + +```text +① 提交发货通知 + ↓ +② 确认解析结果(客户、SKU、数量、Reservation ID 等) + ↓ +③ 提供库存(上传 Excel / 等待自动导出 / 粘贴少量行) + ↓ +④ 确认库存列与订单字段的对齐关系 + ↓ +⑤ 自动匹配库存 + ↓ +⑥ (若不足)确认部分发货或驳回 + ↓ +⑦ 生成发货 Excel + ↓ +⑧ 上传货代系统(自动或手工确认) +``` + +**重要原则**: + +- 必须先确认**发货通知**,再处理**库存**。 +- 必须先确认**字段对齐**,再执行**库存匹配**。 +- 只有匹配通过(或您确认部分发货)后,才能生成 Excel 并上传货代。 + +--- + +## 6. 各阶段您需要做什么 + +### 阶段 ① — 提交发货通知 + +**您可以做:** + +- 在聊天中上传 PDF / Word 发货通知;或 +- 直接粘贴邮件、微信中的发货文字。 + +**系统会做:** + +- 创建任务并分配 **SN-…** 编号; +- 解析客户名称、收货信息、订单明细行。 + +**您会看到:** + +- 助手展示解析出的表格或摘要; +- 若置信度较低,会明确要求您核对后再继续。 + +--- + +### 阶段 ② — 确认发货通知解析 + +**您需要核对:** + +- 客户、交期、收货地址是否正确; +- 每一行 **SKU、需求数量、Reservation ID** 是否与原件一致; +- 单价、金额是否合理(如有)。 + +**可选操作:** + +| 操作 | 含义 | +|------|------| +| **确认** | 解析正确,进入库存环节 | +| **重新解析** | 原文有误或解析不对,请助手重新解析 | +| **驳回** | 本单不再处理,任务结束 | + +聊天页下方会出现对应按钮;也可输入「确认」「重新解析」「驳回」等文字。 + +--- + +### 阶段 ③ — 提供库存 + +**推荐方式(大表):** + +- 在聊天中点击 **「选择库存文件」** 上传 Excel;或 +- 使用助手提示的 **数字选项**(如「1 = 上传库存」),再选文件。 + +**其他方式:** + +- **自动导出**:若已对接 RPA,助手可触发从货代/仓库系统自动拉取库存(需等待完成); +- **小表粘贴**:仅几行库存时,可直接粘贴到聊天(大 Excel 请勿粘贴,易失败)。 + +**注意:** + +- 库存文件须关联**当前任务的 SN-… 编号**; +- 发货通知用 PDF/Word,库存用 Excel,**不要混用**(不要把库存 Excel 当发货通知上传)。 + +--- + +### 阶段 ④ — 确认字段对齐 + +上传库存后,助手会展示**字段对齐表**,说明: + +- 库存 Excel 哪一列对应 SKU、Reservation ID、可用数量; +- 这些列如何与订单里的字段比对; +- 订单与库存各取几行样例供您目视检查。 + +**示例(概念示意):** + +| 比对项 | 库存 Excel 列 | 订单字段 | +|--------|---------------|----------| +| 料号 | AWS Sku | SKU | +| 预留号 | COM ID | Reservation ID | +| 数量 | Qty Available | 需求数量 | + +**可选操作:** + +| 操作 | 含义 | +|------|------| +| **确认** | 列映射正确,可以开始匹配 | +| **更正映射** | 列识别不对,回到映射步骤重新指定 | +| **重新上传** | 换一份库存文件 | +| **驳回 / 取消** | 终止本任务 | + +**在未点击「确认」前,系统不会进行库存匹配**,以免列对错导致误判。 + +--- + +### 阶段 ⑤ — 自动匹配库存 + +确认字段对齐后,系统按规则逐行比对(详见 [§7](#7-库存匹配规则))。 + +**匹配结果类型:** + +| 结果 | 含义 | +|------|------| +| **完全满足** | 所有订单行库存均够 | +| **部分满足** | 部分 SKU 有货、部分不足或只能发一部分 | +| **无法满足** | 全部或关键行无可用库存 | + +助手会以表格形式展示:SKU、Reservation ID、需求数量、可用数量、缺口等。 + +--- + +### 阶段 ⑥ — 库存不足时的决策 + +若存在缺口,系统会暂停并请您选择(见 [§8](#8-库存不足时的处理))。 + +--- + +### 阶段 ⑦⑧ — 生成 Excel 与上传货代 + +匹配满足或您确认部分发货后: + +1. 系统生成发货 Excel(可在任务详情或助手提示中下载); +2. 尝试自动上传货代;若自动化未完成,会提示您手工上传并在系统中登记货代单号。 + +--- + +## 7. 库存匹配规则 + +系统对**每一行订单**执行如下逻辑(业务口径): + +1. 取订单行的 **SKU** 与 **Reservation ID**(若订单有 Reservation ID,必须与库存同一编号比对;若订单无 Reservation ID,则仅按 SKU 汇总所有预留下的可用量)。 +2. 在库存表中,将 **相同 SKU + 相同 Reservation ID** 的多行**可用数量相加**。 +3. 将汇总后的可用数量与订单 **需求数量** 比较: + - 可用 ≥ 需求 → 该行 **满足**; + - 0 < 可用 < 需求 → 该行 **部分满足**(有缺口); + - 可用 = 0 → 该行 **缺货**。 + +**Reservation ID 格式说明:** + +- 常见为 **8~12 位纯数字**,例如 `1000140351`。 +- Excel 中可能被存成数字格式,系统会自动规范为同一字符串再比对,避免「1000140351」与「1000140351.0」对不上。 + +**不参与匹配的字段:** + +- 订单中的 **单价、金额** 仅作记录与导出,不影响「够不够货」的判断。 + +--- + +## 8. 库存不足时的处理 + +| 您的选择 | 后续 | +|----------|------| +| **确认(部分发货)** | 按当前可用库存继续生成发货 Excel,仅发有货部分 | +| **驳回** | 终止任务,不生成发货文件 | +| **重新匹配** | 库存有更新时,在不变更订单的前提下重新比对 | + +若任务已被驳回,助手可能建议「重新创建发货任务」;此时应**新开对话**处理新单据,勿在已驳回任务上继续点「确认对齐」类按钮。 + +--- + +## 9. 生成发货 Excel 与上传货代 + +### 9.1 发货 Excel + +- 在满足匹配条件或您确认部分发货后自动生成; +- 内容基于已确认的订单行与匹配结果; +- 具体列布局取决于公司配置的货代模板(需业务与 IT 共同确认)。 + +### 9.2 上传货代 + +| 方式 | 说明 | +|------|------| +| **自动上传** | 若已配置 RPA,系统排队上传并反馈进度 | +| **手工上传** | 您自行登录货代系统上传 Excel 后,在聊天中告知「已上传,单号 XXX」,由助手登记 | + +上传失败时可 **重试自动上传** 或 **下载 Excel 后手工处理**。 + +--- + +## 10. 任务状态说明 + +业务侧可关注的任务进展(列表页或助手摘要中可能出现): + +| 状态 / 阶段 | 业务含义 | +|-------------|----------| +| 已创建 | 任务已建立,尚未完成解析 | +| 待核对解析 | 发货通知已解析,等您确认 | +| 解析已确认 | 发货通知无误,待提供库存 | +| 待库存 / 库存映射中 | 已收到或正在处理库存文件 | +| 待确认字段对齐 | 须您确认库存列与订单字段对应关系 | +| 已匹配 / 部分匹配 | 库存比对完成 | +| 待确认缺口 | 库存不足,等您决定是否部分发货 | +| 已生成 Excel | 发货文件已就绪 | +| 上传中 / 已上传 | 货代侧处理中或已完成 | +| 已驳回 | 本任务终止 | + +--- + +## 11. 常见操作速查 + +| 您想做什么 | 建议操作 | +|------------|----------| +| 处理新发货通知 | 打开助手 → 上传 PDF/Word 或粘贴文字 | +| 核对解析是否正确 | 看助手表格 → 点 **确认** 或 **重新解析** | +| 上传库存 | 点 **选择库存文件**,或按助手菜单选「上传」 | +| 列映射不对 | 点 **更正映射** 或输入「更正映射」 | +| 换一份库存 | 点 **重新上传** | +| 确认可以比对了 | 字段对齐界面点 **确认** | +| 库存不够仍要发 | 匹配结果页点 **确认(部分发货)** | +| 整单不做 | 点 **驳回** | +| 查进度 | 货代发货列表,或问助手「当前任务进度」 | +| 继续未完成任务 | 从列表「在 Chat 中继续」,或对话中提供 SN-… 编号 | + +**关于聊天中的数字 1 / 2 / 3:** + +- 含义以**助手上一轮文字菜单**为准(例如 1=上传库存、2=粘贴、3=重试导出); +- 不会固定写死,请先看清助手给出的选项再输入数字。 + +--- + +## 12. 常见问题 + +**Q:为什么要先确认发货通知,再传库存?** +A:避免任务编号不一致、订单行未定型就占用库存比对,导致结果不可追溯。 + +**Q:库存 Excel 很大,可以粘贴到聊天吗?** +A:不可以。请使用「选择库存文件」上传;整表粘贴易失败且无法保证列映射准确。 + +**Q:订单有 Reservation ID,库存表里是 COM ID,能匹配吗?** +A:可以。字段对齐环节会把 COM ID 与订单 Reservation ID 对应;确认映射无误即可。 + +**Q:Reservation ID 必须是数字吗?** +A:业务上**一般为 8~12 位纯数字**(如 `1000140351`)。若格式异常,系统会提示核对是否解析正确。 + +**Q:单价、金额错了会影响能不能发货吗?** +A:不会。库存匹配只看 SKU、Reservation ID、需求数量;但导出 Excel 前仍建议在解析确认阶段核对单价与金额。 + +**Q:助手文字建议和下方按钮不一致怎么办?** +A:以**按钮和任务当前状态**为准;若任务已驳回,不应再出现「确认字段对齐」类按钮。遇此类情况请联系 IT 并保留截图。 + +**Q:同一对话里能否处理两票货?** +A:建议**一票货一个对话、一个 SN-… 编号**,避免混淆。 + +--- + +## 13. 待业务侧补充的规范 + +以下信息越明确,系统配置与解析越准确(需业务与 IT 协同): + +| 项 | 说明 | +|----|------| +| 货代库存导出 SOP | 从哪个系统导出、路径、频率、文件名规范 | +| 库存 Excel 样例 | 含真实列名的脱敏样表(尤其 SKU、COM ID、Qty Available) | +| 发货通知样例 | PDF/邮件样例,含 Reservation ID 与 SKU 的典型排版 | +| 货代上传 SOP | 登录步骤、上传入口、必填字段 | +| 正式发货 Excel 模板 | 列顺序、必填项、与货代系统的字段对应关系 | +| Reservation ID 业务规则 | 是否恒为 10 位数字、是否与 COM ID 一一对应等 | + +--- + +## 文档版本 + +| 项目 | 说明 | +|------|------| +| 业务文档 | `docs/shipping_notice_business.md`(本文件) | +| 技术文档 | `docs/shipping_notice.md` | +| 同步维护 | 流程、字段、确认节点变更时 **两份文档一并更新** | diff --git a/frontend/src/api/shippingNotice.ts b/frontend/src/api/shippingNotice.ts index bce63bd1..1f78f676 100644 --- a/frontend/src/api/shippingNotice.ts +++ b/frontend/src/api/shippingNotice.ts @@ -57,4 +57,73 @@ export const getWorkspaceShippingCase = (caseNo: string) => export const workspaceShippingExportUrl = (caseNo: string) => `/api/workspace/shipping-cases/${encodeURIComponent(caseNo)}/export`; +export interface ShippingChatAction { + id: string; + label: string; + message: string; + variant: 'primary' | 'secondary' | 'danger'; +} + +export interface ShippingChatActionsResponse { + case_no: string; + checkpoint?: string | null; + process_status: string; + review_status?: string | null; + pending_human_reason?: string | null; + action_buttons: ShippingChatAction[]; +} + +export const getShippingChatActions = (caseNo: string) => + getJson( + `/api/workspace/shipping-cases/${encodeURIComponent(caseNo)}/chat-actions`, + ); + +export async function uploadWorkspaceShippingInventory(caseNo: string, file: File) { + const form = new FormData(); + form.append('file', file); + const headers = getAuthHeaders(); + delete (headers as Record)['Content-Type']; + const res = await fetch( + `/api/workspace/shipping-cases/${encodeURIComponent(caseNo)}/upload-inventory`, + { method: 'POST', headers, body: form }, + ); + const body = (await res.json().catch(() => ({}))) as ShippingInventoryUploadResponse & { error?: string }; + if (!res.ok) { + throw new Error(body.error || body.message || res.statusText); + } + return body; +} + +export interface ShippingInventoryUploadResponse { + status: string; + message?: string; + case_id?: string; + checkpoint?: string; + data?: Record; +} + +export interface ShippingDecisionResponse { + status: string; + message?: string; + case_id?: string; + checkpoint?: string; + data?: Record; +} + +export async function submitWorkspaceShippingDecision(caseNo: string, decision: string, comment?: string) { + const res = await fetch( + `/api/workspace/shipping-cases/${encodeURIComponent(caseNo)}/submit-decision`, + { + method: 'POST', + headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' }, + body: JSON.stringify({ decision, ...(comment ? { comment } : {}) }), + }, + ); + const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string }; + if (!res.ok || body.status === 'failed') { + throw new Error(body.error || body.message || res.statusText); + } + return body; +} + export const SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent'; diff --git a/frontend/src/composables/useChat.ts b/frontend/src/composables/useChat.ts index 2b13106a..cc2bfac8 100644 --- a/frontend/src/composables/useChat.ts +++ b/frontend/src/composables/useChat.ts @@ -30,6 +30,13 @@ interface ChatMessage { local_id?: string; local_only?: boolean; rated?: boolean; + shipping_actions?: Array<{ + id: string; + label: string; + message: string; + variant?: 'primary' | 'secondary' | 'danger'; + }>; + shipping_actions_used?: boolean; } type RunStatus = 'running' | 'done' | 'error'; diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index 50ead972..be5385b0 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -1,4 +1,4 @@ -import { createI18n } from 'vue-i18n'; +import { createI18n } from 'vue-i18n'; const messages = { 'en': { @@ -1269,6 +1269,13 @@ const messages = { disclaimer: 'AI can make mistakes. Please verify important information.', createNewChat: 'New Chat', shippingNoticeContinue: 'Please continue shipping case {caseId}. Call get_case_status first and tell me the next step.', + shippingNoticeActionsHint: 'Choose an action (no need to type):', + shippingNoticeMissingCaseId: 'Case ID not found. Complete shipping notice parsing first.', + shippingNoticeUploadDone: 'Inventory file uploaded: {fileName}.', + shippingNoticeUploadOk: 'Upload succeeded.', + shippingNoticeUploadFailed: 'Inventory upload failed.', + shippingNoticePasteHint: 'Paste inventory rows in the input box, then send.', + shippingNoticeDecisionDone: 'Action completed.', clearAll: 'Clear All', clearOneRecord: 'Clear This Record', agents: 'Agents', @@ -2768,6 +2775,13 @@ const messages = { disclaimer: 'AI 可能会犯错,请核实重要信息。', createNewChat: '创建新对话', shippingNoticeContinue: '请继续处理发货任务 {caseId},请先调用 get_case_status 查询当前状态并告知我下一步。', + shippingNoticeActionsHint: '请选择操作(无需输入文字):', + shippingNoticeMissingCaseId: '未找到 case_id,请先完成发货通知解析。', + shippingNoticeUploadDone: '库存文件已上传:{fileName}。', + shippingNoticeUploadOk: '上传成功。', + shippingNoticeUploadFailed: '库存文件上传失败。', + shippingNoticePasteHint: '请在输入框粘贴库存小表内容后发送。', + shippingNoticeDecisionDone: '操作已完成。', clearAll: '清空全部', clearOneRecord: '清除该记录', agents: '智能体', diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index a93dd009..4f411d24 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -46,6 +46,12 @@ import { getUserAgent, listUserAgents, } from '../api/user'; +import { + getShippingChatActions, + SHIPPING_NOTICE_AGENT_NAME, + submitWorkspaceShippingDecision, + uploadWorkspaceShippingInventory, +} from '../api/shippingNotice'; const { t, locale } = useI18n(); const { appliedTheme, toggleLightDark } = useTheme(); @@ -714,6 +720,8 @@ const attachments = ref([]); const attachmentUrlInput = ref(''); const isUploadingAttachments = ref(false); const filePickerRef = ref(null); +const shippingInventoryPickerRef = ref(null); +const pendingShippingUploadCaseId = ref(''); const attachmentMenuRef = ref(null); const attachmentUrlInputRef = ref(null); const showAttachmentMenu = ref(false); @@ -2062,6 +2070,427 @@ const shippingCaseIdFromQuery = computed(() => { return typeof value === 'string' ? value.trim() : ''; }); +const SHIPPING_CASE_ID_RE = /SN-\d{8}-[A-F0-9]{8}/i; + +const isShippingNoticeAgent = computed(() => currentAgent.value?.name === SHIPPING_NOTICE_AGENT_NAME); + +const findLatestShippingCaseId = (msgs: Array<{ content?: string }>) => { + for (let i = msgs.length - 1; i >= 0; i -= 1) { + const match = String(msgs[i]?.content || '').match(SHIPPING_CASE_ID_RE); + if (match?.[0]) return match[0].toUpperCase(); + } + return ''; +}; + +const shippingActionButtonClass = (variant?: string) => { + if (variant === 'primary') { + return 'rounded-xl bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60'; + } + if (variant === 'danger') { + return 'rounded-xl border border-rose-200 bg-rose-50 px-4 py-2 text-sm font-medium text-rose-700 transition hover:bg-rose-100 disabled:cursor-not-allowed disabled:opacity-60'; + } + return 'rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60'; +}; + +type ShippingMenuAction = 'upload' | 'paste' | 'retry_rpa' | 'confirm' | 'reparse' | 'reject'; + +const SHIPPING_MENU_ACTION_SPECS: Record< + ShippingMenuAction, + { id: string; label: string; message: string; variant: 'primary' | 'secondary' | 'danger' } +> = { + upload: { id: 'upload_inventory_file', label: '选择库存文件', message: '我要上传库存 Excel', variant: 'primary' }, + paste: { id: 'paste_inventory_json', label: '粘贴库存', message: '我粘贴库存小表', variant: 'secondary' }, + retry_rpa: { id: 'retry_rpa', label: '重试 RPA', message: '重试 RPA 导出库存', variant: 'secondary' }, + confirm: { id: 'confirm', label: '确认', message: '确认', variant: 'primary' }, + reparse: { id: 'reparse', label: '重新解析', message: '重新解析', variant: 'secondary' }, + reject: { id: 'reject', label: '驳回', message: '驳回', variant: 'danger' }, +}; + +const lastAssistantMessageContent = () => { + for (let i = messages.value.length - 1; i >= 0; i -= 1) { + const item = messages.value[i]; + if (item?.role === 'assistant') return String(item.content || ''); + } + return ''; +}; + +const normalizeMenuDigit = (ch: string) => { + const full = '0123456789'; + const idx = full.indexOf(ch); + return idx >= 0 ? idx : Number(ch); +}; + +const classifyShippingMenuLine = (desc: string): ShippingMenuAction | null => { + if (/上传|excel|xlsx|xls|csv|库存文件|\.xlsx/i.test(desc)) return 'upload'; + if (/粘贴|文本|小量|直接发/i.test(desc)) return 'paste'; + if (/重试|rpa|拉取/i.test(desc)) return 'retry_rpa'; + if (/重新解析|重解析|reparse/i.test(desc)) return 'reparse'; + if (/驳回|取消|reject/i.test(desc)) return 'reject'; + if (/确认|confirm/i.test(desc)) return 'confirm'; + return null; +}; + +const parseShippingMenuFromContext = (ctx: string): Map => { + const map = new Map(); + for (const line of String(ctx || '').split('\n')) { + const m = line.match(/^\s*([1-91-9])[\.、\)::]?\s*(.+)$/); + if (!m?.[1] || !m[2]) continue; + const num = normalizeMenuDigit(m[1]); + if (!Number.isFinite(num) || num < 1) continue; + const action = classifyShippingMenuLine(m[2]); + if (action) map.set(num, action); + } + return map; +}; + +const buildShippingMenuButtons = (ctx: string) => { + const menu = parseShippingMenuFromContext(ctx); + if (!menu.size) return null; + return [...menu.entries()] + .sort(([a], [b]) => a - b) + .map(([num, action]) => { + const spec = SHIPPING_MENU_ACTION_SPECS[action]; + return { + ...spec, + label: `${num}. ${spec.label}`, + }; + }); +}; + +const resolveShippingNumericChoice = (text: string): ShippingMenuAction | null => { + const normalized = text.trim(); + if (!/^[1-91-9](?:[\.\、\)::]?)$/.test(normalized)) return null; + const num = normalizeMenuDigit(normalized.charAt(0)); + return parseShippingMenuFromContext(lastAssistantMessageContent()).get(num) || null; +}; + +const isShippingFieldAlignmentPrompt = (text: string) => { + if (/无需确认|确认失败|已驳回|rejected|unfulfillable|重新创建|建议方案|不需要确认/.test(text)) { + return false; + } + return ( + text.includes('【库存字段对齐确认') + || text.includes('字段对齐确认 —') + || (text.includes('请确认后才能匹配') && text.includes('field_alignment')) + || (text.includes('库存字段对齐') && text.includes('请确认')) + ); +}; + +const inferShippingActionsFromContent = (content: string) => { + const text = String(content || ''); + if (isShippingFieldAlignmentPrompt(text)) { + return [ + { id: 'confirm_inventory_mapping', label: '确认', message: '确认', variant: 'primary' as const }, + { id: 'correct_inventory_mapping', label: '更正映射', message: '更正映射', variant: 'secondary' as const }, + { id: 'reparse_inventory', label: '重新上传', message: '重新上传库存', variant: 'secondary' as const }, + { id: 'reject', label: '取消', message: '驳回', variant: 'danger' as const }, + ]; + } + if ( + text.includes('请确认以上信息') + || text.includes('请确认以上') + || text.includes('请核对') + || text.includes('确认后继续') + || text.includes('回复「确认」') + || text.includes('回复"确认"') + ) { + return [ + { id: 'confirm', label: '确认', message: '确认', variant: 'primary' as const }, + { id: 'reparse', label: '重新解析', message: '重新解析', variant: 'secondary' as const }, + { id: 'reject', label: '驳回', message: '驳回', variant: 'danger' as const }, + ]; + } + if (text.includes('库存数量不足') || text.includes('缺口明细')) { + return [ + { id: 'confirm', label: '确认部分发货', message: '确认', variant: 'primary' as const }, + { id: 'rematch', label: '重新匹配', message: '重新匹配', variant: 'secondary' as const }, + { id: 'reject', label: '驳回', message: '驳回', variant: 'danger' as const }, + ]; + } + if ( + text.includes('waiting_inventory') + || text.includes('inventory_rpa_pending') + || text.includes('重试 RPA') + || text.includes('上传库存') + || text.includes('upload_inventory_file') + || /[1-3][\.\、\)]/.test(text) + ) { + const menuButtons = buildShippingMenuButtons(text); + if (menuButtons?.length) return menuButtons; + return [ + { id: 'upload_inventory_file', label: '选择库存文件', message: '我要上传库存 Excel', variant: 'primary' as const }, + { id: 'paste_inventory_json', label: '粘贴库存', message: '我粘贴库存小表', variant: 'secondary' as const }, + { id: 'retry_rpa', label: '重试 RPA', message: '重试 RPA 导出库存', variant: 'secondary' as const }, + ]; + } + return []; +}; + +const SHIPPING_DECISION_ACTIONS = new Set([ + 'confirm', + 'confirm_inventory_mapping', + 'correct_inventory_mapping', + 'reparse_inventory', + 'reject', + 'reparse', + 'rematch', +]); + +const resolveShippingDecisionFromText = (text: string): string | null => { + const normalized = text.trim(); + const direct: Record = { + 更正映射: 'correct_inventory_mapping', + 更正列映射: 'correct_inventory_mapping', + 重新上传库存: 'reparse_inventory', + 重新上传: 'reparse_inventory', + 驳回: 'reject', + 取消: 'reject', + 重新解析: 'reparse', + 重新匹配: 'rematch', + }; + if (direct[normalized]) return direct[normalized]; + if (normalized === '确认') { + const ctx = lastAssistantMessageContent(); + if (ctx.includes('字段对齐') || ctx.includes('field_alignment') || ctx.includes('库存字段对齐')) { + return 'confirm_inventory_mapping'; + } + return 'confirm'; + } + return null; +}; + +const executeShippingDecision = async (decision: string, displayText?: string) => { + const caseId = findLatestShippingCaseId(messages.value); + if (!caseId) { + msg.warning(t('chat.shippingNoticeMissingCaseId')); + return false; + } + try { + const result = await submitWorkspaceShippingDecision(caseId, decision); + const userText = (displayText || decision).trim(); + const assistantContent = formatShippingDecisionAssistantMessage(decision, result, caseId); + const userMsg = { + role: 'user' as const, + content: `${userText} case_id=${caseId}`, + local_id: newLocalMessageId('shipping-user'), + local_only: true, + }; + const assistantMsg = { + role: 'assistant' as const, + content: assistantContent, + local_id: newLocalMessageId('shipping-assistant'), + local_only: true, + }; + messages.value.push(userMsg, assistantMsg); + await saveLocalMessageToBackend(userMsg, userText); + await saveLocalMessageToBackend(assistantMsg, userText); + if (result.message) { + msg.success(result.message); + } + if (!conversationId.value && history.value.length === 0) { + await loadHistory(); + } else if (conversationId.value) { + const exists = history.value.some((h) => h.conversation_id === conversationId.value); + if (!exists) await loadHistory(); + } + void refreshShippingActions(); + return true; + } catch (e: any) { + msg.warning(e?.message || t('chat.shippingNoticeUploadFailed')); + return false; + } +}; + +const formatShippingDecisionAssistantMessage = ( + decision: string, + result: { message?: string; data?: Record; checkpoint?: string }, + caseId: string, +) => { + const lines: string[] = [result.message || t('chat.shippingNoticeDecisionDone')]; + + if (decision === 'correct_inventory_mapping') { + const preview = (result.data?.schema_preview || {}) as Record; + const headers = Array.isArray(preview.headers) ? preview.headers.filter(Boolean) : []; + const suggested = (preview.suggested_mapping || {}) as Record; + if (preview.header_row_index) { + lines.push('', `表头在第 ${preview.header_row_index} 行:${headers.join(' | ')}`); + } else if (headers.length) { + lines.push('', `当前表头:${headers.join(' | ')}`); + } + const mappingLines = [ + suggested.sku ? `- sku → ${suggested.sku}` : null, + suggested.reservation_id ? `- reservation_id → ${suggested.reservation_id}` : null, + suggested.available_qty ? `- available_qty → ${suggested.available_qty}` : null, + ].filter(Boolean); + if (mappingLines.length) { + lines.push('', '建议列映射:', ...mappingLines); + } + lines.push( + '', + '如需调整,请说明要改的列(例如:available_qty 改用 Qty Available)。', + '也可点击「选择库存文件」重新上传。', + ); + } else if (decision === 'confirm_inventory_mapping') { + lines.push('', '下一步:匹配库存与发货需求(match_inventory)。'); + } else if (decision === 'reparse_inventory') { + lines.push('', '请重新上传或粘贴库存 Excel。'); + } + + lines.push('', `case_id=${caseId}`); + return lines.join('\n'); +}; + +const openShippingInventoryPicker = (): boolean => { + const caseId = findLatestShippingCaseId(messages.value); + if (!caseId) { + msg.warning(t('chat.shippingNoticeMissingCaseId')); + return false; + } + pendingShippingUploadCaseId.value = caseId; + shippingInventoryPickerRef.value?.click(); + return true; +}; + +const isShippingInventoryUploadIntent = (text: string) => { + const normalized = text.trim(); + if (!normalized) return false; + + const choice = resolveShippingNumericChoice(normalized); + if (choice === 'upload') return true; + + return [ + /^上传库存$/, + /上传库存文件/, + /手工上传/, + /选择库存/, + /upload.*inventory/i, + ].some((pattern) => pattern.test(normalized)); +}; + +const sendShippingMenuMessage = async (message: string) => { + const caseId = findLatestShippingCaseId(messages.value); + const text = caseId ? `${message} case_id=${caseId}` : message; + await sendMessage(text, agentId, selectedKb.value, []); + if (!conversationId.value && history.value.length === 0) { + await loadHistory(); + } else if (conversationId.value) { + const exists = history.value.some((h) => h.conversation_id === conversationId.value); + if (!exists) await loadHistory(); + } +}; + +const handleShippingMenuAction = async (action: { id?: string; message: string }, msg?: any) => { + if (isThinking.value) return; + + if (action.id === 'upload_inventory_file') { + openShippingInventoryPicker(); + return; + } + + if (action.id === 'paste_inventory_json') { + if (typeof msg !== 'undefined') msg.shipping_actions_used = true; + msg.info(t('chat.shippingNoticePasteHint')); + return; + } + + if (action.id && SHIPPING_DECISION_ACTIONS.has(action.id)) { + if (msg?.shipping_actions_used) return; + if (msg) msg.shipping_actions_used = true; + await executeShippingDecision(action.id, action.message); + return; + } + + if (msg?.shipping_actions_used) return; + if (msg) msg.shipping_actions_used = true; + await sendShippingMenuMessage(action.message); +}; + +let shippingActionsRequestSeq = 0; + +const assistantMessageHasLaterUserReply = (msgs: Array<{ role?: string }>, index: number) => + msgs.slice(index + 1).some((item) => item.role === 'user'); + +const refreshShippingActions = async () => { + if (!isShippingNoticeAgent.value) return; + + const msgs = messages.value; + if (!msgs.length) return; + + const caseId = findLatestShippingCaseId(msgs); + let apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null = null; + let apiResolved = false; + + if (caseId && !isThinking.value) { + const seq = ++shippingActionsRequestSeq; + try { + const data = await getShippingChatActions(caseId); + if (seq === shippingActionsRequestSeq) { + apiResolved = true; + apiButtons = data.action_buttons?.length ? data.action_buttons : []; + } + } catch { + // fall back to content-based buttons + } + } + + let lastOpenAssistantIndex = -1; + for (let i = msgs.length - 1; i >= 0; i -= 1) { + const item = msgs[i]; + if (item?.role !== 'assistant') continue; + if (assistantMessageHasLaterUserReply(msgs, i)) continue; + lastOpenAssistantIndex = i; + break; + } + + msgs.forEach((rawMsg, index) => { + const msg = rawMsg as any; + if (msg.role !== 'assistant' || msg.shipping_actions_used) { + return; + } + if (msg.type && !['text', undefined].includes(msg.type)) { + msg.shipping_actions = undefined; + return; + } + if (assistantMessageHasLaterUserReply(msgs, index)) { + msg.shipping_actions = undefined; + return; + } + + let buttons: Array<{ id: string; label: string; message: string; variant?: string }> = []; + if (apiResolved && index === lastOpenAssistantIndex) { + buttons = apiButtons || []; + } else if (!apiResolved) { + buttons = inferShippingActionsFromContent(String(msg.content || '')); + } + msg.shipping_actions = buttons.length ? buttons : undefined; + }); +}; + +watch([messages, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => { + void refreshShippingActions(); +}, { deep: true }); + +const handleShippingActionClick = async (msg: any, action: { id?: string; message: string }) => { + await handleShippingMenuAction(action, msg); +}; + +const handleShippingInventorySelected = async (event: Event) => { + const input = event.target as HTMLInputElement; + const file = input.files?.[0]; + input.value = ''; + const caseId = pendingShippingUploadCaseId.value; + pendingShippingUploadCaseId.value = ''; + if (!file || !caseId) return; + + try { + const result = await uploadWorkspaceShippingInventory(caseId, file); + const hint = result.message || t('chat.shippingNoticeUploadOk'); + await handleSend(`${t('chat.shippingNoticeUploadDone', { fileName: file.name })} ${hint} case_id=${caseId}`); + } catch (e: any) { + msg.warning(e?.message || t('chat.shippingNoticeUploadFailed')); + } +}; + /** * handleSend * 用途:将输入框内容发送给当前 Agent @@ -2076,6 +2505,33 @@ const handleSend = async (textOrEvent?: string | Event) => { return; } + if (isShippingNoticeAgent.value) { + const menuChoice = resolveShippingNumericChoice(content); + if (menuChoice) { + if (typeof textOrEvent !== 'string') input.value = ''; + if (menuChoice === 'upload') { + if (openShippingInventoryPicker()) return; + } else if (menuChoice === 'paste') { + msg.info(t('chat.shippingNoticePasteHint')); + return; + } else { + await sendShippingMenuMessage(SHIPPING_MENU_ACTION_SPECS[menuChoice].message); + return; + } + } + + const shippingDecision = resolveShippingDecisionFromText(content); + if (shippingDecision) { + if (typeof textOrEvent !== 'string') input.value = ''; + if (await executeShippingDecision(shippingDecision, content.trim())) return; + } + + if (isShippingInventoryUploadIntent(content)) { + if (typeof textOrEvent !== 'string') input.value = ''; + if (openShippingInventoryPicker()) return; + } + } + let files: ChatUploadFileSpec[] = []; if (attachmentPolicy.value.anyEnabled && attachments.value.length > 0) { try { @@ -3076,6 +3532,24 @@ const showChatRating = ref(false); @click="handleChatMarkdownClick" v-html="renderMarkdown(msg.content)" > +
+
{{ $t('chat.shippingNoticeActionsHint') }}
+
+ +
+
@@ -3224,6 +3698,14 @@ const showChatRating = ref(false); autocapitalize="off" > + +