feat(shipping-notice): 实现货代发货通知的库存全流程与对话交互
This commit is contained in:
1 parent
a5cc48b6aa
commit
2607f4a9f6
26 files changed
+5013
-256
No files matched your search
@@ -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")
|
||||
|
||||
|
||||
Reference in new issue
Block a user