from __future__ import annotations import re import uuid from datetime import datetime from pathlib import Path from typing import Any from flask import current_app from app import db from app.models import ShippingTask, ShippingTaskEvent 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 format_match_summary, match_notice_lines from app.services.shipping_notice.match_rule_desc import extract_mapping_payload_extras from app.services.shipping_notice.parse_summary import format_parse_summary 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_mapping_store import ( resolve_inventory_mapping, upsert_inventory_mapping, ) from app.services.shipping_notice.inventory_upload import ( has_uploaded_task_inventory, inventory_text_max_chars, parse_uploaded_task_inventory, read_task_inventory_schema_preview, save_task_inventory_upload, task_inventory_upload_path, ) from app.services.shipping_notice.rpa import ( find_latest_inventory_file, inventory_processed_dir, write_inventory_export_trigger, write_upload_trigger, ) from app.services.shipping_notice.reservation_id import extract_reservation_id 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(task: ShippingTask) -> bool: return task.review_status == "inventory_mapping_review" def _match_completed(task: ShippingTask) -> bool: return bool( task.process_status == "matched" and task.match_status and isinstance(task.line_results_json, list) and len(task.line_results_json) > 0 ) def _excel_gate_error(task: ShippingTask) -> str | None: if task.process_status == "uploaded" and task.export_file_path: return None if not _match_completed(task): return "尚未完成库存匹配。请先上传库存、确认字段对齐并调用 match_inventory。" return None def _latest_inventory_column_meta(task: ShippingTask) -> dict[str, Any] | None: if task.id is None: return None events = ( ShippingTaskEvent.query.filter_by(task_id=task.id) .order_by(ShippingTaskEvent.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_task(task: ShippingTask, column_meta: dict[str, Any] | None = None) -> dict[str, Any]: meta = column_meta or _latest_inventory_column_meta(task) return build_field_alignment_preview( task.inventory_lines_json or [], task.lines_json or [], column_meta=meta, ) def _inventory_mapping_checkpoint_response( task: ShippingTask, *, 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_task(task, column_meta) data = { **_serialize_task(task), "field_alignment": field_alignment, **(extra_data or {}), } return tool_response( status="needs_human", task_id=task.task_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( task: ShippingTask, 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]: task.inventory_lines_json = inventory_lines task.process_status = "inventory_ready" task.error_message = None field_alignment = _field_alignment_for_task(task, column_meta) if require_mapping_review and _mapping_review_enabled(): task.review_status = "inventory_mapping_review" task.pending_human_reason = "inventory_field_mapping_review" _log_event( task, 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( task, message=( f"【必须暂停】已解析库存 {len(inventory_lines)} 行。" "请先向用户展示字段对齐表并等待确认;" "禁止在本轮调用 match_inventory。" ), column_meta=column_meta, extra_data={ "inventory_row_count": len(inventory_lines), "warnings": warnings or [], }, ) task.review_status = None task.pending_human_reason = None _log_event( task, event_type, { "row_count": len(inventory_lines), "warnings": warnings or [], "source": source, "column_meta": column_meta, }, ) db.session.commit() return tool_response( status="ok", task_id=task.task_no, message=f"已载入库存 {len(inventory_lines)} 行,可进行匹配。", data={ **_serialize_task(task), "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: return raw text = payload.get("inventory_lines_json") if isinstance(text, str) and text.strip(): import json try: parsed = json.loads(text) if isinstance(parsed, list): return parsed except json.JSONDecodeError: return None return None def _generate_task_no() -> str: return f"SN-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" def _log_event(task: ShippingTask, event_type: str, detail: dict[str, Any] | None = None) -> None: if task.id is None: db.session.flush() db.session.add(ShippingTaskEvent( task_id=task.id, event_type=event_type, detail_json=detail or {}, )) _TASK_NO_RE = re.compile(r"SN-\d{8}-[A-F0-9]{8}", re.IGNORECASE) def _extract_task_no(text: str) -> str | None: match = _TASK_NO_RE.search(str(text or "")) return match.group(0).upper() if match else None def _get_task(task_id: str) -> ShippingTask | None: value = str(task_id or "").strip() if not value: return None task = ShippingTask.query.filter_by(task_no=value).first() if task: return task if value.isdigit(): return db.session.get(ShippingTask, int(value)) return None def _resolve_task_from_payload(payload: dict[str, Any]) -> ShippingTask | None: """Resolve task by task_id/task_no, embedded SN- in text fields, or conversation_id.""" if not isinstance(payload, dict): return None for key in ("task_id", "task_no"): task = _get_task(str(payload.get(key) or "")) if task: return task for key in ("comment", "user_message", "raw_text", "query"): hint = _extract_task_no(str(payload.get(key) or "")) if hint: task = _get_task(hint) if task: return task conv_id = str(payload.get("conversation_id") or "").strip() if conv_id: return ( ShippingTask.query.filter_by(conversation_id=conv_id) .filter(ShippingTask.process_status.notin_(["rejected"])) .order_by(ShippingTask.id.desc()) .first() ) return None def _serialize_task(task: ShippingTask) -> dict[str, Any]: return { "task_no": task.task_no, "process_status": task.process_status, "review_status": task.review_status, "match_status": task.match_status, "pending_human_reason": task.pending_human_reason, "customer_name": task.customer_name, "customer_code": task.customer_code, "ship_to": task.ship_to, "po_number": task.po_number, "required_date": task.required_date, "lines": task.lines_json or [], "shortage": task.shortage_json, "line_results": task.line_results_json, "export_file_name": task.export_file_name, "freight_ref_no": task.freight_ref_no, "error_message": task.error_message, "conversation_id": task.conversation_id, } def create_task(payload: dict[str, Any]) -> dict[str, Any]: conv_id = str(payload.get("conversation_id") or "").strip() if conv_id: existing = ( ShippingTask.query.filter_by(conversation_id=conv_id) .filter(ShippingTask.process_status.notin_(["rejected"])) .order_by(ShippingTask.id.desc()) .first() ) if existing and existing.process_status != "uploaded": return tool_response( status="ok", task_id=existing.task_no, message=( f"当前会话已有进行中的发货任务 {existing.task_no},请勿重复 create_task。" "用户确认/驳回时请 submit_decision,并带上任务编号或 conversation_id。" ), data=_serialize_task(existing), checkpoint="task_already_exists", ) task = ShippingTask( task_no=_generate_task_no(), user_id=payload.get("user_id"), conversation_id=str(payload.get("conversation_id") or "").strip() or None, source_type=str(payload.get("source_type") or "manual"), raw_content=str(payload.get("raw_content") or "").strip() or None, process_status="created", ) db.session.add(task) _log_event(task, "task_created", {"source_type": task.source_type}) db.session.commit() return tool_response( status="ok", task_id=task.task_no, message=f"已创建发货任务 {task.task_no}", data=_serialize_task(task), ) def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: task = _resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") conv_id = str(payload.get("conversation_id") or "").strip() if conv_id and not task.conversation_id: task.conversation_id = conv_id raw_text = str(payload.get("raw_text") or task.raw_content or "").strip() structured = payload.get("structured") if isinstance(payload.get("structured"), dict) else None notice_files = payload.get("notice_files") if not isinstance(notice_files, list) or not all(isinstance(i, dict) for i in notice_files): notice_files = None parsed, confidence, warnings = extract_notice_fields( raw_text=raw_text, source_type=task.source_type, structured=structured, notice_files=notice_files, ) task.raw_content = raw_text or task.raw_content task.customer_name = str(parsed.get("customer_name") or "").strip() or None task.customer_code = str(parsed.get("customer_code") or "").strip() or None task.ship_to = str(parsed.get("ship_to") or "").strip() or None task.po_number = str(parsed.get("po_number") or "").strip() or None lines = parsed.get("lines") if isinstance(parsed.get("lines"), list) else [] required_date = str(parsed.get("required_date") or "").strip() if not required_date: for line in lines: if isinstance(line, dict): line_date = str(line.get("required_date") or "").strip() if line_date: required_date = line_date break task.required_date = required_date or None task.lines_json = lines task.parse_confidence = confidence task.process_status = "parsed" task.pending_human_reason = None summary_kwargs = { "task_no": task.task_no, "po_number": task.po_number, "ship_to": task.ship_to, "customer_name": task.customer_name, "required_date": task.required_date, "lines": lines, "warnings": warnings, } if confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7): task.process_status = "pending_review" task.review_status = "parse_review" task.pending_human_reason = "low_parse_confidence" _log_event(task, "parse_needs_review", {"confidence": confidence, "warnings": warnings}) db.session.commit() return tool_response( status="needs_human", task_id=task.task_no, message=format_parse_summary(**summary_kwargs, low_confidence=True), data={**_serialize_task(task), "warnings": warnings}, human_options=["confirm", "reject", "reparse"], ) _log_event(task, "parsed", {"confidence": confidence, "warnings": warnings}) db.session.commit() return tool_response( status="ok", task_id=task.task_no, message=format_parse_summary(**summary_kwargs), data={**_serialize_task(task), "warnings": warnings}, ) 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 _extract_partial_inventory_field_mapping(raw: Any) -> dict[str, str]: 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: data = None if not data: return {} inner = data.get("mapping") if isinstance(data.get("mapping"), dict) else data if not isinstance(inner, dict): return {} result: dict[str, str] = {} for key in ("sku", "reservation_id", "available_qty"): value = inner.get(key) if value is None: continue text = str(value).strip() if text: result[key] = text return result def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]: """Parse inventory from uploaded file, chat text, or structured JSON.""" task = _resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") 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) mapping_extras = extract_mapping_payload_extras( payload.get("column_mapping_json") or payload.get("field_mapping") ) if mapping_extras.get("match_rule"): mapping_source = "llm" if use_uploaded or (not inventory_lines and not raw_text and has_uploaded_task_inventory(task.task_no)): if not has_uploaded_task_inventory(task.task_no): return tool_response( status="needs_human", task_id=task.task_no, message="未找到已上传的库存文件。请先 POST /tools/upload_inventory_file 上传 Excel。", data=_serialize_task(task), human_options=["upload_inventory_file", "retry_rpa"], checkpoint="inventory_upload_required", stop_agent_turn=True, ) inventory_lines, column_meta, path = parse_uploaded_task_inventory( task.task_no, field_mapping=field_mapping, mapping_source=mapping_source, llm_match_rule=mapping_extras.get("match_rule"), llm_match_key=mapping_extras.get("match_key"), ) 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( task, "inventory_text_too_large", {"chars": len(raw_text), "max_chars": max_chars}, ) db.session.commit() return tool_response( status="needs_human", task_id=task.task_no, message=( f"库存文本过大({len(raw_text)} 字符,上限 {max_chars})。" "请勿将 Excel 全文传入 LLM;请用 HTTP 节点调用 " "POST /tools/upload_inventory_file 上传,再 " "parse_inventory(use_uploaded_file=true)。" ), data=_serialize_task(task), 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(task, "inventory_parse_failed", {"warnings": warnings, "use_uploaded": use_uploaded}) db.session.commit() return tool_response( status="needs_human", task_id=task.task_no, message="未能解析库存明细。大 Excel 请 upload_inventory_file;小表可粘贴;无库存可走 RPA。", data={**_serialize_task(task), "warnings": warnings}, human_options=["reparse_inventory", "retry_rpa", "paste_inventory_json"], ) return _inventory_loaded_response( task, 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).""" task = _resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") if not has_uploaded_task_inventory(task.task_no): return tool_response( status="needs_human", task_id=task.task_no, message="未找到已上传的库存文件。请先 POST /tools/upload_inventory_file 上传 Excel。", data=_serialize_task(task), human_options=["upload_inventory_file", "retry_rpa"], checkpoint="inventory_upload_required", stop_agent_turn=True, ) try: preview = read_task_inventory_schema_preview(task.task_no) except OSError as exc: return tool_response(status="failed", task_id=task.task_no, message=f"读取库存表头失败: {exc}") _log_event(task, "inventory_schema_preview", {"headers": preview.get("headers")}) db.session.commit() return tool_response( status="ok", task_id=task.task_no, message=( "已读取库存表头与样例行。请根据 schema_preview 推断列映射," "调用 apply_inventory_mapping(column_mapping_json=...)。" ), data={**_serialize_task(task), "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.""" task = _resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") if not has_uploaded_task_inventory(task.task_no): return tool_response( status="needs_human", task_id=task.task_no, message="未找到已上传的库存文件。请先 upload_inventory_file。", data=_serialize_task(task), checkpoint="inventory_upload_required", stop_agent_turn=True, ) try: preview = read_task_inventory_schema_preview(task.task_no) except OSError as exc: return tool_response(status="failed", task_id=task.task_no, message=f"读取库存表头失败: {exc}") raw = payload.get("column_mapping_json") if raw is None: raw = payload.get("field_mapping") direct = normalize_field_mapping(raw) partial = _extract_partial_inventory_field_mapping(raw) template: dict[str, str] = {} if task.customer_code: resolved = resolve_inventory_mapping(task.customer_code, preview=preview) if isinstance(resolved, dict): template = {k: str(v).strip() for k, v in resolved.items() if str(v or "").strip()} suggested = preview.get("suggested_mapping") if isinstance(preview.get("suggested_mapping"), dict) else {} suggested = {k: str(v).strip() for k, v in suggested.items() if str(v or "").strip()} base: dict[str, str] = {} if mapping_is_complete(template): base = template elif mapping_is_complete(suggested): base = suggested else: base = {**template, **suggested} field_mapping = direct or {**base, **partial} mapping_extras = extract_mapping_payload_extras(raw) if direct or partial or mapping_extras.get("match_rule"): mapping_source = "llm" else: mapping_source = "rules" if not mapping_is_complete(field_mapping): return tool_response( status="failed", task_id=task.task_no, message=( "column_mapping_json 无效或不完整。" '需要提供 {"sku":"列名","reservation_id":"列名","available_qty":"列名"}。' "(库存的 Reservation ID 列允许为空值,但必须有该列标题)" ), data={ **_serialize_task(task), "schema_preview": preview, "suggested_mapping": suggested, "template_mapping": template if template else None, "received_mapping": partial or None, }, ) 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", task_id=task.task_no, message=( "列映射与 Excel 表头不匹配。" f"(表头在第 {header_row} 行)" + " ".join(mapping_errors) + " 请根据 schema_preview.headers 重新调用 apply_inventory_mapping。" ), data={**_serialize_task(task), "schema_preview": preview}, ) try: inventory_lines, column_meta, path = parse_uploaded_task_inventory( task.task_no, field_mapping=field_mapping, mapping_source=mapping_source, header_row_index=preview.get("header_row_index"), llm_match_rule=mapping_extras.get("match_rule"), llm_match_key=mapping_extras.get("match_key"), ) except FileNotFoundError as exc: return tool_response(status="failed", task_id=task.task_no, message=str(exc)) except OSError as exc: return tool_response(status="failed", task_id=task.task_no, message=f"解析库存失败: {exc}") warnings = [f"parsed with mapping from uploaded file: {path.name}"] upsert_inventory_mapping(task.customer_code, preview=preview, field_mapping=field_mapping) return _inventory_loaded_response( task, 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(task_id: str, upload: Any) -> dict[str, Any]: """Save multipart Excel; return schema preview for LLM mapping (no full parse).""" task = _get_task(str(task_id or "")) if not task: return tool_response(status="failed", message="未找到任务编号") if upload is None or not getattr(upload, "filename", None): return tool_response(status="failed", task_id=task.task_no, message="未收到 file 字段") filename = str(upload.filename or "").strip() if not filename.lower().endswith((".xlsx", ".xls", ".csv")): return tool_response( status="failed", task_id=task.task_no, message="仅支持 .xlsx / .xls / .csv 库存文件", ) try: save_task_inventory_upload(task.task_no, upload) preview = read_task_inventory_schema_preview(task.task_no) except OSError as exc: return tool_response(status="failed", task_id=task.task_no, message=f"保存库存文件失败: {exc}") template_mapping = resolve_inventory_mapping(task.customer_code, preview=preview) if template_mapping and mapping_is_complete(template_mapping): try: inventory_lines, column_meta, path = parse_uploaded_task_inventory( task.task_no, field_mapping=template_mapping, mapping_source="template", ) if inventory_lines: warnings = [f"parsed from template mapping: {path.name}"] return _inventory_loaded_response( task, inventory_lines, warnings=warnings, column_meta=column_meta, source="uploaded_file_template", require_mapping_review=True, event_type="inventory_template_mapping_used", ) except Exception: pass task.process_status = "waiting_inventory" task.pending_human_reason = "inventory_mapping_inference" _log_event(task, "inventory_file_uploaded", {"filename": filename, "headers": preview.get("headers")}) db.session.commit() return tool_response( status="ok", task_id=task.task_no, message="库存文件已上传,但未能自动识别关键列。请检查表头行并更正列映射后继续。", data={**_serialize_task(task), "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]: task = _resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") mode = str(payload.get("mode") or "auto").strip().lower() inventory_lines = _parse_inventory_lines(payload) if inventory_lines: return _inventory_loaded_response( task, inventory_lines, source="manual_json", require_mapping_review=False, event_type="inventory_uploaded", ) if mode == "retry_rpa" or mode == "auto": latest = find_latest_inventory_file() processed = inventory_processed_dir() if latest and processed: try: lines, column_meta = ingest_inventory_file(latest, move_to=processed) if lines: return _inventory_loaded_response( task, lines, column_meta=column_meta, source="rpa_drop", require_mapping_review=True, event_type="inventory_rpa_drop_ingested", ) except Exception as exc: task.error_message = str(exc)[:500] trigger = write_inventory_export_trigger(task.task_no, {"mode": mode}) if trigger: task.process_status = "waiting_inventory" task.pending_human_reason = "inventory_rpa_pending" _log_event(task, "inventory_rpa_triggered", {"trigger": trigger}) db.session.commit() return tool_response( status="running", task_id=task.task_no, message="已触发 RPA 库存导出,完成后可继续匹配。", data={**_serialize_task(task), "trigger_path": trigger}, ) _log_event(task, "inventory_rpa_retry_requested", {}) db.session.commit() return tool_response( status="needs_human", task_id=task.task_no, message="RPA 库存目录未配置或触发失败。请上传货代库存 Excel。", data=_serialize_task(task), human_options=["upload_inventory_file", "retry_rpa"], ) if task.inventory_lines_json: if _awaiting_inventory_mapping_confirm(task): return _inventory_mapping_checkpoint_response( task, message="库存已解析但未确认字段对齐,请先展示 field_alignment 并等待用户确认。", ) task.process_status = "inventory_ready" db.session.commit() return tool_response( status="ok", task_id=task.task_no, message="已有库存快照且字段对齐已确认,可调用 match_inventory。", data=_serialize_task(task), ) task.process_status = "waiting_inventory" task.pending_human_reason = "inventory_unavailable" _log_event(task, "inventory_missing", {}) db.session.commit() return tool_response( status="needs_human", task_id=task.task_no, message="暂无可用库存数据。请重试 RPA 自动导出,或手动上传货代库存 Excel。", data=_serialize_task(task), human_options=["retry_rpa", "upload_inventory_file"], ) def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: task = _resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") if _awaiting_inventory_mapping_confirm(task): return _inventory_mapping_checkpoint_response( task, message="【禁止匹配】尚未确认库存字段对齐。请先展示 field_alignment,等用户确认后再 submit_decision(confirm_inventory_mapping)。", ) inventory_lines = _parse_inventory_lines(payload) if inventory_lines: task.inventory_lines_json = inventory_lines elif not task.inventory_lines_json: return ensure_inventory({"task_id": task.task_no}) notice_lines = task.lines_json or [] order_missing = [ {"sku": str(line.get("sku") or "").strip(), "reservation_id": str(line.get("reservation_id") or "").strip()} for line in (notice_lines if isinstance(notice_lines, list) else []) if not extract_reservation_id(line.get("reservation_id")) ] inv_missing_count = sum( 1 for row in (task.inventory_lines_json or []) if not extract_reservation_id((row or {}).get("reservation_id")) ) if order_missing: task.process_status = "pending_review" task.review_status = "reservation_id_required" task.pending_human_reason = "reservation_id_required" task.match_status = None task.shortage_json = None task.line_results_json = None detail = { "order_missing_count": len(order_missing), "order_missing_preview": order_missing[:5], } _log_event(task, "reservation_id_required", detail) db.session.commit() return tool_response( status="needs_human", task_id=task.task_no, message=( "当前匹配规则要求发货需求(订单)必须提供 Reservation ID。" f"订单缺少 Reservation ID:{len(order_missing)} 行。" "请重新解析发货通知后再匹配。" ), data={**_serialize_task(task), "reservation_id_required": detail}, human_options=["reparse", "edit_inventory_mapping", "upload_inventory_file", "reject"], checkpoint="reservation_id_required", stop_agent_turn=True, forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"], ) match_status, line_results, shortage = match_notice_lines( notice_lines, task.inventory_lines_json or [], ) if inv_missing_count: if isinstance(shortage, dict): shortage.setdefault("warnings", []) if isinstance(shortage["warnings"], list): shortage["warnings"].append( f"库存存在 {inv_missing_count} 行缺少 Reservation ID,已忽略这部分库存行。" ) task.match_status = match_status task.line_results_json = line_results task.shortage_json = shortage task.pending_human_reason = None match_summary = format_match_summary(match_status, line_results) if match_status == "fulfillable": task.process_status = "matched" task.review_status = "confirmed" _log_event(task, "matched_fulfillable", {"match_status": match_status}) db.session.commit() return tool_response( status="ok", task_id=task.task_no, message=match_summary, data=_serialize_task(task), ) task.process_status = "pending_review" task.review_status = "inventory_shortage_review" task.pending_human_reason = "inventory_shortage" _log_event(task, "match_needs_review", {"match_status": match_status, "shortage": shortage}) db.session.commit() return tool_response( status="needs_human", task_id=task.task_no, message=match_summary, data=_serialize_task(task), human_options=["confirm", "reject", "rematch"], ) def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: task = _resolve_task_from_payload(payload) if not task: return tool_response( status="failed", message=( "未找到任务。用户说「确认/重新解析/驳回」时禁止 create_task。" "请先 get_task_status(conversation_id=...) 或 submit_decision 带上任务编号。" ), ) decision = str(payload.get("decision") or "").strip().lower() comment = str(payload.get("comment") or "").strip() if decision == "reject": task.process_status = "rejected" task.review_status = "rejected" task.pending_human_reason = None _log_event(task, "decision_rejected", {"comment": comment}) db.session.commit() return tool_response( status="ok", task_id=task.task_no, message="已驳回该发货任务。", data=_serialize_task(task), ) if decision in {"confirm", "confirmed", "confirm_parse"}: if task.review_status == "inventory_shortage_review" or task.pending_human_reason == "inventory_shortage": task.review_status = "confirmed" task.process_status = "matched" task.pending_human_reason = None _log_event(task, "decision_confirmed_shortage", {"comment": comment}) db.session.commit() return tool_response( status="ok", task_id=task.task_no, message="已确认部分发货,可继续生成 Excel 并上传货代系统。", data=_serialize_task(task), ) if ( decision == "confirm_parse" or task.review_status == "parse_review" or task.pending_human_reason == "low_parse_confidence" or ( task.process_status in {"parsed", "pending_review", "created"} and not _match_completed(task) ) ): task.review_status = None task.process_status = "parsed" task.pending_human_reason = None task.match_status = None task.shortage_json = None task.line_results_json = None _log_event(task, "parse_confirmed", {"comment": comment}) db.session.commit() if (not task.inventory_lines_json) and (not has_uploaded_task_inventory(task.task_no)): return ensure_inventory({"task_id": task.task_no, "mode": "auto"}) return tool_response( status="ok", task_id=task.task_no, message=( "发货通知已确认。" "请先处理库存(ensure_inventory / parse_inventory → confirm_inventory_mapping → match_inventory)。" "禁止跳过匹配直接 generate_shipment_excel。" ), data=_serialize_task(task), checkpoint="parse_confirmed", next_required_action="ensure_inventory 或 parse_inventory", forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"], ) if _match_completed(task): task.review_status = "confirmed" task.pending_human_reason = None _log_event(task, "decision_confirmed", {"comment": comment}) db.session.commit() return tool_response( status="ok", task_id=task.task_no, message="已确认,可继续生成 Excel 并上传货代系统。", data=_serialize_task(task), ) return tool_response( status="failed", task_id=task.task_no, message="当前状态无法使用 confirm。请先完成库存匹配,或使用 confirm_inventory_mapping / reparse。", data=_serialize_task(task), ) if decision == "rematch": _log_event(task, "decision_rematch", {"comment": comment}) db.session.commit() return match_inventory({"task_id": task.task_no}) if decision == "confirm_inventory_mapping": if not _awaiting_inventory_mapping_confirm(task): return tool_response( status="failed", task_id=task.task_no, message="当前无需确认库存字段对齐。", data=_serialize_task(task), ) meta = _latest_inventory_column_meta(task) or {} inv_mapping = meta.get("mapping") if isinstance(meta.get("mapping"), dict) else {} res_source = None if isinstance(inv_mapping.get("reservation_id"), dict): res_source = inv_mapping["reservation_id"].get("source_column") if not str(res_source or "").strip(): task.pending_human_reason = "inventory_field_mapping_review" task.review_status = "inventory_mapping_review" db.session.commit() return _inventory_mapping_checkpoint_response( task, message=( "库存表必须包含 Reservation ID 列标题(该列允许为空值)。" "请点击「更正映射」重新选择 Reservation ID 对应的列,或重新上传包含该列的库存 Excel。" ), column_meta=meta, ) headers = meta.get("headers") if isinstance(meta.get("headers"), list) else [] field_mapping = meta.get("field_mapping") if isinstance(meta.get("field_mapping"), dict) else None if headers and field_mapping and mapping_is_complete(field_mapping): upsert_inventory_mapping( task.customer_code, preview={ "headers": headers, "header_row_index": meta.get("header_row_index") or 1, }, field_mapping={str(k): str(v).strip() for k, v in field_mapping.items() if str(v or "").strip()}, ) task.review_status = None task.pending_human_reason = None _log_event(task, "inventory_mapping_confirmed", {"comment": comment}) db.session.commit() return tool_response( status="ok", task_id=task.task_no, message="字段对齐已确认。现在可以调用 match_inventory(仅在本轮或下一轮,勿与 parse_inventory 同轮)。", data=_serialize_task(task), checkpoint="inventory_mapping_confirmed", next_required_action="match_inventory", ) if decision == "correct_inventory_mapping": if not _awaiting_inventory_mapping_confirm(task): return tool_response( status="failed", task_id=task.task_no, message="当前不在库存字段对齐确认步骤,无法更正映射。", data=_serialize_task(task), ) task.inventory_lines_json = None task.review_status = None task.pending_human_reason = "inventory_mapping_inference" task.process_status = "waiting_inventory" _log_event(task, "inventory_mapping_correction_requested", {"comment": comment}) db.session.commit() upload_path = task_inventory_upload_path(task.task_no) if upload_path.is_file(): try: preview = read_task_inventory_schema_preview(task.task_no) except OSError as exc: return tool_response( status="failed", task_id=task.task_no, message=f"读取库存表头失败: {exc}", data=_serialize_task(task), ) else: meta = _latest_inventory_column_meta(task) 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", task_id=task.task_no, message=( "已回到列映射步骤。请根据 schema_preview 提供新的 column_mapping_json," "再调用 apply_inventory_mapping。" ), data={**_serialize_task(task), "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": task.inventory_lines_json = None task.review_status = None task.pending_human_reason = None if task.process_status == "inventory_ready": task.process_status = "parsed" upload_path = task_inventory_upload_path(task.task_no) if upload_path.is_file(): try: upload_path.unlink() except OSError: pass _log_event(task, "inventory_reparse_requested", {"comment": comment}) db.session.commit() return tool_response( status="ok", task_id=task.task_no, message="已清除库存快照,请重新上传或粘贴库存后调用 parse_inventory。", data=_serialize_task(task), ) if decision == "reparse": return parse_notice({"task_id": task.task_no, "raw_text": task.raw_content or ""}) return tool_response(status="failed", task_id=task.task_no, message=f"未知 decision: {decision}") def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: task = _resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") gate_error = _excel_gate_error(task) if gate_error: return tool_response( status="failed", task_id=task.task_no, message=gate_error, data=_serialize_task(task), forbidden_next_tools=["upload_to_freight"], next_required_action="match_inventory(须先完成库存上传与字段对齐确认)", ) path, filename = generate_shipment_excel(task) task.export_file_path = path task.export_file_name = filename task.process_status = "waiting_upload" _log_event(task, "export_generated", {"file_name": filename}) db.session.commit() return tool_response( status="ok", task_id=task.task_no, message=f"已生成发货 Excel:{filename}", data={**_serialize_task(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"}, ) def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: task = _resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") if not task.export_file_path: gen = generate_excel({"task_id": task.task_no}) if gen.get("status") != "ok": return gen mode = str(payload.get("mode") or "auto").strip().lower() if mode == "manual_confirm": ref = str(payload.get("freight_ref_no") or "").strip() task.process_status = "uploaded" task.freight_ref_no = ref or None task.pending_human_reason = None _log_event(task, "upload_manual_confirmed", {"freight_ref_no": ref}) db.session.commit() return tool_response( status="ok", task_id=task.task_no, message="已标记为手工上传货代系统完成。", data=_serialize_task(task), ) if mode == "retry_upload" or mode == "auto": queued, trigger = write_upload_trigger(task.task_no, task.export_file_path or "") if queued and trigger: task.process_status = "waiting_upload" task.pending_human_reason = "upload_rpa_pending" _log_event(task, "upload_rpa_triggered", {"queue_file": queued, "trigger": trigger}) db.session.commit() return tool_response( status="running", task_id=task.task_no, message="已触发 RPA 上传货代,请稍候…", data={**_serialize_task(task), "queue_file": queued}, ) task.process_status = "upload_failed" task.pending_human_reason = "upload_rpa_failed" task.error_message = "RPA 上传目录未配置或触发失败" _log_event(task, "upload_rpa_pending", {}) db.session.commit() return tool_response( status="needs_human", task_id=task.task_no, message="RPA 自动上传失败或未配置。请下载 Excel 在货代系统手工上传,完成后告知我。", data=_serialize_task(task), human_options=["retry_upload", "download_excel", "mark_manual_uploaded"], ) def get_task_status(payload: dict[str, Any]) -> dict[str, Any]: task = _resolve_task_from_payload(payload) if not task: return tool_response( status="failed", message="未找到任务。请提供任务编号或 conversation_id(Dify 会话 ID)。", ) return tool_response( status="ok", task_id=task.task_no, message=f"当前状态:{task.process_status}", data=_serialize_task(task), human_options=_human_options_for_task(task), ) def _human_options_for_task(task: ShippingTask) -> list[str] | None: from app.services.shipping_notice.chat_actions import human_options_for_task return human_options_for_task(task) def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: task = _resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") success = bool(payload.get("success", True)) if not success: task.process_status = "waiting_inventory" task.pending_human_reason = "inventory_unavailable" task.error_message = str(payload.get("error_message") or "RPA inventory export failed")[:500] _log_event(task, "inventory_rpa_failed", {"error": task.error_message}) db.session.commit() return tool_response( status="needs_human", task_id=task.task_no, message=task.error_message, data=_serialize_task(task), human_options=["retry_rpa", "upload_inventory_file"], ) file_path = str(payload.get("file_path") or "").strip() path = Path(file_path) if file_path else find_latest_inventory_file() if not path or not path.is_file(): return tool_response(status="failed", task_id=task.task_no, message="库存文件不存在") processed = inventory_processed_dir() lines, column_meta = ingest_inventory_file(path, move_to=processed) return _inventory_loaded_response( task, 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]: task = _resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") success = bool(payload.get("success", True)) if success: task.process_status = "uploaded" task.freight_ref_no = str(payload.get("freight_ref_no") or "").strip() or None task.pending_human_reason = None task.error_message = None _log_event(task, "upload_rpa_success", {"freight_ref_no": task.freight_ref_no}) db.session.commit() return tool_response( status="ok", task_id=task.task_no, message="RPA 已成功上传货代系统。", data=_serialize_task(task), ) task.process_status = "upload_failed" task.pending_human_reason = "upload_rpa_failed" task.error_message = str(payload.get("error_message") or "RPA upload failed")[:500] _log_event(task, "upload_rpa_failed", {"error": task.error_message}) db.session.commit() return tool_response( status="needs_human", task_id=task.task_no, message=task.error_message, data=_serialize_task(task), human_options=["retry_upload", "download_excel", "mark_manual_uploaded"], )