2044 lines
79 KiB
Python
2044 lines
79 KiB
Python
from __future__ import annotations
|
||
|
||
import json
|
||
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.field_alignment_summary import format_field_alignment_summary
|
||
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.rpa_attempts import (
|
||
inventory_rpa_attempts,
|
||
max_rpa_inventory_attempts,
|
||
max_rpa_upload_attempts,
|
||
upload_rpa_attempts,
|
||
)
|
||
from app.services.shipping_notice.reservation_id import extract_reservation_id
|
||
from app.services.shipping_notice.constants import (
|
||
AUTO_CHAIN_FALLBACK,
|
||
AUTO_MAP,
|
||
CP_MAP_INFER,
|
||
CP_PARSE_OK,
|
||
CP_TASK_EXISTS,
|
||
CP_UPLOAD_REQ,
|
||
CP_UPLOADED,
|
||
PH_UPLOAD_RPA_PENDING,
|
||
PH_RPA_PENDING,
|
||
PH_LOW_CONF,
|
||
PH_SHORTAGE,
|
||
RS_ALIGN_REVIEW,
|
||
RS_PARSE_REVIEW,
|
||
RS_SHORTAGE_REVIEW,
|
||
SUGGEST_OK,
|
||
payload_map_json,
|
||
)
|
||
from app.services.shipping_notice.user_facing_status import (
|
||
strip_internal_task_fields,
|
||
user_facing_task_stage,
|
||
)
|
||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state
|
||
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 == RS_ALIGN_REVIEW
|
||
|
||
|
||
def _cfg_bool(key: str, default: bool = False) -> bool:
|
||
val = current_app.config.get(key)
|
||
if val is None:
|
||
return default
|
||
if isinstance(val, bool):
|
||
return val
|
||
return str(val).strip().lower() in {"1", "true", "yes", "on"}
|
||
|
||
|
||
def _cfg_int(key: str, default: int = 0, *, min_value: int | None = None) -> int:
|
||
val = current_app.config.get(key)
|
||
if val is None:
|
||
parsed = default
|
||
else:
|
||
try:
|
||
parsed = int(val)
|
||
except (TypeError, ValueError):
|
||
parsed = default
|
||
if min_value is not None:
|
||
parsed = max(parsed, min_value)
|
||
return parsed
|
||
|
||
|
||
def _auto_progress_enabled() -> bool:
|
||
return _cfg_bool("SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED", False)
|
||
|
||
|
||
def _auto_rpa_inventory_enabled() -> bool:
|
||
return _cfg_bool("SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED", True)
|
||
|
||
|
||
def _rpa_inventory_timeout_seconds() -> int:
|
||
return _cfg_int("SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS", 120, min_value=5)
|
||
|
||
|
||
def _auto_mapping_allow_llm() -> bool:
|
||
return _cfg_bool("SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM", False)
|
||
|
||
|
||
def _auto_match_enabled() -> bool:
|
||
return _cfg_bool("SHIPPING_NOTICE_AUTO_MATCH_ENABLED", True)
|
||
|
||
|
||
def _auto_generate_excel_enabled() -> bool:
|
||
return _cfg_bool("SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED", True)
|
||
|
||
|
||
def _auto_chain_fallback_enabled() -> bool:
|
||
return _cfg_bool("SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK", True)
|
||
|
||
|
||
def _payload_wants_auto_chain_fallback(payload: dict[str, Any] | None) -> bool:
|
||
"""True when caller explicitly opts into backend fallback chaining (Hxops workspace/chat)."""
|
||
if not payload or not _auto_progress_enabled() or not _auto_chain_fallback_enabled():
|
||
return False
|
||
val = payload.get(AUTO_CHAIN_FALLBACK)
|
||
if val is None:
|
||
return False
|
||
if isinstance(val, bool):
|
||
return val
|
||
return str(val).strip().lower() in {"1", "true", "yes", "on"}
|
||
|
||
|
||
def _merge_tool_payload(
|
||
task: ShippingTask,
|
||
payload: dict[str, Any] | None = None,
|
||
*,
|
||
extra: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
result = _tool_payload_for_task(task, payload)
|
||
if extra:
|
||
result.update(extra)
|
||
if _payload_wants_auto_chain_fallback(payload):
|
||
result[AUTO_CHAIN_FALLBACK] = True
|
||
return result
|
||
|
||
|
||
def _auto_upload_enabled() -> bool:
|
||
return _cfg_bool("SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED", False)
|
||
|
||
|
||
def _rpa_upload_timeout_seconds() -> int:
|
||
return _cfg_int("SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS", 30, min_value=5)
|
||
|
||
|
||
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 _latest_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent | None:
|
||
if task.id is None:
|
||
return None
|
||
return (
|
||
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type=event_type)
|
||
.order_by(ShippingTaskEvent.id.desc())
|
||
.first()
|
||
)
|
||
|
||
|
||
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,
|
||
*,
|
||
column_meta: dict[str, Any] | None = None,
|
||
extra_data: dict[str, Any] | None = None,
|
||
lang: str | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Agent MUST stop and wait for user before match_inventory."""
|
||
field_alignment = _field_alignment_for_task(task, column_meta)
|
||
extra = extra_data or {}
|
||
message = format_field_alignment_summary(
|
||
task_no=task.task_no,
|
||
field_alignment=field_alignment,
|
||
inventory_row_count=extra.get("inventory_row_count"),
|
||
warnings=extra.get("warnings") if isinstance(extra.get("warnings"), list) else None,
|
||
lang=lang,
|
||
)
|
||
data = {
|
||
**_serialize_task_for_tool(task),
|
||
"field_alignment": field_alignment,
|
||
**extra,
|
||
}
|
||
return tool_response(
|
||
status="needs_human",
|
||
task=task,
|
||
message=message,
|
||
data=data,
|
||
next_required_action=(
|
||
"向用户原文展示 message(固定 Markdown)后停止本轮;"
|
||
"用户确认后调用 submit_decision(decision=confirm_inventory_mapping);"
|
||
"禁止在同一轮调用 match_inventory"
|
||
),
|
||
forbidden_next_tools=[
|
||
"match_inventory",
|
||
"generate_shipment_excel",
|
||
"upload_to_freight",
|
||
],
|
||
stop_agent_turn=True,
|
||
)
|
||
|
||
|
||
def _mapping_confirm_blockers(task: ShippingTask) -> list[str]:
|
||
"""Reasons inventory field mapping cannot be confirmed yet."""
|
||
blockers: list[str] = []
|
||
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():
|
||
blockers.append("缺少 Reservation ID 列映射")
|
||
field_alignment = _field_alignment_for_task(task)
|
||
warnings = field_alignment.get("warnings") if isinstance(field_alignment.get("warnings"), list) else []
|
||
blockers.extend(str(w) for w in warnings if w)
|
||
return blockers
|
||
|
||
|
||
def _maybe_auto_confirm_inventory_mapping(task: ShippingTask) -> bool:
|
||
if not _auto_progress_enabled():
|
||
return False
|
||
if not _mapping_review_enabled():
|
||
return False
|
||
if not _awaiting_inventory_mapping_confirm(task):
|
||
return False
|
||
if _mapping_confirm_blockers(task):
|
||
return False
|
||
meta = _latest_inventory_column_meta(task) or {}
|
||
mapping_source = str(meta.get("mapping_source") or "rules").strip().lower()
|
||
if mapping_source == "llm" and not _auto_mapping_allow_llm():
|
||
return False
|
||
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()},
|
||
)
|
||
field_alignment = _field_alignment_for_task(task)
|
||
apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED)
|
||
_log_event(task, "inventory_mapping_auto_confirmed", {"field_alignment": field_alignment})
|
||
db.session.commit()
|
||
return True
|
||
|
||
|
||
def _tool_payload_for_task(task: ShippingTask, payload: dict[str, Any] | None = None) -> dict[str, Any]:
|
||
result: dict[str, Any] = {"task_id": task.task_no}
|
||
if not payload:
|
||
return result
|
||
for key in ("lang", "locale", "language"):
|
||
lang = str(payload.get(key) or "").strip()
|
||
if lang:
|
||
result["lang"] = lang
|
||
break
|
||
return result
|
||
|
||
|
||
def _can_auto_advance_mapping(task: ShippingTask) -> bool:
|
||
"""Mapping is complete with no blockers — may skip align_review human gate."""
|
||
if not _auto_progress_enabled() or not _auto_match_enabled():
|
||
return False
|
||
if not _mapping_review_enabled():
|
||
return False
|
||
if not _awaiting_inventory_mapping_confirm(task):
|
||
return False
|
||
if _mapping_confirm_blockers(task):
|
||
return False
|
||
meta = _latest_inventory_column_meta(task) or {}
|
||
mapping_source = str(meta.get("mapping_source") or "rules").strip().lower()
|
||
if mapping_source == "llm" and not _auto_mapping_allow_llm():
|
||
return False
|
||
return True
|
||
|
||
|
||
def _should_auto_chain_after_mapping(
|
||
task: ShippingTask,
|
||
payload: dict[str, Any] | None,
|
||
) -> bool:
|
||
if _payload_wants_auto_chain_fallback(payload):
|
||
return True
|
||
return _can_auto_advance_mapping(task)
|
||
|
||
|
||
def _prepend_tool_message(result: dict[str, Any], prefix: str) -> dict[str, Any]:
|
||
note = str(prefix or "").strip()
|
||
if not note:
|
||
return result
|
||
body = str(result.get("message") or "").strip()
|
||
return {**result, "message": f"{note}\n\n{body}" if body else note}
|
||
|
||
|
||
def _should_auto_chain_after_match(payload: dict[str, Any] | None) -> bool:
|
||
return _payload_wants_auto_chain_fallback(payload)
|
||
|
||
|
||
def _try_auto_chain_after_match(
|
||
task: ShippingTask,
|
||
match_result: dict[str, Any],
|
||
*,
|
||
payload: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""After fulfillable match: generate Excel and optionally trigger RPA upload (fallback chain)."""
|
||
if match_result.get("status") != "ok":
|
||
return match_result
|
||
if not _should_auto_chain_after_match(payload):
|
||
return match_result
|
||
|
||
result = match_result
|
||
tool_payload = _merge_tool_payload(task, payload)
|
||
|
||
if _auto_generate_excel_enabled():
|
||
db.session.refresh(task)
|
||
if not task.export_file_path and _match_completed(task):
|
||
gen = generate_excel(tool_payload)
|
||
if gen.get("status") != "ok":
|
||
return gen
|
||
result = _prepend_tool_message(gen, str(result.get("message") or ""))
|
||
|
||
if _auto_upload_enabled():
|
||
db.session.refresh(task)
|
||
if task.export_file_path and task.process_status != "uploaded":
|
||
up = upload_to_freight({**tool_payload, "mode": "auto"})
|
||
if up.get("status") == "failed":
|
||
return up
|
||
result = _prepend_tool_message(up, str(result.get("message") or ""))
|
||
if up.get("status") in {"running", "needs_human"}:
|
||
return {**up, "message": result.get("message", up.get("message", ""))}
|
||
|
||
return result
|
||
|
||
|
||
def _try_auto_chain_after_inventory_loaded(
|
||
task: ShippingTask,
|
||
*,
|
||
payload: dict[str, Any] | None = None,
|
||
) -> dict[str, Any] | None:
|
||
"""Auto: confirm mapping → match → Excel → RPA upload when allowed."""
|
||
if not _should_auto_chain_after_mapping(task, payload):
|
||
return None
|
||
auto_confirmed = _maybe_auto_confirm_inventory_mapping(task)
|
||
if auto_confirmed:
|
||
db.session.refresh(task)
|
||
if _awaiting_inventory_mapping_confirm(task):
|
||
return None
|
||
if not _auto_match_enabled() or _match_completed(task):
|
||
return None
|
||
match_result = match_inventory(_merge_tool_payload(task, payload))
|
||
if auto_confirmed:
|
||
match_result = _prepend_tool_message(match_result, "字段对齐已自动确认。")
|
||
return _try_auto_chain_after_match(task, match_result, payload=payload)
|
||
|
||
|
||
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,
|
||
chain_payload: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
task.inventory_lines_json = inventory_lines
|
||
field_alignment = _field_alignment_for_task(task, column_meta)
|
||
|
||
if require_mapping_review and _mapping_review_enabled():
|
||
apply_task_transition(task, TaskTransition.INVENTORY_ALIGN_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()
|
||
chained = _try_auto_chain_after_inventory_loaded(task, payload=chain_payload)
|
||
if chained is not None:
|
||
return chained
|
||
lang = None
|
||
if chain_payload:
|
||
lang = str(
|
||
chain_payload.get("lang")
|
||
or chain_payload.get("locale")
|
||
or chain_payload.get("language")
|
||
or ""
|
||
).strip() or None
|
||
return _inventory_mapping_checkpoint_response(
|
||
task,
|
||
column_meta=column_meta,
|
||
extra_data={
|
||
"inventory_row_count": len(inventory_lines),
|
||
"warnings": warnings or [],
|
||
},
|
||
lang=lang,
|
||
)
|
||
|
||
apply_task_transition(task, TaskTransition.INVENTORY_READY)
|
||
_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=task,
|
||
message=f"已载入库存 {len(inventory_lines)} 行,可进行匹配。",
|
||
data={
|
||
**_serialize_task_for_tool(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, *, for_tool: bool = False) -> dict[str, Any]:
|
||
data = {
|
||
"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,
|
||
}
|
||
if for_tool:
|
||
return strip_internal_task_fields(data)
|
||
return data
|
||
|
||
|
||
def _serialize_task_for_tool(task: ShippingTask) -> dict[str, Any]:
|
||
return _serialize_task(task, for_tool=True)
|
||
|
||
|
||
def create_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||
conv_id = str(payload.get("conversation_id") or "").strip()
|
||
hinted_task_no = _extract_task_no(
|
||
str(
|
||
payload.get("task_id")
|
||
or payload.get("task_no")
|
||
or payload.get("raw_content")
|
||
or payload.get("user_message")
|
||
or payload.get("query")
|
||
or payload.get("comment")
|
||
or ""
|
||
)
|
||
)
|
||
if hinted_task_no:
|
||
existing_by_no = _get_task(hinted_task_no)
|
||
if existing_by_no:
|
||
if conv_id and not existing_by_no.conversation_id:
|
||
existing_by_no.conversation_id = conv_id
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="ok",
|
||
task_id=existing_by_no.task_no,
|
||
message=f"已找到发货任务 {existing_by_no.task_no},将继续处理该任务。",
|
||
data=_serialize_task(existing_by_no),
|
||
checkpoint=CP_TASK_EXISTS,
|
||
)
|
||
if conv_id:
|
||
terminal_statuses = {"uploaded", "rejected", "closed"}
|
||
existing = (
|
||
ShippingTask.query.filter_by(conversation_id=conv_id)
|
||
.filter(ShippingTask.process_status.notin_(list(terminal_statuses)))
|
||
.order_by(ShippingTask.id.desc())
|
||
.first()
|
||
)
|
||
if existing:
|
||
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=CP_TASK_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_for_tool(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()
|
||
explicit_task_ref = bool(str(payload.get("task_id") or payload.get("task_no") or "").strip())
|
||
new_notice_payload = bool(
|
||
str(payload.get("raw_text") or "").strip()
|
||
or (isinstance(payload.get("structured"), dict) and payload.get("structured"))
|
||
or (isinstance(payload.get("notice_files"), list) and payload.get("notice_files"))
|
||
)
|
||
if (
|
||
(not explicit_task_ref)
|
||
and conv_id
|
||
and new_notice_payload
|
||
and str(task.process_status or "").strip().lower() in {"uploaded", "rejected", "closed"}
|
||
):
|
||
new_task = ShippingTask(
|
||
task_no=_generate_task_no(),
|
||
user_id=payload.get("user_id"),
|
||
conversation_id=conv_id or None,
|
||
source_type=str(payload.get("source_type") or task.source_type or "manual"),
|
||
raw_content=None,
|
||
process_status="created",
|
||
)
|
||
db.session.add(new_task)
|
||
_log_event(
|
||
new_task,
|
||
"task_created",
|
||
{"source_type": new_task.source_type, "created_from": task.task_no},
|
||
)
|
||
db.session.commit()
|
||
task = new_task
|
||
|
||
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
|
||
|
||
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):
|
||
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
|
||
_log_event(task, "parse_needs_review", {"confidence": confidence, "warnings": warnings})
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="needs_human",
|
||
task=task,
|
||
message=format_parse_summary(**summary_kwargs, low_confidence=True, payload=payload),
|
||
data={**_serialize_task_for_tool(task), "warnings": warnings},
|
||
)
|
||
|
||
apply_task_transition(task, TaskTransition.PARSED)
|
||
_log_event(task, "parsed", {"confidence": confidence, "warnings": warnings})
|
||
db.session.commit()
|
||
auto_threshold = float(current_app.config.get("SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE") or 0.8)
|
||
should_auto_continue = confidence >= auto_threshold and not task.inventory_lines_json
|
||
summary_text = format_parse_summary(
|
||
**summary_kwargs,
|
||
payload=payload,
|
||
include_confirmation_hint=not should_auto_continue,
|
||
)
|
||
|
||
if should_auto_continue:
|
||
lang = payload.get("lang") if isinstance(payload, dict) else None
|
||
auto_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"}
|
||
if lang:
|
||
auto_payload["lang"] = lang
|
||
auto_result = auto_progress(auto_payload) if _auto_progress_enabled() else ensure_inventory(auto_payload)
|
||
msg = str(auto_result.get("message") or "").strip()
|
||
merged_message = summary_text if not msg else f"{summary_text}\n\n{msg}"
|
||
merged_data = {}
|
||
if isinstance(auto_result.get("data"), dict):
|
||
merged_data.update(auto_result["data"])
|
||
merged_data["warnings"] = warnings
|
||
db.session.refresh(task)
|
||
return tool_response(
|
||
status=str(auto_result.get("status") or "ok"),
|
||
task=task,
|
||
message=merged_message,
|
||
data=merged_data,
|
||
next_required_action=auto_result.get("next_required_action"),
|
||
forbidden_next_tools=auto_result.get("forbidden_next_tools"),
|
||
)
|
||
|
||
return tool_response(
|
||
status="ok",
|
||
task_id=task.task_no,
|
||
message=summary_text,
|
||
data={**_serialize_task_for_tool(task), "warnings": warnings},
|
||
)
|
||
|
||
|
||
def _resolve_inventory_field_mapping(payload: dict[str, Any]) -> tuple[dict[str, str] | None, str]:
|
||
raw = payload_map_json(payload)
|
||
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_map_json(payload))
|
||
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=task,
|
||
message="未找到已上传的库存文件。请先 POST /tools/upload_inventory_file 上传 Excel。",
|
||
data=_serialize_task_for_tool(task),
|
||
checkpoint=CP_UPLOAD_REQ,
|
||
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=task,
|
||
message=(
|
||
f"库存文本过大({len(raw_text)} 字符,上限 {max_chars})。"
|
||
"请勿将 Excel 全文传入 LLM;请用 HTTP 节点调用 "
|
||
"POST /tools/upload_inventory_file 上传,再 "
|
||
"parse_inventory(use_uploaded_file=true)。"
|
||
),
|
||
data=_serialize_task_for_tool(task),
|
||
checkpoint=CP_UPLOAD_REQ,
|
||
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=task,
|
||
message="未能解析库存明细。大 Excel 请 upload_inventory_file;小表可粘贴;无库存可走 RPA。",
|
||
data={**_serialize_task_for_tool(task), "warnings": warnings},
|
||
checkpoint=CP_MAP_INFER,
|
||
)
|
||
|
||
return _inventory_loaded_response(
|
||
task,
|
||
inventory_lines,
|
||
warnings=warnings,
|
||
column_meta=column_meta,
|
||
source=source,
|
||
require_mapping_review=True,
|
||
event_type="inventory_parsed",
|
||
chain_payload=payload,
|
||
)
|
||
|
||
|
||
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=task,
|
||
message="未找到已上传的库存文件。请先 POST /tools/upload_inventory_file 上传 Excel。",
|
||
data=_serialize_task_for_tool(task),
|
||
checkpoint=CP_UPLOAD_REQ,
|
||
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=task,
|
||
message=(
|
||
"已读取库存表头与样例行。请根据 schema_preview 推断列映射,"
|
||
"调用 apply_inventory_mapping(map_json=...)。"
|
||
),
|
||
data={**_serialize_task_for_tool(task), "schema_preview": preview},
|
||
checkpoint=CP_MAP_INFER,
|
||
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=task,
|
||
message="未找到已上传的库存文件。请先 upload_inventory_file。",
|
||
data=_serialize_task_for_tool(task),
|
||
checkpoint=CP_UPLOAD_REQ,
|
||
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_map_json(payload)
|
||
|
||
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=(
|
||
"map_json 无效或不完整。"
|
||
'需要提供 {"sku":"列名","reservation_id":"列名","available_qty":"列名"}。'
|
||
"(库存的 Reservation ID 列允许为空值,但必须有该列标题)"
|
||
),
|
||
data={
|
||
**_serialize_task_for_tool(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_for_tool(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",
|
||
chain_payload=payload,
|
||
)
|
||
|
||
|
||
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
|
||
|
||
suggested = preview.get("suggested_mapping") if isinstance(preview.get("suggested_mapping"), dict) else {}
|
||
suggested_clean = {k: str(v).strip() for k, v in suggested.items() if str(v).strip()}
|
||
suggested_complete = mapping_is_complete(suggested_clean)
|
||
auto_map = (
|
||
json.dumps(suggested_clean, ensure_ascii=False) if suggested_complete else None
|
||
)
|
||
|
||
apply_task_transition(task, TaskTransition.MAP_INFER)
|
||
_log_event(task, "inventory_file_uploaded", {"filename": filename, "headers": preview.get("headers")})
|
||
db.session.commit()
|
||
upload_message = "库存文件已上传。"
|
||
if suggested_complete:
|
||
upload_message += " suggested_mapping 已完整,画布可直通 apply_inventory_mapping(无需 LLM)。"
|
||
else:
|
||
upload_message += " 请由画布 LLM 推断列映射后 apply_inventory_mapping。"
|
||
return tool_response(
|
||
status="ok",
|
||
task=task,
|
||
message=upload_message,
|
||
data={
|
||
**_serialize_task_for_tool(task),
|
||
"schema_preview": preview,
|
||
SUGGEST_OK: suggested_complete,
|
||
AUTO_MAP: auto_map,
|
||
},
|
||
next_required_action="apply_inventory_mapping(map_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":
|
||
timeout_seconds = _rpa_inventory_timeout_seconds()
|
||
if (
|
||
task.pending_human_reason == PH_RPA_PENDING
|
||
and task.process_status == "waiting_inventory"
|
||
and not task.inventory_lines_json
|
||
):
|
||
last_trigger = _latest_event(task, "inventory_rpa_triggered")
|
||
if last_trigger and isinstance(last_trigger.created_at, datetime):
|
||
elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds())
|
||
if elapsed < timeout_seconds:
|
||
max_attempts = max_rpa_inventory_attempts()
|
||
attempts = inventory_rpa_attempts(task)
|
||
remaining = max(timeout_seconds - elapsed, 1)
|
||
return tool_response(
|
||
status="running",
|
||
task_id=task.task_no,
|
||
message=(
|
||
f"RPA 库存导出进行中(第 {max(attempts, 1)}/{max_attempts} 次)。"
|
||
f"已等待 {elapsed}s / 超时 {timeout_seconds}s。"
|
||
f"请稍后再试(建议 {remaining}s 后)。"
|
||
),
|
||
data={
|
||
**_serialize_task_for_tool(task),
|
||
"rpa": {
|
||
"attempts": max(attempts, 1),
|
||
"max_attempts": max_attempts,
|
||
"elapsed_seconds": elapsed,
|
||
"timeout_seconds": timeout_seconds,
|
||
"retry_after_seconds": remaining,
|
||
},
|
||
},
|
||
)
|
||
last_failed = _latest_event(task, "inventory_rpa_failed")
|
||
if not last_failed or (last_failed.created_at < last_trigger.created_at):
|
||
task.error_message = f"RPA 库存导出超时(>{timeout_seconds}s)"
|
||
_log_event(
|
||
task,
|
||
"inventory_rpa_failed",
|
||
{
|
||
"error": "timeout",
|
||
"elapsed_seconds": elapsed,
|
||
"timeout_seconds": timeout_seconds,
|
||
},
|
||
)
|
||
db.session.flush()
|
||
|
||
attempts = inventory_rpa_attempts(task)
|
||
max_attempts = max_rpa_inventory_attempts()
|
||
if attempts >= max_attempts and not task.inventory_lines_json:
|
||
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
|
||
task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
|
||
_log_event(task, "inventory_rpa_exhausted", {"attempts": attempts})
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="needs_human",
|
||
task=task,
|
||
message=f"已尝试 {attempts} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。",
|
||
data=_serialize_task_for_tool(task),
|
||
)
|
||
|
||
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]
|
||
|
||
attempt_no = attempts + 1
|
||
trigger = write_inventory_export_trigger(task.task_no, {"mode": mode, "attempt": attempt_no})
|
||
if trigger:
|
||
apply_task_transition(task, TaskTransition.RPA_PENDING)
|
||
_log_event(task, "inventory_rpa_triggered", {"trigger": trigger, "attempt": attempt_no})
|
||
|
||
if attempt_no >= max_attempts and not task.inventory_lines_json:
|
||
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
|
||
task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
|
||
_log_event(task, "inventory_rpa_exhausted", {"attempts": attempt_no})
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="needs_human",
|
||
task=task,
|
||
message=f"已尝试 {attempt_no} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。",
|
||
data=_serialize_task_for_tool(task),
|
||
)
|
||
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="running",
|
||
task_id=task.task_no,
|
||
message=(
|
||
f"已触发 RPA 库存导出(第 {attempt_no}/{max_attempts} 次)。"
|
||
f"若 {timeout_seconds}s 内无回调/无落盘文件,可继续重试;超过最大次数将转人工上传。"
|
||
),
|
||
data={
|
||
**_serialize_task_for_tool(task),
|
||
"rpa": {
|
||
"attempts": attempt_no,
|
||
"max_attempts": max_attempts,
|
||
"timeout_seconds": timeout_seconds,
|
||
},
|
||
},
|
||
)
|
||
|
||
_log_event(task, "inventory_rpa_retry_requested", {})
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="needs_human",
|
||
task=task,
|
||
message="RPA 库存目录未配置或触发失败。请上传货代库存 Excel。",
|
||
data=_serialize_task_for_tool(task),
|
||
checkpoint=CP_UPLOAD_REQ,
|
||
)
|
||
|
||
if task.inventory_lines_json:
|
||
if _awaiting_inventory_mapping_confirm(task):
|
||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||
return _inventory_mapping_checkpoint_response(task, lang=lang or None)
|
||
apply_task_transition(task, TaskTransition.INVENTORY_READY)
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="ok",
|
||
task_id=task.task_no,
|
||
message="已有库存快照且字段对齐已确认,可调用 match_inventory。",
|
||
data=_serialize_task_for_tool(task),
|
||
)
|
||
|
||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||
_log_event(task, "inventory_missing", {})
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="needs_human",
|
||
task=task,
|
||
message="暂无可用库存数据。请重试 RPA 自动导出,或手动上传货代库存 Excel。",
|
||
data=_serialize_task_for_tool(task),
|
||
)
|
||
|
||
|
||
def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||
if not _auto_progress_enabled():
|
||
return tool_response(status="failed", message="auto_progress 未启用")
|
||
|
||
task = _resolve_task_from_payload(payload)
|
||
if not task:
|
||
return tool_response(status="failed", message="未找到任务编号")
|
||
|
||
steps: list[str] = []
|
||
|
||
threshold = current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD")
|
||
try:
|
||
threshold = float(threshold) if threshold is not None else 0.7
|
||
except (TypeError, ValueError):
|
||
threshold = 0.7
|
||
confidence = None
|
||
try:
|
||
confidence = float(task.parse_confidence) if task.parse_confidence is not None else None
|
||
except (TypeError, ValueError):
|
||
confidence = None
|
||
|
||
if task.review_status == RS_PARSE_REVIEW or task.pending_human_reason == PH_LOW_CONF:
|
||
ui = resolve_task_ui_state(task)
|
||
return tool_response(
|
||
status="needs_human",
|
||
task=task,
|
||
message="发货通知解析需要人工确认后才能自动推进。",
|
||
data=_serialize_task_for_tool(task),
|
||
human_options=ui.human_options,
|
||
checkpoint=ui.checkpoint,
|
||
stop_agent_turn=True,
|
||
)
|
||
if confidence is not None and confidence < threshold:
|
||
ui = resolve_task_ui_state(task)
|
||
return tool_response(
|
||
status="needs_human",
|
||
task=task,
|
||
message=f"解析置信度 {confidence:.2f} 低于阈值 {threshold:.2f},请人工确认后再自动推进。",
|
||
data=_serialize_task_for_tool(task),
|
||
human_options=ui.human_options,
|
||
checkpoint=ui.checkpoint,
|
||
stop_agent_turn=True,
|
||
)
|
||
|
||
if not task.inventory_lines_json:
|
||
if not _auto_rpa_inventory_enabled():
|
||
return tool_response(
|
||
status="needs_human",
|
||
task=task,
|
||
message="未开启自动 RPA 获取库存。请手动上传货代库存 Excel。",
|
||
data=_serialize_task_for_tool(task),
|
||
checkpoint=CP_UPLOAD_REQ,
|
||
stop_agent_turn=True,
|
||
)
|
||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||
inv_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"}
|
||
if lang:
|
||
inv_payload["lang"] = lang
|
||
inv = ensure_inventory(inv_payload)
|
||
if inv.get("status") == "running":
|
||
steps.append("触发 RPA 库存导出")
|
||
return inv
|
||
if inv.get("status") != "ok":
|
||
if _maybe_auto_confirm_inventory_mapping(task):
|
||
steps.append("自动确认字段对齐")
|
||
else:
|
||
return inv
|
||
else:
|
||
steps.append("载入库存")
|
||
|
||
if _maybe_auto_confirm_inventory_mapping(task):
|
||
steps.append("自动确认字段对齐")
|
||
|
||
if _awaiting_inventory_mapping_confirm(task):
|
||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||
return _inventory_mapping_checkpoint_response(task, lang=lang or None)
|
||
|
||
if _auto_match_enabled() and not _match_completed(task):
|
||
matched = match_inventory({"task_id": task.task_no})
|
||
if matched.get("status") != "ok":
|
||
return matched
|
||
steps.append("库存匹配")
|
||
|
||
if _auto_generate_excel_enabled() and _match_completed(task) and not task.export_file_path:
|
||
gen = generate_excel({"task_id": task.task_no})
|
||
if gen.get("status") != "ok":
|
||
return gen
|
||
steps.append("生成发货 Excel")
|
||
|
||
if _auto_upload_enabled() and task.export_file_path and task.process_status != "uploaded":
|
||
up = upload_to_freight({"task_id": task.task_no, "mode": "auto"})
|
||
if up.get("status") == "running":
|
||
steps.append("触发 RPA 上传")
|
||
return up
|
||
|
||
suffix = f":{' → '.join(steps)}" if steps else ""
|
||
return tool_response(
|
||
status="ok",
|
||
task=task,
|
||
message=f"自动推进已完成{suffix}",
|
||
data=_serialize_task_for_tool(task),
|
||
)
|
||
|
||
|
||
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):
|
||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||
return _inventory_mapping_checkpoint_response(task, lang=lang or None)
|
||
|
||
inventory_lines = _parse_inventory_lines(payload)
|
||
if inventory_lines:
|
||
task.inventory_lines_json = inventory_lines
|
||
elif not task.inventory_lines_json:
|
||
inv_payload: dict[str, Any] = {"task_id": task.task_no}
|
||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||
if lang:
|
||
inv_payload["lang"] = lang
|
||
return ensure_inventory(inv_payload)
|
||
|
||
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:
|
||
apply_task_transition(task, TaskTransition.RSV_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=task,
|
||
message=(
|
||
"当前匹配规则要求发货需求(订单)必须提供 Reservation ID。"
|
||
f"订单缺少 Reservation ID:{len(order_missing)} 行。"
|
||
"请重新解析发货通知后再匹配。"
|
||
),
|
||
data={**_serialize_task_for_tool(task), "reservation_id_required": detail},
|
||
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 and isinstance(shortage, dict):
|
||
shortage.pop("warnings", None)
|
||
task.match_status = match_status
|
||
task.line_results_json = line_results
|
||
task.shortage_json = shortage
|
||
|
||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() or None
|
||
match_summary = format_match_summary(
|
||
match_status,
|
||
line_results,
|
||
task_no=task.task_no,
|
||
lang=lang,
|
||
)
|
||
|
||
if match_status == "fulfillable":
|
||
apply_task_transition(task, TaskTransition.MATCHED_FULFILLABLE)
|
||
_log_event(task, "matched_fulfillable", {"match_status": match_status})
|
||
db.session.commit()
|
||
match_result = tool_response(
|
||
status="ok",
|
||
task_id=task.task_no,
|
||
message=match_summary,
|
||
data=_serialize_task_for_tool(task),
|
||
)
|
||
return _try_auto_chain_after_match(task, match_result, payload=payload)
|
||
|
||
apply_task_transition(task, TaskTransition.MATCH_SHORTAGE)
|
||
_log_event(task, "match_needs_review", {"match_status": match_status, "shortage": shortage})
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="needs_human",
|
||
task=task,
|
||
message=match_summary,
|
||
data=_serialize_task_for_tool(task),
|
||
)
|
||
|
||
|
||
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":
|
||
apply_task_transition(task, TaskTransition.REJECTED)
|
||
_log_event(task, "decision_rejected", {"comment": comment})
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="ok",
|
||
task_id=task.task_no,
|
||
message="已驳回该发货任务。",
|
||
data=_serialize_task_for_tool(task),
|
||
)
|
||
|
||
if decision in {"close", "closed"}:
|
||
apply_task_transition(task, TaskTransition.CLOSED)
|
||
_log_event(task, "decision_closed", {"comment": comment})
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="ok",
|
||
task_id=task.task_no,
|
||
message="已关闭该发货任务(可在同一会话重新开新单)。",
|
||
data=_serialize_task_for_tool(task),
|
||
)
|
||
|
||
if decision in {"confirm", "confirmed", "confirm_parse"}:
|
||
if task.review_status == RS_SHORTAGE_REVIEW or task.pending_human_reason == PH_SHORTAGE:
|
||
apply_task_transition(task, TaskTransition.CONFIRM_SHORTAGE)
|
||
_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_for_tool(task),
|
||
)
|
||
|
||
if (
|
||
decision == "confirm_parse"
|
||
or task.review_status == RS_PARSE_REVIEW
|
||
or task.pending_human_reason == PH_LOW_CONF
|
||
or (
|
||
task.process_status in {"parsed", "pending_review", "created"}
|
||
and not _match_completed(task)
|
||
)
|
||
):
|
||
apply_task_transition(task, TaskTransition.CONFIRM_PARSE)
|
||
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)):
|
||
next_payload = _merge_tool_payload(task, payload, extra={"mode": "auto"})
|
||
if _payload_wants_auto_chain_fallback(payload):
|
||
return auto_progress(next_payload)
|
||
return ensure_inventory(next_payload)
|
||
return tool_response(
|
||
status="ok",
|
||
task=task,
|
||
message=(
|
||
"发货通知已确认。"
|
||
"请先处理库存(ensure_inventory / parse_inventory → confirm_inventory_mapping → match_inventory)。"
|
||
"禁止跳过匹配直接 generate_shipment_excel。"
|
||
),
|
||
data=_serialize_task_for_tool(task),
|
||
checkpoint=CP_PARSE_OK,
|
||
next_required_action="ensure_inventory 或 parse_inventory",
|
||
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
|
||
)
|
||
|
||
if _match_completed(task):
|
||
apply_task_transition(task, TaskTransition.CONFIRM_MATCHED)
|
||
_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_for_tool(task),
|
||
)
|
||
|
||
if task.process_status == "waiting_inventory" or (
|
||
task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json
|
||
):
|
||
follow_payload = _merge_tool_payload(task, payload, extra={"mode": "auto"})
|
||
if _payload_wants_auto_chain_fallback(payload):
|
||
return auto_progress(follow_payload)
|
||
return ensure_inventory(follow_payload)
|
||
|
||
if _awaiting_inventory_mapping_confirm(task):
|
||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||
return _inventory_mapping_checkpoint_response(task, lang=lang or None)
|
||
|
||
if task.inventory_lines_json or task.process_status == "inventory_ready":
|
||
follow_payload = _merge_tool_payload(task, payload)
|
||
if _payload_wants_auto_chain_fallback(payload):
|
||
return auto_progress(follow_payload)
|
||
return tool_response(
|
||
status="ok",
|
||
task=task,
|
||
message="发货通知已确认,当前任务已进入库存处理阶段,请按当前按钮继续。",
|
||
data=_serialize_task_for_tool(task),
|
||
)
|
||
|
||
return tool_response(
|
||
status="failed",
|
||
task_id=task.task_no,
|
||
message="当前状态无法使用 confirm。请先完成库存匹配,或使用 confirm_inventory_mapping / reparse。",
|
||
data=_serialize_task_for_tool(task),
|
||
)
|
||
|
||
if decision == "rematch":
|
||
_log_event(task, "decision_rematch", {"comment": comment})
|
||
db.session.commit()
|
||
rematch_payload = _merge_tool_payload(task, payload)
|
||
return match_inventory(rematch_payload)
|
||
|
||
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_for_tool(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():
|
||
apply_task_transition(task, TaskTransition.ALIGN_REVIEW_HOLD)
|
||
db.session.commit()
|
||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||
return _inventory_mapping_checkpoint_response(
|
||
task,
|
||
column_meta=meta,
|
||
extra_data={
|
||
"warnings": [
|
||
"库存表必须包含 Reservation ID 列标题(该列允许为空值)。"
|
||
"请改用「更正映射」重新选择 Reservation ID 对应的列,或重新上传包含该列的库存 Excel。"
|
||
],
|
||
},
|
||
lang=lang or None,
|
||
)
|
||
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()},
|
||
)
|
||
apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED)
|
||
_log_event(task, "inventory_mapping_confirmed", {"comment": comment})
|
||
db.session.commit()
|
||
next_payload = _merge_tool_payload(task, payload)
|
||
return match_inventory(next_payload)
|
||
|
||
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_for_tool(task),
|
||
)
|
||
task.inventory_lines_json = None
|
||
apply_task_transition(task, TaskTransition.CORRECT_MAPPING)
|
||
_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_for_tool(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="needs_human",
|
||
task=task,
|
||
message=(
|
||
"已回到列映射步骤。请根据 schema_preview 提供新的 map_json,"
|
||
"再调用 apply_inventory_mapping。"
|
||
),
|
||
data={**_serialize_task_for_tool(task), "schema_preview": preview},
|
||
checkpoint=CP_MAP_INFER,
|
||
next_required_action="apply_inventory_mapping(map_json=...)",
|
||
forbidden_next_tools=["match_inventory"],
|
||
stop_agent_turn=True,
|
||
)
|
||
|
||
if decision == "reparse_inventory":
|
||
task.inventory_lines_json = None
|
||
if task.process_status == "inventory_ready":
|
||
apply_task_transition(task, TaskTransition.REPARSE_INVENTORY_DEMOTE)
|
||
else:
|
||
apply_task_transition(task, TaskTransition.REPARSE_INVENTORY)
|
||
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_for_tool(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_for_tool(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
|
||
apply_task_transition(task, TaskTransition.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_for_tool(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":
|
||
if task.process_status == "uploaded":
|
||
return tool_response(
|
||
status="ok",
|
||
task=task,
|
||
task_id=task.task_no,
|
||
message=f"任务 {task.task_no} 已标记为完成,无需重复操作。",
|
||
data=_serialize_task_for_tool(task),
|
||
checkpoint=CP_UPLOADED,
|
||
human_options=[],
|
||
)
|
||
apply_task_transition(task, TaskTransition.UPLOADED)
|
||
ref = str(payload.get("freight_ref_no") or "").strip()
|
||
if ref:
|
||
task.freight_ref_no = ref
|
||
_log_event(task, "upload_manual_confirmed", {"freight_ref_no": ref or None})
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="ok",
|
||
task=task,
|
||
task_id=task.task_no,
|
||
message=(
|
||
f"已标记为手工上传货代系统完成。任务 {task.task_no} 已全部处理完毕,"
|
||
"无需再进行任何操作。"
|
||
),
|
||
data=_serialize_task_for_tool(task),
|
||
checkpoint=CP_UPLOADED,
|
||
human_options=[],
|
||
)
|
||
|
||
if mode == "retry_upload" or mode == "auto":
|
||
timeout_seconds = _rpa_upload_timeout_seconds()
|
||
max_attempts = max_rpa_upload_attempts()
|
||
if (
|
||
task.pending_human_reason == PH_UPLOAD_RPA_PENDING
|
||
and task.process_status == "waiting_upload"
|
||
and task.export_file_path
|
||
and task.process_status != "uploaded"
|
||
):
|
||
last_trigger = _latest_event(task, "upload_rpa_triggered")
|
||
if last_trigger and isinstance(last_trigger.created_at, datetime):
|
||
elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds())
|
||
if elapsed < timeout_seconds:
|
||
attempts = upload_rpa_attempts(task)
|
||
remaining = max(timeout_seconds - elapsed, 1)
|
||
return tool_response(
|
||
status="running",
|
||
task_id=task.task_no,
|
||
message=(
|
||
f"RPA 上传进行中(第 {max(attempts, 1)}/{max_attempts} 次)。"
|
||
f"已等待 {elapsed}s / 超时 {timeout_seconds}s。"
|
||
f"请稍后再试(建议 {remaining}s 后)。"
|
||
),
|
||
data={
|
||
**_serialize_task_for_tool(task),
|
||
"rpa": {
|
||
"attempts": max(attempts, 1),
|
||
"max_attempts": max_attempts,
|
||
"elapsed_seconds": elapsed,
|
||
"timeout_seconds": timeout_seconds,
|
||
"retry_after_seconds": remaining,
|
||
},
|
||
},
|
||
)
|
||
last_failed = _latest_event(task, "upload_rpa_failed")
|
||
if not last_failed or (last_failed.created_at < last_trigger.created_at):
|
||
task.error_message = f"RPA 上传超时(>{timeout_seconds}s)"
|
||
_log_event(
|
||
task,
|
||
"upload_rpa_failed",
|
||
{"error": "timeout", "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
|
||
)
|
||
db.session.flush()
|
||
|
||
attempts = upload_rpa_attempts(task)
|
||
if attempts >= max_attempts:
|
||
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
|
||
task.error_message = f"已尝试 {attempts} 次仍无法通过 RPA 上传,请下载 Excel 手工上传。"
|
||
_log_event(task, "upload_rpa_exhausted", {"attempts": attempts, "max_attempts": max_attempts})
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="needs_human",
|
||
task=task,
|
||
message=task.error_message,
|
||
data=_serialize_task_for_tool(task),
|
||
)
|
||
|
||
queued, trigger = write_upload_trigger(task.task_no, task.export_file_path or "")
|
||
if queued and trigger:
|
||
apply_task_transition(task, TaskTransition.UPLOAD_RPA_PENDING)
|
||
attempt_no = attempts + 1
|
||
_log_event(
|
||
task,
|
||
"upload_rpa_triggered",
|
||
{
|
||
"queue_file": queued,
|
||
"trigger": trigger,
|
||
"attempt": attempt_no,
|
||
"timeout_seconds": timeout_seconds,
|
||
"max_attempts": max_attempts,
|
||
},
|
||
)
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="running",
|
||
task_id=task.task_no,
|
||
message=(
|
||
f"已触发 RPA 上传货代(第 {attempt_no}/{max_attempts} 次)。"
|
||
f"若 {timeout_seconds}s 内无回调,可重试;超过最大次数将转手工上传。"
|
||
),
|
||
data={
|
||
**_serialize_task_for_tool(task),
|
||
"queue_file": queued,
|
||
"rpa": {"attempts": attempt_no, "max_attempts": max_attempts, "timeout_seconds": timeout_seconds},
|
||
},
|
||
)
|
||
|
||
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
|
||
task.error_message = "RPA 上传目录未配置或触发失败"
|
||
_log_event(task, "upload_rpa_pending", {})
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="needs_human",
|
||
task=task,
|
||
message="RPA 自动上传失败或未配置。请下载 Excel 在货代系统手工上传,完成后告知我。",
|
||
data=_serialize_task_for_tool(task),
|
||
)
|
||
|
||
|
||
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=task,
|
||
message=f"当前进度:{user_facing_task_stage(task)}",
|
||
data=_serialize_task_for_tool(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:
|
||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||
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.flush()
|
||
attempts = inventory_rpa_attempts(task)
|
||
if attempts >= max_rpa_inventory_attempts():
|
||
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
|
||
task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
|
||
_log_event(task, "inventory_rpa_exhausted", {"attempts": attempts})
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="needs_human",
|
||
task=task,
|
||
message=f"已尝试 {attempts} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。",
|
||
data=_serialize_task_for_tool(task),
|
||
)
|
||
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="needs_human",
|
||
task=task,
|
||
message=task.error_message,
|
||
data=_serialize_task_for_tool(task),
|
||
)
|
||
|
||
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:
|
||
apply_task_transition(task, TaskTransition.UPLOADED)
|
||
task.freight_ref_no = str(payload.get("freight_ref_no") or "").strip() or None
|
||
_log_event(task, "upload_rpa_success", {"freight_ref_no": task.freight_ref_no})
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="ok",
|
||
task=task,
|
||
task_id=task.task_no,
|
||
message="RPA 已成功上传货代系统,任务已全部处理完毕。",
|
||
data=_serialize_task_for_tool(task),
|
||
checkpoint=CP_UPLOADED,
|
||
human_options=[],
|
||
)
|
||
|
||
apply_task_transition(task, TaskTransition.UPLOAD_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.flush()
|
||
attempts = upload_rpa_attempts(task)
|
||
max_attempts = max_rpa_upload_attempts()
|
||
if attempts >= max_attempts:
|
||
task.error_message = f"已尝试 {attempts} 次仍无法通过 RPA 上传,请下载 Excel 手工上传。"
|
||
_log_event(task, "upload_rpa_exhausted", {"attempts": attempts, "max_attempts": max_attempts})
|
||
db.session.commit()
|
||
return tool_response(
|
||
status="needs_human",
|
||
task=task,
|
||
message=task.error_message,
|
||
data=_serialize_task_for_tool(task),
|
||
)
|