feat(shipping): 新增货代发货批量自动处理与任务重试功能
本次提交完整实现货代发货通知的自动化批量处理能力: 1. 新增发货单票后台任务类型与专用worker队列,实现任务持久化调度 2. 实现发货批次后台编排器,支持上传后自动逐票推进解析、匹配、导出全流程 3. 新增单票重试、批次待处理重试的API与前端操作界面 4. 补充全量多语言翻译,新增重试、任务列表、状态展示相关文案 5. 优化上传交互逻辑,改为后台自动处理任务,无需手动触发解析指令 6. 修复文件检核工具无数据预检逻辑,避免创建空检核批次 7. 调整发货工作流细节,优化Excel生成幂等性与任务状态同步 8. 更新环境配置与API文档,修正货代工具接口地址端口
This commit is contained in:
1 parent
70e8f700ff
commit
08360a4142
40 files changed
+2515
-371
No files matched your search
@@ -59,4 +59,4 @@ MINIO_SECURE=false
|
||||
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
|
||||
|
||||
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8891
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
|
||||
@@ -1222,6 +1222,9 @@ def chat_completions():
|
||||
external_conversation_id or session.session_id,
|
||||
task_id=shipping_task_id,
|
||||
batch_no=shipping_batch_no,
|
||||
entry_mode="user_chat",
|
||||
user_message=query,
|
||||
trigger_source="frontend_chat",
|
||||
)
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
|
||||
@@ -21,8 +21,11 @@ from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailabl
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
from app.services.schedule import _build_srm_conn_str
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
from app.services.schedule.srm_service import _fetch_records
|
||||
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
|
||||
file_check_bp = Blueprint("file_check_tools", __name__)
|
||||
|
||||
@@ -266,6 +269,44 @@ def _record_run_bind(run: ScheduleRun, data: dict) -> None:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
def _build_no_data_response(task: ScheduleTask) -> dict:
|
||||
"""无待检资料时直接返回提示,不创建批次也不绑定 run_id。"""
|
||||
return {
|
||||
"ok": False,
|
||||
"error_code": "no_data_to_check",
|
||||
"message": "目前没有资料需要检核",
|
||||
"task": {
|
||||
"task_id": task.id,
|
||||
"task_name": task.name,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
"""
|
||||
启动前预检当前任务是否存在待检资料。
|
||||
|
||||
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则直接返回 no_data_to_check,
|
||||
避免创建空批次并向 ChatLog 回写 run_id。
|
||||
"""
|
||||
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
|
||||
return None
|
||||
|
||||
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||
if not cfg or not str(cfg.fetch_sql or "").strip():
|
||||
return None
|
||||
|
||||
if cfg.data_source and not cfg.data_source.is_empty():
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
|
||||
rows = _fetch_records(conn_str, cfg.fetch_sql)
|
||||
if rows:
|
||||
return None
|
||||
return _build_no_data_response(task)
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
def run_file_check():
|
||||
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
|
||||
@@ -301,6 +342,19 @@ def run_file_check():
|
||||
"run": _serialize_tool_run(existing),
|
||||
})
|
||||
|
||||
no_data_response = _precheck_no_data(task)
|
||||
if no_data_response:
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=no_data resolve_ms=%s lock_ms=%s total_ms=%s task_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
task.id,
|
||||
)
|
||||
return jsonify(no_data_response)
|
||||
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
|
||||
@@ -65,7 +65,7 @@ def workspace_shipping_batches():
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/create-from-notices", methods=["POST"])
|
||||
def workspace_create_shipping_batch_from_notices():
|
||||
"""接收多份发货通知附件,创建批次并为每份附件生成任务。"""
|
||||
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
@@ -121,8 +121,8 @@ def workspace_create_shipping_batch_from_notices():
|
||||
"conversation_id": conversation_id or None,
|
||||
"file_count": len(notice_items),
|
||||
"notice_items": notice_items,
|
||||
# 用户态上传通知后仅完成抽文、建批/建任务与 raw_text 落库;
|
||||
# 首轮订单需求解析由 Dify 画布读取 raw_text 后调用 parse_notice(structured=...)。
|
||||
# 上传接口先快速完成建批/建任务与 raw_text 落库,避免请求阻塞;
|
||||
# 后续首轮解析与可自动推进步骤交给后台编排线程逐票执行。
|
||||
"defer_parse": True,
|
||||
}
|
||||
created = shipping_tools.create_batch_tasks(payload)
|
||||
@@ -130,12 +130,26 @@ def workspace_create_shipping_batch_from_notices():
|
||||
batch_data = data.get("batch") if isinstance(data, dict) else None
|
||||
tasks_data = data.get("tasks") if isinstance(data, dict) else None
|
||||
batch_no = str(created.get("batch_no") or (batch_data or {}).get("batch_no") or "").strip()
|
||||
orchestrator_started = False
|
||||
if batch_no:
|
||||
from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator
|
||||
|
||||
orchestrator_started = start_batch_orchestrator(batch_no)
|
||||
if isinstance(data, dict) and batch_no:
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
if focus_task:
|
||||
data["focus_task"] = serialize_task_summary(focus_task)
|
||||
if isinstance(tasks_data, list):
|
||||
data["tasks"] = tasks_data
|
||||
data["orchestrator_started"] = orchestrator_started
|
||||
if isinstance(created, dict):
|
||||
base_message = str(created.get("message") or "").strip()
|
||||
if orchestrator_started:
|
||||
created["message"] = (
|
||||
f"{base_message},后台已开始逐票处理。"
|
||||
if base_message
|
||||
else "后台已开始逐票处理。"
|
||||
)
|
||||
return jsonify(created)
|
||||
|
||||
|
||||
@@ -236,7 +250,7 @@ def workspace_create_shipping_task():
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/create-from-notice", methods=["POST"])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,解析延后到 Dify。"""
|
||||
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
@@ -297,15 +311,23 @@ def workspace_create_shipping_task_from_notice():
|
||||
task.source_file_type = str(getattr(upload, "mimetype", "") or "").strip() or task.source_file_type
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||
|
||||
orchestrator_started = start_task_orchestrator(task_id)
|
||||
return jsonify(
|
||||
{
|
||||
"status": "ok",
|
||||
"task_id": task_id,
|
||||
"message": f"已上传发货通知文件并创建任务 {task_id}。通知原文已保存,等待 Dify 继续解析。",
|
||||
"message": (
|
||||
f"已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。"
|
||||
if orchestrator_started
|
||||
else f"已上传发货通知文件并创建任务 {task_id}。通知原文已保存。"
|
||||
),
|
||||
"data": {
|
||||
"task": serialize_task_summary(task) if task else {"task_no": task_id},
|
||||
"notice_upload": {"filename": upload.filename or "", **meta},
|
||||
"parse_status": "deferred",
|
||||
"orchestrator_started": orchestrator_started,
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -335,6 +357,26 @@ def workspace_shipping_task_chat_actions(task_no: str):
|
||||
return jsonify(build_chat_actions_payload(task))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/retry", methods=["POST"])
|
||||
def workspace_retry_shipping_task(task_no: str):
|
||||
"""重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {"task_id": task.task_no}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
return jsonify(shipping_tools.retry_task(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/upload-inventory", methods=["POST"])
|
||||
def workspace_upload_shipping_inventory(task_no: str):
|
||||
"""用户态上传库存 Excel,并在服务端完成解析。"""
|
||||
@@ -623,3 +665,18 @@ def workspace_shipping_task_export(task_no: str):
|
||||
download_name=download_name,
|
||||
mimetype=EXPORT_MIME_TYPE,
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/retry-pending", methods=["POST"])
|
||||
def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
|
||||
|
||||
return jsonify(retry_batch_pending_tasks(batch.batch_no))
|
||||
@@ -123,6 +123,20 @@ class Config:
|
||||
)
|
||||
# 建单后是否延后 parse_notice,交由 Dify 画布 LLM + Tool 解析(默认 true,符合 Dify 优先原则)
|
||||
SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY = os.getenv('SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY = int(
|
||||
os.getenv('SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY') or '3'
|
||||
)
|
||||
SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS') or '180'
|
||||
)
|
||||
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
|
||||
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
|
||||
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
|
||||
|
||||
@@ -4,3 +4,5 @@ backend/app/jobs/handlers/__init__.py
|
||||
用途:导入各 handler 模块以触发 @register_handler 注册。
|
||||
逻辑:Wave 2 起在 worker 启动前 import 本包。
|
||||
"""
|
||||
|
||||
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_run, wecom_directory_sync # noqa: F401
|
||||
@@ -0,0 +1,19 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_notice_run.py
|
||||
|
||||
用途:货代发货单票后台任务 handler。
|
||||
依赖:jobs.context、jobs.registry、shipping_notice.queue_service。
|
||||
逻辑:统一由 worker 消费 `shipping_notice_run` 队列任务,再委托 shipping_notice.queue_service 执行单票。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.services.shipping_notice.queue_service import run_shipping_notice_job
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_NOTICE_RUN)
|
||||
def run_shipping_notice(ctx: JobContext, payload: dict) -> None:
|
||||
"""消费单票发货后台任务。"""
|
||||
run_shipping_notice_job(payload, logger=ctx.logger)
|
||||
@@ -14,6 +14,7 @@ class JobType(StrEnum):
|
||||
|
||||
KB_CLEAN = 'kb_clean'
|
||||
KB_DIFY_SYNC = 'kb_dify_sync'
|
||||
SHIPPING_NOTICE_RUN = 'shipping_notice_run'
|
||||
SCHEDULE_RUN = 'schedule_run'
|
||||
FILE_CHECK_RUN = 'file_check_run'
|
||||
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
"""
|
||||
services/shipping_notice/batch_orchestrator.py
|
||||
|
||||
用途:发货通知批次/单票后台编排器。
|
||||
依赖:query_service、task_workflow、dify_executor、shipping_notice.tools、tool_common。
|
||||
逻辑:工作台上传后由后端主导单票调度;批次线程只做任务派发,created 票通过 Dify 完成 AI 解析,其余确定性步骤由后端 auto_progress 推进。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
|
||||
from app.services.shipping_notice.dify_executor import run_shipping_parse_via_dify
|
||||
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref, list_sorted_batch_tasks
|
||||
from app.services.shipping_notice.task_workflow import recompute_batch_summary
|
||||
from app.services.shipping_notice.tool_common import auto_progress_enabled, cfg_bool, cfg_int, log_task_event
|
||||
from app.services.shipping_notice.tools import auto_progress
|
||||
|
||||
_RUNNING_BATCHES: set[str] = set()
|
||||
_RUNNING_TASKS: set[str] = set()
|
||||
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
|
||||
|
||||
|
||||
def batch_orchestrator_enabled() -> bool:
|
||||
"""是否启用发货通知后台批次编排器。"""
|
||||
return cfg_bool("SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED", True)
|
||||
|
||||
|
||||
def batch_dispatch_concurrency() -> int:
|
||||
"""单个批次最多并发派发多少张票。"""
|
||||
return cfg_int("SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY", 3, min_value=1)
|
||||
|
||||
|
||||
def _normalize_ref(value: str | None) -> str:
|
||||
return str(value or "").strip().upper()
|
||||
|
||||
|
||||
def _mark_running(bucket: set[str], key: str) -> bool:
|
||||
normalized = _normalize_ref(key)
|
||||
if not normalized:
|
||||
return False
|
||||
if normalized in bucket:
|
||||
return False
|
||||
bucket.add(normalized)
|
||||
return True
|
||||
|
||||
|
||||
def _unmark_running(bucket: set[str], key: str) -> None:
|
||||
normalized = _normalize_ref(key)
|
||||
if not normalized:
|
||||
return
|
||||
bucket.discard(normalized)
|
||||
|
||||
|
||||
def _should_orchestrate_task(task: Any) -> bool:
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||
return False
|
||||
if getattr(task, "review_status", None):
|
||||
return False
|
||||
if getattr(task, "pending_human_reason", None):
|
||||
return False
|
||||
if process_status in {"waiting_inventory", "waiting_upload", "upload_failed"}:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _is_retryable_task(task: Any) -> bool:
|
||||
"""判断任务是否允许由批次重试入口重新派发。"""
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||
return False
|
||||
if getattr(task, "review_status", None):
|
||||
return False
|
||||
if getattr(task, "pending_human_reason", None):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _refresh_batch_focus(task_no: str) -> None:
|
||||
task = get_task_by_ref(task_no)
|
||||
if not task or not task.batch:
|
||||
return
|
||||
task.batch.current_focus_task_no = task.task_no
|
||||
recompute_batch_summary(task.batch)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
"""
|
||||
后台执行单票任务的一轮推进。
|
||||
|
||||
`created` 先由 Dify 做单票解析,其余状态尝试走 auto_progress;进入人工检查点时自然返回。
|
||||
"""
|
||||
normalized_task_no = _normalize_ref(task_no)
|
||||
if not normalized_task_no:
|
||||
return {"status": "missing", "message": "task_no is required"}
|
||||
if not _mark_running(_RUNNING_TASKS, normalized_task_no):
|
||||
return {"status": "skipped", "message": "task already running"}
|
||||
|
||||
try:
|
||||
task = get_task_by_ref(normalized_task_no)
|
||||
if not task:
|
||||
return {"status": "missing", "message": "task not found"}
|
||||
if not _should_orchestrate_task(task):
|
||||
return {
|
||||
"status": "skipped",
|
||||
"message": f"skip process_status={task.process_status or ''}",
|
||||
}
|
||||
|
||||
_refresh_batch_focus(task.task_no)
|
||||
task = get_task_by_ref(normalized_task_no)
|
||||
assert task is not None
|
||||
log_task_event(
|
||||
task,
|
||||
"backend_orchestrator_task_started",
|
||||
{"process_status": task.process_status, "current_step": task.current_step},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
payload: dict[str, Any] = {"task_id": task.task_no, "conversation_id": task.conversation_id}
|
||||
if str(task.process_status or "").strip().lower() == "created":
|
||||
result = run_shipping_parse_via_dify(task.task_no)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-orchestrator] dify-parse result task_no=%s status=%s process_status_before=%s provider_conversation_id=%s message=%s",
|
||||
task.task_no,
|
||||
result.get("status"),
|
||||
task.process_status,
|
||||
result.get("provider_conversation_id"),
|
||||
str(result.get("message") or "")[:300],
|
||||
)
|
||||
refreshed_after_dify = get_task_by_ref(normalized_task_no)
|
||||
if (
|
||||
refreshed_after_dify
|
||||
and auto_progress_enabled()
|
||||
and _should_orchestrate_task(refreshed_after_dify)
|
||||
and str(refreshed_after_dify.process_status or "").strip().lower() != "created"
|
||||
):
|
||||
payload["mode"] = "auto"
|
||||
follow_up = auto_progress(payload)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-orchestrator] auto-progress follow-up task_no=%s status=%s process_status_after_dify=%s current_step=%s message=%s",
|
||||
task.task_no,
|
||||
follow_up.get("status"),
|
||||
getattr(refreshed_after_dify, "process_status", None),
|
||||
getattr(refreshed_after_dify, "current_step", None),
|
||||
str(follow_up.get("message") or "")[:300],
|
||||
)
|
||||
result = {
|
||||
"status": str(follow_up.get("status") or result.get("status") or ""),
|
||||
"message": "\n".join(
|
||||
part for part in [
|
||||
str(result.get("message") or "").strip(),
|
||||
str(follow_up.get("message") or "").strip(),
|
||||
] if part
|
||||
)[:500] or None,
|
||||
}
|
||||
else:
|
||||
payload["mode"] = "auto"
|
||||
result = auto_progress(payload)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-orchestrator] auto-progress task_no=%s status=%s process_status_before=%s current_step_before=%s message=%s",
|
||||
task.task_no,
|
||||
result.get("status"),
|
||||
task.process_status,
|
||||
task.current_step,
|
||||
str(result.get("message") or "")[:300],
|
||||
)
|
||||
|
||||
refreshed = get_task_by_ref(normalized_task_no)
|
||||
if refreshed:
|
||||
if refreshed.batch:
|
||||
recompute_batch_summary(refreshed.batch)
|
||||
log_task_event(
|
||||
refreshed,
|
||||
"backend_orchestrator_task_finished",
|
||||
{
|
||||
"result_status": str(result.get("status") or ""),
|
||||
"process_status": refreshed.process_status,
|
||||
"current_step": refreshed.current_step,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return {
|
||||
"status": str(result.get("status") or ""),
|
||||
"message": str(result.get("message") or "")[:500] or None,
|
||||
}
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
task = get_task_by_ref(normalized_task_no)
|
||||
if task:
|
||||
task.error_message = str(exc)
|
||||
log_task_event(task, "backend_orchestrator_task_failed", {"error": str(exc)[:1000]})
|
||||
if task.batch:
|
||||
recompute_batch_summary(task.batch)
|
||||
db.session.commit()
|
||||
return {"status": "failed", "message": str(exc)[:500] or "background task failed"}
|
||||
finally:
|
||||
db.session.remove()
|
||||
_unmark_running(_RUNNING_TASKS, normalized_task_no)
|
||||
|
||||
|
||||
def _background_task_runner(app: Any, task_no: str) -> None:
|
||||
try:
|
||||
with app.app_context():
|
||||
_run_single_task(task_no)
|
||||
finally:
|
||||
_unmark_running(_RUNNING_BATCHES, f"TASK::{task_no}")
|
||||
|
||||
|
||||
def _background_batch_runner(app: Any, batch_no: str) -> None:
|
||||
normalized_batch_no = _normalize_ref(batch_no)
|
||||
try:
|
||||
with app.app_context():
|
||||
batch = get_batch_by_no(normalized_batch_no)
|
||||
if not batch:
|
||||
return
|
||||
recompute_batch_summary(batch)
|
||||
db.session.commit()
|
||||
|
||||
task_nos = [task.task_no for task in list_sorted_batch_tasks(batch)]
|
||||
if not task_nos:
|
||||
return
|
||||
|
||||
max_workers = min(batch_dispatch_concurrency(), len(task_nos))
|
||||
if max_workers <= 1:
|
||||
for task_no in task_nos:
|
||||
_refresh_batch_focus(task_no)
|
||||
_run_single_task(task_no)
|
||||
batch = get_batch_by_no(normalized_batch_no)
|
||||
if not batch:
|
||||
break
|
||||
else:
|
||||
app_obj = current_app._get_current_object()
|
||||
with ThreadPoolExecutor(
|
||||
max_workers=max_workers,
|
||||
thread_name_prefix=f"shipping-batch-{normalized_batch_no}",
|
||||
) as executor:
|
||||
future_map = {
|
||||
executor.submit(_run_task_with_app_context, app_obj, task_no): task_no
|
||||
for task_no in task_nos
|
||||
}
|
||||
for future in as_completed(future_map):
|
||||
task_no = future_map[future]
|
||||
try:
|
||||
future.result()
|
||||
except Exception as exc:
|
||||
task = get_task_by_ref(task_no)
|
||||
if task:
|
||||
task.error_message = str(exc)
|
||||
log_task_event(
|
||||
task,
|
||||
"backend_orchestrator_task_failed",
|
||||
{"error": str(exc)[:1000], "source": "batch_dispatcher"},
|
||||
)
|
||||
if task.batch:
|
||||
recompute_batch_summary(task.batch)
|
||||
db.session.commit()
|
||||
|
||||
batch = get_batch_by_no(normalized_batch_no)
|
||||
if batch:
|
||||
recompute_batch_summary(batch)
|
||||
db.session.commit()
|
||||
finally:
|
||||
db.session.remove()
|
||||
_unmark_running(_RUNNING_BATCHES, normalized_batch_no)
|
||||
|
||||
|
||||
def start_task_orchestrator(task_no: str | None) -> bool:
|
||||
"""将单票后台任务写入持久化队列。"""
|
||||
normalized_task_no = _normalize_ref(task_no)
|
||||
if not normalized_task_no or not batch_orchestrator_enabled():
|
||||
return False
|
||||
ok, result = enqueue_shipping_notice_job(task_no=normalized_task_no)
|
||||
return ok and result in {"queued_for_worker", "already_queued", "done", "ok", "running", "needs_human", "skipped"}
|
||||
|
||||
|
||||
def start_batch_orchestrator(batch_no: str | None) -> bool:
|
||||
"""批次入口改为逐票入队,由 worker 消费,不再在 web 进程内起长线程。"""
|
||||
normalized_batch_no = _normalize_ref(batch_no)
|
||||
if not normalized_batch_no or not batch_orchestrator_enabled():
|
||||
return False
|
||||
batch = get_batch_by_no(normalized_batch_no)
|
||||
if not batch:
|
||||
return False
|
||||
|
||||
started = False
|
||||
for task in list_sorted_batch_tasks(batch):
|
||||
ok, _result = enqueue_shipping_notice_job(
|
||||
task_no=task.task_no,
|
||||
created_by_id=getattr(batch, "user_id", None),
|
||||
batch_no=batch.batch_no,
|
||||
)
|
||||
started = started or ok
|
||||
recompute_batch_summary(batch)
|
||||
db.session.commit()
|
||||
return started
|
||||
|
||||
|
||||
def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
|
||||
"""重试批次中仍可自动推进的任务,跳过已终态和人工阻断任务。"""
|
||||
normalized_batch_no = _normalize_ref(batch_no)
|
||||
if not normalized_batch_no:
|
||||
return {"status": "failed", "message": "batch_no is required"}
|
||||
batch = get_batch_by_no(normalized_batch_no)
|
||||
if not batch:
|
||||
return {"status": "failed", "message": "batch not found"}
|
||||
|
||||
started = 0
|
||||
skipped = 0
|
||||
for task in list_sorted_batch_tasks(batch):
|
||||
if not _is_retryable_task(task):
|
||||
skipped += 1
|
||||
continue
|
||||
if start_task_orchestrator(task.task_no):
|
||||
started += 1
|
||||
else:
|
||||
skipped += 1
|
||||
|
||||
recompute_batch_summary(batch)
|
||||
db.session.commit()
|
||||
return {
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
"started": started,
|
||||
"skipped": skipped,
|
||||
"message": f"已为批次 {batch.batch_no} 重试 {started} 个任务,跳过 {skipped} 个任务。",
|
||||
}
|
||||
|
||||
|
||||
def _run_task_with_app_context(app: Any, task_no: str) -> dict[str, str | None]:
|
||||
"""批次派发时为单票补充独立 app/db 上下文,避免批次线程串行阻塞。"""
|
||||
with app.app_context():
|
||||
return _run_single_task(task_no)
|
||||
@@ -0,0 +1,348 @@
|
||||
"""
|
||||
services/shipping_notice/dify_executor.py
|
||||
|
||||
用途:发货通知后台编排器内部调用 Dify Chatflow,完成单票 AI 解析。
|
||||
依赖:models.ChatSession、services.dify、agent_resolver、dify_inputs、query_service。
|
||||
逻辑:后台调度器逐票执行时,created 任务在这里触发 Dify;Dify 只负责当前票解析,不承担整批调度。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ChatSession
|
||||
from app.services.dify import DifyService
|
||||
from app.services.shipping_notice.agent_resolver import resolve_chat_agent
|
||||
from app.services.shipping_notice.dify_inputs import build_dify_chat_inputs
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
from app.services.shipping_notice.tool_common import cfg_int
|
||||
|
||||
|
||||
def build_single_task_parse_prompt(task_no: str, *, batch_no: str | None = None) -> str:
|
||||
"""构造后台排程器发给 Dify 的单票解析指令。"""
|
||||
pieces = [
|
||||
"你正在处理货代发货通知任务。",
|
||||
f"当前任务编号:{task_no}。",
|
||||
]
|
||||
if batch_no:
|
||||
pieces.append(f"所属批次:{batch_no}。")
|
||||
pieces.extend(
|
||||
[
|
||||
"只允许处理当前这一票,禁止切换任务、禁止整批循环、禁止调用 switch_focus_task。",
|
||||
"先调用 get_task_status 获取当前任务状态和 raw_text。",
|
||||
"如果当前任务已经不是待解析状态,或已经进入人工确认/下游阶段,请直接总结当前状态并结束。",
|
||||
"如果当前任务仍待解析,请基于 raw_text 用 LLM 抽取结构化字段,并调用 parse_notice(structured=...) 落库。",
|
||||
"禁止再次询问用户“是否开始解析”。",
|
||||
"完成后只返回当前票的简短解析结果摘要。",
|
||||
]
|
||||
)
|
||||
return "".join(pieces)
|
||||
|
||||
|
||||
def _ensure_chat_session_for_task(task: Any, agent_id: int, title: str) -> ChatSession | None:
|
||||
"""尽量复用聊天会话;若任务带本地会话号但会话未建,则补建一条 ChatSession。"""
|
||||
session_id = str(getattr(task, "conversation_id", "") or "").strip()
|
||||
user_id = getattr(task, "user_id", None)
|
||||
if not session_id or not user_id:
|
||||
return None
|
||||
session = ChatSession.query.filter_by(
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
session_id=session_id,
|
||||
).first()
|
||||
if session:
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-dify-executor] reuse chat_session task_no=%s session_id=%s external_conversation_id=%s",
|
||||
getattr(task, "task_no", None),
|
||||
session.session_id,
|
||||
session.external_conversation_id,
|
||||
)
|
||||
return session
|
||||
session = ChatSession(
|
||||
session_id=session_id,
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
title=(str(title or "").strip()[:255]),
|
||||
status="running",
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
last_active_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(session)
|
||||
db.session.commit()
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-dify-executor] create chat_session task_no=%s session_id=%s",
|
||||
getattr(task, "task_no", None),
|
||||
session.session_id,
|
||||
)
|
||||
return session
|
||||
|
||||
|
||||
def _update_chat_session_after_stream(
|
||||
session: ChatSession | None,
|
||||
*,
|
||||
provider_conversation_id: str | None,
|
||||
status: str,
|
||||
) -> None:
|
||||
if not session:
|
||||
return
|
||||
provider_id = str(provider_conversation_id or "").strip() or None
|
||||
changed = False
|
||||
if provider_id and session.external_conversation_id != provider_id:
|
||||
session.external_conversation_id = provider_id
|
||||
changed = True
|
||||
if status and session.status != status:
|
||||
session.status = status
|
||||
changed = True
|
||||
session.last_active_at = datetime.utcnow()
|
||||
session.updated_at = datetime.utcnow()
|
||||
changed = True
|
||||
if changed:
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _log_executor_context(
|
||||
*,
|
||||
task: Any,
|
||||
batch_no: str | None,
|
||||
local_conversation_id: str,
|
||||
provider_conversation_id: str | None,
|
||||
inputs: dict[str, Any],
|
||||
request_id: str,
|
||||
) -> None:
|
||||
if not current_app:
|
||||
return
|
||||
current_app.logger.info(
|
||||
"[shipping-dify-executor] context request_id=%s task_no=%s batch_no=%s session_id=%s provider_conversation_id=%s inputs=%s",
|
||||
request_id,
|
||||
getattr(task, "task_no", None),
|
||||
batch_no,
|
||||
local_conversation_id,
|
||||
provider_conversation_id,
|
||||
json.dumps(inputs, ensure_ascii=False, default=str),
|
||||
)
|
||||
|
||||
|
||||
def _parse_total_timeout_seconds() -> int:
|
||||
"""单票 Dify 解析总超时,避免长时间无终态事件把工作线程一直占住。"""
|
||||
return cfg_int("SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS", 180, min_value=15)
|
||||
|
||||
|
||||
def run_shipping_parse_via_dify(task_no: str) -> dict[str, Any]:
|
||||
"""
|
||||
由后台排程器触发 Dify 处理单票发货通知解析。
|
||||
|
||||
这里不做批次循环,只让 Dify 完成“当前票 AI 解析 + parse_notice”这一步。
|
||||
"""
|
||||
task = get_task_by_ref(task_no)
|
||||
if not task:
|
||||
return {"status": "failed", "message": "task not found"}
|
||||
if not getattr(task, "user_id", None):
|
||||
return {"status": "failed", "message": "task user_id is missing"}
|
||||
|
||||
agent = resolve_chat_agent()
|
||||
if not agent or not getattr(agent, "dify_api_key", None):
|
||||
return {"status": "failed", "message": "shipping dify agent is not available"}
|
||||
|
||||
batch_no = str(getattr(getattr(task, "batch", None), "batch_no", "") or "").strip() or None
|
||||
query = build_single_task_parse_prompt(task.task_no, batch_no=batch_no)
|
||||
session = _ensure_chat_session_for_task(task, agent.id, query)
|
||||
local_conversation_id = (
|
||||
str(getattr(session, "session_id", "") or "").strip()
|
||||
or str(getattr(task, "conversation_id", "") or "").strip()
|
||||
or task.task_no
|
||||
)
|
||||
provider_conversation_id = (
|
||||
str(getattr(session, "external_conversation_id", "") or "").strip() or None
|
||||
)
|
||||
inputs = build_dify_chat_inputs(
|
||||
local_conversation_id,
|
||||
task_id=task.task_no,
|
||||
batch_no=batch_no,
|
||||
entry_mode="orchestrator_parse",
|
||||
user_message="",
|
||||
trigger_source="backend_orchestrator",
|
||||
)
|
||||
request_id = f"shipping-orch-{task.task_no}"
|
||||
started_at = time.perf_counter()
|
||||
total_timeout_seconds = _parse_total_timeout_seconds()
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-dify-executor] start request_id=%s task_no=%s batch_no=%s session_id=%s provider_conversation_id=%s",
|
||||
request_id,
|
||||
task.task_no,
|
||||
batch_no,
|
||||
local_conversation_id,
|
||||
provider_conversation_id,
|
||||
)
|
||||
_log_executor_context(
|
||||
task=task,
|
||||
batch_no=batch_no,
|
||||
local_conversation_id=local_conversation_id,
|
||||
provider_conversation_id=provider_conversation_id,
|
||||
inputs=inputs,
|
||||
request_id=request_id,
|
||||
)
|
||||
|
||||
final_event: dict[str, Any] | None = None
|
||||
final_answer = ""
|
||||
terminal_status = "done"
|
||||
event_count = 0
|
||||
message_event_count = 0
|
||||
message_char_count = 0
|
||||
terminal_event_name = ""
|
||||
|
||||
try:
|
||||
stream = DifyService.stream_chat(
|
||||
query,
|
||||
int(task.user_id),
|
||||
agent,
|
||||
provider_conversation_id,
|
||||
request_id=request_id,
|
||||
session_id=local_conversation_id,
|
||||
inputs=inputs,
|
||||
)
|
||||
for chunk in stream:
|
||||
if time.perf_counter() - started_at > total_timeout_seconds:
|
||||
raise TimeoutError(f"dify parse timed out after {total_timeout_seconds}s")
|
||||
if not isinstance(chunk, str) or not chunk.startswith("data: "):
|
||||
continue
|
||||
payload = chunk[6:].strip()
|
||||
if not payload:
|
||||
continue
|
||||
try:
|
||||
data = json.loads(payload)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
event_name = str(data.get("event") or "").strip()
|
||||
if not event_name:
|
||||
continue
|
||||
event_count += 1
|
||||
provider_id = str(data.get("conversation_id") or "").strip() or None
|
||||
if provider_id:
|
||||
provider_conversation_id = provider_id
|
||||
answer = str(data.get("answer") or "")
|
||||
if answer:
|
||||
if event_name in {"message", "agent_message", "message_end", "workflow_finished"}:
|
||||
message_event_count += 1
|
||||
message_char_count += len(answer)
|
||||
if data.get("replace_answer"):
|
||||
final_answer = answer
|
||||
else:
|
||||
final_answer += answer
|
||||
if current_app and event_name in {"error", "message_end", "workflow_finished"}:
|
||||
current_app.logger.info(
|
||||
"[shipping-dify-executor] terminal-candidate request_id=%s event=%s task_no=%s provider_conversation_id=%s answer_len=%s",
|
||||
request_id,
|
||||
event_name,
|
||||
task.task_no,
|
||||
provider_conversation_id,
|
||||
len(answer),
|
||||
)
|
||||
if event_name == "error":
|
||||
terminal_status = "error"
|
||||
terminal_event_name = event_name
|
||||
final_event = data
|
||||
break
|
||||
if event_name in {"message_end", "workflow_finished"}:
|
||||
terminal_event_name = event_name
|
||||
final_event = data
|
||||
break
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
_update_chat_session_after_stream(
|
||||
session,
|
||||
provider_conversation_id=provider_conversation_id,
|
||||
status="error",
|
||||
)
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
"[shipping-dify-executor] exception request_id=%s task_no=%s provider_conversation_id=%s",
|
||||
request_id,
|
||||
task.task_no,
|
||||
provider_conversation_id,
|
||||
)
|
||||
return {"status": "failed", "message": str(exc)[:500] or "dify execution failed"}
|
||||
|
||||
_update_chat_session_after_stream(
|
||||
session,
|
||||
provider_conversation_id=provider_conversation_id,
|
||||
status=terminal_status,
|
||||
)
|
||||
refreshed = get_task_by_ref(task.task_no)
|
||||
process_status = str(getattr(refreshed, "process_status", "") or "").strip() if refreshed else ""
|
||||
review_status = str(getattr(refreshed, "review_status", "") or "").strip() if refreshed else ""
|
||||
elapsed_ms = int((time.perf_counter() - started_at) * 1000)
|
||||
|
||||
if final_event and str(final_event.get("event") or "").strip() == "error":
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[shipping-dify-executor] failed request_id=%s task_no=%s event=%s provider_conversation_id=%s elapsed_ms=%s events=%s message_events=%s answer_chars=%s process_status=%s review_status=%s error=%s",
|
||||
request_id,
|
||||
task.task_no,
|
||||
terminal_event_name or "error",
|
||||
provider_conversation_id,
|
||||
elapsed_ms,
|
||||
event_count,
|
||||
message_event_count,
|
||||
message_char_count,
|
||||
process_status,
|
||||
review_status,
|
||||
str(final_event.get("message") or "")[:300],
|
||||
)
|
||||
return {
|
||||
"status": "failed",
|
||||
"message": str(final_event.get("message") or "dify returned error")[:500],
|
||||
"provider_conversation_id": provider_conversation_id,
|
||||
}
|
||||
|
||||
if not final_event:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[shipping-dify-executor] missing-terminal-event request_id=%s task_no=%s provider_conversation_id=%s elapsed_ms=%s events=%s process_status=%s review_status=%s",
|
||||
request_id,
|
||||
task.task_no,
|
||||
provider_conversation_id,
|
||||
elapsed_ms,
|
||||
event_count,
|
||||
process_status,
|
||||
review_status,
|
||||
)
|
||||
return {
|
||||
"status": "failed",
|
||||
"message": "dify stream finished without terminal event",
|
||||
"provider_conversation_id": provider_conversation_id,
|
||||
}
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-dify-executor] finished request_id=%s task_no=%s event=%s provider_conversation_id=%s elapsed_ms=%s events=%s message_events=%s answer_chars=%s process_status=%s review_status=%s",
|
||||
request_id,
|
||||
task.task_no,
|
||||
terminal_event_name or str(final_event.get("event") or ""),
|
||||
provider_conversation_id,
|
||||
elapsed_ms,
|
||||
event_count,
|
||||
message_event_count,
|
||||
message_char_count,
|
||||
process_status,
|
||||
review_status,
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "ok",
|
||||
"message": final_answer[:500] or "dify parse finished",
|
||||
"task_process_status": process_status or None,
|
||||
"task_review_status": review_status or None,
|
||||
"provider_conversation_id": provider_conversation_id,
|
||||
}
|
||||
@@ -15,6 +15,9 @@ from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
|
||||
SHIPPING_CONVERSATION_ID_INPUT = "conversation_id"
|
||||
SHIPPING_CURRENT_BATCH_NO_INPUT = "current_batch_no"
|
||||
SHIPPING_CURRENT_TASK_NO_INPUT = "current_task_no"
|
||||
SHIPPING_ENTRY_MODE_INPUT = "entry_mode"
|
||||
SHIPPING_USER_MESSAGE_INPUT = "user_message"
|
||||
SHIPPING_TRIGGER_SOURCE_INPUT = "trigger_source"
|
||||
|
||||
|
||||
def is_shipping_notice_chat_agent(agent) -> bool:
|
||||
@@ -52,6 +55,9 @@ def build_dify_chat_inputs(
|
||||
*,
|
||||
task_id: str | None = None,
|
||||
batch_no: str | None = None,
|
||||
entry_mode: str | None = None,
|
||||
user_message: str | None = None,
|
||||
trigger_source: str | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""
|
||||
构建发货通知 Dify Chatflow inputs。
|
||||
@@ -87,7 +93,10 @@ def build_dify_chat_inputs(
|
||||
current_batch_no = str(task.batch.batch_no or "").strip().upper()
|
||||
|
||||
return {
|
||||
SHIPPING_ENTRY_MODE_INPUT: str(entry_mode or "").strip(),
|
||||
SHIPPING_CONVERSATION_ID_INPUT: conv_id,
|
||||
SHIPPING_CURRENT_BATCH_NO_INPUT: current_batch_no,
|
||||
SHIPPING_CURRENT_TASK_NO_INPUT: current_task_no,
|
||||
SHIPPING_USER_MESSAGE_INPUT: str(user_message or "").strip(),
|
||||
SHIPPING_TRIGGER_SOURCE_INPUT: str(trigger_source or "").strip(),
|
||||
}
|
||||
@@ -29,6 +29,7 @@ from app.services.shipping_notice.match import format_match_summary, match_notic
|
||||
from app.services.shipping_notice.query_service import (
|
||||
resolve_task_from_payload,
|
||||
serialize_task_for_tool,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_id import extract_reservation_id
|
||||
from app.services.shipping_notice.rpa import write_upload_trigger
|
||||
@@ -95,10 +96,9 @@ def log_task_event(task: ShippingTask, event_type: str, detail: dict[str, Any] |
|
||||
|
||||
|
||||
def match_completed(task: ShippingTask) -> bool:
|
||||
"""判断任务是否已完成可履约的库存匹配(process_status=matched 且 line_results 非空)。"""
|
||||
"""判断任务是否已完成可履约的库存匹配(fulfillable 且 line_results 非空)。"""
|
||||
return bool(
|
||||
task.process_status == "matched"
|
||||
and task.match_status
|
||||
task.match_status == "fulfillable"
|
||||
and isinstance(task.line_results_json, list)
|
||||
and len(task.line_results_json) > 0
|
||||
)
|
||||
@@ -345,7 +345,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
基于已匹配任务生成货代发货 Excel 并推进至 waiting_upload。
|
||||
【AI 触发时机】:match_inventory 返回 fulfillable 且用户需下载/上传 Excel 时调用;未匹配前禁止调用。
|
||||
|
||||
核心逻辑:excel_gate_error 门禁 → generate_shipment_excel → 写 export_file_path → WAITING_UPLOAD。
|
||||
核心逻辑:已有导出文件时直接返回成功;否则走 excel_gate_error 门禁 → generate_shipment_excel → 写 export_file_path → WAITING_UPLOAD。
|
||||
|
||||
Args:
|
||||
payload: 须含 task_id 或 conversation_id。
|
||||
@@ -357,8 +357,18 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
|
||||
# [STEP 1] 先校验是否满足导出门禁。
|
||||
# 只有库存匹配完成后才允许生成货代 Excel,避免基于未确认数据导出。
|
||||
# [STEP 1] 若任务已有可下载的导出文件,则直接返回成功,保证重复点击“生成 Excel”幂等。
|
||||
# 这里不重复生成文件,避免任务已进入 waiting_upload 后再次点击却被旧门禁误判为“未完成匹配”。
|
||||
if task.export_file_path and not task_export_error_message(task):
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message=f"发货 Excel 已生成:{task.export_file_name or task.export_file_path}",
|
||||
data={**serialize_task_for_tool(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"},
|
||||
)
|
||||
|
||||
# [STEP 2] 先校验是否满足导出门禁。
|
||||
# 只有库存匹配完成后才允许生成货代 Excel;但 waiting_upload/uploaded 仍应视为“已完成匹配”。
|
||||
gate_error = excel_gate_error(task)
|
||||
if gate_error:
|
||||
return tool_response(
|
||||
@@ -379,7 +389,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
detail="正在按货代模板填充全部应发行",
|
||||
)
|
||||
|
||||
# [STEP 2] 生成文件并把任务推进到等待上传阶段。
|
||||
# [STEP 3] 生成文件并把任务推进到等待上传阶段。
|
||||
# 导出文件路径会成为后续 RPA 上传或人工下载的唯一输入。
|
||||
path, filename = generate_shipment_excel(task)
|
||||
task.export_file_path = path
|
||||
@@ -443,6 +453,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
human_options=[],
|
||||
)
|
||||
apply_task_transition(task, TaskTransition.UPLOADED)
|
||||
task.upload_finished_at = datetime.utcnow()
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step7_upload_freight",
|
||||
@@ -452,6 +463,11 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
progress_percent=100,
|
||||
detail="任务已完成",
|
||||
)
|
||||
# [STEP 2.1] 手工上传确认属于任务终态写路径,需要同步刷新批次汇总,
|
||||
# 否则聊天顶部批次卡片仍会读取旧的 process_summary_json,显示成未完成。
|
||||
from app.services.shipping_notice.task_workflow import sync_batch_after_task_change
|
||||
|
||||
sync_batch_after_task_change(task)
|
||||
ref = str(payload.get("freight_ref_no") or "").strip()
|
||||
if ref:
|
||||
task.freight_ref_no = ref
|
||||
@@ -540,7 +556,6 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
step_title="上传货代",
|
||||
status="running",
|
||||
message="已触发 RPA 上传货代,等待回执",
|
||||
progress_percent=65,
|
||||
current=attempt_no,
|
||||
total=max_attempts,
|
||||
detail=f"第 {attempt_no}/{max_attempts} 次上传尝试",
|
||||
|
||||
@@ -115,6 +115,12 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
{
|
||||
"task_id": task_id,
|
||||
"raw_text": _str_prop("待解析的发货通知全文"),
|
||||
"structured": {
|
||||
"type": "object",
|
||||
"description": "Dify LLM 解析后的结构化结果对象。若提供,后端优先使用该对象中的 lines/confidence/reservation_id 等字段落库。",
|
||||
"additionalProperties": True,
|
||||
},
|
||||
"lang": _str_prop("可选语言代码:zh|en|th"),
|
||||
},
|
||||
required=["task_id"],
|
||||
),
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
"""
|
||||
services/shipping_notice/queue_service.py
|
||||
|
||||
用途:货代发货后台任务最小队列实现(基于 KbJob 持久化表)。
|
||||
依赖:models.KbJob、jobs.types、shipping_notice.batch_orchestrator。
|
||||
逻辑:Web 侧负责 enqueue;worker 侧通过 claim/process 消费单票任务,避免使用进程内 threading。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
import logging
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from app import db
|
||||
from app.jobs.types import JobType
|
||||
from app.models import KbJob
|
||||
|
||||
logger = logging.getLogger('shipping-worker')
|
||||
|
||||
|
||||
def shipping_task_execution_mode() -> str:
|
||||
return str(current_app.config.get('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker') or 'worker').strip().lower()
|
||||
|
||||
|
||||
def enqueue_shipping_notice_job(*, task_no: str, created_by_id: int | None = None, batch_no: str | None = None) -> tuple[bool, str]:
|
||||
"""持久化一条单票发货后台任务;sync 模式下直接执行。"""
|
||||
normalized_task_no = str(task_no or '').strip().upper()
|
||||
if not normalized_task_no:
|
||||
return False, 'task_no is required'
|
||||
|
||||
existing = (
|
||||
db.session.query(KbJob)
|
||||
.filter(
|
||||
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
|
||||
KbJob.status.in_(('queued', 'running')),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for job in existing:
|
||||
payload = job.payload_json or {}
|
||||
if str(payload.get('task_no') or '').strip().upper() == normalized_task_no:
|
||||
return True, 'already_queued'
|
||||
|
||||
job = KbJob(
|
||||
job_type=JobType.SHIPPING_NOTICE_RUN.value,
|
||||
status='queued',
|
||||
progress=0,
|
||||
message='等待后台处理发货任务',
|
||||
payload_json={
|
||||
'task_no': normalized_task_no,
|
||||
'batch_no': str(batch_no or '').strip().upper() or None,
|
||||
},
|
||||
created_by_id=created_by_id,
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
|
||||
if shipping_task_execution_mode() == 'sync':
|
||||
ok, result = run_shipping_notice_job({'job_id': job.id})
|
||||
return ok, result
|
||||
if shipping_task_execution_mode() in ('worker', 'rq'):
|
||||
return True, 'queued_for_worker'
|
||||
return True, 'queued_manual'
|
||||
|
||||
|
||||
def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
|
||||
"""回收长时间 running 的发货后台任务,避免 worker 被卡死任务阻塞。"""
|
||||
timeout_sec = float(current_app.config.get('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 300))
|
||||
cutoff = datetime.utcnow() - timedelta(seconds=timeout_sec)
|
||||
stale_jobs = (
|
||||
db.session.query(KbJob)
|
||||
.filter(
|
||||
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
|
||||
KbJob.status == 'running',
|
||||
KbJob.started_at.isnot(None),
|
||||
KbJob.started_at < cutoff,
|
||||
)
|
||||
.order_by(KbJob.started_at.asc(), KbJob.id.asc())
|
||||
.all()
|
||||
)
|
||||
if not stale_jobs:
|
||||
return 0, 'no_stale_jobs'
|
||||
|
||||
now = datetime.utcnow()
|
||||
message = f'发货任务执行超时(超过 {int(timeout_sec)}s),已自动回收'
|
||||
for job in stale_jobs:
|
||||
job.status = 'failed'
|
||||
job.error_message = message
|
||||
job.message = message
|
||||
job.finished_at = now
|
||||
job.progress = 100
|
||||
db.session.commit()
|
||||
logger.warning('recovered %s stale shipping_notice job(s)', len(stale_jobs))
|
||||
return len(stale_jobs), f'recovered_{len(stale_jobs)}'
|
||||
|
||||
|
||||
def claim_next_shipping_notice_job() -> KbJob | None:
|
||||
"""原子领取下一条 queued 的发货后台任务。"""
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
job = (
|
||||
db.session.query(KbJob)
|
||||
.filter(
|
||||
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
|
||||
KbJob.status == 'queued',
|
||||
)
|
||||
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
|
||||
.with_for_update(skip_locked=True)
|
||||
.first()
|
||||
)
|
||||
except OperationalError:
|
||||
db.session.rollback()
|
||||
logger.exception('failed to claim next shipping notice job')
|
||||
return None
|
||||
|
||||
if not job:
|
||||
db.session.rollback()
|
||||
return None
|
||||
|
||||
job.status = 'running'
|
||||
job.started_at = job.started_at or now
|
||||
job.progress = max(int(job.progress or 0), 1)
|
||||
job.message = 'worker 已领取发货任务'
|
||||
db.session.commit()
|
||||
return job
|
||||
|
||||
|
||||
def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | None = None) -> tuple[bool, str]:
|
||||
"""执行单票发货任务;既可被 worker 调用,也可被 sync enqueue 直调。"""
|
||||
from app.services.shipping_notice.batch_orchestrator import _run_single_task
|
||||
|
||||
job_id = payload.get('job_id')
|
||||
job = db.session.get(KbJob, int(job_id)) if job_id else None
|
||||
if job is None:
|
||||
task_no = str(payload.get('task_no') or '').strip().upper()
|
||||
else:
|
||||
task_no = str((job.payload_json or {}).get('task_no') or '').strip().upper()
|
||||
|
||||
if not task_no:
|
||||
return False, 'missing_task_no'
|
||||
|
||||
result = _run_single_task(task_no)
|
||||
status = str(result.get('status') or '').strip().lower()
|
||||
success = status in {'ok', 'running', 'needs_human', 'skipped'}
|
||||
|
||||
if job is not None:
|
||||
job.progress = 100
|
||||
job.finished_at = datetime.utcnow()
|
||||
job.result_json = dict(result)
|
||||
job.message = str(result.get('message') or '')[:500] or '发货任务处理完成'
|
||||
if success:
|
||||
job.status = 'success'
|
||||
job.error_message = None
|
||||
else:
|
||||
job.status = 'failed'
|
||||
job.error_message = str(result.get('message') or 'shipping notice job failed')[:1000]
|
||||
db.session.commit()
|
||||
|
||||
if logger:
|
||||
logger.info('shipping_notice job task_no=%s status=%s', task_no, status or 'unknown')
|
||||
return success, status or 'done'
|
||||
|
||||
|
||||
def process_next_shipping_notice_job() -> tuple[bool, str]:
|
||||
"""worker 消费发货后台队列的单步入口。"""
|
||||
recover_stale_shipping_notice_jobs()
|
||||
job = claim_next_shipping_notice_job()
|
||||
if not job:
|
||||
return False, 'no_job'
|
||||
return run_shipping_notice_job({'job_id': job.id})
|
||||
@@ -15,7 +15,8 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.models import ChatLog, ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.agent_resolver import resolve_chat_agent
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_PARSE_OK,
|
||||
CP_TASK_EXISTS,
|
||||
@@ -54,6 +55,77 @@ EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to",
|
||||
EDITABLE_NOTICE_LINE_FIELDS = frozenset({"sku", "reservation_id", "qty", "quantity", "required_date", "uom"})
|
||||
|
||||
|
||||
def _build_parse_review_chat_payload(task: ShippingTask) -> dict[str, Any]:
|
||||
return {
|
||||
"taskId": task.task_no,
|
||||
"checkpoint": "parse_review",
|
||||
"header": {
|
||||
"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 [],
|
||||
"saving": False,
|
||||
}
|
||||
|
||||
|
||||
def _upsert_parse_review_chat_message(task: ShippingTask) -> None:
|
||||
"""
|
||||
将 parse_review 结果直接回填到当前聊天会话。
|
||||
|
||||
设计意图:
|
||||
- 不再依赖“前端再次发一轮消息”去索取解析结果;
|
||||
- 同任务只保留一条 shipping-parse-review 消息,重复解析时直接更新。
|
||||
"""
|
||||
session_id = str(task.conversation_id or "").strip()
|
||||
if not session_id or not task.user_id:
|
||||
return
|
||||
agent = resolve_chat_agent()
|
||||
if not agent or not getattr(agent, "id", None):
|
||||
return
|
||||
|
||||
payload = _build_parse_review_chat_payload(task)
|
||||
content = f"请确认或修订以下解析结果。\n任务编号:{task.task_no}"
|
||||
chat_logs = (
|
||||
db.session.query(ChatLog)
|
||||
.filter_by(
|
||||
user_id=task.user_id,
|
||||
agent_id=agent.id,
|
||||
session_id=session_id,
|
||||
message_type="shipping-parse-review",
|
||||
)
|
||||
.order_by(ChatLog.created_at.desc(), ChatLog.id.desc())
|
||||
.all()
|
||||
)
|
||||
|
||||
existing = None
|
||||
for item in chat_logs:
|
||||
item_payload = item.payload if isinstance(item.payload, dict) else {}
|
||||
if str(item_payload.get("taskId") or "").strip().upper() == str(task.task_no or "").strip().upper():
|
||||
existing = item
|
||||
break
|
||||
|
||||
if existing:
|
||||
existing.answer = content
|
||||
existing.payload = payload
|
||||
return
|
||||
|
||||
db.session.add(
|
||||
ChatLog(
|
||||
user_id=task.user_id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session_id,
|
||||
session_id=session_id,
|
||||
query="",
|
||||
answer=content,
|
||||
message_type="shipping-parse-review",
|
||||
payload=payload,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def recompute_batch_summary(batch: ShippingBatch | None) -> None:
|
||||
"""写路径:重算批次汇总并校正 current_focus_task_no。"""
|
||||
if not batch:
|
||||
@@ -62,6 +134,17 @@ def recompute_batch_summary(batch: ShippingBatch | None) -> None:
|
||||
tasks = list_sorted_batch_tasks(batch)
|
||||
batch.file_count = max(int(batch.file_count or 0), len(tasks) or 0)
|
||||
batch.process_summary_json = compute_batch_process_summary(tasks)
|
||||
next_focus = next(
|
||||
(
|
||||
item.task_no
|
||||
for item in tasks
|
||||
if str(item.process_status or "").strip() not in {"uploaded", "completed", "closed", "rejected"}
|
||||
),
|
||||
None,
|
||||
)
|
||||
if next_focus:
|
||||
batch.current_focus_task_no = next_focus
|
||||
return
|
||||
if not batch.current_focus_task_no:
|
||||
batch.current_focus_task_no = tasks[0].task_no if tasks else None
|
||||
return
|
||||
@@ -410,6 +493,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7):
|
||||
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
|
||||
log_task_event(task, "parse_needs_review", {"confidence": confidence, "warnings": warnings})
|
||||
_upsert_parse_review_chat_message(task)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
@@ -721,6 +805,68 @@ def remove_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
|
||||
def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
重置单个任务到可重新自动推进的状态,并重新交给后台编排器。
|
||||
【AI 触发时机】:当用户要求“重试当前票”“重新跑这张单据”时调用。
|
||||
|
||||
核心逻辑:保留解析/库存/匹配等业务真相字段,仅清理错误与人工阻断,再恢复到当前数据所对应的最近可续跑状态。
|
||||
Args:
|
||||
payload: 必须能定位 task;可选 comment 记录重试原因。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: Tool 标准响应,返回重置后的任务状态与是否成功触发后台编排。
|
||||
"""
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
|
||||
comment = str(payload.get("comment") or "").strip()
|
||||
task.review_status = None
|
||||
task.pending_human_reason = None
|
||||
task.error_message = None
|
||||
|
||||
if not task.raw_content and not task.lines_json:
|
||||
task.process_status = "created"
|
||||
elif task.lines_json:
|
||||
if task.export_file_path:
|
||||
task.process_status = "matched"
|
||||
elif task.inventory_lines_json:
|
||||
task.process_status = "inventory_ready"
|
||||
else:
|
||||
task.process_status = "parsed"
|
||||
else:
|
||||
task.process_status = "created"
|
||||
|
||||
log_task_event(
|
||||
task,
|
||||
"task_retry_requested",
|
||||
{
|
||||
"comment": comment,
|
||||
"restored_process_status": task.process_status,
|
||||
},
|
||||
)
|
||||
sync_batch_after_task_change(task)
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||
|
||||
started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message=(
|
||||
f"已重试任务 {task.task_no},后台已重新开始处理。"
|
||||
if started
|
||||
else f"已重置任务 {task.task_no},请稍后再试。"
|
||||
),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"orchestrator_started": started,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def get_task_status(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
查询任务当前进度(Tool / 工作台共用)。
|
||||
|
||||
@@ -18,6 +18,7 @@ parse_notice = task_workflow.parse_notice
|
||||
auto_progress = task_workflow.auto_progress
|
||||
submit_decision = task_workflow.submit_decision
|
||||
get_task_status = task_workflow.get_task_status
|
||||
retry_task = task_workflow.retry_task
|
||||
update_notice_fields = task_workflow.update_notice_fields
|
||||
update_notice_line = task_workflow.update_notice_line
|
||||
add_notice_line = task_workflow.add_notice_line
|
||||
|
||||
@@ -23,9 +23,11 @@ def _shipping_notice_stable_auto_config(app, request):
|
||||
if request.node.get_closest_marker("auto_rpa"):
|
||||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
|
||||
return
|
||||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
|
||||
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
|
||||
|
||||
|
||||
def pytest_configure(config):
|
||||
|
||||
@@ -389,6 +389,81 @@ def test_file_check_tool_start_records_chat_log_bind_context(app, client, monkey
|
||||
assert resolve_run_id_for_chat_log(session_id='bind-on-start', query='执行 RoHS 检核') == run_id
|
||||
|
||||
|
||||
def test_file_check_tool_no_data_does_not_create_run_or_bind_context(app, client, monkeypatch):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
task_id = task.id
|
||||
before_count = ScheduleRun.query.filter_by(schedule_task_id=task_id).count()
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools._precheck_no_data', lambda _task: {
|
||||
'ok': False,
|
||||
'error_code': 'no_data_to_check',
|
||||
'message': '目前没有资料需要检核',
|
||||
'task': {'task_id': _task.id, 'task_name': _task.name},
|
||||
})
|
||||
|
||||
res = client.post(
|
||||
'/api/file-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={
|
||||
'task_id': task_id,
|
||||
'hxops_session_id': 'no-data-session',
|
||||
'hxops_turn_id': 'no-data-turn',
|
||||
'user_message': '立即执行检核',
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['ok'] is False
|
||||
assert data['error_code'] == 'no_data_to_check'
|
||||
assert 'run' not in data
|
||||
|
||||
with app.app_context():
|
||||
after_count = ScheduleRun.query.filter_by(schedule_task_id=task_id).count()
|
||||
assert after_count == before_count
|
||||
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
|
||||
|
||||
assert resolve_run_id_for_chat_log(turn_id='no-data-turn') is None
|
||||
assert resolve_run_id_for_chat_log(session_id='no-data-session', query='立即执行检核') is None
|
||||
|
||||
|
||||
def test_file_check_tool_no_data_keeps_existing_running_conflict_priority(app, client, monkeypatch):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ROHS-NO-DATA-CONFLICT',
|
||||
schedule_task_id=task.id,
|
||||
status='running',
|
||||
trigger_type='manual',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
task_id = task.id
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools._precheck_no_data', lambda _task: {
|
||||
'ok': False,
|
||||
'error_code': 'no_data_to_check',
|
||||
'message': '目前没有资料需要检核',
|
||||
'task': {'task_id': _task.id, 'task_name': _task.name},
|
||||
})
|
||||
|
||||
res = client.post(
|
||||
'/api/file-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={'task_id': task_id},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'check_running'
|
||||
assert data.get('run', {}).get('run_id')
|
||||
|
||||
|
||||
def test_file_check_tool_requires_task_id(app, client):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
|
||||
@@ -7,9 +7,12 @@
|
||||
4. 工作台批量上传通知时仅保存 raw_text,首轮解析延后到 Dify。
|
||||
"""
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingBatch, ShippingTask, User
|
||||
from app.models import Agent, ChatSession, ShippingBatch, ShippingTask, User
|
||||
from app.auth_jwt import issue_local_access_token
|
||||
from app.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs
|
||||
|
||||
|
||||
def _tool_headers(app):
|
||||
@@ -148,7 +151,7 @@ def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client):
|
||||
"/api/workspace/shipping-batches/create-from-notices",
|
||||
headers=headers,
|
||||
data={
|
||||
"files": (__import__("io").BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
|
||||
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
|
||||
"conversation_id": "conv-workspace-batch-001",
|
||||
},
|
||||
content_type="multipart/form-data",
|
||||
@@ -169,6 +172,209 @@ def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client):
|
||||
assert len(task.lines_json or []) == 0
|
||||
|
||||
|
||||
def test_workspace_create_batch_from_notices_starts_orchestrator_when_enabled(app, client, monkeypatch):
|
||||
"""开启编排器时,工作台上传接口应返回 orchestrator_started。"""
|
||||
headers = _workspace_headers(app)
|
||||
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY"] = True
|
||||
started: list[str] = []
|
||||
|
||||
def fake_start(batch_no: str | None) -> bool:
|
||||
if batch_no:
|
||||
started.append(batch_no)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(batch_orchestrator, "start_batch_orchestrator", fake_start)
|
||||
|
||||
res = client.post(
|
||||
"/api/workspace/shipping-batches/create-from-notices",
|
||||
headers=headers,
|
||||
data={
|
||||
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
|
||||
"conversation_id": "conv-workspace-batch-002",
|
||||
},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data["status"] == "ok"
|
||||
assert data["data"]["orchestrator_started"] is True
|
||||
assert started == [data["batch_no"]]
|
||||
|
||||
|
||||
def test_run_single_task_routes_created_task_to_dify_executor(app, monkeypatch):
|
||||
"""编排器遇到 created 任务时应调用后台 Dify 执行器。"""
|
||||
with app.app_context():
|
||||
batch = ShippingBatch(batch_no="SB-ORCH-PARSE", file_count=1)
|
||||
task = ShippingTask(
|
||||
task_no="SN-20260622-AAAA0001",
|
||||
batch=batch,
|
||||
source_type="manual",
|
||||
raw_content="客户:ACME\nA001 x 10",
|
||||
process_status="created",
|
||||
)
|
||||
db.session.add_all([batch, task])
|
||||
db.session.commit()
|
||||
task_no = task.task_no
|
||||
|
||||
called: dict[str, object] = {}
|
||||
|
||||
def fake_dify(task_ref: str):
|
||||
called["dify"] = task_ref
|
||||
return {"status": "ok", "message": "parsed-by-dify"}
|
||||
|
||||
def fake_auto_progress(payload):
|
||||
raise AssertionError("created task should not call auto_progress when auto_progress is disabled")
|
||||
|
||||
monkeypatch.setattr(batch_orchestrator, "run_shipping_parse_via_dify", fake_dify)
|
||||
monkeypatch.setattr(batch_orchestrator, "auto_progress", fake_auto_progress)
|
||||
|
||||
result = batch_orchestrator._run_single_task(task.task_no)
|
||||
assert result["status"] == "ok"
|
||||
assert called.get("dify") == task_no
|
||||
|
||||
|
||||
def test_run_single_task_routes_non_created_task_to_auto_progress(app, monkeypatch):
|
||||
"""编排器遇到非 created 且无人工阻塞的任务时应调用 auto_progress。"""
|
||||
with app.app_context():
|
||||
batch = ShippingBatch(batch_no="SB-ORCH-AUTO", file_count=1)
|
||||
task = ShippingTask(
|
||||
task_no="SN-20260622-BBBB0002",
|
||||
batch=batch,
|
||||
source_type="manual",
|
||||
process_status="parsed",
|
||||
)
|
||||
db.session.add_all([batch, task])
|
||||
db.session.commit()
|
||||
task_no = task.task_no
|
||||
|
||||
called: dict[str, object] = {}
|
||||
|
||||
def fake_dify(task_ref: str):
|
||||
raise AssertionError(f"parsed task should not call dify parse executor: {task_ref}")
|
||||
|
||||
def fake_auto_progress(payload):
|
||||
called["auto_progress"] = payload
|
||||
return {"status": "ok", "message": "advanced"}
|
||||
|
||||
monkeypatch.setattr(batch_orchestrator, "run_shipping_parse_via_dify", fake_dify)
|
||||
monkeypatch.setattr(batch_orchestrator, "auto_progress", fake_auto_progress)
|
||||
|
||||
result = batch_orchestrator._run_single_task(task.task_no)
|
||||
assert result["status"] == "ok"
|
||||
assert isinstance(called.get("auto_progress"), dict)
|
||||
assert called["auto_progress"]["task_id"] == task_no
|
||||
|
||||
|
||||
def test_run_shipping_parse_via_dify_passes_task_context_and_updates_session(app, monkeypatch):
|
||||
"""后台 Dify 执行器应带上当前任务上下文,并回写 provider conversation id。"""
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username="shipping_dify_user",
|
||||
email="shipping_dify_user@example.com",
|
||||
role="user",
|
||||
status="active",
|
||||
)
|
||||
user.set_password("password")
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
|
||||
agent = Agent(
|
||||
name="货代发货通知 Agent",
|
||||
dify_api_key="test-dify-key",
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
|
||||
session = ChatSession(
|
||||
session_id="conv-shipping-dify-001",
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
title="shipping parse",
|
||||
status="running",
|
||||
)
|
||||
batch = ShippingBatch(
|
||||
batch_no="SB-DIFY-EXEC",
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
file_count=1,
|
||||
)
|
||||
task = ShippingTask(
|
||||
task_no="SN-20260622-CCCC0003",
|
||||
batch=batch,
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
source_type="manual",
|
||||
raw_content="客户:ACME\nA001 x 10",
|
||||
process_status="created",
|
||||
)
|
||||
db.session.add_all([session, batch, task])
|
||||
db.session.commit()
|
||||
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def fake_stream_chat(query, user_id, agent_obj, conversation_id=None, **kwargs):
|
||||
captured["query"] = query
|
||||
captured["user_id"] = user_id
|
||||
captured["agent_id"] = agent_obj.id
|
||||
captured["conversation_id"] = conversation_id
|
||||
captured["session_id"] = kwargs.get("session_id")
|
||||
captured["inputs"] = kwargs.get("inputs")
|
||||
yield 'data: {"event":"message_end","conversation_id":"11111111-1111-1111-1111-111111111111","answer":"parsed"}\n\n'
|
||||
|
||||
monkeypatch.setattr(dify_executor.DifyService, "stream_chat", staticmethod(fake_stream_chat))
|
||||
|
||||
result = dify_executor.run_shipping_parse_via_dify(task.task_no)
|
||||
assert result["status"] == "ok"
|
||||
assert captured["user_id"] == user.id
|
||||
assert captured["agent_id"] == agent.id
|
||||
assert captured["session_id"] == session.session_id
|
||||
assert isinstance(captured["inputs"], dict)
|
||||
assert captured["inputs"]["entry_mode"] == "orchestrator_parse"
|
||||
assert captured["inputs"]["trigger_source"] == "backend_orchestrator"
|
||||
assert captured["inputs"]["user_message"] == ""
|
||||
assert captured["inputs"]["current_task_no"] == task.task_no
|
||||
assert captured["inputs"]["current_batch_no"] == batch.batch_no
|
||||
refreshed_session = ChatSession.query.filter_by(session_id=session.session_id).first()
|
||||
assert refreshed_session is not None
|
||||
assert refreshed_session.external_conversation_id == "11111111-1111-1111-1111-111111111111"
|
||||
|
||||
|
||||
def test_build_dify_chat_inputs_supports_unified_frontend_fields(app):
|
||||
"""统一版 Dify inputs 应同时包含 entry_mode/user_message/trigger_source。"""
|
||||
with app.app_context():
|
||||
batch = ShippingBatch(
|
||||
batch_no="SB-DIFY-INPUTS",
|
||||
conversation_id="conv-shipping-inputs-001",
|
||||
current_focus_task_no="SN-20260622-DDDD0004",
|
||||
file_count=1,
|
||||
)
|
||||
task = ShippingTask(
|
||||
task_no="SN-20260622-DDDD0004",
|
||||
batch=batch,
|
||||
conversation_id="conv-shipping-inputs-001",
|
||||
source_type="manual",
|
||||
process_status="created",
|
||||
)
|
||||
db.session.add_all([batch, task])
|
||||
db.session.commit()
|
||||
|
||||
inputs = dify_inputs.build_dify_chat_inputs(
|
||||
"conv-shipping-inputs-001",
|
||||
entry_mode="user_chat",
|
||||
user_message="这票现在什么状态?",
|
||||
trigger_source="frontend_chat",
|
||||
)
|
||||
|
||||
assert inputs["entry_mode"] == "user_chat"
|
||||
assert inputs["conversation_id"] == "conv-shipping-inputs-001"
|
||||
assert inputs["current_batch_no"] == "SB-DIFY-INPUTS"
|
||||
assert inputs["current_task_no"] == "SN-20260622-DDDD0004"
|
||||
assert inputs["user_message"] == "这票现在什么状态?"
|
||||
assert inputs["trigger_source"] == "frontend_chat"
|
||||
|
||||
|
||||
def test_create_empty_batch_returns_batch_shell(app, client):
|
||||
"""验证无 notice_items 时仍可创建批次壳,供后续续办。"""
|
||||
headers = _tool_headers(app)
|
||||
|
||||
+35
-4
@@ -13,7 +13,6 @@ import sys
|
||||
|
||||
from app import create_app
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.runner import run_forever
|
||||
|
||||
_LOG_FORMAT = '%(asctime)s %(levelname)s [worker] %(message)s'
|
||||
|
||||
@@ -28,6 +27,18 @@ def _configure_logging() -> logging.Logger:
|
||||
return logger
|
||||
|
||||
|
||||
def _resolve_processor(queue_name: str):
|
||||
if queue_name == 'kb':
|
||||
from app.services.knowledge_cleaning.queue_service import process_next_kb_job
|
||||
|
||||
return process_next_kb_job
|
||||
if queue_name == 'shipping':
|
||||
from app.services.shipping_notice.queue_service import process_next_shipping_notice_job
|
||||
|
||||
return process_next_shipping_notice_job
|
||||
raise ValueError(f'Unsupported queue: {queue_name}')
|
||||
|
||||
|
||||
def main(*, queues: list[str] | None = None, config_name: str = 'default') -> None:
|
||||
"""
|
||||
启动 worker 主循环。
|
||||
@@ -38,14 +49,34 @@ def main(*, queues: list[str] | None = None, config_name: str = 'default') -> No
|
||||
logger = _configure_logging()
|
||||
app = create_app(config_name)
|
||||
with app.app_context():
|
||||
import app.jobs.handlers # noqa: F401
|
||||
|
||||
ctx = JobContext(
|
||||
config=dict(app.config),
|
||||
logger=logger,
|
||||
extras={'queues': queues or ['kb']},
|
||||
)
|
||||
logger.info('Worker starting queues=%s (skeleton — Wave 2 enables job processing)', ctx.extras['queues'])
|
||||
# Wave 2: import app.jobs.handlers # noqa: F401 — register handlers
|
||||
run_forever(ctx)
|
||||
queue_names = ctx.extras['queues']
|
||||
poll_seconds = 2.0
|
||||
if 'shipping' in queue_names:
|
||||
poll_seconds = float(app.config.get('SHIPPING_NOTICE_WORKER_POLL_SECONDS', poll_seconds))
|
||||
elif 'kb' in queue_names:
|
||||
poll_seconds = float(app.config.get('KB_WORKER_POLL_SECONDS', poll_seconds))
|
||||
|
||||
logger.info('Worker starting queues=%s poll_seconds=%s', queue_names, poll_seconds)
|
||||
processors = [_resolve_processor(name) for name in queue_names]
|
||||
|
||||
import time
|
||||
|
||||
while True:
|
||||
handled = False
|
||||
for processor in processors:
|
||||
processed, message = processor()
|
||||
if processed:
|
||||
handled = True
|
||||
logger.info('processed job: %s', message)
|
||||
if not handled:
|
||||
time.sleep(poll_seconds)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"""
|
||||
backend/workers/worker_shipping_notice.py
|
||||
|
||||
用途:货代发货 worker Supervisor / Compose 兼容启动脚本。
|
||||
逻辑:转调 backend/worker.py,默认只消费 shipping 队列。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_backend_root = Path(__file__).resolve().parents[1]
|
||||
if str(_backend_root) not in sys.path:
|
||||
sys.path.insert(0, str(_backend_root))
|
||||
|
||||
from worker import main
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(queues=['shipping'])
|
||||
+136
-16
@@ -1457,18 +1457,53 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输
|
||||
| 输出名 | Dify 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `ok` | Boolean | API `ok` 字段 |
|
||||
| `error_code` | String | 如 `check_running` / `task_not_found` |
|
||||
| `error_code` | String | 如 `check_running` / `no_data_to_check` / `task_not_found` |
|
||||
| `message` | String | 提示或错误文案 |
|
||||
| `run_id` | String | 检核批次 ID |
|
||||
| `run_no` | String | 检核批次编号 |
|
||||
| `run_status` | String | `running` / `success` / `failed` 等 |
|
||||
| `run_status_label` | String | 批次状态中文文案 |
|
||||
| `task_name` | String | 检核任务名称 |
|
||||
| `started_at` | String | ISO 时间字符串 |
|
||||
| `started_at_display` | String | 按北京时间格式化的启动时间 |
|
||||
| `scene` | String | `started` / `already_running` / `no_data` / `failed` |
|
||||
| `has_run_id` | Boolean | 是否拿到了有效批次 ID |
|
||||
|
||||
**完整 Python 代码**
|
||||
|
||||
```python
|
||||
import json
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
_CN_TZ = timezone(timedelta(hours=8))
|
||||
|
||||
_STATUS_LABEL = {
|
||||
"queued": "排队中",
|
||||
"running": "进行中",
|
||||
"success": "已完成",
|
||||
"partial_failed": "部分失败",
|
||||
"failed": "失败",
|
||||
"cancelled": "已取消",
|
||||
}
|
||||
|
||||
_DEFAULT_TASK_NAME = "RoHS 文件检核"
|
||||
|
||||
|
||||
def _empty_result(message: str = "") -> dict:
|
||||
return {
|
||||
"ok": False,
|
||||
"error_code": "invalid_response",
|
||||
"message": message,
|
||||
"run_id": "",
|
||||
"run_no": "",
|
||||
"run_status": "",
|
||||
"run_status_label": "",
|
||||
"task_name": "",
|
||||
"started_at": "",
|
||||
"started_at_display": "",
|
||||
"scene": "failed",
|
||||
"has_run_id": False,
|
||||
}
|
||||
|
||||
def _load_tool_json(tool_json, tool_text):
|
||||
if isinstance(tool_json, list) and tool_json:
|
||||
@@ -1487,25 +1522,91 @@ def _load_tool_json(tool_json, tool_text):
|
||||
return {}
|
||||
return {}
|
||||
|
||||
def main(tool_json, tool_text) -> dict:
|
||||
empty = {
|
||||
"ok": False, "error_code": "invalid_response", "message": "",
|
||||
"run_id": "", "run_no": "", "run_status": "", "task_name": "", "started_at": "",
|
||||
}
|
||||
def _format_started_at(iso_str) -> str:
|
||||
if not iso_str:
|
||||
return ""
|
||||
|
||||
s = str(iso_str).strip()
|
||||
if not s:
|
||||
return ""
|
||||
|
||||
if s.endswith("Z"):
|
||||
s = s[:-1] + "+00:00"
|
||||
|
||||
try:
|
||||
dt = datetime.fromisoformat(s)
|
||||
except ValueError:
|
||||
return str(iso_str)
|
||||
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
|
||||
local = dt.astimezone(_CN_TZ)
|
||||
return f"{local.year}年{local.month}月{local.day}日 {local.hour:02d}:{local.minute:02d}"
|
||||
|
||||
|
||||
def _status_label(status: str) -> str:
|
||||
key = str(status or "").strip().lower()
|
||||
if not key:
|
||||
return ""
|
||||
return _STATUS_LABEL.get(key, status)
|
||||
|
||||
|
||||
def _resolve_scene(ok: bool, error_code: str) -> str:
|
||||
code = str(error_code or "").strip()
|
||||
if ok:
|
||||
return "started"
|
||||
if code == "check_running":
|
||||
return "already_running"
|
||||
if code == "no_data_to_check":
|
||||
return "no_data"
|
||||
return "failed"
|
||||
|
||||
|
||||
def _safe_str(value) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def main(tool_json, tool_text: str = "") -> dict:
|
||||
data = _load_tool_json(tool_json, tool_text)
|
||||
|
||||
if not data:
|
||||
empty["message"] = "无 Tool 响应"
|
||||
empty = _empty_result("目前没有资料需要检核。")
|
||||
empty["error_code"] = "no_data_to_check"
|
||||
empty["scene"] = "no_data"
|
||||
return empty
|
||||
|
||||
run = data.get("run") or {}
|
||||
if not isinstance(run, dict):
|
||||
run = {}
|
||||
|
||||
ok = bool(data.get("ok"))
|
||||
error_code = _safe_str(data.get("error_code"))
|
||||
message = _safe_str(data.get("message"))
|
||||
|
||||
run_id = _safe_str(run.get("run_id"))
|
||||
run_no = _safe_str(run.get("run_no"))
|
||||
run_status = _safe_str(run.get("status"))
|
||||
task_name = _safe_str(
|
||||
run.get("task_name") or run.get("schedule_name") or _DEFAULT_TASK_NAME
|
||||
)
|
||||
started_at = _safe_str(run.get("started_at"))
|
||||
|
||||
return {
|
||||
"ok": bool(data.get("ok")),
|
||||
"error_code": str(data.get("error_code") or ""),
|
||||
"message": str(data.get("message") or ""),
|
||||
"run_id": str(run.get("run_id") or ""),
|
||||
"run_no": str(run.get("run_no") or ""),
|
||||
"run_status": str(run.get("status") or ""),
|
||||
"task_name": str(run.get("task_name") or run.get("schedule_name") or ""),
|
||||
"started_at": str(run.get("started_at") or ""),
|
||||
"ok": ok,
|
||||
"error_code": error_code,
|
||||
"message": message,
|
||||
"run_id": run_id,
|
||||
"run_no": run_no,
|
||||
"run_status": run_status,
|
||||
"run_status_label": _status_label(run_status),
|
||||
"task_name": task_name,
|
||||
"started_at": started_at,
|
||||
"started_at_display": _format_started_at(started_at),
|
||||
"scene": _resolve_scene(ok, error_code),
|
||||
"has_run_id": bool(run_id),
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1525,6 +1626,7 @@ def main(tool_json, tool_text) -> dict:
|
||||
| --- | --- |
|
||||
| `解析启动检核响应.ok == true` | [§3.11 Answer:检核已启动](#311-answer检核已启动) |
|
||||
| `解析启动检核响应.error_code == "check_running"` | [§3.12 Answer:检核进行中](#312-answer检核进行中) |
|
||||
| `解析启动检核响应.error_code == "no_data_to_check"` | [§3.13 Answer:没有资料需要检核](#313-answer没有资料需要检核) |
|
||||
| 默认 | [§3.24 Answer:错误兜底(启动检核 body)](#324-answer错误兜底启动检核) |
|
||||
|
||||
---
|
||||
@@ -1572,6 +1674,24 @@ def main(tool_json, tool_text) -> dict:
|
||||
|
||||
---
|
||||
|
||||
### 3.13 Answer:没有资料需要检核
|
||||
|
||||
**上游**:IF 启动业务分支(`error_code == "no_data_to_check"`)
|
||||
|
||||
**引用变量**:`解析启动检核响应.message` · **String**
|
||||
|
||||
**回复模板**
|
||||
|
||||
```text
|
||||
目前没有资料需要检核,暂时不用启动本次检核。
|
||||
|
||||
{{#解析启动检核响应.message#}}
|
||||
|
||||
如果后续有新的资料进入检核范围,再发起一次即可。
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3.14 Code:提取查询参数
|
||||
|
||||
**上游**:IF 意图分类(`check_status` 分支)
|
||||
@@ -2031,7 +2151,7 @@ def main(tool_json, tool_text) -> dict:
|
||||
|
||||
### 3.24 Answer:错误兜底(启动检核 body)
|
||||
|
||||
**上游**:IF 启动业务分支(Tool **成功出口** 后,body 中 `ok=false` 且非 `check_running`;如 `invalid_response`)
|
||||
**上游**:IF 启动业务分支(Tool **成功出口** 后,body 中 `ok=false` 且非 `check_running`、`no_data_to_check`;如 `invalid_response`)
|
||||
|
||||
**引用变量**:`解析启动检核响应.message` · **String**;`解析启动检核响应.error_code` · **String**
|
||||
|
||||
|
||||
@@ -157,6 +157,15 @@
|
||||
"raw_text": {
|
||||
"type": "string",
|
||||
"description": "待解析的发货通知全文"
|
||||
},
|
||||
"structured": {
|
||||
"type": "object",
|
||||
"description": "Dify LLM 解析后的结构化结果对象。若提供,后端优先使用该对象中的 lines/confidence/reservation_id 等字段落库。",
|
||||
"additionalProperties": true
|
||||
},
|
||||
"lang": {
|
||||
"type": "string",
|
||||
"description": "可选语言代码:zh|en|th"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -935,4 +944,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -214,6 +214,49 @@ export async function switchWorkspaceShippingBatchFocusTask(batchNo: string, tas
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试当前发货任务。
|
||||
* @param taskNo - 发货任务编号
|
||||
* @param comment - 可选重试备注
|
||||
* @returns 重试结果
|
||||
*/
|
||||
export async function retryWorkspaceShippingTask(taskNo: string, comment?: string) {
|
||||
const res = await fetch(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/retry`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(comment ? { comment } : {}),
|
||||
},
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试批次中仍可自动推进的任务。
|
||||
* @param batchNo - 批次编号
|
||||
* @returns 批次重试结果
|
||||
*/
|
||||
export async function retryWorkspaceShippingBatchPending(batchNo: string) {
|
||||
const res = await fetch(
|
||||
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/retry-pending`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as { status?: string; message?: string; error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交人工决策。
|
||||
* @param taskNo - 发货任务编号
|
||||
@@ -390,6 +433,28 @@ export async function autoProgressWorkspaceShippingTask(taskNo: string, lang?: s
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* 以用户态触发通知解析,供批量上传后逐任务补齐首轮解析。
|
||||
* @param taskNo - 发货任务编号
|
||||
* @param lang - 可选语言代码
|
||||
* @returns 解析与可能的自动推进结果
|
||||
*/
|
||||
export async function parseWorkspaceShippingNotice(taskNo: string, lang?: string) {
|
||||
const res = await fetch(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/parse-notice`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(lang ? { lang } : {}),
|
||||
},
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记货代系统已人工上传完成。
|
||||
* @param taskNo - 发货任务编号
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* features/chat/components/ChatViewContent.vue
|
||||
* 对话页主区域:侧栏、消息列表、输入栏与内置浏览器。
|
||||
* 用途:对话页主区域,组合侧栏、发货批次进度区、消息列表、输入栏与内置浏览器。
|
||||
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingBatchProgressPanel、chat.context。
|
||||
* 逻辑:本文件只做页面结构编排;发货批次进度样式与任务续办交互下沉到独立面板组件。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Loader2 } from 'lucide-vue-next';
|
||||
import ChatShell from '@/shared/layouts/ChatShell.vue';
|
||||
import ChatSidebar from '@/features/chat/components/ChatSidebar.vue';
|
||||
@@ -12,91 +12,10 @@ import ChatInputBar from '@/features/chat/components/ChatInputBar.vue';
|
||||
import ChatMessageList from '@/features/chat/components/ChatMessageList.vue';
|
||||
import ChatMobileHeader from '@/features/chat/components/ChatMobileHeader.vue';
|
||||
import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
|
||||
import ShippingWorkflowStepper from '@/features/chat/components/ShippingWorkflowStepper.vue';
|
||||
import ShippingBatchProgressPanel from '@/features/chat/components/ShippingBatchProgressPanel.vue';
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
import { buildShippingWorkflowSteps } from '@/features/chat/shipping';
|
||||
import type { ShippingCurrentStepProgress, ShippingTaskSummary } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const page = useChatPageContext();
|
||||
const { t } = useI18n();
|
||||
|
||||
const statusMeta = (status?: string | null) => {
|
||||
const map: Record<string, { label: string; chip: string }> = {
|
||||
created: { label: t('chat.shippingNoticeUi.status.created'), chip: 'bg-slate-100 text-slate-700' },
|
||||
waiting_inventory: { label: t('chat.shippingNoticeUi.status.waitingInventory'), chip: 'bg-amber-100 text-amber-700' },
|
||||
inventory_ready: { label: t('chat.shippingNoticeUi.status.inventoryReady'), chip: 'bg-sky-100 text-sky-700' },
|
||||
matched: { label: t('chat.shippingNoticeUi.status.matched'), chip: 'bg-emerald-100 text-emerald-700' },
|
||||
waiting_upload: { label: t('chat.shippingNoticeUi.status.waitingUpload'), chip: 'bg-orange-100 text-orange-700' },
|
||||
uploaded: { label: t('chat.shippingNoticeUi.status.uploaded'), chip: 'bg-emerald-100 text-emerald-700' },
|
||||
upload_failed: { label: t('chat.shippingNoticeUi.status.uploadFailed'), chip: 'bg-rose-100 text-rose-700' },
|
||||
rejected: { label: t('chat.shippingNoticeUi.status.rejected'), chip: 'bg-rose-100 text-rose-700' },
|
||||
closed: { label: t('chat.shippingNoticeUi.status.closed'), chip: 'bg-slate-100 text-slate-700' },
|
||||
};
|
||||
return map[String(status || '').trim()] || { label: String(status || t('chat.shippingNoticeUi.processing')), chip: 'bg-slate-100 text-slate-700' };
|
||||
};
|
||||
|
||||
const stepLabel = (step?: string | null) => {
|
||||
const map: Record<string, string> = {
|
||||
step1_notice_submit: t('chat.shippingNoticeUi.currentStep.noticeParse'),
|
||||
step2_parse_confirm: t('chat.shippingNoticeUi.currentStep.parseConfirm'),
|
||||
step3_inventory_prepare: t('chat.shippingNoticeUi.currentStep.inventoryPrepare'),
|
||||
step4_align_confirm: t('chat.shippingNoticeUi.currentStep.alignConfirm'),
|
||||
step5_match_inventory: t('chat.shippingNoticeUi.currentStep.inventoryMatch'),
|
||||
step6_generate_file: t('chat.shippingNoticeUi.currentStep.generateExcel'),
|
||||
step7_upload_freight: t('chat.shippingNoticeUi.currentStep.uploadFreight'),
|
||||
step2_inventory_prepare: t('chat.shippingNoticeUi.currentStep.inventoryPrepare'),
|
||||
step3_inventory_match: t('chat.shippingNoticeUi.currentStep.inventoryMatch'),
|
||||
step4_shortage_review: t('chat.shippingNoticeUi.currentStep.shortageHandle'),
|
||||
step5_export_excel: t('chat.shippingNoticeUi.currentStep.generateExcel'),
|
||||
step6_upload_freight: t('chat.shippingNoticeUi.currentStep.uploadFreight'),
|
||||
step7_finish: t('chat.shippingNoticeUi.currentStep.finishArchive'),
|
||||
};
|
||||
return map[String(step || '').trim()] || t('chat.shippingNoticeUi.processing');
|
||||
};
|
||||
|
||||
const currentShippingTask = computed<ShippingTaskSummary | null>(() => {
|
||||
const focusTaskNo = String(page.shippingBatchSummary?.current_focus_task_no || '').trim();
|
||||
if (!focusTaskNo || !Array.isArray(page.shippingBatchTasks)) return null;
|
||||
return page.shippingBatchTasks.find((task: ShippingTaskSummary) => task.task_no === focusTaskNo) || null;
|
||||
});
|
||||
|
||||
const currentShippingTaskSource = computed(() => currentShippingTask.value || page.activeShippingTaskDetail || null);
|
||||
const currentShippingSteps = computed(() => buildShippingWorkflowSteps(currentShippingTaskSource.value));
|
||||
const currentShippingStepProgress = computed<ShippingCurrentStepProgress | null>(() => {
|
||||
const payload = currentShippingTaskSource.value?.step_payload;
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
const progress = (payload as Record<string, unknown>).current_step_progress;
|
||||
return progress && typeof progress === 'object' ? progress as ShippingCurrentStepProgress : null;
|
||||
});
|
||||
const currentShippingBatchProgress = computed(() => {
|
||||
const task = currentShippingTask.value;
|
||||
if (!task?.batch_index || !task?.batch_total) return '';
|
||||
return t('chat.shippingNoticeUi.batchProgress', { index: task.batch_index, total: task.batch_total });
|
||||
});
|
||||
const batchCompletedCount = computed(() =>
|
||||
Number(page.shippingBatchSummary?.process_summary?.completed || 0),
|
||||
);
|
||||
const batchRunningCount = computed(() =>
|
||||
Number(page.shippingBatchSummary?.process_summary?.running || 0),
|
||||
);
|
||||
const batchPendingCount = computed(() =>
|
||||
Number(page.shippingBatchSummary?.process_summary?.pending || 0),
|
||||
);
|
||||
const batchFileCount = computed(() =>
|
||||
Number(page.shippingBatchSummary?.file_count || 0),
|
||||
);
|
||||
const batchCurrentIndex = computed(() =>
|
||||
Number(
|
||||
currentShippingTask.value?.batch_index
|
||||
|| page.activeShippingTaskDetail?.batch_index
|
||||
|| page.shippingBatchSummary?.process_summary?.current_index
|
||||
|| 0,
|
||||
),
|
||||
);
|
||||
const batchCompletionPercent = computed(() => {
|
||||
if (!batchFileCount.value) return 0;
|
||||
return Math.min(100, Math.max(0, Math.round((batchCompletedCount.value / batchFileCount.value) * 100)));
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -164,230 +83,17 @@ const batchCompletionPercent = computed(() => {
|
||||
<template v-else>
|
||||
<div class="flex min-h-0 flex-1">
|
||||
<div class="flex min-h-0 flex-1 flex-col">
|
||||
<div
|
||||
v-if="page.isShippingNoticeAgent && (page.shippingBatchSummary || currentShippingTaskSource)"
|
||||
class="mx-4 mt-4 rounded-3xl border border-default/80 bg-[linear-gradient(135deg,rgba(255,255,255,0.96),rgba(246,248,251,0.92))] px-4 py-3 shadow-sm"
|
||||
>
|
||||
<div class="flex flex-wrap items-start justify-between gap-3">
|
||||
<div class="space-y-1">
|
||||
<div class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted">
|
||||
{{ page.shippingBatchSummary ? t('chat.shippingNoticeUi.batchTitle') : t('chat.shippingNoticeUi.taskTitle') }}
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span
|
||||
v-if="page.shippingBatchSummary"
|
||||
class="font-mono text-sm font-semibold text-primary"
|
||||
>
|
||||
{{ page.shippingBatchSummary.batch_no }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="currentShippingTaskSource"
|
||||
class="font-mono text-sm font-semibold text-primary"
|
||||
>
|
||||
{{ currentShippingTaskSource.task_no }}
|
||||
</span>
|
||||
<span
|
||||
v-if="page.shippingBatchSummary?.current_focus_task_no"
|
||||
class="rounded-full bg-brand-50 px-2.5 py-1 text-xs font-medium text-brand-700"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.currentTask', { taskId: page.shippingBatchSummary.current_focus_task_no }) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="currentShippingBatchProgress"
|
||||
class="rounded-full bg-sky-50 px-2.5 py-1 text-xs font-medium text-sky-700"
|
||||
>
|
||||
{{ currentShippingBatchProgress }}
|
||||
</span>
|
||||
<span
|
||||
v-if="batchCurrentIndex"
|
||||
class="rounded-full bg-amber-50 px-2.5 py-1 text-xs font-medium text-amber-700"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.batchCurrentIndex', { index: batchCurrentIndex, total: batchFileCount }) }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="currentShippingTaskSource" class="flex flex-wrap items-center gap-2 text-xs text-secondary">
|
||||
<span class="truncate font-medium text-primary">
|
||||
{{ currentShippingTaskSource.customer_name || currentShippingTaskSource.source_file_name || t('chat.shippingNoticeUi.currentNotice') }}
|
||||
</span>
|
||||
<span
|
||||
class="rounded-full px-2 py-0.5 font-medium"
|
||||
:class="statusMeta(currentShippingTaskSource.process_status).chip"
|
||||
>
|
||||
{{ statusMeta(currentShippingTaskSource.process_status).label }}
|
||||
</span>
|
||||
<span class="text-muted">{{ t('chat.shippingNoticeUi.stepperTitle') }}:{{ stepLabel(currentShippingTaskSource.current_step) }}</span>
|
||||
</div>
|
||||
<ShippingWorkflowStepper
|
||||
v-if="currentShippingTaskSource"
|
||||
:steps="currentShippingSteps"
|
||||
compact
|
||||
class="pt-2"
|
||||
/>
|
||||
<div
|
||||
v-if="currentShippingStepProgress"
|
||||
class="mt-3 rounded-2xl border border-default/80 bg-surface/80 px-3 py-3"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-3 text-xs">
|
||||
<div class="font-medium text-primary">
|
||||
{{ currentShippingStepProgress.step_title || t('chat.shippingNoticeUi.stepDetail.title') }}
|
||||
</div>
|
||||
<div class="text-muted">
|
||||
{{ currentShippingStepProgress.progress_percent ?? 0 }}%
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-1 text-sm text-secondary">
|
||||
{{ currentShippingStepProgress.message || t('chat.shippingNoticeUi.processing') }}
|
||||
</div>
|
||||
<div
|
||||
v-if="currentShippingStepProgress.detail"
|
||||
class="mt-1 text-xs text-muted"
|
||||
>
|
||||
{{ currentShippingStepProgress.detail }}
|
||||
</div>
|
||||
<div
|
||||
v-if="currentShippingStepProgress.current && currentShippingStepProgress.total"
|
||||
class="mt-1 text-xs text-muted"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.stepDetail.counter', { current: currentShippingStepProgress.current, total: currentShippingStepProgress.total }) }}
|
||||
</div>
|
||||
<div class="mt-2 h-2 overflow-hidden rounded-full bg-slate-200">
|
||||
<div
|
||||
class="h-full rounded-full bg-sky-500 transition-all"
|
||||
:style="{ width: `${currentShippingStepProgress.progress_percent ?? 0}%` }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2 pt-1 text-xs">
|
||||
<button
|
||||
v-if="page.shippingBatchSummary"
|
||||
type="button"
|
||||
class="rounded-full border border-default px-2.5 py-1 text-secondary transition hover:bg-surface-soft"
|
||||
@click="page.input = '上一票'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.prevTask') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="page.shippingBatchSummary"
|
||||
type="button"
|
||||
class="rounded-full border border-default px-2.5 py-1 text-secondary transition hover:bg-surface-soft"
|
||||
@click="page.input = '下一票'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.nextTask') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="page.shippingBatchTasks?.length > 1"
|
||||
type="button"
|
||||
class="rounded-full border border-default px-2.5 py-1 text-secondary transition hover:bg-surface-soft"
|
||||
@click="page.shippingBatchTasksExpanded = !page.shippingBatchTasksExpanded"
|
||||
>
|
||||
{{ page.shippingBatchTasksExpanded ? t('chat.shippingNoticeUi.collapseTasks') : t('chat.shippingNoticeUi.viewTasks') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="page.shippingBatchSummary" class="grid grid-cols-4 gap-2 text-right text-xs">
|
||||
<div class="rounded-2xl bg-surface px-3 py-2">
|
||||
<div class="text-muted">{{ t('chat.shippingNoticeUi.fileCount') }}</div>
|
||||
<div class="mt-1 text-sm font-semibold text-primary">{{ batchFileCount }}</div>
|
||||
</div>
|
||||
<div class="rounded-2xl bg-surface px-3 py-2">
|
||||
<div class="text-muted">{{ t('chat.shippingNoticeUi.runningCount') }}</div>
|
||||
<div class="mt-1 text-sm font-semibold text-primary">{{ batchRunningCount }}</div>
|
||||
</div>
|
||||
<div class="rounded-2xl bg-surface px-3 py-2">
|
||||
<div class="text-muted">{{ t('chat.shippingNoticeUi.completedCount') }}</div>
|
||||
<div class="mt-1 text-sm font-semibold text-primary">{{ batchCompletedCount }}</div>
|
||||
</div>
|
||||
<div class="rounded-2xl bg-surface px-3 py-2">
|
||||
<div class="text-muted">{{ t('chat.shippingNoticeUi.pendingCount') }}</div>
|
||||
<div class="mt-1 text-sm font-semibold text-primary">{{ batchPendingCount }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="page.shippingBatchSummary"
|
||||
class="mt-3 space-y-1 border-t border-default/70 pt-3"
|
||||
>
|
||||
<div class="flex items-center justify-between text-[11px] text-muted">
|
||||
<span>{{ t('chat.shippingNoticeUi.batchProgressTitle') }}</span>
|
||||
<span>{{ batchCompletedCount }}/{{ batchFileCount }} · {{ batchCompletionPercent }}%</span>
|
||||
</div>
|
||||
<div class="h-2 overflow-hidden rounded-full bg-slate-200">
|
||||
<div
|
||||
class="h-full rounded-full bg-brand-500 transition-all"
|
||||
:style="{ width: `${batchCompletionPercent}%` }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="page.shippingInventorySelectionActive && page.shippingBatchTasks?.length > 1"
|
||||
class="mt-3 flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-amber-200 bg-amber-50/90 px-3 py-3 text-sm text-amber-900"
|
||||
>
|
||||
<div class="space-y-1">
|
||||
<div class="font-semibold">{{ t('chat.shippingNoticeUi.inventoryTaskPickTitle') }}</div>
|
||||
<div class="text-xs text-amber-800">
|
||||
{{ t('chat.shippingNoticeUi.inventoryTaskPickHint') }}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-amber-300 px-3 py-1 text-xs font-medium text-amber-800 transition hover:bg-amber-100"
|
||||
@click="page.cancelShippingInventoryTaskSelection()"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.cancelInventoryTaskPick') }}
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
v-if="page.shippingBatchTasksExpanded && page.shippingBatchTasks?.length"
|
||||
class="mt-3 grid gap-2 border-t border-default/70 pt-3 sm:grid-cols-2 xl:grid-cols-3"
|
||||
>
|
||||
<button
|
||||
v-for="task in page.shippingBatchTasks"
|
||||
:key="task.task_no"
|
||||
type="button"
|
||||
class="rounded-2xl border px-3 py-3 text-left transition"
|
||||
:class="task.task_no === page.shippingBatchSummary?.current_focus_task_no ? 'border-brand-300 bg-brand-50/80 shadow-sm' : 'border-default bg-surface hover:bg-surface-soft'"
|
||||
@click="page.switchShippingFocusTask(task.task_no)"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div class="font-mono text-xs font-semibold text-primary">{{ task.task_no }}</div>
|
||||
<span
|
||||
class="rounded-full px-2 py-0.5 text-[11px] font-medium"
|
||||
:class="statusMeta(task.process_status).chip"
|
||||
>
|
||||
{{ statusMeta(task.process_status).label }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-2 truncate text-sm font-medium text-secondary">{{ task.customer_name || task.source_file_name || '未命名通知' }}</div>
|
||||
<div class="mt-1 text-[11px] text-muted">
|
||||
{{ stepLabel(task.current_step) }}
|
||||
<span v-if="task.batch_index && task.batch_total">
|
||||
· {{ t('chat.shippingNoticeUi.batchProgress', { index: task.batch_index, total: task.batch_total }) }}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="page.shippingInventorySelectionActive"
|
||||
class="mt-3 flex items-center justify-between gap-2"
|
||||
>
|
||||
<span
|
||||
v-if="page.shippingInventorySelectionTaskId === task.task_no"
|
||||
class="rounded-full bg-brand-50 px-2 py-1 text-[11px] font-medium text-brand-700"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.inventoryTargetTask', { taskId: task.task_no }) }}
|
||||
</span>
|
||||
<span v-else class="text-[11px] text-muted">
|
||||
{{ t('chat.shippingNoticeUi.inventoryTargetIdle') }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-brand-200 px-2.5 py-1 text-[11px] font-medium text-brand-700 transition hover:bg-brand-50"
|
||||
@click.stop="page.selectShippingInventoryUploadTask(task.task_no)"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.uploadInventoryToTask') }}
|
||||
</button>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<ShippingBatchProgressPanel
|
||||
v-if="page.isShippingNoticeAgent && (page.shippingBatchSummary || page.activeShippingTaskDetail)"
|
||||
:batch-summary="page.shippingBatchSummary"
|
||||
:batch-tasks="page.shippingBatchTasks"
|
||||
:active-task-detail="page.activeShippingTaskDetail"
|
||||
:tasks-expanded="page.shippingBatchTasksExpanded"
|
||||
:inventory-selection-active="page.shippingInventorySelectionActive && page.shippingBatchTasks?.length > 1"
|
||||
@update:tasks-expanded="page.shippingBatchTasksExpanded = $event"
|
||||
@focus-task="page.switchShippingFocusTask"
|
||||
@resume-task="page.resumeShippingTask"
|
||||
/>
|
||||
|
||||
<ChatMessageList
|
||||
:messages="page.messages"
|
||||
|
||||
@@ -0,0 +1,443 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/ShippingBatchProgressPanel.vue
|
||||
* 用途:发货通知聊天顶部批次进度卡片,按原型方案 C 展示批次概览、任务切换列表、七步进度与续办弹层。
|
||||
* 依赖:shippingStepper、shipping.api.types、vue-i18n、lucide-vue-next。
|
||||
* 逻辑:上游由 ChatViewContent 传入批次/任务状态;本组件只负责展示与抛出 focus/resume 事件,不直接请求后端。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { List, PlayCircle, X } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { buildShippingWorkflowSteps, type ShippingWorkflowStepItem } from '@/features/chat/shipping';
|
||||
import { retryWorkspaceShippingBatchPending } from '@/features/chat/api/shipping.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
|
||||
const props = defineProps<{
|
||||
batchSummary: ShippingBatchSummary | null;
|
||||
batchTasks: ShippingTaskSummary[];
|
||||
activeTaskDetail: ShippingTaskDetail | null;
|
||||
tasksExpanded: boolean;
|
||||
inventorySelectionActive: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:tasksExpanded': [value: boolean];
|
||||
'focus-task': [taskNo: string];
|
||||
'resume-task': [taskNo: string];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const showTaskDialog = ref(false);
|
||||
const retryingPending = ref(false);
|
||||
|
||||
const COMPLETED_PROCESS_STATUSES = new Set(['uploaded', 'closed']);
|
||||
const CIRCLED_NUMBERS = ['①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨'];
|
||||
|
||||
const processSummary = computed(() => {
|
||||
const summary = props.batchSummary?.process_summary || null;
|
||||
const total = Number(summary?.total || props.batchSummary?.file_count || props.batchTasks.length || 0);
|
||||
const completed = Number(
|
||||
summary?.completed
|
||||
|| props.batchTasks.filter((task) => COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim())).length
|
||||
|| 0,
|
||||
);
|
||||
const runningFallback = props.batchTasks.some(
|
||||
(task) => !COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim()),
|
||||
) ? 1 : 0;
|
||||
const running = Number(summary?.running || runningFallback || 0);
|
||||
const pending = Math.max(0, Number(summary?.pending ?? (total - completed - running)));
|
||||
return { total, completed, running, pending };
|
||||
});
|
||||
|
||||
const currentTask = computed<ShippingTaskSummary | ShippingTaskDetail | null>(() => {
|
||||
const focusTaskNo = String(props.batchSummary?.current_focus_task_no || '').trim().toUpperCase();
|
||||
if (focusTaskNo) {
|
||||
return props.batchTasks.find((task) => String(task.task_no || '').trim().toUpperCase() === focusTaskNo)
|
||||
|| props.activeTaskDetail
|
||||
|| null;
|
||||
}
|
||||
return props.activeTaskDetail || props.batchTasks[0] || null;
|
||||
});
|
||||
|
||||
const currentTaskNo = computed(() => String(currentTask.value?.task_no || '').trim().toUpperCase());
|
||||
const currentTaskName = computed(() =>
|
||||
String(
|
||||
currentTask.value?.source_file_name
|
||||
|| currentTask.value?.customer_name
|
||||
|| t('chat.shippingNoticeUi.currentNotice'),
|
||||
).trim(),
|
||||
);
|
||||
const currentTaskIndex = computed(() =>
|
||||
Number(
|
||||
currentTask.value?.batch_index
|
||||
|| props.batchSummary?.process_summary?.current_index
|
||||
|| 0,
|
||||
),
|
||||
);
|
||||
const currentTaskTotal = computed(() =>
|
||||
Number(
|
||||
currentTask.value?.batch_total
|
||||
|| props.batchSummary?.file_count
|
||||
|| processSummary.value.total
|
||||
|| 0,
|
||||
),
|
||||
);
|
||||
const currentSteps = computed(() => buildShippingWorkflowSteps(currentTask.value));
|
||||
|
||||
const resolveActiveStep = (steps: ShippingWorkflowStepItem[]) =>
|
||||
steps.findIndex((step) => step.status === 'current' || step.status === 'blocked');
|
||||
|
||||
const currentStepMeta = computed(() => {
|
||||
const steps = currentSteps.value;
|
||||
if (!steps.length) return { index: 0, label: t('chat.shippingNoticeUi.processing') };
|
||||
const activeIndex = resolveActiveStep(steps);
|
||||
const safeIndex = activeIndex >= 0 ? activeIndex : steps.length - 1;
|
||||
return {
|
||||
index: safeIndex + 1,
|
||||
label: t(steps[safeIndex]?.label || 'chat.shippingNoticeUi.processing'),
|
||||
};
|
||||
});
|
||||
|
||||
const summaryLine = computed(() => t('chat.shippingNoticeUi.batchSummaryLine', {
|
||||
total: processSummary.value.total,
|
||||
completed: processSummary.value.completed,
|
||||
running: processSummary.value.running,
|
||||
pending: processSummary.value.pending,
|
||||
}));
|
||||
|
||||
/**
|
||||
* 将任务状态映射为原型中列表右侧的紧凑状态文案。
|
||||
*
|
||||
* 核心逻辑:完成态显示“已完成”,阻塞态显示“步骤 X 待确认”,运行态显示“步骤 X/Y”,
|
||||
* 其余回退到“排队中”,以匹配原型中批次队列的短标签风格。
|
||||
* @param task - 任务摘要或详情
|
||||
* @returns 原型列表使用的短文案与颜色类
|
||||
*/
|
||||
const resolveTaskStateMeta = (task: ShippingTaskSummary | ShippingTaskDetail | null) => {
|
||||
if (!task) {
|
||||
return { text: t('chat.shippingNoticeUi.queuedState'), tone: 'text-muted' };
|
||||
}
|
||||
if (COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim())) {
|
||||
return { text: t('chat.shippingNoticeUi.completedState'), tone: 'text-emerald-700' };
|
||||
}
|
||||
|
||||
const steps = buildShippingWorkflowSteps(task);
|
||||
const blockedIndex = steps.findIndex((step) => step.status === 'blocked');
|
||||
if (blockedIndex >= 0) {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.stepNeedsConfirm', { step: blockedIndex + 1 }),
|
||||
tone: 'text-amber-700',
|
||||
};
|
||||
}
|
||||
|
||||
const activeIndex = resolveActiveStep(steps);
|
||||
if (activeIndex >= 0) {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.stepFraction', { current: activeIndex + 1, total: steps.length }),
|
||||
tone: 'text-brand-600',
|
||||
};
|
||||
}
|
||||
|
||||
return { text: t('chat.shippingNoticeUi.queuedState'), tone: 'text-muted' };
|
||||
};
|
||||
|
||||
const shortTaskNo = (taskNo?: string | null) => {
|
||||
const value = String(taskNo || '').trim();
|
||||
if (value.length <= 10) return value || '--';
|
||||
return `${value.slice(0, 5)}...${value.slice(-3)}`;
|
||||
};
|
||||
|
||||
const isCurrentTask = (taskNo?: string | null) =>
|
||||
String(taskNo || '').trim().toUpperCase() === currentTaskNo.value;
|
||||
|
||||
const openTaskDialog = () => {
|
||||
if (!props.batchTasks.length) return;
|
||||
showTaskDialog.value = true;
|
||||
};
|
||||
|
||||
const handleFocusTask = (taskNo: string) => {
|
||||
emit('focus-task', taskNo);
|
||||
};
|
||||
|
||||
const handleResumeTask = (taskNo: string) => {
|
||||
showTaskDialog.value = false;
|
||||
emit('resume-task', taskNo);
|
||||
};
|
||||
|
||||
const handleRetryPending = async () => {
|
||||
const batchNo = String(props.batchSummary?.batch_no || '').trim();
|
||||
if (!batchNo || retryingPending.value) return;
|
||||
retryingPending.value = true;
|
||||
try {
|
||||
const result = await retryWorkspaceShippingBatchPending(batchNo);
|
||||
msg.success(result.message || t('chat.shippingNoticeUi.retryPendingDone'));
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('chat.shippingNoticeUi.retryFailed'));
|
||||
} finally {
|
||||
retryingPending.value = false;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
class="mx-auto mt-4 w-full max-w-4xl overflow-hidden rounded-2xl border border-sky-100 bg-gradient-to-br from-sky-50 via-white to-emerald-50 shadow-sm"
|
||||
>
|
||||
<div class="border-b border-sky-100/80 px-4 py-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<div class="text-xs text-slate-500">
|
||||
{{ summaryLine }}
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
v-if="batchSummary?.batch_no"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-default bg-white/80 px-2.5 py-1 text-xs font-medium text-secondary transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="retryingPending"
|
||||
@click="handleRetryPending"
|
||||
>
|
||||
{{ retryingPending ? t('chat.shippingNoticeUi.retrying') : t('chat.shippingNoticeUi.retryPendingTasks') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-default bg-white/80 px-2.5 py-1 text-xs font-medium text-secondary transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700"
|
||||
@click="openTaskDialog"
|
||||
>
|
||||
<List class="h-3.5 w-3.5" />
|
||||
{{ t('chat.shippingNoticeUi.taskListResume') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="batchTasks.length > 1"
|
||||
type="button"
|
||||
class="text-xs font-medium text-brand-600 transition hover:text-brand-700"
|
||||
@click="emit('update:tasksExpanded', !tasksExpanded)"
|
||||
>
|
||||
{{ tasksExpanded ? `${t('chat.shippingNoticeUi.collapseTaskList')} ▲` : `${t('chat.shippingNoticeUi.expandTaskList')} ▼` }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="tasksExpanded && batchTasks.length"
|
||||
class="mt-2 space-y-1 border-t border-dashed border-sky-100 pt-2"
|
||||
>
|
||||
<button
|
||||
v-for="(task, index) in batchTasks"
|
||||
:key="task.task_no"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-xs transition hover:bg-white/70"
|
||||
:class="isCurrentTask(task.task_no) ? 'bg-white/80 ring-1 ring-brand-200' : ''"
|
||||
@click="handleFocusTask(task.task_no)"
|
||||
>
|
||||
<span class="text-muted">{{ CIRCLED_NUMBERS[index] || `${index + 1}` }}</span>
|
||||
<span class="flex-1 truncate" :class="isCurrentTask(task.task_no) ? 'font-medium text-secondary' : ''">
|
||||
{{ task.source_file_name || task.customer_name || t('chat.shippingNoticeUi.currentNotice') }}
|
||||
</span>
|
||||
<span class="font-mono text-brand-600">{{ shortTaskNo(task.task_no) }}</span>
|
||||
<span
|
||||
class="rounded-full px-1.5 py-0.5"
|
||||
:class="isCurrentTask(task.task_no) ? 'text-brand-600' : resolveTaskStateMeta(task).tone"
|
||||
>
|
||||
{{ resolveTaskStateMeta(task).text }}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-3 px-4 py-4">
|
||||
<div class="flex flex-wrap items-baseline justify-between gap-2">
|
||||
<div>
|
||||
<div class="font-mono text-sm font-semibold text-brand-700">
|
||||
{{ currentTaskNo || batchSummary?.batch_no || '--' }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-xs text-muted">
|
||||
当前 · 第 {{ currentTaskIndex || 0 }}/{{ currentTaskTotal || 0 }} 笔 ·
|
||||
<em class="not-italic text-secondary">{{ currentTaskName }}</em>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-xs text-muted">
|
||||
步骤 <strong class="text-secondary">{{ currentStepMeta.index }}</strong>/{{ currentSteps.length || 7 }} · {{ currentStepMeta.label }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="scheme-stepper">
|
||||
<template v-for="(step, index) in currentSteps" :key="step.id">
|
||||
<div
|
||||
class="scheme-step-node"
|
||||
:class="{
|
||||
done: step.status === 'completed',
|
||||
active: step.status === 'current' || step.status === 'blocked',
|
||||
}"
|
||||
>
|
||||
<div class="scheme-step-dot">
|
||||
{{ step.status === 'completed' ? '✓' : index + 1 }}
|
||||
</div>
|
||||
<div class="scheme-step-label">{{ t(step.label) }}</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="inventorySelectionActive"
|
||||
class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.inventoryTaskPickHint') }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="showTaskDialog"
|
||||
class="fixed inset-0 z-[120] flex items-center justify-center bg-slate-900/30 px-4"
|
||||
@click.self="showTaskDialog = false"
|
||||
>
|
||||
<div class="w-full max-w-[620px] rounded-[28px] bg-white p-5 shadow-[0_24px_80px_rgba(15,23,42,0.22)]">
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<div class="text-[32px] font-semibold tracking-tight text-slate-800">
|
||||
{{ t('chat.shippingNoticeUi.taskListTitle') }}
|
||||
</div>
|
||||
<div class="mt-1 text-sm text-slate-500">
|
||||
{{ t('chat.shippingNoticeUi.taskListHint') }}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full p-2 text-slate-400 transition hover:bg-slate-100 hover:text-slate-600"
|
||||
@click="showTaskDialog = false"
|
||||
>
|
||||
<X class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="mt-5 space-y-3">
|
||||
<button
|
||||
v-for="task in batchTasks"
|
||||
:key="task.task_no"
|
||||
type="button"
|
||||
class="w-full rounded-3xl border px-4 py-4 text-left transition hover:border-[#8bc8f5] hover:bg-[#f8fbff]"
|
||||
:class="isCurrentTask(task.task_no) ? 'border-[#8bc8f5] bg-[#f5fbff]' : 'border-[#e5edf5] bg-white'"
|
||||
@click="handleResumeTask(task.task_no)"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="font-mono text-lg font-semibold text-[#1277c8]">
|
||||
{{ task.task_no }}
|
||||
</div>
|
||||
<div class="mt-1 truncate text-[15px] text-slate-700">
|
||||
{{ task.source_file_name || task.customer_name || t('chat.shippingNoticeUi.currentNotice') }}
|
||||
</div>
|
||||
<div class="mt-1 text-sm text-slate-500">
|
||||
{{ resolveTaskStateMeta(task).text }}
|
||||
</div>
|
||||
<div
|
||||
v-if="isCurrentTask(task.task_no)"
|
||||
class="mt-2 inline-flex items-center gap-1 text-sm font-medium text-[#1277c8]"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.currentFocus') }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<span
|
||||
class="rounded-full px-3 py-1 text-sm font-medium"
|
||||
:class="COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim())
|
||||
? 'bg-emerald-100 text-emerald-700'
|
||||
: isCurrentTask(task.task_no)
|
||||
? 'bg-sky-100 text-sky-700'
|
||||
: 'bg-amber-100 text-amber-700'"
|
||||
>
|
||||
{{ COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim())
|
||||
? t('chat.shippingNoticeUi.completedState')
|
||||
: isCurrentTask(task.task_no)
|
||||
? t('chat.shippingNoticeUi.runningState')
|
||||
: t('chat.shippingNoticeUi.pendingState') }}
|
||||
</span>
|
||||
<PlayCircle class="h-5 w-5 text-[#1492df]" />
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.scheme-stepper {
|
||||
display: flex;
|
||||
overflow-x: auto;
|
||||
padding-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.scheme-step-node {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
min-width: 52px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.scheme-step-node:not(:last-child)::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
left: calc(50% + 11px);
|
||||
width: calc(100% - 22px);
|
||||
height: 2px;
|
||||
background: #e2e8f0;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.scheme-step-node.done:not(:last-child)::after {
|
||||
background: #0284c7;
|
||||
}
|
||||
|
||||
.scheme-step-node.active:not(:last-child)::after {
|
||||
background: linear-gradient(90deg, #0284c7 50%, #e2e8f0 50%);
|
||||
}
|
||||
|
||||
.scheme-step-dot {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
margin: 0 auto 0.25rem;
|
||||
border: 2px solid #e2e8f0;
|
||||
border-radius: 9999px;
|
||||
background: #fff;
|
||||
color: #64748b;
|
||||
font-size: 0.55rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.scheme-step-node.done .scheme-step-dot {
|
||||
border-color: #0284c7;
|
||||
background: #0284c7;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.scheme-step-node.active .scheme-step-dot {
|
||||
border-color: #0284c7;
|
||||
box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.18);
|
||||
color: #0284c7;
|
||||
}
|
||||
|
||||
.scheme-step-label {
|
||||
color: #64748b;
|
||||
font-size: 0.58rem;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.scheme-step-node.active .scheme-step-label {
|
||||
color: #0284c7;
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
@@ -87,9 +87,12 @@ export function useChatPage() {
|
||||
const scroll = useChatScroll({ container: chatScrollContainer, messages });
|
||||
scroll.setupThinkingScrollWatch(isThinking, conversationId);
|
||||
|
||||
let resetShippingConversationState = () => {};
|
||||
|
||||
const resetPeripheralState = () => {
|
||||
browser.close();
|
||||
queryPreview.close();
|
||||
resetShippingConversationState();
|
||||
};
|
||||
|
||||
const disposePeripherals = () => {
|
||||
@@ -204,6 +207,7 @@ export function useChatPage() {
|
||||
loadConversation: (id, opts) => loadConversation(id, opts),
|
||||
createNewChatView,
|
||||
});
|
||||
resetShippingConversationState = shipping.resetShippingConversationState;
|
||||
|
||||
const conversationApi = createChatPageConversationApi({
|
||||
deps,
|
||||
@@ -416,6 +420,7 @@ export function useChatPage() {
|
||||
shippingInventorySelectionActive: shipping.shippingInventorySelectionActive,
|
||||
shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId,
|
||||
switchShippingFocusTask: shipping.switchShippingFocusTask,
|
||||
resumeShippingTask: shipping.resumeShippingTask,
|
||||
selectShippingInventoryUploadTask: shipping.selectShippingInventoryUploadTask,
|
||||
cancelShippingInventoryTaskSelection: shipping.cancelShippingInventoryTaskSelection,
|
||||
shippingSuggestedPrompt: shipping.shippingSuggestedPrompt,
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
import {
|
||||
computed,
|
||||
onBeforeUnmount,
|
||||
ref,
|
||||
watch,
|
||||
type ComputedRef,
|
||||
@@ -48,6 +49,7 @@ import {
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
import { listChatMessages } from '../api/chat.api';
|
||||
|
||||
export interface UseChatShippingOptions {
|
||||
deps: ChatDeps;
|
||||
@@ -152,6 +154,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const shippingConversationTaskIdCache = ref<Record<string, string>>({});
|
||||
const shippingInventorySchemaPreviewCache = ref<Record<string, unknown>>({});
|
||||
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
|
||||
const lastConversationSyncKey = ref('');
|
||||
let shippingStatusPollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const syncShippingBatchSummary = async (batchNo: string) => {
|
||||
const normalized = String(batchNo || '').trim();
|
||||
@@ -174,8 +178,14 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
created_at: detail.created_at,
|
||||
updated_at: detail.updated_at,
|
||||
};
|
||||
if (detail.focus_task?.task_no) {
|
||||
resolvedShippingTaskId.value = String(detail.focus_task.task_no).trim();
|
||||
const preferredTaskNo = String(
|
||||
detail.focus_task?.task_no
|
||||
|| detail.process_summary?.current_task_no
|
||||
|| detail.current_focus_task_no
|
||||
|| '',
|
||||
).trim();
|
||||
if (preferredTaskNo) {
|
||||
resolvedShippingTaskId.value = preferredTaskNo;
|
||||
}
|
||||
} catch {
|
||||
// ignore summary refresh failure in chat flow
|
||||
@@ -195,9 +205,34 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
};
|
||||
}
|
||||
await syncShippingBatchSummary(batchNo);
|
||||
await syncActiveShippingTaskDetail(normalizedTaskNo);
|
||||
await refreshShippingActions();
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 清空当前聊天页绑定的发货任务上下文。
|
||||
*
|
||||
* 核心逻辑:在新建对话、切换 Agent 或离开发货任务场景时,主动清掉批次/任务/上传缓存,
|
||||
* 避免顶部 Stepper、列表展开态和待上传库存文件残留到下一次新会话。
|
||||
*/
|
||||
const resetShippingConversationState = () => {
|
||||
shippingAutoFlowRequested.value = false;
|
||||
pendingShippingUploadTaskId.value = '';
|
||||
pendingShippingInventoryFile.value = null;
|
||||
shippingInventorySelectionActive.value = false;
|
||||
shippingInventorySelectionTaskId.value = '';
|
||||
resolvedShippingTaskId.value = '';
|
||||
resolvedShippingBatchNo.value = '';
|
||||
shippingBatchSummary.value = null;
|
||||
shippingBatchTasks.value = [];
|
||||
shippingBatchTasksExpanded.value = false;
|
||||
activeShippingTaskDetail.value = null;
|
||||
shippingConversationTaskIdCache.value = {};
|
||||
shippingInventorySchemaPreviewCache.value = {};
|
||||
lastConversationSyncKey.value = '';
|
||||
};
|
||||
|
||||
const getActiveShippingTaskId = () =>
|
||||
findLatestShippingTaskId(messages.value)
|
||||
|| resolvedShippingTaskId.value
|
||||
@@ -215,6 +250,17 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
batch_no: getActiveShippingBatchNo(),
|
||||
});
|
||||
|
||||
const hasRunningShippingBatchTasks = () =>
|
||||
shippingBatchTasks.value.some(
|
||||
(task) => !['uploaded', 'completed', 'closed', 'rejected'].includes(String(task.process_status || '').trim()),
|
||||
);
|
||||
|
||||
/**
|
||||
* 同步当前焦点任务详情,并在仅恢复 `task_no` 的场景下补齐 `batch_no` 上下文。
|
||||
*
|
||||
* 核心逻辑:先拉取任务详情,再把详情里的批次号回填到聊天状态,确保会话恢复后仍能继续按批次模式加载 2 票/多票摘要。
|
||||
* @param taskId - 可选任务编号;未传时回退到当前激活任务
|
||||
*/
|
||||
const syncActiveShippingTaskDetail = async (taskId?: string) => {
|
||||
const normalized = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
|
||||
if (!normalized) {
|
||||
@@ -222,12 +268,43 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
activeShippingTaskDetail.value = await getWorkspaceShippingTask(normalized);
|
||||
const detail = await getWorkspaceShippingTask(normalized);
|
||||
activeShippingTaskDetail.value = detail;
|
||||
const batchNo = String(detail.batch_no || '').trim();
|
||||
if (batchNo && resolvedShippingBatchNo.value !== batchNo) {
|
||||
resolvedShippingBatchNo.value = batchNo;
|
||||
}
|
||||
} catch {
|
||||
activeShippingTaskDetail.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
const syncConversationMessagesIfNeeded = async (taskId?: string) => {
|
||||
const conversationKey = String(conversationId.value || '').trim();
|
||||
const normalizedTaskId = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
|
||||
if (!conversationKey || !normalizedTaskId || !isShippingNoticeAgent.value || isThinking.value) return;
|
||||
const detail = activeShippingTaskDetail.value;
|
||||
// 任务详情接口当前不返回顶层 checkpoint,parse_review 需从详情状态字段回推。
|
||||
const checkpoint = String(
|
||||
(detail?.step_payload as Record<string, unknown> | undefined)?.checkpoint
|
||||
|| detail?.review_status
|
||||
|| '',
|
||||
).trim();
|
||||
if (checkpoint !== 'parse_review') return;
|
||||
const exists = messages.value.some((msg) => {
|
||||
if (msg.type !== 'shipping-parse-review' || !msg.payload || typeof msg.payload !== 'object') return false;
|
||||
return String((msg.payload as { taskId?: string }).taskId || '').trim().toUpperCase() === normalizedTaskId;
|
||||
});
|
||||
if (exists) return;
|
||||
const syncKey = `${conversationKey}|${normalizedTaskId}|parse_review`;
|
||||
if (lastConversationSyncKey.value === syncKey) return;
|
||||
const loaded = await listChatMessages(conversationKey, currentAgentId.value);
|
||||
if (Array.isArray(loaded) && loaded.length > 0) {
|
||||
messages.value = loaded;
|
||||
lastConversationSyncKey.value = syncKey;
|
||||
}
|
||||
};
|
||||
|
||||
const lastAssistantMessageContent = () => {
|
||||
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
|
||||
const item = messages.value[i];
|
||||
@@ -422,9 +499,32 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
|
||||
if (prevId !== nextId) {
|
||||
resolvedShippingTaskId.value = '';
|
||||
if (!shippingBatchNoFromQuery.value) {
|
||||
resolvedShippingBatchNo.value = '';
|
||||
shippingBatchSummary.value = null;
|
||||
shippingBatchTasks.value = [];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 续办指定任务,并把聊天上下文切到该任务继续推进。
|
||||
*
|
||||
* 核心逻辑:先切换批次焦点任务,再复用既有“请继续处理发货任务”提示词触发一次发送,
|
||||
* 让 Agent 基于最新 task_id/batch_no 返回下一步动作。
|
||||
* @param taskNo - 需要续办的任务编号
|
||||
* @returns 是否已成功触发续办
|
||||
*/
|
||||
const resumeShippingTask = async (taskNo: string) => {
|
||||
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
|
||||
if (!normalizedTaskNo || !isShippingNoticeAgent.value || isThinking.value) return false;
|
||||
const switched = await switchShippingFocusTask(normalizedTaskNo);
|
||||
if (!switched) return false;
|
||||
input.value = t('chat.shippingNoticeContinue', { taskId: normalizedTaskNo });
|
||||
await invokeHandleSend?.();
|
||||
return true;
|
||||
};
|
||||
|
||||
const onConversationLoadedEmpty = async () => {
|
||||
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
|
||||
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
|
||||
@@ -442,6 +542,42 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
await invokeHandleSend?.();
|
||||
};
|
||||
|
||||
/**
|
||||
* 启停发货批次状态短轮询。
|
||||
*
|
||||
* 核心逻辑:聊天流当前没有 shipping 专属 SSE;因此在存在任务/批次上下文时每 3 秒补拉一次,
|
||||
* 让顶部 Stepper、批次统计和动作按钮能在后端异步状态变化后自动更新。
|
||||
*/
|
||||
const restartShippingStatusPolling = () => {
|
||||
if (shippingStatusPollTimer) {
|
||||
clearInterval(shippingStatusPollTimer);
|
||||
shippingStatusPollTimer = null;
|
||||
}
|
||||
if (!isShippingNoticeAgent.value) return;
|
||||
const batchNo = getActiveShippingBatchNo();
|
||||
const taskId = getActiveShippingTaskId();
|
||||
if (!batchNo && !taskId) return;
|
||||
|
||||
shippingStatusPollTimer = setInterval(() => {
|
||||
if (!isShippingNoticeAgent.value) return;
|
||||
const nextBatchNo = getActiveShippingBatchNo();
|
||||
const nextTaskId = getActiveShippingTaskId();
|
||||
if (!nextBatchNo && !nextTaskId) return;
|
||||
void (async () => {
|
||||
if (nextBatchNo) await syncShippingBatchSummary(nextBatchNo);
|
||||
if (nextTaskId) {
|
||||
await syncActiveShippingTaskDetail(nextTaskId);
|
||||
await syncConversationMessagesIfNeeded(nextTaskId);
|
||||
}
|
||||
await refreshShippingActions();
|
||||
if (!hasRunningShippingBatchTasks() && !isThinking.value && shippingStatusPollTimer) {
|
||||
clearInterval(shippingStatusPollTimer);
|
||||
shippingStatusPollTimer = null;
|
||||
}
|
||||
})();
|
||||
}, 3000);
|
||||
};
|
||||
|
||||
// ── 动作按钮 watch ────────────────────────────────────────
|
||||
const shippingActionsWatchKey = computed(() => {
|
||||
const msgs = messages.value;
|
||||
@@ -460,6 +596,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
syncShippingParseReviewCard(taskId),
|
||||
syncActiveShippingTaskDetail(taskId),
|
||||
]);
|
||||
await syncConversationMessagesIfNeeded(taskId);
|
||||
});
|
||||
});
|
||||
watch([resolvedShippingBatchNo, shippingBatchNoFromQuery], ([batchNo, queryBatchNo]) => {
|
||||
@@ -470,6 +607,19 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
}
|
||||
void syncShippingBatchSummary(nextBatchNo);
|
||||
}, { immediate: true });
|
||||
watch(
|
||||
[isShippingNoticeAgent, conversationId, resolvedShippingBatchNo, shippingBatchNoFromQuery, resolvedShippingTaskId, shippingTaskIdFromQuery, isThinking],
|
||||
() => {
|
||||
restartShippingStatusPolling();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
onBeforeUnmount(() => {
|
||||
if (shippingStatusPollTimer) {
|
||||
clearInterval(shippingStatusPollTimer);
|
||||
shippingStatusPollTimer = null;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
shippingBindSend,
|
||||
@@ -491,6 +641,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
|
||||
getCurrentShippingChatContext,
|
||||
getActiveShippingBatchNo,
|
||||
switchShippingFocusTask,
|
||||
resumeShippingTask,
|
||||
resetShippingConversationState,
|
||||
resumeShippingTaskFromQuery,
|
||||
normalizeShippingHeaderForDisplay,
|
||||
getShippingInventoryMappingPayload,
|
||||
|
||||
@@ -65,6 +65,12 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
|
||||
|
||||
const startNewChat = () => {
|
||||
ctx.createNewChatView();
|
||||
ctx.clearAttachments();
|
||||
ctx.input.value = '';
|
||||
ctx.copiedIndex.value = null;
|
||||
ctx.resetPeripheralState();
|
||||
ctx.filePreviewVisible.value = false;
|
||||
ctx.previewFile.value = null;
|
||||
void ctx.router.replace({ path: ctx.route.path, query: {} });
|
||||
};
|
||||
|
||||
|
||||
@@ -45,6 +45,8 @@ const CURRENT_STEP_INDEX_MAP: Record<string, number> = {
|
||||
step7_finish: 6,
|
||||
};
|
||||
|
||||
const TERMINAL_PROCESS_STATUSES = new Set(['uploaded', 'closed']);
|
||||
|
||||
function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined): number {
|
||||
const currentStep = String(task?.current_step || '').trim();
|
||||
const processStatus = String(task?.process_status || '').trim();
|
||||
@@ -60,7 +62,7 @@ function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined):
|
||||
}
|
||||
}
|
||||
|
||||
if (processStatus === 'uploaded' || processStatus === 'closed') return 6;
|
||||
if (TERMINAL_PROCESS_STATUSES.has(processStatus)) return 6;
|
||||
if (processStatus === 'waiting_upload' || processStatus === 'upload_failed' || hasExport) return 5;
|
||||
if (processStatus === 'matched') return 4;
|
||||
if (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage') return 4;
|
||||
@@ -102,7 +104,10 @@ export function buildShippingWorkflowSteps(
|
||||
|
||||
return SHIPPING_WORKFLOW_STEP_LABELS.map((label, index) => {
|
||||
let status: ShippingWorkflowStepItem['status'] = 'pending';
|
||||
if (index < currentIndex) {
|
||||
// [STEP 1] uploaded/closed 是整票已完成的终态,不能再被 current_step 渲染成“第 7 步进行中”。
|
||||
if (TERMINAL_PROCESS_STATUSES.has(processStatus)) {
|
||||
status = 'completed';
|
||||
} else if (index < currentIndex) {
|
||||
status = 'completed';
|
||||
} else if (index === currentIndex) {
|
||||
status = 'current';
|
||||
|
||||
@@ -47,6 +47,11 @@ export function buildShippingNoticeUploadPrompt(
|
||||
|| ((result?.data as { tasks?: Array<{ task_id?: string }> } | undefined)?.tasks?.[0]?.task_id)
|
||||
|| '',
|
||||
).trim();
|
||||
const taskIds = Array.isArray((result?.data as { tasks?: unknown[] } | undefined)?.tasks)
|
||||
? ((result?.data as { tasks?: Array<{ task_id?: string }> }).tasks || [])
|
||||
.map((task) => String(task?.task_id || '').trim())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const fileCount = Number(options?.fileCount || 0);
|
||||
const fileLabel = options?.fileName
|
||||
? `《${options.fileName}》`
|
||||
@@ -54,7 +59,11 @@ export function buildShippingNoticeUploadPrompt(
|
||||
const parts = [`我已上传${fileLabel}`];
|
||||
if (batchNo) parts.push(`批次 ${batchNo}`);
|
||||
if (taskId) parts.push(`当前任务 ${taskId}`);
|
||||
return `${parts.join(',')}。请读取任务 raw_text,用 LLM 抽取结构化字段后调用 parse_notice(structured=...) 落库;若抽取失败可仅传 raw_text 走后端规则兜底,并展示解析结果供我确认。`;
|
||||
if (fileCount > 1 || taskIds.length > 1) {
|
||||
const taskListText = taskIds.length ? `任务列表:${taskIds.join('、')}。` : '';
|
||||
return `${parts.join(',')}。${taskListText}请立即开始整批处理,不要只处理当前任务。先调用 get_batch_status 查看整批状态,再按批次顺序逐票处理:必要时调用 switch_focus_task 切到对应任务,然后读取该任务 raw_text,用 LLM 抽取结构化字段并调用 parse_notice(structured=...) 落库;若抽取失败可仅传 task_id 让后端用 raw_text 兜底。每处理完一票,都继续切到下一票,直到本批每一票都进入各自下一阶段(待确认、待上传库存、自动推进中的任一状态)。禁止再次询问我“是否开始解析”或只停在第一票。`;
|
||||
}
|
||||
return `${parts.join(',')}。请立即读取任务 raw_text,用 LLM 抽取结构化字段后直接调用 parse_notice(structured=...) 落库;若抽取失败可仅传 raw_text 走后端规则兜底。禁止再次询问我“是否开始解析”或“是否现在开始解析”。解析完成后,请直接展示解析结果供我确认。`;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -107,12 +107,11 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
};
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'shipping-match-result',
|
||||
type: 'text',
|
||||
content: [
|
||||
String(result.message || '').trim(),
|
||||
`任务编号:${taskId}`,
|
||||
].filter(Boolean).join('\n'),
|
||||
payload: buildMatchResultPayload(taskId, result),
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
@@ -158,11 +157,9 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
};
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: [
|
||||
String(result.message || '').trim(),
|
||||
`任务编号:${taskId}`,
|
||||
].filter(Boolean).join('\n'),
|
||||
type: 'shipping-match-result',
|
||||
content: String(result.message || '').trim(),
|
||||
payload: buildMatchResultPayload(taskId, result),
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
type ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import { buildShippingInventoryUploadPrompt, buildShippingNoticeUploadPrompt, classifyShippingUploadFile } from './shippingUploadPrompt';
|
||||
import { buildShippingInventoryUploadPrompt, classifyShippingUploadFile } from './shippingUploadPrompt';
|
||||
import type { PendingAttachment } from '../types/shipping.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
@@ -184,18 +184,19 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
).trim();
|
||||
const hint = String(result.message || '').trim();
|
||||
const status = String((result as { status?: string }).status || '').trim();
|
||||
const orchestratorStarted = Boolean(
|
||||
(result.data as { orchestrator_started?: boolean } | undefined)?.orchestrator_started,
|
||||
);
|
||||
const tail = status === 'needs_human' ? '请根据提示进行确认/驳回。' : '';
|
||||
await ctx.pushShippingLocalAssistantMessage(
|
||||
[
|
||||
hint || `已处理发货通知附件:${file.name}`,
|
||||
batchNo ? `批次编号:${batchNo}` : '',
|
||||
taskId ? `任务编号:${taskId}` : '',
|
||||
orchestratorStarted ? '后台已开始按票处理,请稍后查看进度自动刷新。' : '',
|
||||
tail,
|
||||
].filter(Boolean).join('\n'),
|
||||
);
|
||||
await ctx.sendShippingMenuMessage(
|
||||
buildShippingNoticeUploadPrompt(result as unknown as Record<string, unknown>, { fileName: file.name }),
|
||||
);
|
||||
void ctx.refreshShippingActions();
|
||||
};
|
||||
|
||||
@@ -231,6 +232,9 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
const fileCount = Number(batch?.file_count || noticeFiles.length || 0);
|
||||
const hint = String(result.message || '').trim();
|
||||
const status = String((result as { status?: string }).status || '').trim();
|
||||
const orchestratorStarted = Boolean(
|
||||
(result.data as { orchestrator_started?: boolean } | undefined)?.orchestrator_started,
|
||||
);
|
||||
const tail = status === 'needs_human' ? '请根据提示进行确认/驳回。' : '';
|
||||
await ctx.pushShippingLocalAssistantMessage(
|
||||
[
|
||||
@@ -238,12 +242,10 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
batchNo ? `批次编号:${batchNo}` : '',
|
||||
taskId ? `当前任务:${taskId}` : '',
|
||||
focusProgress,
|
||||
orchestratorStarted ? `后台已开始按票拆分处理,本批 ${fileCount} 票会逐步更新状态。` : '',
|
||||
tail,
|
||||
].filter(Boolean).join('\n'),
|
||||
);
|
||||
await ctx.sendShippingMenuMessage(
|
||||
buildShippingNoticeUploadPrompt(result as unknown as Record<string, unknown>, { fileCount }),
|
||||
);
|
||||
void ctx.refreshShippingActions();
|
||||
};
|
||||
|
||||
|
||||
@@ -157,6 +157,7 @@ export interface ShippingNoticeUploadResponse {
|
||||
batch?: ShippingBatchSummary;
|
||||
focus_task?: ShippingTaskSummary | null;
|
||||
tasks?: Array<Record<string, unknown>>;
|
||||
orchestrator_started?: boolean;
|
||||
};
|
||||
human_options?: string[];
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
markWorkspaceShippingManualUploaded,
|
||||
matchWorkspaceShippingInventory,
|
||||
removeWorkspaceShippingNoticeLine,
|
||||
retryWorkspaceShippingTask,
|
||||
SHIPPING_NOTICE_AGENT_NAME,
|
||||
submitWorkspaceShippingDecision,
|
||||
updateWorkspaceShippingNoticeFields,
|
||||
@@ -39,6 +40,7 @@ import {
|
||||
import type { ChatMessage } from '@/features/chat/types/chat.types';
|
||||
import type { ShippingParseReviewPayload } from '@/features/chat/types/shipping.types';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { buildShippingWorkflowSteps, shippingActionButtonClass } from '@/features/chat/shipping';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -47,6 +49,7 @@ const props = defineProps<{
|
||||
|
||||
const router = useRouter();
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const loading = ref(false);
|
||||
const detailLoading = ref(false);
|
||||
@@ -55,6 +58,7 @@ const selectedTaskNo = ref<string | null>(null);
|
||||
const detail = ref<ShippingTaskDetail | null>(null);
|
||||
const detailSaving = ref(false);
|
||||
const detailActionBusy = ref(false);
|
||||
const detailRetrying = ref(false);
|
||||
const detailActionButtons = ref<ShippingChatAction[]>([]);
|
||||
const statusFilter = ref('all');
|
||||
const chatAgentId = ref<number | null>(null);
|
||||
@@ -97,6 +101,9 @@ const detailStepProgress = computed<ShippingCurrentStepProgress | null>(() => {
|
||||
const progress = (payload as Record<string, unknown>).current_step_progress;
|
||||
return progress && typeof progress === 'object' ? progress as ShippingCurrentStepProgress : null;
|
||||
});
|
||||
const detailStepHasPercent = computed(() =>
|
||||
typeof detailStepProgress.value?.progress_percent === 'number',
|
||||
);
|
||||
|
||||
const loadCases = async () => {
|
||||
loading.value = true;
|
||||
@@ -290,6 +297,20 @@ const handleWorkspaceAction = async (action: ShippingChatAction) => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleRetryCurrentTask = async () => {
|
||||
if (!detail.value || detailRetrying.value) return;
|
||||
detailRetrying.value = true;
|
||||
try {
|
||||
const result = await retryWorkspaceShippingTask(detail.value.task_no, '工作台重试当前票');
|
||||
msg.success(result.message || t('workspace.shippingNotice.retryCurrentDone'));
|
||||
await Promise.all([loadDetail(detail.value.task_no), loadCases()]);
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('workspace.shippingNotice.retryFailed'));
|
||||
} finally {
|
||||
detailRetrying.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
watch(selectedTaskNo, (val) => {
|
||||
if (val) loadDetail(val);
|
||||
else detail.value = null;
|
||||
@@ -397,6 +418,15 @@ onMounted(async () => {
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="detailRetrying"
|
||||
@click="handleRetryCurrentTask"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
{{ detailRetrying ? $t('workspace.shippingNotice.retrying') : $t('workspace.shippingNotice.retryCurrentTask') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="chatAgentId"
|
||||
type="button"
|
||||
@@ -428,8 +458,8 @@ onMounted(async () => {
|
||||
<div class="font-medium text-primary">
|
||||
{{ detailStepProgress.step_title || t('chat.shippingNoticeUi.stepDetail.title') }}
|
||||
</div>
|
||||
<div class="text-muted">
|
||||
{{ detailStepProgress.progress_percent ?? 0 }}%
|
||||
<div v-if="detailStepHasPercent" class="text-muted">
|
||||
{{ detailStepProgress.progress_percent }}%
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-1 text-sm text-secondary">
|
||||
@@ -444,10 +474,13 @@ onMounted(async () => {
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.stepDetail.counter', { current: detailStepProgress.current, total: detailStepProgress.total }) }}
|
||||
</div>
|
||||
<div class="mt-2 h-2 overflow-hidden rounded-full bg-slate-200">
|
||||
<div
|
||||
v-if="detailStepHasPercent"
|
||||
class="mt-2 h-2 overflow-hidden rounded-full bg-slate-200"
|
||||
>
|
||||
<div
|
||||
class="h-full rounded-full bg-sky-500 transition-all"
|
||||
:style="{ width: `${detailStepProgress.progress_percent ?? 0}%` }"
|
||||
:style="{ width: `${detailStepProgress.progress_percent}%` }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -80,7 +80,22 @@
|
||||
"currentTask": "Current task {taskId}",
|
||||
"batchProgress": "Item {index}/{total}",
|
||||
"batchCurrentIndex": "Currently processing item {index}/{total}",
|
||||
"batchSummaryLine": "Batch {total} items · Completed {completed} · In progress {running} · Pending {pending}",
|
||||
"currentNotice": "Current notice",
|
||||
"currentStepLabel": "Current",
|
||||
"stepHeadline": "Step {current}/{total} · {label}",
|
||||
"stepFraction": "Step {current}/{total}",
|
||||
"stepNeedsConfirm": "Step {step} needs confirmation",
|
||||
"taskListResume": "Task List / Resume",
|
||||
"taskListTitle": "Task List",
|
||||
"taskListHint": "Switching tasks also updates the top Stepper and available actions",
|
||||
"expandTaskList": "Expand list",
|
||||
"collapseTaskList": "Collapse list",
|
||||
"currentFocus": "Current focus →",
|
||||
"runningState": "In progress",
|
||||
"pendingState": "Pending",
|
||||
"completedState": "Completed",
|
||||
"queuedState": "Queued",
|
||||
"prevTask": "Previous",
|
||||
"nextTask": "Next",
|
||||
"collapseTasks": "Hide tasks",
|
||||
|
||||
@@ -80,7 +80,22 @@
|
||||
"currentTask": "งานปัจจุบัน {taskId}",
|
||||
"batchProgress": "รายการ {index}/{total}",
|
||||
"batchCurrentIndex": "กำลังประมวลผลรายการที่ {index}/{total}",
|
||||
"batchSummaryLine": "ชุดนี้ {total} รายการ · เสร็จแล้ว {completed} · กำลังดำเนินการ {running} · รอดำเนินการ {pending}",
|
||||
"currentNotice": "ใบแจ้งปัจจุบัน",
|
||||
"currentStepLabel": "ปัจจุบัน",
|
||||
"stepHeadline": "ขั้นตอน {current}/{total} · {label}",
|
||||
"stepFraction": "ขั้นตอน {current}/{total}",
|
||||
"stepNeedsConfirm": "ขั้นตอน {step} รอยืนยัน",
|
||||
"taskListResume": "รายการงาน / ดำเนินการต่อ",
|
||||
"taskListTitle": "รายการงาน",
|
||||
"taskListHint": "เมื่อสลับงาน Stepper ด้านบนและการดำเนินการจะอัปเดตพร้อมกัน",
|
||||
"expandTaskList": "ขยายรายการ",
|
||||
"collapseTaskList": "ย่อรายการ",
|
||||
"currentFocus": "โฟกัสปัจจุบัน →",
|
||||
"runningState": "กำลังดำเนินการ",
|
||||
"pendingState": "รอยืนยัน",
|
||||
"completedState": "เสร็จแล้ว",
|
||||
"queuedState": "อยู่ในคิว",
|
||||
"prevTask": "ก่อนหน้า",
|
||||
"nextTask": "ถัดไป",
|
||||
"collapseTasks": "ซ่อนงาน",
|
||||
|
||||
@@ -80,7 +80,26 @@
|
||||
"currentTask": "当前任务 {taskId}",
|
||||
"batchProgress": "第 {index}/{total} 票",
|
||||
"batchCurrentIndex": "当前处理第 {index}/{total} 票",
|
||||
"batchSummaryLine": "本批 {total} 笔 · 已完成 {completed} · 进行中 {running} · 待处理 {pending}",
|
||||
"currentNotice": "当前通知",
|
||||
"currentStepLabel": "当前",
|
||||
"stepHeadline": "步骤 {current}/{total} · {label}",
|
||||
"stepFraction": "步骤 {current}/{total}",
|
||||
"stepNeedsConfirm": "步骤 {step} 待确认",
|
||||
"taskListResume": "任务列表 / 续办",
|
||||
"retryPendingTasks": "重试未完成票",
|
||||
"retryPendingDone": "已重新提交未完成票",
|
||||
"retryFailed": "重试失败",
|
||||
"retrying": "重试中...",
|
||||
"taskListTitle": "任务列表",
|
||||
"taskListHint": "切换任务后,对话顶部 Stepper 与操作同步更新",
|
||||
"expandTaskList": "展开列表",
|
||||
"collapseTaskList": "收起列表",
|
||||
"currentFocus": "当前聚焦 →",
|
||||
"runningState": "进行中",
|
||||
"pendingState": "待确认",
|
||||
"completedState": "已完成",
|
||||
"queuedState": "排队中",
|
||||
"prevTask": "上一票",
|
||||
"nextTask": "下一票",
|
||||
"collapseTasks": "收起任务",
|
||||
|
||||
@@ -160,6 +160,10 @@
|
||||
"loadFailed": "加载失败",
|
||||
"openChat": "在 Chat 中继续",
|
||||
"download": "下载 Excel",
|
||||
"retryCurrentTask": "重试当前票",
|
||||
"retryCurrentDone": "已重新提交当前票",
|
||||
"retryFailed": "重试失败",
|
||||
"retrying": "重试中...",
|
||||
"lines": "发货明细",
|
||||
"qty": "数量",
|
||||
"columns": {
|
||||
|
||||
@@ -80,7 +80,22 @@
|
||||
"currentTask": "當前任務 {taskId}",
|
||||
"batchProgress": "第 {index}/{total} 票",
|
||||
"batchCurrentIndex": "當前處理第 {index}/{total} 票",
|
||||
"batchSummaryLine": "本批 {total} 筆 · 已完成 {completed} · 進行中 {running} · 待處理 {pending}",
|
||||
"currentNotice": "當前通知",
|
||||
"currentStepLabel": "目前",
|
||||
"stepHeadline": "步驟 {current}/{total} · {label}",
|
||||
"stepFraction": "步驟 {current}/{total}",
|
||||
"stepNeedsConfirm": "步驟 {step} 待確認",
|
||||
"taskListResume": "任務列表 / 續辦",
|
||||
"taskListTitle": "任務列表",
|
||||
"taskListHint": "切換任務後,對話頂部 Stepper 與操作會同步更新",
|
||||
"expandTaskList": "展開列表",
|
||||
"collapseTaskList": "收起列表",
|
||||
"currentFocus": "目前聚焦 →",
|
||||
"runningState": "進行中",
|
||||
"pendingState": "待確認",
|
||||
"completedState": "已完成",
|
||||
"queuedState": "排隊中",
|
||||
"prevTask": "上一票",
|
||||
"nextTask": "下一票",
|
||||
"collapseTasks": "收起任務",
|
||||
|
||||
Reference in new issue
Block a user