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
@@ -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'])
|
||||
Reference in new issue
Block a user